cleargate 0.14.0 → 0.15.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +16 -0
- package/dist/MANIFEST.json +71 -15
- package/dist/admin-api/index.cjs +0 -1
- package/dist/admin-api/index.js +1 -2
- package/dist/auth/factory.cjs +0 -1
- package/dist/auth/factory.js +2 -3
- package/dist/auth/require-token.cjs +0 -1
- package/dist/auth/require-token.js +1 -2
- package/dist/auth/token-store.cjs +0 -1
- package/dist/auth/token-store.js +1 -2
- package/dist/{bootstrap-root-QKSA5V75.js → bootstrap-root-2H5HVTCC.js} +1 -2
- package/dist/{chunk-PDE37WFQ.js → chunk-A7MSQUU7.js} +2 -3
- package/dist/{chunk-BTSZOEWC.js → chunk-P6KEDAK2.js} +0 -1
- package/dist/{chunk-E3X7IE5E.js → chunk-PY6FHGV5.js} +1 -2
- package/dist/{chunk-5DI2Z3C2.js → chunk-Y53ZZYYU.js} +1 -2
- package/dist/cli.cjs +1564 -1414
- package/dist/cli.js +1514 -1364
- package/dist/lib/ledger.cjs +0 -1
- package/dist/lib/ledger.js +1 -2
- package/dist/lib/lifecycle-reconcile.cjs +0 -1
- package/dist/lib/lifecycle-reconcile.js +2 -3
- package/dist/{whoami-EANGN46Z.js → whoami-JKQQPABQ.js} +3 -4
- package/package.json +4 -3
- package/templates/cleargate-planning/.claude/agents/architect.md +4 -2
- package/templates/cleargate-planning/.claude/agents/developer.md +4 -11
- package/templates/cleargate-planning/.claude/agents/qa.md +14 -6
- package/templates/cleargate-planning/.claude/hooks/pending-task-sentinel.sh +2 -2
- package/templates/cleargate-planning/.claude/skills/sprint-execution/SKILL.md +19 -1
- package/templates/cleargate-planning/.cleargate/config.example.yml +16 -0
- package/templates/cleargate-planning/.cleargate/scripts/close_sprint.deferred-verify.red.node.test.ts +245 -0
- package/templates/cleargate-planning/.cleargate/scripts/close_sprint.mjs +227 -0
- package/templates/cleargate-planning/.cleargate/scripts/gate-checks.json +5 -4
- package/templates/cleargate-planning/.cleargate/scripts/init_sprint.mjs +75 -2
- package/templates/cleargate-planning/.cleargate/scripts/pre_gate_common.sh +48 -0
- package/templates/cleargate-planning/.cleargate/scripts/pre_gate_runner.sh +57 -1
- package/templates/cleargate-planning/.cleargate/scripts/provision_worktree_config.sh +155 -0
- package/templates/cleargate-planning/.cleargate/scripts/qa_red_lint.mjs +380 -0
- package/templates/cleargate-planning/.cleargate/scripts/run_script.sh +34 -1
- package/templates/cleargate-planning/.cleargate/scripts/test/cr077_eviction.red.sh +113 -0
- package/templates/cleargate-planning/.cleargate/scripts/test/cr078_init.test.sh +309 -0
- package/templates/cleargate-planning/.cleargate/scripts/test/cr079_provision.red.sh +262 -0
- package/templates/cleargate-planning/.cleargate/scripts/test/cr080_wrapper.test.sh +177 -0
- package/templates/cleargate-planning/.cleargate/scripts/test/cr081_qa_red_lint.red.sh +348 -0
- package/templates/cleargate-planning/.cleargate/sprint-runs/_off-sprint/.session-totals.json +1 -0
- package/templates/cleargate-planning/.cleargate/sprint-runs/_off-sprint/token-ledger.jsonl +27 -0
- package/templates/cleargate-planning/.cleargate/templates/sprint_context.md +17 -0
- package/templates/cleargate-planning/.cleargate/templates/story.md +1 -0
- package/templates/cleargate-planning/MANIFEST.json +71 -15
- package/dist/admin-api/index.cjs.map +0 -1
- package/dist/admin-api/index.js.map +0 -1
- package/dist/auth/factory.cjs.map +0 -1
- package/dist/auth/factory.js.map +0 -1
- package/dist/auth/require-token.cjs.map +0 -1
- package/dist/auth/require-token.js.map +0 -1
- package/dist/auth/token-store.cjs.map +0 -1
- package/dist/auth/token-store.js.map +0 -1
- package/dist/bootstrap-root-QKSA5V75.js.map +0 -1
- package/dist/chunk-5DI2Z3C2.js.map +0 -1
- package/dist/chunk-BTSZOEWC.js.map +0 -1
- package/dist/chunk-E3X7IE5E.js.map +0 -1
- package/dist/chunk-PDE37WFQ.js.map +0 -1
- package/dist/cli.cjs.map +0 -1
- package/dist/cli.js.map +0 -1
- package/dist/lib/ledger.cjs.map +0 -1
- package/dist/lib/ledger.js.map +0 -1
- package/dist/lib/lifecycle-reconcile.cjs.map +0 -1
- package/dist/lib/lifecycle-reconcile.js.map +0 -1
- package/dist/templates/cleargate-planning/.claude/agents/architect-reader.md +0 -61
- package/dist/templates/cleargate-planning/.claude/agents/architect-synth.md +0 -124
- package/dist/templates/cleargate-planning/.claude/agents/architect.md +0 -230
- package/dist/templates/cleargate-planning/.claude/agents/cleargate-wiki-contradict.md +0 -108
- package/dist/templates/cleargate-planning/.claude/agents/cleargate-wiki-ingest.md +0 -194
- package/dist/templates/cleargate-planning/.claude/agents/cleargate-wiki-lint.md +0 -261
- package/dist/templates/cleargate-planning/.claude/agents/cleargate-wiki-query.md +0 -143
- package/dist/templates/cleargate-planning/.claude/agents/developer.md +0 -185
- package/dist/templates/cleargate-planning/.claude/agents/devops.md +0 -257
- package/dist/templates/cleargate-planning/.claude/agents/qa.md +0 -171
- package/dist/templates/cleargate-planning/.claude/agents/reporter.md +0 -274
- package/dist/templates/cleargate-planning/.claude/hooks/pending-task-sentinel.sh +0 -209
- package/dist/templates/cleargate-planning/.claude/hooks/pre-commit-surface-gate.sh +0 -33
- package/dist/templates/cleargate-planning/.claude/hooks/pre-commit-test-ratchet.sh +0 -58
- package/dist/templates/cleargate-planning/.claude/hooks/pre-commit.sh +0 -19
- package/dist/templates/cleargate-planning/.claude/hooks/pre-edit-gate.sh +0 -162
- package/dist/templates/cleargate-planning/.claude/hooks/pre-tool-use-autonomy.sh +0 -58
- package/dist/templates/cleargate-planning/.claude/hooks/pre-tool-use-task.sh +0 -148
- package/dist/templates/cleargate-planning/.claude/hooks/session-start.sh +0 -75
- package/dist/templates/cleargate-planning/.claude/hooks/stamp-and-gate.sh +0 -43
- package/dist/templates/cleargate-planning/.claude/hooks/token-ledger.sh +0 -590
- package/dist/templates/cleargate-planning/.claude/settings.json +0 -68
- package/dist/templates/cleargate-planning/.claude/skills/flashcard/SKILL.md +0 -102
- package/dist/templates/cleargate-planning/.claude/skills/sprint-execution/SKILL.md +0 -742
- package/dist/templates/cleargate-planning/.cleargate/FLASHCARD.md +0 -7
- package/dist/templates/cleargate-planning/.cleargate/config.example.yml +0 -67
- package/dist/templates/cleargate-planning/.cleargate/config.yml +0 -18
- package/dist/templates/cleargate-planning/.cleargate/delivery/archive/.gitkeep +0 -0
- package/dist/templates/cleargate-planning/.cleargate/delivery/pending-sync/.gitkeep +0 -0
- package/dist/templates/cleargate-planning/.cleargate/knowledge/cleargate-enforcement.md +0 -551
- package/dist/templates/cleargate-planning/.cleargate/knowledge/cleargate-protocol.md +0 -878
- package/dist/templates/cleargate-planning/.cleargate/knowledge/mid-sprint-triage-rubric.md +0 -160
- package/dist/templates/cleargate-planning/.cleargate/knowledge/readiness-gates.md +0 -213
- package/dist/templates/cleargate-planning/.cleargate/knowledge/sprint-closeout-checklist.md +0 -71
- package/dist/templates/cleargate-planning/.cleargate/scripts/_migrate-schema-v3.mjs +0 -120
- package/dist/templates/cleargate-planning/.cleargate/scripts/assert_story_files.mjs +0 -265
- package/dist/templates/cleargate-planning/.cleargate/scripts/close_sprint.mjs +0 -1012
- package/dist/templates/cleargate-planning/.cleargate/scripts/collision_surface.sh +0 -114
- package/dist/templates/cleargate-planning/.cleargate/scripts/constants.mjs +0 -62
- package/dist/templates/cleargate-planning/.cleargate/scripts/dedupe_frontmatter.mjs +0 -219
- package/dist/templates/cleargate-planning/.cleargate/scripts/file_surface_diff.sh +0 -320
- package/dist/templates/cleargate-planning/.cleargate/scripts/gate-checks.json +0 -15
- package/dist/templates/cleargate-planning/.cleargate/scripts/init_gate_config.sh +0 -38
- package/dist/templates/cleargate-planning/.cleargate/scripts/init_sprint.mjs +0 -240
- package/dist/templates/cleargate-planning/.cleargate/scripts/launch_wave.mjs +0 -341
- package/dist/templates/cleargate-planning/.cleargate/scripts/lib/report-filename.mjs +0 -54
- package/dist/templates/cleargate-planning/.cleargate/scripts/pre_gate_common.sh +0 -206
- package/dist/templates/cleargate-planning/.cleargate/scripts/pre_gate_runner.sh +0 -371
- package/dist/templates/cleargate-planning/.cleargate/scripts/prefill_report.mjs +0 -280
- package/dist/templates/cleargate-planning/.cleargate/scripts/prep_doc_refresh.mjs +0 -378
- package/dist/templates/cleargate-planning/.cleargate/scripts/prep_qa_context.mjs +0 -888
- package/dist/templates/cleargate-planning/.cleargate/scripts/run_script.sh +0 -209
- package/dist/templates/cleargate-planning/.cleargate/scripts/sprint_trends.mjs +0 -71
- package/dist/templates/cleargate-planning/.cleargate/scripts/state.schema.json +0 -127
- package/dist/templates/cleargate-planning/.cleargate/scripts/suggest_improvements.mjs +0 -717
- package/dist/templates/cleargate-planning/.cleargate/scripts/surface-whitelist.txt +0 -27
- package/dist/templates/cleargate-planning/.cleargate/scripts/test/test_assert_story_files.sh +0 -261
- package/dist/templates/cleargate-planning/.cleargate/scripts/test/test_file_surface.sh +0 -210
- package/dist/templates/cleargate-planning/.cleargate/scripts/test/test_flashcard_gate.sh +0 -190
- package/dist/templates/cleargate-planning/.cleargate/scripts/test/test_prep_qa_context.sh +0 -482
- package/dist/templates/cleargate-planning/.cleargate/scripts/test/test_test_ratchet.sh +0 -327
- package/dist/templates/cleargate-planning/.cleargate/scripts/test_ratchet.mjs +0 -261
- package/dist/templates/cleargate-planning/.cleargate/scripts/update_state.mjs +0 -246
- package/dist/templates/cleargate-planning/.cleargate/scripts/validate_bounce_readiness.mjs +0 -111
- package/dist/templates/cleargate-planning/.cleargate/scripts/validate_state.mjs +0 -184
- package/dist/templates/cleargate-planning/.cleargate/scripts/write_dispatch.sh +0 -172
- package/dist/templates/cleargate-planning/.cleargate/templates/Bug.md +0 -126
- package/dist/templates/cleargate-planning/.cleargate/templates/CR.md +0 -130
- package/dist/templates/cleargate-planning/.cleargate/templates/Sprint Plan Template.md +0 -137
- package/dist/templates/cleargate-planning/.cleargate/templates/epic.md +0 -166
- package/dist/templates/cleargate-planning/.cleargate/templates/hotfix.md +0 -111
- package/dist/templates/cleargate-planning/.cleargate/templates/initiative.md +0 -122
- package/dist/templates/cleargate-planning/.cleargate/templates/sprint_context.md +0 -50
- package/dist/templates/cleargate-planning/.cleargate/templates/sprint_report.md +0 -224
- package/dist/templates/cleargate-planning/.cleargate/templates/story.md +0 -213
- package/dist/templates/cleargate-planning/CLAUDE.md +0 -66
- package/dist/templates/cleargate-planning/MANIFEST.json +0 -503
- package/dist/templates/synthesis/active-sprint.md +0 -30
- package/dist/templates/synthesis/open-gates.md +0 -38
- package/dist/templates/synthesis/product-state.md +0 -31
- package/dist/templates/synthesis/roadmap.md +0 -63
- package/dist/whoami-EANGN46Z.js.map +0 -1
package/dist/lib/ledger.cjs.map
DELETED
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"sources":["../../src/lib/ledger.ts"],"sourcesContent":["/**\n * ledger.ts — CR-018\n *\n * Sprint-wide cost math: parses token-ledger.jsonl rows and sums delta tokens\n * for the Reporter agent. Distinct from ledger-reader.ts (per-work-item\n * attribution lookup); this file provides sumDeltas() for sprint-total cost.\n *\n * Format detection handles three cases:\n * 'delta' — all rows carry delta.* blocks (post-0.9.0)\n * 'pre-0.9.0' — all rows use flat input/output/cache_* fields (pre-0.9.0)\n * 'mixed' — some rows have delta, others don't (SPRINT-15 cutover window)\n */\n\n// ─── Public types ─────────────────────────────────────────────────────────────\n\n/** Token counts block (used in both delta and session_total). */\nexport interface TokenCounts {\n input: number;\n output: number;\n cache_creation: number;\n cache_read: number;\n}\n\n/** Full post-0.9.0 ledger row shape. */\nexport interface LedgerRowV2 {\n ts: string;\n sprint_id: string;\n story_id: string;\n work_item_id: string;\n agent_type: string;\n session_id: string;\n transcript?: string;\n sentinel_started_at?: string;\n delta_from_turn?: number;\n delta: TokenCounts;\n session_total: TokenCounts;\n model: string;\n turns: number;\n}\n\n/** Result returned by sumDeltas(). */\nexport interface SumResult {\n /** Aggregated token totals across all rows (using appropriate format). */\n totals: TokenCounts;\n /** How the totals were computed. */\n format: 'delta' | 'pre-0.9.0' | 'mixed';\n /**\n * Present when format is 'pre-0.9.0' or 'mixed'.\n * Reporter should paste this verbatim into REPORT.md §3.\n */\n pre_v2_caveat?: string;\n}\n\n// ─── Internal helpers ─────────────────────────────────────────────────────────\n\nfunction isTokenCounts(v: unknown): v is TokenCounts {\n if (typeof v !== 'object' || v === null) return false;\n const obj = v as Record<string, unknown>;\n return (\n typeof obj['input'] === 'number' &&\n typeof obj['output'] === 'number' &&\n typeof obj['cache_creation'] === 'number' &&\n typeof obj['cache_read'] === 'number'\n );\n}\n\nfunction hasDelta(row: Record<string, unknown>): boolean {\n return isTokenCounts(row['delta']);\n}\n\nfunction zeroCounts(): TokenCounts {\n return { input: 0, output: 0, cache_creation: 0, cache_read: 0 };\n}\n\nfunction addCounts(a: TokenCounts, b: TokenCounts): TokenCounts {\n return {\n input: a.input + b.input,\n output: a.output + b.output,\n cache_creation: a.cache_creation + b.cache_creation,\n cache_read: a.cache_read + b.cache_read,\n };\n}\n\n/**\n * Last-row-per-session trick for pre-0.9.0 flat-field rows.\n * Groups rows by session_id, takes the row with max ts per group,\n * and sums the flat input/output/cache_* fields across those last rows.\n */\nfunction lastRowTrickForFlatRows(rows: Record<string, unknown>[]): TokenCounts {\n const sessionMap = new Map<string, Record<string, unknown>>();\n\n for (const row of rows) {\n const sessionId = typeof row['session_id'] === 'string' ? row['session_id'] : '(unknown)';\n const existing = sessionMap.get(sessionId);\n if (!existing) {\n sessionMap.set(sessionId, row);\n } else {\n const existingTs = typeof existing['ts'] === 'string' ? existing['ts'] : '';\n const rowTs = typeof row['ts'] === 'string' ? row['ts'] : '';\n if (rowTs > existingTs) {\n sessionMap.set(sessionId, row);\n }\n }\n }\n\n let totals = zeroCounts();\n for (const row of sessionMap.values()) {\n totals = addCounts(totals, {\n input: typeof row['input'] === 'number' ? row['input'] : 0,\n output: typeof row['output'] === 'number' ? row['output'] : 0,\n cache_creation: typeof row['cache_creation'] === 'number' ? row['cache_creation'] : 0,\n cache_read: typeof row['cache_read'] === 'number' ? row['cache_read'] : 0,\n });\n }\n return totals;\n}\n\n// ─── Public API ───────────────────────────────────────────────────────────────\n\n/**\n * Compute sprint-wide token totals from an array of raw ledger rows (parsed JSONL).\n *\n * Format-detection algorithm (mandatory):\n * 1. Classify each row: has `delta` object with 4 numeric fields → v2; else → flat/legacy.\n * 2. All v2 → format='delta', sum delta.* directly.\n * 3. All flat → format='pre-0.9.0', group by session_id, last-row-per-session trick.\n * 4. Mixed → format='mixed', delta rows contribute delta.*; flat rows within\n * each session use last-row trick scoped to flat rows only.\n *\n * Malformed or unrecognisable rows are skipped with a console.warn.\n *\n * @param rows Array of parsed JSON objects (unknown type for defensive parsing).\n */\nexport function sumDeltas(rows: unknown[]): SumResult {\n // Filter to recognisable objects; skip malformed rows.\n const validRows: Record<string, unknown>[] = [];\n for (const raw of rows) {\n if (typeof raw === 'object' && raw !== null && !Array.isArray(raw)) {\n validRows.push(raw as Record<string, unknown>);\n } else {\n console.warn('[ledger.ts] sumDeltas: skipping malformed row (not an object):', raw);\n }\n }\n\n if (validRows.length === 0) {\n return { totals: zeroCounts(), format: 'delta' };\n }\n\n const deltaRows = validRows.filter(hasDelta);\n const flatRows = validRows.filter((r) => !hasDelta(r));\n\n // All rows are v2 (delta) format\n if (flatRows.length === 0) {\n let totals = zeroCounts();\n for (const row of deltaRows) {\n const d = row['delta'] as TokenCounts;\n totals = addCounts(totals, d);\n }\n return { totals, format: 'delta' };\n }\n\n // All rows are pre-0.9.0 flat format\n if (deltaRows.length === 0) {\n const totals = lastRowTrickForFlatRows(flatRows);\n return {\n totals,\n format: 'pre-0.9.0',\n pre_v2_caveat:\n '**Ledger format note:** This sprint\\'s token-ledger.jsonl uses pre-0.9.0 flat-field rows; ' +\n 'cost is computed via the last-row-per-session trick ' +\n '(reconciliation accuracy ±N × real-cost where N = SubagentStop fires per session).',\n };\n }\n\n // Mixed format: both delta rows and flat rows in same ledger (e.g. SPRINT-15 cutover)\n // Delta rows → sum delta.*\n // Flat rows → group by session_id, last-row trick (scoped to flat rows only)\n let totals = zeroCounts();\n\n // Sum delta rows directly\n for (const row of deltaRows) {\n const d = row['delta'] as TokenCounts;\n totals = addCounts(totals, d);\n }\n\n // Apply last-row trick to flat rows\n const flatTotals = lastRowTrickForFlatRows(flatRows);\n totals = addCounts(totals, flatTotals);\n\n const caveat =\n `Mixed format ledger: ${deltaRows.length} delta rows + ${flatRows.length} pre-0.9.0 rows; ` +\n `flat segment uses last-row trick.`;\n\n return {\n totals,\n format: 'mixed',\n pre_v2_caveat: caveat,\n };\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAuDA,SAAS,cAAc,GAA8B;AACnD,MAAI,OAAO,MAAM,YAAY,MAAM,KAAM,QAAO;AAChD,QAAM,MAAM;AACZ,SACE,OAAO,IAAI,OAAO,MAAM,YACxB,OAAO,IAAI,QAAQ,MAAM,YACzB,OAAO,IAAI,gBAAgB,MAAM,YACjC,OAAO,IAAI,YAAY,MAAM;AAEjC;AAEA,SAAS,SAAS,KAAuC;AACvD,SAAO,cAAc,IAAI,OAAO,CAAC;AACnC;AAEA,SAAS,aAA0B;AACjC,SAAO,EAAE,OAAO,GAAG,QAAQ,GAAG,gBAAgB,GAAG,YAAY,EAAE;AACjE;AAEA,SAAS,UAAU,GAAgB,GAA6B;AAC9D,SAAO;AAAA,IACL,OAAO,EAAE,QAAQ,EAAE;AAAA,IACnB,QAAQ,EAAE,SAAS,EAAE;AAAA,IACrB,gBAAgB,EAAE,iBAAiB,EAAE;AAAA,IACrC,YAAY,EAAE,aAAa,EAAE;AAAA,EAC/B;AACF;AAOA,SAAS,wBAAwB,MAA8C;AAC7E,QAAM,aAAa,oBAAI,IAAqC;AAE5D,aAAW,OAAO,MAAM;AACtB,UAAM,YAAY,OAAO,IAAI,YAAY,MAAM,WAAW,IAAI,YAAY,IAAI;AAC9E,UAAM,WAAW,WAAW,IAAI,SAAS;AACzC,QAAI,CAAC,UAAU;AACb,iB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AAI,OAAO;AACrB,MAAAA,UAAS,UAAUA,SAAQ,CAAC;AAAA,IAC9B;AACA,WAAO,EAAE,QAAAA,SAAQ,QAAQ,QAAQ;AAAA,EACnC;AAGA,MAAI,UAAU,WAAW,GAAG;AAC1B,UAAMA,UAAS,wBAAwB,QAAQ;AAC/C,WAAO;AAAA,MACL,QAAAA;AAAA,MACA,QAAQ;AAAA,MACR,eACE;AAAA,IAGJ;AAAA,EACF;AAKA,MAAI,SAAS,WAAW;AAGxB,aAAW,OAAO,WAAW;AAC3B,UAAM,IAAI,IAAI,OAAO;AACrB,aAAS,UAAU,QAAQ,CAAC;AAAA,EAC9B;AAGA,QAAM,aAAa,wBAAwB,QAAQ;AACnD,WAAS,UAAU,QAAQ,UAAU;AAErC,QAAM,SACJ,wBAAwB,UAAU,MAAM,iBAAiB,SAAS,MAAM;AAG1E,SAAO;AAAA,IACL;AAAA,IACA,QAAQ;AAAA,IACR,eAAe;AAAA,EACjB;AACF;","names":["totals"]}
|
package/dist/lib/ledger.js.map
DELETED
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"sources":["../../src/lib/ledger.ts"],"sourcesContent":["/**\n * ledger.ts — CR-018\n *\n * Sprint-wide cost math: parses token-ledger.jsonl rows and sums delta tokens\n * for the Reporter agent. Distinct from ledger-reader.ts (per-work-item\n * attribution lookup); this file provides sumDeltas() for sprint-total cost.\n *\n * Format detection handles three cases:\n * 'delta' — all rows carry delta.* blocks (post-0.9.0)\n * 'pre-0.9.0' — all rows use flat input/output/cache_* fields (pre-0.9.0)\n * 'mixed' — some rows have delta, others don't (SPRINT-15 cutover window)\n */\n\n// ─── Public types ─────────────────────────────────────────────────────────────\n\n/** Token counts block (used in both delta and session_total). */\nexport interface TokenCounts {\n input: number;\n output: number;\n cache_creation: number;\n cache_read: number;\n}\n\n/** Full post-0.9.0 ledger row shape. */\nexport interface LedgerRowV2 {\n ts: string;\n sprint_id: string;\n story_id: string;\n work_item_id: string;\n agent_type: string;\n session_id: string;\n transcript?: string;\n sentinel_started_at?: string;\n delta_from_turn?: number;\n delta: TokenCounts;\n session_total: TokenCounts;\n model: string;\n turns: number;\n}\n\n/** Result returned by sumDeltas(). */\nexport interface SumResult {\n /** Aggregated token totals across all rows (using appropriate format). */\n totals: TokenCounts;\n /** How the totals were computed. */\n format: 'delta' | 'pre-0.9.0' | 'mixed';\n /**\n * Present when format is 'pre-0.9.0' or 'mixed'.\n * Reporter should paste this verbatim into REPORT.md §3.\n */\n pre_v2_caveat?: string;\n}\n\n// ─── Internal helpers ─────────────────────────────────────────────────────────\n\nfunction isTokenCounts(v: unknown): v is TokenCounts {\n if (typeof v !== 'object' || v === null) return false;\n const obj = v as Record<string, unknown>;\n return (\n typeof obj['input'] === 'number' &&\n typeof obj['output'] === 'number' &&\n typeof obj['cache_creation'] === 'number' &&\n typeof obj['cache_read'] === 'number'\n );\n}\n\nfunction hasDelta(row: Record<string, unknown>): boolean {\n return isTokenCounts(row['delta']);\n}\n\nfunction zeroCounts(): TokenCounts {\n return { input: 0, output: 0, cache_creation: 0, cache_read: 0 };\n}\n\nfunction addCounts(a: TokenCounts, b: TokenCounts): TokenCounts {\n return {\n input: a.input + b.input,\n output: a.output + b.output,\n cache_creation: a.cache_creation + b.cache_creation,\n cache_read: a.cache_read + b.cache_read,\n };\n}\n\n/**\n * Last-row-per-session trick for pre-0.9.0 flat-field rows.\n * Groups rows by session_id, takes the row with max ts per group,\n * and sums the flat input/output/cache_* fields across those last rows.\n */\nfunction lastRowTrickForFlatRows(rows: Record<string, unknown>[]): TokenCounts {\n const sessionMap = new Map<string, Record<string, unknown>>();\n\n for (const row of rows) {\n const sessionId = typeof row['session_id'] === 'string' ? row['session_id'] : '(unknown)';\n const existing = sessionMap.get(sessionId);\n if (!existing) {\n sessionMap.set(sessionId, row);\n } else {\n const existingTs = typeof existing['ts'] === 'string' ? existing['ts'] : '';\n const rowTs = typeof row['ts'] === 'string' ? row['ts'] : '';\n if (rowTs > existingTs) {\n sessionMap.set(sessionId, row);\n }\n }\n }\n\n let totals = zeroCounts();\n for (const row of sessionMap.values()) {\n totals = addCounts(totals, {\n input: typeof row['input'] === 'number' ? row['input'] : 0,\n output: typeof row['output'] === 'number' ? row['output'] : 0,\n cache_creation: typeof row['cache_creation'] === 'number' ? row['cache_creation'] : 0,\n cache_read: typeof row['cache_read'] === 'number' ? row['cache_read'] : 0,\n });\n }\n return totals;\n}\n\n// ─── Public API ───────────────────────────────────────────────────────────────\n\n/**\n * Compute sprint-wide token totals from an array of raw ledger rows (parsed JSONL).\n *\n * Format-detection algorithm (mandatory):\n * 1. Classify each row: has `delta` object with 4 numeric fields → v2; else → flat/legacy.\n * 2. All v2 → format='delta', sum delta.* directly.\n * 3. All flat → format='pre-0.9.0', group by session_id, last-row-per-session trick.\n * 4. Mixed → format='mixed', delta rows contribute delta.*; flat rows within\n * each session use last-row trick scoped to flat rows only.\n *\n * Malformed or unrecognisable rows are skipped with a console.warn.\n *\n * @param rows Array of parsed JSON objects (unknown type for defensive parsing).\n */\nexport function sumDeltas(rows: unknown[]): SumResult {\n // Filter to recognisable objects; skip malformed rows.\n const validRows: Record<string, unknown>[] = [];\n for (const raw of rows) {\n if (typeof raw === 'object' && raw !== null && !Array.isArray(raw)) {\n validRows.push(raw as Record<string, unknown>);\n } else {\n console.warn('[ledger.ts] sumDeltas: skipping malformed row (not an object):', raw);\n }\n }\n\n if (validRows.length === 0) {\n return { totals: zeroCounts(), format: 'delta' };\n }\n\n const deltaRows = validRows.filter(hasDelta);\n const flatRows = validRows.filter((r) => !hasDelta(r));\n\n // All rows are v2 (delta) format\n if (flatRows.length === 0) {\n let totals = zeroCounts();\n for (const row of deltaRows) {\n const d = row['delta'] as TokenCounts;\n totals = addCounts(totals, d);\n }\n return { totals, format: 'delta' };\n }\n\n // All rows are pre-0.9.0 flat format\n if (deltaRows.length === 0) {\n const totals = lastRowTrickForFlatRows(flatRows);\n return {\n totals,\n format: 'pre-0.9.0',\n pre_v2_caveat:\n '**Ledger format note:** This sprint\\'s token-ledger.jsonl uses pre-0.9.0 flat-field rows; ' +\n 'cost is computed via the last-row-per-session trick ' +\n '(reconciliation accuracy ±N × real-cost where N = SubagentStop fires per session).',\n };\n }\n\n // Mixed format: both delta rows and flat rows in same ledger (e.g. SPRINT-15 cutover)\n // Delta rows → sum delta.*\n // Flat rows → group by session_id, last-row trick (scoped to flat rows only)\n let totals = zeroCounts();\n\n // Sum delta rows directly\n for (const row of deltaRows) {\n const d = row['delta'] as TokenCounts;\n totals = addCounts(totals, d);\n }\n\n // Apply last-row trick to flat rows\n const flatTotals = lastRowTrickForFlatRows(flatRows);\n totals = addCounts(totals, flatTotals);\n\n const caveat =\n `Mixed format ledger: ${deltaRows.length} delta rows + ${flatRows.length} pre-0.9.0 rows; ` +\n `flat segment uses last-row trick.`;\n\n return {\n totals,\n format: 'mixed',\n pre_v2_caveat: caveat,\n };\n}\n"],"mappings":";;;;;;;;AAAA;AAuDA,SAAS,cAAc,GAA8B;AACnD,MAAI,OAAO,MAAM,YAAY,MAAM,KAAM,QAAO;AAChD,QAAM,MAAM;AACZ,SACE,OAAO,IAAI,OAAO,MAAM,YACxB,OAAO,IAAI,QAAQ,MAAM,YACzB,OAAO,IAAI,gBAAgB,MAAM,YACjC,OAAO,IAAI,YAAY,MAAM;AAEjC;AAEA,SAAS,SAAS,KAAuC;AACvD,SAAO,cAAc,IAAI,OAAO,CAAC;AACnC;AAEA,SAAS,aAA0B;AACjC,SAAO,EAAE,OAAO,GAAG,QAAQ,GAAG,gBAAgB,GAAG,YAAY,EAAE;AACjE;AAEA,SAAS,UAAU,GAAgB,GAA6B;AAC9D,SAAO;AAAA,IACL,OAAO,EAAE,QAAQ,EAAE;AAAA,IACnB,QAAQ,EAAE,SAAS,EAAE;AAAA,IACrB,gBAAgB,EAAE,iBAAiB,EAAE;AAAA,IACrC,YAAY,EAAE,aAAa,EAAE;AAAA,EAC/B;AACF;AAOA,SAAS,wBAAwB,MAA8C;AAC7E,QAAM,aAAa,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AAQ;AAC3C,QAAM,WAAW,UAAU,OAAO,CAAC,MAAM,CAAC,SAAS,CAAC,CAAC;AAGrD,MAAI,SAAS,WAAW,GAAG;AACzB,QAAIA,UAAS,WAAW;AACxB,eAAW,OAAO,WAAW;AAC3B,YAAM,IAAI,IAAI,OAAO;AACrB,MAAAA,UAAS,UAAUA,SAAQ,CAAC;AAAA,IAC9B;AACA,WAAO,EAAE,QAAAA,SAAQ,QAAQ,QAAQ;AAAA,EACnC;AAGA,MAAI,UAAU,WAAW,GAAG;AAC1B,UAAMA,UAAS,wBAAwB,QAAQ;AAC/C,WAAO;AAAA,MACL,QAAAA;AAAA,MACA,QAAQ;AAAA,MACR,eACE;AAAA,IAGJ;AAAA,EACF;AAKA,MAAI,SAAS,WAAW;AAGxB,aAAW,OAAO,WAAW;AAC3B,UAAM,IAAI,IAAI,OAAO;AACrB,aAAS,UAAU,QAAQ,CAAC;AAAA,EAC9B;AAGA,QAAM,aAAa,wBAAwB,QAAQ;AACnD,WAAS,UAAU,QAAQ,UAAU;AAErC,QAAM,SACJ,wBAAwB,UAAU,MAAM,iBAAiB,SAAS,MAAM;AAG1E,SAAO;AAAA,IACL;AAAA,IACA,QAAQ;AAAA,IACR,eAAe;AAAA,EACjB;AACF;","names":["totals"]}
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"sources":["../../src/lib/lifecycle-reconcile.ts","../../src/wiki/parse-frontmatter.ts","../../src/lib/parent-rollup.ts"],"sourcesContent":["/**\n * lifecycle-reconcile.ts — CR-017 Lifecycle Status Reconciliation + Decomposition Gate\n *\n * Public API:\n * reconcileLifecycle(opts) → { drift: DriftItem[], clean: number }\n * reconcileDecomposition(opts) → { missing: MissingDecomp[], clean: number }\n * reconcileCurrentSprintStories(opts) → ReconcileCurrentSprintResult (BUG-032)\n * parseCommitMessage(msg) → Array<{ verb, id, type }>\n * VERB_STATUS_MAP — verb-to-expected-status table\n *\n * TERMINAL_STATES referenced from .cleargate/scripts/constants.mjs:45.\n * Do NOT redefine; duplicate literal with source citation.\n */\n\nimport * as fs from 'node:fs';\nimport * as path from 'node:path';\nimport { spawnSync } from 'node:child_process';\nimport { parseFrontmatter } from '../wiki/parse-frontmatter.js';\n\n// ─── Constants ─────────────────────────────────────────────────────────────────\n\n/**\n * Terminal statuses for artifact lifecycle (post-CR-067).\n * Source: .cleargate/scripts/constants.mjs:45 TERMINAL_STATES.\n * NOTE: These are the *artifact* terminal statuses, not state.json story states.\n *\n * CR-067 keep/remove decisions:\n * Completed — KEEP (sole canonical terminal post-CR-067 vocab unification)\n * Abandoned — KEEP (explicit non-completion terminal; needed for cleargate_id audit)\n * Closed — KEEP (issue-specific terminal; not subject to CR-067 vocab scope)\n * Resolved — KEEP (bug-specific terminal; not subject to CR-067 vocab scope)\n * Done — REMOVE (CR-067 unified vocab; all Done artifacts migrated to Completed)\n * Verified — REMOVE (CR-067 unified vocab; all Verified artifacts migrated to Completed)\n * Escalated — REMOVE (state.json story-state vocab, not artifact status; lives in TERMINAL_STATE_JSON)\n * Parking Lot — REMOVE (state.json story-state vocab, not artifact status; lives in TERMINAL_STATE_JSON)\n */\nexport const ARTIFACT_TERMINAL_STATUSES = new Set([\n 'Completed',\n 'Abandoned',\n 'Closed',\n 'Resolved',\n]);\n\n/**\n * Canonical single expected status for all artifact gate-checks (post-CR-067).\n * All per-verb expected[] arrays reference this constant.\n */\nconst ARTIFACT_GATE_EXPECTED = ['Completed'] as const;\n\n/**\n * Verb-to-expected-status map (v1).\n * Key: verb pattern (lower-case), Value: { types, expected }.\n * types: which artifact types this verb applies to.\n * expected: accepted terminal statuses for this verb.\n */\nexport const VERB_STATUS_MAP: Readonly<Record<string, { types: string[]; expected: string[] }>> = {\n feat: {\n types: ['STORY', 'EPIC', 'CR'],\n expected: [...ARTIFACT_GATE_EXPECTED],\n },\n fix: {\n types: ['BUG', 'HOTFIX'],\n expected: [...ARTIFACT_GATE_EXPECTED],\n },\n};\n\n// ─── Types ─────────────────────────────────────────────────────────────────────\n\nexport interface DriftItem {\n id: string;\n type: 'STORY' | 'CR' | 'BUG' | 'EPIC' | 'PROPOSAL' | 'HOTFIX';\n expected_status: string;\n actual_status: string | null;\n file_path: string | null;\n in_archive: boolean;\n commit_shas: string[];\n carry_over: boolean;\n}\n\nexport interface ReconcileLifecycleResult {\n drift: DriftItem[];\n clean: number;\n}\n\nexport interface ReconcileLifecycleOpts {\n since: Date;\n until?: Date;\n deliveryRoot: string;\n repoRoot: string;\n /** Test seam: replace spawnSync git calls */\n gitRunner?: (cmd: string, args: string[]) => string;\n}\n\nexport interface MissingDecomp {\n id: string;\n type: 'epic' | 'proposal';\n reason: 'no-child-stories' | 'no-decomposed-epic' | 'file-missing';\n expected_files: string[];\n}\n\nexport interface ReconcileDecompositionResult {\n missing: MissingDecomp[];\n clean: number;\n}\n\nexport interface ReconcileDecompositionOpts {\n sprintPlanPath: string;\n deliveryRoot: string;\n}\n\n// ─── ID shape regex (longest-alternative-first per BUG-010 + assert_story_files.mjs) ──\n\nconst ID_PATTERN = /\\b(STORY-\\d{3}-\\d{2}|(CR|BUG|EPIC|HOTFIX)-\\d{3}|(PROPOSAL|PROP)-\\d{3})\\b/g;\n\n/** Artifact type names recognized by the reconciler */\ntype ArtifactType = 'STORY' | 'CR' | 'BUG' | 'EPIC' | 'PROPOSAL' | 'HOTFIX';\n\nfunction normalizeId(raw: string): string {\n // PROP-NNN → PROPOSAL-NNN (BUG-009 lesson)\n return raw.replace(/^PROP-(\\d+)$/, 'PROPOSAL-$1');\n}\n\nfunction idType(id: string): ArtifactType | null {\n if (/^STORY-\\d{3}-\\d{2}$/.test(id)) return 'STORY';\n if (/^CR-\\d{3}$/.test(id)) return 'CR';\n if (/^BUG-\\d{3}$/.test(id)) return 'BUG';\n if (/^EPIC-\\d{3}$/.test(id)) return 'EPIC';\n if (/^PROPOSAL-\\d{3}$/.test(id)) return 'PROPOSAL';\n if (/^HOTFIX-\\d{3}$/.test(id)) return 'HOTFIX';\n return null;\n}\n\n// ─── parseCommitMessage ────────────────────────────────────────────────────────\n\n/**\n * Parse a commit message (subject + optional first body line) for work-item IDs.\n * Returns one entry per ID found with the verb inferred from conventional prefix.\n *\n * commit format: `<verb>(<scope>): <description>\\n\\n<body>`\n * multi-ID: `fix(cli)!: BUG-001 fix + CR-001 align`\n * merge: `merge: STORY-001-01 → main`\n */\nexport function parseCommitMessage(\n msg: string,\n): Array<{ verb: string; id: string; type: string }> {\n const lines = msg.split('\\n');\n const subject = lines[0] ?? '';\n\n // First non-empty body line (if any) after the blank separator\n let firstBodyLine = '';\n for (let i = 1; i < lines.length; i++) {\n if (lines[i]?.trim()) {\n firstBodyLine = lines[i]!;\n break;\n }\n }\n\n // Extract verb from subject: `feat(...)`, `fix(...)`, `merge:`, `chore(...)`, etc.\n const verbMatch = /^(\\w+)[(!]/.exec(subject) ?? /^(\\w+):/.exec(subject);\n const verb = verbMatch ? verbMatch[1]!.toLowerCase() : '';\n\n // Scan subject + first body line for IDs\n const searchText = subject + (firstBodyLine ? '\\n' + firstBodyLine : '');\n const results: Array<{ verb: string; id: string; type: string }> = [];\n const seen = new Set<string>();\n\n let m: RegExpExecArray | null;\n ID_PATTERN.lastIndex = 0;\n while ((m = ID_PATTERN.exec(searchText)) !== null) {\n const rawId = m[0]!;\n const id = normalizeId(rawId);\n if (seen.has(id)) continue;\n seen.add(id);\n const type = idType(id);\n if (!type) continue;\n results.push({ verb, id, type });\n }\n\n return results;\n}\n\n// ─── File finders ─────────────────────────────────────────────────────────────\n\ninterface FoundFile {\n absPath: string;\n inArchive: boolean;\n relPath: string; // relative to deliveryRoot\n}\n\nfunction findArtifactFile(deliveryRoot: string, id: string): FoundFile | null {\n const prefix = `${id}_`;\n const dirs: Array<{ rel: string; inArchive: boolean }> = [\n { rel: 'pending-sync', inArchive: false },\n { rel: 'archive', inArchive: true },\n ];\n for (const { rel, inArchive } of dirs) {\n const dir = path.join(deliveryRoot, rel);\n let entries: string[];\n try {\n entries = fs.readdirSync(dir);\n } catch {\n continue;\n }\n // match `ID_*.md` OR `ID.md`\n const match = entries.find(\n (e) => (e.startsWith(prefix) || e === `${id}.md`) && e.endsWith('.md'),\n );\n if (match) {\n const absPath = path.join(dir, match);\n return { absPath, inArchive, relPath: `${rel}/${match}` };\n }\n }\n return null;\n}\n\nfunction readArtifactStatus(absPath: string): { status: string | null; carryOver: boolean } {\n let raw: string;\n try {\n raw = fs.readFileSync(absPath, 'utf8');\n } catch {\n return { status: null, carryOver: false };\n }\n try {\n const { fm } = parseFrontmatter(raw);\n const status = typeof fm['status'] === 'string' ? fm['status'] : null;\n const carryOver = fm['carry_over'] === true;\n return { status, carryOver };\n } catch {\n return { status: null, carryOver: false };\n }\n}\n\n// ─── reconcileLifecycle ────────────────────────────────────────────────────────\n\n/**\n * Scan git log in [since, until] range and reconcile artifact statuses.\n *\n * For each commit touching feat/fix verbs with IDs:\n * - Find the artifact file in pending-sync or archive\n * - Check if status is at expected terminal status\n * - Report drift items for non-terminal artifacts\n * - Skip artifacts with carry_over: true\n */\nexport function reconcileLifecycle(opts: ReconcileLifecycleOpts): ReconcileLifecycleResult {\n const { since, until = new Date(), deliveryRoot, repoRoot } = opts;\n\n const gitRunner =\n opts.gitRunner ??\n ((cmd: string, args: string[]) => {\n const result = spawnSync(cmd, args, { encoding: 'utf8', cwd: repoRoot });\n return (result.stdout ?? '') as string;\n });\n\n // git log --format=\"%H %s%n%b%n---COMMIT---\" --after=<since> --before=<until>\n const sinceIso = since.toISOString();\n const untilIso = until.toISOString();\n const logOutput = gitRunner('git', [\n 'log',\n `--after=${sinceIso}`,\n `--before=${untilIso}`,\n '--format=%H%x00%s%x00%b%x00---COMMIT---',\n '--',\n ]);\n\n // Map: id → DriftItem (accumulates SHAs for bundled-commit grouping)\n // We track each id independently; bundled-commit = multiple SHAs per id\n const idToItem = new Map<string, DriftItem>();\n // Track ids that were found CLEAN (fully reconciled)\n const cleanIds = new Set<string>();\n\n if (logOutput.trim()) {\n // Split by commit separator\n const rawCommits = logOutput.split('---COMMIT---\\n').filter((c) => c.trim());\n\n for (const raw of rawCommits) {\n // Each commit entry: sha\\0subject\\0body\\0\n const [sha = '', subject = '', body = ''] = raw.split('\\x00');\n const trimSha = sha.trim();\n const trimSubject = subject.trim();\n const trimBody = body.trim();\n\n if (!trimSha || !trimSubject) continue;\n\n const commitMsg = trimSubject + (trimBody ? '\\n\\n' + trimBody : '');\n const parsed = parseCommitMessage(commitMsg);\n\n for (const { verb, id, type } of parsed) {\n // Skip merge, chore, docs, refactor, test, file, plan verbs (no expectation)\n if (verb === 'merge' || verb === 'chore' || verb === 'docs' || verb === 'refactor'\n || verb === 'test' || verb === 'file' || verb === 'plan') {\n continue;\n }\n\n // Skip PROPOSAL types — proposals aren't shipped via feat/fix commits\n if (type === 'PROPOSAL') continue;\n\n const verbConfig = VERB_STATUS_MAP[verb];\n if (!verbConfig) continue;\n\n // Verb mismatch: feat(BUG-NNN) → soft warning only, handled at call site\n // We still need to find the file and check status for the call site to report\n\n // Find the artifact file\n const found = findArtifactFile(deliveryRoot, id);\n if (!found) {\n // Unknown ID — log once at info level (no drift)\n // We skip unknown IDs (no file found); call site logs info\n continue;\n }\n\n // Read status + carry_over from CURRENT frontmatter\n const { status, carryOver } = readArtifactStatus(found.absPath);\n\n // carry_over: true → skip silently\n if (carryOver) continue;\n\n // Determine expected statuses for this (verb, type) pair\n let expectedStatuses: string[];\n if (verb === 'feat' && type === 'BUG') {\n // verb mismatch — soft warning, does not block; still check status\n // Use Completed as expected for BUG even with feat verb (post-CR-067)\n expectedStatuses = [...ARTIFACT_GATE_EXPECTED];\n } else if (!verbConfig.types.includes(type)) {\n // Type not covered by this verb's map — skip\n continue;\n } else {\n expectedStatuses = verbConfig.expected;\n }\n\n const isTerminal = status !== null && expectedStatuses.includes(status);\n const isArchived = found.inArchive;\n\n if (isTerminal && isArchived) {\n // Clean\n cleanIds.add(id);\n // If we previously recorded drift for this id (from another commit), remove it\n // (Most recent status check wins — carry_over already handled above)\n idToItem.delete(id);\n } else if (!idToItem.has(id)) {\n // New drift item\n const expectedStr = expectedStatuses[0] ?? 'Completed';\n idToItem.set(id, {\n id,\n type: type as DriftItem['type'],\n expected_status: expectedStr,\n actual_status: status,\n file_path: found.relPath,\n in_archive: isArchived,\n commit_shas: [trimSha],\n carry_over: carryOver,\n });\n } else {\n // Existing drift item — add SHA if not already present\n const existing = idToItem.get(id)!;\n if (!existing.commit_shas.includes(trimSha)) {\n existing.commit_shas.push(trimSha);\n }\n }\n }\n }\n }\n\n // Remove from drift any IDs that ended up in cleanIds\n for (const id of cleanIds) {\n idToItem.delete(id);\n }\n\n const drift = Array.from(idToItem.values());\n return { drift, clean: cleanIds.size };\n}\n\n// ─── reconcileCrossSprintOrphans ──────────────────────────────────────────────\n\n/**\n * Orphan drift item: a file in pending-sync/ with a non-terminal status\n * that has been marked Done (or another terminal state) in a closed sprint's\n * state.json — indicating it was completed but never archived.\n */\nexport interface OrphanDriftItem {\n id: string;\n type: 'CR' | 'STORY' | 'BUG' | 'EPIC' | 'HOTFIX';\n pending_sync_status: string;\n state_json_state: string;\n state_json_sprint: string;\n file_path: string;\n}\n\nexport interface ReconcileOrphansOpts {\n /** Path to .cleargate/delivery */\n deliveryRoot: string;\n /** Path to .cleargate/sprint-runs */\n sprintRunsRoot: string;\n}\n\nexport interface ReconcileOrphansResult {\n drift: OrphanDriftItem[];\n clean: number;\n}\n\n/**\n * Detect cross-sprint orphan drift: items in pending-sync/ with status: Ready\n * (or any non-terminal status) that are recorded as Done in a closed sprint's\n * state.json. These were completed but never archived at sprint close.\n *\n * Active-sprint exclusion: reads .active sentinel to identify the current\n * sprint and skips that sprint's state.json (in-flight items are not orphans).\n *\n * Scope: only scans pending-sync/*.md files matching the work-item-ID pattern.\n * Does NOT scan .script-incidents/ or any subdirectory.\n */\nexport function reconcileCrossSprintOrphans(opts: ReconcileOrphansOpts): ReconcileOrphansResult {\n const { deliveryRoot, sprintRunsRoot } = opts;\n\n // Terminal states from state.json (story-level states, not artifact statuses)\n const TERMINAL_STATE_JSON = new Set(['Done', 'Escalated', 'Parking Lot']);\n\n // Read the active sprint sentinel (to exclude it from orphan detection)\n let activeSprintId: string | null = null;\n try {\n activeSprintId = fs.readFileSync(path.join(sprintRunsRoot, '.active'), 'utf8').trim();\n } catch {\n // No .active file — no active sprint; scan all sprints\n }\n\n // Collect all pending-sync *.md files (no subdirectory traversal)\n const pendingDir = path.join(deliveryRoot, 'pending-sync');\n let pendingFiles: string[];\n try {\n pendingFiles = fs.readdirSync(pendingDir).filter(\n (f) => f.endsWith('.md') && !f.startsWith('.'),\n );\n } catch {\n pendingFiles = [];\n }\n\n // Build a map: id → { status, filePath } for each pending-sync item\n interface PendingItem {\n status: string;\n filePath: string;\n type: OrphanDriftItem['type'];\n }\n const pendingMap = new Map<string, PendingItem>();\n\n for (const fileName of pendingFiles) {\n const absPath = path.join(pendingDir, fileName);\n const { status } = readArtifactStatus(absPath);\n if (status === null) continue;\n // Skip already-terminal items in pending-sync (shouldn't be there but be safe)\n if (ARTIFACT_TERMINAL_STATUSES.has(status)) continue;\n\n // Extract ID from filename: filenames use <ID>_<slug>.md or <ID>.md format.\n // ID_PATTERN uses \\b word-boundaries which don't fire between a digit and '_'\n // (since '_' is a word char), so we extract the prefix before the first '_' or '.'.\n const fileNameNoExt = fileName.endsWith('.md') ? fileName.slice(0, -3) : fileName;\n const prefixPart = fileNameNoExt.split('_')[0] ?? fileNameNoExt;\n const rawId = prefixPart;\n const id = normalizeId(rawId);\n const type = idType(id);\n if (!type || type === 'PROPOSAL') continue;\n\n pendingMap.set(id, {\n status,\n filePath: path.join('pending-sync', fileName),\n type: type as OrphanDriftItem['type'],\n });\n }\n\n if (pendingMap.size === 0) {\n return { drift: [], clean: 0 };\n }\n\n // Walk sprint-runs directories for state.json files\n let sprintDirs: string[];\n try {\n sprintDirs = fs.readdirSync(sprintRunsRoot).filter((entry) => {\n // Skip the .active sentinel file and any hidden files\n if (entry.startsWith('.')) return false;\n // Skip non-directories (e.g. files in root)\n try {\n return fs.statSync(path.join(sprintRunsRoot, entry)).isDirectory();\n } catch {\n return false;\n }\n });\n } catch {\n sprintDirs = [];\n }\n\n const drift: OrphanDriftItem[] = [];\n // Track which IDs we've flagged to avoid duplicates (first sprint that shows Done wins)\n const flagged = new Set<string>();\n let clean = 0;\n\n for (const sprintDir of sprintDirs) {\n // Skip the active sprint\n if (activeSprintId && sprintDir === activeSprintId) continue;\n\n const stateFile = path.join(sprintRunsRoot, sprintDir, 'state.json');\n let stateJson: Record<string, unknown>;\n try {\n const raw = fs.readFileSync(stateFile, 'utf8');\n stateJson = JSON.parse(raw) as Record<string, unknown>;\n } catch {\n continue;\n }\n\n const stories = stateJson['stories'] as Record<string, { state: string }> | undefined;\n if (!stories || typeof stories !== 'object') continue;\n\n for (const [id, storyEntry] of Object.entries(stories)) {\n // Skip if already flagged from an earlier sprint\n if (flagged.has(id)) continue;\n\n const pending = pendingMap.get(id);\n if (!pending) continue; // not in pending-sync\n\n const stateInJson = storyEntry?.state ?? '';\n if (TERMINAL_STATE_JSON.has(stateInJson)) {\n // This item is Done in a closed sprint but still in pending-sync — orphan drift\n flagged.add(id);\n drift.push({\n id,\n type: pending.type,\n pending_sync_status: pending.status,\n state_json_state: stateInJson,\n state_json_sprint: sprintDir,\n file_path: pending.filePath,\n });\n } else {\n // Item is in pending-sync AND in state.json but NOT terminal — correctly in-flight\n clean++;\n }\n }\n }\n\n return { drift, clean };\n}\n\n// ─── reconcileDecomposition ───────────────────────────────────────────────────\n\n/**\n * Read the sprint plan's epics: and proposals: frontmatter arrays and verify\n * that each referenced epic has ≥1 child story file, and each proposal has\n * a decomposed epic.\n */\nexport function reconcileDecomposition(opts: ReconcileDecompositionOpts): ReconcileDecompositionResult {\n const { sprintPlanPath, deliveryRoot } = opts;\n\n // Parse sprint plan frontmatter\n let raw: string;\n try {\n raw = fs.readFileSync(sprintPlanPath, 'utf8');\n } catch {\n return { missing: [], clean: 0 };\n }\n\n let fm: Record<string, unknown>;\n try {\n ({ fm } = parseFrontmatter(raw));\n } catch {\n return { missing: [], clean: 0 };\n }\n\n const epics: string[] = Array.isArray(fm['epics']) ? fm['epics'].map(String) : [];\n const proposals: string[] = Array.isArray(fm['proposals']) ? fm['proposals'].map(String) : [];\n\n const pendingDir = path.join(deliveryRoot, 'pending-sync');\n const archiveDir = path.join(deliveryRoot, 'archive');\n\n // Read both dirs for all .md files\n function listMdFiles(dir: string): string[] {\n try {\n return fs.readdirSync(dir).filter((f) => f.endsWith('.md'));\n } catch {\n return [];\n }\n }\n const pendingFiles = listMdFiles(pendingDir);\n const archiveFiles = listMdFiles(archiveDir);\n const allFiles = [...pendingFiles, ...archiveFiles];\n\n const missing: MissingDecomp[] = [];\n let clean = 0;\n\n // Check epics\n for (const epicId of epics) {\n // Find the epic file\n const epicFile = allFiles.find(\n (f) => f.startsWith(`${epicId}_`) || f === `${epicId}.md`,\n );\n if (!epicFile) {\n missing.push({\n id: epicId,\n type: 'epic',\n reason: 'file-missing',\n expected_files: [`pending-sync/${epicId}_<name>.md`],\n });\n continue;\n }\n\n // Find child stories: any STORY-*.md with parent_epic_ref: epicId\n const childStories = findChildStories(\n epicId,\n pendingDir,\n pendingFiles,\n archiveDir,\n archiveFiles,\n );\n\n if (childStories.length === 0) {\n missing.push({\n id: epicId,\n type: 'epic',\n reason: 'no-child-stories',\n expected_files: [\n `pending-sync/${epicId.replace('EPIC-', 'STORY-')}-01_<name>.md`,\n ],\n });\n } else {\n clean++;\n }\n }\n\n // Check proposals\n for (const proposalId of proposals) {\n // Find a decomposed epic that cites this proposal in context_source\n const decomposedEpic = findDecomposedEpic(\n proposalId,\n pendingDir,\n pendingFiles,\n );\n if (!decomposedEpic) {\n missing.push({\n id: proposalId,\n type: 'proposal',\n reason: 'no-decomposed-epic',\n expected_files: [`pending-sync/EPIC-<NNN>_<name>.md with context_source citing ${proposalId}`],\n });\n } else {\n clean++;\n }\n }\n\n return { missing, clean };\n}\n\n/**\n * Find story files in pending-sync or archive that have parent_epic_ref: epicId.\n */\nfunction findChildStories(\n epicId: string,\n pendingDir: string,\n pendingFiles: string[],\n archiveDir: string,\n archiveFiles: string[],\n): string[] {\n const results: string[] = [];\n const epicNumMatch = /^EPIC-(\\d+)$/.exec(epicId);\n if (!epicNumMatch) return results;\n const epicNum = epicNumMatch[1]!;\n\n const storyPrefix = `STORY-${epicNum}-`;\n\n for (const [files, dir] of [[pendingFiles, pendingDir], [archiveFiles, archiveDir]] as const) {\n for (const f of files) {\n if (!f.startsWith(storyPrefix) && !f.startsWith('STORY-')) continue;\n // Quick filename match first\n if (!f.includes(storyPrefix)) continue;\n const absPath = path.join(dir, f);\n try {\n const raw = fs.readFileSync(absPath, 'utf8');\n const { fm } = parseFrontmatter(raw);\n const parentRef = fm['parent_epic_ref'];\n if (parentRef === epicId) {\n results.push(f);\n }\n } catch {\n // skip malformed files\n }\n }\n }\n return results;\n}\n\n/**\n * Find an epic file in pending-sync whose context_source cites proposalId.\n */\nfunction findDecomposedEpic(\n proposalId: string,\n pendingDir: string,\n pendingFiles: string[],\n): string | null {\n for (const f of pendingFiles) {\n if (!f.startsWith('EPIC-')) continue;\n const absPath = path.join(pendingDir, f);\n try {\n const raw = fs.readFileSync(absPath, 'utf8');\n const { fm } = parseFrontmatter(raw);\n const contextSource = fm['context_source'];\n if (\n typeof contextSource === 'string' &&\n contextSource.includes(proposalId)\n ) {\n return f;\n }\n } catch {\n // skip\n }\n }\n return null;\n}\n\n// ─── Verb mismatch checker (exported for test use) ────────────────────────────\n\n/**\n * Check if a (verb, type) combination is a mismatch (soft warning only in v1).\n * Returns a warning message or null if no mismatch.\n */\nexport function checkVerbMismatch(verb: string, type: string): string | null {\n if (verb === 'feat' && type === 'BUG') {\n return `verb 'feat' unusual for BUG; expected 'fix'`;\n }\n if (verb === 'fix' && (type === 'STORY' || type === 'EPIC' || type === 'CR')) {\n return `verb 'fix' unusual for ${type}; expected 'feat'`;\n }\n return null;\n}\n\n// ─── reconcileCurrentSprintStories (BUG-032) ─────────────────────────────────\n\n/**\n * Result item for a story processed by reconcileCurrentSprintStories.\n */\nexport interface CurrentSprintStoryFlip {\n id: string;\n type: OrphanDriftItem['type'];\n old_status: string;\n new_status: 'Completed';\n file_path: string;\n archived: boolean;\n}\n\nexport interface ReconcileCurrentSprintResult {\n flipped: CurrentSprintStoryFlip[];\n skipped_already_terminal: number;\n skipped_not_done: number;\n}\n\nexport interface ReconcileCurrentSprintOpts {\n /** Path to .cleargate/delivery */\n deliveryRoot: string;\n /** Path to .cleargate/sprint-runs */\n sprintRunsRoot: string;\n /** The sprint ID being closed (e.g. \"SPRINT-30\") */\n sprintId: string;\n /**\n * When true: scan ALL closed sprints (sprint_status: Completed) and flip\n * any Done stories whose frontmatter is still non-terminal.\n * Used by `cleargate sprint reconcile-lifecycle --retroactive`.\n */\n retroactive?: boolean;\n}\n\n/**\n * Atomic in-place frontmatter field rewrite (raw-bytes regex-replace).\n * Follows FLASHCARD 2026-04-24 #frontmatter #write-back pattern.\n * Rewrites a single YAML field in the --- block, preserving all other content.\n *\n * @param filePath - absolute path to the markdown file\n * @param field - YAML key name (e.g. 'status', 'approved')\n * @param rawValue - raw YAML value string (e.g. '\"Completed\"', 'true')\n */\nfunction setFrontmatterFieldAtomic(filePath: string, field: string, rawValue: string): void {\n const raw = fs.readFileSync(filePath, 'utf8');\n const fm = raw.match(/^---\\n([\\s\\S]*?)\\n---/);\n if (!fm) throw new Error(`No frontmatter in ${filePath}`);\n let newFm = fm[1];\n const fieldRx = new RegExp(`^${field}:.*$`, 'm');\n if (fieldRx.test(newFm)) {\n newFm = newFm.replace(fieldRx, `${field}: ${rawValue}`);\n } else {\n // Field not present — append it to the frontmatter block\n newFm = newFm.trimEnd() + `\\n${field}: ${rawValue}`;\n }\n const newRaw = raw.replace(fm[1], newFm);\n const tmp = filePath + '.tmp.' + process.pid;\n fs.writeFileSync(tmp, newRaw, 'utf8');\n fs.renameSync(tmp, filePath);\n}\n\n/**\n * Flip all Done-state stories in the closing sprint from their current frontmatter\n * status to `status: Completed, approved: true`, then move the file from\n * pending-sync/ to archive/.\n *\n * Root cause addressed (BUG-032): `reconcileCrossSprintOrphans` explicitly skips\n * the active sprint via the `.active` sentinel. No existing step flips same-sprint\n * story frontmatter at close time. This function fills that gap.\n *\n * Idempotence: stories already at a terminal status (Completed, Abandoned, etc.)\n * are skipped silently. Running this function twice produces the same result.\n *\n * When `retroactive: true`: scans ALL sprint-runs directories (not just the\n * provided sprintId) and flips any stories in Done-state sprints whose frontmatter\n * is still non-terminal. Used by `cleargate sprint reconcile-lifecycle --retroactive`.\n *\n * Implementation note: iterates over state.json story IDs and uses `findArtifactFile`\n * to locate the pending-sync file. This handles both standard `STORY-\\d{3}-\\d{2}`\n * and non-standard (test fixture) IDs like `STORY-TEST-01` correctly.\n */\nexport function reconcileCurrentSprintStories(\n opts: ReconcileCurrentSprintOpts,\n): ReconcileCurrentSprintResult {\n const { deliveryRoot, sprintRunsRoot, sprintId, retroactive = false } = opts;\n\n const TERMINAL_STATE_JSON = new Set(['Done', 'Escalated', 'Parking Lot']);\n const archiveDir = path.join(deliveryRoot, 'archive');\n\n // Determine which sprint dirs to scan\n let sprintDirsToScan: string[];\n if (retroactive) {\n // Retroactive: scan ALL sprint-runs dirs that are Completed\n try {\n sprintDirsToScan = fs.readdirSync(sprintRunsRoot).filter((entry) => {\n if (entry.startsWith('.')) return false;\n try {\n return fs.statSync(path.join(sprintRunsRoot, entry)).isDirectory();\n } catch {\n return false;\n }\n });\n } catch {\n sprintDirsToScan = [];\n }\n // Filter to Completed sprints only\n sprintDirsToScan = sprintDirsToScan.filter((dir) => {\n const stateFile = path.join(sprintRunsRoot, dir, 'state.json');\n try {\n const raw = fs.readFileSync(stateFile, 'utf8');\n const s = JSON.parse(raw) as Record<string, unknown>;\n return s['sprint_status'] === 'Completed';\n } catch {\n return false;\n }\n });\n } else {\n // Normal close: scan only the current sprint\n sprintDirsToScan = [sprintId];\n }\n\n const flipped: CurrentSprintStoryFlip[] = [];\n let skipped_already_terminal = 0;\n let skipped_not_done = 0;\n const flippedIds = new Set<string>();\n\n for (const dir of sprintDirsToScan) {\n const stateFile = path.join(sprintRunsRoot, dir, 'state.json');\n let stateJson: Record<string, unknown>;\n try {\n const raw = fs.readFileSync(stateFile, 'utf8');\n stateJson = JSON.parse(raw) as Record<string, unknown>;\n } catch {\n continue;\n }\n\n const stories = stateJson['stories'] as Record<string, { state: string }> | undefined;\n if (!stories || typeof stories !== 'object') continue;\n\n for (const [storyId, storyEntry] of Object.entries(stories)) {\n if (flippedIds.has(storyId)) continue; // already handled by an earlier sprint dir\n\n const stateInJson = storyEntry?.state ?? '';\n if (!TERMINAL_STATE_JSON.has(stateInJson)) {\n skipped_not_done++;\n continue;\n }\n\n // State is Done (or other terminal) in state.json — find the pending-sync file\n // Use findArtifactFile which handles ID_*.md and ID.md patterns for any ID format\n const found = findArtifactFile(deliveryRoot, storyId);\n if (!found) continue; // file not in pending-sync or archive — nothing to flip\n\n // Skip if file is already in archive (idempotence guard — already flipped)\n if (found.inArchive) {\n // Read status to check if it's already terminal\n const { status } = readArtifactStatus(found.absPath);\n if (status !== null && ARTIFACT_TERMINAL_STATUSES.has(status)) {\n skipped_already_terminal++;\n }\n // Either way, skip — already archived\n continue;\n }\n\n // File is in pending-sync — read current status\n const { status: currentStatus } = readArtifactStatus(found.absPath);\n if (currentStatus !== null && ARTIFACT_TERMINAL_STATUSES.has(currentStatus)) {\n // Already terminal in pending-sync (unusual but safe to skip)\n skipped_already_terminal++;\n continue;\n }\n\n // Compute destination path in archive/\n const fileName = path.basename(found.absPath);\n const destPath = path.join(archiveDir, fileName);\n const srcPath = found.absPath;\n\n // 1. Set status: \"Completed\" in frontmatter (Done state is authoritative)\n setFrontmatterFieldAtomic(srcPath, 'status', '\"Completed\"');\n // 2. Set approved: true in frontmatter\n setFrontmatterFieldAtomic(srcPath, 'approved', 'true');\n // 3. Move file from pending-sync/ to archive/\n fs.mkdirSync(archiveDir, { recursive: true });\n\n // Idempotence: if file already in archive, do not double-move\n if (!fs.existsSync(destPath)) {\n fs.renameSync(srcPath, destPath);\n } else {\n // Archive already has this file — remove the pending-sync copy\n fs.rmSync(srcPath, { force: true });\n }\n\n flippedIds.add(storyId);\n flipped.push({\n id: storyId,\n type: (idType(storyId) ?? 'STORY') as OrphanDriftItem['type'],\n old_status: currentStatus ?? 'unknown',\n new_status: 'Completed',\n file_path: path.join('archive', fileName),\n archived: true,\n });\n }\n }\n\n return { flipped, skipped_already_terminal, skipped_not_done };\n}\n\n// ─── Parent rollup re-exports (STORY-066-01) ──────────────────────────────────\n\nexport { rollUpParentStatus, walkActiveParents, type RollupResult } from './parent-rollup.js';\n","/**\n * YAML frontmatter parser backed by js-yaml with CORE_SCHEMA (YAML 1.2 core).\n *\n * Parses `---\\n<yaml>\\n---\\n<body>` into a typed frontmatter map + body string.\n * Preserves native types (null, boolean, number, string), nested maps, and\n * arrays. Uses CORE_SCHEMA so ISO-8601 timestamp strings are NOT coerced to\n * Date objects (YAML 1.1's quirk).\n *\n * Historical note: an earlier hand-rolled parser flattened indented nested\n * maps into top-level keys and stringified null/boolean scalars. See\n * BUG-001 and FLASHCARD entry `#yaml #frontmatter`.\n */\n\nimport yaml from 'js-yaml';\n\nexport function parseFrontmatter(raw: string): { fm: Record<string, unknown>; body: string } {\n const lines = raw.split('\\n');\n if (lines[0] !== '---') {\n throw new Error('parseFrontmatter: input does not start with ---');\n }\n let closeIdx = -1;\n for (let i = 1; i < lines.length; i++) {\n if (lines[i] === '---') { closeIdx = i; break; }\n }\n if (closeIdx === -1) {\n throw new Error('parseFrontmatter: missing closing ---');\n }\n\n const yamlText = lines.slice(1, closeIdx).join('\\n');\n const bodyLines = lines.slice(closeIdx + 1);\n // strip one leading blank line if present\n if (bodyLines[0] === '') bodyLines.shift();\n const body = bodyLines.join('\\n');\n\n if (yamlText.trim() === '') {\n return { fm: {}, body };\n }\n\n let parsed: unknown;\n try {\n parsed = yaml.load(yamlText, { schema: yaml.CORE_SCHEMA });\n } catch (err) {\n throw new Error(`parseFrontmatter: invalid YAML: ${(err as Error).message}`);\n }\n\n if (parsed === null || parsed === undefined) {\n return { fm: {}, body };\n }\n if (typeof parsed !== 'object' || Array.isArray(parsed)) {\n throw new Error('parseFrontmatter: frontmatter is not a YAML mapping');\n }\n\n return { fm: parsed as Record<string, unknown>, body };\n}\n","/**\n * parent-rollup.ts — CR-066 parent status rollup library\n *\n * Pure library: no I/O side-effects beyond reading frontmatter from disk.\n * Writing flips is the responsibility of the caller (STORY-066-02).\n *\n * Public API:\n * rollUpParentStatus(parentFilePath, opts) → Promise<RollupResult>\n * walkActiveParents(opts) → Promise<RollupResult[]>\n * RollupResult (interface)\n */\n\nimport * as fs from 'node:fs';\nimport * as path from 'node:path';\nimport { parseFrontmatter } from '../wiki/parse-frontmatter.js';\nimport { ARTIFACT_TERMINAL_STATUSES } from './lifecycle-reconcile.js';\n\n// ─── Types ─────────────────────────────────────────────────────────────────────\n\nexport interface RollupResult {\n parent_id: string;\n parent_path: string;\n current_status: string;\n proposed_status: 'Completed' | null;\n coverage: 'full' | 'partial' | 'zero' | 'sub-epic-partial';\n terminal_children: string[];\n pending_children: string[];\n verdict: 'auto-flip' | 'halt-partial' | 'halt-zero-children' | 'skip-deferred' | 'no-op';\n halt_reason?: string;\n}\n\nexport interface WalkActiveParentsOpts {\n deliveryRoot: string;\n archiveRoot: string;\n}\n\n// ─── Helpers ───────────────────────────────────────────────────────────────────\n\n/**\n * Safely parse frontmatter from a file path.\n * Returns null on any read or parse error.\n */\nfunction readFm(filePath: string): Record<string, unknown> | null {\n try {\n const raw = fs.readFileSync(filePath, 'utf8');\n const { fm } = parseFrontmatter(raw);\n return fm;\n } catch {\n return null;\n }\n}\n\n/**\n * Extract the canonical ID from frontmatter, checking all known ID-key conventions\n * in priority order before falling back to the filename stem.\n *\n * Key priority order mirrors template conventions:\n * story_id (story.md) → epic_id (epic.md) → sprint_id (Sprint Plan Template.md)\n * → bug_id (Bug.md) → cr_id (CR.md) → initiative_id (initiative.md)\n * → hotfix_id (hotfix.md)\n *\n * Filename stem fallback: takes the first underscore-delimited segment so that\n * files named \"EPIC-010_Multi_Participant_MCP_Sync.md\" resolve to \"EPIC-010\".\n */\nfunction extractId(fm: Record<string, unknown>, filePath: string): string {\n for (const key of [\n 'story_id',\n 'epic_id',\n 'sprint_id',\n 'bug_id',\n 'cr_id',\n 'initiative_id',\n 'hotfix_id',\n ]) {\n const val = fm[key];\n if (typeof val === 'string' && val.trim() !== '') return val.trim();\n }\n // Fallback: parse from filename stem (first underscore-delimited segment)\n const stem = path.basename(filePath, '.md');\n return stem.split('_')[0] ?? stem;\n}\n\n/**\n * Enumerate all children of a parent across both archive and pending-sync.\n * Children are identified by `parent_cleargate_id` OR `parent_epic_ref` frontmatter\n * matching the parentId.\n *\n * Caching is done via the fmCache map (keyed by absolute path) to avoid\n * re-reading files during recursive sub-epic walks.\n */\nfunction enumerateChildren(\n parentId: string,\n deliveryRoot: string,\n archiveRoot: string,\n fmCache: Map<string, Record<string, unknown>>\n): { id: string; status: string }[] {\n const pendingSyncDir = path.join(deliveryRoot, 'pending-sync');\n const results: { id: string; status: string }[] = [];\n\n const pools: string[] = [];\n if (fs.existsSync(archiveRoot)) pools.push(archiveRoot);\n if (fs.existsSync(pendingSyncDir)) pools.push(pendingSyncDir);\n\n for (const dir of pools) {\n let entries: string[];\n try {\n entries = fs.readdirSync(dir);\n } catch {\n entries = [];\n }\n\n for (const entry of entries) {\n if (!entry.endsWith('.md')) continue;\n const absPath = path.join(dir, entry);\n\n let fm = fmCache.get(absPath);\n if (fm === undefined) {\n const parsed = readFm(absPath);\n if (parsed === null) continue;\n fm = parsed;\n fmCache.set(absPath, fm);\n }\n\n // Match by parent_cleargate_id or parent_epic_ref\n const parentCleargateId = fm['parent_cleargate_id'];\n const parentEpicRef = fm['parent_epic_ref'];\n\n const isChild =\n (typeof parentCleargateId === 'string' && parentCleargateId.trim() === parentId) ||\n (typeof parentEpicRef === 'string' && parentEpicRef.trim() === parentId);\n\n if (!isChild) continue;\n\n const childId = extractId(fm, absPath);\n const status = typeof fm['status'] === 'string' ? fm['status'].trim() : '';\n results.push({ id: childId, status });\n }\n }\n\n return results;\n}\n\n// ─── Core rollup logic ────────────────────────────────────────────────────────\n\n/**\n * Internal implementation with cycle-detection via visited set.\n */\nasync function rollUpParentStatusInternal(\n parentFilePath: string,\n opts: WalkActiveParentsOpts,\n visited: Set<string>,\n fmCache: Map<string, Record<string, unknown>>\n): Promise<RollupResult> {\n const { deliveryRoot, archiveRoot } = opts;\n\n // Read parent frontmatter\n let fm = fmCache.get(parentFilePath);\n if (fm === undefined) {\n const raw = readFm(parentFilePath);\n if (raw === null) {\n throw new Error(`parent-rollup: cannot read frontmatter from ${parentFilePath}`);\n }\n fm = raw;\n fmCache.set(parentFilePath, fm);\n }\n\n const parentId = extractId(fm, parentFilePath);\n const currentStatus = typeof fm['status'] === 'string' ? fm['status'].trim() : '';\n\n // Short-circuit: already terminal\n if (ARTIFACT_TERMINAL_STATUSES.has(currentStatus)) {\n return {\n parent_id: parentId,\n parent_path: parentFilePath,\n current_status: currentStatus,\n proposed_status: null,\n coverage: 'full',\n terminal_children: [],\n pending_children: [],\n verdict: 'no-op',\n };\n }\n\n // Cycle detection (before recursing into sub_epics)\n if (visited.has(parentId)) {\n throw new Error(`parent-rollup: sub_epics cycle detected at ${parentId}`);\n }\n visited.add(parentId);\n\n // Sub-epic recursion path\n const subEpicsField = fm['sub_epics'];\n const subEpics: string[] =\n Array.isArray(subEpicsField) && subEpicsField.length > 0\n ? (subEpicsField as unknown[]).filter((s): s is string => typeof s === 'string')\n : [];\n\n if (subEpics.length > 0) {\n // Recurse into sub-epics\n const pendingSyncDir = path.join(deliveryRoot, 'pending-sync');\n\n const terminalSubEpics: string[] = [];\n const pendingSubEpics: string[] = [];\n\n for (const subEpicId of subEpics) {\n // Locate the sub-epic file — search pending-sync and archive\n let subEpicPath: string | null = null;\n const candidateDirs = [pendingSyncDir, archiveRoot];\n for (const dir of candidateDirs) {\n if (!fs.existsSync(dir)) continue;\n let entries: string[];\n try {\n entries = fs.readdirSync(dir);\n } catch {\n entries = [];\n }\n for (const entry of entries) {\n if (!entry.endsWith('.md')) continue;\n const absPath = path.join(dir, entry);\n let subFm = fmCache.get(absPath);\n if (subFm === undefined) {\n const parsed = readFm(absPath);\n if (parsed === null) continue;\n subFm = parsed;\n fmCache.set(absPath, subFm);\n }\n const entryId = extractId(subFm, absPath);\n if (entryId === subEpicId) {\n subEpicPath = absPath;\n break;\n }\n }\n if (subEpicPath !== null) break;\n }\n\n if (subEpicPath === null) {\n // Sub-epic file not found; treat as pending\n pendingSubEpics.push(subEpicId);\n continue;\n }\n\n // Read sub-epic frontmatter to check for DEFERRED\n let subFm = fmCache.get(subEpicPath);\n if (subFm === undefined) {\n const parsed = readFm(subEpicPath);\n if (parsed === null) {\n pendingSubEpics.push(subEpicId);\n continue;\n }\n subFm = parsed;\n fmCache.set(subEpicPath, subFm);\n }\n\n const subStatus = typeof subFm['status'] === 'string' ? subFm['status'].trim() : '';\n\n // Exclude DEFERRED sub-epics from denominator entirely\n if (subStatus === 'DEFERRED') {\n continue;\n }\n\n // Already terminal (e.g. Completed) counts as done — no further recursion needed\n if (ARTIFACT_TERMINAL_STATUSES.has(subStatus)) {\n terminalSubEpics.push(subEpicId);\n continue;\n }\n\n // Recurse: make a snapshot of visited before entering sub-epic, restore after\n // (so sibling sub-epics don't block each other)\n const visitedSnapshot = new Set(visited);\n const subResult = await rollUpParentStatusInternal(\n subEpicPath,\n opts,\n visitedSnapshot,\n fmCache\n );\n\n if (subResult.verdict === 'auto-flip' || subResult.verdict === 'no-op') {\n terminalSubEpics.push(subEpicId);\n } else {\n pendingSubEpics.push(subEpicId);\n }\n }\n\n // Remove parentId from visited since we're returning up the stack\n visited.delete(parentId);\n\n const total = terminalSubEpics.length + pendingSubEpics.length;\n\n if (total === 0) {\n // All sub-epics were DEFERRED (excluded) or none exist — treat as zero-children\n return {\n parent_id: parentId,\n parent_path: parentFilePath,\n current_status: currentStatus,\n proposed_status: null,\n coverage: 'zero',\n terminal_children: [],\n pending_children: [],\n verdict: 'halt-zero-children',\n halt_reason: `${parentId}: 0 children drafted; not reconcilable — decompose or abandon`,\n };\n }\n\n if (pendingSubEpics.length === 0) {\n return {\n parent_id: parentId,\n parent_path: parentFilePath,\n current_status: currentStatus,\n proposed_status: 'Completed',\n coverage: 'full',\n terminal_children: terminalSubEpics,\n pending_children: [],\n verdict: 'auto-flip',\n };\n }\n\n return {\n parent_id: parentId,\n parent_path: parentFilePath,\n current_status: currentStatus,\n proposed_status: null,\n coverage: 'sub-epic-partial',\n terminal_children: terminalSubEpics,\n pending_children: pendingSubEpics,\n verdict: 'halt-partial',\n halt_reason: `${parentId}: ${terminalSubEpics.length}/${total} sub-epics terminal — pending: ${pendingSubEpics.join(', ')}`,\n };\n }\n\n // Leaf-epic / sprint: enumerate children from archive + pending-sync\n const children = enumerateChildren(parentId, deliveryRoot, archiveRoot, fmCache);\n\n visited.delete(parentId);\n\n if (children.length === 0) {\n return {\n parent_id: parentId,\n parent_path: parentFilePath,\n current_status: currentStatus,\n proposed_status: null,\n coverage: 'zero',\n terminal_children: [],\n pending_children: [],\n verdict: 'halt-zero-children',\n halt_reason: `${parentId}: 0 children drafted; not reconcilable — decompose or abandon`,\n };\n }\n\n const terminalChildren: string[] = [];\n const pendingChildren: string[] = [];\n\n for (const child of children) {\n if (ARTIFACT_TERMINAL_STATUSES.has(child.status)) {\n terminalChildren.push(child.id);\n } else {\n pendingChildren.push(child.id);\n }\n }\n\n const total = terminalChildren.length + pendingChildren.length;\n\n if (pendingChildren.length === 0) {\n return {\n parent_id: parentId,\n parent_path: parentFilePath,\n current_status: currentStatus,\n proposed_status: 'Completed',\n coverage: 'full',\n terminal_children: terminalChildren,\n pending_children: [],\n verdict: 'auto-flip',\n };\n }\n\n return {\n parent_id: parentId,\n parent_path: parentFilePath,\n current_status: currentStatus,\n proposed_status: null,\n coverage: 'partial',\n terminal_children: terminalChildren,\n pending_children: pendingChildren,\n verdict: 'halt-partial',\n halt_reason: `${parentId}: ${terminalChildren.length}/${total} children terminal — pending: ${pendingChildren.join(', ')}`,\n };\n}\n\n// ─── Public API ───────────────────────────────────────────────────────────────\n\n/**\n * Roll up the status of a single parent (Epic or Sprint).\n *\n * @param parentFilePath — absolute path to the parent .md file\n * @param opts — deliveryRoot: root of the delivery tree; archiveRoot: absolute path to archive/\n * @returns RollupResult with verdict, coverage, and child lists\n */\nexport async function rollUpParentStatus(\n parentFilePath: string,\n opts: WalkActiveParentsOpts\n): Promise<RollupResult> {\n const visited = new Set<string>();\n const fmCache = new Map<string, Record<string, unknown>>();\n return rollUpParentStatusInternal(parentFilePath, opts, visited, fmCache);\n}\n\n/**\n * Walk all active parents (EPIC-*.md + SPRINT-*.md) in deliveryRoot/pending-sync/\n * and return one RollupResult per parent.\n *\n * Already-terminal parents (status: Completed/Done/etc.) emit verdict: 'no-op'.\n */\nexport async function walkActiveParents(\n opts: WalkActiveParentsOpts\n): Promise<RollupResult[]> {\n const { deliveryRoot } = opts;\n const pendingSyncDir = path.join(deliveryRoot, 'pending-sync');\n\n let entries: string[];\n try {\n entries = fs.readdirSync(pendingSyncDir);\n } catch {\n return [];\n }\n\n const parentFiles = entries.filter(\n (e) =>\n e.endsWith('.md') &&\n (e.startsWith('EPIC-') || e.startsWith('SPRINT-'))\n );\n\n const results: RollupResult[] = [];\n const fmCache = new Map<string, Record<string, unknown>>();\n\n for (const entry of parentFiles) {\n const absPath = path.join(pendingSyncDir, entry);\n try {\n const visited = new Set<string>();\n const result = await rollUpParentStatusInternal(absPath, opts, visited, fmCache);\n results.push(result);\n } catch (err) {\n // Propagate cycle errors; skip unreadable files\n if (err instanceof Error && err.message.includes('sub_epics cycle detected')) {\n throw err;\n }\n // Other errors (e.g. unreadable) — skip silently\n }\n }\n\n return results;\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA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AAM,OAAO;AAClE,UAAI,kBAAkB,QAAQ,2BAA2B,IAAI,aAAa,GAAG;AAE3E;AACA;AAAA,MACF;AAGA,YAAM,WAAgB,eAAS,MAAM,OAAO;AAC5C,YAAM,WAAgB,WAAK,YAAY,QAAQ;AAC/C,YAAM,UAAU,MAAM;AAGtB,gCAA0B,SAAS,UAAU,aAAa;AAE1D,gCAA0B,SAAS,YAAY,MAAM;AAErD,MAAG,cAAU,YAAY,EAAE,WAAW,KAAK,CAAC;AAG5C,UAAI,CAAI,eAAW,QAAQ,GAAG;AAC5B,QAAG,eAAW,SAAS,QAAQ;AAAA,MACjC,OAAO;AAEL,QAAG,WAAO,SAAS,EAAE,OAAO,KAAK,CAAC;AAAA,MACpC;AAEA,iBAAW,IAAI,OAAO;AACtB,cAAQ,KAAK;AAAA,QACX,IAAI;AAAA,QACJ,MAAO,OAAO,OAAO,KAAK;AAAA,QAC1B,YAAY,iBAAiB;AAAA,QAC7B,YAAY;AAAA,QACZ,WAAgB,WAAK,WAAW,QAAQ;AAAA,QACxC,UAAU;AAAA,MACZ,CAAC;AAAA,IACH;AAAA,EACF;AAEA,SAAO,EAAE,SAAS,0BAA0B,iBAAiB;AAC/D;","names":["fs","path","yaml","subFm","total"]}
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"sources":[],"sourcesContent":[],"mappings":"","names":[]}
|
|
@@ -1,61 +0,0 @@
|
|
|
1
|
-
---
|
|
2
|
-
name: architect-reader
|
|
3
|
-
description: Use DURING Sprint Design Review fan-out (STORY-033-03 / EPIC-033). One instance spawned per story by the Orchestrator. Reads a single story file and returns a structured digest for architect-synth to consume. Do NOT schedule, plan waves, or emit waves.json — that is architect-synth's job.
|
|
4
|
-
tools: Read, Bash
|
|
5
|
-
model: sonnet
|
|
6
|
-
---
|
|
7
|
-
|
|
8
|
-
role: architect-reader
|
|
9
|
-
|
|
10
|
-
You are the **Architect-Reader** agent for ClearGate SDR fan-out (EPIC-033). Role prefix: `role: architect-reader` (keep this string in your output so the token-ledger hook can identify you).
|
|
11
|
-
|
|
12
|
-
## Your one job
|
|
13
|
-
|
|
14
|
-
Given exactly ONE story file path, read it and return a compact structured digest. Nothing more.
|
|
15
|
-
|
|
16
|
-
## Digest shape (pin this exactly — architect-synth validates against it)
|
|
17
|
-
|
|
18
|
-
```json
|
|
19
|
-
{
|
|
20
|
-
"storyId": "STORY-NNN-NN",
|
|
21
|
-
"parallel_eligible": "y" | "n",
|
|
22
|
-
"file_surface": ["path/to/file.ts", ...],
|
|
23
|
-
"file_creates": ["path/to/new-file.ts", ...],
|
|
24
|
-
"db_write_set": ["table_name", ...],
|
|
25
|
-
"dep_predecessors": ["STORY-NNN-NN", ...]
|
|
26
|
-
}
|
|
27
|
-
```
|
|
28
|
-
|
|
29
|
-
Field sources:
|
|
30
|
-
- `storyId` — frontmatter `story_id`
|
|
31
|
-
- `parallel_eligible` — frontmatter `parallel_eligible` (default `"y"` if absent)
|
|
32
|
-
- `file_surface` — ALL paths emitted by `.cleargate/scripts/collision_surface.sh <story-file>`. Do NOT filter. Include every emitted path. If the script emits NOTHING on stdout (it prints a `[collision_surface] WARN:` line on stderr when it cannot parse any path — no §3.1 table, prose-only table, or only slash-free/extension-less tokens), report `file_surface: []` faithfully. Do NOT invent paths. An empty `file_surface` is the fail-safe signal architect-synth needs to serialize this story (BUG-033) — empty is "unproven", never "disjoint".
|
|
33
|
-
- `file_creates` — paths from §3.1 rows/cells tagged as creations ("New Files Needed" row values, "Primary File (new)" cells). Union into `file_surface` for the disjointness predicate (architect-synth unions them; reader reports separately).
|
|
34
|
-
- `db_write_set` — frontmatter `db_write_set` array (default `[]` if absent or empty)
|
|
35
|
-
- `dep_predecessors` — frontmatter `dep_predecessors` array (default `[]` if absent)
|
|
36
|
-
|
|
37
|
-
## Workflow
|
|
38
|
-
|
|
39
|
-
1. Read the story file at the path provided.
|
|
40
|
-
2. Extract frontmatter fields: `story_id`, `parallel_eligible`, `db_write_set`, `dep_predecessors`.
|
|
41
|
-
3. Run `collision_surface.sh` to get `file_surface`:
|
|
42
|
-
```bash
|
|
43
|
-
bash .cleargate/scripts/collision_surface.sh <story-file-path>
|
|
44
|
-
```
|
|
45
|
-
4. Parse §3.1 table for `file_creates` (rows whose label column contains "new" or "create", or "Primary File (new)" cells).
|
|
46
|
-
5. Return the digest JSON object ONLY — no prose, no extra fields.
|
|
47
|
-
|
|
48
|
-
## Fail-safe
|
|
49
|
-
|
|
50
|
-
If the story file is missing, unreadable, or has no parseable §3.1 table:
|
|
51
|
-
- Return a digest with `parallel_eligible: "n"`, empty arrays for all list fields.
|
|
52
|
-
- Set `storyId` to the ID extracted from the filename if frontmatter is unparseable.
|
|
53
|
-
- Do NOT throw an error — architect-synth handles missing metadata via fail-safe-serialize.
|
|
54
|
-
|
|
55
|
-
## What you are NOT
|
|
56
|
-
|
|
57
|
-
- Not a planner — do not decide wave assignments.
|
|
58
|
-
- Not architect-synth — do not emit `waves.json` or the §2.1–2.5 SDR block.
|
|
59
|
-
- Not the Architect — do not call `AskUserQuestion` or read other stories.
|
|
60
|
-
|
|
61
|
-
Return ONLY the JSON digest. One per dispatch.
|
|
@@ -1,124 +0,0 @@
|
|
|
1
|
-
---
|
|
2
|
-
name: architect-synth
|
|
3
|
-
description: Use DURING Sprint Design Review fan-out (STORY-033-03 / EPIC-033) AFTER all architect-reader agents have returned digests. Consumes N reader digests, evaluates the five-clause wave-compatibility predicate, and emits the §2.1–2.5 SDR block, Wave Assignment table, and waves.json artifact.
|
|
4
|
-
tools: Read, Write, Bash
|
|
5
|
-
model: opus
|
|
6
|
-
---
|
|
7
|
-
|
|
8
|
-
role: architect-synth
|
|
9
|
-
|
|
10
|
-
You are the **Architect-Synth** agent for ClearGate SDR fan-out (EPIC-033). Role prefix: `role: architect-synth` (keep this string in your output so the token-ledger hook can identify you).
|
|
11
|
-
|
|
12
|
-
## Your one job
|
|
13
|
-
|
|
14
|
-
Given N reader digests (one per story), compute a collision-free wave assignment and emit three outputs:
|
|
15
|
-
1. The §2.1–2.5 SDR block (as defined in `.claude/agents/architect.md` `## Sprint Design Review` section)
|
|
16
|
-
2. The Wave Assignment markdown table
|
|
17
|
-
3. `waves.json` artifact at `.cleargate/sprint-runs/<sprint-id>/plans/waves.json`
|
|
18
|
-
|
|
19
|
-
## Reader digest shape (validated on input)
|
|
20
|
-
|
|
21
|
-
```json
|
|
22
|
-
{
|
|
23
|
-
"storyId": "STORY-NNN-NN",
|
|
24
|
-
"parallel_eligible": "y" | "n",
|
|
25
|
-
"file_surface": ["path/to/file.ts", ...],
|
|
26
|
-
"file_creates": ["path/to/new-file.ts", ...],
|
|
27
|
-
"db_write_set": ["table_name", ...],
|
|
28
|
-
"dep_predecessors": ["STORY-NNN-NN", ...]
|
|
29
|
-
}
|
|
30
|
-
```
|
|
31
|
-
|
|
32
|
-
If any digest is missing required fields (`storyId`, `parallel_eligible`, `file_surface`, `file_creates`, `db_write_set`, `dep_predecessors`), treat that story as **fail-safe-serialized** (see below).
|
|
33
|
-
|
|
34
|
-
## Five-clause wave-compatibility predicate
|
|
35
|
-
|
|
36
|
-
Two stories A and B may share a wave IFF ALL five clauses hold:
|
|
37
|
-
|
|
38
|
-
1. **parallel_eligible:** `A.parallel_eligible == "y"` AND `B.parallel_eligible == "y"`
|
|
39
|
-
2. **file_surface disjoint:** `(A.file_surface ∪ A.file_creates) ∩ (B.file_surface ∪ B.file_creates) == ∅`
|
|
40
|
-
3. **file_creates disjoint:** `A.file_creates ∩ B.file_creates == ∅` (already covered by clause 2 when unioned; kept separate for clarity)
|
|
41
|
-
4. **db_write_set disjoint:** `A.db_write_set ∩ B.db_write_set == ∅`
|
|
42
|
-
5. **no dependency edge:** A is NOT in B.dep_predecessors AND B is NOT in A.dep_predecessors
|
|
43
|
-
|
|
44
|
-
Any failed clause → serialize A and B into different waves. Cite the failing clause in the wave rationale.
|
|
45
|
-
|
|
46
|
-
**Empty-surface guard (BUG-033 — do NOT fail open).** Clause 2 is only meaningful when BOTH stories have a NON-empty surface. If either story's `(file_surface ∪ file_creates)` is empty — `collision_surface.sh` emitted nothing because the story has no §3.1 table, a prose-only table, or only slash-free / extension-less tokens (`architect-reader` reports `[]`) — you must NOT read `∅ ∩ ∅ = ∅` as "disjoint". An empty surface is **unproven**, not **proven-disjoint**. Fail-safe-serialize the empty-surface story (see below) BEFORE running any pairwise clause-2 check; never co-wave it.
|
|
47
|
-
|
|
48
|
-
## Tiny-sprint floor (N ≤ 2)
|
|
49
|
-
|
|
50
|
-
When the milestone has N ≤ 2 stories: skip the fan-out computation entirely. Emit a SINGLE wave containing ALL stories with `parallel: false`. Rationale must mention "tiny-sprint floor" or "N≤2" or "sequential". **Always emit `waves.json`** even at the floor — downstream STORY-033-04 reads `parallel: false` rather than special-casing file absence.
|
|
51
|
-
|
|
52
|
-
## Fail-safe-serialize rule
|
|
53
|
-
|
|
54
|
-
A story is fail-safe-serialized when ANY of:
|
|
55
|
-
- Its digest is missing required fields (malformed frontmatter, no parseable §3.1 table)
|
|
56
|
-
- **Its surface is empty — `(file_surface ∪ file_creates)` has no entries** (BUG-033). This is distinct from "missing fields": the field is present but `[]`. An empty surface is unproven, never proven-disjoint, so it cannot be co-waved.
|
|
57
|
-
- Its `db_write_set` is non-empty (coarse DB collision axis — surface for serial treatment)
|
|
58
|
-
- It was placed here by the Orchestrator with explicit `parallel_eligible: "n"`
|
|
59
|
-
|
|
60
|
-
Fail-safe-serialized stories are placed in their own trailing serial wave, NEVER co-waved with another story. The rationale MUST contain exactly:
|
|
61
|
-
- For missing/unparseable metadata OR an empty surface: `"unknown collision metadata — fail-safe-serialized"`
|
|
62
|
-
- For DB-touching: `"DB-touching story serialized: db_write_set non-empty (coarse DB collision axis)"`
|
|
63
|
-
|
|
64
|
-
## Wave packing algorithm
|
|
65
|
-
|
|
66
|
-
1. Build a dependency graph: edge A→B means "A must precede B" (B.dep_predecessors contains A).
|
|
67
|
-
2. Topologically sort stories respecting dependency edges.
|
|
68
|
-
3. Greedily assign each story to the earliest wave where it is compatible with all already-assigned stories in that wave (predicate clauses 1-5 all pass).
|
|
69
|
-
4. Fail-safe stories skip compatibility checking — they go into their own trailing serial wave.
|
|
70
|
-
5. Number waves `wave1`, `wave2`, … in execution order.
|
|
71
|
-
6. A wave with exactly one story: `parallel: false`.
|
|
72
|
-
7. A wave with multiple stories all compatible: `parallel: true`.
|
|
73
|
-
|
|
74
|
-
## waves.json shape
|
|
75
|
-
|
|
76
|
-
```json
|
|
77
|
-
{
|
|
78
|
-
"sprint": "SPRINT-NN",
|
|
79
|
-
"generated_at": "<iso-timestamp>",
|
|
80
|
-
"waves": [
|
|
81
|
-
{
|
|
82
|
-
"wave": "wave1",
|
|
83
|
-
"stories": ["STORY-NNN-NN", "STORY-NNN-MM"],
|
|
84
|
-
"parallel": true,
|
|
85
|
-
"rationale": "disjoint file surfaces, all parallel_eligible=y, no shared db_write_set"
|
|
86
|
-
},
|
|
87
|
-
{
|
|
88
|
-
"wave": "wave2",
|
|
89
|
-
"stories": ["STORY-DB-TOUCH"],
|
|
90
|
-
"parallel": false,
|
|
91
|
-
"rationale": "DB-touching story serialized: db_write_set non-empty (coarse DB collision axis)"
|
|
92
|
-
}
|
|
93
|
-
]
|
|
94
|
-
}
|
|
95
|
-
```
|
|
96
|
-
|
|
97
|
-
Write `waves.json` to `.cleargate/sprint-runs/<sprint-id>/plans/waves.json`.
|
|
98
|
-
|
|
99
|
-
## Wave Assignment markdown table
|
|
100
|
-
|
|
101
|
-
Append to the §2.1–2.5 SDR block:
|
|
102
|
-
|
|
103
|
-
```markdown
|
|
104
|
-
## Wave Assignment
|
|
105
|
-
|
|
106
|
-
| Wave | Stories | Parallel? | Rationale |
|
|
107
|
-
|------|---------|-----------|-----------|
|
|
108
|
-
| wave1 | STORY-A, STORY-B | Yes | disjoint file surfaces, both parallel_eligible=y |
|
|
109
|
-
| wave2 | STORY-DB | No | DB-touching story serialized |
|
|
110
|
-
```
|
|
111
|
-
|
|
112
|
-
## SDR §2.1–2.5 reference
|
|
113
|
-
|
|
114
|
-
The canonical §2.1–2.5 SDR structure (Phase Plan / Merge Ordering / Shared-Surface Warnings / Lane Audit / ADR-Conflict Flags) is defined in `.claude/agents/architect.md` `## Sprint Design Review` section. Reference that section — do NOT re-document the five subsections here. Your output replaces the single-dispatch SDR for N>2 milestones.
|
|
115
|
-
|
|
116
|
-
## What you are NOT
|
|
117
|
-
|
|
118
|
-
- Not architect-reader — you consume digests; you do not read story files directly.
|
|
119
|
-
- Not the Architect — do not re-run TPV, write the milestone plan file, or read source code beyond what digests provide.
|
|
120
|
-
- Not STORY-033-04 — do not build `launch_wave.mjs`, the segment verdict, or the barrier merge.
|
|
121
|
-
|
|
122
|
-
## Autonomy Contract
|
|
123
|
-
|
|
124
|
-
During sprint execution, do NOT call `AskUserQuestion`. If a digest is malformed, fail-safe-serialize the story and proceed. If all digests are malformed, emit a single serial wave with all stories and note the condition in the rationale. Return BLOCKED only if you cannot write `waves.json` at all.
|