@opengsd/gsd-core 1.6.0 → 1.7.0-rc.1

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.
Files changed (68) hide show
  1. package/.claude-plugin/plugin.json +1 -1
  2. package/agents/gsd-verifier.md +1 -0
  3. package/bin/gsd-mcp-server.js +31 -0
  4. package/bin/install.js +293 -1145
  5. package/commands/gsd/review.md +6 -0
  6. package/gemini-extension.json +1 -1
  7. package/gsd-core/bin/gsd-tools.cjs +116 -1
  8. package/gsd-core/bin/lib/adapter-declarative.cjs +35 -0
  9. package/gsd-core/bin/lib/adapter-imperative.cjs +52 -0
  10. package/gsd-core/bin/lib/assumption-delta.cjs +231 -0
  11. package/gsd-core/bin/lib/capability-lifecycle.cjs +7 -7
  12. package/gsd-core/bin/lib/capability-loader.cjs +18 -0
  13. package/gsd-core/bin/lib/capability-lock.cjs +2 -2
  14. package/gsd-core/bin/lib/capability-registry.cjs +889 -82
  15. package/gsd-core/bin/lib/capability-source.cjs +4 -4
  16. package/gsd-core/bin/lib/capability-validator.cjs +198 -0
  17. package/gsd-core/bin/lib/cli-skew-check.cjs +44 -0
  18. package/gsd-core/bin/lib/command-aliases.cjs +8 -0
  19. package/gsd-core/bin/lib/config.cjs +27 -0
  20. package/gsd-core/bin/lib/embedding-adapter.cjs +27 -0
  21. package/gsd-core/bin/lib/external-descriptor-trust.cjs +70 -0
  22. package/gsd-core/bin/lib/hook-bus.cjs +81 -0
  23. package/gsd-core/bin/lib/host-integration.cjs +408 -0
  24. package/gsd-core/bin/lib/init.cjs +1 -1
  25. package/gsd-core/bin/lib/install-engine.cjs +755 -0
  26. package/gsd-core/bin/lib/install-profiles.cjs +35 -4
  27. package/gsd-core/bin/lib/installer-migrations.cjs +1 -1
  28. package/gsd-core/bin/lib/mcp-server.cjs +194 -0
  29. package/gsd-core/bin/lib/milestone.cjs +27 -30
  30. package/gsd-core/bin/lib/model-adapter.cjs +50 -0
  31. package/gsd-core/bin/lib/phase.cjs +41 -72
  32. package/gsd-core/bin/lib/planning-workspace.cjs +1 -1
  33. package/gsd-core/bin/lib/probe-core.cjs +91 -1
  34. package/gsd-core/bin/lib/review-reviewer-selection.cjs +129 -13
  35. package/gsd-core/bin/lib/roadmap-upgrade.cjs +3 -2
  36. package/gsd-core/bin/lib/roadmap.cjs +17 -3
  37. package/gsd-core/bin/lib/runtime-artifact-conversion.cjs +65 -9
  38. package/gsd-core/bin/lib/runtime-artifact-install-plan.cjs +54 -4
  39. package/gsd-core/bin/lib/runtime-artifact-layout.cjs +5 -2
  40. package/gsd-core/bin/lib/runtime-hooks-surface.cjs +1 -1
  41. package/gsd-core/bin/lib/runtime-name-policy.cjs +160 -30
  42. package/gsd-core/bin/lib/shell-command-projection.cjs +37 -1
  43. package/gsd-core/bin/lib/stale-bake-guard.cjs +254 -0
  44. package/gsd-core/bin/lib/state-command-router.cjs +4 -0
  45. package/gsd-core/bin/lib/state-io.cjs +55 -0
  46. package/gsd-core/bin/lib/state-transition.cjs +1588 -0
  47. package/gsd-core/bin/lib/state.cjs +306 -681
  48. package/gsd-core/bin/lib/surface.cjs +4 -1
  49. package/gsd-core/bin/lib/workstream.cjs +4 -4
  50. package/gsd-core/bin/shared/config-schema.manifest.json +9 -0
  51. package/gsd-core/references/honest-verifier.md +105 -0
  52. package/gsd-core/references/reviewer-instances.md +99 -0
  53. package/gsd-core/workflows/autonomous.md +9 -9
  54. package/gsd-core/workflows/manager.md +15 -15
  55. package/gsd-core/workflows/plan-phase.md +1 -1
  56. package/gsd-core/workflows/review.md +26 -0
  57. package/gsd-core/workflows/thread.md +4 -4
  58. package/gsd-core/workflows/verify-phase.md +11 -4
  59. package/hooks/dist/gsd-graphify-update.sh +7 -1
  60. package/hooks/gsd-graphify-update.sh +7 -1
  61. package/package.json +4 -4
  62. package/scripts/ci-test-scope.cjs +38 -9
  63. package/scripts/lint-allow-test-rule-refs.allowlist.json +0 -1
  64. package/scripts/lint-regression-test-names.allowlist.json +3 -0
  65. package/scripts/lint-test-file-count.allowlist.json +19 -5
  66. package/scripts/mutation-matrix.cjs +45 -3
  67. package/scripts/prompt-injection-scan.sh +8 -0
  68. package/scripts/lint-windows-test-portability.cjs +0 -178
@@ -0,0 +1,1588 @@
1
+ "use strict";
2
+ /**
3
+ * STATE.md Transition Module — ADR-1769.
4
+ *
5
+ * Phase 1 substrate: field-classification table, section constants, the pure
6
+ * `transitionCore` dispatch, and the `beginPhase` intent (migrating
7
+ * `cmdStateBeginPhase` in state.cts onto this seam).
8
+ *
9
+ * Sibling/super-module of the STATE.md Document Module (state-document.cjs):
10
+ * consumes its `stateExtractField` / `stateReplaceField` primitives. Body
11
+ * section headings live as constants here (single writer after migration).
12
+ *
13
+ * Pure core + injected I/O (ADR-1769 §3): the exported `transitionCore` is a
14
+ * pure function `(content, intent, deps) → result`; adapters that own locks,
15
+ * file I/O, and the disk-scan wrap it.
16
+ */
17
+ Object.defineProperty(exports, "__esModule", { value: true });
18
+ exports.STATE_MD_SECTIONS = exports.FIELD_CLASSIFICATION = void 0;
19
+ exports.getFieldClassification = getFieldClassification;
20
+ exports.applyStatePreservation = applyStatePreservation;
21
+ exports.transitionCore = transitionCore;
22
+ // eslint-disable-next-line @typescript-eslint/no-require-imports
23
+ const frontmatter = require("./frontmatter.cjs");
24
+ const state_document_cjs_1 = require("./state-document.cjs");
25
+ const state_document_cjs_2 = require("./state-document.cjs");
26
+ const markdown_sectionizer_cjs_1 = require("./markdown-sectionizer.cjs");
27
+ const phase_lifecycle_cjs_1 = require("./phase-lifecycle.cjs");
28
+ // eslint-disable-next-line @typescript-eslint/no-require-imports
29
+ const phaseIdMod = require("./phase-id.cjs");
30
+ const { extractFrontmatter, reconstructFrontmatter } = frontmatter;
31
+ const { escapeRegex } = phaseIdMod;
32
+ // Stop predicate for section-body slicing: a level-2+ heading ends the section.
33
+ const STOP_H2_PLUS = (lv) => lv >= 2;
34
+ /**
35
+ * Single source of truth for "which fields win when frontmatter and body
36
+ * disagree". Transitions declare which body fields they touch; the core
37
+ * consults the table to apply the preservation policy uniformly.
38
+ *
39
+ * Adding a new STATE.md field = one row here, not 9 transition edits.
40
+ *
41
+ * Field set verified against `buildStateFrontmatter` (state.cts:1474) — every
42
+ * frontmatter key emitted there has a row here.
43
+ *
44
+ * Frozen null-prototype object: prevents prototype-pollution lookups
45
+ * (`FIELD_CLASSIFICATION['toString']` returns undefined, not the inherited
46
+ * function). Use `getFieldClassification()` for lookups.
47
+ */
48
+ exports.FIELD_CLASSIFICATION = Object.freeze(Object.assign(Object.create(null), {
49
+ // Schema
50
+ gsd_state_version: { source: 'free', preservation: 'derive' },
51
+ // Milestone (external — from ROADMAP.md)
52
+ milestone: { source: 'external', preservation: 'preserve-if-placeholder' },
53
+ milestone_name: { source: 'external', preservation: 'preserve-if-placeholder' },
54
+ // Phase / plan position (body-derived)
55
+ current_phase: { source: 'body', preservation: 'preserve-when-unchanged' },
56
+ current_phase_name: { source: 'curated', preservation: 'preserve-always' }, // #1743, #1695
57
+ current_plan: { source: 'body', preservation: 'preserve-when-unchanged' },
58
+ // Status / lifecycle (body-derived; #1230 delta heuristic applies)
59
+ status: { source: 'body', preservation: 'preserve-when-unchanged' },
60
+ stopped_at: { source: 'body', preservation: 'preserve-when-unchanged' },
61
+ paused_at: { source: 'body', preservation: 'preserve-when-unchanged' },
62
+ // Activity log
63
+ last_updated: { source: 'free', preservation: 'derive' }, // realClock.nowIso()
64
+ last_activity: { source: 'body', preservation: 'derive' }, // always refresh on transition
65
+ last_activity_desc: { source: 'body', preservation: 'preserve-when-unchanged' },
66
+ // Progress block (disk-derived, except the curated progress ratchet)
67
+ progress: { source: 'curated', preservation: 'preserve-always' }, // #3242, #1446
68
+ 'progress.total_phases': { source: 'disk', preservation: 'derive' },
69
+ 'progress.completed_phases': { source: 'disk', preservation: 'derive' },
70
+ 'progress.total_plans': { source: 'disk', preservation: 'derive' },
71
+ 'progress.completed_plans': { source: 'disk', preservation: 'derive' },
72
+ 'progress.percent': { source: 'disk', preservation: 'derive' },
73
+ }));
74
+ /**
75
+ * Own-property classification lookup. Returns `null` for unknown fields
76
+ * (including inherited prototype methods like `toString`/`valueOf`).
77
+ */
78
+ function getFieldClassification(field) {
79
+ if (!Object.prototype.hasOwnProperty.call(exports.FIELD_CLASSIFICATION, field))
80
+ return null;
81
+ return exports.FIELD_CLASSIFICATION[field];
82
+ }
83
+ /**
84
+ * Pure, table-driven post-sync preservation. Mutates `postFm` in place to
85
+ * mirror the pre-consolidation inline block (which also mutated in place) and
86
+ * returns whether any field was restored.
87
+ */
88
+ function applyStatePreservation(input) {
89
+ const { preFm, postFm, preFmSnapshot, resync } = input;
90
+ let mutated = false;
91
+ // Curated progress ratchet (#3242/#1446; closes the #1264 class by routing
92
+ // the policy through the table). Restored only when the table says preserve-
93
+ // always AND this transition is not re-deriving from disk (!resync). sync and
94
+ // the lifecycle transitions pass resync=true and recompute; patch/update and
95
+ // body-only writes pass resync=false and keep the curated counters.
96
+ const progressCls = getFieldClassification('progress');
97
+ if (progressCls !== null &&
98
+ progressCls.preservation === 'preserve-always' &&
99
+ !resync &&
100
+ preFm &&
101
+ preFm['progress']) {
102
+ postFm['progress'] = preFm['progress'];
103
+ mutated = true;
104
+ }
105
+ // status — #1230 body-delta heuristic. Table: preserve-when-unchanged.
106
+ const statusCls = getFieldClassification('status');
107
+ if (statusCls !== null &&
108
+ statusCls.preservation === 'preserve-when-unchanged' &&
109
+ input.postBodyStatus === input.preBodyStatus &&
110
+ typeof preFmSnapshot['status'] === 'string' &&
111
+ preFmSnapshot['status'].length > 0 &&
112
+ preFmSnapshot['status'] !== 'unknown' &&
113
+ postFm['status'] !== preFmSnapshot['status']) {
114
+ postFm['status'] = preFmSnapshot['status'];
115
+ mutated = true;
116
+ }
117
+ // stopped_at — same #1230 body-delta heuristic. Table: preserve-when-unchanged.
118
+ const stoppedCls = getFieldClassification('stopped_at');
119
+ if (stoppedCls !== null &&
120
+ stoppedCls.preservation === 'preserve-when-unchanged' &&
121
+ input.postBodyStoppedAt === input.preBodyStoppedAt &&
122
+ typeof preFmSnapshot['stopped_at'] === 'string' &&
123
+ preFmSnapshot['stopped_at'].length > 0 &&
124
+ postFm['stopped_at'] !== preFmSnapshot['stopped_at']) {
125
+ postFm['stopped_at'] = preFmSnapshot['stopped_at'];
126
+ mutated = true;
127
+ }
128
+ // current_phase_name — curated (#1743/#1695). Table: preserve-always.
129
+ const phaseNameCls = getFieldClassification('current_phase_name');
130
+ if (phaseNameCls !== null &&
131
+ phaseNameCls.preservation === 'preserve-always' &&
132
+ input.postBodyPhaseSource === input.preBodyPhaseSource &&
133
+ typeof preFmSnapshot['current_phase_name'] === 'string' &&
134
+ preFmSnapshot['current_phase_name'].length > 0 &&
135
+ postFm['current_phase_name'] !== preFmSnapshot['current_phase_name']) {
136
+ postFm['current_phase_name'] = preFmSnapshot['current_phase_name'];
137
+ mutated = true;
138
+ }
139
+ return { postFm, mutated };
140
+ }
141
+ // ----------------------------------------------------------------------------
142
+ // Body section constants (ADR-1769 §6 — single writer after migration)
143
+ // ----------------------------------------------------------------------------
144
+ /**
145
+ * Top-level STATE.md section headings (H2). Aligned byte-for-byte with the
146
+ * canonical template at `gsd-core/templates/state.md`. Sub-headings (H3) like
147
+ * `### Decisions` / `### Pending Todos` / `### Blockers/Concerns` live under
148
+ * `## Accumulated Context` and are not mutated by any Phase 1–7 transition;
149
+ * they will be added here if a future transition needs them.
150
+ *
151
+ * Verified against `gsd-core/templates/state.md` (codex Phase 1 review).
152
+ */
153
+ exports.STATE_MD_SECTIONS = {
154
+ projectReference: '## Project Reference',
155
+ currentPosition: '## Current Position',
156
+ performanceMetrics: '## Performance Metrics',
157
+ accumulatedContext: '## Accumulated Context',
158
+ deferredItems: '## Deferred Items',
159
+ sessionContinuity: '## Session Continuity',
160
+ };
161
+ // ----------------------------------------------------------------------------
162
+ // transitionCore — pure dispatch (ADR-1769 §3)
163
+ // ----------------------------------------------------------------------------
164
+ /**
165
+ * Pure transition core. `(content, intent, deps) → result`.
166
+ *
167
+ * Discriminated-union dispatch via plain `switch` (ADR-1769 §2.7 Kernighan's
168
+ * Law: debuggability over conciseness; the substrate sets the pattern).
169
+ *
170
+ * Phases 2–7 add cases for the remaining 9 intent kinds. A missing case is
171
+ * a compile-time error (the function would not return on that path).
172
+ */
173
+ function transitionCore(content, intent, deps) {
174
+ switch (intent.kind) {
175
+ case 'beginPhase':
176
+ return beginPhaseCore(content, intent, deps);
177
+ case 'advancePlan':
178
+ return advancePlanCore(content, deps);
179
+ case 'completePhase':
180
+ return completePhaseCore(content, intent, deps);
181
+ case 'plannedPhase':
182
+ return plannedPhaseCore(content, intent, deps);
183
+ case 'milestoneSwitch':
184
+ return milestoneSwitchCore(content, intent, deps);
185
+ case 'milestoneComplete':
186
+ return milestoneCompleteCore(content, intent, deps);
187
+ case 'patch':
188
+ return patchCore(content, intent);
189
+ case 'update':
190
+ return updateCore(content, intent);
191
+ case 'prune':
192
+ return pruneCore(content, intent);
193
+ case 'sync':
194
+ return syncCore(content, intent, deps);
195
+ case 'rebuild':
196
+ return rebuildCore(content, intent, deps);
197
+ }
198
+ }
199
+ // ----------------------------------------------------------------------------
200
+ // beginPhase — intent implementation (Phase 1)
201
+ // ----------------------------------------------------------------------------
202
+ /**
203
+ * Apply a `beginPhase` transition to STATE.md content.
204
+ *
205
+ * Phase 1 scope (this file): the Status field update only. Subsequent
206
+ * behaviors land via RED-GREEN cycles per the ADR-1769 migration plan:
207
+ * - Current Phase, Current Phase Name, Current Plan, Total Plans
208
+ * - Current Position section mutation
209
+ * - Idempotency guard (#3127)
210
+ * - Resume vs first-time branching
211
+ * - #1255 / #1257 format-detection parity
212
+ *
213
+ * Adapters that acquire the STATE.md lock and call this core live in
214
+ * state.cts and consume the existing `readModifyWriteStateMd` post-sync
215
+ * machinery (preserves the #1230 delta heuristic without re-implementing it).
216
+ */
217
+ function beginPhaseCore(content, intent, deps) {
218
+ const updated = [];
219
+ // #1255: body-field replacements operate on body only (frontmatter stripped),
220
+ // not on the full content. The YAML `status:` key matches `^Status:\s*`
221
+ // before the body pipe-table row if full content is passed.
222
+ const existingFm = extractFrontmatter(content);
223
+ const hasFrontmatter = Object.keys(existingFm).length > 0;
224
+ let body = stripFrontmatter(content);
225
+ const reassemble = (b) => hasFrontmatter
226
+ ? `---\n${reconstructFrontmatter(existingFm)}\n---\n\n${b}`
227
+ : b;
228
+ const today = deps.clock.today();
229
+ // Consult the field-classification table for the frontmatter keys this
230
+ // transition touches (codex Phase 1 review: "table not consulted by
231
+ // transitionCore"). The table tracks FRONTMATTER keys (lowercase: `status`,
232
+ // `current_phase`, `last_activity`); body field names like `Status` /
233
+ // `Current Phase` are aliases and aren't enforced here — they're driven by
234
+ // the first-time/resume branching below, which encodes the same rules.
235
+ // Phase 2+ will dispatch preservation based on this lookup.
236
+ for (const fmKey of ['status', 'current_phase', 'current_plan', 'last_activity']) {
237
+ const cls = getFieldClassification(fmKey);
238
+ if (cls === null) {
239
+ throw new Error(`transitionCore beginPhase: frontmatter key ${JSON.stringify(fmKey)} is not in FIELD_CLASSIFICATION; ` +
240
+ `add a row per ADR-1769 §4 before touching it.`);
241
+ }
242
+ }
243
+ // Helper: try to replace a body field; push to `updated` on success.
244
+ // Body field names (Title Case: 'Status', 'Current Phase') are not in the
245
+ // table — they're body-side aliases of classified frontmatter keys.
246
+ const tryField = (name, value) => {
247
+ const replaced = (0, state_document_cjs_1.stateReplaceField)(body, name, value);
248
+ if (replaced !== null) {
249
+ body = replaced;
250
+ updated.push(name);
251
+ }
252
+ };
253
+ // #3127 idempotency guard: if Status already contains "Executing Phase N" for
254
+ // the current phase number, this is a resume (e.g. --wave N continue). Skip
255
+ // the first-time-only fields so mid-flight state (Current Plan, Total Plans,
256
+ // Current Phase Name, Last Activity Description) is preserved.
257
+ // Extract from body (not full content) so the YAML `status:` key cannot
258
+ // shadow the body Status field (#1255).
259
+ const currentStatus = (0, state_document_cjs_1.stateExtractField)(body, 'Status') || '';
260
+ const isAlreadyExecuting = new RegExp(`Executing Phase\\s+${escapeRegex(String(intent.phaseNumber))}\\b`, 'i').test(currentStatus);
261
+ // Status update (applies on both first-time and resume — Status is always refreshed).
262
+ tryField('Status', `Executing Phase ${intent.phaseNumber}`);
263
+ // Last Activity date — safe to refresh on resume (tracks when execute-phase ran).
264
+ tryField('Last Activity', today);
265
+ if (!isAlreadyExecuting) {
266
+ // First-time execution: set all progress fields.
267
+ tryField('Last Activity Description', `Phase ${intent.phaseNumber} execution started`);
268
+ tryField('Current Phase', String(intent.phaseNumber));
269
+ if (intent.phaseName) {
270
+ tryField('Current Phase Name', intent.phaseName);
271
+ }
272
+ tryField('Current Plan', '1');
273
+ if (intent.planCount) {
274
+ tryField('Total Plans in Phase', String(intent.planCount));
275
+ }
276
+ // **Current focus:** body text line (#1104).
277
+ const focusLabel = intent.phaseName
278
+ ? `Phase ${intent.phaseNumber} — ${intent.phaseName}`
279
+ : `Phase ${intent.phaseNumber}`;
280
+ const focusPattern = /(\*\*Current focus:\*\*\s*).*/i;
281
+ if (focusPattern.test(body)) {
282
+ body = body.replace(focusPattern, (_match, prefix) => `${prefix}${focusLabel}`);
283
+ updated.push('Current focus');
284
+ }
285
+ // ## Current Position section mutation (#1104, #1365).
286
+ // ADR-1372 T6: tokenizeHeadings + offset splicing (replaceSection adoption
287
+ // deferred to a later phase). Mirrors state.cts:2261-2324 byte-for-behaviour.
288
+ body = mutateCurrentPositionFirstTime(body, intent, today, updated);
289
+ }
290
+ else {
291
+ // Resume path: only update Last activity timestamp in Current Position
292
+ // (do not touch Plan:, Phase:, Status:, stopped_at, progress.percent).
293
+ body = mutateCurrentPositionResume(body, intent, today, updated);
294
+ }
295
+ return { content: reassemble(body), updated };
296
+ }
297
+ /**
298
+ * Find the `## Current Position` section, return its `{start, end}` byte
299
+ * offsets in `body` (end is exclusive — first byte of the next section or
300
+ * body.length). Returns `null` when the section is absent.
301
+ *
302
+ * ADR-1372 T6: tokenizeHeadings-based locator (fence-aware).
303
+ */
304
+ function locateCurrentPosition(body) {
305
+ const hs = (0, markdown_sectionizer_cjs_1.tokenizeHeadings)(body);
306
+ const idx = hs.findIndex(h => h.level === 2 && /^current\s+position$/i.test(h.text));
307
+ if (idx === -1)
308
+ return null;
309
+ const h = hs[idx];
310
+ const lines = body.split('\n');
311
+ const hl = lines[h.line - 1];
312
+ const start = h.offset + hl.length + 1;
313
+ let end = body.length;
314
+ for (let j = idx + 1; j < hs.length; j++) {
315
+ if (STOP_H2_PLUS(hs[j].level)) {
316
+ end = hs[j].offset - 1;
317
+ break;
318
+ }
319
+ }
320
+ return { start, end };
321
+ }
322
+ /**
323
+ * First-time ## Current Position mutation: update Phase / Plan / Status /
324
+ * Last activity lines. Mirrors state.cts:2261-2324 byte-for-behaviour
325
+ * (inline regex first, pipe-table fallback via stateReplaceField — #1257).
326
+ */
327
+ function mutateCurrentPositionFirstTime(body, intent, today, updated) {
328
+ const span = locateCurrentPosition(body);
329
+ if (span === null)
330
+ return body;
331
+ let sectionBody = body.slice(span.start, span.end);
332
+ // Phase line — inline first, then pipe-table fallback (#1257).
333
+ const phaseLabel = `${intent.phaseNumber}${intent.phaseName ? ` (${intent.phaseName})` : ''} — EXECUTING`;
334
+ if (/^Phase:/m.test(sectionBody)) {
335
+ sectionBody = sectionBody.replace(/^Phase:.*$/m, `Phase: ${phaseLabel}`);
336
+ }
337
+ else {
338
+ const replaced = (0, state_document_cjs_1.stateReplaceField)(sectionBody, 'Phase', phaseLabel);
339
+ if (replaced !== null)
340
+ sectionBody = replaced;
341
+ }
342
+ // Plan line.
343
+ const planValue = `1 of ${intent.planCount || '?'}`;
344
+ if (/^Plan:/m.test(sectionBody)) {
345
+ sectionBody = sectionBody.replace(/^Plan:.*$/m, `Plan: ${planValue}`);
346
+ }
347
+ else {
348
+ const replaced = (0, state_document_cjs_1.stateReplaceField)(sectionBody, 'Plan', planValue);
349
+ if (replaced !== null)
350
+ sectionBody = replaced;
351
+ }
352
+ // Status line.
353
+ const statusValue = `Executing Phase ${intent.phaseNumber}`;
354
+ if (/^Status:/m.test(sectionBody)) {
355
+ sectionBody = sectionBody.replace(/^Status:.*$/m, `Status: ${statusValue}`);
356
+ }
357
+ else {
358
+ const replaced = (0, state_document_cjs_1.stateReplaceField)(sectionBody, 'Status', statusValue);
359
+ if (replaced !== null)
360
+ sectionBody = replaced;
361
+ }
362
+ // Last activity line. The inline value carries date + narrative.
363
+ const activityValue = `${today} — Phase ${intent.phaseNumber} execution started`;
364
+ if (/^Last activity:/im.test(sectionBody)) {
365
+ sectionBody = sectionBody.replace(/^Last activity:.*$/im, `Last activity: ${activityValue}`);
366
+ }
367
+ else {
368
+ const replaced = (0, state_document_cjs_1.stateReplaceField)(sectionBody, 'Last Activity', activityValue) ??
369
+ (0, state_document_cjs_1.stateReplaceField)(sectionBody, 'Last activity', activityValue);
370
+ if (replaced !== null)
371
+ sectionBody = replaced;
372
+ }
373
+ updated.push('Current Position');
374
+ return body.slice(0, span.start) + sectionBody + body.slice(span.end);
375
+ }
376
+ /**
377
+ * Resume ## Current Position mutation: only update Last activity line
378
+ * (preserves Plan/Phase/Status — #3127). Mirrors state.cts:2329-2363
379
+ * byte-for-behaviour.
380
+ */
381
+ function mutateCurrentPositionResume(body, intent, today, updated) {
382
+ const span = locateCurrentPosition(body);
383
+ if (span === null)
384
+ return body;
385
+ let sectionBody = body.slice(span.start, span.end);
386
+ const resumeActivity = `Last activity: ${today} — Phase ${intent.phaseNumber} execution resumed (wave continue)`;
387
+ if (/^Last activity:/im.test(sectionBody)) {
388
+ sectionBody = sectionBody.replace(/^Last activity:.*$/im, resumeActivity);
389
+ updated.push('Last activity (resume)');
390
+ }
391
+ else {
392
+ // Pipe-table format fallback (#1255).
393
+ const replaced = (0, state_document_cjs_1.stateReplaceField)(sectionBody, 'Last Activity', resumeActivity) ??
394
+ (0, state_document_cjs_1.stateReplaceField)(sectionBody, 'Last activity', resumeActivity);
395
+ if (replaced !== null) {
396
+ sectionBody = replaced;
397
+ updated.push('Last activity (resume)');
398
+ }
399
+ }
400
+ return body.slice(0, span.start) + sectionBody + body.slice(span.end);
401
+ }
402
+ /**
403
+ * Strip ALL frontmatter blocks from the start of `content`.
404
+ *
405
+ * TODO (ADR-1769 follow-up): move to `frontmatter.cjs` or `state-document.cjs`
406
+ * so it's a shared primitive. Inlined here in Phase 1 to avoid touching
407
+ * `state.cjs` (which is the migration target itself) and to keep the Phase 1
408
+ * diff contained. Body is byte-identical to `state.cts:1653 stripFrontmatter`
409
+ * (same CRLF + stacked-block handling).
410
+ */
411
+ function stripFrontmatter(content) {
412
+ let result = content;
413
+ while (true) {
414
+ const stripped = result.replace(/^\s*---\r?\n[\s\S]*?\r?\n---\s*/, '');
415
+ if (stripped === result)
416
+ break;
417
+ result = stripped;
418
+ }
419
+ return result;
420
+ }
421
+ /**
422
+ * Update fields within the ## Current Position section for advancePlan.
423
+ * Mirrors `updateCurrentPositionFields` (state.cts:496) byte-for-behaviour:
424
+ * only replaces Status / Last Activity when the existing value is a known
425
+ * template default (Knuth invariant: preserve executor-authored values).
426
+ * Plan is always replaced (system-derived, never executor-authored).
427
+ *
428
+ * Cannot import `updateCurrentPositionFields` from state.cjs directly (circular
429
+ * dep: state.cjs → state-transition.cjs → state.cjs), so the mutation is
430
+ * inlined here using the same primitives.
431
+ */
432
+ function mutateCurrentPositionForAdvance(content, fields, statusDefaults, lastActivityDefaults) {
433
+ const span = locateCurrentPosition(content);
434
+ if (span === null)
435
+ return content;
436
+ let sectionBody = content.slice(span.start, span.end);
437
+ let mutated = false;
438
+ if (fields.status) {
439
+ const replaced = (0, state_document_cjs_1.stateReplaceFieldIfTemplate)(sectionBody, 'Status', statusDefaults, fields.status);
440
+ if (replaced !== null && replaced !== sectionBody) {
441
+ sectionBody = replaced;
442
+ mutated = true;
443
+ }
444
+ }
445
+ if (fields.lastActivity) {
446
+ const replaced = (0, state_document_cjs_1.stateReplaceFieldIfTemplate)(sectionBody, 'Last Activity', lastActivityDefaults, fields.lastActivity) ??
447
+ (0, state_document_cjs_1.stateReplaceFieldIfTemplate)(sectionBody, 'Last activity', lastActivityDefaults, fields.lastActivity);
448
+ if (replaced !== null && replaced !== sectionBody) {
449
+ sectionBody = replaced;
450
+ mutated = true;
451
+ }
452
+ }
453
+ if (fields.plan) {
454
+ // Plan is always replaced — system-derived, not executor-authored.
455
+ if (/^Plan:/m.test(sectionBody)) {
456
+ sectionBody = sectionBody.replace(/^Plan:.*$/m, `Plan: ${fields.plan}`);
457
+ mutated = true;
458
+ }
459
+ else {
460
+ const replaced = (0, state_document_cjs_1.stateReplaceField)(sectionBody, 'Plan', fields.plan);
461
+ if (replaced !== null) {
462
+ sectionBody = replaced;
463
+ mutated = true;
464
+ }
465
+ }
466
+ }
467
+ if (!mutated)
468
+ return content;
469
+ return content.slice(0, span.start) + sectionBody + content.slice(span.end);
470
+ }
471
+ // ----------------------------------------------------------------------------
472
+ // advancePlan — intent implementation (Phase 2)
473
+ // ----------------------------------------------------------------------------
474
+ /**
475
+ * Apply an `advancePlan` transition to STATE.md content.
476
+ *
477
+ * Parses Current Plan / Total Plans (legacy separate fields or compound
478
+ * "Plan: X of Y" format), increments the plan number, updates body fields
479
+ * and the ## Current Position section. When currentPlan >= totalPlans,
480
+ * takes the phase-complete branch (sets Status to "Phase complete — ready
481
+ * for verification") instead of advancing.
482
+ *
483
+ * Uses `stateReplaceFieldIfTemplate` (template-default-aware) to preserve
484
+ * executor-authored field values (Knuth invariant from cmdStateAdvancePlan).
485
+ *
486
+ * Returns `data.advanced` / `data.currentPlan` / `data.totalPlans` for the
487
+ * adapter to construct CLI output.
488
+ */
489
+ function advancePlanCore(content, deps) {
490
+ const today = deps.clock.today();
491
+ // #1255: body-field replacements operate on body only (frontmatter stripped),
492
+ // not on the full content. The YAML `status:` key matches `^Status:\s*`
493
+ // before the body field if full content is passed (codex Phase 2 review:
494
+ // HIGH blocking finding — same pattern beginPhaseCore already handles).
495
+ const existingFm = extractFrontmatter(content);
496
+ const hasFrontmatter = Object.keys(existingFm).length > 0;
497
+ let body = stripFrontmatter(content);
498
+ const reassemble = (b) => hasFrontmatter
499
+ ? `---\n${reconstructFrontmatter(existingFm)}\n---\n\n${b}`
500
+ : b;
501
+ // Parse plan number — legacy first, then compound.
502
+ const legacyPlan = (0, state_document_cjs_1.stateExtractField)(content, 'Current Plan');
503
+ const legacyTotal = (0, state_document_cjs_1.stateExtractField)(content, 'Total Plans in Phase');
504
+ const planField = (0, state_document_cjs_1.stateExtractField)(content, 'Plan');
505
+ let currentPlan;
506
+ let totalPlans;
507
+ let useCompoundFormat = false;
508
+ if (legacyPlan && legacyTotal) {
509
+ currentPlan = parseInt(legacyPlan, 10);
510
+ totalPlans = parseInt(legacyTotal, 10);
511
+ }
512
+ else if (planField) {
513
+ currentPlan = parseInt(planField, 10);
514
+ const ofMatch = planField.match(/of\s+(\d+)/);
515
+ totalPlans = ofMatch ? parseInt(ofMatch[1], 10) : NaN;
516
+ useCompoundFormat = true;
517
+ }
518
+ else {
519
+ currentPlan = NaN;
520
+ totalPlans = NaN;
521
+ }
522
+ if (isNaN(currentPlan) || isNaN(totalPlans)) {
523
+ return { content: reassemble(body), updated: [], data: { error: true } };
524
+ }
525
+ const updated = [];
526
+ const statusDefaults = state_document_cjs_2.KNOWN_TEMPLATE_DEFAULTS['Status'];
527
+ const lastActivityDefaults = state_document_cjs_2.KNOWN_TEMPLATE_DEFAULTS['Last Activity'];
528
+ if (currentPlan >= totalPlans) {
529
+ // Phase-complete branch.
530
+ body = (0, state_document_cjs_1.stateReplaceFieldIfTemplate)(body, 'Status', statusDefaults, 'Phase complete — ready for verification') || body;
531
+ body = (0, state_document_cjs_1.stateReplaceFieldIfTemplate)(body, 'Last Activity', lastActivityDefaults, today) || body;
532
+ body = (0, state_document_cjs_1.stateReplaceFieldIfTemplate)(body, 'Last activity', lastActivityDefaults, today) || body;
533
+ body = mutateCurrentPositionForAdvance(body, {
534
+ status: 'Phase complete — ready for verification',
535
+ lastActivity: today,
536
+ }, statusDefaults, lastActivityDefaults);
537
+ updated.push('Status', 'Last Activity', 'Current Position');
538
+ return {
539
+ content: reassemble(body),
540
+ updated,
541
+ data: { advanced: false, reason: 'last_plan', current_plan: currentPlan, total_plans: totalPlans, status: 'ready_for_verification' },
542
+ };
543
+ }
544
+ // Normal advance branch.
545
+ const newPlan = currentPlan + 1;
546
+ let planDisplayValue;
547
+ if (useCompoundFormat) {
548
+ planDisplayValue = planField.replace(/^\d+/, String(newPlan));
549
+ body = (0, state_document_cjs_1.stateReplaceField)(body, 'Plan', planDisplayValue) || body;
550
+ }
551
+ else {
552
+ planDisplayValue = `${newPlan} of ${totalPlans}`;
553
+ body = (0, state_document_cjs_1.stateReplaceField)(body, 'Current Plan', String(newPlan)) || body;
554
+ }
555
+ body = (0, state_document_cjs_1.stateReplaceFieldIfTemplate)(body, 'Status', statusDefaults, 'Ready to execute') || body;
556
+ body = (0, state_document_cjs_1.stateReplaceFieldIfTemplate)(body, 'Last Activity', lastActivityDefaults, today) || body;
557
+ body = (0, state_document_cjs_1.stateReplaceFieldIfTemplate)(body, 'Last activity', lastActivityDefaults, today) || body;
558
+ body = mutateCurrentPositionForAdvance(body, {
559
+ status: 'Ready to execute',
560
+ lastActivity: today,
561
+ plan: planDisplayValue,
562
+ }, statusDefaults, lastActivityDefaults);
563
+ updated.push('Current Plan', 'Status', 'Last Activity', 'Current Position');
564
+ return {
565
+ content: reassemble(body),
566
+ updated,
567
+ data: { advanced: true, previous_plan: currentPlan, current_plan: newPlan, total_plans: totalPlans },
568
+ };
569
+ }
570
+ // ----------------------------------------------------------------------------
571
+ // completePhase — intent implementation (Phase 3)
572
+ // ----------------------------------------------------------------------------
573
+ /**
574
+ * Apply a `completePhase` transition to STATE.md content.
575
+ *
576
+ * Migrates the inline STATE.md transform that lived inside `cmdPhaseComplete`
577
+ * (phase.cts) onto the substrate. Owns the field-classification-governed body
578
+ * mutations: Current Phase (preserving the `of total` shape and phase name),
579
+ * Current Phase Name, Status (`Milestone complete` on the last phase, else
580
+ * `Ready to plan`), Current Plan (`Not started`), Last Activity + Description,
581
+ * and the Completed/Total Phases + Progress percent block (re-derived from the
582
+ * roadmap via the injected `roadmapProvider`).
583
+ *
584
+ * The adapter (`cmdPhaseComplete`) retains two concerns that are NOT pure field
585
+ * updates: `updatePerformanceMetricsSection` (a section table upsert) and
586
+ * `syncStateFrontmatter` (the disk-scan post-sync). It also retains the
587
+ * multi-file atomic transaction (`writePlanningFileSet`) that writes ROADMAP,
588
+ * REQUIREMENTS, and STATE together — `readModifyWriteStateMd` is not used here
589
+ * because STATE.md is committed atomically with the other two files.
590
+ *
591
+ * Behavior is byte-for-byte with the pre-migration `phase.cts:1671-1772` block
592
+ * (verified by characterization tests in tests/state-transition.test.cjs).
593
+ */
594
+ function completePhaseCore(content, intent, deps) {
595
+ const updated = [];
596
+ const today = deps.clock.today();
597
+ // Consult the field-classification table for the frontmatter keys this
598
+ // transition touches (same guard beginPhaseCore applies). A missing row is a
599
+ // substrate defect — fail loudly rather than silently re-encoding policy.
600
+ for (const fmKey of [
601
+ 'current_phase',
602
+ 'current_phase_name',
603
+ 'status',
604
+ 'current_plan',
605
+ 'last_activity',
606
+ 'last_activity_desc',
607
+ 'progress',
608
+ ]) {
609
+ const cls = getFieldClassification(fmKey);
610
+ if (cls === null) {
611
+ throw new Error(`transitionCore completePhase: frontmatter key ${JSON.stringify(fmKey)} is not in FIELD_CLASSIFICATION; ` +
612
+ `add a row per ADR-1769 §4 before touching it.`);
613
+ }
614
+ }
615
+ // #1255: body-field replacements operate on body only (frontmatter stripped),
616
+ // so the YAML `status:` / `current_phase:` keys cannot shadow the body fields.
617
+ const existingFm = extractFrontmatter(content);
618
+ const hasFrontmatter = Object.keys(existingFm).length > 0;
619
+ let body = stripFrontmatter(content);
620
+ const reassemble = (b) => hasFrontmatter
621
+ ? `---\n${reconstructFrontmatter(existingFm)}\n---\n\n${b}`
622
+ : b;
623
+ // Current Phase — preserve the existing `of <total>` shape and the phase name
624
+ // in parens (mirrors phase.cts:1675-1697 byte-for-behaviour).
625
+ const phaseValue = intent.nextPhaseNum || intent.phaseNum;
626
+ const nextPhaseDisplayName = intent.nextPhaseName;
627
+ const existingPhaseField = (0, state_document_cjs_1.stateExtractField)(body, 'Current Phase') || (0, state_document_cjs_1.stateExtractField)(body, 'Phase');
628
+ let newPhaseValue = String(phaseValue);
629
+ if (existingPhaseField) {
630
+ const totalMatch = existingPhaseField.match(/of\s+(\d+)/);
631
+ const nameMatch = existingPhaseField.match(/\(([^)]+)\)/);
632
+ if (totalMatch) {
633
+ const total = totalMatch[1];
634
+ const nameStr = nextPhaseDisplayName
635
+ ? ` (${nextPhaseDisplayName})`
636
+ : nameMatch
637
+ ? ` (${nameMatch[1]})`
638
+ : '';
639
+ newPhaseValue = `${phaseValue} of ${total}${nameStr}`;
640
+ }
641
+ else if (nextPhaseDisplayName) {
642
+ newPhaseValue = `${phaseValue} — ${nextPhaseDisplayName}`;
643
+ }
644
+ }
645
+ const phaseAfter = (0, state_document_cjs_1.stateReplaceFieldWithFallback)(body, 'Current Phase', 'Phase', newPhaseValue);
646
+ if (phaseAfter !== body) {
647
+ body = phaseAfter;
648
+ updated.push('Current Phase');
649
+ }
650
+ // Current Phase Name — only written when a next-phase display name is known
651
+ // (#1743/#1695: classified curated/preserve-always, so an absent name does
652
+ // NOT clear an existing curated value).
653
+ if (nextPhaseDisplayName) {
654
+ const after = (0, state_document_cjs_1.stateReplaceField)(body, 'Current Phase Name', nextPhaseDisplayName);
655
+ if (after) {
656
+ body = after;
657
+ updated.push('Current Phase Name');
658
+ }
659
+ }
660
+ // Status — `Milestone complete` on the final phase, otherwise `Ready to plan`.
661
+ const statusValue = intent.isLastPhase ? 'Milestone complete' : 'Ready to plan';
662
+ const statusAfter = (0, state_document_cjs_1.stateReplaceFieldWithFallback)(body, 'Status', null, statusValue);
663
+ if (statusAfter !== body) {
664
+ body = statusAfter;
665
+ updated.push('Status');
666
+ }
667
+ // Current Plan — reset for the next phase.
668
+ const planAfter = (0, state_document_cjs_1.stateReplaceFieldWithFallback)(body, 'Current Plan', 'Plan', 'Not started');
669
+ if (planAfter !== body) {
670
+ body = planAfter;
671
+ updated.push('Current Plan');
672
+ }
673
+ // Last Activity — prefer the prose `Last activity:` line (date + narrative)
674
+ // when present, else the bold `Last Activity:` date field.
675
+ const lastActivityDescription = `Phase ${intent.phaseNum} complete${intent.nextPhaseNum ? `, transitioned to Phase ${intent.nextPhaseNum}` : ''}`;
676
+ if (/^Last activity:/m.test(body)) {
677
+ const after = (0, state_document_cjs_1.stateReplaceField)(body, 'Last activity', `${today} — ${lastActivityDescription}`);
678
+ if (after) {
679
+ body = after;
680
+ updated.push('Last Activity');
681
+ }
682
+ }
683
+ else {
684
+ const after = (0, state_document_cjs_1.stateReplaceField)(body, 'Last Activity', today);
685
+ if (after) {
686
+ body = after;
687
+ updated.push('Last Activity');
688
+ }
689
+ }
690
+ const ladAfter = (0, state_document_cjs_1.stateReplaceField)(body, 'Last Activity Description', lastActivityDescription);
691
+ if (ladAfter) {
692
+ body = ladAfter;
693
+ updated.push('Last Activity Description');
694
+ }
695
+ // Progress block — re-derive completed/total phases from the roadmap when
696
+ // available (milestone-wide source of truth), then recompute the percent.
697
+ // Only runs when a Completed Phases field exists (the existing guard).
698
+ const completedRaw = (0, state_document_cjs_1.stateExtractField)(body, 'Completed Phases');
699
+ if (completedRaw !== null) {
700
+ let newCompleted = parseInt(completedRaw, 10);
701
+ let derivedTotalPhases = null;
702
+ const roadmapContent = deps.roadmapProvider ? deps.roadmapProvider() : null;
703
+ if (roadmapContent) {
704
+ const derived = (0, phase_lifecycle_cjs_1.deriveProgressFromRoadmap)(roadmapContent);
705
+ if (derived.completedPhases !== null)
706
+ newCompleted = derived.completedPhases;
707
+ if (derived.totalPhases !== null)
708
+ derivedTotalPhases = derived.totalPhases;
709
+ }
710
+ const completedAfter = (0, state_document_cjs_1.stateReplaceField)(body, 'Completed Phases', String(newCompleted));
711
+ if (completedAfter) {
712
+ body = completedAfter;
713
+ updated.push('Completed Phases');
714
+ }
715
+ const totalRaw = (0, state_document_cjs_1.stateExtractField)(body, 'Total Phases');
716
+ const totalPhases = derivedTotalPhases || (totalRaw ? parseInt(totalRaw, 10) : null);
717
+ if (totalPhases && totalPhases > 0) {
718
+ const newPercent = (0, phase_lifecycle_cjs_1.clampPercent)(newCompleted, totalPhases);
719
+ const progAfter = (0, state_document_cjs_1.stateReplaceField)(body, 'Progress', `${newPercent}%`);
720
+ if (progAfter) {
721
+ body = progAfter;
722
+ updated.push('Progress');
723
+ }
724
+ // Inline `percent:` token (frontmatter / progress sub-block).
725
+ body = body.replace(/(percent:\s*)\d+/, `$1${newPercent}`);
726
+ }
727
+ }
728
+ return { content: reassemble(body), updated };
729
+ }
730
+ // ----------------------------------------------------------------------------
731
+ // plannedPhase — intent implementation (Phase 4)
732
+ // ----------------------------------------------------------------------------
733
+ /**
734
+ * Apply a `plannedPhase` transition to STATE.md content.
735
+ *
736
+ * Migrates `cmdStatePlannedPhase` (state.cts) onto the substrate. Updates the
737
+ * per-phase body fields after plan-phase runs: Status (template-aware — only
738
+ * replaces handler-generated values, preserving executor-authored ones),
739
+ * Total Plans in Phase, Last Activity (template-aware), Last Activity
740
+ * Description, and the ## Current Position section. The adapter wraps this in
741
+ * `readModifyWriteStateMd({ resync: false })` so the milestone-wide progress.*
742
+ * frontmatter is NOT re-derived from a half-planned disk snapshot (#500 RC1).
743
+ *
744
+ * Uses `mutateCurrentPositionForAdvance` (the inlined twin of state.cts's
745
+ * `updateCurrentPositionFields`) so the Knuth template-default invariant
746
+ * applies inside the Current Position section too.
747
+ */
748
+ function plannedPhaseCore(content, intent, deps) {
749
+ const updated = [];
750
+ const today = deps.clock.today();
751
+ for (const fmKey of ['status', 'last_activity', 'last_activity_desc']) {
752
+ const cls = getFieldClassification(fmKey);
753
+ if (cls === null) {
754
+ throw new Error(`transitionCore plannedPhase: frontmatter key ${JSON.stringify(fmKey)} is not in FIELD_CLASSIFICATION; ` +
755
+ `add a row per ADR-1769 §4 before touching it.`);
756
+ }
757
+ }
758
+ // #1255: body-field replacements operate on body only.
759
+ const existingFm = extractFrontmatter(content);
760
+ const hasFrontmatter = Object.keys(existingFm).length > 0;
761
+ let body = stripFrontmatter(content);
762
+ const reassemble = (b) => hasFrontmatter
763
+ ? `---\n${reconstructFrontmatter(existingFm)}\n---\n\n${b}`
764
+ : b;
765
+ const statusDefaults = state_document_cjs_2.KNOWN_TEMPLATE_DEFAULTS['Status'];
766
+ const lastActivityDefaults = state_document_cjs_2.KNOWN_TEMPLATE_DEFAULTS['Last Activity'];
767
+ // Status — template-aware (preserve executor-authored values).
768
+ const statusAfter = (0, state_document_cjs_1.stateReplaceFieldIfTemplate)(body, 'Status', statusDefaults, 'Ready to execute');
769
+ if (statusAfter !== null && statusAfter !== body) {
770
+ body = statusAfter;
771
+ updated.push('Status');
772
+ }
773
+ // Total Plans in Phase — system-derived; always replaced when a count is given.
774
+ if (intent.planCount !== null && intent.planCount !== undefined) {
775
+ const result = (0, state_document_cjs_1.stateReplaceField)(body, 'Total Plans in Phase', String(intent.planCount));
776
+ if (result) {
777
+ body = result;
778
+ updated.push('Total Plans in Phase');
779
+ }
780
+ }
781
+ // Last Activity — template-aware.
782
+ const lastActivityAfter = (0, state_document_cjs_1.stateReplaceFieldIfTemplate)(body, 'Last Activity', lastActivityDefaults, today);
783
+ if (lastActivityAfter !== null && lastActivityAfter !== body) {
784
+ body = lastActivityAfter;
785
+ updated.push('Last Activity');
786
+ }
787
+ // Last Activity Description.
788
+ const ladResult = (0, state_document_cjs_1.stateReplaceField)(body, 'Last Activity Description', `Phase ${intent.phaseNumber} planning complete — ${intent.planCount || '?'} plans ready`);
789
+ if (ladResult) {
790
+ body = ladResult;
791
+ updated.push('Last Activity Description');
792
+ }
793
+ // ## Current Position section — Status + Last activity (template-aware).
794
+ const beforePos = body;
795
+ body = mutateCurrentPositionForAdvance(body, {
796
+ status: 'Ready to execute',
797
+ lastActivity: `${today} — Phase ${intent.phaseNumber} planning complete`,
798
+ }, statusDefaults, lastActivityDefaults);
799
+ if (body !== beforePos)
800
+ updated.push('Current Position');
801
+ return { content: reassemble(body), updated };
802
+ }
803
+ // ----------------------------------------------------------------------------
804
+ // milestoneSwitch — intent implementation (Phase 4)
805
+ // ----------------------------------------------------------------------------
806
+ /**
807
+ * Apply a `milestoneSwitch` transition to STATE.md content.
808
+ *
809
+ * Migrates `cmdStateMilestoneSwitch` (state.cts) onto the substrate. Resets
810
+ * STATE.md for a new milestone cycle: rewrites the frontmatter (milestone,
811
+ * milestone_name, status='planning', last_updated, last_activity, and the
812
+ * progress block zeroed) and rewrites the ## Current Position body to the
813
+ * "defining requirements" starting state. `gsd_state_version` is preserved.
814
+ * Body content OUTSIDE Current Position (e.g. Accumulated Context) is
815
+ * preserved.
816
+ *
817
+ * This is a destructive reset intent: it intentionally overwrites the curated
818
+ * `progress` / `current_phase_name` fields (classified preserve-always) because
819
+ * a new milestone starts from zero. That is the intent's contract, not a
820
+ * violation of the field-classification table — the table governs the steady-
821
+ * state RMW transitions; a milestone boundary is an explicit reset.
822
+ *
823
+ * The adapter wraps this in `acquireStateLock` + `platformWriteSync` (NOT
824
+ * `readModifyWriteStateMd`) because milestoneSwitch rebuilds frontmatter
825
+ * directly and must not run the steady-state `syncStateFrontmatter` post-sync.
826
+ */
827
+ function milestoneSwitchCore(content, intent, deps) {
828
+ const today = deps.clock.today();
829
+ const updated = [
830
+ 'milestone',
831
+ 'milestone_name',
832
+ 'status',
833
+ 'last_updated',
834
+ 'last_activity',
835
+ 'progress',
836
+ 'Current Position',
837
+ ];
838
+ const existingFm = extractFrontmatter(content);
839
+ const body = stripFrontmatter(content);
840
+ const resolvedName = (intent.name && intent.name.trim()) || 'milestone';
841
+ // ## Current Position reset body (mirrors state.cts:2371-2375).
842
+ const resetPositionBody = `\nPhase: Not started (defining requirements)\n` +
843
+ `Plan: —\n` +
844
+ `Status: Defining requirements\n` +
845
+ `Last activity: ${today} — Milestone ${intent.version} started\n\n`;
846
+ let newBody;
847
+ const hs = (0, markdown_sectionizer_cjs_1.tokenizeHeadings)(body);
848
+ const posIdx = hs.findIndex((h) => h.level === 2 && /^current\s+position$/i.test(h.text));
849
+ if (posIdx !== -1) {
850
+ const h = hs[posIdx];
851
+ const lines = body.split('\n');
852
+ const hl = lines[h.line - 1];
853
+ const bodyStart = h.offset + hl.length + 1;
854
+ let bodyEnd = body.length;
855
+ for (let j = posIdx + 1; j < hs.length; j++) {
856
+ if (STOP_H2_PLUS(hs[j].level)) {
857
+ bodyEnd = hs[j].offset - 1;
858
+ break;
859
+ }
860
+ }
861
+ newBody = body.slice(0, bodyStart) + resetPositionBody + body.slice(bodyEnd);
862
+ }
863
+ else {
864
+ const preface = body.trim().length > 0 ? body : '# Project State\n';
865
+ newBody = `${preface.trimEnd()}\n\n## Current Position\n${resetPositionBody}`;
866
+ }
867
+ // Rebuilt frontmatter — curated fields are intentionally reset (milestone
868
+ // boundary). gsd_state_version is preserved.
869
+ const fm = {
870
+ gsd_state_version: existingFm['gsd_state_version'] || '1.0',
871
+ milestone: intent.version,
872
+ milestone_name: resolvedName,
873
+ status: 'planning',
874
+ last_updated: deps.clock.nowIso(),
875
+ last_activity: today,
876
+ progress: {
877
+ total_phases: 0,
878
+ completed_phases: 0,
879
+ total_plans: 0,
880
+ completed_plans: 0,
881
+ percent: 0,
882
+ },
883
+ };
884
+ const yamlStr = reconstructFrontmatter(fm);
885
+ const assembled = `---\n${yamlStr}\n---\n\n${newBody.replace(/^\n+/, '')}`;
886
+ return { content: assembled, updated };
887
+ }
888
+ // ----------------------------------------------------------------------------
889
+ // milestoneComplete — intent implementation (Phase 5)
890
+ // ----------------------------------------------------------------------------
891
+ /**
892
+ * Apply a `milestoneComplete` transition to STATE.md content.
893
+ *
894
+ * Migrates the STATE.md write path inside `cmdMilestoneComplete` (milestone.cts)
895
+ * onto the substrate. Owns the closure write: Status (`<version> milestone
896
+ * complete`), Last Activity, Last Activity Description, a ## Current Position
897
+ * reset to the "Awaiting next milestone" state, and a ## Operator Next Steps
898
+ * reset pointing at the next-milestone command.
899
+ *
900
+ * The adapter (`cmdMilestoneComplete`) retains `writeStateMd` (the writer that
901
+ * owns the lock + steady-state syncStateFrontmatter post-sync) and resolves the
902
+ * runtime-specific next-milestone slash command, injecting it via
903
+ * `intent.nextMilestoneCommand` so the core stays pure.
904
+ *
905
+ * The two section resets use raw regex (with the pre-seam `allow-adhoc-markdown`
906
+ * waivers carried from milestone.cts) rather than tokenizeHeadings because the
907
+ * `## Operator Next Steps` section is non-canonical (not in STATE_MD_SECTIONS)
908
+ * and the existing behavior + its tests pin the exact regex semantics. A future
909
+ * collectSection migration (#1372) can swap both to section primitives.
910
+ *
911
+ * Behavior is byte-for-byte with the pre-migration milestone.cts:314-353 block.
912
+ */
913
+ function milestoneCompleteCore(content, intent, deps) {
914
+ const updated = [];
915
+ const today = deps.clock.today();
916
+ const version = intent.version;
917
+ for (const fmKey of ['status', 'last_activity', 'last_activity_desc']) {
918
+ const cls = getFieldClassification(fmKey);
919
+ if (cls === null) {
920
+ throw new Error(`transitionCore milestoneComplete: frontmatter key ${JSON.stringify(fmKey)} is not in FIELD_CLASSIFICATION; ` +
921
+ `add a row per ADR-1769 §4 before touching it.`);
922
+ }
923
+ }
924
+ // #1255: body-field replacements operate on body only.
925
+ const existingFm = extractFrontmatter(content);
926
+ const hasFrontmatter = Object.keys(existingFm).length > 0;
927
+ let body = stripFrontmatter(content);
928
+ const reassemble = (b) => hasFrontmatter
929
+ ? `---\n${reconstructFrontmatter(existingFm)}\n---\n\n${b}`
930
+ : b;
931
+ // Status — `<version> milestone complete`.
932
+ const statusAfter = (0, state_document_cjs_1.stateReplaceFieldWithFallback)(body, 'Status', null, `${version} milestone complete`);
933
+ if (statusAfter !== body) {
934
+ body = statusAfter;
935
+ updated.push('Status');
936
+ }
937
+ // Last Activity.
938
+ const lastActivityAfter = (0, state_document_cjs_1.stateReplaceFieldWithFallback)(body, 'Last Activity', 'Last activity', today);
939
+ if (lastActivityAfter !== body) {
940
+ body = lastActivityAfter;
941
+ updated.push('Last Activity');
942
+ }
943
+ // Last Activity Description.
944
+ const ladAfter = (0, state_document_cjs_1.stateReplaceFieldWithFallback)(body, 'Last Activity Description', null, `${version} milestone completed and archived`);
945
+ if (ladAfter !== body) {
946
+ body = ladAfter;
947
+ updated.push('Last Activity Description');
948
+ }
949
+ // ## Current Position reset — stop resume/progress flows pointing at closed
950
+ // execution instructions.
951
+ const positionPattern = /(##\s*Current Position\s*\n)([\s\S]*?)(?=\n##|$)/i; // allow-adhoc-markdown: pre-seam section write-modify carried from milestone.cts; pending collectSection migration #1372
952
+ const closedPositionBody = `\nPhase: Milestone ${version} complete\n` +
953
+ `Plan: —\n` +
954
+ `Status: Awaiting next milestone\n` +
955
+ `Last activity: ${today} — Milestone ${version} completed and archived\n\n`;
956
+ if (positionPattern.test(body)) {
957
+ body = body.replace(positionPattern, (_m, header) => `${header}${closedPositionBody}`);
958
+ }
959
+ else {
960
+ body = `${body.trimEnd()}\n\n## Current Position\n${closedPositionBody}`;
961
+ }
962
+ updated.push('Current Position');
963
+ // ## Operator Next Steps — normalize stale tails that can persist after close.
964
+ const operatorPattern = /(##\s*Operator Next Steps\s*\n)([\s\S]*?)(?=\n##|$)/i; // allow-adhoc-markdown: pre-seam section write-modify carried from milestone.cts; pending collectSection migration #1372
965
+ if (operatorPattern.test(body)) {
966
+ body = body.replace(operatorPattern, `$1\n- Start the next milestone with ${intent.nextMilestoneCommand}\n\n`);
967
+ }
968
+ else {
969
+ body = `${body.trimEnd()}\n\n## Operator Next Steps\n\n- Start the next milestone with ${intent.nextMilestoneCommand}\n`;
970
+ }
971
+ updated.push('Operator Next Steps');
972
+ return { content: reassemble(body), updated };
973
+ }
974
+ // ----------------------------------------------------------------------------
975
+ // patch — intent implementation (Phase 6)
976
+ // ----------------------------------------------------------------------------
977
+ /**
978
+ * Apply a `patch` transition to STATE.md content.
979
+ *
980
+ * Migrates `cmdStatePatch` (state.cts) onto the substrate. Applies each
981
+ * caller-supplied `{field: value}` pair via `stateReplaceField` over the full
982
+ * content (body + frontmatter — patch can target either), tracking which fields
983
+ * were updated vs. not found.
984
+ *
985
+ * The curated-field preservation that fixes #1743/#1695 is NOT in this core —
986
+ * it lives in `readModifyWriteStateMd`'s post-sync delta (table-driven via
987
+ * `getFieldClassification('current_phase_name').preservation === 'preserve-always'`).
988
+ * `patch` consulting the table "refuses to overwrite" curated fields implicitly:
989
+ * when the patch does not change a curated field's body source line, the
990
+ * existing frontmatter value wins over the sync re-derivation. The adapter
991
+ * still owns field-name validation (security) and the resync-progress decision.
992
+ *
993
+ * `data.updated` / `data.failed` mirror the pre-migration CLI output shape.
994
+ */
995
+ function patchCore(content, intent) {
996
+ const updated = [];
997
+ const failed = [];
998
+ let result = content;
999
+ for (const [field, value] of Object.entries(intent.patches)) {
1000
+ const replaced = (0, state_document_cjs_1.stateReplaceField)(result, field, value);
1001
+ if (replaced !== null) {
1002
+ result = replaced;
1003
+ updated.push(field);
1004
+ }
1005
+ else {
1006
+ failed.push(field);
1007
+ }
1008
+ }
1009
+ return { content: result, updated, data: { updated, failed } };
1010
+ }
1011
+ // ----------------------------------------------------------------------------
1012
+ // update — intent implementation (Phase 7)
1013
+ // ----------------------------------------------------------------------------
1014
+ /**
1015
+ * Apply an `update` transition to STATE.md content.
1016
+ *
1017
+ * Migrates `cmdStateUpdate` (state.cts) onto the substrate. A single-field
1018
+ * body-only update (the field is replaced in the body; frontmatter is preserved
1019
+ * as-is and re-synced by the adapter's `readModifyWriteStateMd` post-sync).
1020
+ * Mirrors the pre-migration body-strip/reassemble contract.
1021
+ */
1022
+ function updateCore(content, intent) {
1023
+ const existingFm = extractFrontmatter(content);
1024
+ const hasFrontmatter = Object.keys(existingFm).length > 0;
1025
+ const body = stripFrontmatter(content);
1026
+ const result = (0, state_document_cjs_1.stateReplaceField)(body, intent.field, intent.value);
1027
+ if (result === null) {
1028
+ return { content, updated: [], data: { updated: false } };
1029
+ }
1030
+ const reassembled = hasFrontmatter
1031
+ ? `---\n${reconstructFrontmatter(existingFm)}\n---\n\n${result}`
1032
+ : result;
1033
+ return { content: reassembled, updated: [intent.field], data: { updated: true } };
1034
+ }
1035
+ // Stop predicate for prune section slicing: a level-2 OR level-3 heading ends
1036
+ // the section (mirrors state.cts STOP_H2_H3 — Decisions / Recently Completed /
1037
+ // Blockers / Performance Metrics live at H2 or H3).
1038
+ const STOP_H2_H3 = (lv) => lv === 2 || lv === 3;
1039
+ /**
1040
+ * Apply a `prune` transition to STATE.md content.
1041
+ *
1042
+ * Migrates the section-pruning half of `cmdStatePrune` (state.cts) onto the
1043
+ * substrate. Pure `content → {content, archivedSections}` given a cutoff phase:
1044
+ * archives Decisions / Recently Completed / resolved Blockers / Performance
1045
+ * Metrics table rows whose phase number is <= cutoff. ADR-1372 T6
1046
+ * tokenizeHeadings + untrimmed-span splicing, byte-identical to the pre-migration
1047
+ * `prunePass`.
1048
+ *
1049
+ * The adapter owns currentPhase derivation (with the #1760 `Phase` / `Current
1050
+ * Phase` fallback), keepRecent/dryRun, and STATE-ARCHIVE.md writes.
1051
+ */
1052
+ function pruneCore(content, intent) {
1053
+ const cutoff = intent.cutoff;
1054
+ const sections = [];
1055
+ let c = content;
1056
+ // Helper: locate a heading matching pred, extract untrimmed body [bs, se),
1057
+ // apply transform, splice back. All prune sections stop at level 2 or 3.
1058
+ const pruneSectionSpan = (pred, transform, sectionName) => {
1059
+ const hs = (0, markdown_sectionizer_cjs_1.tokenizeHeadings)(c);
1060
+ const i = hs.findIndex((h) => pred(h.level, h.text));
1061
+ if (i === -1)
1062
+ return;
1063
+ const h = hs[i];
1064
+ const ls = c.split('\n');
1065
+ const hl = ls[h.line - 1];
1066
+ const bs = h.offset + hl.length + 1;
1067
+ let se = c.length;
1068
+ for (let j = i + 1; j < hs.length; j++) {
1069
+ if (STOP_H2_H3(hs[j].level)) {
1070
+ se = hs[j].offset - 1;
1071
+ break;
1072
+ }
1073
+ }
1074
+ const body = c.slice(bs, se);
1075
+ const { keep, archive } = transform(body);
1076
+ if (archive.length > 0) {
1077
+ sections.push({ section: sectionName, count: archive.length, lines: archive });
1078
+ c = c.slice(0, bs) + keep.join('\n') + c.slice(se);
1079
+ }
1080
+ };
1081
+ pruneSectionSpan((lv, text) => (lv === 2 || lv === 3) && /^(?:Decisions|Decisions Made|Accumulated.*Decisions)$/i.test(text), (body) => {
1082
+ const keep = [], archive = [];
1083
+ for (const line of body.split('\n')) {
1084
+ const phaseMatch = line.match(/^\s*-\s*\[Phase\s+(\d+)/i);
1085
+ if (phaseMatch && parseInt(phaseMatch[1], 10) <= cutoff) {
1086
+ archive.push(line);
1087
+ }
1088
+ else {
1089
+ keep.push(line);
1090
+ }
1091
+ }
1092
+ return { keep, archive };
1093
+ }, 'Decisions');
1094
+ pruneSectionSpan((lv, text) => (lv === 2 || lv === 3) && /^recently\s+completed$/i.test(text), (body) => {
1095
+ const keep = [], archive = [];
1096
+ for (const line of body.split('\n')) {
1097
+ const phaseMatch = line.match(/Phase\s+(\d+)/i);
1098
+ if (phaseMatch && parseInt(phaseMatch[1], 10) <= cutoff) {
1099
+ archive.push(line);
1100
+ }
1101
+ else {
1102
+ keep.push(line);
1103
+ }
1104
+ }
1105
+ return { keep, archive };
1106
+ }, 'Recently Completed');
1107
+ pruneSectionSpan((lv, text) => (lv === 2 || lv === 3) && /^(?:Blockers|Blockers\/Concerns|Blockers\s*&\s*Concerns)$/i.test(text), (body) => {
1108
+ const keep = [], archive = [];
1109
+ for (const line of body.split('\n')) {
1110
+ const isResolved = /~~.*~~|\[RESOLVED\]/i.test(line);
1111
+ const phaseMatch = line.match(/Phase\s+(\d+)/i);
1112
+ if (isResolved && phaseMatch && parseInt(phaseMatch[1], 10) <= cutoff) {
1113
+ archive.push(line);
1114
+ }
1115
+ else {
1116
+ keep.push(line);
1117
+ }
1118
+ }
1119
+ return { keep, archive };
1120
+ }, 'Blockers (resolved)');
1121
+ pruneSectionSpan((lv, text) => (lv === 2 || lv === 3) && /^performance\s+metrics$/i.test(text), (body) => {
1122
+ const keep = [], archive = [];
1123
+ for (const line of body.split('\n')) {
1124
+ const tableRowMatch = line.match(/^\|\s*(\d+)\s*\|/);
1125
+ if (tableRowMatch) {
1126
+ const rowPhase = parseInt(tableRowMatch[1], 10);
1127
+ if (rowPhase <= cutoff) {
1128
+ archive.push(line);
1129
+ }
1130
+ else {
1131
+ keep.push(line);
1132
+ }
1133
+ }
1134
+ else {
1135
+ keep.push(line);
1136
+ }
1137
+ }
1138
+ return { keep, archive };
1139
+ }, 'Performance Metrics');
1140
+ const totalPruned = sections.reduce((sum, s) => sum + s.count, 0);
1141
+ return {
1142
+ content: c,
1143
+ updated: totalPruned > 0 ? ['pruned'] : [],
1144
+ data: { archivedSections: sections, totalPruned },
1145
+ };
1146
+ }
1147
+ // ----------------------------------------------------------------------------
1148
+ // sync — intent implementation (Phase 7)
1149
+ // ----------------------------------------------------------------------------
1150
+ /**
1151
+ * Apply a `sync` transition to STATE.md content.
1152
+ *
1153
+ * Migrates the body-write half of `cmdStateSync` (state.cts) onto the substrate.
1154
+ * Updates Total Plans in Phase, the Progress bar, and Last Activity from
1155
+ * disk-derived numbers (injected via the intent). Returns the per-field change
1156
+ * log via `data.changes` so the adapter can build the CLI output.
1157
+ *
1158
+ * #1761: when the current milestone cannot be bounded to a versioned phase set,
1159
+ * the adapter passes `percent: null` and this core leaves Progress untouched
1160
+ * (rather than silently writing fallback-derived wrong values).
1161
+ */
1162
+ function syncCore(content, intent, deps) {
1163
+ const today = deps.clock.today();
1164
+ const changes = [];
1165
+ let modified = content;
1166
+ const updated = [];
1167
+ if (intent.totalPlansInPhase !== null) {
1168
+ const currentPlansField = (0, state_document_cjs_1.stateExtractField)(modified, 'Total Plans in Phase');
1169
+ if (currentPlansField && parseInt(currentPlansField, 10) !== intent.totalPlansInPhase) {
1170
+ changes.push(`Total Plans in Phase: ${currentPlansField} -> ${intent.totalPlansInPhase}`);
1171
+ const result = (0, state_document_cjs_1.stateReplaceField)(modified, 'Total Plans in Phase', String(intent.totalPlansInPhase));
1172
+ if (result) {
1173
+ modified = result;
1174
+ updated.push('Total Plans in Phase');
1175
+ }
1176
+ }
1177
+ }
1178
+ if (intent.percent !== null) {
1179
+ const currentProgress = (0, state_document_cjs_1.stateExtractField)(modified, 'Progress');
1180
+ if (currentProgress) {
1181
+ const currentPercent = parseInt(currentProgress.replace(/[^\d]/g, ''), 10);
1182
+ if (currentPercent !== intent.percent) {
1183
+ const barWidth = 10;
1184
+ const filled = Math.round((intent.percent / 100) * barWidth);
1185
+ const bar = '█'.repeat(filled) + '░'.repeat(barWidth - filled);
1186
+ const progressStr = `[${bar}] ${intent.percent}%`;
1187
+ changes.push(`Progress: ${currentProgress} -> ${progressStr}`);
1188
+ const result = (0, state_document_cjs_1.stateReplaceField)(modified, 'Progress', progressStr);
1189
+ if (result) {
1190
+ modified = result;
1191
+ updated.push('Progress');
1192
+ }
1193
+ }
1194
+ }
1195
+ }
1196
+ const lastActivityResult = (0, state_document_cjs_1.stateReplaceField)(modified, 'Last Activity', today);
1197
+ if (lastActivityResult) {
1198
+ const oldActivity = (0, state_document_cjs_1.stateExtractField)(modified, 'Last Activity');
1199
+ if (oldActivity !== today) {
1200
+ changes.push(`Last Activity: ${oldActivity} -> ${today}`);
1201
+ updated.push('Last Activity');
1202
+ }
1203
+ modified = lastActivityResult;
1204
+ }
1205
+ return { content: modified, updated, data: { changes } };
1206
+ }
1207
+ // ----------------------------------------------------------------------------
1208
+ // rebuild — intent implementation (ADR-1817, capstone 11th transition)
1209
+ // ----------------------------------------------------------------------------
1210
+ //
1211
+ // Implements the body-structure derivability contract (ADR-1817 §2–§6):
1212
+ // - §2 re-derives derived sections (## Current Position prose, By Phase table
1213
+ // inside ## Performance Metrics), preserves curated sections verbatim
1214
+ // (## Accumulated Context, ## Deferred Items, ## Project Reference, ##
1215
+ // Session Continuity's prose fields) and unknown sections.
1216
+ // - §3 every mutation appends a structured entry to ## Rebuild Log
1217
+ // (ADR-1411 provenance principle — never drop silently).
1218
+ // - §4 idempotency: a no-mutation rebuild appends NO log entry, so two
1219
+ // successive runs on a clean file are byte-identical.
1220
+ // - §5 non-overlapping with sync (sync = 3 frontmatter fields, lightweight,
1221
+ // auto-triggered; rebuild = body structure, heavier, manual).
1222
+ // - §6 orthogonal to auto_prune_state (rebuild reconciles with current
1223
+ // canonical sources; prune removes by retention policy).
1224
+ //
1225
+ // Section ordering is invariant: rebuild rewrites content IN PLACE; it does
1226
+ // not reorder, insert (other than ## Rebuild Log when absent), or remove
1227
+ // sections.
1228
+ const REBUILD_LOG_SECTION = '## Rebuild Log';
1229
+ const REBUILD_LOG_TRUNCATION_LIMIT = 512;
1230
+ /**
1231
+ * Truncate a string for inclusion in a rebuild log entry. Per ADR-1817 §3 the
1232
+ * `before` / `after` fields are bounded to REBUILD_LOG_TRUNCATION_LIMIT chars
1233
+ * to prevent unbounded log growth when the drifted content is large.
1234
+ */
1235
+ function truncateForLog(s) {
1236
+ if (s.length <= REBUILD_LOG_TRUNCATION_LIMIT)
1237
+ return s;
1238
+ return s.slice(0, REBUILD_LOG_TRUNCATION_LIMIT - 3) + '...';
1239
+ }
1240
+ /**
1241
+ * Apply a `rebuild` transition to STATE.md content. Pure core per ADR-1769 §3
1242
+ * and ADR-1817 §1. Returns `{ content, updated, data }` where `data.mutated`
1243
+ * is false when no drift was found (idempotency contract, ADR-1817 §4).
1244
+ */
1245
+ function rebuildCore(content, _intent, deps) {
1246
+ const timestamp = deps.clock.nowIso();
1247
+ const log = [];
1248
+ let modified = content;
1249
+ // §2 Decision: re-derive derived sections, preserve others. Order is
1250
+ // oldest-section-first so log entries appear in body order.
1251
+ modified = reconcileCurrentPosition(modified, timestamp, log);
1252
+ modified = reconcileByPhaseTable(modified, deps, timestamp, log);
1253
+ modified = stripTemplatePlaceholders(modified, timestamp, log);
1254
+ modified = deduplicateSessionArchive(modified, timestamp, log);
1255
+ // §3 + §4: append the audit log ONLY when mutations occurred. The
1256
+ // log-appends-only-on-mutation rule is what makes idempotency byte-identical
1257
+ // (without it, the second invocation would always append a no-op entry).
1258
+ if (log.length > 0) {
1259
+ modified = appendRebuildLogSection(modified, log);
1260
+ }
1261
+ const updated = log.length > 0 ? ['rebuild'] : [];
1262
+ return {
1263
+ content: modified,
1264
+ updated,
1265
+ data: {
1266
+ mutated: log.length > 0,
1267
+ mutations: log.length,
1268
+ log,
1269
+ },
1270
+ };
1271
+ }
1272
+ /**
1273
+ * §2 — re-derive `## Current Position` prose fields from frontmatter.
1274
+ *
1275
+ * Drift class: `Phase:`, `Status:` etc. in body contradict frontmatter after
1276
+ * a milestone switch or prune (epic #1817). The body prose is re-derivable
1277
+ * because `buildStateFrontmatter` already derives the canonical values from
1278
+ * disk; rebuild pushes those back into the body prose.
1279
+ *
1280
+ * Implementation: pull each canonical value from frontmatter and replace the
1281
+ * body field via `stateReplaceField`. Skip silently when frontmatter lacks
1282
+ * the key (Leaky-Abstractions guard — don't synthesize values the canonical
1283
+ * source doesn't have).
1284
+ */
1285
+ function reconcileCurrentPosition(content, timestamp, log) {
1286
+ const fm = extractFrontmatter(content);
1287
+ if (!fm || typeof fm !== 'object')
1288
+ return content;
1289
+ let modified = content;
1290
+ // Phase prose: frontmatter `current_phase` overrides body `**Current Phase:**`.
1291
+ // The body `Phase:` prose line (e.g. "Phase: 3 of 12 (Test Phase)") is owned
1292
+ // by other transitions (beginPhase / completePhase) and reconstructed from
1293
+ // total-phase counts; rebuild reconciles only the `**Current Phase:**` body
1294
+ // field that frontmatter is the canonical source for.
1295
+ const fmPhase = fm.current_phase;
1296
+ if (typeof fmPhase === 'string' || typeof fmPhase === 'number') {
1297
+ const canonicalPhase = String(fmPhase);
1298
+ const existing = (0, state_document_cjs_1.stateExtractField)(modified, 'Current Phase');
1299
+ if (existing !== null && existing !== canonicalPhase) {
1300
+ const replaced = (0, state_document_cjs_1.stateReplaceField)(modified, 'Current Phase', canonicalPhase);
1301
+ if (replaced !== null) {
1302
+ modified = replaced;
1303
+ log.push({
1304
+ timestamp,
1305
+ kind: 'current-position-reconciled',
1306
+ section: exports.STATE_MD_SECTIONS.currentPosition,
1307
+ before: truncateForLog(existing),
1308
+ after: truncateForLog(canonicalPhase),
1309
+ reason: "frontmatter 'current_phase' is canonical; body 'Current Phase' was stale",
1310
+ });
1311
+ }
1312
+ }
1313
+ }
1314
+ // Phase name prose.
1315
+ const fmPhaseName = fm.current_phase_name;
1316
+ if (typeof fmPhaseName === 'string' || typeof fmPhaseName === 'number') {
1317
+ const canonicalName = String(fmPhaseName);
1318
+ const existing = (0, state_document_cjs_1.stateExtractField)(modified, 'Current Phase Name');
1319
+ if (existing !== null && existing !== canonicalName) {
1320
+ const replaced = (0, state_document_cjs_1.stateReplaceField)(modified, 'Current Phase Name', canonicalName);
1321
+ if (replaced !== null) {
1322
+ modified = replaced;
1323
+ log.push({
1324
+ timestamp,
1325
+ kind: 'current-position-reconciled',
1326
+ section: exports.STATE_MD_SECTIONS.currentPosition,
1327
+ before: truncateForLog(existing),
1328
+ after: truncateForLog(canonicalName),
1329
+ reason: "frontmatter 'current_phase_name' is canonical; body 'Current Phase Name' was stale",
1330
+ });
1331
+ }
1332
+ }
1333
+ }
1334
+ return modified;
1335
+ }
1336
+ /**
1337
+ * §2 — re-derive the `**By Phase:**` table inside `## Performance Metrics`
1338
+ * from the injected `phaseInventoryProvider`. Drift class: orphaned rows for
1339
+ * phases from a prior milestone, or zero-padded phase IDs that were renamed
1340
+ * (epic #1817).
1341
+ *
1342
+ * Leaky-Abstractions guard (ADR-1817 §1): when `phaseInventoryProvider` is
1343
+ * absent (no disk scan wired), this step is a no-op. The core stays pure and
1344
+ * testable without disk I/O.
1345
+ */
1346
+ function reconcileByPhaseTable(content, deps, timestamp, log) {
1347
+ if (!deps.phaseInventoryProvider)
1348
+ return content;
1349
+ const inventory = deps.phaseInventoryProvider();
1350
+ if (!inventory || inventory.length === 0)
1351
+ return content;
1352
+ // The canonical table shape (from gsd-core/templates/state.md):
1353
+ // | Phase | Plans | Total | Avg/Plan |
1354
+ // |-------|-------|-------|----------|
1355
+ // | - | - | - | - |
1356
+ // rebuild renders one row per inventory record (Phase N: P plans). The
1357
+ // Total/Avg columns are runtime-collected by other commands; rebuild does
1358
+ // NOT re-derive them and resets them to '-' so future plan-completion
1359
+ // repopulates. The canonical reconciliation target is the row SET.
1360
+ const tableRows = inventory.map((r) => `| ${r.number} | ${r.planCount} | - | - |`);
1361
+ const canonicalTable = [
1362
+ '| Phase | Plans | Total | Avg/Plan |',
1363
+ '|-------|-------|-------|----------|',
1364
+ ...tableRows,
1365
+ ];
1366
+ // Line-based splice: find `**By Phase:**` line, then walk forward collecting
1367
+ // the table block (header + separator + body rows), replace the block with
1368
+ // the canonical table preceded by a single blank-line separator.
1369
+ const lines = content.split('\n');
1370
+ const markerIdx = lines.findIndex((l) => l.trim() === '**By Phase:**');
1371
+ if (markerIdx === -1)
1372
+ return content; // unknown shape — preserve verbatim
1373
+ // Walk forward from markerIdx+1 to find the table block span. Skip leading
1374
+ // blank lines; once we see the first table row, consume subsequent table
1375
+ // rows; stop at the first non-table line after we've started.
1376
+ let blockStart = -1;
1377
+ let blockEnd = -1;
1378
+ for (let i = markerIdx + 1; i < lines.length; i++) {
1379
+ const trimmed = lines[i].trim();
1380
+ const isTable = trimmed.startsWith('|') && trimmed.endsWith('|');
1381
+ if (blockStart === -1) {
1382
+ if (isTable) {
1383
+ blockStart = i;
1384
+ blockEnd = i + 1;
1385
+ }
1386
+ else if (trimmed === '')
1387
+ continue;
1388
+ else
1389
+ break; // non-table, non-blank before any row — unknown shape
1390
+ }
1391
+ else {
1392
+ if (isTable)
1393
+ blockEnd = i + 1;
1394
+ else
1395
+ break;
1396
+ }
1397
+ }
1398
+ if (blockStart === -1)
1399
+ return content; // no table found
1400
+ // Replace lines[blockStart..blockEnd) with canonicalTable.
1401
+ const beforeBlock = lines.slice(0, markerIdx + 1);
1402
+ const afterBlock = lines.slice(blockEnd);
1403
+ // Splice: `**By Phase:**` + blank + canonicalTable rows + (whatever came after)
1404
+ const newLines = [...beforeBlock, '', ...canonicalTable, ...afterBlock];
1405
+ const candidate = newLines.join('\n');
1406
+ if (candidate === content)
1407
+ return content;
1408
+ log.push({
1409
+ timestamp,
1410
+ kind: 'by-phase-table-reconciled',
1411
+ section: exports.STATE_MD_SECTIONS.performanceMetrics,
1412
+ before: truncateForLog(lines.slice(blockStart, blockEnd).join('\n')),
1413
+ after: truncateForLog(canonicalTable.join('\n')),
1414
+ reason: 'phase dirs on disk are canonical; rows for missing phases dropped, missing phases added',
1415
+ });
1416
+ return candidate;
1417
+ }
1418
+ /**
1419
+ * §2 + epic-#1817 drift class — template-placeholder field values left in
1420
+ * place when an AI agent wrote partial state. The canonical template uses
1421
+ * `[X]`, `[Y]`, `[Phase name]`, `[date]`, `[N]`, etc. (see
1422
+ * `gsd-core/templates/state.md`). Rebuild clears any `**Field:** [placeholder]`
1423
+ * line where the value still matches the placeholder shape.
1424
+ *
1425
+ * "Clears" means: leaves the field in place with the literal text `(pending)`,
1426
+ * signalling that rebuild recognized the placeholder but had no canonical
1427
+ * source to substitute. This is honest — better than silently leaving `[X]`
1428
+ * which looks like a value.
1429
+ */
1430
+ const TEMPLATE_PLACEHOLDER_VALUE = /^\s*\[[^\]]+\]\s*$|^\s*-\s*$/;
1431
+ function stripTemplatePlaceholders(content, timestamp, log) {
1432
+ // Scan body `**Field:** value` lines; when value matches the placeholder
1433
+ // shape, replace with `(pending)`. We deliberately do NOT touch fields that
1434
+ // other transitions actively maintain (syncCore's three, beginPhase's set,
1435
+ // etc.) — only the template placeholder rows that nothing has touched.
1436
+ const lines = content.split('\n');
1437
+ const replacements = [];
1438
+ for (let i = 0; i < lines.length; i++) {
1439
+ const line = lines[i];
1440
+ const m = line.match(/^\s*\*\*([^*]+):\*\*\s*(.*)$/);
1441
+ if (!m)
1442
+ continue;
1443
+ const fieldName = m[1];
1444
+ const value = m[2];
1445
+ if (TEMPLATE_PLACEHOLDER_VALUE.test(value)) {
1446
+ const cleared = `**${fieldName}:** (pending)`;
1447
+ replacements.push({ lineIdx: i, before: line, after: cleared, fieldName });
1448
+ }
1449
+ }
1450
+ if (replacements.length === 0)
1451
+ return content;
1452
+ for (const r of replacements) {
1453
+ lines[r.lineIdx] = r.after;
1454
+ log.push({
1455
+ timestamp,
1456
+ kind: 'placeholder-removed',
1457
+ section: exports.STATE_MD_SECTIONS.currentPosition,
1458
+ before: truncateForLog(r.before.trim()),
1459
+ after: truncateForLog(r.after),
1460
+ reason: `field ${JSON.stringify(r.fieldName)} still carried template placeholder ${JSON.stringify(r.before.match(/\*\*[^*]+:\*\*\s*(.*)$/)?.[1]?.trim() ?? '')}; no canonical source available — replaced with (pending)`,
1461
+ });
1462
+ }
1463
+ return lines.join('\n');
1464
+ }
1465
+ /**
1466
+ * §2 + epic-#1817 drift class — duplicate `## Session Continuity Archive`
1467
+ * blocks from repeated `state record-session` calls on a corrupt file. The
1468
+ * canonical template has one `## Session Continuity` section; archived blocks
1469
+ * may accumulate as `### Session — <timestamp>` H3 sub-sections under it.
1470
+ * Rebuild keeps the most-recent N (default 3) and drops older duplicates,
1471
+ * logging each drop.
1472
+ *
1473
+ * Conservative scope: only acts when the section has more than 3 H3
1474
+ * `### Session —` sub-headings; otherwise it's a no-op (preserve verbatim).
1475
+ */
1476
+ const DEFAULT_MAX_SESSION_ARCHIVES = 3;
1477
+ // `tokenizeHeadings` strips leading `#` markers — `h.text` for `### Session — X`
1478
+ // is just `Session — X`. Match the bare heading text.
1479
+ const SESSION_ARCHIVE_H3 = /^Session\s+—/;
1480
+ function deduplicateSessionArchive(content, timestamp, log) {
1481
+ const hs = (0, markdown_sectionizer_cjs_1.tokenizeHeadings)(content);
1482
+ // Find `## Session Continuity` H2.
1483
+ const sectionIdx = hs.findIndex((h) => h.level === 2 && h.text === 'Session Continuity');
1484
+ if (sectionIdx === -1)
1485
+ return content;
1486
+ // Find the section span: from this H2's offset to the next H2 (or EOF).
1487
+ const sectionStart = hs[sectionIdx].offset;
1488
+ let sectionEnd = content.length;
1489
+ for (let i = sectionIdx + 1; i < hs.length; i++) {
1490
+ if (hs[i].level === 2) {
1491
+ sectionEnd = hs[i].offset;
1492
+ break;
1493
+ }
1494
+ }
1495
+ // Count `### Session — …` H3 sub-headings inside the section.
1496
+ const archiveHeadings = hs.filter((h) => h.level === 3 && h.offset >= sectionStart && h.offset < sectionEnd && SESSION_ARCHIVE_H3.test(h.text));
1497
+ if (archiveHeadings.length <= DEFAULT_MAX_SESSION_ARCHIVES)
1498
+ return content;
1499
+ // Keep the most-recent N by offset (last N in document order; if timestamps
1500
+ // in the H3 text are in chronological order — the template convention —
1501
+ // last-N == most-recent-N).
1502
+ const dropCount = archiveHeadings.length - DEFAULT_MAX_SESSION_ARCHIVES;
1503
+ const toDrop = archiveHeadings.slice(0, dropCount);
1504
+ // Compute the byte spans to drop: each archived H3 spans from its offset to
1505
+ // the next H3 (or to sectionEnd). Drop with one preceding blank line so we
1506
+ // don't leave a dangling separator.
1507
+ let mutated = content;
1508
+ // Process from the bottom up so offsets don't shift mid-edit.
1509
+ for (let i = toDrop.length - 1; i >= 0; i--) {
1510
+ const h = toDrop[i];
1511
+ let spanEnd = sectionEnd;
1512
+ // Find next H3 at-or-after h.offset (within the section).
1513
+ for (const candidate of hs) {
1514
+ if (candidate.level === 3 && candidate.offset > h.offset && candidate.offset < sectionEnd) {
1515
+ spanEnd = candidate.offset;
1516
+ break;
1517
+ }
1518
+ }
1519
+ const dropStart = h.offset;
1520
+ const before = mutated.slice(0, dropStart);
1521
+ const after = mutated.slice(spanEnd);
1522
+ const droppedText = mutated.slice(dropStart, spanEnd);
1523
+ mutated = before + after;
1524
+ log.push({
1525
+ timestamp,
1526
+ kind: 'session-archive-deduplicated',
1527
+ section: exports.STATE_MD_SECTIONS.sessionContinuity,
1528
+ before: truncateForLog(droppedText),
1529
+ after: '',
1530
+ reason: `archived session ${JSON.stringify(h.text)} exceeded the ${DEFAULT_MAX_SESSION_ARCHIVES}-most-recent retention; dropped`,
1531
+ });
1532
+ }
1533
+ return mutated;
1534
+ }
1535
+ /**
1536
+ * §3 — append a structured audit entry to `## Rebuild Log`. Per ADR-1817 §3
1537
+ * the section is created if absent; existing entries are preserved verbatim
1538
+ * (append-only).
1539
+ *
1540
+ * Format (yaml-ish, human-readable, machine-parseable):
1541
+ *
1542
+ * ## Rebuild Log
1543
+ *
1544
+ * - timestamp: 2026-06-29T19:30:00Z
1545
+ * kind: placeholder-removed
1546
+ * section: ## Current Position
1547
+ * before: ...
1548
+ * after: ...
1549
+ * reason: ...
1550
+ */
1551
+ function appendRebuildLogSection(content, entries) {
1552
+ const lines = content.split('\n');
1553
+ // Render the new entry block.
1554
+ const rendered = [];
1555
+ for (const e of entries) {
1556
+ rendered.push(`- timestamp: ${e.timestamp}`);
1557
+ rendered.push(` kind: ${e.kind}`);
1558
+ rendered.push(` section: ${e.section}`);
1559
+ rendered.push(` before: ${e.before.replace(/\n/g, ' \\n ')}`);
1560
+ rendered.push(` after: ${e.after.replace(/\n/g, ' \\n ')}`);
1561
+ rendered.push(` reason: ${e.reason.replace(/\n/g, ' \\n ')}`);
1562
+ }
1563
+ // Locate an existing `## Rebuild Log` section.
1564
+ const sectionHeaderIdx = lines.findIndex((l) => l.trim() === REBUILD_LOG_SECTION);
1565
+ if (sectionHeaderIdx === -1) {
1566
+ // Create the section at end-of-file, separated by a blank line.
1567
+ const needsLeadingBlank = lines.length > 0 && lines[lines.length - 1].trim() !== '';
1568
+ const trailer = needsLeadingBlank ? ['', REBUILD_LOG_SECTION, '', ...rendered] : [REBUILD_LOG_SECTION, '', ...rendered];
1569
+ return [...lines, ...trailer].join('\n');
1570
+ }
1571
+ // Append to the existing section. Find the end of the existing log entries
1572
+ // (walk forward until the next H2 or EOF). Insert before that boundary.
1573
+ let insertAt = sectionHeaderIdx + 1;
1574
+ while (insertAt < lines.length) {
1575
+ const l = lines[insertAt];
1576
+ if (/^##\s/.test(l))
1577
+ break;
1578
+ insertAt++;
1579
+ }
1580
+ // Preserve a blank-line separator before the new entries if the prior line
1581
+ // is non-blank and non-header.
1582
+ const sep = [];
1583
+ if (insertAt > 0 && lines[insertAt - 1].trim() !== '' && lines[insertAt - 1].trim() !== REBUILD_LOG_SECTION) {
1584
+ sep.push('');
1585
+ }
1586
+ const next = [...lines.slice(0, insertAt), ...sep, ...rendered, ...lines.slice(insertAt)];
1587
+ return next.join('\n');
1588
+ }