From c667dbbf4a861c00148ed77e87526d5d3369380d Mon Sep 17 00:00:00 2001 From: "sam-cloud-app[bot]" <252427705+sam-cloud-app[bot]@users.noreply.github.com> Date: Sat, 16 May 2026 10:35:16 +0000 Subject: [PATCH 01/11] =?UTF-8?q?Add=20PRD=20for=20issue=20#16:=20Workflow?= =?UTF-8?q?:=20replan=20=E2=80=94=20handle=20requirement=20changes=20mid-b?= =?UTF-8?q?uild?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- _sam-output/issues/16/prd.md | 400 +++++++++++++++++++++++++++++++++++ 1 file changed, 400 insertions(+) create mode 100644 _sam-output/issues/16/prd.md diff --git a/_sam-output/issues/16/prd.md b/_sam-output/issues/16/prd.md new file mode 100644 index 0000000..721538f --- /dev/null +++ b/_sam-output/issues/16/prd.md @@ -0,0 +1,400 @@ +# PRD: Workflow: replan — handle requirement changes mid-build + +> **Issue:** #16 +> **Repository:** sam-agents/sam +> **Generated:** 2026-05-16T10:35:16.967Z +> **Type:** feature +> **Priority:** medium +> **Labels:** feature, workflow, enhancement, complex + +--- + +## Overview + +Implement 'sam-replan' workflow to handle mid-build requirement changes + +## Original Request + +## Problem + +Today's workflows handle the linear happy path (`plan` → `build-tdd` → done) and additive iteration after v1 (`extend`), but do **not** handle requirement changes that occur mid-build or that modify/remove existing functionality. + +## Scenarios we cannot handle today + +| Scenario | Current outcome | +|---|---| +| Mid-build: a requirement changes (e.g. \"title max should be 100 not 200\", stories 2–3 done) | No workflow. `plan --force` wipes everything including done stories. Manual edit is the only option. | +| Mid-build: a feature is added | Awkward. `extend` is designed for post-v1, not mid-build. | +| Feature removal (\"drop tags entirely\") | No workflow. User manually edits files. No deprecation lifecycle. | +| Bug fix in done work | Partial — user can re-invoke `build-tdd` on one story, but there is no formal `fix` workflow framing it. | +| Tech-stack pivot | No workflow. Effectively `plan --force` rebuild from scratch. | + +## Proposed shape: `sam-replan` + +``` +sam-replan +``` + +Pipeline: + +1. **Diff** — compare revised PRD against current `prd.md`. Categorize each change: added / modified / removed / unchanged. +2. **Impact analysis** — for each modified or removed item, walk the `produces` / `consumes` graph from the existing contracts and stories to identify affected artifacts. +3. **Per-category action** — + - Added → behave like `extend` (new contracts + stories appended) + - Modified, story not yet built → update story file in place; if a contract changes, bump version + - Modified, story done → bump contract version, mark story `needs-rebuild`, keep code as-is until user confirms rebuild + - Removed → mark story `obsolete`, deprecate the contract, do **not** delete code automatically +4. **Impact summary as a gate** — show the user what will change before doing anything (\"you're about to invalidate 4 done stories — confirm?\"). +5. **Merge revised PRD** into `prd.md` with a change-log entry (reuse Phase 4 from `extend`). + +## Why this is tractable now + +Contracts-first design from v0.8.0 already gives us the dependency graph: every story declares its `produces` and `consumes` contracts. `replan` walks that graph to compute impact. The hard problem (which artifacts are affected by a given PRD change) is already half-solved. + +## Acceptance criteria + +- New workflow registered in `_sam/_config/workflow-manifest.csv` and `bin/cli.js` +- Story status lifecycle gains `needs-rebuild` and `obsolete` +- Contract lifecycle gains `deprecated` +- Diff + impact summary printed before any file is touched +- Tested on a real iteration scenario (e.g. modify the sam26 todo PRD mid-build) + +## Out of scope + +- Automatic code deletion when features are removed (defer to user) +- Automatic dependency-graph repair when contracts diverge — keep it explicit + +--- + +## 🎯 Implementation Plan + +### Summary +Implement the `sam-replan` workflow — a 5-step pipeline that diffs a revised PRD against the current one, computes impact on existing contracts/stories, and surgically updates artifacts while preserving done work. This requires new story statuses (`needs-rebuild`, `obsolete`), a new contract status (`deprecated` already exists), and an interactive impact-summary gate. + +--- + +### Tasks + +- [ ] **Task 1: Add `needs-rebuild` and `obsolete` to the story status lifecycle** + - Edit `_sam/core/resources/story-schema.md` to add `needs-rebuild` and `obsolete` to the `status` enum and transition rules + - `needs-rebuild`: a done story whose contract changed; code is kept but story must be re-built when user confirms + - `obsolete`: a story whose feature was removed from the PRD; code is not deleted but story is retired + - Add transition rules: `done → needs-rebuild`, `done → obsolete`, `ready → obsolete`, `in-progress → obsolete`, `needs-rebuild → in-progress` (when user confirms rebuild) + - **Files:** `_sam/core/resources/story-schema.md` + - **Acceptance:** Schema doc lists both new statuses with clear transition rules; existing statuses unchanged + +- [ ] **Task 2: Document the `deprecated` contract status in contract-schema.md** + - `deprecated` already exists in contract-schema.md — verify it has clear lifecycle guidance for the replan use case + - Add a "Replan lifecycle" subsection under Field rules → `status` explaining that replan may set `deprecated` when a feature is removed, and that `deprecated` contracts are not deleted + - **Files:** `_sam/core/resources/contract-schema.md` + - **Acceptance:** Contract schema documents how `deprecated` is used during replan; no new status values needed + +- [ ] **Task 3: Create the `replan` workflow directory and `workflow.md`** + - Create `_sam/core/workflows/replan/workflow.md` following the `extend` pattern + - Frontmatter: `name: replan`, `description`, `version: 1.0.0` + - Sections: Goal, Your Role, INPUTS (revised PRD path), Required preconditions (same as extend: sdocs/ must exist with at least one story), Optional flags (`--force`), OUTPUTS (modified sdocs/ tree + impact summary), Phase overview (5 phases listed below) + - Define output structure including `sdocs/replans/--analysis.md` for impact archive + - **Files:** `_sam/core/workflows/replan/workflow.md` + - **Acceptance:** workflow.md is valid, follows extend's structure, documents all 5 phases at a high level + +- [ ] **Task 4: Write Step 1 — Diff revised PRD against current PRD** + - Create `_sam/core/workflows/replan/steps/step-01-diff-prd.md` + - Agent: `architect` (Atlas) + - Purpose: Compare revised PRD against `sdocs/prd.md`, categorize each requirement as `added | modified | removed | unchanged` + - Entry conditions: revised PRD file exists, `sdocs/prd.md` exists + - Required reading: both PRDs, `sdocs/architecture-ref.md` + - Process: section-by-section comparison, produce a structured diff summary + - Output: `sdocs/replans/--diff.md` with categorized changes + - Gate: every PRD section classified; no unclassified sections remain + - **Files:** `_sam/core/workflows/replan/steps/step-01-diff-prd.md` + - **Acceptance:** Step file follows build-tdd/extend step anatomy (frontmatter, entry conditions, required reading, process, gate conditions, failure modes, next step) + +- [ ] **Task 5: Write Step 2 — Impact analysis on contracts and stories** + - Create `_sam/core/workflows/replan/steps/step-02-impact-analysis.md` + - Agent: `architect` + - Purpose: For each `modified` or `removed` item from Step 1, walk the `produces`/`consumes` graph to identify affected contracts and stories + - Required reading: `sdocs/contracts/INDEX.md`, all story files, diff output from Step 1 + - Process: for each changed requirement, find contracts that implement it (via story `produces`), then find downstream consumers; classify each affected artifact with its current status (done, ready, in-progress, etc.) + - Output: append impact matrix to `sdocs/replans/--analysis.md` + - Gate: every modified/removed requirement has at least one mapped artifact or explicit "no impact" note + - **Files:** `_sam/core/workflows/replan/steps/step-02-impact-analysis.md` + - **Acceptance:** Step file documents the graph-walking algorithm; output format for the impact matrix is specified + +- [ ] **Task 6: Write Step 3 — Impact summary gate (user confirmation)** + - Create `_sam/core/workflows/replan/steps/step-03-impact-gate.md` + - Agent: `architect` + - Purpose: Present the impact summary to the user and require explicit confirmation before making changes + - Process: format the impact matrix as a human-readable summary (X stories affected, Y contracts to update, Z stories to mark obsolete, W done stories to mark needs-rebuild); ask user to confirm or abort + - Gate: user confirms `proceed` — if user aborts, halt workflow cleanly with no file modifications + - **Files:** `_sam/core/workflows/replan/steps/step-03-impact-gate.md` + - **Acceptance:** Step halts without side effects if user declines; confirmation is explicit (not implicit) + +- [ ] **Task 7: Write Step 4 — Apply per-category changes to contracts and stories** + - Create `_sam/core/workflows/replan/steps/step-04-apply-changes.md` + - Agent: `architect` + - Purpose: Execute the actual artifact changes based on the confirmed impact analysis + - Per-category actions: + - **Added** → behave like `extend` (new contracts at `draft`, new stories at `ready`, append to epics) + - **Modified, story not yet built** → update story file in place; bump contract version if contract changes + - **Modified, story done** → bump contract version, set story status to `needs-rebuild`, preserve existing code + - **Removed** → set story status to `obsolete`, set contract status to `deprecated`, do NOT delete files + - Gate: all affected artifacts updated; no contract left without an owner; `depends_on` graph remains acyclic; INDEX.md updated + - **Files:** `_sam/core/workflows/replan/steps/step-04-apply-changes.md` + - **Acceptance:** Each of the 4 categories has explicit, detailed instructions; gate conditions are checklistable + +- [ ] **Task 8: Write Step 5 — Merge revised PRD with changelog** + - Create `_sam/core/workflows/replan/steps/step-05-merge-prd.md` + - Agent: `architect` + - Purpose: Merge the revised PRD into `sdocs/prd.md` with a changelog entry + - Reuse the pattern from `extend` Phase 4 (`step-04-merge-prd.md`) — read it for reference + - Process: update affected sections in the PRD body, bump `version` in frontmatter, append to `## Change log` with date + summary of what changed and why + - Archive the revised PRD input to `sdocs/replans/--revised-prd.md` + - Gate: PRD version strictly greater than previous; changelog entry present; pre-existing unchanged content preserved + - **Files:** `_sam/core/workflows/replan/steps/step-05-merge-prd.md` + - **Acceptance:** Step follows extend's merge-prd pattern; changelog format is consistent + +- [ ] **Task 9: Register `replan` in workflow-manifest.csv** + - Add row to `_sam/_config/workflow-manifest.csv`: `"replan","SAM Replan Workflow - Handle mid-build requirement changes by diffing revised PRD, computing impact, and surgically updating contracts and stories without destroying done work.","core","_sam/core/workflows/replan/workflow.md"` + - **Files:** `_sam/_config/workflow-manifest.csv` + - **Acceptance:** `npm test` (verify-manifest) passes with the new row + +- [ ] **Task 10: Register `replan` in `bin/cli.js` WORKFLOWS array** + - Add a new entry to the `WORKFLOWS` array (after `extend`): `{ name: 'replan', file: 'core/workflows/replan/workflow.md', display: 'SAM Replan Workflow', description: '...' }` + - This automatically gets picked up by `generateCursorRules`, `generateClaudeCommands`, `generateGeminiSkills`, `generateCopilotSkills`, and `generateAntigravitySkills` since they iterate over `WORKFLOWS` + - **Files:** `bin/cli.js` + - **Acceptance:** `node bin/cli.js --platform all ./test-project` generates replan skills for all platforms + +- [ ] **Task 11: Run `sync-templates` and verify** + - Run `npm run sync-templates` to mirror `_sam/` → `templates/_sam/` + - Run `npm test` to confirm verify-sync, verify-manifest, and verify-gemini all pass + - Smoke-test with `node bin/cli.js --platform all ./test-project` and confirm replan skill files appear + - **Files:** `templates/_sam/core/workflows/replan/` (generated), `templates/_sam/_config/workflow-manifest.csv` (generated) + - **Acceptance:** `npm test` passes; replan workflow files exist in `templates/`; platform skill files generated for all 5 platforms + +--- + +### Technical Considerations +- **Extend is the closest analog** — replan's steps 4 and 5 heavily mirror extend's steps 2–4. Reference extend's step files when writing replan steps. +- **The `produces`/`consumes` graph is the key data structure** — Step 2 (impact analysis) depends on walking this graph. The graph already exists in story frontmatter; no new infrastructure is needed. +- **No code deletion** — the issue explicitly scopes out automatic code deletion. `obsolete` stories and `deprecated` contracts keep their files intact. +- **`needs-rebuild` is a user-driven gate** — marking a story `needs-rebuild` does NOT trigger an automatic rebuild. The user must explicitly invoke `build-tdd` on that story, which reads the status and proceeds. +- **Idempotency** — archive the revised PRD and diff in `sdocs/replans/` so repeated invocations can detect prior runs (same pattern as extend's `sdocs/addenda/`). +- **Step file anatomy** must include: frontmatter, agent, purpose, entry conditions, required reading, process, gate conditions, failure modes, next step — match existing step files exactly. + +### Dependencies +- Requires familiarity with the `extend` workflow (read all 4 step files as reference before starting) +- Tasks 1–2 (schema changes) should be done before Tasks 4–8 (step files reference the new statuses) +- Task 3 (workflow.md) should be done before Tasks 4–8 (step files reference the phase overview) +- Tasks 9–10 (registration) can be done in parallel with step file writing +- Task 11 (sync + verify) must be last + +### Estimated Complexity +**Medium** — No runtime code to write (this is a template-generation tool). All deliverables are markdown workflow definitions following well-established patterns. The intellectual complexity is in the impact-analysis algorithm design (Step 2) and the per-category mutation rules (Step 4), but the implementation is documentation, not code. + +--- +*🏷️ Add label `ready-for-dev` when ready for implementation* + +--- + +## 🏗️ Architecture Review + +### Overview + +The `replan` workflow is a 5-phase pipeline that diffs a revised PRD against the current one, computes impact via the `produces`/`consumes` contract graph, and surgically updates stories and contracts — introducing two new story statuses (`needs-rebuild`, `obsolete`) and leveraging the existing `deprecated` contract status. The implementation plan proposes 11 tasks, all markdown template files plus two registration points (`workflow-manifest.csv` and `bin/cli.js`). No runtime code changes. + +### Component Design + +``` + ┌──────────────────────┐ + │ Revised PRD (input) │ + └──────────┬───────────┘ + │ + ┌────────────────▼───────────────┐ + │ Step 1: Diff PRD │ + │ Agent: Atlas │ + │ In: revised-prd + sdocs/prd.md │ + │ Out: categorized diff │ + │ (added/modified/removed/ │ + │ unchanged) │ + └────────────────┬───────────────┘ + │ + ┌────────────────▼───────────────┐ + │ Step 2: Impact Analysis │ + │ Agent: Atlas │ + │ In: diff + contracts/INDEX.md │ + │ + all stories │ + │ Out: impact matrix │ + │ (walks produces/consumes DAG) │ + └────────────────┬───────────────┘ + │ + ┌────────────────▼───────────────┐ + │ Step 3: Impact Gate │ + │ Agent: Atlas │ + │ In: impact matrix │ + │ Out: user confirms / aborts │ + │ ⚠️ NO FILE WRITES BEFORE THIS │ + └────────────────┬───────────────┘ + │ (user confirms) + ┌────────────────▼───────────────┐ + │ Step 4: Apply Changes │ + │ Agent: Atlas │ + │ Per-category mutations: │ + │ • added → new contracts+stories│ + │ • modified (not built) → update │ + │ • modified (done) → needs-rebuild│ + │ • removed → obsolete/deprecated │ + └────────────────┬───────────────┘ + │ + ┌────────────────▼───────────────┐ + │ Step 5: Merge PRD │ + │ Agent: Atlas │ + │ In: revised PRD + live PRD │ + │ Out: updated prd.md + changelog│ + │ (mirrors extend step-04) │ + └────────────────┬───────────────┘ + │ + ┌──────────▼───────────┐ + │ sdocs/replans/ │ + │ (audit trail) │ + └──────────────────────┘ +``` + +### Data Model + +**Story status lifecycle — proposed additions:** + +``` + ┌─────────┐ + │ draft │ + └────┬────┘ + │ + ┌────▼────┐ + ┌─────│ ready │─────────────┐ + │ └────┬────┘ │ + │ │ │ + │ ┌────▼──────┐ │ + │ │in-progress│───┐ │ + │ └───────────┘ │ │ + │ │ │ + │ ┌──────▼──────┐ │ + │ │ done │ │ + │ └──┬─────┬───┘ │ + │ │ │ │ + │ ┌────────▼┐ ┌─▼──────────┐ + │ │needs- │ │ obsolete │◄──┤ + │ │rebuild │ └─────────────┘ │ + │ └────┬────┘ │ + │ │ │ + │ ┌────▼──────┐ │ + │ │in-progress│ (user confirms) │ + │ └───────────┘ │ + │ │ + └──────► obsolete ◄─────────────────┘ + (any non-done status → obsolete) + + ┌─────────┐ + │ blocked │ (any → blocked, unchanged) + └─────────┘ +``` + +**Contract status lifecycle — no new values needed:** + +``` + draft → stable → deprecated + (replan sets this on removal) +``` + +**New artifact directory:** + +``` +sdocs/replans/ + --diff.md # Step 1 output + --analysis.md # Step 2 output (impact matrix) + --revised-prd.md # Input archive (Step 5) +``` + +### Technical Decisions + +| Decision | Choice | Rationale | +|----------|--------|-----------| +| All 5 steps use Atlas | Single agent | All phases are architectural reasoning (diff, impact, mutation rules). No code is written, so Titan/Dyna/Argus are irrelevant. Matches `extend` which also uses Atlas for all 4 steps. | +| `needs-rebuild` as status, not flag | Story `status` field | Consistent with existing pattern: status is the single source of truth for resume. A separate flag would create dual-state ambiguity. | +| No automatic code deletion | Explicit out-of-scope | Correct — agents should never silently delete user code. `obsolete` marks intent; user acts on it. | +| Audit trail in `sdocs/replans/` | Mirrors `sdocs/addenda/` from extend | Enables idempotency detection and provides decision history. Consistent pattern. | +| Gate before file writes (Step 3) | Interactive confirmation | High-blast-radius operation — mutating done stories is irreversible in workflow terms. Gate is essential. | +| Reuse extend's merge-PRD pattern | Step 5 mirrors extend step-04 | Proven pattern, avoids divergence. PRD merge logic shouldn't differ by workflow. | + +### Risk Assessment + +**High Risk:** + +- **Step 2's "requirement → contract" mapping is under-specified.** The diff in Step 1 produces _PRD-level_ changes (sections, requirements). Step 2 must map those to _contracts_. But contracts aren't tagged with which PRD requirement they implement — they're tagged with an `owner_story`, and stories are tagged with ACs from the PRD. The mapping is `PRD requirement → story ACs → story → produces → contract`. This multi-hop walk is the hardest part of the workflow and the plan doesn't detail how the agent should resolve ambiguous mappings (e.g., a PRD section that maps to 3 stories producing 5 contracts). **Recommendation:** Step 2 should include explicit heuristics for this mapping — e.g., keyword matching between PRD section titles and story titles, or requiring the user to annotate which requirements changed. + +**Medium Risk:** + +- **`needs-rebuild` → `in-progress` transition needs a trigger mechanism.** The plan says the user "must explicitly invoke `build-tdd`" on a `needs-rebuild` story, but `build-tdd`'s entry condition today checks for `status: ready` or `status: in-progress`. It will reject `needs-rebuild` unless we also update `build-tdd`'s entry conditions. **Recommendation:** Add a note in Task 1 that `build-tdd` step-01-red.md entry conditions must accept `needs-rebuild` as a valid starting status (treating it like `ready`), or document that the user must manually set status to `in-progress` first. I'd favor the former — adding `needs-rebuild` to build-tdd's accepted statuses is cleaner. + +- **Contract version bumping on "modified, done" stories.** Step 4 says to bump the contract version when a done story's requirement changes. But version bumps can cascade — any story that `consumes` that contract at the old version may also need attention. The impact analysis in Step 2 should flag these transitive consumers, but Step 4's instructions should explicitly handle the cascade (mark downstream consumers as `needs-rebuild` too, or at minimum flag them in the output). + +- **Ordering of Steps 4 and 5.** Step 4 modifies stories/contracts, Step 5 merges the PRD. If Step 4 fails mid-way (e.g., agent hits a complex case), we have partially-mutated artifacts but the PRD still reflects the old state. Consider whether Step 5 should run first (merge PRD as the source of truth) and Step 4 second (mutate artifacts to match). Counter-argument: the current order lets the user see artifact changes before the PRD is locked in. I'd keep the current order but add a rollback note to Step 4's failure modes. + +**Low Risk:** + +- **`obsolete` stories still appear in `depends_on` chains.** If STORY-003 is marked `obsolete` but STORY-005 has `depends_on: [STORY-003]`, the DAG is now semantically broken (depending on retired work). Step 4 should address this — either remove obsolete stories from downstream `depends_on` lists or document that `obsolete` stories are treated as `done` for dependency purposes. + +- **Duplicate replan runs.** If the user runs `replan` twice with similar PRDs, the idempotency check (detecting prior runs in `sdocs/replans/`) isn't detailed. The plan mentions it but doesn't specify behavior. Should be documented in Step 1. + +### Implementation Notes + +- **Read all 4 extend step files before writing any replan step.** The plan says this but it bears emphasis — the extend steps are the structural template. Match their section ordering exactly: frontmatter → purpose → entry conditions → required reading → process → gate conditions → failure modes → next step. + +- **Step file frontmatter pattern** from build-tdd: + ```yaml + --- + step: 1 + name: diff-prd + description: Compare revised PRD against current PRD and categorize changes + agents: [architect] + --- + ``` + +- **The `sdocs/replans/` directory parallels `sdocs/addenda/`** from extend. Use the same naming convention: `--.md`. + +- **For Task 10 (cli.js registration):** the entry goes after `extend` in the WORKFLOWS array. The shape is: + ```js + { + name: 'replan', + file: 'core/workflows/replan/workflow.md', + display: 'SAM Replan Workflow', + description: 'Handle mid-build requirement changes...' + } + ``` + +- **For Task 9 (manifest):** match the CSV quoting style exactly — all four fields double-quoted, no trailing newline issues. + +- **`blocked` status transitions are unchanged** — any status can transition to `blocked`. The plan correctly doesn't touch this. + +- **Step 4 is the most complex step file** — it has 4 distinct sub-algorithms (one per category). Structure it with clear H3 subheadings for each category to keep it scannable. + +### Questions for Stakeholder + +1. **`needs-rebuild` and `build-tdd` integration:** Should `build-tdd` step-01-red accept `needs-rebuild` as a valid entry status? The plan is silent on this. If not, the user must manually edit story status before rebuilding, which adds friction. + +2. **Transitive impact cascading:** When a done story is marked `needs-rebuild` due to a contract version bump, should its downstream consumers (stories that `consumes` the same contract) also be flagged? The issue description doesn't address transitive impact explicitly. + +3. **`--force` flag mentioned in Task 3 workflow.md:** What should `--force` do — skip the impact gate (Step 3)? This should be documented but I'd recommend against implementing it in v1, since the gate is the primary safety mechanism. + +--- + +*🏗️ Architecture review complete. The plan is sound and well-structured — the extend workflow provides a proven template. The primary risk is the PRD-to-contract mapping heuristic in Step 2, which needs more specificity. The `needs-rebuild` integration with `build-tdd` is a small but important gap to close. Ready for implementation after addressing the high-risk item.* + +--- + +## Notes + +- Target Directory: `/tmp/sam-repos/sam-agents/sam` +- Tech Stack: JavaScript + +--- + +*🤖 Generated by Tara 🎯 (Triage) → Pete 📋 (Planning) → Alex 🏗️ (Architecture)* From 744d8fd6c0d0066063c1065754149dd49e3cef7a Mon Sep 17 00:00:00 2001 From: "sam-cloud-app[bot]" <252427705+sam-cloud-app[bot]@users.noreply.github.com> Date: Sat, 16 May 2026 10:38:07 +0000 Subject: [PATCH 02/11] Task 1/11: Add `needs-rebuild` and `obsolete` to the story status lifecycle MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - Add `needs-rebuild` and `obsolete` to the status enum in story-schema.md - Add transition rules: done→needs-rebuild, needs-rebuild→in-progress, done→obsolete, ready→obsolete, in-progress→obsolete - Add verify-story-schema.js to validate statuses and transitions - Register verification script in npm test suite Co-Authored-By: Claude Opus 4.6 (1M context) --- _sam/core/resources/story-schema.md | 7 +- package.json | 3 +- scripts/verify-story-schema.js | 78 +++++++++++++++++++ templates/_sam/core/resources/story-schema.md | 7 +- 4 files changed, 92 insertions(+), 3 deletions(-) create mode 100644 scripts/verify-story-schema.js diff --git a/_sam/core/resources/story-schema.md b/_sam/core/resources/story-schema.md index d7ed126..2a73f4e 100644 --- a/_sam/core/resources/story-schema.md +++ b/_sam/core/resources/story-schema.md @@ -31,7 +31,7 @@ id: STORY-003 # stable identifier; never renumber epic: EPIC-001 # parent epic id (or null for ad-hoc stories) kind: feature # feature | integration | scaffolding title: User can reset password # one-line summary, no trailing period -status: ready # draft | ready | in-progress | done | blocked +status: ready # draft | ready | in-progress | done | blocked | needs-rebuild | obsolete priority: P1 # P0 (critical) | P1 (normal) | P2 (nice-to-have) prd: ../../prd.md # relative path from this file to the source PRD (or null) depends_on: [STORY-001] # list of story ids that must be `done` first; [] if none @@ -52,6 +52,11 @@ created: 2026-05-13 # YYYY-MM-DD; never changes after creation - `ready` → `in-progress` (when `build-tdd` picks it up) - `in-progress` → `done` (when `build-tdd` completes all phases) - any → `blocked` (when retry limit hit; include reason in body) + - `done` → `needs-rebuild` (when a contract this story produces has changed; code is kept but story must be re-built when user confirms) + - `needs-rebuild` → `in-progress` (when user confirms rebuild; `build-tdd` picks it up again) + - `done` → `obsolete` (when the feature is removed from the PRD; code is not deleted but story is retired) + - `ready` → `obsolete` (when the feature is removed before build starts) + - `in-progress` → `obsolete` (when the feature is removed during build) - `priority` — drives execution order in `plan-n-build`. - `prd` — relative link so agents can pull PRD context without re-deriving it. - `depends_on` — `plan-n-build` honors this when ordering execution. diff --git a/package.json b/package.json index 095916e..57f65d4 100644 --- a/package.json +++ b/package.json @@ -38,11 +38,12 @@ "node": ">=16.0.0" }, "scripts": { - "test": "node scripts/verify-manifest.js && node scripts/verify-sync.js && node scripts/verify-gemini.js && node scripts/verify-copilot.js", + "test": "node scripts/verify-manifest.js && node scripts/verify-sync.js && node scripts/verify-gemini.js && node scripts/verify-copilot.js && node scripts/verify-story-schema.js", "verify:sync": "node scripts/verify-sync.js", "verify:manifest": "node scripts/verify-manifest.js", "verify:gemini": "node scripts/verify-gemini.js", "verify:copilot": "node scripts/verify-copilot.js", + "verify:story-schema": "node scripts/verify-story-schema.js", "sync-templates": "node scripts/sync-templates.js" } } diff --git a/scripts/verify-story-schema.js b/scripts/verify-story-schema.js new file mode 100644 index 0000000..cf32a3d --- /dev/null +++ b/scripts/verify-story-schema.js @@ -0,0 +1,78 @@ +#!/usr/bin/env node +/** + * Verify that story-schema.md contains all required statuses and transition rules. + */ + +const fs = require('fs'); +const path = require('path'); + +const repoRoot = path.join(__dirname, '..'); +const schemaPath = path.join(repoRoot, '_sam', 'core', 'resources', 'story-schema.md'); + +let errors = 0; + +if (!fs.existsSync(schemaPath)) { + console.error(`Story schema missing: ${schemaPath}`); + process.exit(1); +} + +const content = fs.readFileSync(schemaPath, 'utf8'); + +// Required statuses in the status enum +const requiredStatuses = ['draft', 'ready', 'in-progress', 'done', 'blocked', 'needs-rebuild', 'obsolete']; + +for (const status of requiredStatuses) { + if (!content.includes(status)) { + console.error(`Missing status in schema: ${status}`); + errors++; + } +} + +// Required transition rules (statuses are backtick-wrapped in the schema) +const requiredTransitions = [ + ['done', 'needs-rebuild'], + ['done', 'obsolete'], + ['ready', 'obsolete'], + ['in-progress', 'obsolete'], + ['needs-rebuild', 'in-progress'], +]; + +for (const [from, to] of requiredTransitions) { + // Match backtick-wrapped format: `from` → `to` + const pattern = `\`${from}\` → \`${to}\``; + if (!content.includes(pattern)) { + console.error(`Missing transition rule: ${from} → ${to}`); + errors++; + } +} + +// Verify the status enum line in frontmatter includes the new statuses +const statusEnumMatch = content.match(/status:.*#.+/); +if (statusEnumMatch) { + const statusLine = statusEnumMatch[0]; + if (!statusLine.includes('needs-rebuild')) { + console.error('Status enum line in frontmatter does not include needs-rebuild'); + errors++; + } + if (!statusLine.includes('obsolete')) { + console.error('Status enum line in frontmatter does not include obsolete'); + errors++; + } +} + +// Verify templates copy matches +const templatesSchemaPath = path.join(repoRoot, 'templates', '_sam', 'core', 'resources', 'story-schema.md'); +if (fs.existsSync(templatesSchemaPath)) { + const templatesContent = fs.readFileSync(templatesSchemaPath, 'utf8'); + if (content !== templatesContent) { + console.error('story-schema.md differs between _sam/ and templates/_sam/'); + errors++; + } +} + +if (errors > 0) { + console.error(`\n${errors} story schema error(s) found.`); + process.exit(1); +} else { + console.log('Story schema valid (all statuses and transitions present).'); +} diff --git a/templates/_sam/core/resources/story-schema.md b/templates/_sam/core/resources/story-schema.md index d7ed126..2a73f4e 100644 --- a/templates/_sam/core/resources/story-schema.md +++ b/templates/_sam/core/resources/story-schema.md @@ -31,7 +31,7 @@ id: STORY-003 # stable identifier; never renumber epic: EPIC-001 # parent epic id (or null for ad-hoc stories) kind: feature # feature | integration | scaffolding title: User can reset password # one-line summary, no trailing period -status: ready # draft | ready | in-progress | done | blocked +status: ready # draft | ready | in-progress | done | blocked | needs-rebuild | obsolete priority: P1 # P0 (critical) | P1 (normal) | P2 (nice-to-have) prd: ../../prd.md # relative path from this file to the source PRD (or null) depends_on: [STORY-001] # list of story ids that must be `done` first; [] if none @@ -52,6 +52,11 @@ created: 2026-05-13 # YYYY-MM-DD; never changes after creation - `ready` → `in-progress` (when `build-tdd` picks it up) - `in-progress` → `done` (when `build-tdd` completes all phases) - any → `blocked` (when retry limit hit; include reason in body) + - `done` → `needs-rebuild` (when a contract this story produces has changed; code is kept but story must be re-built when user confirms) + - `needs-rebuild` → `in-progress` (when user confirms rebuild; `build-tdd` picks it up again) + - `done` → `obsolete` (when the feature is removed from the PRD; code is not deleted but story is retired) + - `ready` → `obsolete` (when the feature is removed before build starts) + - `in-progress` → `obsolete` (when the feature is removed during build) - `priority` — drives execution order in `plan-n-build`. - `prd` — relative link so agents can pull PRD context without re-deriving it. - `depends_on` — `plan-n-build` honors this when ordering execution. From 1e9efb53b7e27ad102ec82d0dc67f5c2fd9d98e8 Mon Sep 17 00:00:00 2001 From: "sam-cloud-app[bot]" <252427705+sam-cloud-app[bot]@users.noreply.github.com> Date: Sat, 16 May 2026 10:38:58 +0000 Subject: [PATCH 03/11] Task 2/11: Document the `deprecated` contract status in contract-schema.md MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Add Replan lifecycle subsection under Field rules → status explaining how sam-replan uses deprecated, version bumps, and status transitions for removed, modified, and added features. Co-Authored-By: Claude Opus 4.6 (1M context) --- _sam/core/resources/contract-schema.md | 7 +++++++ templates/_sam/core/resources/contract-schema.md | 7 +++++++ 2 files changed, 14 insertions(+) diff --git a/_sam/core/resources/contract-schema.md b/_sam/core/resources/contract-schema.md index 34a598f..df64ad6 100644 --- a/_sam/core/resources/contract-schema.md +++ b/_sam/core/resources/contract-schema.md @@ -47,6 +47,13 @@ created: 2026-05-14 # YYYY-MM-DD - `draft` — Atlas designed it, no story has implemented it yet - `stable` — implemented and exercised by at least one story - `deprecated` — superseded; consumers must migrate +- **Replan lifecycle for `status`** — when `sam-replan` processes a revised PRD: + - *Feature removed* → the contract is set to `deprecated`. The contract file is **not** deleted; code that implements it remains in place until the user explicitly removes it. + - *Feature modified, story already done* → the contract `version` is bumped and the owning story is marked `needs-rebuild`. The contract stays `stable` (the new version is the current truth). + - *Feature modified, story not yet built* → the contract is updated in place; `status` remains `draft` or `stable` as-is. + - *Feature added* → new contracts are created at `draft`, same as the `extend` workflow. + - A `deprecated` contract must not be referenced by any new story's `consumes:` list. Existing stories that consume it are flagged in the impact summary for the user to address. + - Deprecation is permanent within a plan cycle — there is no "un-deprecate". If the feature returns, a new contract with a new id is created. - `owner_story` — the story whose `produces:` list contains this contract. Exactly one. `null` only for contracts that pre-exist the planning run (legacy code). - `version` — pinned in story `consumes:` entries via `id@version` when a breaking change is needed; otherwise consumers always read latest. diff --git a/templates/_sam/core/resources/contract-schema.md b/templates/_sam/core/resources/contract-schema.md index 34a598f..df64ad6 100644 --- a/templates/_sam/core/resources/contract-schema.md +++ b/templates/_sam/core/resources/contract-schema.md @@ -47,6 +47,13 @@ created: 2026-05-14 # YYYY-MM-DD - `draft` — Atlas designed it, no story has implemented it yet - `stable` — implemented and exercised by at least one story - `deprecated` — superseded; consumers must migrate +- **Replan lifecycle for `status`** — when `sam-replan` processes a revised PRD: + - *Feature removed* → the contract is set to `deprecated`. The contract file is **not** deleted; code that implements it remains in place until the user explicitly removes it. + - *Feature modified, story already done* → the contract `version` is bumped and the owning story is marked `needs-rebuild`. The contract stays `stable` (the new version is the current truth). + - *Feature modified, story not yet built* → the contract is updated in place; `status` remains `draft` or `stable` as-is. + - *Feature added* → new contracts are created at `draft`, same as the `extend` workflow. + - A `deprecated` contract must not be referenced by any new story's `consumes:` list. Existing stories that consume it are flagged in the impact summary for the user to address. + - Deprecation is permanent within a plan cycle — there is no "un-deprecate". If the feature returns, a new contract with a new id is created. - `owner_story` — the story whose `produces:` list contains this contract. Exactly one. `null` only for contracts that pre-exist the planning run (legacy code). - `version` — pinned in story `consumes:` entries via `id@version` when a breaking change is needed; otherwise consumers always read latest. From 3fc4d794b1cd173b3752dd999c911c8a43416a57 Mon Sep 17 00:00:00 2001 From: "sam-cloud-app[bot]" <252427705+sam-cloud-app[bot]@users.noreply.github.com> Date: Sat, 16 May 2026 10:41:00 +0000 Subject: [PATCH 04/11] Task 3/11: Create the `replan` workflow directory and workflow.md Co-Authored-By: Claude Opus 4.6 (1M context) --- _sam/_config/workflow-manifest.csv | 1 + _sam/core/workflows/replan/workflow.md | 215 ++++++++++++++++++ templates/_sam/_config/workflow-manifest.csv | 1 + .../_sam/core/workflows/replan/workflow.md | 215 ++++++++++++++++++ 4 files changed, 432 insertions(+) create mode 100644 _sam/core/workflows/replan/workflow.md create mode 100644 templates/_sam/core/workflows/replan/workflow.md diff --git a/_sam/_config/workflow-manifest.csv b/_sam/_config/workflow-manifest.csv index 526ab7a..662e174 100644 --- a/_sam/_config/workflow-manifest.csv +++ b/_sam/_config/workflow-manifest.csv @@ -5,3 +5,4 @@ name,description,module,path "build-tdd","SAM Build-TDD Workflow - Implements a single user story using RED-GREEN-REFACTOR with conditional UI/CSS/A11y/Security review.","core","_sam/core/workflows/build-tdd/workflow.md" "plan-n-build","SAM end-to-end composer - runs plan, then tdd for every story, then comprehensive docs.","core","_sam/core/workflows/plan-n-build/workflow.md" "extend","SAM Extend Workflow - Plan additive changes on top of an existing app. Reads existing sdocs/, never wipes; emits new contracts, stories, and regression integration without modifying done work.","core","_sam/core/workflows/extend/workflow.md" +"replan","SAM Replan Workflow - Handle requirement changes mid-build by diffing a revised PRD against the current state and surgically updating affected artifacts.","core","_sam/core/workflows/replan/workflow.md" diff --git a/_sam/core/workflows/replan/workflow.md b/_sam/core/workflows/replan/workflow.md new file mode 100644 index 0000000..462d3f3 --- /dev/null +++ b/_sam/core/workflows/replan/workflow.md @@ -0,0 +1,215 @@ +--- +name: replan +description: SAM Replan Workflow - Handle requirement changes mid-build by diffing a revised PRD against the current state and surgically updating affected artifacts. +version: 1.0.0 +--- + +# SAM Replan Workflow + +**Goal:** Handle requirement changes that occur mid-build or that modify/remove existing functionality. Unlike `extend` (additive-only) or `plan --force` (full wipe), `replan` performs surgical updates: it diffs a revised PRD against the current one, computes impact via the contract dependency graph, and applies per-category actions (add / modify / remove) while preserving done work wherever possible. + +**Your Role:** You are SAM orchestrating a replanning pass. You coordinate Atlas (diff analysis, impact computation, contract evolution, story updates). The output is a modified `sdocs/` tree ready for `build-tdd` on any stories marked `needs-rebuild` or newly created. + +This workflow is the mid-build counterpart to `extend`. Use it whenever requirements change in ways that affect or remove existing functionality — not just add to it. + +--- + +## INPUTS + +``` +/sam:core:workflows:replan +``` + +Required: +- `` — a markdown file containing the full revised PRD. Atlas diffs this against the current `sdocs/prd.md` (or root `prd.md`) to determine what changed. + +Required preconditions: +- `sdocs/prd.md` (or equivalent at the linked location) exists +- `sdocs/architecture-ref.md` exists +- `sdocs/contracts/INDEX.md` exists +- `sdocs/stories/` exists with at least one story (otherwise use `plan` for the initial run) + +Optional flags: +- `--force` — skip the confirmation gate (Phase 4) and apply all changes without user confirmation. Use with caution — this bypasses the safety net for destructive operations. + +--- + +## OUTPUTS + +Modifies the existing `sdocs/` tree and merges the revised PRD: + +``` +/ +├── prd.md # REPLACED with revised PRD + change log entry +└── sdocs/ + ├── replans/ + │ └── --analysis.md # impact analysis archive (audit trail) + ├── contracts/ + │ ├── /.md # NEW contracts (from added requirements) + │ ├── /.md # VERSION-BUMPED contracts (from modified requirements) + │ └── /.md # STATUS → deprecated (from removed requirements) + ├── epics/ + │ └── EPIC--.md # new epic(s), if created for added requirements + └── stories/ + ├── STORY--.md # NEW stories (added requirements) + ├── STORY--.md # MODIFIED stories (status → needs-rebuild) + └── STORY--.md # OBSOLETE stories (status → obsolete) +``` + +Existing artifacts: +- Untouched if the revised PRD doesn't affect them +- Status changed to `needs-rebuild` for done stories whose contracts were modified +- Status changed to `obsolete` for stories tied to removed requirements +- Contracts set to `deprecated` when their requirement is removed +- Story ids continue the existing sequence for new stories — never reuse an existing id +- Code is NEVER deleted automatically — only metadata (status fields) changes + +--- + +## SCHEMA CONTRACTS + +Every NEW or AMENDED file MUST conform to: +- `_sam/core/resources/story-schema.md` +- `_sam/core/resources/epic-schema.md` +- `_sam/core/resources/contract-schema.md` + +Refuse to emit invalid artifacts. Existing artifacts that already pass schema are not re-validated unless their status changes. + +--- + +## PHASES + +### Phase 1: Diff PRD +**Load step:** `./steps/step-01-diff-prd.md` + +- Atlas loads the revised PRD and the current PRD (`sdocs/prd.md` or root `prd.md`) +- Performs a semantic diff: categorizes each requirement as **added**, **modified**, **removed**, or **unchanged** +- For modified requirements: identifies what specifically changed (acceptance criteria, scope, constraints) +- Produces a structured diff report at `sdocs/replans/--analysis.md` + +**Gate:** Every requirement in both PRDs is categorized; no ambiguous changes remain; the analysis file is written. + +### Phase 2: Impact Analysis +**Load step:** `./steps/step-02-impact-analysis.md` + +- For each modified or removed requirement, walk the `produces` / `consumes` graph from existing contracts and stories +- Identify all affected artifacts: which contracts change, which stories are invalidated +- Classify each affected story by current status: + - `done` stories affected by a modification → candidate for `needs-rebuild` + - `done` stories affected by a removal → candidate for `obsolete` + - `ready` or `in-progress` stories → update in place (less disruptive) +- Append the full impact graph to `sdocs/replans/--analysis.md` + +**Gate:** Every modified/removed requirement has a traced impact path; no orphan references; impact summary is complete. + +### Phase 3: Apply Changes +**Load step:** `./steps/step-03-apply-changes.md` + +Per-category actions: + +- **Added requirements** → behave like `extend`: new contracts (`status: draft`) + new stories appended +- **Modified, story not yet built** (`ready` / `in-progress`) → update story file in place; if a contract changes, bump contract version +- **Modified, story done** → bump contract version, mark story `needs-rebuild`, keep code as-is until user confirms rebuild +- **Removed requirements** → mark story `obsolete`, set contract `status: deprecated`, do NOT delete code automatically + +For each contract change: +- New contract → write with `status: draft`, `version: 1` +- Modified contract → bump `version: N → N+1`, update body +- Removed contract → set `status: deprecated`, preserve body for reference + +Update `sdocs/contracts/INDEX.md` to reflect the new state. + +**Gate:** All changes applied; contract INDEX regenerated; story dependency graph remains acyclic; every new contract has an owner story. + +### Phase 4: Impact Summary Gate +**Load step:** `./steps/step-04-impact-gate.md` + +- Present the user with a summary of all changes about to be finalized: + - Stories marked `needs-rebuild` (with count) + - Stories marked `obsolete` (with count) + - Contracts deprecated (with count) + - New stories/contracts created (with count) +- Unless `--force` is set, halt and wait for user confirmation before proceeding +- If the user rejects: roll back all changes from Phase 3; leave the analysis file as documentation + +**Gate:** User confirms (or `--force` is set); all changes from Phase 3 are finalized. + +### Phase 5: Merge Revised PRD +**Load step:** `./steps/step-05-merge-prd.md` + +- Replace the current PRD content with the revised PRD +- Append a `## Change log` entry citing the replan slug, date, and summary of changes (N added, N modified, N removed) +- Bump frontmatter `version` and `last_updated` +- The analysis file at `sdocs/replans/` remains as the audit trail; the PRD is the source of truth for the current spec + +**Gate:** PRD `version` strictly greater than before; `## Change log` contains a new entry; revised PRD validates against `prd-schema.md`. + +--- + +## EXIT STATES + +### Success +All artifacts updated; impact analysis archived. Output summary: + +``` +Replan complete. +Analysis: sdocs/replans/2026-05-15-title-length-analysis.md +Contracts: 1 new, 2 modified (v1→v2), 1 deprecated +Stories: 2 new (status: ready), 3 needs-rebuild, 1 obsolete +PRD: version 1.0.0 → 1.1.0 + +Next: /sam:core:workflows:build-tdd sdocs/stories/STORY--.md + (run on each needs-rebuild story to update implementation) +``` + +### Diff failure (Phase 1) +Halt if the revised PRD cannot be meaningfully diffed against the current PRD (e.g. completely different structure, no overlapping requirements). Suggest using `plan --force` for a full rewrite instead. + +### Impact analysis failure (Phase 2) +Halt if the dependency graph cannot be resolved (e.g. contracts reference stories that don't exist, circular dependencies). Write partial analysis to the replans file for debugging. + +### User rejection (Phase 4) +Halt and roll back Phase 3 changes. The analysis file remains for reference. User can revise the PRD and re-run, or use `--force` if they reconsider. + +### PRD merge failure (Phase 5) +Halt and roll back the PRD file. The contract + story artifacts from Phase 3 stay (they are independently valid). Re-run with the PRD issue fixed. + +--- + +## RESUMPTION + +`replan` is idempotent on the same revised PRD: + +- Compares the revised PRD content to any prior archived analysis +- If an identical replan has already been processed (same slug, same diff): halts with "replan already applied on ; pass --force to re-process" +- With `--force`: re-runs from Phase 1; may produce different results if the system state has changed since the last run + +Stories marked `needs-rebuild` retain that status until `build-tdd` is run on them, at which point they transition back to `done`. + +Stories marked `obsolete` are terminal — they are never rebuilt. Their code remains but is no longer maintained by the workflow system. + +--- + +## RELATIONSHIP TO OTHER WORKFLOWS + +| | plan | extend | replan | +|--------------------------|-------------------------------|-------------------------------|-------------------------------------| +| Input | PRD | addendum + existing sdocs/ | revised PRD + existing sdocs/ | +| Output | full epics + stories + contracts | additional artifacts | modified artifact tree | +| Existing artifacts | wiped (with --force) | preserved; additive only | surgically updated per category | +| Handles additions | yes | yes | yes | +| Handles modifications | yes (full rewrite) | no | yes (targeted) | +| Handles removals | yes (full rewrite) | no | yes (deprecation lifecycle) | +| Use when | initial build or full rewrite | adding post-v1 features | requirements change mid-build | + +If `replan` reports that the changes are too extensive to apply surgically (>80% of stories affected), it will suggest `plan --force` as an alternative. + +--- + +## AUTONOMOUS BEHAVIOR + +- No human prompts during execution except at Phase 4 (impact summary gate) +- Atlas decides epic attachment for new stories +- All decisions logged in the analysis report +- Halt cleanly on gate failures with actionable messages +- Code is never deleted — only metadata changes are autonomous diff --git a/templates/_sam/_config/workflow-manifest.csv b/templates/_sam/_config/workflow-manifest.csv index 526ab7a..662e174 100644 --- a/templates/_sam/_config/workflow-manifest.csv +++ b/templates/_sam/_config/workflow-manifest.csv @@ -5,3 +5,4 @@ name,description,module,path "build-tdd","SAM Build-TDD Workflow - Implements a single user story using RED-GREEN-REFACTOR with conditional UI/CSS/A11y/Security review.","core","_sam/core/workflows/build-tdd/workflow.md" "plan-n-build","SAM end-to-end composer - runs plan, then tdd for every story, then comprehensive docs.","core","_sam/core/workflows/plan-n-build/workflow.md" "extend","SAM Extend Workflow - Plan additive changes on top of an existing app. Reads existing sdocs/, never wipes; emits new contracts, stories, and regression integration without modifying done work.","core","_sam/core/workflows/extend/workflow.md" +"replan","SAM Replan Workflow - Handle requirement changes mid-build by diffing a revised PRD against the current state and surgically updating affected artifacts.","core","_sam/core/workflows/replan/workflow.md" diff --git a/templates/_sam/core/workflows/replan/workflow.md b/templates/_sam/core/workflows/replan/workflow.md new file mode 100644 index 0000000..462d3f3 --- /dev/null +++ b/templates/_sam/core/workflows/replan/workflow.md @@ -0,0 +1,215 @@ +--- +name: replan +description: SAM Replan Workflow - Handle requirement changes mid-build by diffing a revised PRD against the current state and surgically updating affected artifacts. +version: 1.0.0 +--- + +# SAM Replan Workflow + +**Goal:** Handle requirement changes that occur mid-build or that modify/remove existing functionality. Unlike `extend` (additive-only) or `plan --force` (full wipe), `replan` performs surgical updates: it diffs a revised PRD against the current one, computes impact via the contract dependency graph, and applies per-category actions (add / modify / remove) while preserving done work wherever possible. + +**Your Role:** You are SAM orchestrating a replanning pass. You coordinate Atlas (diff analysis, impact computation, contract evolution, story updates). The output is a modified `sdocs/` tree ready for `build-tdd` on any stories marked `needs-rebuild` or newly created. + +This workflow is the mid-build counterpart to `extend`. Use it whenever requirements change in ways that affect or remove existing functionality — not just add to it. + +--- + +## INPUTS + +``` +/sam:core:workflows:replan +``` + +Required: +- `` — a markdown file containing the full revised PRD. Atlas diffs this against the current `sdocs/prd.md` (or root `prd.md`) to determine what changed. + +Required preconditions: +- `sdocs/prd.md` (or equivalent at the linked location) exists +- `sdocs/architecture-ref.md` exists +- `sdocs/contracts/INDEX.md` exists +- `sdocs/stories/` exists with at least one story (otherwise use `plan` for the initial run) + +Optional flags: +- `--force` — skip the confirmation gate (Phase 4) and apply all changes without user confirmation. Use with caution — this bypasses the safety net for destructive operations. + +--- + +## OUTPUTS + +Modifies the existing `sdocs/` tree and merges the revised PRD: + +``` +/ +├── prd.md # REPLACED with revised PRD + change log entry +└── sdocs/ + ├── replans/ + │ └── --analysis.md # impact analysis archive (audit trail) + ├── contracts/ + │ ├── /.md # NEW contracts (from added requirements) + │ ├── /.md # VERSION-BUMPED contracts (from modified requirements) + │ └── /.md # STATUS → deprecated (from removed requirements) + ├── epics/ + │ └── EPIC--.md # new epic(s), if created for added requirements + └── stories/ + ├── STORY--.md # NEW stories (added requirements) + ├── STORY--.md # MODIFIED stories (status → needs-rebuild) + └── STORY--.md # OBSOLETE stories (status → obsolete) +``` + +Existing artifacts: +- Untouched if the revised PRD doesn't affect them +- Status changed to `needs-rebuild` for done stories whose contracts were modified +- Status changed to `obsolete` for stories tied to removed requirements +- Contracts set to `deprecated` when their requirement is removed +- Story ids continue the existing sequence for new stories — never reuse an existing id +- Code is NEVER deleted automatically — only metadata (status fields) changes + +--- + +## SCHEMA CONTRACTS + +Every NEW or AMENDED file MUST conform to: +- `_sam/core/resources/story-schema.md` +- `_sam/core/resources/epic-schema.md` +- `_sam/core/resources/contract-schema.md` + +Refuse to emit invalid artifacts. Existing artifacts that already pass schema are not re-validated unless their status changes. + +--- + +## PHASES + +### Phase 1: Diff PRD +**Load step:** `./steps/step-01-diff-prd.md` + +- Atlas loads the revised PRD and the current PRD (`sdocs/prd.md` or root `prd.md`) +- Performs a semantic diff: categorizes each requirement as **added**, **modified**, **removed**, or **unchanged** +- For modified requirements: identifies what specifically changed (acceptance criteria, scope, constraints) +- Produces a structured diff report at `sdocs/replans/--analysis.md` + +**Gate:** Every requirement in both PRDs is categorized; no ambiguous changes remain; the analysis file is written. + +### Phase 2: Impact Analysis +**Load step:** `./steps/step-02-impact-analysis.md` + +- For each modified or removed requirement, walk the `produces` / `consumes` graph from existing contracts and stories +- Identify all affected artifacts: which contracts change, which stories are invalidated +- Classify each affected story by current status: + - `done` stories affected by a modification → candidate for `needs-rebuild` + - `done` stories affected by a removal → candidate for `obsolete` + - `ready` or `in-progress` stories → update in place (less disruptive) +- Append the full impact graph to `sdocs/replans/--analysis.md` + +**Gate:** Every modified/removed requirement has a traced impact path; no orphan references; impact summary is complete. + +### Phase 3: Apply Changes +**Load step:** `./steps/step-03-apply-changes.md` + +Per-category actions: + +- **Added requirements** → behave like `extend`: new contracts (`status: draft`) + new stories appended +- **Modified, story not yet built** (`ready` / `in-progress`) → update story file in place; if a contract changes, bump contract version +- **Modified, story done** → bump contract version, mark story `needs-rebuild`, keep code as-is until user confirms rebuild +- **Removed requirements** → mark story `obsolete`, set contract `status: deprecated`, do NOT delete code automatically + +For each contract change: +- New contract → write with `status: draft`, `version: 1` +- Modified contract → bump `version: N → N+1`, update body +- Removed contract → set `status: deprecated`, preserve body for reference + +Update `sdocs/contracts/INDEX.md` to reflect the new state. + +**Gate:** All changes applied; contract INDEX regenerated; story dependency graph remains acyclic; every new contract has an owner story. + +### Phase 4: Impact Summary Gate +**Load step:** `./steps/step-04-impact-gate.md` + +- Present the user with a summary of all changes about to be finalized: + - Stories marked `needs-rebuild` (with count) + - Stories marked `obsolete` (with count) + - Contracts deprecated (with count) + - New stories/contracts created (with count) +- Unless `--force` is set, halt and wait for user confirmation before proceeding +- If the user rejects: roll back all changes from Phase 3; leave the analysis file as documentation + +**Gate:** User confirms (or `--force` is set); all changes from Phase 3 are finalized. + +### Phase 5: Merge Revised PRD +**Load step:** `./steps/step-05-merge-prd.md` + +- Replace the current PRD content with the revised PRD +- Append a `## Change log` entry citing the replan slug, date, and summary of changes (N added, N modified, N removed) +- Bump frontmatter `version` and `last_updated` +- The analysis file at `sdocs/replans/` remains as the audit trail; the PRD is the source of truth for the current spec + +**Gate:** PRD `version` strictly greater than before; `## Change log` contains a new entry; revised PRD validates against `prd-schema.md`. + +--- + +## EXIT STATES + +### Success +All artifacts updated; impact analysis archived. Output summary: + +``` +Replan complete. +Analysis: sdocs/replans/2026-05-15-title-length-analysis.md +Contracts: 1 new, 2 modified (v1→v2), 1 deprecated +Stories: 2 new (status: ready), 3 needs-rebuild, 1 obsolete +PRD: version 1.0.0 → 1.1.0 + +Next: /sam:core:workflows:build-tdd sdocs/stories/STORY--.md + (run on each needs-rebuild story to update implementation) +``` + +### Diff failure (Phase 1) +Halt if the revised PRD cannot be meaningfully diffed against the current PRD (e.g. completely different structure, no overlapping requirements). Suggest using `plan --force` for a full rewrite instead. + +### Impact analysis failure (Phase 2) +Halt if the dependency graph cannot be resolved (e.g. contracts reference stories that don't exist, circular dependencies). Write partial analysis to the replans file for debugging. + +### User rejection (Phase 4) +Halt and roll back Phase 3 changes. The analysis file remains for reference. User can revise the PRD and re-run, or use `--force` if they reconsider. + +### PRD merge failure (Phase 5) +Halt and roll back the PRD file. The contract + story artifacts from Phase 3 stay (they are independently valid). Re-run with the PRD issue fixed. + +--- + +## RESUMPTION + +`replan` is idempotent on the same revised PRD: + +- Compares the revised PRD content to any prior archived analysis +- If an identical replan has already been processed (same slug, same diff): halts with "replan already applied on ; pass --force to re-process" +- With `--force`: re-runs from Phase 1; may produce different results if the system state has changed since the last run + +Stories marked `needs-rebuild` retain that status until `build-tdd` is run on them, at which point they transition back to `done`. + +Stories marked `obsolete` are terminal — they are never rebuilt. Their code remains but is no longer maintained by the workflow system. + +--- + +## RELATIONSHIP TO OTHER WORKFLOWS + +| | plan | extend | replan | +|--------------------------|-------------------------------|-------------------------------|-------------------------------------| +| Input | PRD | addendum + existing sdocs/ | revised PRD + existing sdocs/ | +| Output | full epics + stories + contracts | additional artifacts | modified artifact tree | +| Existing artifacts | wiped (with --force) | preserved; additive only | surgically updated per category | +| Handles additions | yes | yes | yes | +| Handles modifications | yes (full rewrite) | no | yes (targeted) | +| Handles removals | yes (full rewrite) | no | yes (deprecation lifecycle) | +| Use when | initial build or full rewrite | adding post-v1 features | requirements change mid-build | + +If `replan` reports that the changes are too extensive to apply surgically (>80% of stories affected), it will suggest `plan --force` as an alternative. + +--- + +## AUTONOMOUS BEHAVIOR + +- No human prompts during execution except at Phase 4 (impact summary gate) +- Atlas decides epic attachment for new stories +- All decisions logged in the analysis report +- Halt cleanly on gate failures with actionable messages +- Code is never deleted — only metadata changes are autonomous From aa6764e8cefe13d59411e3d1166a1010b7510f18 Mon Sep 17 00:00:00 2001 From: "sam-cloud-app[bot]" <252427705+sam-cloud-app[bot]@users.noreply.github.com> Date: Sat, 16 May 2026 10:42:31 +0000 Subject: [PATCH 05/11] =?UTF-8?q?Task=204/11:=20Write=20Step=201=20?= =?UTF-8?q?=E2=80=94=20Diff=20revised=20PRD=20against=20current=20PRD?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Create step-01-diff-prd.md for the replan workflow. Atlas performs a semantic section-by-section comparison of a revised PRD against the current sdocs/prd.md, categorizing each requirement as added, modified, removed, or unchanged. Includes rename detection, modification detail drill-down, and an 80% threshold warning for near-total rewrites. Co-Authored-By: Claude Opus 4.6 (1M context) --- .../replan/steps/step-01-diff-prd.md | 196 ++++++++++++++++++ .../replan/steps/step-01-diff-prd.md | 196 ++++++++++++++++++ 2 files changed, 392 insertions(+) create mode 100644 _sam/core/workflows/replan/steps/step-01-diff-prd.md create mode 100644 templates/_sam/core/workflows/replan/steps/step-01-diff-prd.md diff --git a/_sam/core/workflows/replan/steps/step-01-diff-prd.md b/_sam/core/workflows/replan/steps/step-01-diff-prd.md new file mode 100644 index 0000000..80ef9d0 --- /dev/null +++ b/_sam/core/workflows/replan/steps/step-01-diff-prd.md @@ -0,0 +1,196 @@ +--- +step: 1 +name: diff-prd +description: Compare revised PRD against current sdocs/prd.md and categorize each requirement as added, modified, removed, or unchanged +agents: [architect] +--- + +# Step 1: Diff Revised PRD Against Current PRD + +**Agent:** Atlas (System Architect) + +**Purpose:** Perform a semantic, section-by-section comparison of a revised PRD against the current `sdocs/prd.md`. Every requirement is categorized as `added | modified | removed | unchanged`. The structured diff report drives all downstream phases — an incorrect classification here will cascade through impact analysis and artifact updates. + +--- + +## ENTRY CONDITIONS + +- Revised PRD file exists and is readable +- `sdocs/prd.md` (or root `prd.md`) exists and is readable +- `sdocs/architecture-ref.md` exists (needed for context on architectural constraints) +- `sdocs/stories/` exists with at least one story file (otherwise use `plan`, not `replan`) + +If any precondition fails, halt and tell the user which file is missing. + +--- + +## REQUIRED READING + +Before any analysis: +- The revised PRD — read in full +- `sdocs/prd.md` — read in full (this is the baseline for the diff) +- `sdocs/architecture-ref.md` — especially `## Key Architectural Decisions` and `## System Shape` (to understand whether changes cross architectural boundaries) + +--- + +## PROCESS + +### 1.1 Inventory Current PRD Sections + +Parse the current `sdocs/prd.md` and build an inventory of every requirement-bearing section: + +```yaml +sections: + - id: # derived from heading text + heading: + level:

+ type: feature | constraint | scope | meta + acceptance_criteria: [] + content_hash: +``` + +Focus on `## Features`, `## Acceptance Criteria`, `## Constraints`, and `## Out of Scope`. Meta sections (title, overview, changelog) are tracked but classified separately. + +### 1.2 Inventory Revised PRD Sections + +Repeat the same parse on the revised PRD. Use identical slugging rules so sections can be matched by id. + +### 1.3 Match and Classify + +For each section in the union of both inventories: + +| Current PRD | Revised PRD | Classification | +|-------------|-------------|----------------| +| present | present, same content | `unchanged` | +| present | present, different content | `modified` | +| present | absent | `removed` | +| absent | present | `added` | + +For `modified` sections, drill into the specific changes: + +```yaml +modification_detail: + section: + changes: + - field: acceptance_criteria + type: ac-added | ac-removed | ac-changed + before: + after: + - field: scope + type: narrowed | broadened | reframed + before: + after: + - field: constraints + type: added | removed | changed + before: + after: +``` + +### 1.4 Detect Renames and Moves + +Before finalizing a `removed` + `added` pair, check for potential renames: +- If a removed section and an added section share >70% content similarity, flag them as a **rename candidate** +- Present rename candidates in the diff report for human verification +- Do NOT auto-classify renames as `unchanged` — classify as `modified` with a rename note + +### 1.5 Generate Diff Summary + +Produce a count summary: + +```yaml +summary: + total_sections: + added: + modified: + removed: + unchanged: + rename_candidates: +``` + +If removed + modified sections exceed 80% of total, append a warning: + +> ⚠ More than 80% of requirements are affected. Consider using `plan --force` for a full rewrite instead. + +### 1.6 Write Diff Report + +Write the structured diff to `sdocs/replans/--diff.md`: + +```markdown +--- +replan_slug: +phase: replan-step-1 +date: +revised_prd: +current_prd: sdocs/prd.md +--- + +# PRD Diff — + +## Summary +- Total sections: N +- Added: N +- Modified: N +- Removed: N +- Unchanged: N + +## Added Sections +| Section | Heading | Type | +|---------|---------|------| +| | | feature | + +## Modified Sections +| Section | Heading | What Changed | +|---------|---------|--------------| +| | | AC added, scope broadened | + +### Modification Details +#### +- **Before:** +- **After:** +- **Change type:** + +## Removed Sections +| Section | Heading | Type | +|---------|---------|------| +| | | feature | + +## Unchanged Sections +| Section | Heading | +|---------|---------| +| | | + +## Rename Candidates +| Removed | Added | Similarity | +|---------|-------|------------| +| | | ~75% | +``` + +The slug is derived from the most significant change in the revised PRD (e.g. `title-length-update`, `drop-tags-feature`). If there is no clear dominant change, use a generic slug like `multi-change`. + +--- + +## GATE — DIFF PASSES WHEN + +- [ ] Every section in the current PRD is accounted for (classified as `modified`, `removed`, or `unchanged`) +- [ ] Every section in the revised PRD is accounted for (classified as `modified`, `added`, or `unchanged`) +- [ ] No section is left unclassified +- [ ] Every `modified` section has a `modification_detail` entry explaining what changed +- [ ] Rename candidates (if any) are flagged, not silently absorbed +- [ ] Diff report written to `sdocs/replans/--diff.md` +- [ ] Summary counts are internally consistent (`added + modified + removed + unchanged = total unique sections across both PRDs`) + +--- + +## FAILURE MODES + +- **Unreadable PRD:** Halt with error message identifying which file could not be parsed. +- **Completely different structure:** If no sections match between current and revised PRD (0 unchanged, 0 modified), warn that the PRDs share no common structure and recommend `plan --force` instead. +- **Ambiguous classification:** If a section cannot be confidently classified (e.g. heading matches but content is entirely rewritten), classify as `modified` with a note — never leave it unclassified. + +--- + +## NEXT + +→ Step 2: Impact Analysis (`step-02-impact-analysis.md`) + +Atlas passes the structured diff report to the next phase, which walks the contract dependency graph to determine which artifacts are affected by each modified or removed requirement. diff --git a/templates/_sam/core/workflows/replan/steps/step-01-diff-prd.md b/templates/_sam/core/workflows/replan/steps/step-01-diff-prd.md new file mode 100644 index 0000000..80ef9d0 --- /dev/null +++ b/templates/_sam/core/workflows/replan/steps/step-01-diff-prd.md @@ -0,0 +1,196 @@ +--- +step: 1 +name: diff-prd +description: Compare revised PRD against current sdocs/prd.md and categorize each requirement as added, modified, removed, or unchanged +agents: [architect] +--- + +# Step 1: Diff Revised PRD Against Current PRD + +**Agent:** Atlas (System Architect) + +**Purpose:** Perform a semantic, section-by-section comparison of a revised PRD against the current `sdocs/prd.md`. Every requirement is categorized as `added | modified | removed | unchanged`. The structured diff report drives all downstream phases — an incorrect classification here will cascade through impact analysis and artifact updates. + +--- + +## ENTRY CONDITIONS + +- Revised PRD file exists and is readable +- `sdocs/prd.md` (or root `prd.md`) exists and is readable +- `sdocs/architecture-ref.md` exists (needed for context on architectural constraints) +- `sdocs/stories/` exists with at least one story file (otherwise use `plan`, not `replan`) + +If any precondition fails, halt and tell the user which file is missing. + +--- + +## REQUIRED READING + +Before any analysis: +- The revised PRD — read in full +- `sdocs/prd.md` — read in full (this is the baseline for the diff) +- `sdocs/architecture-ref.md` — especially `## Key Architectural Decisions` and `## System Shape` (to understand whether changes cross architectural boundaries) + +--- + +## PROCESS + +### 1.1 Inventory Current PRD Sections + +Parse the current `sdocs/prd.md` and build an inventory of every requirement-bearing section: + +```yaml +sections: + - id: # derived from heading text + heading: + level:

+ type: feature | constraint | scope | meta + acceptance_criteria: [] + content_hash: +``` + +Focus on `## Features`, `## Acceptance Criteria`, `## Constraints`, and `## Out of Scope`. Meta sections (title, overview, changelog) are tracked but classified separately. + +### 1.2 Inventory Revised PRD Sections + +Repeat the same parse on the revised PRD. Use identical slugging rules so sections can be matched by id. + +### 1.3 Match and Classify + +For each section in the union of both inventories: + +| Current PRD | Revised PRD | Classification | +|-------------|-------------|----------------| +| present | present, same content | `unchanged` | +| present | present, different content | `modified` | +| present | absent | `removed` | +| absent | present | `added` | + +For `modified` sections, drill into the specific changes: + +```yaml +modification_detail: + section: + changes: + - field: acceptance_criteria + type: ac-added | ac-removed | ac-changed + before: + after: + - field: scope + type: narrowed | broadened | reframed + before: + after: + - field: constraints + type: added | removed | changed + before: + after: +``` + +### 1.4 Detect Renames and Moves + +Before finalizing a `removed` + `added` pair, check for potential renames: +- If a removed section and an added section share >70% content similarity, flag them as a **rename candidate** +- Present rename candidates in the diff report for human verification +- Do NOT auto-classify renames as `unchanged` — classify as `modified` with a rename note + +### 1.5 Generate Diff Summary + +Produce a count summary: + +```yaml +summary: + total_sections: + added: + modified: + removed: + unchanged: + rename_candidates: +``` + +If removed + modified sections exceed 80% of total, append a warning: + +> ⚠ More than 80% of requirements are affected. Consider using `plan --force` for a full rewrite instead. + +### 1.6 Write Diff Report + +Write the structured diff to `sdocs/replans/--diff.md`: + +```markdown +--- +replan_slug: +phase: replan-step-1 +date: +revised_prd: +current_prd: sdocs/prd.md +--- + +# PRD Diff — + +## Summary +- Total sections: N +- Added: N +- Modified: N +- Removed: N +- Unchanged: N + +## Added Sections +| Section | Heading | Type | +|---------|---------|------| +| | | feature | + +## Modified Sections +| Section | Heading | What Changed | +|---------|---------|--------------| +| | | AC added, scope broadened | + +### Modification Details +#### +- **Before:** +- **After:** +- **Change type:** + +## Removed Sections +| Section | Heading | Type | +|---------|---------|------| +| | | feature | + +## Unchanged Sections +| Section | Heading | +|---------|---------| +| | | + +## Rename Candidates +| Removed | Added | Similarity | +|---------|-------|------------| +| | | ~75% | +``` + +The slug is derived from the most significant change in the revised PRD (e.g. `title-length-update`, `drop-tags-feature`). If there is no clear dominant change, use a generic slug like `multi-change`. + +--- + +## GATE — DIFF PASSES WHEN + +- [ ] Every section in the current PRD is accounted for (classified as `modified`, `removed`, or `unchanged`) +- [ ] Every section in the revised PRD is accounted for (classified as `modified`, `added`, or `unchanged`) +- [ ] No section is left unclassified +- [ ] Every `modified` section has a `modification_detail` entry explaining what changed +- [ ] Rename candidates (if any) are flagged, not silently absorbed +- [ ] Diff report written to `sdocs/replans/--diff.md` +- [ ] Summary counts are internally consistent (`added + modified + removed + unchanged = total unique sections across both PRDs`) + +--- + +## FAILURE MODES + +- **Unreadable PRD:** Halt with error message identifying which file could not be parsed. +- **Completely different structure:** If no sections match between current and revised PRD (0 unchanged, 0 modified), warn that the PRDs share no common structure and recommend `plan --force` instead. +- **Ambiguous classification:** If a section cannot be confidently classified (e.g. heading matches but content is entirely rewritten), classify as `modified` with a note — never leave it unclassified. + +--- + +## NEXT + +→ Step 2: Impact Analysis (`step-02-impact-analysis.md`) + +Atlas passes the structured diff report to the next phase, which walks the contract dependency graph to determine which artifacts are affected by each modified or removed requirement. From 72fc60ccc9c147a681616eb4ce17b8db75047e6e Mon Sep 17 00:00:00 2001 From: "sam-cloud-app[bot]" <252427705+sam-cloud-app[bot]@users.noreply.github.com> Date: Sat, 16 May 2026 10:44:22 +0000 Subject: [PATCH 06/11] =?UTF-8?q?Task=205/11:=20Write=20Step=202=20?= =?UTF-8?q?=E2=80=94=20Impact=20analysis=20on=20contracts=20and=20stories?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Co-Authored-By: Claude Opus 4.6 (1M context) --- .../replan/steps/step-02-impact-analysis.md | 269 ++++++++++++++++++ .../replan/steps/step-02-impact-analysis.md | 269 ++++++++++++++++++ 2 files changed, 538 insertions(+) create mode 100644 _sam/core/workflows/replan/steps/step-02-impact-analysis.md create mode 100644 templates/_sam/core/workflows/replan/steps/step-02-impact-analysis.md diff --git a/_sam/core/workflows/replan/steps/step-02-impact-analysis.md b/_sam/core/workflows/replan/steps/step-02-impact-analysis.md new file mode 100644 index 0000000..782ebfc --- /dev/null +++ b/_sam/core/workflows/replan/steps/step-02-impact-analysis.md @@ -0,0 +1,269 @@ +--- +step: 2 +name: impact-analysis +description: Walk the produces/consumes graph to identify contracts and stories affected by each modified or removed requirement from the Step 1 diff +agents: [architect] +--- + +# Step 2: Impact Analysis on Contracts and Stories + +**Agent:** Atlas (System Architect) + +**Purpose:** For each `modified` or `removed` requirement identified in Step 1, walk the `produces`/`consumes` dependency graph to determine which contracts and stories are affected. The output is a structured impact matrix that drives all downstream decisions — which stories need rebuilding, which contracts need version bumps or deprecation, and which artifacts are untouched. + +--- + +## ENTRY CONDITIONS + +- Step 1 diff report exists at `sdocs/replans/--diff.md` +- Diff report contains at least one `modified` or `removed` section (otherwise skip to Step 5 — merge) +- `sdocs/contracts/INDEX.md` exists and is readable +- `sdocs/stories/` directory exists with at least one story file + +If any precondition fails, halt and tell the user which file or directory is missing. + +--- + +## REQUIRED READING + +Before any analysis: +- `sdocs/replans/--diff.md` — the structured diff from Step 1 (read in full) +- `sdocs/contracts/INDEX.md` — the contract index (read in full) +- Every contract file referenced in INDEX.md — at minimum read the frontmatter (`id`, `kind`, `status`, `owner_story`, `version`) +- Every story file in `sdocs/stories/` — at minimum read the frontmatter (`id`, `status`, `produces`, `consumes`, `depends_on`) +- `_sam/core/resources/contract-schema.md` — for understanding contract lifecycle rules +- `_sam/core/resources/story-schema.md` — for understanding story status transitions + +--- + +## PROCESS + +### 2.1 Build the Dependency Graph + +Construct an in-memory graph from story and contract frontmatter: + +```yaml +graph: + contracts: + - id: + kind: + status: + version: + producer: # from owner_story + consumers: [, ...] # stories whose consumes: list includes this contract + + stories: + - id: + status: + produces: [, ...] + consumes: [, ...] + depends_on: [, ...] +``` + +Every contract must appear exactly once as a node. Every story must appear exactly once. Cross-reference: +- For each story's `produces` list, the corresponding contract's `producer` field must point back to that story +- For each story's `consumes` list, that story must appear in the corresponding contract's `consumers` list + +Flag any inconsistencies (orphan contracts, dangling references) as warnings in the output — do not halt, but record them. + +### 2.2 Map Requirements to Contracts + +For each `modified` or `removed` requirement from the diff report, identify which contracts implement or relate to it: + +1. **By owner story:** Find stories whose `## User Story` or `## Acceptance Criteria` directly trace to the changed PRD section. Then collect those stories' `produces` contracts. +2. **By content match:** Scan contract bodies for references to the changed requirement (e.g. a contract's `## Shape` mentions the feature being modified). This catches contracts not yet linked to a story. +3. **By section-id mapping:** If the PRD sections use consistent naming (e.g. `## Feature: Tags`), match against story titles and contract titles. + +For each mapping, record the confidence level: + +```yaml +mappings: + - requirement: + classification: modified | removed + matched_contracts: + - contract: + match_type: owner-story | content-match | title-match + confidence: high | medium | low + matched_stories: + - story: + relation: producer | consumer | dependency +``` + +If a requirement maps to zero contracts and zero stories, record it as `no-impact` with a brief explanation (e.g. "this section is a constraint, not a feature — no artifacts implement it directly"). + +### 2.3 Walk Downstream Dependencies + +For each directly affected contract, trace its downstream impact: + +1. **Consumer stories:** Find all stories in the contract's `consumers` list +2. **Transitive dependencies:** For each consumer story, check if it `produces` contracts that are consumed by further stories. Walk one level deep (direct consumers of the affected contract, plus their immediate downstream). +3. **Do NOT walk indefinitely** — cap at two hops from the origin contract. Beyond that, flag as "possible transitive impact — manual review recommended." + +Record the full impact chain: + +```yaml +impact_chain: + - origin_contract: + origin_requirement: + directly_affected: + - artifact: + type: story | contract + current_status: + impact: needs-version-bump | needs-rebuild | needs-deprecation | needs-update + transitively_affected: + - artifact: + type: story | contract + hops: <1 | 2> + current_status: + impact: possible-rebuild | review-recommended +``` + +### 2.4 Classify Impact per Artifact + +For each affected artifact, assign an impact classification based on the requirement change type and the artifact's current status: + +**For contracts:** + +| Requirement Change | Contract Status | Impact Classification | +|---|---|---| +| modified | draft | `update-in-place` — edit contract body, no version bump | +| modified | stable | `version-bump` — bump version, update body | +| modified | deprecated | `no-action` — already deprecated, note in report | +| removed | draft | `deprecate` — set status to deprecated | +| removed | stable | `deprecate` — set status to deprecated | +| removed | deprecated | `no-action` — already deprecated | + +**For stories:** + +| Requirement Change | Story Status | Impact Classification | +|---|---|---| +| modified | draft or ready | `update-in-place` — edit story ACs and technical notes | +| modified | in-progress | `needs-rebuild` — mark status, keep partial code | +| modified | done | `needs-rebuild` — mark status, keep existing code | +| modified | blocked | `update-in-place` — update while already stalled | +| modified | needs-rebuild | `no-action` — already marked for rebuild | +| modified | obsolete | `no-action` — already retired | +| removed | draft or ready | `obsolete` — set status to obsolete | +| removed | in-progress | `obsolete` — set status to obsolete, keep code | +| removed | done | `obsolete` — set status to obsolete, keep code | +| removed | blocked | `obsolete` — set status to obsolete | +| removed | needs-rebuild | `obsolete` — set status to obsolete | +| removed | obsolete | `no-action` — already retired | + +### 2.5 Generate Impact Summary Statistics + +Produce counts for the impact gate: + +```yaml +impact_summary: + requirements_analyzed: # modified + removed from diff + with_mapped_artifacts: # requirements that map to at least one contract or story + with_no_impact: # requirements with explicit "no impact" note + unmapped: # should be 0 — gate fails if > 0 + + contracts_affected: + contracts_to_version_bump: + contracts_to_deprecate: + contracts_to_update_in_place: + + stories_affected: + stories_to_rebuild: # done or in-progress → needs-rebuild + stories_to_obsolete: + stories_to_update: # draft/ready → update-in-place + + done_stories_invalidated: # critical metric — shown prominently to user +``` + +### 2.6 Write Impact Analysis Report + +Write the analysis to `sdocs/replans/--analysis.md`: + +```markdown +--- +replan_slug: +phase: replan-step-2 +date: +diff_report: sdocs/replans/--diff.md +--- + +# Impact Analysis — + +## Summary + +- Requirements analyzed: N (M modified, K removed) +- Contracts affected: N (X version-bump, Y deprecate, Z update-in-place) +- Stories affected: N (X needs-rebuild, Y obsolete, Z update-in-place) +- **Done stories invalidated: N** ← user should pay attention to this + +## Dependency Graph Warnings + + + +## Requirement → Artifact Mapping + +### (modified|removed) + +**Matched contracts:** +| Contract | Match Type | Confidence | Current Status | Impact | +|----------|------------|------------|----------------|--------| +| | owner-story | high | stable | version-bump | + +**Matched stories:** +| Story | Relation | Current Status | Impact | +|-------|----------|----------------|--------| +| | producer | done | needs-rebuild | + +**Downstream (transitive):** +| Artifact | Type | Hops | Current Status | Impact | +|----------|------|------|----------------|--------| +| | story | 1 | ready | review-recommended | + +--- + +### + +--- + +## No-Impact Requirements + +| Requirement | Reason | +|-------------|--------| +| | constraint section — no implementing artifacts | + +## Full Impact Matrix + +| Artifact | Type | Current Status | Impact | Caused By | +|----------|------|----------------|--------|-----------| +| | contract | stable | version-bump | | +| | story | done | needs-rebuild | | +| ... | | | | | +``` + +--- + +## GATE — IMPACT ANALYSIS PASSES WHEN + +- [ ] Every `modified` or `removed` requirement from the diff report has at least one mapped artifact OR an explicit `no-impact` note with justification +- [ ] `unmapped` count is 0 — no requirement is left without a classification +- [ ] The dependency graph was built from ALL contracts in INDEX.md and ALL stories in `sdocs/stories/` +- [ ] Every affected artifact has exactly one impact classification (no ambiguous entries) +- [ ] Downstream impact chains are capped at 2 hops — anything beyond is flagged for manual review +- [ ] Impact analysis report written to `sdocs/replans/--analysis.md` +- [ ] Summary statistics are internally consistent (e.g. `contracts_affected = contracts_to_version_bump + contracts_to_deprecate + contracts_to_update_in_place`) + +--- + +## FAILURE MODES + +- **Missing contracts or stories:** If INDEX.md references a contract file that doesn't exist, or a story references a contract not in INDEX.md, record as a graph warning and continue — do not halt the entire analysis for one broken reference. +- **Requirement maps to zero artifacts:** Acceptable ONLY if an explicit `no-impact` note is provided. If the agent cannot determine why there's no impact, flag the requirement as `unmapped` and fail the gate. +- **Circular dependencies:** If the graph contains a cycle (story A consumes a contract produced by story B, which consumes a contract produced by story A), record the cycle as a warning and cap traversal at the cycle boundary. +- **Massive blast radius:** If `done_stories_invalidated` exceeds 50% of all done stories, append a warning recommending `plan --force` instead of replan. + +--- + +## NEXT + +→ Step 3: Per-Category Actions (`step-03-apply-changes.md`) + +Atlas passes the impact matrix to the next phase, which applies the classified actions: updating stories and contracts in place, bumping versions, setting statuses to `needs-rebuild` or `obsolete`, and deprecating contracts. The impact matrix is the authoritative input — Step 3 does not re-derive impact, it executes it. diff --git a/templates/_sam/core/workflows/replan/steps/step-02-impact-analysis.md b/templates/_sam/core/workflows/replan/steps/step-02-impact-analysis.md new file mode 100644 index 0000000..782ebfc --- /dev/null +++ b/templates/_sam/core/workflows/replan/steps/step-02-impact-analysis.md @@ -0,0 +1,269 @@ +--- +step: 2 +name: impact-analysis +description: Walk the produces/consumes graph to identify contracts and stories affected by each modified or removed requirement from the Step 1 diff +agents: [architect] +--- + +# Step 2: Impact Analysis on Contracts and Stories + +**Agent:** Atlas (System Architect) + +**Purpose:** For each `modified` or `removed` requirement identified in Step 1, walk the `produces`/`consumes` dependency graph to determine which contracts and stories are affected. The output is a structured impact matrix that drives all downstream decisions — which stories need rebuilding, which contracts need version bumps or deprecation, and which artifacts are untouched. + +--- + +## ENTRY CONDITIONS + +- Step 1 diff report exists at `sdocs/replans/--diff.md` +- Diff report contains at least one `modified` or `removed` section (otherwise skip to Step 5 — merge) +- `sdocs/contracts/INDEX.md` exists and is readable +- `sdocs/stories/` directory exists with at least one story file + +If any precondition fails, halt and tell the user which file or directory is missing. + +--- + +## REQUIRED READING + +Before any analysis: +- `sdocs/replans/--diff.md` — the structured diff from Step 1 (read in full) +- `sdocs/contracts/INDEX.md` — the contract index (read in full) +- Every contract file referenced in INDEX.md — at minimum read the frontmatter (`id`, `kind`, `status`, `owner_story`, `version`) +- Every story file in `sdocs/stories/` — at minimum read the frontmatter (`id`, `status`, `produces`, `consumes`, `depends_on`) +- `_sam/core/resources/contract-schema.md` — for understanding contract lifecycle rules +- `_sam/core/resources/story-schema.md` — for understanding story status transitions + +--- + +## PROCESS + +### 2.1 Build the Dependency Graph + +Construct an in-memory graph from story and contract frontmatter: + +```yaml +graph: + contracts: + - id: + kind: + status: + version: + producer: # from owner_story + consumers: [, ...] # stories whose consumes: list includes this contract + + stories: + - id: + status: + produces: [, ...] + consumes: [, ...] + depends_on: [, ...] +``` + +Every contract must appear exactly once as a node. Every story must appear exactly once. Cross-reference: +- For each story's `produces` list, the corresponding contract's `producer` field must point back to that story +- For each story's `consumes` list, that story must appear in the corresponding contract's `consumers` list + +Flag any inconsistencies (orphan contracts, dangling references) as warnings in the output — do not halt, but record them. + +### 2.2 Map Requirements to Contracts + +For each `modified` or `removed` requirement from the diff report, identify which contracts implement or relate to it: + +1. **By owner story:** Find stories whose `## User Story` or `## Acceptance Criteria` directly trace to the changed PRD section. Then collect those stories' `produces` contracts. +2. **By content match:** Scan contract bodies for references to the changed requirement (e.g. a contract's `## Shape` mentions the feature being modified). This catches contracts not yet linked to a story. +3. **By section-id mapping:** If the PRD sections use consistent naming (e.g. `## Feature: Tags`), match against story titles and contract titles. + +For each mapping, record the confidence level: + +```yaml +mappings: + - requirement: + classification: modified | removed + matched_contracts: + - contract: + match_type: owner-story | content-match | title-match + confidence: high | medium | low + matched_stories: + - story: + relation: producer | consumer | dependency +``` + +If a requirement maps to zero contracts and zero stories, record it as `no-impact` with a brief explanation (e.g. "this section is a constraint, not a feature — no artifacts implement it directly"). + +### 2.3 Walk Downstream Dependencies + +For each directly affected contract, trace its downstream impact: + +1. **Consumer stories:** Find all stories in the contract's `consumers` list +2. **Transitive dependencies:** For each consumer story, check if it `produces` contracts that are consumed by further stories. Walk one level deep (direct consumers of the affected contract, plus their immediate downstream). +3. **Do NOT walk indefinitely** — cap at two hops from the origin contract. Beyond that, flag as "possible transitive impact — manual review recommended." + +Record the full impact chain: + +```yaml +impact_chain: + - origin_contract: + origin_requirement: + directly_affected: + - artifact: + type: story | contract + current_status: + impact: needs-version-bump | needs-rebuild | needs-deprecation | needs-update + transitively_affected: + - artifact: + type: story | contract + hops: <1 | 2> + current_status: + impact: possible-rebuild | review-recommended +``` + +### 2.4 Classify Impact per Artifact + +For each affected artifact, assign an impact classification based on the requirement change type and the artifact's current status: + +**For contracts:** + +| Requirement Change | Contract Status | Impact Classification | +|---|---|---| +| modified | draft | `update-in-place` — edit contract body, no version bump | +| modified | stable | `version-bump` — bump version, update body | +| modified | deprecated | `no-action` — already deprecated, note in report | +| removed | draft | `deprecate` — set status to deprecated | +| removed | stable | `deprecate` — set status to deprecated | +| removed | deprecated | `no-action` — already deprecated | + +**For stories:** + +| Requirement Change | Story Status | Impact Classification | +|---|---|---| +| modified | draft or ready | `update-in-place` — edit story ACs and technical notes | +| modified | in-progress | `needs-rebuild` — mark status, keep partial code | +| modified | done | `needs-rebuild` — mark status, keep existing code | +| modified | blocked | `update-in-place` — update while already stalled | +| modified | needs-rebuild | `no-action` — already marked for rebuild | +| modified | obsolete | `no-action` — already retired | +| removed | draft or ready | `obsolete` — set status to obsolete | +| removed | in-progress | `obsolete` — set status to obsolete, keep code | +| removed | done | `obsolete` — set status to obsolete, keep code | +| removed | blocked | `obsolete` — set status to obsolete | +| removed | needs-rebuild | `obsolete` — set status to obsolete | +| removed | obsolete | `no-action` — already retired | + +### 2.5 Generate Impact Summary Statistics + +Produce counts for the impact gate: + +```yaml +impact_summary: + requirements_analyzed: # modified + removed from diff + with_mapped_artifacts: # requirements that map to at least one contract or story + with_no_impact: # requirements with explicit "no impact" note + unmapped: # should be 0 — gate fails if > 0 + + contracts_affected: + contracts_to_version_bump: + contracts_to_deprecate: + contracts_to_update_in_place: + + stories_affected: + stories_to_rebuild: # done or in-progress → needs-rebuild + stories_to_obsolete: + stories_to_update: # draft/ready → update-in-place + + done_stories_invalidated: # critical metric — shown prominently to user +``` + +### 2.6 Write Impact Analysis Report + +Write the analysis to `sdocs/replans/--analysis.md`: + +```markdown +--- +replan_slug: +phase: replan-step-2 +date: +diff_report: sdocs/replans/--diff.md +--- + +# Impact Analysis — + +## Summary + +- Requirements analyzed: N (M modified, K removed) +- Contracts affected: N (X version-bump, Y deprecate, Z update-in-place) +- Stories affected: N (X needs-rebuild, Y obsolete, Z update-in-place) +- **Done stories invalidated: N** ← user should pay attention to this + +## Dependency Graph Warnings + + + +## Requirement → Artifact Mapping + +### (modified|removed) + +**Matched contracts:** +| Contract | Match Type | Confidence | Current Status | Impact | +|----------|------------|------------|----------------|--------| +| | owner-story | high | stable | version-bump | + +**Matched stories:** +| Story | Relation | Current Status | Impact | +|-------|----------|----------------|--------| +| | producer | done | needs-rebuild | + +**Downstream (transitive):** +| Artifact | Type | Hops | Current Status | Impact | +|----------|------|------|----------------|--------| +| | story | 1 | ready | review-recommended | + +--- + +### + +--- + +## No-Impact Requirements + +| Requirement | Reason | +|-------------|--------| +| | constraint section — no implementing artifacts | + +## Full Impact Matrix + +| Artifact | Type | Current Status | Impact | Caused By | +|----------|------|----------------|--------|-----------| +| | contract | stable | version-bump | | +| | story | done | needs-rebuild | | +| ... | | | | | +``` + +--- + +## GATE — IMPACT ANALYSIS PASSES WHEN + +- [ ] Every `modified` or `removed` requirement from the diff report has at least one mapped artifact OR an explicit `no-impact` note with justification +- [ ] `unmapped` count is 0 — no requirement is left without a classification +- [ ] The dependency graph was built from ALL contracts in INDEX.md and ALL stories in `sdocs/stories/` +- [ ] Every affected artifact has exactly one impact classification (no ambiguous entries) +- [ ] Downstream impact chains are capped at 2 hops — anything beyond is flagged for manual review +- [ ] Impact analysis report written to `sdocs/replans/--analysis.md` +- [ ] Summary statistics are internally consistent (e.g. `contracts_affected = contracts_to_version_bump + contracts_to_deprecate + contracts_to_update_in_place`) + +--- + +## FAILURE MODES + +- **Missing contracts or stories:** If INDEX.md references a contract file that doesn't exist, or a story references a contract not in INDEX.md, record as a graph warning and continue — do not halt the entire analysis for one broken reference. +- **Requirement maps to zero artifacts:** Acceptable ONLY if an explicit `no-impact` note is provided. If the agent cannot determine why there's no impact, flag the requirement as `unmapped` and fail the gate. +- **Circular dependencies:** If the graph contains a cycle (story A consumes a contract produced by story B, which consumes a contract produced by story A), record the cycle as a warning and cap traversal at the cycle boundary. +- **Massive blast radius:** If `done_stories_invalidated` exceeds 50% of all done stories, append a warning recommending `plan --force` instead of replan. + +--- + +## NEXT + +→ Step 3: Per-Category Actions (`step-03-apply-changes.md`) + +Atlas passes the impact matrix to the next phase, which applies the classified actions: updating stories and contracts in place, bumping versions, setting statuses to `needs-rebuild` or `obsolete`, and deprecating contracts. The impact matrix is the authoritative input — Step 3 does not re-derive impact, it executes it. From 3bf75760441348599e13bdec5ec0a4cbb0d707c4 Mon Sep 17 00:00:00 2001 From: "sam-cloud-app[bot]" <252427705+sam-cloud-app[bot]@users.noreply.github.com> Date: Sat, 16 May 2026 10:46:09 +0000 Subject: [PATCH 07/11] =?UTF-8?q?Task=206/11:=20Write=20Step=203=20?= =?UTF-8?q?=E2=80=94=20Impact=20summary=20gate=20(user=20confirmation)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../replan/steps/step-03-impact-gate.md | 211 ++++++++++++++++++ .../replan/steps/step-03-impact-gate.md | 211 ++++++++++++++++++ 2 files changed, 422 insertions(+) create mode 100644 _sam/core/workflows/replan/steps/step-03-impact-gate.md create mode 100644 templates/_sam/core/workflows/replan/steps/step-03-impact-gate.md diff --git a/_sam/core/workflows/replan/steps/step-03-impact-gate.md b/_sam/core/workflows/replan/steps/step-03-impact-gate.md new file mode 100644 index 0000000..2232ee5 --- /dev/null +++ b/_sam/core/workflows/replan/steps/step-03-impact-gate.md @@ -0,0 +1,211 @@ +--- +step: 3 +name: impact-gate +description: Present the impact summary to the user and require explicit confirmation before applying any changes to contracts or stories +agents: [architect] +--- + +# Step 3: Impact Summary Gate (User Confirmation) + +**Agent:** Atlas (System Architect) + +**Purpose:** Present a human-readable impact summary derived from the Step 2 analysis report and require explicit user confirmation before any file modifications occur. This is the safety net — if the user declines, the workflow halts cleanly with zero side effects. + +--- + +## ENTRY CONDITIONS + +- Step 2 impact analysis report exists at `sdocs/replans/--analysis.md` +- The analysis report contains a valid `impact_summary` section with all required counts +- No file modifications have been made yet — Steps 1 and 2 are read-only analysis steps + +If the analysis report is missing or malformed, halt with an error directing the user to re-run Step 2. + +--- + +## REQUIRED READING + +Before presenting the summary: +- `sdocs/replans/--analysis.md` — the full impact analysis from Step 2 (read in full) +- The `impact_summary` section specifically — extract all counts +- The `Full Impact Matrix` section — needed for the detailed breakdown + +--- + +## PROCESS + +### 3.1 Extract Impact Counts + +Read the impact summary statistics from the Step 2 analysis report and validate internal consistency: + +```yaml +counts: + contracts_affected: + contracts_to_version_bump: + contracts_to_deprecate: + contracts_to_update_in_place: + + stories_affected: + stories_to_rebuild: # done/in-progress → needs-rebuild + stories_to_obsolete: + stories_to_update: # draft/ready → update-in-place + + done_stories_invalidated: # critical — prominently highlighted + new_stories_to_create: # from added requirements + new_contracts_to_create: # from added requirements +``` + +Verify that: +- `contracts_affected = contracts_to_version_bump + contracts_to_deprecate + contracts_to_update_in_place` +- `stories_affected = stories_to_rebuild + stories_to_obsolete + stories_to_update` + +If counts are inconsistent, halt and report the discrepancy — do not present a misleading summary. + +### 3.2 Format the Impact Summary + +Present the summary to the user in this exact format: + +``` +═══════════════════════════════════════════════════════ + REPLAN IMPACT SUMMARY — +═══════════════════════════════════════════════════════ + + Contracts + Version bump: (stable contracts with modified requirements) + Deprecate: (contracts tied to removed requirements) + Update in place: (draft contracts — no version bump needed) + New: (from added requirements) + + Stories + Mark needs-rebuild: (done/in-progress stories to revisit) + Mark obsolete: (stories tied to removed requirements) + Update in place: (draft/ready stories — edit ACs and notes) + New: (from added requirements) + + ⚠ Done stories invalidated: + These stories were previously completed and will require + a build-tdd pass after replan completes. + +═══════════════════════════════════════════════════════ +``` + +If `done_stories_invalidated > 0`, also list the specific story IDs and their current titles: + +``` + Stories requiring rebuild: + - STORY-003: (done → needs-rebuild) + - STORY-007: <title> (done → needs-rebuild) +``` + +If `stories_to_obsolete > 0`, list the specific stories being retired: + +``` + Stories being retired: + - STORY-005: <title> (→ obsolete, code preserved) + - STORY-009: <title> (→ obsolete, code preserved) +``` + +If `contracts_to_deprecate > 0`, list the contracts being deprecated: + +``` + Contracts being deprecated: + - CONTRACT-<id>: <title> (→ deprecated, body preserved) +``` + +### 3.3 Check for High-Impact Warning + +If the Step 2 analysis flagged a massive blast radius (>50% of done stories invalidated), repeat the warning prominently: + +``` + ⚠⚠ HIGH IMPACT WARNING ⚠⚠ + More than 50% of completed stories will be invalidated. + Consider using `plan --force` for a full rebuild instead. +``` + +### 3.4 Prompt for Confirmation + +After the summary, present the user with an explicit choice: + +``` + This replan will modify the files listed above. + No code will be deleted — only metadata (status fields) will change. + + Options: + proceed — apply all changes listed above + abort — halt replan with no file modifications + detail — show the full impact matrix before deciding +``` + +**Handling each response:** + +- **`proceed`**: Record the confirmation and advance to Step 4. Log: + ``` + ✓ User confirmed replan. Proceeding to apply changes. + ``` + +- **`abort`**: Halt the workflow immediately. Print: + ``` + Replan aborted by user. No files were modified. + The impact analysis is preserved at: + sdocs/replans/<YYYY-MM-DD>-<slug>-analysis.md + + To re-run with a different revised PRD: + /sam:core:workflows:replan <new-revised-prd.md> + + To apply this replan without the gate: + /sam:core:workflows:replan <revised-prd.md> --force + ``` + Exit with zero side effects. The analysis file from Steps 1–2 remains as documentation. + +- **`detail`**: Display the full `Full Impact Matrix` table from the analysis report. Then re-prompt the same `proceed / abort` choice (no recursive `detail` — show it once). + +### 3.5 Handle --force Flag + +If the workflow was invoked with `--force`: +- Still print the impact summary (for the log / audit trail) +- Skip the confirmation prompt +- Log: `--force flag set. Skipping confirmation gate.` +- Proceed directly to Step 4 + +### 3.6 Record Gate Outcome + +Append the gate outcome to the analysis report: + +```markdown +## Gate 3: User Confirmation + +- **Date:** <timestamp> +- **Outcome:** confirmed | aborted | force-skipped +- **Done stories invalidated:** <N> +- **User response:** <proceed | abort | --force> +``` + +This creates an audit trail of whether the user explicitly approved the changes. + +--- + +## GATE — IMPACT GATE PASSES WHEN + +- [ ] Impact summary was presented to the user with all counts from Step 2 +- [ ] Counts are internally consistent (verified before display) +- [ ] User explicitly responded `proceed` OR `--force` flag was set +- [ ] If user responded `abort`, workflow halted with zero file modifications +- [ ] Gate outcome is appended to the analysis report +- [ ] No files outside `sdocs/replans/` were modified during this step + +--- + +## FAILURE MODES + +- **Missing analysis report:** Halt with error — cannot present a summary without data. Direct user to re-run from Step 1. +- **Inconsistent counts:** Halt with error showing the inconsistency. Do not present a misleading summary. Direct user to re-run Step 2. +- **User does not respond:** In non-interactive contexts, treat as `abort`. Never default to `proceed` — confirmation must be explicit. +- **Unexpected input:** If the user responds with something other than `proceed`, `abort`, or `detail`, re-prompt once with the valid options. If the second response is also unrecognized, treat as `abort` and halt safely. + +--- + +## NEXT + +→ Step 4: Apply Per-Category Changes (`step-04-apply-changes.md`) + +Once the user confirms, Atlas proceeds to apply the classified actions from the impact matrix: updating stories and contracts in place, bumping versions, setting statuses to `needs-rebuild` or `obsolete`, and deprecating contracts. The impact matrix from Step 2 is the authoritative input — Step 4 does not re-derive impact, it executes it. diff --git a/templates/_sam/core/workflows/replan/steps/step-03-impact-gate.md b/templates/_sam/core/workflows/replan/steps/step-03-impact-gate.md new file mode 100644 index 0000000..2232ee5 --- /dev/null +++ b/templates/_sam/core/workflows/replan/steps/step-03-impact-gate.md @@ -0,0 +1,211 @@ +--- +step: 3 +name: impact-gate +description: Present the impact summary to the user and require explicit confirmation before applying any changes to contracts or stories +agents: [architect] +--- + +# Step 3: Impact Summary Gate (User Confirmation) + +**Agent:** Atlas (System Architect) + +**Purpose:** Present a human-readable impact summary derived from the Step 2 analysis report and require explicit user confirmation before any file modifications occur. This is the safety net — if the user declines, the workflow halts cleanly with zero side effects. + +--- + +## ENTRY CONDITIONS + +- Step 2 impact analysis report exists at `sdocs/replans/<YYYY-MM-DD>-<slug>-analysis.md` +- The analysis report contains a valid `impact_summary` section with all required counts +- No file modifications have been made yet — Steps 1 and 2 are read-only analysis steps + +If the analysis report is missing or malformed, halt with an error directing the user to re-run Step 2. + +--- + +## REQUIRED READING + +Before presenting the summary: +- `sdocs/replans/<YYYY-MM-DD>-<slug>-analysis.md` — the full impact analysis from Step 2 (read in full) +- The `impact_summary` section specifically — extract all counts +- The `Full Impact Matrix` section — needed for the detailed breakdown + +--- + +## PROCESS + +### 3.1 Extract Impact Counts + +Read the impact summary statistics from the Step 2 analysis report and validate internal consistency: + +```yaml +counts: + contracts_affected: <N> + contracts_to_version_bump: <N> + contracts_to_deprecate: <N> + contracts_to_update_in_place: <N> + + stories_affected: <N> + stories_to_rebuild: <N> # done/in-progress → needs-rebuild + stories_to_obsolete: <N> + stories_to_update: <N> # draft/ready → update-in-place + + done_stories_invalidated: <N> # critical — prominently highlighted + new_stories_to_create: <N> # from added requirements + new_contracts_to_create: <N> # from added requirements +``` + +Verify that: +- `contracts_affected = contracts_to_version_bump + contracts_to_deprecate + contracts_to_update_in_place` +- `stories_affected = stories_to_rebuild + stories_to_obsolete + stories_to_update` + +If counts are inconsistent, halt and report the discrepancy — do not present a misleading summary. + +### 3.2 Format the Impact Summary + +Present the summary to the user in this exact format: + +``` +═══════════════════════════════════════════════════════ + REPLAN IMPACT SUMMARY — <slug> +═══════════════════════════════════════════════════════ + + Contracts + Version bump: <N> (stable contracts with modified requirements) + Deprecate: <N> (contracts tied to removed requirements) + Update in place: <N> (draft contracts — no version bump needed) + New: <N> (from added requirements) + + Stories + Mark needs-rebuild: <N> (done/in-progress stories to revisit) + Mark obsolete: <N> (stories tied to removed requirements) + Update in place: <N> (draft/ready stories — edit ACs and notes) + New: <N> (from added requirements) + + ⚠ Done stories invalidated: <N> + These stories were previously completed and will require + a build-tdd pass after replan completes. + +═══════════════════════════════════════════════════════ +``` + +If `done_stories_invalidated > 0`, also list the specific story IDs and their current titles: + +``` + Stories requiring rebuild: + - STORY-003: <title> (done → needs-rebuild) + - STORY-007: <title> (done → needs-rebuild) +``` + +If `stories_to_obsolete > 0`, list the specific stories being retired: + +``` + Stories being retired: + - STORY-005: <title> (→ obsolete, code preserved) + - STORY-009: <title> (→ obsolete, code preserved) +``` + +If `contracts_to_deprecate > 0`, list the contracts being deprecated: + +``` + Contracts being deprecated: + - CONTRACT-<id>: <title> (→ deprecated, body preserved) +``` + +### 3.3 Check for High-Impact Warning + +If the Step 2 analysis flagged a massive blast radius (>50% of done stories invalidated), repeat the warning prominently: + +``` + ⚠⚠ HIGH IMPACT WARNING ⚠⚠ + More than 50% of completed stories will be invalidated. + Consider using `plan --force` for a full rebuild instead. +``` + +### 3.4 Prompt for Confirmation + +After the summary, present the user with an explicit choice: + +``` + This replan will modify the files listed above. + No code will be deleted — only metadata (status fields) will change. + + Options: + proceed — apply all changes listed above + abort — halt replan with no file modifications + detail — show the full impact matrix before deciding +``` + +**Handling each response:** + +- **`proceed`**: Record the confirmation and advance to Step 4. Log: + ``` + ✓ User confirmed replan. Proceeding to apply changes. + ``` + +- **`abort`**: Halt the workflow immediately. Print: + ``` + Replan aborted by user. No files were modified. + The impact analysis is preserved at: + sdocs/replans/<YYYY-MM-DD>-<slug>-analysis.md + + To re-run with a different revised PRD: + /sam:core:workflows:replan <new-revised-prd.md> + + To apply this replan without the gate: + /sam:core:workflows:replan <revised-prd.md> --force + ``` + Exit with zero side effects. The analysis file from Steps 1–2 remains as documentation. + +- **`detail`**: Display the full `Full Impact Matrix` table from the analysis report. Then re-prompt the same `proceed / abort` choice (no recursive `detail` — show it once). + +### 3.5 Handle --force Flag + +If the workflow was invoked with `--force`: +- Still print the impact summary (for the log / audit trail) +- Skip the confirmation prompt +- Log: `--force flag set. Skipping confirmation gate.` +- Proceed directly to Step 4 + +### 3.6 Record Gate Outcome + +Append the gate outcome to the analysis report: + +```markdown +## Gate 3: User Confirmation + +- **Date:** <timestamp> +- **Outcome:** confirmed | aborted | force-skipped +- **Done stories invalidated:** <N> +- **User response:** <proceed | abort | --force> +``` + +This creates an audit trail of whether the user explicitly approved the changes. + +--- + +## GATE — IMPACT GATE PASSES WHEN + +- [ ] Impact summary was presented to the user with all counts from Step 2 +- [ ] Counts are internally consistent (verified before display) +- [ ] User explicitly responded `proceed` OR `--force` flag was set +- [ ] If user responded `abort`, workflow halted with zero file modifications +- [ ] Gate outcome is appended to the analysis report +- [ ] No files outside `sdocs/replans/` were modified during this step + +--- + +## FAILURE MODES + +- **Missing analysis report:** Halt with error — cannot present a summary without data. Direct user to re-run from Step 1. +- **Inconsistent counts:** Halt with error showing the inconsistency. Do not present a misleading summary. Direct user to re-run Step 2. +- **User does not respond:** In non-interactive contexts, treat as `abort`. Never default to `proceed` — confirmation must be explicit. +- **Unexpected input:** If the user responds with something other than `proceed`, `abort`, or `detail`, re-prompt once with the valid options. If the second response is also unrecognized, treat as `abort` and halt safely. + +--- + +## NEXT + +→ Step 4: Apply Per-Category Changes (`step-04-apply-changes.md`) + +Once the user confirms, Atlas proceeds to apply the classified actions from the impact matrix: updating stories and contracts in place, bumping versions, setting statuses to `needs-rebuild` or `obsolete`, and deprecating contracts. The impact matrix from Step 2 is the authoritative input — Step 4 does not re-derive impact, it executes it. From 317ba0310f3fb2fa258ed50dd95f26ca9ebe034b Mon Sep 17 00:00:00 2001 From: "sam-cloud-app[bot]" <252427705+sam-cloud-app[bot]@users.noreply.github.com> Date: Sat, 16 May 2026 10:47:56 +0000 Subject: [PATCH 08/11] =?UTF-8?q?Task=207/11:=20Write=20Step=204=20?= =?UTF-8?q?=E2=80=94=20Apply=20per-category=20changes=20to=20contracts=20a?= =?UTF-8?q?nd=20stories?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com> --- .../replan/steps/step-04-apply-changes.md | 237 ++++++++++++++++++ .../replan/steps/step-04-apply-changes.md | 237 ++++++++++++++++++ 2 files changed, 474 insertions(+) create mode 100644 _sam/core/workflows/replan/steps/step-04-apply-changes.md create mode 100644 templates/_sam/core/workflows/replan/steps/step-04-apply-changes.md diff --git a/_sam/core/workflows/replan/steps/step-04-apply-changes.md b/_sam/core/workflows/replan/steps/step-04-apply-changes.md new file mode 100644 index 0000000..5fde769 --- /dev/null +++ b/_sam/core/workflows/replan/steps/step-04-apply-changes.md @@ -0,0 +1,237 @@ +--- +step: 4 +name: apply-changes +description: Execute per-category artifact changes (added, modified-unbuilt, modified-done, removed) based on the confirmed impact analysis +agents: [architect] +--- + +# Step 4: Apply Per-Category Changes to Contracts and Stories + +**Agent:** Atlas (System Architect) + +**Purpose:** Execute the actual artifact changes based on the confirmed impact analysis from Step 2 and the user confirmation from Step 3. Each change category (added, modified-unbuilt, modified-done, removed) has distinct handling rules. This step modifies files — it is the first step in the pipeline that writes to `sdocs/contracts/` and `sdocs/stories/`. + +--- + +## ENTRY CONDITIONS + +- Step 3 gate passed — user confirmed `proceed` OR `--force` flag was set +- Step 2 impact analysis report exists at `sdocs/replans/<YYYY-MM-DD>-<slug>-analysis.md` +- The analysis report contains a valid `Full Impact Matrix` section with per-artifact actions +- `sdocs/contracts/INDEX.md` exists and is readable +- `sdocs/stories/` directory exists with at least one story file +- `sdocs/replans/<YYYY-MM-DD>-<slug>-diff.md` exists (for added section details) + +If any precondition fails, halt and tell the user which file is missing. Do NOT attempt partial application. + +--- + +## REQUIRED READING + +Before applying any changes: +- `sdocs/replans/<YYYY-MM-DD>-<slug>-analysis.md` — the full impact matrix (authoritative input for this step) +- `sdocs/replans/<YYYY-MM-DD>-<slug>-diff.md` — the PRD diff (needed for added section details) +- `sdocs/contracts/INDEX.md` — current contract registry +- Each contract and story file listed in the impact matrix — read before modifying + +--- + +## PROCESS + +### 4.1 Category: ADDED Requirements + +For each requirement classified as `added` in the Step 1 diff, behave identically to the `extend` workflow: + +**Contracts:** +- Create new contract files in `sdocs/contracts/` following the standard contract template +- Set status to `draft` +- Assign the next available contract ID (check INDEX.md for the current highest ID) +- Fill in `produces` and `consumes` fields based on the added requirement's scope +- Add the new contract to `sdocs/contracts/INDEX.md` + +**Stories:** +- Create new story files in `sdocs/stories/` following the standard story template +- Set status to `ready` +- Link to the newly created contracts via `produces` and `consumes` fields +- Derive acceptance criteria directly from the added PRD section +- Append new stories to the relevant epic file (or create a new epic if the added requirement is a standalone feature) +- Assign the next available story ID (check existing stories for the current highest ID) + +**Validation for added:** +- [ ] Each added requirement has at least one contract created +- [ ] Each added requirement has at least one story created +- [ ] All new contracts are registered in INDEX.md +- [ ] All new stories reference their contracts in `produces`/`consumes` +- [ ] New story IDs do not collide with existing IDs + +--- + +### 4.2 Category: MODIFIED — Story Not Yet Built + +For requirements classified as `modified` where the associated stories have status `draft`, `ready`, or `blocked` (i.e., no code has been written yet): + +**Contracts:** +- If the contract is in `draft` status: update the contract file in place. No version bump needed — drafts are mutable. +- If the contract is in `stable` status: bump the `version` field (e.g., `1.0.0` → `1.1.0` for additive changes, `2.0.0` for breaking changes). Add a changelog entry to the contract file noting what changed and why. +- Update the contract body (fields, endpoints, interfaces) to reflect the modified requirement +- Update `sdocs/contracts/INDEX.md` if the contract description changed + +**Stories:** +- Update the story file in place: + - Revise acceptance criteria to match the modified requirement + - Update the `produces`/`consumes` references if contract IDs or versions changed + - Add a note in the story's changelog section: `[replan <date>] ACs updated per revised PRD` +- Do NOT change the story status — it remains `draft`/`ready`/`blocked` as before +- If the story's `depends_on` references changed contracts, verify the dependency still resolves + +**Validation for modified-unbuilt:** +- [ ] Each affected contract has its body updated to reflect the new requirement text +- [ ] Stable contracts received a version bump; draft contracts were updated in place +- [ ] Each affected story has revised acceptance criteria +- [ ] Story `produces`/`consumes` references point to correct contract versions +- [ ] No story status was changed (remains draft/ready/blocked) + +--- + +### 4.3 Category: MODIFIED — Story Done or In-Progress + +For requirements classified as `modified` where the associated stories have status `done` or `in-progress` (i.e., code exists for this story): + +**Contracts:** +- Bump the contract `version` field: + - Minor bump (`1.0.0` → `1.1.0`) if the change is additive (new fields, relaxed constraints) + - Major bump (`1.0.0` → `2.0.0`) if the change is breaking (removed fields, tightened constraints, changed types) +- Add a changelog entry: `[replan <date>] <description of change>. Stories marked needs-rebuild.` +- Update the contract body to reflect the modified requirement +- Do NOT change the contract status — it remains `stable` + +**Stories:** +- Set story status to `needs-rebuild` +- Add a changelog entry: `[replan <date>] Status changed to needs-rebuild. Requirement modified: <brief description>` +- Update the acceptance criteria to reflect the new requirement (so the rebuild targets the correct behavior) +- Update `produces`/`consumes` references to point to the new contract version +- Preserve all existing fields (implementation notes, code references, etc.) — do NOT delete any information about the existing implementation +- Do NOT modify or delete any code files — only story metadata changes + +**Important:** The `needs-rebuild` status signals to the `build-tdd` workflow that this story needs a new TDD pass. The existing code is preserved as-is until the user explicitly triggers a rebuild. + +**Validation for modified-done:** +- [ ] Each affected contract received a version bump (minor or major as appropriate) +- [ ] Each affected story status is now `needs-rebuild` +- [ ] Story acceptance criteria reflect the NEW requirement (not the old one) +- [ ] Existing implementation notes and code references are preserved in the story file +- [ ] No code files were modified or deleted +- [ ] Contract changelog documents the change and references the replan + +--- + +### 4.4 Category: REMOVED Requirements + +For requirements classified as `removed` in the Step 1 diff: + +**Contracts:** +- Set contract status to `deprecated` +- Add a `deprecated_date` field with today's date +- Add a `deprecated_reason` field: `Requirement removed in replan <YYYY-MM-DD>-<slug>` +- Add a changelog entry: `[replan <date>] Deprecated — requirement removed from PRD` +- Do NOT delete the contract file — it remains as documentation +- Do NOT remove the contract from INDEX.md — update its status column to `deprecated` + +**Stories:** +- Set story status to `obsolete` +- Add a changelog entry: `[replan <date>] Status changed to obsolete. Requirement removed from PRD.` +- Do NOT delete the story file — it remains as documentation +- Do NOT modify or delete any code files associated with the story +- If the story has `produces` contracts that are ONLY consumed by other obsolete stories, note this in the changelog (orphan detection) + +**Important constraints:** +- Never delete files during a replan. Deprecated/obsolete artifacts serve as documentation of what existed and why it was removed. +- Never modify code automatically when a requirement is removed. The user decides when and how to clean up implementation artifacts. + +**Validation for removed:** +- [ ] Each affected contract status is now `deprecated` +- [ ] Each affected contract has `deprecated_date` and `deprecated_reason` fields +- [ ] Each affected story status is now `obsolete` +- [ ] No files were deleted (contracts or stories) +- [ ] No code files were modified or deleted +- [ ] INDEX.md reflects the `deprecated` status for affected contracts + +--- + +## 4.5 Update INDEX.md + +After all per-category changes are applied, regenerate the summary sections of `sdocs/contracts/INDEX.md`: + +- Update status for modified contracts (version bumps) +- Update status for deprecated contracts +- Add entries for newly created contracts +- Verify the total contract count matches the number of contract files + +--- + +## 4.6 Validate Dependency Graph + +After all changes are applied, perform a consistency check on the `depends_on` / `produces` / `consumes` graph: + +1. **No dangling references:** Every contract ID referenced in a story's `produces`/`consumes` must exist in `sdocs/contracts/` +2. **No orphaned active contracts:** Every non-deprecated contract should be referenced by at least one non-obsolete story (warn if not — do not halt) +3. **Acyclic check:** Walk the `depends_on` graph across stories. If a cycle is detected, halt and report the cycle — do not proceed to Step 5 +4. **Version consistency:** If a story references a contract, it must reference the current version (not a stale version left over from before the replan) + +If validation fails on items 1, 3, or 4: halt with a detailed error. These are structural problems that must be fixed before proceeding. +If validation fails on item 2 (orphaned contracts): log a warning but continue — orphaned contracts may be consumed by future stories. + +--- + +## 4.7 Write Application Log + +Append the application results to the analysis report (`sdocs/replans/<YYYY-MM-DD>-<slug>-analysis.md`): + +```markdown +## Step 4: Changes Applied + +- **Date:** <timestamp> +- **Contracts created:** <N> +- **Contracts version-bumped:** <N> +- **Contracts deprecated:** <N> +- **Contracts updated in place:** <N> +- **Stories created:** <N> +- **Stories marked needs-rebuild:** <N> +- **Stories marked obsolete:** <N> +- **Stories updated in place:** <N> +- **Dependency graph valid:** yes | no (with details) +- **Warnings:** <any non-fatal issues> +``` + +--- + +## GATE — APPLY CHANGES PASSES WHEN + +- [ ] All `added` requirements have new contracts (status: `draft`) and new stories (status: `ready`) +- [ ] All `modified-unbuilt` stories have updated ACs; their contracts are updated (version-bumped if stable, edited in place if draft) +- [ ] All `modified-done` stories are now status `needs-rebuild`; their contracts are version-bumped with changelog entries +- [ ] All `removed` stories are now status `obsolete`; their contracts are status `deprecated` with `deprecated_date` and `deprecated_reason` +- [ ] No files were deleted during this step +- [ ] No code files were modified during this step (only `sdocs/` artifacts) +- [ ] `sdocs/contracts/INDEX.md` is updated and accurate +- [ ] Dependency graph passes: no dangling references, no cycles, version references are current +- [ ] Application log appended to the analysis report + +--- + +## FAILURE MODES + +- **Missing analysis report or gate not passed:** Halt immediately. Step 4 must never run without Step 3 confirmation. +- **Contract ID collision:** If a new contract ID would collide with an existing one, increment until a unique ID is found. Log the collision. +- **Story ID collision:** Same as contract — increment until unique. Log the collision. +- **Cycle detected in dependency graph:** Halt and report the full cycle path. The user must resolve the cycle before the replan can continue. Suggest which `depends_on` edge to remove. +- **Stale version reference:** If a story references an old contract version after the replan applied a bump, fix the reference automatically and log it as a correction. +- **File write failure:** If any file cannot be written, halt immediately and report which files were successfully updated and which failed. Do not leave the system in a partially-applied state — roll back all changes in the current category if possible. + +--- + +## NEXT + +→ Step 5: Merge Revised PRD (`step-05-merge-prd.md`) + +With all contracts and stories updated, Atlas merges the revised PRD into `sdocs/prd.md` with a changelog entry, completing the replan pipeline. The merged PRD becomes the new source of truth for subsequent `build-tdd` passes on `needs-rebuild` stories. diff --git a/templates/_sam/core/workflows/replan/steps/step-04-apply-changes.md b/templates/_sam/core/workflows/replan/steps/step-04-apply-changes.md new file mode 100644 index 0000000..5fde769 --- /dev/null +++ b/templates/_sam/core/workflows/replan/steps/step-04-apply-changes.md @@ -0,0 +1,237 @@ +--- +step: 4 +name: apply-changes +description: Execute per-category artifact changes (added, modified-unbuilt, modified-done, removed) based on the confirmed impact analysis +agents: [architect] +--- + +# Step 4: Apply Per-Category Changes to Contracts and Stories + +**Agent:** Atlas (System Architect) + +**Purpose:** Execute the actual artifact changes based on the confirmed impact analysis from Step 2 and the user confirmation from Step 3. Each change category (added, modified-unbuilt, modified-done, removed) has distinct handling rules. This step modifies files — it is the first step in the pipeline that writes to `sdocs/contracts/` and `sdocs/stories/`. + +--- + +## ENTRY CONDITIONS + +- Step 3 gate passed — user confirmed `proceed` OR `--force` flag was set +- Step 2 impact analysis report exists at `sdocs/replans/<YYYY-MM-DD>-<slug>-analysis.md` +- The analysis report contains a valid `Full Impact Matrix` section with per-artifact actions +- `sdocs/contracts/INDEX.md` exists and is readable +- `sdocs/stories/` directory exists with at least one story file +- `sdocs/replans/<YYYY-MM-DD>-<slug>-diff.md` exists (for added section details) + +If any precondition fails, halt and tell the user which file is missing. Do NOT attempt partial application. + +--- + +## REQUIRED READING + +Before applying any changes: +- `sdocs/replans/<YYYY-MM-DD>-<slug>-analysis.md` — the full impact matrix (authoritative input for this step) +- `sdocs/replans/<YYYY-MM-DD>-<slug>-diff.md` — the PRD diff (needed for added section details) +- `sdocs/contracts/INDEX.md` — current contract registry +- Each contract and story file listed in the impact matrix — read before modifying + +--- + +## PROCESS + +### 4.1 Category: ADDED Requirements + +For each requirement classified as `added` in the Step 1 diff, behave identically to the `extend` workflow: + +**Contracts:** +- Create new contract files in `sdocs/contracts/` following the standard contract template +- Set status to `draft` +- Assign the next available contract ID (check INDEX.md for the current highest ID) +- Fill in `produces` and `consumes` fields based on the added requirement's scope +- Add the new contract to `sdocs/contracts/INDEX.md` + +**Stories:** +- Create new story files in `sdocs/stories/` following the standard story template +- Set status to `ready` +- Link to the newly created contracts via `produces` and `consumes` fields +- Derive acceptance criteria directly from the added PRD section +- Append new stories to the relevant epic file (or create a new epic if the added requirement is a standalone feature) +- Assign the next available story ID (check existing stories for the current highest ID) + +**Validation for added:** +- [ ] Each added requirement has at least one contract created +- [ ] Each added requirement has at least one story created +- [ ] All new contracts are registered in INDEX.md +- [ ] All new stories reference their contracts in `produces`/`consumes` +- [ ] New story IDs do not collide with existing IDs + +--- + +### 4.2 Category: MODIFIED — Story Not Yet Built + +For requirements classified as `modified` where the associated stories have status `draft`, `ready`, or `blocked` (i.e., no code has been written yet): + +**Contracts:** +- If the contract is in `draft` status: update the contract file in place. No version bump needed — drafts are mutable. +- If the contract is in `stable` status: bump the `version` field (e.g., `1.0.0` → `1.1.0` for additive changes, `2.0.0` for breaking changes). Add a changelog entry to the contract file noting what changed and why. +- Update the contract body (fields, endpoints, interfaces) to reflect the modified requirement +- Update `sdocs/contracts/INDEX.md` if the contract description changed + +**Stories:** +- Update the story file in place: + - Revise acceptance criteria to match the modified requirement + - Update the `produces`/`consumes` references if contract IDs or versions changed + - Add a note in the story's changelog section: `[replan <date>] ACs updated per revised PRD` +- Do NOT change the story status — it remains `draft`/`ready`/`blocked` as before +- If the story's `depends_on` references changed contracts, verify the dependency still resolves + +**Validation for modified-unbuilt:** +- [ ] Each affected contract has its body updated to reflect the new requirement text +- [ ] Stable contracts received a version bump; draft contracts were updated in place +- [ ] Each affected story has revised acceptance criteria +- [ ] Story `produces`/`consumes` references point to correct contract versions +- [ ] No story status was changed (remains draft/ready/blocked) + +--- + +### 4.3 Category: MODIFIED — Story Done or In-Progress + +For requirements classified as `modified` where the associated stories have status `done` or `in-progress` (i.e., code exists for this story): + +**Contracts:** +- Bump the contract `version` field: + - Minor bump (`1.0.0` → `1.1.0`) if the change is additive (new fields, relaxed constraints) + - Major bump (`1.0.0` → `2.0.0`) if the change is breaking (removed fields, tightened constraints, changed types) +- Add a changelog entry: `[replan <date>] <description of change>. Stories marked needs-rebuild.` +- Update the contract body to reflect the modified requirement +- Do NOT change the contract status — it remains `stable` + +**Stories:** +- Set story status to `needs-rebuild` +- Add a changelog entry: `[replan <date>] Status changed to needs-rebuild. Requirement modified: <brief description>` +- Update the acceptance criteria to reflect the new requirement (so the rebuild targets the correct behavior) +- Update `produces`/`consumes` references to point to the new contract version +- Preserve all existing fields (implementation notes, code references, etc.) — do NOT delete any information about the existing implementation +- Do NOT modify or delete any code files — only story metadata changes + +**Important:** The `needs-rebuild` status signals to the `build-tdd` workflow that this story needs a new TDD pass. The existing code is preserved as-is until the user explicitly triggers a rebuild. + +**Validation for modified-done:** +- [ ] Each affected contract received a version bump (minor or major as appropriate) +- [ ] Each affected story status is now `needs-rebuild` +- [ ] Story acceptance criteria reflect the NEW requirement (not the old one) +- [ ] Existing implementation notes and code references are preserved in the story file +- [ ] No code files were modified or deleted +- [ ] Contract changelog documents the change and references the replan + +--- + +### 4.4 Category: REMOVED Requirements + +For requirements classified as `removed` in the Step 1 diff: + +**Contracts:** +- Set contract status to `deprecated` +- Add a `deprecated_date` field with today's date +- Add a `deprecated_reason` field: `Requirement removed in replan <YYYY-MM-DD>-<slug>` +- Add a changelog entry: `[replan <date>] Deprecated — requirement removed from PRD` +- Do NOT delete the contract file — it remains as documentation +- Do NOT remove the contract from INDEX.md — update its status column to `deprecated` + +**Stories:** +- Set story status to `obsolete` +- Add a changelog entry: `[replan <date>] Status changed to obsolete. Requirement removed from PRD.` +- Do NOT delete the story file — it remains as documentation +- Do NOT modify or delete any code files associated with the story +- If the story has `produces` contracts that are ONLY consumed by other obsolete stories, note this in the changelog (orphan detection) + +**Important constraints:** +- Never delete files during a replan. Deprecated/obsolete artifacts serve as documentation of what existed and why it was removed. +- Never modify code automatically when a requirement is removed. The user decides when and how to clean up implementation artifacts. + +**Validation for removed:** +- [ ] Each affected contract status is now `deprecated` +- [ ] Each affected contract has `deprecated_date` and `deprecated_reason` fields +- [ ] Each affected story status is now `obsolete` +- [ ] No files were deleted (contracts or stories) +- [ ] No code files were modified or deleted +- [ ] INDEX.md reflects the `deprecated` status for affected contracts + +--- + +## 4.5 Update INDEX.md + +After all per-category changes are applied, regenerate the summary sections of `sdocs/contracts/INDEX.md`: + +- Update status for modified contracts (version bumps) +- Update status for deprecated contracts +- Add entries for newly created contracts +- Verify the total contract count matches the number of contract files + +--- + +## 4.6 Validate Dependency Graph + +After all changes are applied, perform a consistency check on the `depends_on` / `produces` / `consumes` graph: + +1. **No dangling references:** Every contract ID referenced in a story's `produces`/`consumes` must exist in `sdocs/contracts/` +2. **No orphaned active contracts:** Every non-deprecated contract should be referenced by at least one non-obsolete story (warn if not — do not halt) +3. **Acyclic check:** Walk the `depends_on` graph across stories. If a cycle is detected, halt and report the cycle — do not proceed to Step 5 +4. **Version consistency:** If a story references a contract, it must reference the current version (not a stale version left over from before the replan) + +If validation fails on items 1, 3, or 4: halt with a detailed error. These are structural problems that must be fixed before proceeding. +If validation fails on item 2 (orphaned contracts): log a warning but continue — orphaned contracts may be consumed by future stories. + +--- + +## 4.7 Write Application Log + +Append the application results to the analysis report (`sdocs/replans/<YYYY-MM-DD>-<slug>-analysis.md`): + +```markdown +## Step 4: Changes Applied + +- **Date:** <timestamp> +- **Contracts created:** <N> +- **Contracts version-bumped:** <N> +- **Contracts deprecated:** <N> +- **Contracts updated in place:** <N> +- **Stories created:** <N> +- **Stories marked needs-rebuild:** <N> +- **Stories marked obsolete:** <N> +- **Stories updated in place:** <N> +- **Dependency graph valid:** yes | no (with details) +- **Warnings:** <any non-fatal issues> +``` + +--- + +## GATE — APPLY CHANGES PASSES WHEN + +- [ ] All `added` requirements have new contracts (status: `draft`) and new stories (status: `ready`) +- [ ] All `modified-unbuilt` stories have updated ACs; their contracts are updated (version-bumped if stable, edited in place if draft) +- [ ] All `modified-done` stories are now status `needs-rebuild`; their contracts are version-bumped with changelog entries +- [ ] All `removed` stories are now status `obsolete`; their contracts are status `deprecated` with `deprecated_date` and `deprecated_reason` +- [ ] No files were deleted during this step +- [ ] No code files were modified during this step (only `sdocs/` artifacts) +- [ ] `sdocs/contracts/INDEX.md` is updated and accurate +- [ ] Dependency graph passes: no dangling references, no cycles, version references are current +- [ ] Application log appended to the analysis report + +--- + +## FAILURE MODES + +- **Missing analysis report or gate not passed:** Halt immediately. Step 4 must never run without Step 3 confirmation. +- **Contract ID collision:** If a new contract ID would collide with an existing one, increment until a unique ID is found. Log the collision. +- **Story ID collision:** Same as contract — increment until unique. Log the collision. +- **Cycle detected in dependency graph:** Halt and report the full cycle path. The user must resolve the cycle before the replan can continue. Suggest which `depends_on` edge to remove. +- **Stale version reference:** If a story references an old contract version after the replan applied a bump, fix the reference automatically and log it as a correction. +- **File write failure:** If any file cannot be written, halt immediately and report which files were successfully updated and which failed. Do not leave the system in a partially-applied state — roll back all changes in the current category if possible. + +--- + +## NEXT + +→ Step 5: Merge Revised PRD (`step-05-merge-prd.md`) + +With all contracts and stories updated, Atlas merges the revised PRD into `sdocs/prd.md` with a changelog entry, completing the replan pipeline. The merged PRD becomes the new source of truth for subsequent `build-tdd` passes on `needs-rebuild` stories. From dd451b182bac07f976e4d55102e86c3fe09bcadd Mon Sep 17 00:00:00 2001 From: "sam-cloud-app[bot]" <252427705+sam-cloud-app[bot]@users.noreply.github.com> Date: Sat, 16 May 2026 10:49:36 +0000 Subject: [PATCH 09/11] =?UTF-8?q?Task=208/11:=20Write=20Step=205=20?= =?UTF-8?q?=E2=80=94=20Merge=20revised=20PRD=20with=20changelog?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com> --- .../replan/steps/step-05-merge-prd.md | 184 ++++++++++++++++++ .../replan/steps/step-05-merge-prd.md | 184 ++++++++++++++++++ 2 files changed, 368 insertions(+) create mode 100644 _sam/core/workflows/replan/steps/step-05-merge-prd.md create mode 100644 templates/_sam/core/workflows/replan/steps/step-05-merge-prd.md diff --git a/_sam/core/workflows/replan/steps/step-05-merge-prd.md b/_sam/core/workflows/replan/steps/step-05-merge-prd.md new file mode 100644 index 0000000..71566ce --- /dev/null +++ b/_sam/core/workflows/replan/steps/step-05-merge-prd.md @@ -0,0 +1,184 @@ +--- +step: 5 +name: merge-prd +description: Merge the revised PRD into sdocs/prd.md with a changelog entry and archive the revised PRD input file +agents: [architect] +--- + +# Step 5: Merge Revised PRD with Changelog + +**Agent:** Atlas (System Architect) + +**Purpose:** Merge the revised PRD into the live `sdocs/prd.md` so the PRD reflects the current product state after the replan. The revised PRD input is archived to `sdocs/replans/` as the audit trail. This step is adapted from the `extend` workflow's Phase 4 (`step-04-merge-prd.md`) but handles modifications and removals in addition to additions. + +--- + +## ENTRY CONDITIONS + +- Step 4 gate passed — all per-category artifact changes (contracts, stories) have been applied successfully +- Step 4 application log has been appended to the analysis report +- The PRD file exists at the canonical location (default: `sdocs/prd.md`; fallback: `prd.md` at project root) +- The revised PRD input file (passed as the workflow argument) is still accessible +- `sdocs/replans/` directory exists (created by earlier steps) +- `sdocs/replans/<YYYY-MM-DD>-<slug>-diff.md` exists (from Step 1) +- `sdocs/replans/<YYYY-MM-DD>-<slug>-analysis.md` exists (from Step 2/4) + +If any precondition fails, halt and tell the user which file is missing. Do NOT attempt a partial merge. + +--- + +## SCHEMA REFERENCE + +`_sam/core/resources/prd-schema.md`, especially the `## Change log` section. The merge step writes into structures the schema documents. + +--- + +## PROCESS + +### 5.1 Locate the PRD + +In order: +1. Check `sdocs/prd.md` +2. Check `prd.md` at project root +3. Check any done story's frontmatter `prd:` field resolved to an absolute path +4. If still not found: halt with "cannot locate PRD; specify the path manually" + +### 5.2 Read and Parse the Existing PRD + +Identify which canonical sections are present. Note the current frontmatter `version` value — the merge must produce a strictly greater version. + +Required sections to consider for merging (from `prd-schema.md`): +- `## Functional Requirements` (or equivalent: `## Features`, `## Requirements`) +- `## Non-Functional Requirements` +- `## Out of Scope` +- `## Change log` (optional in schema, but the merge will create it if absent) + +### 5.3 Map Revised PRD Changes → PRD Sections + +Using the Step 1 diff (`sdocs/replans/<YYYY-MM-DD>-<slug>-diff.md`) as the guide for what changed, apply the following mapping: + +| Change category | PRD action | +|-----------------|------------| +| **Added** requirements | Append new requirement entries to `## Functional Requirements` — combine the feature name (bold lead) and a one-paragraph summary. Append acceptance criteria as sub-bullets. | +| **Modified** requirements | Update the affected requirement entries in place. Revise the description and acceptance criteria to match the revised PRD. Do NOT rewrite surrounding unchanged requirements. | +| **Removed** requirements | Mark the requirement as deprecated inline: prefix with `~~` strikethrough and append `(removed in replan <YYYY-MM-DD>)`. Do NOT delete the text — preserve it for audit. | +| **Unchanged** requirements | Do NOT touch. Preserve verbatim. | + +### 5.4 Apply the Changes + +In this order: + +1. **Frontmatter bumps:** + - `version: N.M` → `version: N.(M+1)` for non-breaking changes; `version: (N+1).0` for breaking changes (removals or modifications that break existing contracts). Atlas decides based on the impact analysis. + - `last_updated: <today's date>` + - Leave `created`, `title`, `owner`, `source` untouched + +2. **Functional Requirements:** Apply additions, modifications, and removals per Section 5.3. + +3. **Non-Functional Requirements:** If the revised PRD modifies NFRs, update them in place. If new NFRs are added, append them. + +4. **Out of Scope:** If the revised PRD adds or modifies out-of-scope items, update accordingly. Create `## Out of Scope` if it doesn't exist and the revised PRD specifies exclusions. + +5. **Change log:** Append one entry for this replan run: + ```markdown + - **<YYYY-MM-DD> — replan: <slug>.** <summary of changes: N requirements added, N modified, N removed. Key changes: brief description of the most significant change> + ``` + If `## Change log` doesn't exist, create it at the end of the PRD body (after Out of Scope, before Open Questions / Assumptions if those exist). + +### 5.5 Preserve Existing Content + +Do NOT: +- Rewrite, rephrase, or "improve" existing unchanged sections +- Reorder existing requirements +- Touch `## Assumptions` or `## Open Questions` from the original drafting workflow +- Remove any section that existed before the merge (sections can only be added or have content modified within them) + +The only exception: requirements explicitly classified as `removed` in the diff receive strikethrough treatment — this is a controlled, auditable modification, not a deletion. + +### 5.6 Archive the Revised PRD Input + +Copy the revised PRD input file to: +``` +sdocs/replans/<YYYY-MM-DD>-<slug>-revised-prd.md +``` + +This preserves the exact input that triggered the replan, alongside the diff and analysis reports already in the same directory. + +### 5.7 Validate the Result + +Before writing: + +- [ ] Every section that existed BEFORE the merge still exists +- [ ] Frontmatter `version` is strictly greater than the previous value +- [ ] `## Change log` contains an entry with this run's date and the replan slug +- [ ] PRD still passes `prd-schema.md` validation (required sections present and non-empty) +- [ ] No pre-existing unchanged content was modified (diff the unchanged sections to verify) +- [ ] Archived revised PRD exists at `sdocs/replans/<YYYY-MM-DD>-<slug>-revised-prd.md` +- [ ] Line count of merged PRD is reasonable (may be less than original if removals use strikethrough, but should not drop dramatically) + +If any check fails, halt and roll back. Atomic write only. + +### 5.8 Write + +Replace the PRD file at its discovered location. Print a unified diff (or summary of changed sections) to the run log so the user can review what changed. + +--- + +## OUTPUT SUMMARY + +After successful merge, print: + +``` +PRD merged (replan). +File: <path> +Version: <old> → <new> +Requirements added: <N> +Requirements modified: <N> +Requirements removed: <N> +Change log: <YYYY-MM-DD> — replan: <slug> +Archived input: sdocs/replans/<YYYY-MM-DD>-<slug>-revised-prd.md +``` + +--- + +## GATE — MERGE PASSES WHEN + +- [ ] PRD file written with strictly-greater `version` +- [ ] `## Change log` entry present with replan slug and date +- [ ] All `added` requirements from the diff appear in the merged PRD's Functional Requirements +- [ ] All `modified` requirements reflect the revised text (not the old text) +- [ ] All `removed` requirements are marked with strikethrough and removal annotation (not deleted) +- [ ] No pre-existing unchanged PRD content was altered or removed +- [ ] PRD still validates against `prd-schema.md` +- [ ] Revised PRD input archived to `sdocs/replans/<YYYY-MM-DD>-<slug>-revised-prd.md` + +--- + +## FAILURE MODES + +- **PRD not found:** Halt with the locations tried. User must specify the path or move the PRD to a canonical location. +- **PRD has no canonical sections (free-form prose):** Halt with "PRD too unstructured to merge automatically; convert to `prd-schema.md` format or apply changes by hand." Do not guess. +- **Frontmatter `version` parse fails:** Treat as if `version: 0.1` and bump to `0.2`. Warn in the run log. +- **Validation fails after merge:** Roll back the file. Do not leave the PRD in a half-merged state. +- **Revised PRD input file missing:** Halt. Without the input file, we cannot archive it. The user must provide it again. +- **Archive path collision:** If `sdocs/replans/<YYYY-MM-DD>-<slug>-revised-prd.md` already exists (replan run twice on same day with same slug), append a numeric suffix: `-revised-prd-2.md`, `-revised-prd-3.md`, etc. + +--- + +## RELATIONSHIP TO OTHER STEPS + +| Step | Touches | Source of truth | +|------|---------|-----------------| +| 1 diff-prd | nothing (write-only reports) | the revised PRD + current PRD | +| 2 impact-analysis | nothing (write-only reports) | the diff + existing contracts/stories | +| 3 impact-gate | nothing (user confirmation) | the impact summary | +| 4 apply-changes | `sdocs/contracts/**`, `sdocs/stories/**` | the impact analysis | +| **5 merge-prd** | **`sdocs/prd.md`**, **`sdocs/replans/`** | **the revised PRD + diff report** | + +The PRD merge is intentionally LAST. If Steps 1–4 fail, the PRD stays untouched, and rerunning `replan` is safe. If Step 5 fails AFTER Steps 1–4 succeeded, the artifacts are coherent (stories + contracts updated) but the PRD is stale — the user can re-run merge alone. + +--- + +## NEXT + +Workflow exits. The user runs `build-tdd` on any stories with status `needs-rebuild` or newly created stories with status `ready`. diff --git a/templates/_sam/core/workflows/replan/steps/step-05-merge-prd.md b/templates/_sam/core/workflows/replan/steps/step-05-merge-prd.md new file mode 100644 index 0000000..71566ce --- /dev/null +++ b/templates/_sam/core/workflows/replan/steps/step-05-merge-prd.md @@ -0,0 +1,184 @@ +--- +step: 5 +name: merge-prd +description: Merge the revised PRD into sdocs/prd.md with a changelog entry and archive the revised PRD input file +agents: [architect] +--- + +# Step 5: Merge Revised PRD with Changelog + +**Agent:** Atlas (System Architect) + +**Purpose:** Merge the revised PRD into the live `sdocs/prd.md` so the PRD reflects the current product state after the replan. The revised PRD input is archived to `sdocs/replans/` as the audit trail. This step is adapted from the `extend` workflow's Phase 4 (`step-04-merge-prd.md`) but handles modifications and removals in addition to additions. + +--- + +## ENTRY CONDITIONS + +- Step 4 gate passed — all per-category artifact changes (contracts, stories) have been applied successfully +- Step 4 application log has been appended to the analysis report +- The PRD file exists at the canonical location (default: `sdocs/prd.md`; fallback: `prd.md` at project root) +- The revised PRD input file (passed as the workflow argument) is still accessible +- `sdocs/replans/` directory exists (created by earlier steps) +- `sdocs/replans/<YYYY-MM-DD>-<slug>-diff.md` exists (from Step 1) +- `sdocs/replans/<YYYY-MM-DD>-<slug>-analysis.md` exists (from Step 2/4) + +If any precondition fails, halt and tell the user which file is missing. Do NOT attempt a partial merge. + +--- + +## SCHEMA REFERENCE + +`_sam/core/resources/prd-schema.md`, especially the `## Change log` section. The merge step writes into structures the schema documents. + +--- + +## PROCESS + +### 5.1 Locate the PRD + +In order: +1. Check `sdocs/prd.md` +2. Check `prd.md` at project root +3. Check any done story's frontmatter `prd:` field resolved to an absolute path +4. If still not found: halt with "cannot locate PRD; specify the path manually" + +### 5.2 Read and Parse the Existing PRD + +Identify which canonical sections are present. Note the current frontmatter `version` value — the merge must produce a strictly greater version. + +Required sections to consider for merging (from `prd-schema.md`): +- `## Functional Requirements` (or equivalent: `## Features`, `## Requirements`) +- `## Non-Functional Requirements` +- `## Out of Scope` +- `## Change log` (optional in schema, but the merge will create it if absent) + +### 5.3 Map Revised PRD Changes → PRD Sections + +Using the Step 1 diff (`sdocs/replans/<YYYY-MM-DD>-<slug>-diff.md`) as the guide for what changed, apply the following mapping: + +| Change category | PRD action | +|-----------------|------------| +| **Added** requirements | Append new requirement entries to `## Functional Requirements` — combine the feature name (bold lead) and a one-paragraph summary. Append acceptance criteria as sub-bullets. | +| **Modified** requirements | Update the affected requirement entries in place. Revise the description and acceptance criteria to match the revised PRD. Do NOT rewrite surrounding unchanged requirements. | +| **Removed** requirements | Mark the requirement as deprecated inline: prefix with `~~` strikethrough and append `(removed in replan <YYYY-MM-DD>)`. Do NOT delete the text — preserve it for audit. | +| **Unchanged** requirements | Do NOT touch. Preserve verbatim. | + +### 5.4 Apply the Changes + +In this order: + +1. **Frontmatter bumps:** + - `version: N.M` → `version: N.(M+1)` for non-breaking changes; `version: (N+1).0` for breaking changes (removals or modifications that break existing contracts). Atlas decides based on the impact analysis. + - `last_updated: <today's date>` + - Leave `created`, `title`, `owner`, `source` untouched + +2. **Functional Requirements:** Apply additions, modifications, and removals per Section 5.3. + +3. **Non-Functional Requirements:** If the revised PRD modifies NFRs, update them in place. If new NFRs are added, append them. + +4. **Out of Scope:** If the revised PRD adds or modifies out-of-scope items, update accordingly. Create `## Out of Scope` if it doesn't exist and the revised PRD specifies exclusions. + +5. **Change log:** Append one entry for this replan run: + ```markdown + - **<YYYY-MM-DD> — replan: <slug>.** <summary of changes: N requirements added, N modified, N removed. Key changes: brief description of the most significant change> + ``` + If `## Change log` doesn't exist, create it at the end of the PRD body (after Out of Scope, before Open Questions / Assumptions if those exist). + +### 5.5 Preserve Existing Content + +Do NOT: +- Rewrite, rephrase, or "improve" existing unchanged sections +- Reorder existing requirements +- Touch `## Assumptions` or `## Open Questions` from the original drafting workflow +- Remove any section that existed before the merge (sections can only be added or have content modified within them) + +The only exception: requirements explicitly classified as `removed` in the diff receive strikethrough treatment — this is a controlled, auditable modification, not a deletion. + +### 5.6 Archive the Revised PRD Input + +Copy the revised PRD input file to: +``` +sdocs/replans/<YYYY-MM-DD>-<slug>-revised-prd.md +``` + +This preserves the exact input that triggered the replan, alongside the diff and analysis reports already in the same directory. + +### 5.7 Validate the Result + +Before writing: + +- [ ] Every section that existed BEFORE the merge still exists +- [ ] Frontmatter `version` is strictly greater than the previous value +- [ ] `## Change log` contains an entry with this run's date and the replan slug +- [ ] PRD still passes `prd-schema.md` validation (required sections present and non-empty) +- [ ] No pre-existing unchanged content was modified (diff the unchanged sections to verify) +- [ ] Archived revised PRD exists at `sdocs/replans/<YYYY-MM-DD>-<slug>-revised-prd.md` +- [ ] Line count of merged PRD is reasonable (may be less than original if removals use strikethrough, but should not drop dramatically) + +If any check fails, halt and roll back. Atomic write only. + +### 5.8 Write + +Replace the PRD file at its discovered location. Print a unified diff (or summary of changed sections) to the run log so the user can review what changed. + +--- + +## OUTPUT SUMMARY + +After successful merge, print: + +``` +PRD merged (replan). +File: <path> +Version: <old> → <new> +Requirements added: <N> +Requirements modified: <N> +Requirements removed: <N> +Change log: <YYYY-MM-DD> — replan: <slug> +Archived input: sdocs/replans/<YYYY-MM-DD>-<slug>-revised-prd.md +``` + +--- + +## GATE — MERGE PASSES WHEN + +- [ ] PRD file written with strictly-greater `version` +- [ ] `## Change log` entry present with replan slug and date +- [ ] All `added` requirements from the diff appear in the merged PRD's Functional Requirements +- [ ] All `modified` requirements reflect the revised text (not the old text) +- [ ] All `removed` requirements are marked with strikethrough and removal annotation (not deleted) +- [ ] No pre-existing unchanged PRD content was altered or removed +- [ ] PRD still validates against `prd-schema.md` +- [ ] Revised PRD input archived to `sdocs/replans/<YYYY-MM-DD>-<slug>-revised-prd.md` + +--- + +## FAILURE MODES + +- **PRD not found:** Halt with the locations tried. User must specify the path or move the PRD to a canonical location. +- **PRD has no canonical sections (free-form prose):** Halt with "PRD too unstructured to merge automatically; convert to `prd-schema.md` format or apply changes by hand." Do not guess. +- **Frontmatter `version` parse fails:** Treat as if `version: 0.1` and bump to `0.2`. Warn in the run log. +- **Validation fails after merge:** Roll back the file. Do not leave the PRD in a half-merged state. +- **Revised PRD input file missing:** Halt. Without the input file, we cannot archive it. The user must provide it again. +- **Archive path collision:** If `sdocs/replans/<YYYY-MM-DD>-<slug>-revised-prd.md` already exists (replan run twice on same day with same slug), append a numeric suffix: `-revised-prd-2.md`, `-revised-prd-3.md`, etc. + +--- + +## RELATIONSHIP TO OTHER STEPS + +| Step | Touches | Source of truth | +|------|---------|-----------------| +| 1 diff-prd | nothing (write-only reports) | the revised PRD + current PRD | +| 2 impact-analysis | nothing (write-only reports) | the diff + existing contracts/stories | +| 3 impact-gate | nothing (user confirmation) | the impact summary | +| 4 apply-changes | `sdocs/contracts/**`, `sdocs/stories/**` | the impact analysis | +| **5 merge-prd** | **`sdocs/prd.md`**, **`sdocs/replans/`** | **the revised PRD + diff report** | + +The PRD merge is intentionally LAST. If Steps 1–4 fail, the PRD stays untouched, and rerunning `replan` is safe. If Step 5 fails AFTER Steps 1–4 succeeded, the artifacts are coherent (stories + contracts updated) but the PRD is stale — the user can re-run merge alone. + +--- + +## NEXT + +Workflow exits. The user runs `build-tdd` on any stories with status `needs-rebuild` or newly created stories with status `ready`. From 5bf1c0a00550ef28916dedd8f9c6f36125d08f36 Mon Sep 17 00:00:00 2001 From: "sam-cloud-app[bot]" <252427705+sam-cloud-app[bot]@users.noreply.github.com> Date: Sat, 16 May 2026 10:51:35 +0000 Subject: [PATCH 10/11] Task 10/11: Register `replan` in `bin/cli.js` WORKFLOWS array Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com> --- bin/cli.js | 6 ++++++ scripts/verify-copilot.js | 3 ++- scripts/verify-gemini.js | 3 ++- 3 files changed, 10 insertions(+), 2 deletions(-) diff --git a/bin/cli.js b/bin/cli.js index ada2d28..29aa259 100644 --- a/bin/cli.js +++ b/bin/cli.js @@ -53,6 +53,12 @@ const WORKFLOWS = [ file: 'core/workflows/extend/workflow.md', display: 'SAM Extend Workflow', description: 'Plan additive changes on top of an existing app. Reads existing sdocs/, never wipes; emits new contracts, stories, and regression integration without modifying done work.' + }, + { + name: 'replan', + file: 'core/workflows/replan/workflow.md', + display: 'SAM Replan Workflow', + description: 'Handle requirement changes mid-build. Diffs a revised PRD against the current one, computes impact on contracts and stories, and applies per-category actions (added/modified/removed) with user confirmation.' } ]; diff --git a/scripts/verify-copilot.js b/scripts/verify-copilot.js index 5be14e3..9ac9c51 100644 --- a/scripts/verify-copilot.js +++ b/scripts/verify-copilot.js @@ -69,7 +69,8 @@ function verifyCopilotInstall() { { name: 'sam-plan', display: 'SAM Planning Workflow' }, { name: 'sam-build-tdd', display: 'SAM Build-TDD Workflow' }, { name: 'sam-plan-n-build', display: 'SAM Plan-n-Build Workflow' }, - { name: 'sam-extend', display: 'SAM Extend Workflow' } + { name: 'sam-extend', display: 'SAM Extend Workflow' }, + { name: 'sam-replan', display: 'SAM Replan Workflow' } ]; const instructions = fs.readFileSync(instructionsPath, 'utf8'); diff --git a/scripts/verify-gemini.js b/scripts/verify-gemini.js index b49d841..14ced6e 100644 --- a/scripts/verify-gemini.js +++ b/scripts/verify-gemini.js @@ -64,7 +64,8 @@ function verifyGeminiSkills() { 'sam-plan', 'sam-build-tdd', 'sam-plan-n-build', - 'sam-extend' + 'sam-extend', + 'sam-replan' ]; for (const skill of expectedAgentSkills) { From c4223ece91f36464aae86fed552cfdc2d341c9dc Mon Sep 17 00:00:00 2001 From: "sam-cloud-app[bot]" <252427705+sam-cloud-app[bot]@users.noreply.github.com> Date: Sat, 16 May 2026 10:56:03 +0000 Subject: [PATCH 11/11] Task 11/11: Run `sync-templates` and verify MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - Add replan Claude command template for /sam:core:workflows:replan - Add replan to display output for all 5 platforms - Update workflow count in Copilot instructions (5 → 7) - All tests pass; replan skill files generated for all platforms Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com> --- bin/cli.js | 17 +++++++++++------ .../commands/sam/core/workflows/replan.md | 6 ++++++ 2 files changed, 17 insertions(+), 6 deletions(-) create mode 100644 templates/.claude/commands/sam/core/workflows/replan.md diff --git a/bin/cli.js b/bin/cli.js index 29aa259..7490677 100644 --- a/bin/cli.js +++ b/bin/cli.js @@ -744,7 +744,7 @@ All SAM integration files are located in: copilot-integration/ // Add one workflow file per SAM workflow instructionsContent += `## SAM Workflows -Five workflows compose the SAM experience (quick-prd, scope, plan, build-tdd, plan-n-build). Each is a self-contained playbook the user can invoke. +Seven workflows compose the SAM experience (quick-prd, scope, plan, build-tdd, plan-n-build, extend, replan). Each is a self-contained playbook the user can invoke. `; @@ -901,7 +901,8 @@ function install(platform, targetDir) { log(' /sam:core:workflows:plan - PRD -> epics + stories'); log(' /sam:core:workflows:build-tdd - One story -> tested code'); log(' /sam:core:workflows:plan-n-build - Full pipeline (plan + tdd + docs)'); - log(' /sam:core:workflows:extend - Plan additive changes on top of existing app\n'); + log(' /sam:core:workflows:extend - Plan additive changes on top of existing app'); + log(' /sam:core:workflows:replan - Handle requirement changes mid-build\n'); } if (platform === 'cursor' || platform === 'all') { @@ -924,7 +925,8 @@ function install(platform, targetDir) { log(' @sam-plan - PRD -> epics + stories'); log(' @sam-build-tdd - One story -> tested code'); log(' @sam-plan-n-build - Full pipeline (plan + tdd + docs)'); - log(' @sam-extend - Plan additive changes on top of existing app\n'); + log(' @sam-extend - Plan additive changes on top of existing app'); + log(' @sam-replan - Handle requirement changes mid-build\n'); } if (platform === 'antigravity' || platform === 'all') { @@ -947,7 +949,8 @@ function install(platform, targetDir) { log(' /sam-plan - PRD -> epics + stories'); log(' /sam-build-tdd - One story -> tested code'); log(' /sam-plan-n-build - Full pipeline (plan + tdd + docs)'); - log(' /sam-extend - Plan additive changes on top of existing app\n'); + log(' /sam-extend - Plan additive changes on top of existing app'); + log(' /sam-replan - Handle requirement changes mid-build\n'); } if (platform === 'gemini' || platform === 'all') { @@ -970,7 +973,8 @@ function install(platform, targetDir) { log(' sam-plan - PRD -> epics + stories'); log(' sam-build-tdd - One story -> tested code'); log(' sam-plan-n-build - Full pipeline (plan + tdd + docs)'); - log(' sam-extend - Plan additive changes on top of existing app\n'); + log(' sam-extend - Plan additive changes on top of existing app'); + log(' sam-replan - Handle requirement changes mid-build\n'); } if (platform === 'copilot' || platform === 'all') { @@ -993,7 +997,8 @@ function install(platform, targetDir) { log(' "Run sam-plan" - PRD -> epics + stories'); log(' "Run sam-build-tdd" - One story -> tested code'); log(' "Run sam-plan-n-build" - Full pipeline (plan + tdd + docs)'); - log(' "Run sam-extend" - Plan additive changes on top of existing app\n'); + log(' "Run sam-extend" - Plan additive changes on top of existing app'); + log(' "Run sam-replan" - Handle requirement changes mid-build\n'); } if (platform === 'claude' || platform === 'all') { diff --git a/templates/.claude/commands/sam/core/workflows/replan.md b/templates/.claude/commands/sam/core/workflows/replan.md new file mode 100644 index 0000000..aec1a54 --- /dev/null +++ b/templates/.claude/commands/sam/core/workflows/replan.md @@ -0,0 +1,6 @@ +--- +name: 'replan' +description: 'SAM Replan Workflow - Handle requirement changes mid-build. Diffs a revised PRD against the current one, computes impact on contracts and stories, and applies per-category actions with user confirmation.' +--- + +IT IS CRITICAL THAT YOU FOLLOW THIS COMMAND: LOAD the FULL @_sam/core/workflows/replan/workflow.md, READ its entire contents and follow its directions exactly!