From 2553db092582d057030a31137b9f05062cca4a32 Mon Sep 17 00:00:00 2001 From: Am0rfu5 <1178902+Am0rfu5@users.noreply.github.com> Date: Sat, 27 Jun 2026 15:31:46 +0000 Subject: [PATCH 01/28] chore(project): AICSDP/p3 s0-s3 --- .../step-00-toolset-augmentation-document.md | 93 ++++ .../p3/step-01-phase-2-input-validation.md | 231 ++++++++++ .../p3/step-02-design-brief-register.md | 321 ++++++++++++++ .../p3/step-03-mc-04-design-specification.md | 418 ++++++++++++++++++ .../p3/step-03-mc-12-design-specification.md | 360 +++++++++++++++ .../p3/step-03-mc-21-design-specification.md | 373 ++++++++++++++++ 6 files changed, 1796 insertions(+) create mode 100644 project/AICSDP/p3/step-00-toolset-augmentation-document.md create mode 100644 project/AICSDP/p3/step-01-phase-2-input-validation.md create mode 100644 project/AICSDP/p3/step-02-design-brief-register.md create mode 100644 project/AICSDP/p3/step-03-mc-04-design-specification.md create mode 100644 project/AICSDP/p3/step-03-mc-12-design-specification.md create mode 100644 project/AICSDP/p3/step-03-mc-21-design-specification.md diff --git a/project/AICSDP/p3/step-00-toolset-augmentation-document.md b/project/AICSDP/p3/step-00-toolset-augmentation-document.md new file mode 100644 index 0000000..8af53a8 --- /dev/null +++ b/project/AICSDP/p3/step-00-toolset-augmentation-document.md @@ -0,0 +1,93 @@ +# Toolset Augmentation Document — Phase 3 (Design & Technical Analysis) + +**Project:** `@diamondslab/diamonds` v1.3.2 +**Phase 3 Run Date:** 2026-05-26 +**Practitioner:** Solo maintainer (DiamondsLab) +**AI Model:** Claude Opus 4.7 +**Code-Access Mode:** Hybrid with explicit flags +**Status:** Living document — amendments captured in §7 + +> ⚠️ This document is **living**. When AI capabilities shift during +> the Phase 3 run (a connector activates, a Skill becomes available, +> a tool errors out), add a dated entry to §7 — do not produce a new +> document. + +--- + +## §1 — Direct Code Access + +| Capability | Available? | Repository / Path | Notes | +| -------------------------------- | ---------- | ---------------------------------------------------------------------------------------------------------------------------------------------------- | ----------------------------------------------------------------------- | +| Filesystem read (via GitHub MCP) | Yes | `DiamondsLab/diamonds` main branch (v1.3.2) | `get_file_contents` works for any path in the repo | +| Filesystem read (via GitHub MCP) | Yes | `DF3NDR/ai-centric-software-development` main branch | Phase 3 toolkit files, skill files, articles | +| Filesystem write | No | — | Outputs land at `/mnt/user-data/outputs/`; practitioner commits to repo | +| Git operations | Read-only | — | Tag/branch references via MCP; no write | +| Cross-repo access | Yes | Both `DiamondsLab/diamonds` and `DF3NDR/ai-centric-software-development`; presumably also `DiamondsLab/diamonds-dev-env` if needed for MC-22 context | Via GitHub MCP | + +## §2 — Library and Specification Documentation Lookup + +| Capability | Available? | Anticipated Use in Phase 3 | +| ----------------------------------- | ----------------- | ------------------------------------------------------------------------------------------------------------------ | +| Context7 | Yes | MC-04 (TypeScript / JSDoc), MC-21 (ethers.js v6 Signer), MC-12 (CycloneDX 1.5, npm provenance, SLSA provenance) | +| Project knowledge with library docs | N/A | This project's knowledge base contains the Playbook articles, not external library docs — Context7 covers that gap | +| Web fetch | Yes (constrained) | For specs not in Context7 (e.g., specific RFC or W3C documents) | + +## §3 — Cross-Repo Search and Code Cross-Reference + +| Capability | Available? | Use Case | +| ----------------------------- | ---------------- | ---------------------------------------------------------------------------------------------- | +| GitHub code search | Yes | Cross-reference verification for MC-22 integration-peer assumptions; consumer search for MC-21 | +| Enterprise / codebase search | N/A | No enterprise search configured | +| Cross-repo reference tracking | Yes (via search) | Manual via `Github:search_code`; not a dedicated cross-reference tool | + +## §4 — Diagram and Visualization Rendering + +| Capability | Available? | Notes | +| ------------------------------ | -------------------- | ------------------------------------------------------------------------------------------------------- | +| Mermaid in rendered output | Yes | Selective use for layer diagrams, lifecycle diagrams, schema composition diagrams | +| External diagramming source | Yes (via Visualizer) | For more complex visual artifacts | +| Visualization MCP / Visualizer | Yes | Available but used judiciously — design specifications are primarily prose+tables, not visual artifacts | + +## §5 — Skills, Custom AIs, Specialized Agents + +| Capability | Active? | Description | +| -------------------------- | ----------------------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | +| AI-Centric Playbook Skill | Yes (SKILL.md consulted at session start) | `DF3NDR/ai-centric-software-development:skills/ai-centric-playbook/`; three reference files (`core-principles.md`, `sdd-cycle.md`, `building-blocks-and-toolsets.md`) on-demand; not preemptively loaded | +| Project-level instructions | Yes | Claude Project Instructions for this conversation; provides AI-Centric Software Development consultant role framing | +| Specialized agents | No | None configured for this session | +| Other Skills loaded | None | — | + +## §6 — Phase 2 Artifact Access + +| Artifact | Loaded? | Access Path | +| -------------------------------------------- | --------------------------------------- | ------------------------------------------------------------------------------ | +| Phase 2 Improvement Plan (Step 06 synthesis) | Yes — loaded into context | `DiamondsLab/diamonds:project/AICSDP/P2/step-06-improvement-plan-synthesis.md` | +| Phase 2 Step 03 (Mechanism Decisions) | Yes — fetched during Step 01 Category 5 | `DiamondsLab/diamonds:project/AICSDP/P2/step-03-mechanism-decisions.md` | +| Phase 2 Step 01-02, 04-05 artifacts | On-demand | `DiamondsLab/diamonds:project/AICSDP/P2/*` via GitHub MCP | +| Phase 1 Information Report | On-demand | Presumably `DiamondsLab/diamonds:project/AICSDP/P1/` via GitHub MCP | + +## §7 — Mid-Phase Amendments + +_Append-only. When a capability shifts during the Phase 3 run, add a dated entry below. Do not edit prior entries._ + +| Date | Step | Capability | Change | Impact | +| ------------------------------------------------------ | ---- | ---------- | ------ | ------ | +| _(none yet — populated as the Phase 3 run progresses)_ | | | | | + +## §8 — Known Friction Points + +| Capability | Friction | Workaround | +| ---------- | ------------------------------------------------------------- | ---------------------------------------------------------------------- | +| GitHub MCP | Theoretical rate limiting on heavy fetch cycles | Cache fetched artifacts in working context; batch reads where possible | +| Context7 | Occasionally returns stale or incomplete library snapshots | Cross-check against authoritative source when stakes warrant | +| Visualizer | Best for inline single-concept visuals, not full system views | Use selectively where prose+tables can't convey the design | + +## §9 — Code-Access Mode Rationale + +This session operates in **Hybrid with explicit flags** mode. GitHub MCP provides read access to both `DiamondsLab/diamonds` (subject) and `DF3NDR/ai-centric-software-development` (toolkit + Playbook reference). Code-derived claims about Diamonds source use `[CONFIRM]` when I've fetched and read the relevant file; `[AWARE]` when relying on the Improvement Plan's restatement without re-fetching; `[QUESTION]` when something needs practitioner clarification. The mode is unlikely to shift during the run unless GitHub MCP errors out or Context7 becomes unavailable; if that happens, §7 captures the amendment. + +--- + +## Version + +v1.0 (initial Phase 3 capability inventory; living thereafter) diff --git a/project/AICSDP/p3/step-01-phase-2-input-validation.md b/project/AICSDP/p3/step-01-phase-2-input-validation.md new file mode 100644 index 0000000..766aa1b --- /dev/null +++ b/project/AICSDP/p3/step-01-phase-2-input-validation.md @@ -0,0 +1,231 @@ +# Phase 2 Input Validation Report — Phase 3 (Design & Technical Analysis) + +**Project:** `@diamondslab/diamonds` v1.3.2 +**Validation Date:** 2026-05-26 +**Phase 2 Completion Date:** 2026-05-22 +**Practitioner:** Solo maintainer (DiamondsLab) +**AI Model:** Claude Opus 4.7 +**Phase 2 Improvement Plan Version:** v1.0 (2026-05-22, no amendments since) +**Status:** Validated — Pending Practitioner Final Review + +> ⚠️ This report validates that Phase 3 understands the Phase 2 +> inputs correctly. It is **not** a re-litigation of Phase 2 +> decisions. Phase 2 mechanism choices are authoritative for this +> cycle. Gaps surface either as Phase 3 local (resolve within Phase 3) or as upstream Phase 2 toolkit (queue for separate Phase 2 +> toolkit revision). + +--- + +## §1 — Subject Identity & Plan Currency + +| Field | Value | Confidence | +| -------------------------------------- | ----------------------- | --------------------------------------------------------------------------------------------------- | +| Subject name | `@diamondslab/diamonds` | High [CONFIRM — Improvement Plan §1.1] | +| Subject current version | v1.3.2 | High [CONFIRM — Plan metadata; practitioner confirmed no new release 2026-05-22 through 2026-05-26] | +| Improvement Plan date | 2026-05-22 | High [CONFIRM — Plan metadata] | +| Plan amendments since completion? | No | High [CONFIRM — practitioner confirmation] | +| Subject release since Plan completion? | No | High [CONFIRM — practitioner confirmation] | + +## §2 — Sharpened Objective & Defining Mechanism + +**Sharpened objective (inherited from Phase 1):** Transform Diamonds from a working library that cannot prove it works to external developers or auditors into a productized library where external developers can adopt and external auditors can verify, without practitioner support. + +**Defining mechanism (Plan §1.2):** _Narrow the claims-vs-proof gap through a sequenced productization arc._ + +Operationalized as three sequential steps: + +1. **Tier 1 (Foundation)** clears cognitive surface — codebase becomes honestly what it claims to be +2. **Tier 2 (Coordinated Breaking-Change Block)** ships v2.0 with verifiable release evidence +3. **Tier 3 (Productization)** completes the adoption-readiness claim + +**Phase 3 application:** Every Step 03 design specification will be evaluated against the defining mechanism — does this specification narrow the claims-vs-proof gap for its mechanism? Specifications that are vague enough to weaken the gap-narrowing fail the criterion. + +**Confidence:** High [CONFIRM — Plan §1.2; practitioner confirmation] + +## §3 — Principle Weights (Inherited Unchanged from Phase 2 Step 02) + +| Principle | Weight | Source | Confidence | +| ------------------------ | -----: | ------------------------------------------------------------------------------------------------ | ---------- | +| Security | 1.5× | Phase 2 Step 02 §1 — auditor persona + 7 of 22 MCs security-bearing | High | +| Maintainability | 1.5× | Phase 2 Step 02 §1 — solo maintainer + HC-08 + 16 of 22 MCs touch Maintainability | High | +| Economics | 1.0× | Phase 2 Step 02 §1 — no commercial pressure | High | +| Operations | 1.0× | Phase 2 Step 02 §1 — pre-production state; **explicit deprioritization; future-cycle elevation** | High | +| Scoring & Metrics | 1.0× | Phase 2 Step 02 §1 — standard baseline | High | +| Correctness Verification | 1.5× | Phase 2 Step 02 §1 — auditor persona consumes verifiable correctness | High | + +**Explicit deprioritizations to preserve:** + +- **Operations 1.0× deprioritized** with elevation deferred to next cycle. Phase 3 produces observability design at _baseline weight_; does _not_ silently elevate to 1.5×. + +## §4 — Design Brief Inventory + +**Primary briefs (from Plan §6) — 4 briefs:** + +| Brief ID | Source MC(s) | Chosen Mechanism (summarized) | Design Questions Named | Constraints Inherited | Verification Method | Confidence | +| ----------- | ---------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------- | -------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------ | +| MC-04 brief | MC-04 | Formal TypeScript `IDeploymentStrategy` interface + lifecycle methods + JSDoc security-boundary annotations + conformance test suite + worked sibling-strategy example | 5: lifecycle methods specifics; JSDoc security-boundary semantics; conformance test scope; worked sibling example; NTI-03 interaction | MK-08 ERC-2535 conformance; HC-05 v2.0 breaking changes per-item justified; F-41 auditor reproducibility | Contract conformance test passes against worked example; reference external strategy produces auditor-reproducible deployment records | High | +| MC-21 brief | MC-21 | Clean break — v2.0 `RPCDeploymentStrategy` constructor takes `signer: Signer` instead of `privateKey`; no shim | 4: exact Signer interface signature; Signer source examples for migration doc; internal-architecture implications; MC-04 contract interaction | SR-03 private-key-in-constructor; MK-01 deployment record format unchanged | v2.0 constructor type signature; Signer-injection tested against three Signer sources; deployment records byte-identical to v1.3.2 | High (Plan §6.2 brief content) — but rejected-alternatives detail missing from Phase 2 Step 03 §2; see §11.2 | +| MC-07 brief | MC-07 (Layer 1+2+3+examples) | Three-layer structure (Quickstart / Core Concepts / Reference) + colocated working examples | 4: Layer 2 concept-doc list; cross-link structure between Layers; doc-authoring style guide; per-doc scope for Layer 3 reference docs | F-25, F-40 docs-vs-code gap; F-41 auditor reproducibility | AI proxy-reader test against deployed site, 5 questions at ≥80% success rate | High | +| MC-12 brief | MC-12 | npm `--provenance` + cyclonedx-npm SBOM + lockfile snapshot + release-evidence artifact | 4: release-evidence artifact layout; SBOM contents; lockfile-snapshot format; auditor use-flow | HC-06 no external certification; F-41 auditor reproducibility | Auditor-persona check: fresh AI session given npm URL + GitHub release URL verifies published code matches released source | High | + +**Supplementary briefs (from Plan §10.1) — 2 briefs:** + +| Brief ID | Type | Phase 2 Description | Phase 3 Activity | Scorecard Conditional Addressed | Confidence | +| ------------------------------- | ------------- | -------------------------------------------------------------------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ------------------------------------ | ---------------------------------------------------------------------------------------------------------------- | +| Observability touchpoints brief | Observability | "v2.0 chosen mechanisms get observability hooks for future-cycle Operations elevation" | Produce observability touchpoint design for v2.0 chosen mechanisms (MC-04 contract, MC-21 Signer, MC-11 CI pipeline, MC-12 publish flow) | Operations CONDITIONAL | Medium — supplementary brief has no design-question enumeration in Plan §10.1; Step 02/03 will produce questions | +| Verification artifacts brief | Verification | "Proxy-reader question set, auditor-persona prompt, MC-04 conformance test scope" | Produce concrete verification instruments (proxy-reader question text, auditor-persona prompts, conformance test enumerations) for the four primary briefs and other verification-method-bearing MCs | Correctness Verification CONDITIONAL | Medium — same reason | + +**Total:** 6 briefs (4 primary + 2 supplementary). No MCs in Plan §2 with chosen mechanisms that should have produced a brief but didn't. + +## §5 — Mechanism Choices + +For each design brief, chosen mechanism and rejected alternatives (Phase 3 must not silently re-litigate). + +| Brief | Chosen Mechanism | Rejected Alternatives (Phase 2 Step 03 §2) | Phase 5 Estimate-Refinement Notes | Confidence | +| ------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | -------------------------------------------------------------------------------------------------------------------------- | ------------------ | +| MC-04 brief | Formal TypeScript IDeploymentStrategy interface + lifecycle methods + JSDoc security-boundary + conformance test suite + worked sibling-strategy example | (1) Documented convention without enforced interface (markdown only); (2) Plugin-loader pattern; (3) Abstract base class only | **Refinement expected** — Plan §6.1 explicit: "Estimate uncertainty is wider than other MCs (24 ± 12 dev-hours plausible)" | High | +| MC-21 brief | Clean break: v2.0 constructor takes `signer: Signer` instead of `privateKey`; no shim | **Missing from Phase 2 Step 03 §2** — inferring from Plan §6.2 + Step 03 §3.1 dependency table: deprecation cycle with shim was the implied alternative, rejected because zero external adopters make clean break cheaper. **See §11.2 P3-Obs-04.** | Refinement possible (refactor-class brief; edge cases may emerge) | Medium | +| MC-07 brief | Layered docs (Quickstart / Core Concepts / Reference) + colocated working examples | (1) Single canonical narrative + worked examples; (2) Tutorial-driven (multiple persona tutorials); (3) API reference only | Refinement possible at per-doc level (Plan §5.3 per-doc cut staging) | High | +| MC-12 brief | npm `--provenance` + cyclonedx-npm SBOM + lockfile snapshot + release-evidence artifact | (1) npm `--provenance` only; (2) npm provenance + SLSA Level 2; (3) npm provenance + Sigstore signed releases; (4) Release evidence in repo only (no SBOM) | Refinement not expected (schema-class brief; narrower uncertainty) | High | +| Observability brief | Not specified at Phase 2 (supplementary brief) | Step 03 produces; first design | Step 03 produces first estimate | n/a (first design) | +| Verification brief | Not specified at Phase 2 (supplementary brief) | Step 03 produces; first design | Step 03 produces first estimate | n/a (first design) | + +## §6 — Cost Model Continuation + +| Item | Confirmed? | Notes | +| ----------------------------------------------------------------- | ---------- | ------------------------------------------------------------------------------------------- | +| Three-quantity model (dev-hrs + multiplier + maint-hrs) | Yes | Inherited from Phase 2 v1.1 | +| Multiplier defaults (mechanical 10×, doc 8×, config 5×, novel 3×) | Yes | Inherited; remain BELIEVED at v1.0 | +| BELIEVED tag for multipliers at v1.0 | Yes | No Phase 5 calibration data yet (Phase 5 has not started) | +| Token-count and token-cost as derived dimensions | Yes | Inherited (6,000 tokens/dev-hr default; ~$2.50/100K Opus 4.7 ESTIMATED) | +| Phase 3 design work may refine estimates | Yes | MC-04 refinement expected; MC-21 / MC-07 refinement possible; MC-12 refinement not expected | + +## §7 — Capacity Envelope + +| Field | Phase 2 Value | Phase 3 Start Value | Change? | +| ------------------------------------------ | -------------------------------------------------------------------- | ------------------- | ------- | +| Maintainer-time / capacity (HC-08) | <5 hr/week ecosystem; ~2 hr/week Diamonds-minority-share | Unchanged | No | +| Commercial-services budget (HC-03 layer 1) | $0 | $0 | No | +| AI-usage budget (HC-03 layer 2) | ~$32 ESTIMATED for full plan; budget bounded but not strictly capped | Unchanged | No | +| Timeline (HC-02) | Open-ended; 5-10 months full plan; ~7 weeks floor (v2.0) | Unchanged | No | + +**No envelope changes between Phase 2 completion (2026-05-22) and Phase 3 start (2026-05-26).** + +## §8 — Phase 2 Scorecard Conditionals + +| Principle | Phase 2 Status | What Made It Conditional | Phase 3 Remediation Activity | In Scope This Run? | +| ---------------------------- | --------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------ | ---------------------------------------------------- | +| Security | PASS | — | — | n/a | +| Maintainability | PASS | — | — | n/a | +| Economics | PASS | — | — | n/a | +| **Operations** | **CONDITIONAL** | Operations explicitly deprioritized (weight 1.0×); elevation deferred to next cycle | Phase 3 produces observability touchpoint design for v2.0 chosen mechanisms; next-cycle Phase 2 re-weights | **Yes — Observability supplementary brief** | +| Scoring & Metrics | PASS | — | — | n/a | +| **Correctness Verification** | **CONDITIONAL** | Some verification methods are AI-proxy-reader-tests and auditor-persona-checks (novel verification mechanisms); Phase 3 must produce specific verification artifacts before Phase 5 implements | Phase 3 produces verification-artifact specifications alongside design briefs for MC-04, MC-21, MC-07, MC-12 | **Yes — Verification artifacts supplementary brief** | + +**Phase 3 obligations:** + +- **Operations CONDITIONAL → PASS** requires _design production_ (not Operations elevation). Phase 3 produces observability design at baseline weight; future cycle elevates. +- **Correctness Verification CONDITIONAL → PASS** requires _concrete instruments_ (not descriptions). Phase 3 produces instruments via the Verification brief; Step 05 refines to Phase 6-executable form. + +## §9 — Worst-Case Plan-Failure Common Mechanism + +**Common mechanism (Plan §8.2):** _"Load-bearing concentration. Multiple Phase 2 outcomes depend on a small number of high-leverage MCs reaching completion in the right order. The plan has too few 'natural pause points' — places where partial completion produces a coherent intermediate state. When complexity, capacity, or attention discontinuity hits, the plan tends to stall mid-block rather than mid-tier."_ + +**Three failure branches:** + +1. **Branch 1** — Coordinated Block stalls on unforeseen MC-04 complexity +2. **Branch 2** — Doc-heavy Tier 3 exceeds capacity; Layer 3 quietly disappears +3. **Branch 3** — Burst-then-dormant cadence reasserts + +**Plan mitigations (Plan §8.3) Phase 3 must preserve:** + +| Mitigation | Phase 3 Preservation Obligation | +| ---------------------------------------------------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | +| Floor design (partial Branch 3 mitigation) | n/a (Phase 5+ concern) | +| **MC-04 Phase 3 design brief discipline mitigates Branch 1** | **MC-04 brief Step 03 design specification must enumerate edge cases concretely** (partial deployment; deployment-record migration across diamond cuts; multi-call atomicity). Under-specifying edge cases at design time = letting Phase 5 hit them at implementation time = Branch 1. | +| **MC-07 Layer 3 per-doc cut staging mitigates Branch 2** | **MC-07 brief Step 03 cross-link structure must support per-doc cuts.** Over-coupling docs (cross-references that cascade) = weakened cut staging = Branch 2. | +| Phase 7 feature-branch-staleness watch-trigger (partial Branch 3 mitigation) | n/a (Phase 7 concern) | + +## §10 — Forward Handoffs (from Plan §10.4) + +| Recipient Phase | Phase 2 Expected Phase 3 to Produce | Brief(s) That Produce It | In Scope? | +| -------------------------------- | --------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------- | ---------------------------------------------------- | +| Phase 3 | 6 design briefs + Phase 5 task-list seeds as anchoring inputs | All six Step 03 briefs | **Yes — primary Phase 3 scope** | +| Phase 4 (Architecture) | Coordinated Block module-boundary design uses Phase 3 contract specifications | MC-04 brief (contract surface), MC-21 brief (refactor surface), Verification brief (test harness location) | Yes — Phase 3 produces; Phase 4 consumes | +| Phase 5 (Implementation) | Task-list seeds with per-MC acceptance criteria; per-Layer-3 staging cut order; MC-04 estimate refinement | All six briefs contribute Phase 5 implementability notes | Yes — Phase 3 produces estimates + anchors | +| Phase 6 (Testing & Audit) | Per-MC verification methods + concrete instruments (conformance tests, AI proxy-reader, auditor-persona checks) | Verification brief produces concrete instruments; each primary brief contributes Phase 6 verification notes | Yes — Phase 3 produces instruments; Phase 6 executes | +| Phase 7 (Deployment & Evolution) | Observability for ongoing measurement; cost projection; v2.0 launch; six watch-triggers | Observability brief produces touchpoint design feeding Phase 7 | Yes — Phase 3 produces observability surface | +| Next-Cycle Phase 2 | Operations re-weighting; AI-acceleration multiplier calibration data; updated Phase 1 toolkit | Observability brief surfaces Operations elevation inputs; Step 06 §10.4 Phase 7 Calibration Handoff carries forward | Yes — Phase 3 produces surfaces | + +**No Plan §10.4 deliverable lacks a Phase 3 brief that produces it.** + +## §11 — Validation Gap Register (Split by Scope) + +### §11.1 — Phase 3 Local Gaps + +Gaps that Phase 3 must resolve within its own seven steps, or acknowledge as documented limitation. + +| Gap ID | Description | Affected Brief / Category | Resolution Path | Priority | +| -------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | ------------------------- | --------------- | -------- | +| _(none)_ | The validation walkthrough produced no Phase 3 local gaps. All Plan §6 / §10.1 briefs have sufficient inputs for Step 03 design work to proceed. Open design questions per brief are normal Step 03 work, not validation gaps. | — | — | — | + +### §11.2 — Upstream Phase 2 Toolkit Gaps + +Gaps that exist because the Phase 2 toolkit itself was structurally incomplete. Queue for Phase 2 toolkit revision in a separate session. Phase 3 proceeds with workaround or in-line amendment. + +| Gap ID | Description | What the Phase 2 Toolkit Was Missing | Phase 3 Workaround | Phase 2 Toolkit Revision Recommendation | +| -------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | +| **VG-P3-U-01** (P3-Obs-04) | Phase 2 Step 03 §2 detail is missing for MC-21. §1.1 lists MC-21 as a multi-mechanism MC requiring Phase 2 decision, but §2 only contains entries for MC-01, MC-04, MC-07, MC-08, MC-11, MC-12, MC-19. The MC-21 mechanism (clean-break vs deprecation-cycle-with-shim) was decided but the principle-weighted rationale and rejected-alternatives detail are not documented. | The Phase 2 Step 03 prompt's Evaluation Checklist should include a check that every multi-mechanism MC listed in §1.1 has a corresponding §2 detail entry. Synthesis at Step 06 should also verify §2 coverage matches §1.1. | Plan §6.2 brief content (chosen mechanism, design questions, constraints, verification method) is sufficient for Step 03 design work on MC-21. Rejected alternatives inferred from Plan §6.2 context plus Step 03 §3.1 dependency table. | Add `[Mandatory] Every multi-mechanism MC in §1.1 must have a §2 detail entry with chosen mechanism, principle-weighted rationale, rejected alternatives, verification method, and inter-MC dependencies` to Step 03 prompt's Evaluation Checklist. Step 06 prompt's evaluation should re-check this. | +| **VG-P3-U-02** (P3-Obs-05) | NTI mentions in primary briefs don't have explicit cycle-vs-future-cycle clarification. Plan §6.1 mentions NTI-03 (`diamonds-safe`) and says "the contract should be designed knowing diamonds-safe is the most concrete near-term consumer, but not exclusively for diamonds-safe." Phase 2 Step 03 MC-04 entry uses "becomes addressable once contract exists." Neither explicitly states "NTI-03 is _not_ being addressed this cycle." A practitioner returning to the Plan after a few days can reasonably ask "is SafeDeploymentStrategy being built this cycle?" — a question the artifact doesn't answer directly. | The Phase 2 Step 03 prompt should ask, for any NTI mentioned in a brief's constraint chain: "Is this NTI being addressed this cycle, or future-cycle? If future-cycle, what specific Phase 3 deliverable enables the future-cycle work?" The cycle-vs-future distinction would then be explicit in the §2 entry. | Phase 3 confirmed during Step 01 validation (via Category 11 practitioner clarification) that NTI-03 / `diamonds-safe` is _not_ being built this cycle. Phase 3 produces the contract, the worked sibling example, and the how-to-write-a-new-strategy doc that enable future-cycle `diamonds-safe` work. The Step 03 MC-04 brief specification will reflect this scope explicitly. | Add `[Mandatory] For each NTI mentioned in a brief's chosen-mechanism dependency or constraint chain, state whether the NTI is being addressed this cycle or future-cycle, and what this-cycle deliverable enables the future-cycle work if future-cycle` to Step 03 prompt's per-MC mechanism decision template. | + +> **Each upstream gap requires the structural diagnosis (what the +> Phase 2 toolkit didn't have a slot for) and a concrete revision +> recommendation. Vague upstream gaps don't actionably produce +> Phase 2 toolkit improvements. Both gaps above meet this discipline.** + +## §12 — Validation Confidence Summary + +| Validation Category | Confidence | Notes | +| ---------------------------------------- | ------------------------------------------------------------------------------------------------ | ------------------------------------------------------------------ | +| Subject identity & plan currency | High | Practitioner confirmation; no drift since Phase 2 completion | +| Sharpened objective & defining mechanism | High | Plan §1.2 explicit | +| Principle weights | High | Plan §4.2 explicit; deprioritization framing confirmed | +| Design brief inventory | High | All 6 briefs accounted for | +| Mechanism choices | High overall; **Medium for MC-21** specifically (Phase 2 Step 03 §2 detail missing — VG-P3-U-01) | Phase 3 proceeds with Plan §6.2 brief content; gap routed upstream | +| Cost model continuation | High | Three-quantity model inherited unchanged | +| Capacity envelope | High | No changes between Phase 2 completion and Phase 3 start | +| Phase 2 scorecard conditionals | High | Both CONDITIONALs have clear Phase 3 remediation paths | +| Worst-case common mechanism | High | Plan §8 explicit; Phase 3 preservation obligations clear | +| Forward handoffs | High | Every Plan §10.4 deliverable mapped to a Phase 3 brief | +| Validation gap pre-check | High | Practitioner confirmed nothing else to surface | + +**Overall validation status:** **Anchored** — Phase 3 has the inputs it needs to proceed with Step 02 (Design Brief Triage) and the subsequent design work. Two upstream Phase 2 toolkit gaps surfaced for separate toolkit revision; neither blocks this Phase 3 cycle. + +**Next step:** Step 02 Design Brief Triage will inventory the six briefs in detail, classify each by artifact type, capture inter-brief dependencies, and produce the sequenced Design Brief Register that anchors Step 03 iterations. + +--- + +## Confidence and Code-Access Notes + +| Field | Value | +| --------------------------------- | ------------------------------------------------------------------------------------------ | +| Code-access mode (from Step 00) | Hybrid with explicit flags | +| Code-derived claims flagged with | [CONFIRM] / [AWARE] / [QUESTION] as applicable | +| Overall validation confidence | High | +| Specific lower-confidence section | §5 MC-21 rejected alternatives — Medium (Phase 2 Step 03 §2 missing; routed as VG-P3-U-01) | + +--- + +## Version History + +| Version | Date | Source | Summary | +| ------- | ---------- | ------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | +| v1.0 | 2026-05-26 | Initial Step 01 production for Diamonds Phase 3 dogfood | 11-category validation walkthrough complete. Two upstream Phase 2 toolkit gaps surfaced (VG-P3-U-01 MC-21 missing §2 detail; VG-P3-U-02 NTI cycle-vs-future-cycle ambiguity). Zero Phase 3 local gaps. Overall status Anchored. | + +--- + +_Part of the Phase 3 (Existing Projects) Design & Technical Analysis Tool Set — v1.0_ +_AI-Centric Software Development Playbook_ +_Companion file: `design-technical-analysis.existing-project.instructions.md`_ +_Previous step: `step-00-building-block-discovery.prompt.md` (Toolset Augmentation Document produced)_ +_Next step: `step-02-design-brief-triage.prompt.md`_ diff --git a/project/AICSDP/p3/step-02-design-brief-register.md b/project/AICSDP/p3/step-02-design-brief-register.md new file mode 100644 index 0000000..9b612ad --- /dev/null +++ b/project/AICSDP/p3/step-02-design-brief-register.md @@ -0,0 +1,321 @@ +# Design Brief Register — Phase 3 (Design & Technical Analysis) + +**Project:** `@diamondslab/diamonds` v1.3.2 +**Triage Date:** 2026-05-26 +**Practitioner:** Solo maintainer (DiamondsLab) +**AI Model:** Claude Opus 4.7 +**Improvement Plan Version:** v1.0 (2026-05-22, no amendments) +**Step 01 Validation Confidence:** Anchored (Overall High; one Medium on MC-21 rejected alternatives — VG-P3-U-01 routed upstream) +**Status:** Draft — Pending Practitioner Review + +> ⚠️ This register sequences and classifies the design briefs Phase 3 +> must produce. Step 03 (Per-Artifact Design Specification) runs once +> per brief, using the artifact-type sub-template indicated. + +--- + +## §1 — Brief Inventory (Combined Primary + Supplementary) + +| Brief ID | Source MC(s) | Origin | Primary Artifact Type | Secondary Type (if any) | Step 01 Confidence | +| ----------------------- | --------------------------------------------------------------------------------------------------------------------------- | -------------------------- | --------------------------------- | ----------------------- | ----------------------------------------------------------------- | +| **MC-04 brief** | MC-04 (Strategy extensibility for external multi-party modules) | Plan §6.1 (primary) | **Contract** | — | High | +| **MC-21 brief** | MC-21 (Private key refactored out of RPCDeploymentStrategy constructor) | Plan §6.2 (primary) | **Refactor** | — | High overall; Medium on rejected alternatives detail (VG-P3-U-01) | +| **MC-07 brief** | MC-07 (Core-concept narrative documentation + working example scripts — Layer 1 + Layer 2 + Layer 3 + examples/) | Plan §6.3 (primary) | **IA (Information Architecture)** | — | High | +| **MC-12 brief** | MC-12 (Publish pipeline + provenance + release-evidence) | Plan §6.4 (primary) | **Schema** | — | High | +| **Observability brief** | Cross-cutting (touches MC-04, MC-21, MC-11, MC-12 chosen mechanisms) | Plan §10.1 (supplementary) | **Observability Touchpoints** | — | Medium (no Phase 2 design-question enumeration; Step 03 produces) | +| **Verification brief** | Cross-cutting (verifies MC-04, MC-21, MC-07, MC-12 chosen mechanisms; refines per-MC verification methods named in Plan §6) | Plan §10.1 (supplementary) | **Verification Artifacts** | — | Medium (no Phase 2 design-question enumeration; Step 03 produces) | + +**Total briefs: 6** — 4 primary + 2 supplementary. Six distinct artifact types from the Step 03 unified prompt's seven sub-templates (Contract / Refactor / IA / Schema / Observability / Verification). No "Other (declared shape)" types in this cycle. + +## §2 — Per-Brief Details + +### §2.1 — MC-04 brief + +| Field | Value | +| --------------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | +| Source MC(s) | MC-04 | +| Origin | Plan §6.1 (primary) | +| Primary artifact type | **Contract** | +| Secondary type | None | +| Phase 2 chosen mechanism (summary) | Formal TypeScript `IDeploymentStrategy` interface + lifecycle methods + JSDoc security-boundary annotations + contract conformance test suite + worked sibling-strategy example | +| Plan §6.1 design questions | (1) Specific lifecycle methods in `IDeploymentStrategy` — pre-deploy, deploy, post-deploy, record-write, error-recovery? (2) JSDoc security-boundary semantics — how does an external strategy provably _not_ bypass the deployment-record-writing path? (3) Conformance test suite scope — partial-deployment handling, deployment-record migration across diamond cuts, multi-call atomicity. (4) Worked sibling example shape — minimal but functional external strategy. (5) NTI-03 interaction — contract designed knowing diamonds-safe is intended near-term consumer, **not exclusively for diamonds-safe; diamonds-safe NOT built this cycle** (confirmed Step 01 Category 11) | +| Constraints inherited from Phase 1 | MK-08 (ERC-2535 conformance) — contract cannot weaken ERC-2535 guarantees; HC-05 (v2.0 breaking changes per-item justified); F-41 (auditor reproducibility) — extension contract must preserve this property | +| Verification method (from Plan §6.1) | Contract conformance test passes against worked example; reference external strategy produces auditor-reproducible deployment records; TypeScript interface JSDoc covers security boundaries; Phase 3 produces formal design brief covering specific interface methods and semantics before Phase 5 implements | +| Dependencies (briefs this depends on) | None (MC-04 is the contract anchor — other briefs depend on it) | +| Dependents (briefs that depend on this) | MC-21 brief (refactor's post-state reflects contract); MC-07 brief (Layer 3 writing-a-new-strategy doc references contract + worked example); Observability brief (touchpoints insert at contract lifecycle methods); Verification brief (conformance test instruments verify contract) | +| Principle-weight sensitivity | **High on Security 1.5×** (JSDoc security boundaries; trust model between core and extension); **High on Correctness Verification 1.5×** (contract conformance test is the verification surface); **High on Maintainability 1.5×** (the contract is the long-lived extension surface) | +| Phase 5 estimate-refinement expected | **Yes (explicit)** — Plan §6.1: _"Estimate uncertainty is wider than other MCs (24 ± 12 dev-hours plausible per Step 04 Branch 1). Phase 3 design brief completeness should surface estimate refinement before Phase 5 starts."_ | +| Step 01 §11.1 gap carryover | None | +| Step 03 iteration priority | **H** — anchor brief; widest weight-sensitivity; explicit refinement requirement; first in strict order; Branch 1 mitigation (edge-case enumeration) lives here | + +### §2.2 — MC-21 brief + +| Field | Value | +| --------------------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | +| Source MC(s) | MC-21 | +| Origin | Plan §6.2 (primary) | +| Primary artifact type | **Refactor** | +| Secondary type | None | +| Phase 2 chosen mechanism (summary) | Clean break — v2.0 `RPCDeploymentStrategy` constructor takes `signer: Signer` instead of `privateKey`; no shim | +| Plan §6.2 design questions | (1) Exact `Signer` interface signature — ethers' `Signer` abstract class as-is, or a Diamonds-specific wrapper? (2) Signer source examples for migration doc — ethers `Wallet` (private-key-backed), mock Signer (for tests), one external Signer source (KMS-backed or hardware-wallet-backed). (3) Internal-architecture implications — any other code path in Diamonds making assumptions about private-key access that Signer abstraction will break? (4) Interaction with MC-04's extension contract — the contract must reflect the post-MC-21 interface | +| Constraints inherited from Phase 1 | SR-03 (private-key-in-constructor risk) — refactor must close this finding; MK-01 (deployment record format unchanged) — refactor must preserve byte-identical deployment records for same logical input | +| Verification method (from Plan §6.2) | v2.0 constructor type signature accepts no `privateKey`; Signer-injection works with Wallet, mock Signer, and one external Signer source; deployment records byte-identical to v1.3.2 for same input | +| Dependencies (briefs this depends on) | **MC-04 brief** (refactor's post-state must be reflected in the contract — the contract is the post-MC-21 interface, not the pre-MC-21 one) | +| Dependents (briefs that depend on this) | MC-07 brief (Layer 3 secure-key-handling doc references Signer-injection patterns); Observability brief (touchpoints insert at refactored constructor / Signer-use points); Verification brief (refactor verification instruments) | +| Principle-weight sensitivity | **High on Security 1.5×** (closes SR-03 private-key risk; trust model around Signer source matters); **High on Maintainability 1.5×** (migration path quality affects future-cycle work); Medium on Correctness Verification 1.5× (byte-identical deployment-record invariant is testable) | +| Phase 5 estimate-refinement expected | Possible — refactor-class brief; edge cases may emerge (e.g., a Signer source the design didn't anticipate, an internal code path that has an implicit private-key assumption) | +| Step 01 §11.1 gap carryover | None — but note **VG-P3-U-01** (Phase 2 Step 03 §2 detail missing for this brief) routed upstream; Phase 3 proceeds with Plan §6.2 content as authoritative | +| Step 03 iteration priority | **H** — second in strict order (depends on MC-04); high principle-weight sensitivity | + +### §2.3 — MC-07 brief + +| Field | Value | +| --------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | +| Source MC(s) | MC-07 (Layer 1 Quickstart + Layer 2 Core Concepts + Layer 3 Reference + examples/) | +| Origin | Plan §6.3 (primary) | +| Primary artifact type | **IA (Information Architecture)** | +| Secondary type | None | +| Phase 2 chosen mechanism (summary) | Three-layer structure (Quickstart / Core Concepts / Reference) + colocated working examples | +| Plan §6.3 design questions | (1) Exact concept-doc list in Layer 2 — Step 03 sketched 5-6 docs; Phase 3 finalizes the list and ordering. (2) Cross-link structure between Layers — which Layer 2 concepts link forward to which Layer 3 reference docs? (3) Doc-authoring style guide — voice, code-block conventions, cross-link conventions, "you" vs. "the developer" addressing; affects AI-acceleration efficiency in Phase 5. (4) Per-doc scope for Layer 3 reference docs — each Layer 3 doc has per-doc variance (per Step 05 §2.4 acknowledgment); Phase 3 firms up scope per doc | +| Constraints inherited from Phase 1 | F-25, F-40 (docs-vs-code gap) — narrative must close this gap, not deepen it; F-41 (auditor reproducibility) — auditor-verification reference doc must surface this property | +| Verification method (from Plan §6.3) | AI proxy-reader test against deployed site, 5 questions at ≥80% success rate | +| Dependencies (briefs this depends on) | **MC-04 brief** (Layer 3 writing-a-new-strategy doc references contract + worked example); **MC-21 brief** (Layer 3 secure-key-handling doc references Signer-injection patterns) — soft dependencies (IA can be designed before; specific doc content depends on prior briefs' completion) | +| Dependents (briefs that depend on this) | Verification brief (proxy-reader question set is verification instrument for IA); Observability brief (no direct dependency, but documentation is a touchpoint for the productization arc) | +| Principle-weight sensitivity | **High on Maintainability 1.5×** (IA quality determines AI-queryability, contributor ramp-up, long-term doc evolution); **High on Correctness Verification 1.5×** (proxy-reader test, link-checker, per-doc verification methods); Medium on Security 1.5× (Layer 3 secure-key-handling doc surface) | +| Phase 5 estimate-refinement expected | Possible at per-doc level — Plan §5.3 per-doc cut staging acknowledges variance; Phase 3 IA brief firms up per-doc scope which informs per-doc estimates | +| Step 01 §11.1 gap carryover | None | +| Step 03 iteration priority | **M-H** — large brief (covers Layer 1+2+3+examples); parallel-eligible with MC-04/MC-21 at the IA-design level; specific Layer 3 doc content depends on MC-04/MC-21 completion | + +### §2.4 — MC-12 brief + +| Field | Value | +| --------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | +| Source MC(s) | MC-12 | +| Origin | Plan §6.4 (primary) | +| Primary artifact type | **Schema** | +| Secondary type | None | +| Phase 2 chosen mechanism (summary) | npm `--provenance` + cyclonedx-npm SBOM + lockfile snapshot + release-evidence artifact | +| Plan §6.4 design questions | (1) Exact release-evidence artifact layout — file list, archive format, naming convention. (2) SBOM contents required — CycloneDX 1.5 baseline; any Diamonds-specific extensions? (3) Lockfile-snapshot format — raw yarn.lock + content hash, or processed dependency tree? (4) Auditor use-flow — how does an auditor _use_ the release-evidence artifact? Schema designed for auditor consumption, not just archival | +| Constraints inherited from Phase 1 | HC-06 (no external certification required) — schema is for verifiability, not for SLSA Level 2 certification; F-41 (auditor reproducibility) — release-evidence is how reproducibility surfaces as a feature | +| Verification method (from Plan §6.4) | Auditor-persona check: fresh AI session given npm URL + GitHub release URL verifies published code matches released source without practitioner support | +| Dependencies (briefs this depends on) | None at design level (schema is largely independent of contract / refactor / IA content) | +| Dependents (briefs that depend on this) | Verification brief (auditor-persona prompt verifies release-evidence schema); Observability brief (publish flow touchpoints) | +| Principle-weight sensitivity | **High on Security 1.5×** (provenance + SBOM are supply-chain security artifacts); **High on Correctness Verification 1.5×** (auditor-reproducibility is the verification surface); Medium on Maintainability 1.5× (schema longevity matters) | +| Phase 5 estimate-refinement expected | Not expected — schema-class brief; narrower uncertainty than contract/refactor briefs | +| Step 01 §11.1 gap carryover | None | +| Step 03 iteration priority | **M** — independent (parallelizable with MC-04/MC-21/MC-07); narrower uncertainty; high principle-weight sensitivity | + +### §2.5 — Observability brief + +| Field | Value | +| --------------------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | +| Source MC(s) | Cross-cutting — observability touchpoints inserting into MC-04 (contract lifecycle methods), MC-21 (Signer-use points), MC-11 (CI pipeline gates), MC-12 (publish flow); also potentially MC-22 (smoke workflow), MC-08 (docs site deploys) | +| Origin | Plan §10.1 (supplementary brief addressing Operations CONDITIONAL) | +| Primary artifact type | **Observability Touchpoints** | +| Secondary type | None | +| Phase 2 description | "v2.0 chosen mechanisms get observability hooks for future-cycle Operations elevation" | +| Plan-named design questions | **None enumerated in Plan §10.1.** Step 03 produces design questions during the brief's iteration. Expected question shape: (1) Which v2.0 chosen mechanisms get touchpoints, at what depth? (2) What observation modes (metric / log / trace / event) per touchpoint? (3) What alerting thresholds and dashboard sketches? (4) How do touchpoints support Phase 7 watch-triggers from Plan §10.3? | +| Constraints inherited | Operations CONDITIONAL frame (Plan §9); Operations 1.0× weight inherited unchanged (no silent elevation); v2.0 chosen mechanisms bound the touchpoint inventory | +| Verification method | None named in Plan §10.1 — Step 05 Verification Strategy will determine how observability design is verified (typically: review for completeness against MC-04/MC-21/MC-11/MC-12 chosen-mechanism surfaces; Phase 7 watch-trigger alignment) | +| Dependencies (briefs this depends on) | **All four primary briefs** (touchpoints insert into mechanisms the primaries specify) — strict dependency. Cannot complete observability brief until MC-04/MC-21/MC-12 specifications are at least drafted; MC-11 chosen mechanism is finalized in Plan §2.2 so no design-time dependency. | +| Dependents (briefs that depend on this) | Verification brief (verification of observability design itself); next-cycle Phase 2 Operations elevation (consumes observability surface) | +| Principle-weight sensitivity | **Baseline Operations 1.0×** (deprioritized; no silent elevation); Medium on Maintainability 1.5× (observability is part of the long-lived system surface); Low on Security 1.5× (touchpoints could expose data — design considers but is not dominated by) | +| Phase 5 estimate-refinement expected | **First estimate** — Phase 2 supplementary brief had no estimate; Step 03 produces | +| Step 01 §11.1 gap carryover | None | +| Step 03 iteration priority | **L-M** — last in strict order (depends on primary briefs); baseline weight; first design | + +### §2.6 — Verification brief + +| Field | Value | +| --------------------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | +| Source MC(s) | Cross-cutting — verification instruments for MC-04 (contract conformance), MC-21 (refactor invariants), MC-07 (proxy-reader for IA), MC-12 (auditor-persona for release evidence); also potentially MC-08 (link checker, search index validation), MC-22 (smoke workflow design) | +| Origin | Plan §10.1 (supplementary brief addressing Correctness Verification CONDITIONAL) | +| Primary artifact type | **Verification Artifacts** | +| Secondary type | None | +| Phase 2 description | "Proxy-reader question set, auditor-persona prompt, MC-04 conformance test scope" — i.e., produce the concrete instruments behind the per-MC verification methods named in Plan §6 | +| Plan-named design questions | **None enumerated in Plan §10.1.** Step 03 produces design questions during the brief's iteration. Expected question shape: (1) Which Phase 2-named verification methods need refinement into Phase 6-executable instruments? (2) For each instrument: scope, content, success criteria, execution discipline? (3) How do instruments compose across primary briefs (one auditor-persona for multiple primary briefs vs separate)? (4) Cross-brief integration with Step 05 (which instrument verifies which brief)? | +| Constraints inherited | Correctness Verification CONDITIONAL frame (Plan §9); Correctness Verification 1.5× weight elevated; Phase 2 §6 per-MC verification methods inherited as starting points | +| Verification method | Self-referential — verification of the verification instruments themselves is done by Step 05 review + practitioner sign-off | +| Dependencies (briefs this depends on) | **All four primary briefs** (instruments verify what the primaries specify) — strict dependency. Step 03 can begin design questions before primary briefs complete, but instrument content cannot finalize until verified-artifacts are specified. **Cannot complete before Step 05.** | +| Dependents (briefs that depend on this) | Step 05 Verification Strategy (consumes brief outputs and refines into Phase 6-executable form); Phase 6 (executes instruments) | +| Principle-weight sensitivity | **High on Correctness Verification 1.5×** (this is the brief that resolves the CV CONDITIONAL); Medium on Security 1.5× (instruments verify security properties); Medium on Maintainability 1.5× (instruments are themselves maintainable artifacts) | +| Phase 5 estimate-refinement expected | **First estimate** — Phase 2 supplementary brief had no estimate; Step 03 produces | +| Step 01 §11.1 gap carryover | None | +| Step 03 iteration priority | **M** — last in strict order (depends on primary briefs); refines into Step 05; elevated weight (CV 1.5×) | + +## §3 — Inter-Brief Dependency Graph + +``` + [No dependencies] + │ + ▼ + ┌──────────────┐ + │ MC-04 brief │ (Contract — the anchor) + └──────┬───────┘ + │ + ┌──────────┴──────────┐ + ▼ │ + ┌──────────────┐ │ + │ MC-21 brief │ │ + │ (Refactor) │ │ + └──────┬───────┘ │ + │ │ + │ │ + ┌──────┴──────────┐ │ + │ MC-07 brief │ │ + │ (IA — soft) │ │ + └──────┬──────────┘ │ + │ │ + ┌──────┴──────────┐ │ + │ MC-12 brief │ (Schema — independent of MC-04/MC-21/MC-07 + │ (parallel) │ at the design level) + └──────┬──────────┘ + │ + ┌───────────┼───────────┐ + │ │ │ + ▼ ▼ ▼ +┌─────────────────────────────────────┐ +│ [All four primary briefs │ +│ must be drafted before] │ +│ │ +│ ┌──────────────────────┐ │ +│ │ Observability brief │ │ +│ └──────────────────────┘ │ +│ │ +│ ┌──────────────────────┐ │ +│ │ Verification brief │ │ +│ └──────────────────────┘ │ +└─────────────────────────────────────┘ +``` + +**Dependency notes:** + +- **MC-04 → MC-21:** Strict. MC-21's post-state must be reflected in MC-04's contract. The contract reflects the post-MC-21 `RPCDeploymentStrategy` interface, not the pre-MC-21 one. MC-04 must be drafted to a state where MC-21's interface change can land against it. +- **MC-04 → MC-07 (Layer 3):** Soft. MC-07's IA can be designed at structural level (layers, cross-link graph, style guide) without MC-04 complete. But Layer 3 writing-a-new-strategy doc's _specific scope_ references MC-04's contract + worked example. +- **MC-21 → MC-07 (Layer 3):** Soft. Same pattern — MC-07's IA design proceeds in parallel; Layer 3 secure-key-handling doc's specific scope references MC-21's Signer-injection patterns. +- **MC-12:** Independent of MC-04 / MC-21 / MC-07 at the design-specification level. Can be drafted in parallel with any of the above. +- **Observability brief → all four primary briefs:** Strict. Touchpoints insert into mechanisms the primaries specify. Cannot complete until primaries are drafted. +- **Verification brief → all four primary briefs:** Strict. Instruments verify what the primaries specify. Cannot complete until primaries are drafted; specifically, verification brief content refines further in Step 05 after Step 04 coordination identifies cross-brief verification dependencies. + +## §4 — Sequencing Recommendation + +### §4.1 — Strict Order Tier + +Briefs with strict dependencies: + +1. **MC-04 brief** must complete (or reach drafted-state) before MC-21 brief can finalize +2. **MC-21 brief** completes after MC-04 +3. **MC-07 brief Layer 3 portion** depends on MC-04 / MC-21 (soft — IA structure can be designed first, then Layer 3 content firmed up) +4. **Observability brief** completes after all four primary briefs are at least drafted +5. **Verification brief** completes after all four primary briefs are at least drafted; further refinement in Step 05 + +### §4.2 — Parallel-Eligible Groups + +Briefs without strict dependencies on each other (can run in parallel Step 03 sessions if capacity permits): + +| Group | Briefs | Constraint | +| ------------------------------ | ----------------------------------------------------------------------- | ---------------------------------------------------------------------------------------------------------------- | +| Group A (after MC-04 anchor) | MC-21 brief + MC-12 brief | MC-21 depends on MC-04; MC-12 is independent. Both can be drafted in parallel after MC-04 reaches drafted state. | +| Group B (after primary briefs) | Observability brief + Verification brief | Both depend on all four primary briefs; can be drafted in parallel after primaries are at drafted state. | +| Group C (cross-cutting) | MC-07 brief structural design (Layers + style guide + cross-link graph) | Can be drafted in parallel with MC-04 / MC-21 / MC-12. Layer 3 per-doc scope refinement waits for MC-04 / MC-21. | + +### §4.3 — Last-Tier Briefs + +- **Verification brief** completes last among Step 03 outputs because Step 05 (Verification Strategy) refines it further into Phase 6-executable instruments +- **Observability brief** completes second-to-last; depends on primaries + +### §4.4 — Practitioner Execution Choice + +**Recommended execution: sequential per the strict order, with MC-12 + MC-07 structural design opportunistically parallel.** + +Rationale: Single-practitioner solo session capacity (per Step 00 §1 + HC-08 envelope) makes parallel AI sessions across briefs cognitively expensive even though they're technically eligible. Sequential execution with per-brief focus reset is the recommended pattern per the toolkit's behavioral rules. The Plan §1.2 defining mechanism ("narrow the claims-vs-proof gap") benefits from sequential per-brief focus; each brief's specification is more rigorous when authored in isolation. + +**Recommended Step 03 order:** + +1. **MC-04 brief** (anchor; widest weight-sensitivity; explicit refinement requirement; Branch 1 mitigation) +2. **MC-21 brief** (depends on MC-04; high principle-weight sensitivity) +3. **MC-12 brief** (independent; narrower uncertainty; opportunistic — could move earlier if practitioner prefers) +4. **MC-07 brief** (IA structure + per-doc scope; soft-dependent on MC-04 / MC-21) +5. **Observability brief** (depends on primaries) +6. **Verification brief** (depends on primaries; refined further in Step 05) + +Six Step 03 iterations total. Per the prompt's behavioral rule: one brief per session is the default, but sequential briefs in a single session work with explicit focus reset between. + +## §5 — Principle-Weight Sensitivity Summary + +| Principle | Weight | Briefs Sensitive | +| ------------------------ | -----: | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | +| Security | 1.5× | **MC-04 (High)** — JSDoc security boundaries, trust model; **MC-21 (High)** — SR-03 closure, Signer source trust; **MC-12 (High)** — provenance + SBOM are supply-chain security; MC-07 (Medium) — Layer 3 secure-key-handling doc; Verification (Medium) — security properties verified | +| Maintainability | 1.5× | **MC-04 (High)** — contract is long-lived extension surface; **MC-21 (High)** — migration path quality; **MC-07 (High)** — IA quality determines doc evolution; MC-12 (Medium) — schema longevity; Verification (Medium) — instruments are maintainable artifacts | +| Economics | 1.0× | **MC-04** estimate refinement is explicit (Plan §6.1); MC-07 per-doc cut staging affects cost realization; others baseline | +| Operations | 1.0× | **Observability brief (Baseline — deprioritized)** — design at 1.0× weight, no silent elevation; all v2.0 chosen mechanisms surface operational implications via touchpoints | +| Scoring & Metrics | 1.0× | All briefs contribute per-artifact scorecard contributions in Step 03 §5; Verification brief specifically produces scoring instruments | +| Correctness Verification | 1.5× | **MC-04 (High)** — conformance test is the verification surface; **MC-07 (High)** — proxy-reader test, link-checker, per-doc verification; **MC-12 (High)** — auditor-reproducibility; **Verification brief (High — addresses CV CONDITIONAL)** — concrete instruments are the resolution; MC-21 (Medium) — byte-identical deployment-record invariant; Observability (Low — verification of touchpoint design itself) | + +**Brief-distribution by sensitivity:** + +- **Highest-attention briefs:** MC-04 (High on Security, Maintainability, CV); MC-07 (High on Maintainability, CV; Medium on Security); Verification (High on CV; Medium on Security, Maintainability) +- **Mid-attention briefs:** MC-21 (High on Security, Maintainability; Medium on CV); MC-12 (High on Security, CV; Medium on Maintainability) +- **Lower-attention briefs:** Observability (Baseline Operations; Medium on Maintainability; Low on Security, CV) + +## §6 — Phase 5 Estimate-Refinement Briefs + +| Brief ID | Phase 2 Estimate | Estimate-Refinement Reason | Step 03 §3 Section Required? | +| ------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------- | ---------------------------------------------------------------------------------------------------------------------------- | ----------------------------------------------------------- | +| MC-04 brief | 8.0 maint-hrs ESTIMATED (~24 dev-hrs at 3× novel-design multiplier; ± 12 dev-hrs per Branch 1 narrative) | **Explicit** — Plan §6.1 names estimate uncertainty as wider than other MCs; Phase 3 design brief completeness should refine | **Yes** | +| MC-21 brief | 2.4 maint-hrs ESTIMATED | Possible — refactor-class brief; edge cases (Signer source variants, internal-architecture implications) may emerge | Step 03 produces §3 if edge cases surface | +| MC-07 brief | 0.75 + 3.0 + 4.0 + 1.0 = 8.75 maint-hrs ESTIMATED (cumulative across Layer 1+2+3+examples); Plan §5.3 per-doc staging acknowledges Layer 3 variance | Possible at per-doc level — Phase 3 IA brief firms up per-doc scope which informs per-doc estimates | Step 03 produces §3 at per-doc granularity for Layer 3 docs | +| MC-12 brief | 1.6 maint-hrs ESTIMATED | Not expected — schema-class brief; narrower uncertainty | No | +| Observability brief | None (supplementary brief; no Plan §3 cost row) | First estimate — Step 03 produces | **Yes** (first estimate) | +| Verification brief | None (supplementary brief; no Plan §3 cost row) | First estimate — Step 03 produces; further refined in Step 05 | **Yes** (first estimate) | + +## §7 — Validation-Gap Carryovers + +| Brief ID | Gap from Step 01 §11 | Resolution Approach in Step 03 | +| ----------- | ---------------------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | +| MC-21 brief | **VG-P3-U-01 (P3-Obs-04)** — Phase 2 Step 03 §2 detail missing | Phase 3 proceeds with Plan §6.2 content as authoritative. Rejected alternative (deprecation cycle with shim) inferred from Plan §6.2 + Step 03 §3.1. Step 03 specification will note the inferred alternative explicitly so future cycles see the inference, not a silent re-litigation. Upstream toolkit revision recommendation captured in Step 01 §11.2 for Phase 2 v1.2. | +| MC-04 brief | **VG-P3-U-02 (P3-Obs-05)** — NTI cycle-vs-future-cycle ambiguity | Phase 3 Step 03 MC-04 specification will state explicitly: "diamonds-safe / NTI-03 is NOT being built this cycle. This cycle produces the contract + worked sibling example + how-to-write-a-new-strategy doc that enable future-cycle diamonds-safe work." Upstream toolkit revision recommendation captured in Step 01 §11.2 for Phase 2 v1.2. | + +## §8 — Comprehensiveness Check Result + +| Item | Result | +| ------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------ | +| Practitioner surfaced any candidate brief outside Plan §6/§10.1? | **No** — practitioner confirmation 2026-05-26: no design decisions noticed beyond the six briefs | +| If Yes, candidate brief description | n/a | +| If Yes, routing (upstream toolkit gap / Phase 2 run amendment / accept and add to register) | n/a | +| Step 03 execution sequence | **Confirmed:** MC-04 → MC-21 → MC-12 → MC-07 → Observability → Verification | + +--- + +## Step 03 Execution Plan + +**Six briefs to process; sequential execution per §4.4 recommendation.** + +| Order | Brief | Type | Iteration Priority | Expected Step 03 Effort (this dogfood session) | +| ----: | ------------------- | ------------------------- | ------------------ | -------------------------------------------------------------------------------------------------- | +| 1 | MC-04 brief | Contract | H | Substantial (anchor brief; widest weight-sensitivity; explicit refinement; ~30-45 min interactive) | +| 2 | MC-21 brief | Refactor | H | Moderate (depends on MC-04; rejected alternatives inference from VG-P3-U-01) | +| 3 | MC-12 brief | Schema | M | Moderate (independent; narrower uncertainty) | +| 4 | MC-07 brief | IA | M-H | Substantial (covers Layer 1+2+3+examples; per-doc scope work) | +| 5 | Observability brief | Observability Touchpoints | L-M | Moderate (first design; baseline weight) | +| 6 | Verification brief | Verification Artifacts | M | Moderate (first design; refined further in Step 05) | + +**Sequencing note:** MC-12 (item 3) is positioned earlier than MC-07 (item 4) despite MC-07 being primary because MC-12 is independent and benefits from being done while MC-04 / MC-21 context is fresh; MC-07 then proceeds in a fresh focus reset for the substantial IA work. + +**Per the toolkit's "one brief per session is the default" rule:** Practitioner may choose to process all six briefs in this single session with explicit focus resets between each, or split across sessions. The dogfood proceeds with sequential single-session execution; observation captured if multi-brief single-session degrades brief quality. + +--- + +## Version History + +| Version | Date | Source | Summary | +| ------- | ---------- | ------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | +| v1.0 | 2026-05-26 | Initial Step 02 production for Diamonds Phase 3 dogfood | Six briefs classified (4 Contract/Refactor/IA/Schema primary + 2 Observability Touchpoints/Verification Artifacts supplementary); dependency graph captured with MC-04 → MC-21 → primaries-as-prereq-for-supplementaries strict order; principle-weight sensitivity mapped per brief; estimate-refinement flagged per brief; VG-P3-U-01 and VG-P3-U-02 carryover resolution paths defined; sequential execution recommended per §4.4. | + +--- + +_Part of the Phase 3 (Existing Projects) Design & Technical Analysis Tool Set — v1.0_ +_AI-Centric Software Development Playbook_ +_Companion file: `design-technical-analysis.existing-project.instructions.md`_ +_Previous step: `step-01-phase-2-input-validation.prompt.md` (Validation Report produced; Anchored status)_ +_Next step: `step-03-per-artifact-design-specification.prompt.md` (six brief iterations)_ diff --git a/project/AICSDP/p3/step-03-mc-04-design-specification.md b/project/AICSDP/p3/step-03-mc-04-design-specification.md new file mode 100644 index 0000000..5aa18cd --- /dev/null +++ b/project/AICSDP/p3/step-03-mc-04-design-specification.md @@ -0,0 +1,418 @@ +# Design Specification Artifact — MC-04 brief + +**Brief ID:** MC-04 brief +**Source MC(s):** MC-04 (Strategy extensibility for external multi-party modules) +**Origin:** Plan §6.1 (primary) +**Primary Artifact Type:** Contract +**Secondary Type:** None +**Specification Date:** 2026-05-26 +**Practitioner:** Solo maintainer (DiamondsLab) +**AI Model:** Claude Opus 4.7 +**Improvement Plan Version:** v1.0 (2026-05-22, no amendments) +**Step 02 Register Reference:** Step 02 §2.1 (MC-04 brief) +**Status:** Draft — Pending Practitioner Final Review + +> ⚠️ This artifact specifies the chosen mechanism at design level. +> It is Phase-5-implementable without further design work. Phase 4 +> architecture decisions, Phase 5 implementation details, and Phase +> 6 verification execution are out of scope. + +--- + +## §1 — Brief Intake Confirmation + +| Field | Value | Confirmed | +| ---------------------------------------------------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ------------------------------------ | +| Brief ID | MC-04 brief | Yes | +| Phase 2 chosen mechanism (full text) | "Formal extension contract — TypeScript interface (IDeploymentStrategy) with explicit lifecycle methods, plus a contract conformance test suite that external strategy implementations can run against. Document the contract as a versioned interface, with a worked sibling-strategy example (one minimal but functional external strategy) that proves the contract is sufficient." | Yes | +| Plan §6.1 design questions | Q1: Specific lifecycle methods; Q2: JSDoc security-boundary semantics; Q3: Conformance test suite scope; Q4: Worked sibling example shape; Q5: NTI-03 interaction | Yes — all five addressed in §2 below | +| Inherited constraints | MK-08 (ERC-2535 conformance); HC-05 (v2.0 breaking changes per-item justified); F-41 (auditor reproducibility) | Yes | +| Verification method named in Plan | Contract conformance test passes against worked example; reference external strategy produces auditor-reproducible deployment records; TypeScript interface JSDoc covers security boundaries | Yes | +| Artifact type (primary) | Contract — confirmed against Step 02 §2.1 classification | Yes | +| Step 01 §11.1 gap carryover (if any) — resolved | None | Yes | +| Step 02 §7 carryover (VG-P3-U-02 NTI cycle-vs-future-cycle) — resolved | Yes — diamonds-safe NOT being built this cycle; contract + worked sibling example + migration doc enable future-cycle work | Yes (stated explicitly in §2.5) | + +--- + +## §2 — Design Specification + +### §2.1 — Method Surface + +**Design specification:** + +The v2.0 contract is the TypeScript interface **`IDeploymentStrategy`** (renamed from v1.3.2's `DeploymentStrategy`), formalizing all 15 lifecycle methods currently exposed by `DeploymentStrategy.ts`: + +| Phase | pre Method | main Method | post Method | +| --------------------------------- | -------------------------------------------------------------------- | ----------------------------------------------------------------- | --------------------------------------------------------------------- | +| Deploy Diamond | `preDeployDiamond(diamond: Diamond): Promise` | `deployDiamond(diamond: Diamond): Promise` | `postDeployDiamond(diamond: Diamond): Promise` | +| Deploy Facets | `preDeployFacets(diamond: Diamond): Promise` | `deployFacets(diamond: Diamond): Promise` | `postDeployFacets(diamond: Diamond): Promise` | +| Update Function Selector Registry | `preUpdateFunctionSelectorRegistry(diamond: Diamond): Promise` | `updateFunctionSelectorRegistry(diamond: Diamond): Promise` | `postUpdateFunctionSelectorRegistry(diamond: Diamond): Promise` | +| Perform Diamond Cut | `prePerformDiamondCut(diamond: Diamond): Promise` | `performDiamondCut(diamond: Diamond): Promise` | `postPerformDiamondCut(diamond: Diamond): Promise` | +| Run Post-Deploy Callbacks | `preRunPostDeployCallbacks(diamond: Diamond): Promise` | `runPostDeployCallbacks(diamond: Diamond): Promise` | `postRunPostDeployCallbacks(diamond: Diamond): Promise` | + +**Stratified JSDoc treatment.** The 15 methods receive different JSDoc rigor based on extension role: + +- **5 main methods** (`deployDiamond`, `deployFacets`, `updateFunctionSelectorRegistry`, `performDiamondCut`, `runPostDeployCallbacks`) get full JSDoc: + - Purpose + - Parameter contract + - Post-conditions (per §2.3 below) + - Idempotency posture (per §2.2 below) + - Trust assumptions (per §2.3 below) + - Edge case handling guidance +- **10 pre/post hook methods** get brief JSDoc: + - Purpose ("extension point for X before/after the main phase") + - Empty-default-implementation note (the base class implementation does nothing; override if your strategy needs to take action) + +**Import surface:** + +- v2.0 publishes the interface as `IDeploymentStrategy` only +- No alias for the old `DeploymentStrategy` name (hard break) +- Migration doc (jointly authored with MC-21 brief's migration coverage; lives in `examples/migration-v1-to-v2.md` or equivalent per MC-07 IA decisions) walks the rename: + - Before (v1.3.2): `import { DeploymentStrategy } from '@diamondslab/diamonds'` + - After (v2.0): `import { IDeploymentStrategy } from '@diamondslab/diamonds'` +- HC-05's "v2.0 breaking changes per-item justified" discipline: the rename's justification = consistent TypeScript interface naming convention; bundled with MC-21's Signer-injection break into one coherent v2.0 migration narrative + +**Phase 5 implementation note:** Phase 5 renames `src/strategies/DeploymentStrategy.ts` → `src/strategies/IDeploymentStrategy.ts` and updates all internal imports. The 15 method signatures match the existing `DeploymentStrategy.ts` shape; only the name changes at this stage. + +### §2.2 — Lifecycle Semantics + +**Design specification:** + +**Phase ordering (interface-level JSDoc):** + +> "When invoked by `DiamondDeployer`, the 5 phases execute in this order: +> +> 1. Deploy Diamond +> 2. Deploy Facets +> 3. Update Function Selector Registry +> 4. Perform Diamond Cut +> 5. Run Post-Deploy Callbacks +> +> Within each phase, the pre/main/post methods execute in that order." + +**Idempotency posture per method:** + +| Method | Idempotency | Annotation | +| ------------------------------------ | -------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | +| `preDeployDiamond` | Idempotent in steady state | "Default implementation is idempotent (no-op). Overrides should preserve idempotency where the strategy's semantics permit." | +| `deployDiamond` | **NOT IDEMPOTENT** | "This method deploys a new Diamond contract on-chain. Calling twice with the same input deploys two Diamonds. Implementers should guard against accidental re-invocation (e.g., by checking `deployedDiamondData.DiamondAddress` before deploying)." | +| `postDeployDiamond` | Idempotent in steady state | Same as `preDeployDiamond`. | +| `preDeployFacets` | Idempotent in steady state | Same. | +| `deployFacets` | Idempotent in steady state | "The default implementation checks `deployedVersion` vs `upgradeVersion` per facet and is a no-op for facets already at target version. Overrides should preserve this property." | +| `postDeployFacets` | Idempotent in steady state | Same as `preDeployFacets`. | +| `preUpdateFunctionSelectorRegistry` | Idempotent in steady state | Same. | +| `updateFunctionSelectorRegistry` | Idempotent in steady state | "Applies registry updates from the current in-memory state. Applying twice produces the same result." | +| `postUpdateFunctionSelectorRegistry` | Idempotent in steady state | Same. | +| `prePerformDiamondCut` | Idempotent in steady state | Same. | +| `performDiamondCut` | **NOT IDEMPOTENT** | "This method submits an on-chain diamondCut transaction. Calling twice attempts the same cuts; result depends on the diamond's current on-chain state (may revert or no-op). Implementers should guard against accidental re-invocation." | +| `postPerformDiamondCut` | Idempotent in steady state | Same. | +| `preRunPostDeployCallbacks` | Idempotent in steady state | Same. | +| `runPostDeployCallbacks` | Implementation-dependent | "Idempotency depends on the callbacks registered. Implementer is responsible for documenting callback idempotency." | +| `postRunPostDeployCallbacks` | Idempotent in steady state | Same. | + +**Atomicity across phases:** + +> "The contract does NOT guarantee atomicity across phases. If a strategy execution fails partway through, the implementer's pre/main/post hooks for the last completed phase have run, but no subsequent phase has. Recovery is the implementer's responsibility — typically by reading `deployedDiamondData` to determine the last completed state and resuming from there." + +**Implicit state semantics:** + +> "Each method receives the `Diamond` object with state mutations from all prior methods in the lifecycle already applied. Implementers may read the state freely. State mutations within a method MUST go through the `Diamond` object's public methods (`updateDeployedDiamondData`, `registerFunctionSelectors`, etc.) — direct field manipulation is forbidden by contract." + +**Error recovery:** + +> "Methods may throw on failure. The contract does NOT specify error recovery semantics — strategies that need transactional recovery (e.g., retry-on-error with exponential backoff) implement recovery within their own method bodies. Implementers should not assume the caller will retry; methods should leave `deployedDiamondData` in a consistent state even when throwing (mutations made before the throw are visible)." + +### §2.3 — Security Boundaries + +**Design specification:** + +**Architecture:** Contract specifies **post-conditions** that conforming implementations must satisfy; `BaseDeploymentStrategy` extension is the **recommended-but-not-required** implementation pattern. External strategies that implement `IDeploymentStrategy` directly are valid as long as they satisfy contract post-conditions. + +**Post-conditions per method:** + +| Method | Post-condition | +| ------------------------------------------ | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | +| `deployDiamond` (returns) | `diamond.getDeployedDiamondData().DiamondAddress` is set to a non-zero address; `DeployedFacets['DiamondCutFacet']` is populated with `{ address, tx_hash, version: 0, funcSelectors }` | +| `deployFacets` (returns) | For each facet in `getDeployConfig().facets` with a target version > current deployed version: `getNewDeployedFacets()[facetName]` is populated with `{ priority, address, tx_hash, version, funcSelectors, deployInclude, deployExclude, initFunction, verified }` | +| `updateFunctionSelectorRegistry` (returns) | `diamond.functionSelectorRegistry` reflects all new facet additions; any selectors for retired facets carry `RegistryFacetCutAction.Remove`; no orphaned selectors (selectors with `Add`/`Replace`/`Deployed` action whose `facetName` matches another entry with a different `address`) | +| `performDiamondCut` (returns) | The diamond contract on-chain reflects all facet cuts in the registry; `deployedDiamondData.DeployedFacets` is updated to reflect the post-cut state; `deployedDiamondData.protocolVersion` matches the config's protocolVersion | +| `runPostDeployCallbacks` (returns) | All registered callbacks for facets in the new deployment have executed (or the strategy threw mid-callback) | +| All 10 `pre*` and `post*` hooks | No post-conditions (extension hooks; implementer-defined behavior) | + +**Trust assumptions (interface-level JSDoc — visible to auditors):** + +The contract assumes implementers honor these properties. The contract cannot enforce them at the type or runtime level; making the assumptions explicit lets auditors assess specific implementers against them. + +| Assumption | What it means for implementers | +| --------------------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | +| **Honest about state mutations** | The implementer doesn't construct a "shadow" `Diamond` object and update the real one with falsified data. The implementer uses the real `diamond` parameter as the state surface. | +| **Correct about on-chain transactions** | If the implementer claims a transaction succeeded (records a tx hash), it did. The recorded tx hash is real. | +| **Single-Signer discipline** | All on-chain calls go through `diamond.getSigner()`. The implementer doesn't construct a separate Signer mid-execution. | +| **Lifecycle ordering respected** | Within a phase, pre/main/post are called by `DiamondDeployer` in order; the implementer doesn't reorder them via its own logic. | + +**Phase 6 verification note:** The conformance test suite (§2.4) verifies the post-conditions mechanically. The trust assumptions are not mechanically verifiable; they are auditor-relevant context. + +### §2.4 — Conformance Scope + +**Design specification:** + +**Conformance test suite: 17 tests across 3 categories.** + +#### Category 1 — Lifecycle compliance (5 tests) + +| Test ID | What it verifies | +| ------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | +| C-L-01 | All 15 lifecycle methods are present on the strategy implementation (TypeScript type-check) | +| C-L-02 | Methods are called in the contract-specified order when invoked through `DiamondDeployer` | +| C-L-03 | Within each phase, pre → main → post ordering holds | +| C-L-04 | Methods marked idempotent return without error when called twice with same input; observable state is identical | +| C-L-05 | Methods marked non-idempotent (`deployDiamond`, `performDiamondCut`) may throw on second invocation OR are guarded by the implementer; the test verifies guard or accepts the throw | + +#### Category 2 — Post-condition compliance (7 tests) + +| Test ID | What it verifies | +| ------- | -------------------------------------------------------------------------------------- | +| C-P-01 | After `deployDiamond`, `deployedDiamondData.DiamondAddress` is a non-zero address | +| C-P-02 | After `deployDiamond`, `DeployedFacets['DiamondCutFacet']` is populated | +| C-P-03 | After `deployFacets`, `getNewDeployedFacets()` is populated for each upgradeable facet | +| C-P-04 | After `updateFunctionSelectorRegistry`, no orphaned selectors exist | +| C-P-05 | After `performDiamondCut`, the on-chain diamond reflects all facet cuts | +| C-P-06 | After `performDiamondCut`, `deployedDiamondData.protocolVersion` matches config | +| C-P-07 | After `runPostDeployCallbacks`, all registered callbacks have executed | + +#### Category 3 — Edge case handling (5 tests) + +| Test ID | What it verifies | +| ------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | +| C-E-01 | **Partial-deployment recovery** — strategy invoked twice with a `Diamond` where Phase 1+2 completed but Phase 3 was interrupted; second invocation completes the deployment without re-deploying Phase 1+2 artifacts | +| C-E-02 | **Deployment-record migration** — strategy invoked against a `Diamond` with v1 `deployedDiamondData`; strategy produces v2 `deployedDiamondData` with v1 data preserved appropriately and v2 changes applied | +| C-E-03 | **Multi-call mid-phase failure (deployFacets)** — within `deployFacets`, simulate one facet deployment failing; verify `deployedDiamondData` reflects the facets that did deploy and doesn't claim the failed one deployed | +| C-E-04 | **Multi-call mid-phase failure (performDiamondCut)** — within `performDiamondCut`, simulate cut transaction failure; verify `deployedDiamondData` doesn't claim a cut that didn't happen | +| C-E-05 | **Empty deployment** — strategy invoked with a `Diamond` config that has zero facets; verify the strategy doesn't throw and produces a valid (empty-facets) deployment record | + +**Conformance harness location:** + +- Lives in the Diamonds repo at `src/strategies/__conformance__/` (or equivalent — Phase 5 implementation detail) +- Published as `@diamondslab/diamonds/conformance` sub-export (Phase 5 chooses the npm packaging mechanism) +- Implementation-agnostic: tests verify the contract surface, not the inheritance pattern; works for any class claiming to implement `IDeploymentStrategy` + +**Three purposes the conformance suite serves:** + +1. **Self-conformance** — Diamonds' own CI runs the suite against `LocalDeploymentStrategy`, `RPCDeploymentStrategy`, and `LoggingDeploymentStrategy` (the worked sibling example). If any fails conformance, Diamonds caught it before release. +2. **Contract regression detection** — when Diamonds changes the contract in a future cycle, Diamonds' own strategies must still pass. If they don't, the contract change broke `BaseDeploymentStrategy` or its subclasses, and the contract-change cost becomes visible. +3. **External conformance** — external strategy authors run the same suite against their implementations. They get verifiable evidence of conformance, and when Diamonds updates the contract (new version of `@diamondslab/diamonds`), external authors run their conformance against the updated suite to find any new breakage. + +**Conformance suite versioning:** + +- v2.0 contract ships v1.0 of the conformance suite +- Future v2.1 that adds a new lifecycle method ships v1.1 of the conformance suite (additive — old strategies still pass) +- Future v3.0 that changes contract semantics ships v2.0 of the conformance suite (breaking — old strategies must update to claim v3.0 conformance) + +**Execution discipline:** + +- **Per-PR (Diamonds CI):** Category 1 (C-L-_, 5 tests) + Category 2 (C-P-_, 7 tests) = 12 tests +- **Pre-release (Diamonds CI on tag push or release branch):** Category 3 (C-E-\*, 5 tests) = 5 tests +- **Release-evidence (MC-12 brief):** Full 17-test run output included in v2.0 release-evidence artifact + +External strategy authors are encouraged to follow the same execution discipline against their implementations. + +### §2.5 — Worked Reference Implementation + +**Design specification:** + +**Strategy: `LoggingDeploymentStrategy`** + +- Extends `BaseDeploymentStrategy` +- Demonstrates extension via pre/post lifecycle hooks +- Useful real-world artifact: structured logging for debugging deployment workflows + +**Logging scope:** + +| What is logged | When | +| --------------------------------------------------- | --------------------------------------------------------------------------------------------- | +| Lifecycle event: method entry | At the start of each of the 15 lifecycle methods | +| Lifecycle event: method exit | At successful return of each of the 15 lifecycle methods | +| Lifecycle event: method throw | At thrown error from any method (with error class + message; not full stack trace by default) | +| State transition: deployment-record update | Each call to `diamond.updateDeployedDiamondData(...)` | +| State transition: function-selector-registry update | Each `Add`/`Replace`/`Remove` operation on the registry | +| On-chain transaction hash | Each `deploy()`, `diamondCut()`, callback transaction submission | + +**Log format:** Structured (specific format — JSON, key-value, structured-text — is a Phase 5 implementation choice based on existing `BaseDeploymentStrategy` logging conventions). Each log line includes: timestamp, diamond name, phase, method, event type, structured payload. + +**Sensitive-field redaction:** Not in scope for v2.0. The worked example logs raw addresses and tx hashes. (A future strategy could add redaction discipline — this is intentional v1.0 scope.) + +**Repository location:** + +- **Ships in `src/strategies/`** alongside `LocalDeploymentStrategy` and `RPCDeploymentStrategy` +- External users `import { LoggingDeploymentStrategy } from '@diamondslab/diamonds'` +- **Brief walkthrough in `examples/logging-strategy/`** (1-2 pages): how `LoggingDeploymentStrategy` uses the extension hooks; the design decisions; conformance run output for the example + +**Diamonds CI:** Conformance suite runs against `LoggingDeploymentStrategy` per the §2.4 execution discipline. + +**NTI-03 / `diamonds-safe` framing (resolving VG-P3-U-02):** + +> **The worked sibling example is NOT `SafeDeploymentStrategy` and is NOT the realization of NTI-03 / `diamonds-safe`.** It is a deliberately minimal example whose purpose is to **prove the contract is sufficient for external implementers**. Future-cycle work builds `diamonds-safe` once the contract exists in v2.0. This cycle produces: +> +> - The `IDeploymentStrategy` contract (the surface external strategies implement) +> - The worked sibling example (`LoggingDeploymentStrategy`) proving the contract is sufficient +> - The how-to-write-a-new-strategy reference doc (MC-07 brief Layer 3) referencing this contract + worked example +> +> Together these enable future-cycle `diamonds-safe` work without requiring this cycle to build it. + +### §2.6 — Rejected Alternatives at Specification Level + +| Decision | Alternatives Considered | Selected Option | Why Other Options Rejected | +| ------------------------------ | ---------------------------------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------- | +| Method surface partition | (i) Formalize all 15; (ii) Reduce to 5 main methods; (iii) Formalize all 15 with stratified JSDoc | **(iii)** | (i) over-specifies; (ii) breaks existing extenders by dropping pre/post hooks from contract; (iii) preserves consumer expectations and gives clear extension partition | +| Interface naming | (i) `IDeploymentStrategy`; (ii) Keep `DeploymentStrategy`; (iii) Rename to `DiamondDeploymentLifecycle` | **(i)** | (ii) inconsistent with Plan §6.1 framing; (iii) outside MC-21's stated scope; (i) matches Plan | +| Import surface | (i) Hard break only; (ii) Soft alias re-export; (iii) Hard break + migration doc | **(iii)** | (ii) accumulates technical debt + violates MC-21's clean-break discipline; (iii) is (i) with HC-05's per-item-justification discipline made explicit | +| Lifecycle ordering | (i) 15-method strict order; (ii) 5-phase ordered, pre/main/post within-phase convention; (iii) Phase-only, pre/post implementation-dependent | **(ii)** | (i) over-specifies; (iii) under-specifies; (ii) matches `BaseDeploymentStrategy` actual behavior | +| Idempotency | (i) No idempotency guarantee; (ii) Per-method specification with two non-idempotent exceptions; (iii) Implementer's responsibility to document | **(ii)** | (i) loses retry-on-failure property; (iii) leaves readers without contract picture; (ii) captures `BaseDeploymentStrategy` behavior faithfully | +| Security boundary architecture | (i) JSDoc-only; (ii) JSDoc + protected method enforcement; (iii) JSDoc + post-condition conformance assertions | **(iii)** at contract level + **(ii)** as recommended pattern | (i) doesn't help direct implementers; (ii) alone doesn't help non-Base implementers; (iii) provides "provably not bypass" at conformance test surface | +| Conformance test categories | Various enumerations | **17 tests across 3 categories** (5 + 7 + 5) | Walkthrough produced consensus on the 17-test list; no alternative warranted separate elaboration | +| Conformance harness location | (i) Diamonds sub-export with runner; (ii) Reusable copy-into-own-repo pattern; (iii) Diamonds-internal only with documented pattern | **(i)** | (ii) test logic drifts; (iii) doesn't produce verifiable evidence for externals; (i) is the only architecture producing "claims-vs-proof gap" narrowing | +| Test execution discipline | (i) All 17 per-PR; (ii) 12 per-PR + 5 pre-release; (iii) All 17 per-PR + nightly extended | **(ii)** | (i) per-PR runtime cost; (iii) two CI surfaces under HC-08 capacity envelope; (ii) pragmatic middle | +| Worked example shape | (i) `LoggingDeploymentStrategy`; (ii) `ExternalSignerDeploymentStrategy`; (iii) `MockDeploymentStrategy`; (iv) `JSONFileDeploymentStrategy` | **(i)** | (ii) HW/KMS dimension grows beyond minimal; (iii) "fake the contract" wrong message; (iv) novel and untested; (i) clean demonstration + useful artifact | +| Logging scope | (i) Lifecycle-only; (ii) Lifecycle + state transitions; (iii) Lifecycle + state + redaction | **(ii)** | (i) doesn't demonstrate A.3 state-mutation surface; (iii) redaction is own design exercise; (ii) shows both lifecycle and contract's state-mutation surface | +| Worked example location | (i) Ships in `src/strategies/`; (ii) Lives in `examples/`; (iii) Hybrid — ships + brief walkthrough | **(iii)** with soft take | (i) misses educational opportunity; (ii) less integrated; (iii) class ships + brief 1-2 page walkthrough in examples/ | + +--- + +## §3 — Phase 5 Estimate Refinement + +**Three-quantity cost model refinement** (per Phase 2 v1.1 discipline; multipliers BELIEVED at v1.0): + +| Quantity | Phase 2 Estimate | Phase 3 Refined Estimate | Tag | Rationale | +| ------------------------------------- | ---------------: | -----------------------: | --------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | +| Dev-hours | 24 (± 12) | **26 (± 4)** | ESTIMATED | Decomposition: interface JSDoc authoring 6 dev-hrs; conformance suite 17 tests at ~1 dev-hr each = 17 dev-hrs; `LoggingDeploymentStrategy` + walkthrough 3 dev-hrs. Refinement narrowed the uncertainty band because the 17-test enumeration and worked-example shape are now concrete. | +| AI-acceleration multiplier (category) | 3× novel-design | **3× novel-design** | BELIEVED | Specification-heavy work; novel-design category continues to apply. No Phase 5 calibration data yet to upgrade tag. | +| Derived maintainer-hours | 8.0 | **~8.7** | ESTIMATED | 26 ÷ 3 = 8.67. Within Plan §6.1's stated ±12 dev-hour band, slightly above the 8.0 central estimate. | +| Token-count (derived) | 144K | **~156K** | ESTIMATED | 26 dev-hrs × 6,000 tokens/hr = 156K. | +| Token-cost (derived) | $3.50 | **~$3.90** | ESTIMATED | 156K × $2.50/100K = $3.90. | + +**Net effect of refinement:** Estimate central value rose ~9% (8.0 → 8.7 maint-hrs), but the uncertainty band narrowed from ±12 dev-hours to ±4 dev-hours. The refinement reduces cost _risk_ without reducing cost — consistent with Plan §6.1's Branch 1 mitigation intent (surface edge cases at design time, not implementation time). + +**Capacity impact:** Diamonds' ~2 hr/week share — 8.7 maint-hrs is ~4 weeks of work for MC-04 alone. Fits within Plan §3's Tier 2 envelope (~12 weeks total). + +**Multiplier graduation note:** The 3× novel-design multiplier remains BELIEVED. Phase 5 execution of MC-04 will produce the first empirical data point for novel-design category multiplier (per Plan §10.4 Phase 7 Calibration Handoff). If Phase 5 actual dev-hours-vs-maint-hours ratio differs from 3×, that's calibration data for graduating BELIEVED → ESTIMATED → MEASURED. + +--- + +## §4 — Cross-Brief References + +| Related Brief | Relationship | Reference | +| ------------------------- | ------------------------------------------------------------------------------------ | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | +| **MC-21 brief** | Provides post-refactor interface that this contract reflects | §2.1 method surface inherits post-MC-21 `RPCDeploymentStrategy` shape; the contract IS the post-MC-21 interface | +| **MC-07 brief (Layer 3)** | Receives this specification as input for "how-to-write-a-new-strategy" reference doc | MC-07's Layer 3 reference doc set will include a writing-a-new-strategy guide referencing this contract spec; `examples/logging-strategy/` walkthrough sits adjacent to MC-07's example-colocation pattern | +| **Observability brief** | Will insert touchpoints at this contract's lifecycle methods | The 15 lifecycle methods are natural observability insertion points; the Observability brief chooses which methods get touchpoints at what depth | +| **Verification brief** | Refines the 17 conformance tests into Phase 6-executable instruments | Step 05's Verification Strategy refines test enumeration (test cases, inputs, expected outputs, verification predicates) for each of the 17; this Step 03 specification is the source | +| **MC-12 brief** | Release-evidence schema includes conformance suite version + run output | MC-12's release-evidence artifact layout will include conformance run results; this Step 03 specification provides the "what gets included" half | + +--- + +## §5 — Per-Artifact Principle Scorecard Contribution + +| Principle | Weight (Inherited) | Per-Artifact Rating | Rationale | +| ------------------------ | -----------------: | ------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | +| Security | 1.5× | **PASS** | §2.3 post-condition specification provides "provably not bypass" via conformance test; trust assumptions enumerated explicitly in JSDoc; conformance test Category 2 verifies deployment-record-writing path is exercised | +| Maintainability | 1.5× | **PASS** | §2.1 stratified JSDoc partitions "must understand" (5 main methods) from "may extend" (10 pre/post hooks); §2.4 conformance harness as sub-export = contract-regression detection mechanism; §2.6 rejected alternatives documented prevent future-cycle re-litigation | +| Economics | 1.0× | **PASS** | §3 Phase 5 estimate refinement produced; refined estimate within Plan §6.1's ±12 dev-hour band; capacity envelope (Plan §3) preserved | +| Operations | 1.0× | **PASS (baseline)** | Baseline weight preserved (no silent elevation); Observability brief will produce touchpoint design for this contract's lifecycle methods; contract's lifecycle methods are natural observability insertion points | +| Scoring & Metrics | 1.0× | **PASS** | Per-artifact scoring discipline applied (this scorecard); §2.4 conformance test count (17) and execution discipline (12 PR + 5 release) provide measurable artifacts; §3 estimate refinement produces measurable cost-vs-budget evidence | +| Correctness Verification | 1.5× | **PASS** | §2.4 conformance suite is the central CV instrument — produces verifiable evidence of contract conformance; §2.3 post-conditions are the verification predicates; the Verification brief (later Step 03 iteration) will further refine the 17 tests into Phase 6-executable form | + +**Weight-sensitivity flags:** + +- **Highest sensitivity:** Security (1.5×) and Correctness Verification (1.5×) — A.3 + A.4 decisions could have moved these scores materially. A weaker A.3 (Option i JSDoc-only) or smaller A.4 conformance scope would have produced CONDITIONAL. The strong A.3 + A.4 decisions hold both at PASS. +- **Medium sensitivity:** Maintainability (1.5×) — A.1 stratification was the key call; without it, the contract surface could have ended up either over-rigid or under-specified, moving Maintainability to CONDITIONAL. +- **Lower sensitivity:** Economics, Operations, Scoring & Metrics — design decisions had limited material effect on these principle scores at the artifact level. + +**Below-threshold flags:** None. All six principles at PASS. + +--- + +## §6 — Phase 2 Invalidation Check + +| Field | Result | +| -------------------------------------------------------------- | -------------- | +| Does this specification reveal Phase 2 mechanism invalidation? | **No** | +| If Yes, invalidation report attached | Not applicable | + +The Phase 2 chosen mechanism (Formal TypeScript `IDeploymentStrategy` interface + lifecycle methods + JSDoc security-boundary annotations + contract conformance test suite + worked sibling-strategy example) was specifiable at design level. Each Phase 2 Plan §6.1 design question received a concrete answer: + +- Q1 (lifecycle methods specifics) → §2.1 + §2.2: 15 methods formalized with 5-phase ordering +- Q2 (JSDoc security-boundary semantics) → §2.3: post-conditions + trust assumptions +- Q3 (conformance test scope) → §2.4: 17 tests across 3 categories +- Q4 (worked sibling example shape) → §2.5: `LoggingDeploymentStrategy` +- Q5 (NTI-03 interaction) → §2.5 + Step 01 Category 11 clarification: diamonds-safe NOT built this cycle; contract + example + migration doc enable future-cycle work + +--- + +## §7 — Phase 5 Implementability Check + +| Field | Result | +| ---------------------------------------------------------------- | ------------------------------------------- | +| Can Phase 5 implement from this specification without ambiguity? | **Yes, with five pre-implementation tasks** | + +### §7.1 — Implementability Pre-Implementation Tasks + +| Pre-Implementation Task | Type | Resolution | +| ------------------------------------------------------------------------------------------------------------ | --------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | +| Exact TypeScript signatures for the 15 methods (return types, parameter type imports) | Implementation detail | Phase 5 reads `BaseDeploymentStrategy.ts` and matches existing signatures; only the interface name changes to `IDeploymentStrategy` | +| JSDoc tag formatting conventions (`@since`, `@param`, `@returns`, `@throws`) | Implementation detail | Phase 5 follows existing TypeScript JSDoc conventions in the Diamonds codebase; MC-07 brief Layer 3 reference doc style guide may inform | +| Conformance test framework choice (Mocha + Chai vs Jest vs Vitest) | Implementation detail | Phase 5 reads existing test setup (per `docs/testing-guide.md`) and continues with the established framework | +| Conformance suite sub-export build configuration (`package.json` `exports` field, separate `tsconfig`, etc.) | Implementation detail | Phase 5 chooses the npm packaging mechanism for the `@diamondslab/diamonds/conformance` sub-export; the design specification states "sub-export," not the packaging mechanism | +| `LoggingDeploymentStrategy` log format (JSON vs key-value vs structured-text) | Implementation detail | Phase 5 chooses based on existing logging patterns in `BaseDeploymentStrategy` (which currently uses `chalk` + `console.log`); the design specification states "structured logs," not a specific format | + +These five items are Phase 5 implementation choices, not design-level decisions. Phase 5 can begin implementation without re-litigating design. + +--- + +## §8 — Forward Handoff Notes + +| Recipient Phase | What This Specification Provides | What Recipient Phase Must Do With It | +| ----------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | +| **Phase 4 (Architecture)** | The contract surface (15 methods, ordering, post-conditions, trust model) anchors the module-boundary discussion for the v2.0 strategies subsystem; the conformance suite sub-export location anchors the package structure | Phase 4 decides: where in the module structure the conformance harness lives; how the sub-export integrates with existing package boundaries; module-boundary changes that flow from the `DeploymentStrategy` → `IDeploymentStrategy` rename | +| **Phase 5 (Implementation)** | The complete design specification: methods, ordering, semantics, security boundaries, conformance scope, worked example shape, rejected alternatives | Phase 5 implements the `IDeploymentStrategy` interface, the JSDoc, the conformance suite (17 tests), `LoggingDeploymentStrategy`, the `examples/logging-strategy/` walkthrough, and the migration doc (jointly with MC-21 brief's migration coverage) | +| **Phase 6 (Testing & Audit)** | The 17 conformance tests are the verification instruments (Step 05 will further refine into Phase 6-executable form); the test execution discipline (12 PR + 5 pre-release) is the gate definition | Phase 6 executes the 17-test suite as part of v2.0 release validation; verifies the conformance suite catches at least the 12 + 5 tests at the appropriate gate; runs the suite against `LocalDeploymentStrategy`, `RPCDeploymentStrategy`, and `LoggingDeploymentStrategy` | + +--- + +## §9 — Cross-Brief References (Detailed) + +See §4 above. Step 04 (Inter-Artifact Coordination) consumes this section to verify bidirectional consistency with other briefs. + +--- + +## §10 — Confidence and Code-Access Notes + +| Field | Value | +| -------------------------------- | ---------------------------------------------- | +| Code-access mode (from Step 00) | Hybrid with explicit flags | +| Code-derived claims flagged with | [CONFIRM] / [AWARE] / [QUESTION] as applicable | +| Overall specification confidence | High | +| Specific low-confidence sections | None | + +**Code references in this specification:** + +- `src/strategies/DeploymentStrategy.ts` [CONFIRM — fetched 2026-05-26] +- `src/strategies/BaseDeploymentStrategy.ts` [CONFIRM — fetched 2026-05-26] +- `src/strategies/LocalDeploymentStrategy.ts` [AWARE — code search result; not separately fetched] +- `src/strategies/RPCDeploymentStrategy.ts` [AWARE — code search result; not separately fetched] +- `src/core/DiamondDeployer.ts` [AWARE — code search result; inferred lifecycle invocation pattern from `BaseDeploymentStrategy.ts`] + +--- + +## Version History + +| Version | Date | Source | Summary | +| ------- | ---------- | -------------------------------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | +| v1.0 | 2026-05-26 | Initial Step 03 production via Sub-Template A (Contract) | 17 specification-level decisions captured across A.1–A.6 (Method Surface 3; Lifecycle Semantics 3; Security Boundaries 2; Conformance Scope 3; Worked Reference Implementation 3; Rejected Alternatives 12 in summary table). Per-artifact principle scorecard: 6 PASS / 0 CONDITIONAL / 0 FAIL. Phase 2 invalidation: No. Phase 5 implementability: Yes with 5 pre-implementation tasks. Phase 5 estimate refinement: 8.0 → 8.7 maint-hrs (~9% increase, ±4 dev-hour band narrowed from ±12). VG-P3-U-02 carryover resolved (diamonds-safe NOT built this cycle; explicitly stated in §2.5). | + +--- + +_Part of the Phase 3 (Existing Projects) Design & Technical Analysis Tool Set — v1.0_ +_AI-Centric Software Development Playbook_ +_Companion file: `design-technical-analysis.existing-project.instructions.md`_ +_Previous step: `step-02-design-brief-triage.prompt.md`_ +_Next brief in Step 03 iteration sequence: MC-21 brief (Refactor sub-template)_ diff --git a/project/AICSDP/p3/step-03-mc-12-design-specification.md b/project/AICSDP/p3/step-03-mc-12-design-specification.md new file mode 100644 index 0000000..81df139 --- /dev/null +++ b/project/AICSDP/p3/step-03-mc-12-design-specification.md @@ -0,0 +1,360 @@ +# Design Specification Artifact — MC-12 brief + +**Brief ID:** MC-12 brief +**Source MC(s):** MC-12 (Publish pipeline + provenance + release-evidence) +**Origin:** Plan §6.4 (primary) +**Primary Artifact Type:** Schema +**Secondary Type:** None +**Specification Date:** 2026-05-26 +**Practitioner:** Solo maintainer (DiamondsLab) +**AI Model:** Claude Opus 4.7 +**Improvement Plan Version:** v1.0 (2026-05-22, no amendments) +**Step 02 Register Reference:** Step 02 §2.4 (MC-12 brief) +**Status:** Draft — Pending Practitioner Final Review + +> ⚠️ This artifact specifies the chosen mechanism at design level. +> It is Phase-5-implementable without further design work. Phase 4 +> architecture decisions, Phase 5 implementation details, and Phase +> 6 verification execution are out of scope. + +--- + +## §1 — Brief Intake Confirmation + +| Field | Value | Confirmed | +| ------------------------------------ | ------------------------------------------------------------------------------------------------------------------------------------------------------- | ------------------------------------ | +| Brief ID | MC-12 brief | Yes | +| Phase 2 chosen mechanism (full text) | "npm `--provenance` + cyclonedx-npm SBOM + lockfile snapshot + release-evidence artifact." (Plan §6.4) | Yes | +| Plan §6.4 design questions | Q1: Release-evidence artifact layout; Q2: SBOM contents required; Q3: Lockfile-snapshot format; Q4: Auditor use-flow | Yes — all four addressed in §2 below | +| Inherited constraints | HC-06 (no external certification required); F-41 (auditor reproducibility) | Yes | +| Verification method named in Plan | Auditor-persona check: fresh AI session given npm URL + GitHub release URL verifies published code matches released source without practitioner support | Yes | +| Artifact type (primary) | Schema — confirmed against Step 02 §2.4 classification | Yes | +| Step 01 §11.1 gap carryover | None | Yes | +| Step 02 §7 carryover | None | Yes | + +--- + +## §2 — Design Specification + +### §2.1 — Artifact Layout + +**Design specification:** + +Each v2.0+ release of `@diamondslab/diamonds` produces an **evidence bundle** consisting of individual files attached to the GitHub Release, accompanied by a manifest file that documents the bundle. The bundle's entry point is the manifest. + +**Files in a v2.0.0 release bundle:** + +| Artifact | Filename | Format | +| ------------------------- | ----------------------------------------- | ----------------------------------------------------------- | +| Manifest | `diamonds-v2.0.0-release-evidence.json` | Custom JSON schema (see §2.1.2) | +| SBOM | `diamonds-v2.0.0-sbom.json` | CycloneDX 1.5 JSON | +| Lockfile | `diamonds-v2.0.0-yarn.lock` | Raw Yarn lockfile (unmodified) | +| npm provenance | `diamonds-v2.0.0-npm-provenance.json` | npm provenance attestation v0.1 | +| Conformance output | `diamonds-v2.0.0-conformance-output.json` | Diamonds conformance schema v1.0 (defined by MC-04 Phase 5) | +| Migration doc (v2.0 only) | `diamonds-v2.0.0-migration-v1-to-v2.md` | Markdown | + +**Naming convention:** `diamonds-v-.` — every filename carries the release version explicitly to prevent cross-release ambiguity when files are downloaded into a common folder. + +**Future releases (v2.x and beyond):** Same six-file shape minus the migration doc (which is v2.0-specific). Future v3.0 would have its own `migration-v2-to-v3.md`. + +#### §2.1.1 — Why files + manifest (not single archive) + +A single archive (tarball or zip) would be opaque to the AI-auditor proxy-reader scenario Plan §6.4 specifies; AI sessions running in chat interfaces typically lack shell access to extract archives, so they couldn't inspect the bundle without practitioner intervention. Individual files + manifest gives the AI auditor: (a) an entry point for discovery (the manifest); (b) per-file integrity verification (the SHA-256 hashes); (c) freedom to fetch only the files relevant to their concern. + +#### §2.1.2 — Manifest schema + +The manifest file (`diamonds-v-release-evidence.json`) follows this schema: + +```json +{ + "schemaVersion": "1.0", + "release": { + "tag": "v2.0.0", + "diamondsVersion": "2.0.0", + "publishedAt": "2026-08-15T12:34:56Z", + "commit": "abc123def456..." + }, + "files": { + "sbom": { + "path": "diamonds-v2.0.0-sbom.json", + "sha256": "...", + "format": "CycloneDX-1.5-JSON" + }, + "lockfile": { + "path": "diamonds-v2.0.0-yarn.lock", + "sha256": "...", + "format": "yarn-lock-v1" + }, + "provenance": { + "path": "diamonds-v2.0.0-npm-provenance.json", + "sha256": "...", + "format": "npm-provenance-attestation-v0.1" + }, + "conformance": { + "path": "diamonds-v2.0.0-conformance-output.json", + "sha256": "...", + "format": "diamonds-conformance-v1.0" + }, + "migrationDoc": { + "path": "diamonds-v2.0.0-migration-v1-to-v2.md", + "sha256": "...", + "format": "markdown" + } + }, + "externalReferences": { + "npmPackage": "https://www.npmjs.com/package/@diamondslab/diamonds/v/2.0.0", + "githubRelease": "https://github.com/DiamondsLab/diamonds/releases/tag/v2.0.0", + "githubCommit": "https://github.com/DiamondsLab/diamonds/commit/abc123..." + }, + "verificationChecks": { + "integrity": "Verify each file's SHA-256 hash matches manifest", + "commitIdentity": "Verify manifest commit, GitHub release commit, and npm provenance commit all match", + "content": "Inspect SBOM, conformance output, and migration doc for content review", + "reproduction": "Optionally run 'yarn install --frozen-lockfile' against the lockfile and verify SBOM consistency" + } +} +``` + +The `schemaVersion` field versions the manifest schema itself; future evolution increments this. The `verificationChecks` field documents the four-spoke auditor flow (per §2.4) inside the manifest for AI-auditor discovery. + +### §2.2 — Format Requirements + +**Format decisions per file:** + +| Evidence file | Format | Rationale | +| ------------------ | --------------------------------------------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------- | +| SBOM | **CycloneDX 1.5 JSON** | Plan §6.4 specifies CycloneDX baseline; `cyclonedx-npm` produces 1.5 JSON by default; JSON is AI-auditor-parseable; XML variant adds nothing | +| Lockfile | **Raw `yarn.lock` (unmodified)** | The lockfile IS the source of truth for Yarn dependency resolution; any derived form would diverge or require additional verification | +| npm provenance | **npm provenance attestation v0.1 JSON** | Format determined by npm's tooling; not a Diamonds choice | +| Conformance output | **Diamonds-specific JSON schema (`diamonds-conformance-v1.0`)** | Defined by MC-04 brief's Phase 5 implementation; MC-12's manifest references it as `files.conformance.format` | +| Migration doc | **Markdown** | Designed in MC-04 §2.1 and MC-21 §2.4 as `examples/migration-v1-to-v2.md` | +| Manifest | **Custom JSON schema** (per §2.1.2) | Diamonds-specific; `schemaVersion: "1.0"` | + +**SBOM extension policy:** **No Diamonds-specific extensions** beyond CycloneDX 1.5 baseline. Pure CycloneDX semantics. Diamonds-specific facts that need surfacing (conformance claims, migration narrative) are carried by other evidence files in the bundle, not by SBOM extensions. + +Rationale: Adding `diamondslab:` namespace properties would only pay weight if there were a downstream consumer using them (none this cycle). HC-06 ("no external certification required") aligns with the minimal-extension posture. A future cycle can add extensions when a real consumer surfaces; v2.0 establishes the baseline. + +### §2.3 — Composition Rules + +**Build-coherence by construction.** The release pipeline (Phase 5 implementation) emits all six files from a single coordinated invocation. Cross-file content consistency is guaranteed at the source (the build), not verified at the destination (the audit). + +**Phase 5 implementation requirement:** The MC-12 release pipeline runs the following steps atomically within a single CI job: + +1. Capture the commit SHA and timestamp +2. Run `cyclonedx-npm` to generate the SBOM from the lockfile +3. Capture the raw `yarn.lock` as-is +4. Run the MC-04 conformance suite to produce conformance output +5. (For v2.0 only) Include the migration doc from the repo +6. Compute SHA-256 hashes for all files +7. Build the manifest with the hashes, commit, timestamp, and external references +8. Upload all files to the GitHub Release atomically + +If any step fails, the release pipeline fails the whole job; no partial bundle is published. + +**Auditor's three mechanical integrity checks (per §2.4):** + +1. **Each file's SHA-256** matches the hash in the manifest's `files..sha256` +2. **The manifest's `release.commit`** matches the GitHub release's commit (visible on the release page) +3. **The npm provenance** (in `files.provenance.path`) attests the same commit + +If all three pass, the bundle's internal consistency is verified. Content review (Spoke C in §2.4) is a separate concern. + +**Lockfile content scope:** **Raw `yarn.lock` only**. The SBOM provides JSON-formatted dependency listing for inspection; the lockfile provides reproduction (`yarn install --frozen-lockfile` against the raw file). Auditors who want to verify SBOM consistency against the lockfile run `yarn install --frozen-lockfile` and compare against the SBOM's dependency list (Spoke D — Reproduction). + +### §2.4 — Consumer Use-Flow + +**Hub-and-spoke auditor flow.** The manifest is the hub; four verification spokes branch from it. + +``` +Hub: Auditor fetches the manifest file (entry point) + │ + ├──► Spoke A — Integrity + │ Verify each file's SHA-256 matches manifest + │ + ├──► Spoke B — CommitIdentity + │ Verify manifest.release.commit = GitHub commit = npm provenance commit + │ + ├──► Spoke C — Content + │ Read SBOM + conformance output + migration doc; structural review + │ + └──► Spoke D — Reproduction (optional) + Run yarn install --frozen-lockfile against lockfile; + verify SBOM consistency +``` + +**Auditor flow specification (for Verification brief's later refinement into auditor-persona prompt):** + +1. **Entry:** Auditor receives the npm URL and GitHub release URL +2. **Discovery:** Auditor fetches the GitHub release page; downloads the manifest file (`diamonds-v-release-evidence.json`) +3. **Spoke selection:** Auditor reviews the manifest's `verificationChecks` field and chooses which spokes to exercise based on their concern (security audit may prioritize Integrity + CommitIdentity; content review may prioritize Content; reproducibility audit may prioritize Reproduction) +4. **Spoke execution:** For each chosen spoke, auditor performs the documented check +5. **Findings:** Auditor produces structured findings — "verified" / "discrepancies found" / "incomplete" per spoke; overall judgment on the bundle + +**Why hub-and-spoke (not linear or decision-tree):** The verification method specifies "fresh AI session" — an AI auditor doing best work needs clear entry + well-defined checks + judgment freedom about prioritization. Linear flow constrains judgment; decision tree is for automated verifiers. Hub-and-spoke matches AI persona's working pattern. + +### §2.5 — Sensitive Data Handling + +**The release-evidence bundle does not carry sensitive data by construction.** + +| Evidence file | Sensitive data exposure | Handling | +| ------------------ | ----------------------------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | +| Manifest | None — file paths, hashes, public URLs, public commit SHA | No special handling | +| SBOM | None — dependency names + versions + hashes are public package metadata | No special handling | +| yarn.lock | None — same as SBOM; resolved versions and integrity hashes are public | No special handling | +| npm provenance | None — provenance attestation is signed by npm for public verification | No special handling | +| Conformance output | Theoretical risk — could contain deployment-record fragments | **Phase 5 implementation note:** Conformance test fixtures use deterministic test addresses (Hardhat default accounts); production deployment data does not enter conformance output | +| Migration doc | None — markdown documentation with placeholder values | **Phase 5 authoring note:** Migration doc's AWS KMS example uses obvious placeholder values (e.g., `arn:aws:kms:us-east-1:123456789012:key/REPLACE-WITH-YOUR-KEY-ID`) to make the placeholder nature unmistakable | + +**No active redaction discipline required** — the bundle's schema does not admit secrets by design. The auditor-persona check does not need to scan for secrets; it verifies content correctness. + +### §2.6 — Rejected Schema Alternatives + +#### Mechanism-level rejected alternatives (from Phase 2 Step 03 §2.4) + +| Alternative | Why rejected | +| ----------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | +| **npm `--provenance` only** | Provides build attestation but not full reproducibility; insufficient for F-41 auditor-reproducibility constraint | +| **npm provenance + SLSA Level 2 certification** | SLSA Level 2 requires hosted-build-platform attestation infrastructure beyond what Diamonds operates; HC-06 explicitly excludes external certification this cycle | +| **npm provenance + Sigstore signed releases** | Adds key-management surface for release signing — practitioner key management is itself a security concern; provenance + SBOM + lockfile achieves the verifiability goal without the additional surface | +| **Release evidence in repo only (no SBOM)** | Reproducibility check possible but no dependency-listing surface for vulnerability scanning; weaker auditor-reproducibility story | + +#### Specification-level rejected alternatives (during this Step 03 design walkthrough) + +| Decision | Alternatives Considered | Selected Option | Why Other Options Rejected | +| --------------------------------- | ----------------------------------------------------------------------------------------------------- | --------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------- | +| Artifact bundling | (i) Single archive; (ii) Individual files; (iii) Files + manifest | **(iii)** | (i) opaque to AI auditor; (ii) leaves "complete set" ambiguous; (iii) manifest provides discovery + integrity | +| Naming convention | (i) Versioned filename pattern; (ii) Short stable names; (iii) Versioned prefix structure | **(i)** | (ii) collision risk across releases; (iii) GitHub Release attachments are flat (no folders); (i) unambiguous | +| Diamonds-specific SBOM extensions | (i) None (pure CycloneDX); (ii) `diamondslab:` namespace properties; (iii) Sibling metadata file | **(i)** | (ii) speculative — no consumer this cycle; (iii) adds file; (i) HC-06 alignment | +| Cross-file integrity | (i) Hash integrity only; (ii) Hash + content consistency check; (iii) Build-coherence by construction | **(iii)** | (i) leaves bundle-level inconsistency possible; (ii) auditor does work that should be release pipeline's; (iii) pipeline is the integrity guarantor | +| Lockfile content scope | (i) Raw yarn.lock only; (ii) Raw + processed JSON; (iii) Processed JSON only | **(i)** | (ii) duplicates SBOM role with two-version sync burden; (iii) loses reproduction property; (i) SBOM provides inspection, lockfile provides reproduction | +| Auditor flow | (i) Linear flow; (ii) Hub-and-spoke; (iii) Decision tree | **(ii)** | (i) constrains AI judgment unnecessarily; (iii) prescriptive for automation, not AI persona; (ii) clear entry + judgment-friendly spokes | +| Sensitive-data handling | (a) Construction-based exclusion + placeholders; (b) Active redaction discipline; (c) No discipline | **(a)** | (b) overkill — bundle doesn't admit secrets by schema design; (c) leaves risk; (a) discipline + placeholders catches the only real-risk file (conformance output) | + +--- + +## §3 — Phase 5 Estimate Refinement + +**No refinement.** Per Step 02 §6, MC-12 refinement was not expected (schema-class brief; narrower uncertainty). Phase 2's 1.6 maint-hrs ESTIMATED holds. + +| Quantity | Phase 2 Estimate | Phase 3 Refined Estimate | Tag | +| ------------------------------------- | -----------------------: | -----------------------: | --------- | +| Dev-hours | ~8 | **~8** (unchanged) | ESTIMATED | +| AI-acceleration multiplier (category) | 5× config edit (blended) | **5× config edit** | BELIEVED | +| Derived maintainer-hours | 1.6 | **1.6** (unchanged) | ESTIMATED | + +Design walkthrough surfaced no scope-changing edge cases. + +--- + +## §4 — Cross-Brief References + +| Related Brief | Relationship | Reference | +| ------------------------- | -------------------------------------------------------------------------------------------------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------- | +| **MC-04 brief** | Conformance output format is defined by MC-04 Phase 5 work; included in this evidence bundle | The manifest's `files.conformance.format = "diamonds-conformance-v1.0"` is a placeholder; MC-04's Phase 5 implementation defines the actual schema | +| **MC-21 brief** | The v2.0 migration doc is included in v2.0's evidence bundle | Migration doc co-authored across MC-04 + MC-21 briefs; evidence bundle includes the result as `diamonds-v2.0.0-migration-v1-to-v2.md` | +| **MC-07 brief (Layer 3)** | Layer 3 reference docs include "how to verify a Diamonds release" documentation that references this evidence bundle | MC-07 Layer 3 doc set will include a release-verification guide referencing this specification | +| **Observability brief** | Will insert touchpoints at the release pipeline (publish flow) | The release pipeline (CI job emitting the bundle) is the operational surface; Observability brief decides what gets observed | +| **Verification brief** | Refines §2.4's hub-and-spoke auditor flow into a concrete auditor-persona prompt | Step 05's Verification Strategy refines the four-spoke flow into actual prompt text | + +--- + +## §5 — Per-Artifact Principle Scorecard Contribution + +| Principle | Weight | Per-Artifact Rating | Rationale | +| ------------------------ | -----: | ------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | +| Security | 1.5× | **PASS** | npm `--provenance` provides build attestation; SBOM provides supply-chain visibility for vulnerability scanning; §2.5 sensitive-data exclusion is by-construction; bundle does not introduce new key-management surface | +| Maintainability | 1.5× | **PASS** | §2.3 build-coherence by construction means release pipeline is the integrity guarantor; §2.6 rejected alternatives documented; manifest schema is versioned (`schemaVersion: "1.0"`) so future evolution is explicit | +| Economics | 1.0× | **PASS** | Phase 2's 1.6 maint-hrs estimate holds; design walkthrough surfaced no scope expansion; §2.6 rejected alternatives removed expensive options | +| Operations | 1.0× | **PASS (baseline)** | Baseline weight preserved; release pipeline is the operational surface; Observability brief will produce touchpoint design for the publish flow | +| Scoring & Metrics | 1.0× | **PASS** | Per-artifact scoring discipline applied; 7 sub-decisions captured with rejected alternatives; cross-file integrity check (3 mechanical checks per §2.3) is the measurable verification surface | +| Correctness Verification | 1.5× | **PASS** | Bundle is _designed_ for the auditor-persona verification method (Plan §6.4); §2.4 hub-and-spoke flow with explicit `verificationChecks` field in the manifest enables AI-auditor discovery; the Verification brief refines into a concrete auditor-persona prompt | + +**Weight-sensitivity flags:** + +- **Highest sensitivity:** Correctness Verification (1.5×) — §2.1.1 (manifest + files architecture) and §2.4 (hub-and-spoke flow with documented checks) are the key decisions; weaker choices would have moved CV to CONDITIONAL +- **Medium sensitivity:** Security (1.5×) — §2.5 sensitive-data handling and §2.3 build-coherence are central +- **Lower sensitivity:** Maintainability, Economics, Operations, Scoring & Metrics — design decisions had limited material effect + +**Below-threshold flags:** None. All six principles at PASS. + +--- + +## §6 — Phase 2 Invalidation Check + +| Field | Result | +| -------------------------------------------------------------- | -------------- | +| Does this specification reveal Phase 2 mechanism invalidation? | **No** | +| If Yes, invalidation report attached | Not applicable | + +Each Plan §6.4 design question received a concrete answer: + +- Q1 (artifact layout) → §2.1: individual files + manifest with versioned naming pattern +- Q2 (SBOM contents) → §2.2: pure CycloneDX 1.5; no Diamonds-specific extensions +- Q3 (lockfile-snapshot format) → §2.3: raw `yarn.lock` only +- Q4 (auditor use-flow) → §2.4: hub-and-spoke flow with manifest as entry point and four documented spokes + +--- + +## §7 — Phase 5 Implementability Check + +| Field | Result | +| ---------------------------------------------------------------- | ---------------------------------------- | +| Can Phase 5 implement from this specification without ambiguity? | **Yes, with 3 pre-implementation tasks** | + +### §7.1 — Phase 5 Pre-Implementation Tasks + +| Pre-Implementation Task | Type | Resolution | +| ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | -------------------------------- | -------------------------------------------------------------------------------------------------------------------------------------- | +| **Release pipeline implementation** — the CI job that runs `cyclonedx-npm`, captures the lockfile, runs the conformance suite, builds the manifest, attaches all files to the GitHub Release atomically | Implementation detail | Phase 5 designs the GitHub Actions workflow (or equivalent); design specification provides the _requirement_ (build-coherent emission) | +| **Conformance output JSON schema definition** | Cross-brief Phase 5 coordination | MC-04's Phase 5 work defines the schema; MC-12's Phase 5 work uses it via `files.conformance.format` | +| **Manifest schema implementation** — TypeScript types or JSON Schema definition for `release-evidence.json`; CI verification | Implementation detail | Phase 5 writes the schema definition from the §2.1.2 specification | + +--- + +## §8 — Forward Handoff Notes + +| Recipient Phase | What This Specification Provides | What Recipient Phase Must Do With It | +| ------------------------------------ | ----------------------------------------------------------------------------------------------------------------------------------------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | +| **Phase 4 (Architecture)** | The release pipeline is a build-coherent emitter; the evidence bundle has a specific six-file shape with naming convention; the manifest is the entry point | Phase 4 considers: where in the build pipeline architecture the SBOM generation, lockfile capture, conformance run, and manifest generation steps live | +| **Phase 5 (Implementation)** | The complete schema spec: manifest fields, file formats, naming conventions, build-coherence requirement, auditor flow documentation | Phase 5 implements the release pipeline; defines the manifest schema as TypeScript types or JSON Schema; coordinates with MC-04's Phase 5 work for the conformance output format | +| **Phase 6 (Testing & Audit)** | The four-spoke auditor flow (Integrity / CommitIdentity / Content / Reproduction) with documented checks; the auditor-persona prompt source material | Phase 6 (refined via Step 05) runs the auditor-persona check against v2.0 release; verifies bundle structure and content correctness | +| **Phase 7 (Deployment & Evolution)** | The release-evidence bundle as the public-facing v2.0 launch artifact; manifest's externalReferences as discovery surface | Phase 7 operates the release process; bundle becomes part of every v2.x release | + +--- + +## §9 — Cross-Brief References (Detailed) + +See §4 above. Step 04 (Inter-Artifact Coordination) consumes this section. + +--- + +## §10 — Confidence and Code-Access Notes + +| Field | Value | +| -------------------------------- | ---------------------------------------------- | +| Code-access mode (from Step 00) | Hybrid with explicit flags | +| Code-derived claims flagged with | [CONFIRM] / [AWARE] / [QUESTION] as applicable | +| Overall specification confidence | High | +| Specific low-confidence sections | None | + +**Code references in this specification:** + +- No direct code reads required (MC-12 is a release-pipeline schema; current Diamonds repo has no MC-12 implementation to fetch — the pipeline is Phase 5 work) +- CycloneDX 1.5 format reference [AWARE — ecosystem standard; not separately verified via Context7 this session] +- npm provenance attestation v0.1 format reference [AWARE — npm's tooling output; not separately verified via Context7 this session] + +--- + +## Version History + +| Version | Date | Source | Summary | +| ------- | ---------- | ------------------------------------------------------ | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | +| v1.0 | 2026-05-26 | Initial Step 03 production via Sub-Template D (Schema) | 7 specification-level decisions captured across D.1 (2), D.2 (1; rest constrained-by-ecosystem), D.3 (2), D.4 (1), D.5 (bundled); 7 specification-level + 4 mechanism-level rejected alternatives in §2.6. Per-artifact principle scorecard: 6 PASS / 0 CONDITIONAL / 0 FAIL. Phase 2 invalidation: No. Phase 5 implementability: Yes with 3 pre-implementation tasks. Phase 5 estimate refinement: No change (Phase 2's 1.6 maint-hrs confirmed). Schema designed around AI-auditor verification method (Plan §6.4); manifest as entry point with hub-and-spoke flow; six-file bundle with versioned naming convention; build-coherent emission. | + +--- + +_Part of the Phase 3 (Existing Projects) Design & Technical Analysis Tool Set — v1.0_ +_AI-Centric Software Development Playbook_ +_Companion file: `design-technical-analysis.existing-project.instructions.md`_ +_Previous step: MC-21 brief Design Specification Artifact_ +_Next brief in Step 03 iteration sequence: MC-07 brief (IA sub-template) — Session 2_ diff --git a/project/AICSDP/p3/step-03-mc-21-design-specification.md b/project/AICSDP/p3/step-03-mc-21-design-specification.md new file mode 100644 index 0000000..2033502 --- /dev/null +++ b/project/AICSDP/p3/step-03-mc-21-design-specification.md @@ -0,0 +1,373 @@ +# Design Specification Artifact — MC-21 brief + +**Brief ID:** MC-21 brief +**Source MC(s):** MC-21 (Private key refactored out of RPCDeploymentStrategy constructor) +**Origin:** Plan §6.2 (primary) +**Primary Artifact Type:** Refactor +**Secondary Type:** None +**Specification Date:** 2026-05-26 +**Practitioner:** Solo maintainer (DiamondsLab) +**AI Model:** Claude Opus 4.7 +**Improvement Plan Version:** v1.0 (2026-05-22, no amendments) +**Step 02 Register Reference:** Step 02 §2.2 (MC-21 brief) +**Status:** Draft — Pending Practitioner Final Review + +> ⚠️ This artifact specifies the chosen mechanism at design level. +> It is Phase-5-implementable without further design work. Phase 4 +> architecture decisions, Phase 5 implementation details, and Phase +> 6 verification execution are out of scope. + +--- + +## §1 — Brief Intake Confirmation + +| Field | Value | Confirmed | +| ------------------------------------------------------------------------------------------ | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | ------------------------------------ | +| Brief ID | MC-21 brief | Yes | +| Phase 2 chosen mechanism (full text) | "Clean break — v2.0 `RPCDeploymentStrategy` constructor takes `signer: Signer` instead of `privateKey`; no shim." (Plan §6.2) | Yes | +| Plan §6.2 design questions | Q1: Exact `Signer` interface signature; Q2: Signer source examples; Q3: Internal-architecture implications; Q4: Interaction with MC-04 contract | Yes — all four addressed in §2 below | +| Inherited constraints | SR-03 (private-key-in-constructor risk); MK-01 (deployment record format unchanged) | Yes | +| Verification method named in Plan | v2.0 constructor type signature accepts no `privateKey`; Signer-injection works with `Wallet`, mock Signer, and one external Signer source; deployment records byte-identical to v1.3.2 for same input | Yes | +| Artifact type (primary) | Refactor — confirmed against Step 02 §2.2 classification | Yes | +| Step 01 §11.1 gap carryover (if any) — resolved | None | Yes | +| Step 02 §7 carryover (VG-P3-U-01 — Phase 2 Step 03 §2 detail missing for MC-21) — resolved | Inferred rejected alternative (deprecation cycle with shim) made explicit in §2.5 Rejected Approaches | Yes | + +--- + +## §2 — Design Specification + +### §2.1 — Pre-Refactor Interface + +**Design specification:** Anchored in `src/strategies/RPCDeploymentStrategy.ts` at v1.3.2. + +| Element | v1.3.2 shape | +| ------------------------------ | ------------------------------------------------------------------------------------------------------------------------------------------------------------------ | +| Class name | `RPCDeploymentStrategy` | +| Constructor signature | `constructor(rpcUrl: string, privateKey: string, gasLimitMultiplier: number = 1.2, maxRetries: number = 3, retryDelayMs: number = 2000, verbose: boolean = false)` | +| Private key validation | `/^0x[a-fA-F0-9]{64}$/` regex in `validateConstructorInputs(...)` | +| Provider construction | `this.provider = new JsonRpcProvider(rpcUrl)` inside constructor body | +| Signer construction | `this.signer = new ethers.Wallet(privateKey, this.provider)` inside constructor body | +| Public methods exposing Signer | `getSigner(): Signer` — already public | +| Configuration exposure | `getConfig()` returns `{ rpcUrl, signerAddress, gasLimitMultiplier, maxRetries, retryDelayMs, verbose }` | + +**v1.3.2 invariants the pre-refactor interface provides:** + +1. **MK-01:** Same deployment config + same network state produces deployment records with the same JSON schema (structure) +2. **Signer identity:** The Signer used for all on-chain calls is derived from the constructor's `privateKey`; single-Signer discipline +3. **RPC connection:** All on-chain calls go through the constructor's `rpcUrl` via the bound Provider +4. **Validation:** Constructor rejects invalid `privateKey` formats, invalid `gasLimitMultiplier` ranges, invalid retry counts, invalid retry delays — fails fast + +**Current consumers (within Diamonds repo; no external adopters per Phase 1 baseline):** + +- Test fixtures in `tests/` +- Example deployment scripts in `examples/` +- Zero production consumers external to Diamonds + +### §2.2 — Post-Refactor Interface + +**Design specification (v2.0):** + +```typescript +class RPCDeploymentStrategy extends BaseDeploymentStrategy { + constructor( + signer: Signer, // ethers Signer abstract type + gasLimitMultiplier: number = 1.2, + maxRetries: number = 3, + retryDelayMs: number = 2000, + verbose: boolean = false, + ); + + getSigner(): Signer; // unchanged + getProvider(): Provider; // base type (was JsonRpcProvider) + getConfig(): { + signerAddress: string; // unchanged (derived from signer.getAddress()) + gasLimitMultiplier: number; + maxRetries: number; + retryDelayMs: number; + verbose: boolean; + // rpcUrl REMOVED + }; + // ... lifecycle methods inherited from BaseDeploymentStrategy (unchanged) +} +``` + +**Constructor changes:** + +| Change | Detail | +| ---------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------- | +| Replace `rpcUrl: string, privateKey: string` | with `signer: Signer` (ethers v6 abstract type) | +| Remove `validateConstructorInputs` rpcUrl check | (no longer needed) | +| Remove `validateConstructorInputs` privateKey regex check | (no longer needed) | +| Add `validateConstructorInputs` signer.provider null check | Throws clear error: "Signer must have a Provider. Did you pass a disconnected Wallet? Use `new ethers.Wallet(privateKey, provider)` or `signer.connect(provider)`." | +| Remove Provider construction (`new JsonRpcProvider(rpcUrl)`) | Provider derived from `signer.provider` | +| Remove Signer construction (`new ethers.Wallet(privateKey, provider)`) | Signer is passed in directly | + +**Internal field changes:** + +- Remove `private rpcUrl: string` +- Remove `private privateKey: string` (was already implicitly removed — the field was a constructor parameter shorthand) +- Keep `private signer: Signer` (assigned from constructor parameter) +- Keep `private provider: Provider` (derived from `signer.provider`) + +**Public accessor changes:** + +- `getSigner(): Signer` — return type unchanged; returns the injected Signer +- `getProvider(): Provider` — return type changed from `JsonRpcProvider` to `Provider` (base type); honestly reflects that any Provider-backed Signer is accepted +- `getConfig()` — drops the `rpcUrl` field entirely; the v2.0 class isn't RPC-URL-driven and the field is misleading + +**Class name decision:** **Keep `RPCDeploymentStrategy`** for v2.0. Renaming a second class on top of MC-21's other changes adds churn for low semantic benefit. The class name reflects its dominant use case (RPC-backed deployments) even though the constructor accepts any Provider-backed Signer. A future cycle could rename if external adopters surface and the framing becomes confusing. + +### §2.3 — Invariants Preserved + +**Three invariants preserved through the refactor:** + +#### Invariant 1: MK-01 structural byte-identity + +> **Statement:** The `deployedDiamondData.json` produced by `RPCDeploymentStrategy` v2.0 has byte-identical _structure_ to v1.3.2 (same JSON keys, same nesting, same field types) for the same `Diamond` configuration. Field _values_ (addresses, tx hashes) differ between deployment instances by definition of on-chain deployment. + +**What's preserved:** + +- Same set of `DeployedFacets` keys (facet names) +- Same field set per facet (`{ address, tx_hash, version, funcSelectors }`) +- Same selector arrays per facet (depend on facet ABI, not Signer identity) +- Same `protocolVersion` field +- Same `DeployerAddress` field name (value will be the new Signer's address; field name preserved) + +**What's not preserved (and isn't expected to be):** + +- `tx_hash` values (deployment-instance-specific) +- `address` values for newly-deployed contracts (nonce-dependent) +- `DeployerAddress` _value_ (different Signer → different address) + +**Verification instrument (refined in Step 05):** A test deploys the same `Diamond` config under v1.3.2 RPCDeploymentStrategy and v2.0 RPCDeploymentStrategy in two separate Hardhat forks; the resulting `deployedDiamondData.json` files are compared by JSON-structure equality (keys, types, array lengths) but not by value equality for address/tx_hash fields. The Phase 6 verification step runs this comparison and reports pass/fail. + +#### Invariant 2: SR-03 closure + +> **Statement:** The v2.0 `RPCDeploymentStrategy` constructor accepts no private key. The caller is responsible for Signer construction (and therefore key management). This closes Phase 1 finding SR-03 by design — the type signature makes it structurally impossible for a private key to enter Diamonds' process memory through this class. + +**Closure mechanism:** + +- **TypeScript type system enforcement** — The constructor parameter type is `Signer` (an abstract class); no string parameter named `privateKey` exists. The type system prevents passing a string-typed private key. +- **JSDoc documentation** — Constructor JSDoc states: _"This strategy never accepts or stores a private key. The caller constructs the Signer (using their preferred key management approach) and passes it to the constructor. This closes Phase 1 finding SR-03 by design — the type signature makes it structurally impossible for a private key to enter Diamonds' process memory through this class."_ +- **MC-04 conformance** — The conformance test suite (per MC-04 brief §2.4) verifies the contract surface; no test in the suite exercises a `privateKey` parameter because none exists. + +**No new CI infrastructure required** — the closure is structural, not test-verified. + +#### Invariant 3: Wallet-equivalent performance + +> **Statement:** When constructed with an `ethers.Wallet`-backed Signer, performance characteristics are equivalent to v1.3.2. With externally-managed Signers (KMS, hardware wallet), per-transaction signing latency may be higher; this is outside the strategy's control and depends on the Signer source's characteristics. + +**Documentation location:** Constructor JSDoc. + +**No benchmark verification** — performance is not the refactor's primary axis; benchmarks would add brittle CI tests for a property the refactor doesn't intend to change. + +### §2.4 — Migration Path + +**Internal landing sequence: atomic single-PR.** + +The full refactor lands in a single v2.0 PR containing: + +- `RPCDeploymentStrategy` class changes (constructor, validation, fields, accessors, JSDoc) +- Test fixture updates throughout `tests/` (mechanical search-and-update for `new RPCDeploymentStrategy(...)` construction sites) +- Example script updates in `examples/` (same mechanical pattern) +- Migration doc co-authored with MC-04 brief (single artifact at `examples/migration-v1-to-v2.md`) +- Co-authored alongside MC-04's `IDeploymentStrategy` rename PR (Step 04 coordination work will formalize the coordinated landing cohort — MC-04 + MC-21 + MC-22 + MC-13 per Plan §5.2) + +**Why atomic landing:** Aligns with MC-21's clean-break discipline (Plan §6.2: "no shim"). No intermediate broken state on the feature branch; CI verifies the full refactor before merge. + +**Consumer migration steps (for external future adopters):** + +| Step | v1.3.2 code | v2.0 code | +| --------------------- | --------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------ | +| 1. Construct Provider | (implicit — strategy constructed it from rpcUrl) | `const provider = new JsonRpcProvider(rpcUrl)` (or other Provider) | +| 2. Construct Signer | (implicit — strategy constructed Wallet from privateKey) | `const signer = new ethers.Wallet(privateKey, provider)` (or KMS Signer, hardware-wallet Signer, etc.) | +| 3. Construct strategy | `new RPCDeploymentStrategy(rpcUrl, privateKey, gasMultiplier, retries, delay, verbose)` | `new RPCDeploymentStrategy(signer, gasMultiplier, retries, delay, verbose)` | + +**Migration doc structure (jointly authored with MC-04 brief; lives at `examples/migration-v1-to-v2.md`):** + +1. **Interface rename** (MC-04 coverage) — `DeploymentStrategy` → `IDeploymentStrategy`; import path updates +2. **Signer injection** (MC-21 coverage) — constructor signature change with rationale (SR-03 closure) +3. **Signer source examples** (MC-21 coverage): + - **`ethers.Wallet`** — the v1.3.2 equivalent. Code example showing private-key-backed Signer construction. + - **Mock Signer for tests** — for Diamonds' own test suite + downstream test suites. Code example. + - **AWS KMS Signer** — the external Signer demonstration. Code example showing KMS configuration + Signer construction + Diamond deployment. Realistic production use case; demonstrates SR-03 closure benefit concretely. + +**Internal-architecture cascade analysis (Plan §6.2 design question 3):** + +Reading of `src/strategies/RPCDeploymentStrategy.ts` and `src/strategies/BaseDeploymentStrategy.ts` reveals: + +1. `privateKey` is referenced in exactly three places within `RPCDeploymentStrategy.ts`: constructor parameter, constructor body's `new ethers.Wallet(privateKey, this.provider)`, and `validateConstructorInputs` regex check. All three are replaced or removed by the refactor. +2. The class does NOT store `privateKey` as a field after construction. +3. Internal code paths use `this.signer` (a `Signer`), not anything privateKey-derived. All operations are `Signer`-interface calls, identical for any `Signer` implementation. +4. `BaseDeploymentStrategy` makes no `privateKey` assumptions; it accesses the Signer via `diamond.getSigner()`. +5. `Diamond.getSigner()` returns whatever Signer the strategy was given; the abstraction is already in place throughout. + +**Conclusion: Internal-architecture cascade is minimal.** The `privateKey` concept is localized to the constructor + `validateConstructorInputs`. Removing it doesn't cascade. The Signer abstraction was already established throughout the codebase. + +**Phase 5 pre-implementation task:** Phase 5 implementation does a final search-and-update pass on test files, example scripts, and any other consumers when the constructor signature changes. The pass is mechanical; compile errors flag every consumer that needs updating. + +**Migration doc work attribution:** The migration doc work is attributed entirely to MC-04 brief's estimate (which captured "migration doc jointly authored with MC-21 brief's migration coverage" in MC-04 §3). For MC-21, the migration coverage is _coordinated_ but not separately _estimated_ — preventing double-counting across briefs. Step 04 Coordination Register will formalize this in the Shared Decisions section. + +### §2.5 — Rejected Approaches + +#### Mechanism-level rejected alternatives (inferred from Plan §6.2 + Phase 2 Step 03 §3.1 dependency table; explicit because Phase 2 Step 03 §2 detail for MC-21 is missing — see VG-P3-U-01) + +| Alternative | Why rejected | +| --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | +| **Deprecation cycle with shim** — v2.0 accepts both old (`rpcUrl, privateKey`) and new (`signer`) constructor signatures, with the old signature emitting a deprecation warning; v3.0 removes the old signature | Diamonds has zero external adopters per Phase 1 baseline; the cost of carrying a shim (code maintenance, documentation burden, deprecation tracking) is non-zero while the user-facing benefit (smoother migration for external adopters) is essentially nil; clean break aligns with v2.0's coherent migration narrative (one v2.0 break covering MC-04 interface rename + MC-21 Signer injection, not multiple deprecation windows) | +| **Additive: keep `privateKey` constructor + add `signer` constructor overload** — Both constructors valid in v2.0+; users choose | Same rationale as above (no external adopters; carrying the additive surface costs maintenance); also weakens the SR-03 closure because a `privateKey`-accepting constructor remains in the API surface | +| **Factory pattern** — Remove the public constructor entirely; replace with `RPCDeploymentStrategy.fromPrivateKey(...)` and `RPCDeploymentStrategy.fromSigner(...)` static factories | Larger surface change than Plan §6.2 specifies; the `fromPrivateKey` factory perpetuates SR-03 in a renamed form; doesn't actually close the finding | + +#### Specification-level rejected alternatives (during this Step 03 design walkthrough) + +| Decision | Alternatives Considered | Selected Option | Why Other Options Rejected | +| -------------------------------------- | ---------------------------------------------------------------------------------------------------------------------- | --------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | +| Signer interface signature | (i) ethers `Signer` as-is; (ii) Diamonds-specific `IDiamondSigner` wrapper; (iii) Structural type | **(i)** | (ii) over-abstraction for zero-external-adopter project; (iii) too low-level for constructor signature; (i) matches Plan §6.2 chosen mechanism and ethers v6 idiom | +| Provider relationship | (i) Provider from Signer; (ii) Constructor takes both; (iii) `rpcUrl` kept | **(i)** | (ii) two-parameter mismatch risk; (iii) `rpcUrl` doesn't generalize to non-RPC Signers (mock, KMS) which Plan §6.2 verification explicitly names | +| Provider absence handling | (i) Validate at construction; (ii) Validate at first use; (iii) TypeScript type narrowing | **(i)** | (ii) defers failure unhelpfully; (iii) imposes type-narrowing burden on callers for marginal benefit; (i) matches existing `validateConstructorInputs` convention | +| `getProvider()` return type | (i) Keep `JsonRpcProvider`; (ii) Return base `Provider`; (iii) Generic over Provider type | **(ii)** | (i) contradicts B.2.2's "any Signer-with-Provider" framing; (iii) over-engineering for negligible benefit; (ii) honestly reflects what the v2.0 class accepts | +| `getConfig().rpcUrl` field | (a) Drop entirely; (b) Best-effort derived; (c) Replace with `providerType` | **(a)** | (b) misleading when Provider isn't `JsonRpcProvider`; (c) adds a field for marginal benefit; (a) honestly reflects that the v2.0 class isn't RPC-URL-driven | +| Class name | Rename to e.g., `SignerDeploymentStrategy`; **Keep `RPCDeploymentStrategy`** | **Keep** | Renaming a second class on top of MC-21's other changes adds churn; class still talks to chains via RPC in the dominant case; existing `RPCStepRecord` / `RPCDeploymentStore` infrastructure aligns with the kept name | +| MK-01 byte-identity interpretation | (i) Byte-identical including addresses; (ii) Structural identity; (iii) Replay-determinism | **(ii)** | (i) unachievable for on-chain (nonce-dependent addresses); (iii) requires deterministic test env that's a higher bar than Plan §6.2 intends; (ii) is the actually-verifiable property | +| SR-03 closure mechanism | (i) JSDoc + code review; (ii) JSDoc + CI grep check; (iii) JSDoc + type system + MC-04 conformance | **(iii)** | (i) too light on enforcement; (ii) brittle CI check; (iii) leverages existing mechanisms (TypeScript types, MC-04 conformance) without new infrastructure | +| Performance characteristics | (i) Wallet-parity claim documented; (ii) No invariant, qualitative documentation; (iii) Benchmark in MC-04 conformance | **(i)** | (ii) loses the "if not changing Signer source, performance unchanged" message; (iii) benchmarks are noisy and verify a non-changing property; (i) sets correct expectations | +| Signer source examples (migration doc) | (i) KMS-backed; (ii) Hardware-wallet (Ledger); (iii) Browser-injected; (iv) Custom abstract mock | **(i)** | (ii) Phase 6 verification needs hardware; (iii) mismatched to deployment scripts; (iv) too abstract; (i) realistic production case with stable library ecosystem (AWS KMS specifically) | +| Internal-architecture verification | (i) Confirmed as analyzed; (ii) Fetch test files to verify; (iii) Defer to Phase 5 pre-implementation task | **(iii)** | (i) leaves Phase 5 less-explicit task surface; (ii) marginal additional confidence at fetch cost; (iii) documents finding + names Phase 5 task | +| Internal landing sequence | (i) Atomic single-PR; (ii) Phased class-first-then-consumers; (iii) Phased tests-first-with-shim | **(i)** | (ii) intermediate broken state on branch; (iii) test shim contradicts clean-break framing; (i) aligns with MC-21's clean-break discipline | +| Migration doc location | (a) Single doc covering MC-04 + MC-21; (b) Two separate docs; (c) Inside MC-07 Layer 3 | **(a)** | (b) fragments the v2.0 migration narrative; (c) couples to MC-07 IA design that doesn't exist yet; (a) standalone artifact that MC-07's IA can reference | + +### §2.6 — Phase 5 Estimate Refinement Outcome + +**No refinement.** Phase 2's estimate of 2.4 maint-hrs ESTIMATED confirmed. + +Design walkthrough surfaced no scope-changing edge cases. The refactor is genuinely localized to `RPCDeploymentStrategy.ts` constructor + `validateConstructorInputs`, with mechanical consumer updates in test/example files. The migration doc work is attributed to MC-04 brief's estimate to prevent double-counting (Step 04 Coordination Register formalizes this). + +| Quantity | Phase 2 Estimate | Phase 3 Refined Estimate | Tag | +| ------------------------------------- | ---------------: | -----------------------: | --------- | +| Dev-hours | 7.2 | **7.2** (unchanged) | ESTIMATED | +| AI-acceleration multiplier (category) | 3× novel-design | **3× novel-design** | BELIEVED | +| Derived maintainer-hours | 2.4 | **2.4** (unchanged) | ESTIMATED | +| Token-count (derived) | ~43K | **~43K** (unchanged) | ESTIMATED | +| Token-cost (derived) | ~$1.08 | **~$1.08** (unchanged) | ESTIMATED | + +--- + +## §3 — Phase 5 Estimate Refinement + +See §2.6 above. Outcome: no refinement to MC-21's estimate; Plan §6.2's central estimate holds. Migration doc work attributed to MC-04 brief. + +--- + +## §4 — Cross-Brief References + +| Related Brief | Relationship | Reference | +| ------------------------- | ----------------------------------------------------------------------------------------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | +| **MC-04 brief** | Provides the contract surface; this refactor's post-state IS the contract; migration doc co-authored | The 15 lifecycle methods in MC-04's contract reflect the post-MC-21 `RPCDeploymentStrategy` interface; the migration doc at `examples/migration-v1-to-v2.md` covers both MC-04 interface rename and MC-21 Signer injection | +| **MC-07 brief (Layer 3)** | Will produce reference docs for secure-key-handling and writing-a-new-strategy that reference this refactor | MC-07 Layer 3 secure-key-handling doc references the Signer-injection patterns; the writing-a-new-strategy doc references the post-refactor constructor pattern | +| **Observability brief** | Will insert touchpoints at the refactored constructor / Signer-use points | The constructor's `signer.provider` validation and the `validateConnection()` flow are natural observability insertion points; the Observability brief decides depth | +| **Verification brief** | Refines the MK-01 structural byte-identity instrument into a Phase 6-executable form | Step 05's Verification Strategy refines the JSON-structure-equality test (test fixture choice, deterministic test environment configuration, comparison predicate) | +| **MC-12 brief** | Release-evidence schema includes the v2.0 migration doc as part of release artifacts | MC-12's release-evidence artifact layout will name what release artifacts get bundled (the migration doc is one of them) | + +--- + +## §5 — Per-Artifact Principle Scorecard Contribution + +| Principle | Weight (Inherited) | Per-Artifact Rating | Rationale | +| ------------------------ | -----------------: | ------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | +| Security | 1.5× | **PASS** | §2.3 SR-03 closure via TypeScript type signature + JSDoc reference + MC-04 conformance — structural guarantee that private key never enters Diamonds' process memory through this class; the type system enforces what the original SR-03 finding asked Phase 2 to address | +| Maintainability | 1.5× | **PASS** | §2.2 post-refactor interface is cleaner than pre-refactor (one parameter `signer: Signer` replaces two parameters `rpcUrl` + `privateKey`); §2.5 rejected approaches documented prevent future-cycle re-litigation; migration doc co-authored with MC-04 produces coherent v2.0 migration narrative; §2.4 internal-architecture analysis showed minimal cascade | +| Economics | 1.0× | **PASS** | §2.6 estimate refinement produced no change; Phase 2's 2.4 maint-hrs estimate confirmed; migration-doc attribution clarified to prevent double-counting in Step 04 coordination work | +| Operations | 1.0× | **PASS (baseline)** | Baseline weight preserved; refactor doesn't change deployment semantics or observability surface; Observability brief will produce touchpoint design for the refactored constructor and Signer-use points | +| Scoring & Metrics | 1.0× | **PASS** | Per-artifact scoring discipline applied (this scorecard); 13 sub-decisions captured with rejected alternatives in §2.5; MK-01 structural identity invariant is the measurable verification surface | +| Correctness Verification | 1.5× | **PASS** | §2.3 MK-01 structural byte-identity is a Phase 6-verifiable invariant; §2.3 SR-03 closure is structurally verified by TypeScript types + MC-04 conformance; the Verification brief (later iteration) will refine these into Phase 6-executable instruments | + +**Weight-sensitivity flags:** + +- **Highest sensitivity:** Security (1.5×) — §2.3 SR-03 closure framing was the central call; without explicit closure documentation, Security could have been CONDITIONAL +- **Medium sensitivity:** Maintainability (1.5×) and Correctness Verification (1.5×) — §2.2 clean-break design and §2.3 MK-01 framing were key calls +- **Lower sensitivity:** Economics, Operations, Scoring & Metrics — design decisions had limited material effect on these principle scores + +**Below-threshold flags:** None. All six principles at PASS. + +--- + +## §6 — Phase 2 Invalidation Check + +| Field | Result | +| -------------------------------------------------------------- | -------------- | +| Does this specification reveal Phase 2 mechanism invalidation? | **No** | +| If Yes, invalidation report attached | Not applicable | + +The Phase 2 chosen mechanism (clean break — v2.0 constructor takes `signer: Signer`; no shim) was specifiable at design level. Each Phase 2 Plan §6.2 design question received a concrete answer: + +- Q1 (exact Signer interface signature) → §2.2: ethers `Signer` abstract class as-is +- Q2 (Signer source examples for migration doc) → §2.4: `Wallet`, mock, AWS KMS +- Q3 (internal-architecture implications) → §2.4: minimal; localized; Phase 5 search-and-update pass for consumers +- Q4 (interaction with MC-04's extension contract) → §4 cross-brief references: contract reflects post-MC-21 interface; coordinated v2.0 landing + +--- + +## §7 — Phase 5 Implementability Check + +| Field | Result | +| ---------------------------------------------------------------- | ---------------------------------------- | +| Can Phase 5 implement from this specification without ambiguity? | **Yes, with 2 pre-implementation tasks** | + +### §7.1 — Phase 5 Pre-Implementation Tasks + +| Pre-Implementation Task | Type | Resolution | +| ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | --------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | +| **Search-and-update consumer files** — every test file and example script that constructs `RPCDeploymentStrategy(rpcUrl, privateKey, ...)` must change to `RPCDeploymentStrategy(new ethers.Wallet(privateKey, new JsonRpcProvider(rpcUrl)), ...)` (or equivalent for non-Wallet sources) | Mechanical task | Phase 5 grep `RPCDeploymentStrategy(` across `tests/` and `examples/` and updates each construction site; §2.4 already established this is mechanical | +| **AWS KMS Signer working example in migration doc** — the AWS KMS code example must be runnable; this requires choosing a specific KMS library (e.g., `aws-kms-ethers-signer` or building a minimal Signer subclass against AWS SDK) and producing a working example | Implementation detail | Phase 5 chooses the library based on current ecosystem state (Context7 lookup at implementation time recommended); the migration doc's KMS section is one of the last pieces to author | + +Both items are appropriately deferred — tactical implementation choices, not design-level decisions. + +--- + +## §8 — Forward Handoff Notes + +| Recipient Phase | What This Specification Provides | What Recipient Phase Must Do With It | +| ----------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | +| **Phase 4 (Architecture)** | The post-refactor constructor signature; the `getProvider(): Provider` base-type accessor; the `getConfig()` field set without `rpcUrl`; the SR-03 closure framing | Phase 4 considers: whether the strategy class's module placement changes given the Signer-injection pattern (likely no — it stays in `src/strategies/`); whether `RPCStepRecord` / `RPCDeploymentStore` module boundary needs adjustment given the class name kept but the RPC framing softened (likely no) | +| **Phase 5 (Implementation)** | The complete v2.0 spec: constructor change, validation rewrite, accessor changes, JSDoc covering SR-03 + performance + trust assumptions; atomic landing sequence; migration doc structure | Phase 5 implements as a single coordinated PR: class changes + test/example updates + migration doc; co-authored with MC-04's brief work; CI verifies on the feature branch before merge | +| **Phase 6 (Testing & Audit)** | The MK-01 structural byte-identity verification instrument (JSON-structure-equality test); the SR-03 closure verification mechanism (TypeScript type system enforcement + MC-04 conformance); Wallet-equivalent performance is documented (not benchmarked) | Phase 6 executes the structural-identity test as part of v2.0 release validation; verifies MC-04 conformance suite passes (which covers the SR-03 closure structurally); reviews the JSDoc documentation for SR-03 + performance claims | + +--- + +## §9 — Cross-Brief References (Detailed) + +See §4 above. Step 04 (Inter-Artifact Coordination) consumes this section to verify bidirectional consistency with other briefs. + +--- + +## §10 — Confidence and Code-Access Notes + +| Field | Value | +| -------------------------------- | ---------------------------------------------- | +| Code-access mode (from Step 00) | Hybrid with explicit flags | +| Code-derived claims flagged with | [CONFIRM] / [AWARE] / [QUESTION] as applicable | +| Overall specification confidence | High | +| Specific low-confidence sections | None | + +**Code references in this specification:** + +- `src/strategies/RPCDeploymentStrategy.ts` [CONFIRM — fetched 2026-05-26 during this Step 03 iteration] +- `src/strategies/BaseDeploymentStrategy.ts` [CONFIRM — fetched 2026-05-26 during MC-04 Step 03 iteration] +- `src/strategies/DeploymentStrategy.ts` [CONFIRM — fetched 2026-05-26 during MC-04 Step 03 iteration] +- Internal consumer count (test files + example scripts) [AWARE — not enumerated by code search; P3-Obs-08 captured the `Github:search_code` "No approval received" friction; Phase 5 search-and-update pass handles enumeration] + +--- + +## Version History + +| Version | Date | Source | Summary | +| ------- | ---------- | -------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | +| v1.0 | 2026-05-26 | Initial Step 03 production via Sub-Template B (Refactor) | 13 specification-level decisions captured across B.2 (4 sub-decisions), B.3 (3), B.4 (3), and B.5 documentation; 12 specification-level + 3 mechanism-level rejected approaches in §2.5. Per-artifact principle scorecard: 6 PASS / 0 CONDITIONAL / 0 FAIL. Phase 2 invalidation: No. Phase 5 implementability: Yes with 2 pre-implementation tasks. Phase 5 estimate refinement: No change (Phase 2's 2.4 maint-hrs confirmed); migration doc work attributed to MC-04 brief to prevent double-counting. VG-P3-U-01 carryover resolved — deprecation-cycle-with-shim explicitly documented as inferred-rejected alternative in §2.5. | + +--- + +_Part of the Phase 3 (Existing Projects) Design & Technical Analysis Tool Set — v1.0_ +_AI-Centric Software Development Playbook_ +_Companion file: `design-technical-analysis.existing-project.instructions.md`_ +_Previous step: MC-04 brief Design Specification Artifact_ +_Next brief in Step 03 iteration sequence: MC-12 brief (Schema sub-template)_ From 4b70fa4a6f33b28672250bd40f238491601a675e Mon Sep 17 00:00:00 2001 From: Am0rfu5 <1178902+Am0rfu5@users.noreply.github.com> Date: Fri, 3 Jul 2026 17:28:19 +0000 Subject: [PATCH 02/28] docs(project): M0-E1 reliable in-container scan invocations - establish reliable in-container commands for audit/semgrep/git-secrets (no yarn findPackageLocation state bug) - record slither (errors: crytic-compile KeyError) + tests best-effort as not-hardened - baseline.md invocations table; read-only, no source/config/hook changed - includes pre-push-security-gates project plan + M0 milestone/epic breakout scaffolding Task 5.0 in tasks-e1-reproduce-gates-in-container.md Co-Authored-By: Claude Opus 4.8 --- .../Milestone-00/Epic-01/CHANGELOG.md | 13 ++ .../e1-reproduce-gates-in-container.md | 42 +++++ .../prd-e1-reproduce-gates-in-container.md | 63 +++++++ .../tasks-e1-reproduce-gates-in-container.md | 43 +++++ .../Epic-02/overview/e2-findings-baseline.md | 45 +++++ .../milestone-01-baseline-and-scan-harness.md | 81 ++++++++ project/pre-push-security-gates/baseline.md | 31 ++++ .../pre-push-security-gates-project-plan.md | 175 ++++++++++++++++++ 8 files changed, 493 insertions(+) create mode 100644 project/pre-push-security-gates/Milestone-00/Epic-01/CHANGELOG.md create mode 100644 project/pre-push-security-gates/Milestone-00/Epic-01/overview/e1-reproduce-gates-in-container.md create mode 100644 project/pre-push-security-gates/Milestone-00/Epic-01/prd-e1-reproduce-gates-in-container.md create mode 100644 project/pre-push-security-gates/Milestone-00/Epic-01/tasks-e1-reproduce-gates-in-container.md create mode 100644 project/pre-push-security-gates/Milestone-00/Epic-02/overview/e2-findings-baseline.md create mode 100644 project/pre-push-security-gates/Milestone-00/overview/milestone-01-baseline-and-scan-harness.md create mode 100644 project/pre-push-security-gates/baseline.md create mode 100644 project/pre-push-security-gates/pre-push-security-gates-project-plan.md diff --git a/project/pre-push-security-gates/Milestone-00/Epic-01/CHANGELOG.md b/project/pre-push-security-gates/Milestone-00/Epic-01/CHANGELOG.md new file mode 100644 index 0000000..1b491e5 --- /dev/null +++ b/project/pre-push-security-gates/Milestone-00/Epic-01/CHANGELOG.md @@ -0,0 +1,13 @@ +# Changelog — M0-E1 Reproduce Gates In-Container + +## 2026-07-03 — Reliable in-container invocations established (read-only) + +- Ran every `.husky/pre-push` gate in the devcontainer and recorded a **reliable invocation** for each *remaining* gate into [`baseline.md`](../../baseline.md): + - **npm audit** — `yarn npm audit --severity moderate` runs cleanly (exit 1 = the 2 lodash findings, **not** a tooling failure); no `findPackageLocation` state error. + - **semgrep** — `semgrep scan --config .semgrep.yml --exclude-rule weak-encryption` runs cleanly (exit 0, 10 findings; the `--error` flag is what makes findings blocking). + - **git-secrets** — `git secrets --scan` clean (exit 0). +- Recorded **best-effort** (not hardened) current behavior: + - **slither** — `slither . --config-file slither.config.json --ignore-compile` **errors** (crytic-compile `KeyError: 'output'`); does not run cleanly in-container → evidence for the **M3** decommission. + - **tests** — `yarn test` trips the yarn state bug; alt `npx hardhat test`; known 51/0. Tests **leave the gate in M4**. +- **No source, config, or hook changed** — the only new file is `baseline.md` (plus the project planning docs from the pipeline). The pre-existing `yarn.lock` change is unrelated and excluded from the commit. +- **Follow-up:** M0-E2 appends the *findings* and *tooling-repo rationale* sections to the same `baseline.md`. diff --git a/project/pre-push-security-gates/Milestone-00/Epic-01/overview/e1-reproduce-gates-in-container.md b/project/pre-push-security-gates/Milestone-00/Epic-01/overview/e1-reproduce-gates-in-container.md new file mode 100644 index 0000000..4c8b486 --- /dev/null +++ b/project/pre-push-security-gates/Milestone-00/Epic-01/overview/e1-reproduce-gates-in-container.md @@ -0,0 +1,42 @@ +# Epic 1 — Reproduce Gates In-Container (M0-E1) + +> **Parent milestone:** [Milestone 1 — Baseline & Reliable Scan Harness (M0)](../../overview/milestone-01-baseline-and-scan-harness.md) · **Maps to:** [`pre-push-security-gates-project-plan.md`](../../../pre-push-security-gates-project-plan.md) §5 M0 → M0-E1 +> **Owner:** Engineer · **Impact/blast radius:** read-only; no source/config/hook change · **Estimated effort:** S · **Status:** 📋 planned + +## 1. Objective +Establish a **reliable, repeatable way to run each pre-push gate inside the devcontainer** that does **not** trip the yarn `findPackageLocation` state-file bug (which makes the hook's `yarn