@opengsd/gsd-core 1.5.0 → 1.6.0-rc.2

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 (95) hide show
  1. package/.claude-plugin/plugin.json +1 -1
  2. package/agents/gsd-plan-checker.md +34 -0
  3. package/agents/gsd-planner.md +2 -0
  4. package/agents/gsd-roadmapper.md +6 -0
  5. package/bin/install.js +199 -365
  6. package/commands/gsd/capture.md +5 -1
  7. package/gemini-extension.json +1 -1
  8. package/gsd-core/bin/gsd-tools.cjs +695 -5
  9. package/gsd-core/bin/lib/adr-parser.cjs +45 -23
  10. package/gsd-core/bin/lib/audit.cjs +2 -2
  11. package/gsd-core/bin/lib/capability-consent.cjs +763 -0
  12. package/gsd-core/bin/lib/capability-ledger.cjs +831 -0
  13. package/gsd-core/bin/lib/capability-lifecycle.cjs +1551 -0
  14. package/gsd-core/bin/lib/capability-loader.cjs +764 -0
  15. package/gsd-core/bin/lib/capability-lock.cjs +553 -0
  16. package/gsd-core/bin/lib/capability-registry.cjs +198 -4
  17. package/gsd-core/bin/lib/capability-source.cjs +1242 -0
  18. package/gsd-core/bin/lib/capability-state.cjs +9 -6
  19. package/gsd-core/bin/lib/capability-trust.cjs +550 -0
  20. package/gsd-core/bin/lib/capability-validator.cjs +2066 -0
  21. package/gsd-core/bin/lib/capability-writer.cjs +14 -5
  22. package/gsd-core/bin/lib/check-command-router.cjs +69 -18
  23. package/gsd-core/bin/lib/command-aliases.cjs +8 -0
  24. package/gsd-core/bin/lib/commands.cjs +247 -0
  25. package/gsd-core/bin/lib/config-loader.cjs +98 -84
  26. package/gsd-core/bin/lib/config-schema.cjs +26 -7
  27. package/gsd-core/bin/lib/config.cjs +7 -1
  28. package/gsd-core/bin/lib/decisions.cjs +149 -60
  29. package/gsd-core/bin/lib/frontmatter.cjs +7 -3
  30. package/gsd-core/bin/lib/gap-checker.cjs +126 -11
  31. package/gsd-core/bin/lib/init.cjs +91 -22
  32. package/gsd-core/bin/lib/legacy-cleanup.cjs +96 -0
  33. package/gsd-core/bin/lib/loop-resolver.cjs +26 -2
  34. package/gsd-core/bin/lib/markdown-sectionizer.cjs +471 -0
  35. package/gsd-core/bin/lib/milestone.cjs +41 -2
  36. package/gsd-core/bin/lib/phase-command-router.cjs +5 -0
  37. package/gsd-core/bin/lib/phase-id.cjs +25 -11
  38. package/gsd-core/bin/lib/phase-lifecycle.cjs +14 -5
  39. package/gsd-core/bin/lib/phase.cjs +33 -4
  40. package/gsd-core/bin/lib/probe-core.cjs +7 -0
  41. package/gsd-core/bin/lib/prohibition-enforcement.cjs +59 -26
  42. package/gsd-core/bin/lib/project-root.cjs +89 -2
  43. package/gsd-core/bin/lib/resolution.cjs +26 -0
  44. package/gsd-core/bin/lib/roadmap-command-router.cjs +16 -3
  45. package/gsd-core/bin/lib/roadmap-parser.cjs +73 -106
  46. package/gsd-core/bin/lib/roadmap-upgrade.cjs +47 -17
  47. package/gsd-core/bin/lib/roadmap.cjs +5 -2
  48. package/gsd-core/bin/lib/runtime-artifact-conversion.cjs +423 -3
  49. package/gsd-core/bin/lib/runtime-artifact-install-plan.cjs +77 -0
  50. package/gsd-core/bin/lib/runtime-artifact-layout.cjs +1 -28
  51. package/gsd-core/bin/lib/runtime-homes.cjs +53 -1
  52. package/gsd-core/bin/lib/runtime-name-policy.cjs +44 -0
  53. package/gsd-core/bin/lib/semver-compare.cjs +127 -0
  54. package/gsd-core/bin/lib/shell-command-projection.cjs +55 -1
  55. package/gsd-core/bin/lib/state-document.cjs +4 -2
  56. package/gsd-core/bin/lib/state.cjs +317 -161
  57. package/gsd-core/bin/lib/surface.cjs +12 -19
  58. package/gsd-core/bin/lib/uat-predicate.cjs +7 -47
  59. package/gsd-core/bin/lib/uat.cjs +39 -26
  60. package/gsd-core/bin/lib/validate.cjs +5 -2
  61. package/gsd-core/bin/lib/verify.cjs +40 -15
  62. package/gsd-core/bin/lib/worktree-safety.cjs +202 -0
  63. package/gsd-core/bin/shared/config-defaults.manifest.json +6 -1
  64. package/gsd-core/bin/shared/config-schema.manifest.json +5 -1
  65. package/gsd-core/references/context-budget.md +8 -8
  66. package/gsd-core/references/execute-phase-between-wave-reset.md +43 -0
  67. package/gsd-core/references/execute-phase-context-guard.md +16 -0
  68. package/gsd-core/references/execute-phase-wave-guard.md +33 -0
  69. package/gsd-core/references/planner-antipatterns.md +48 -0
  70. package/gsd-core/references/planning-config.md +4 -0
  71. package/gsd-core/references/prohibition-probe.md +15 -9
  72. package/gsd-core/references/scout-codebase.md +2 -2
  73. package/gsd-core/workflows/autonomous.md +33 -33
  74. package/gsd-core/workflows/diagnose-issues.md +6 -1
  75. package/gsd-core/workflows/discuss-phase/templates/context.md +1 -1
  76. package/gsd-core/workflows/discuss-phase.md +1 -2
  77. package/gsd-core/workflows/execute-phase.md +12 -12
  78. package/gsd-core/workflows/help/modes/full.md +10 -0
  79. package/gsd-core/workflows/list-seeds.md +63 -0
  80. package/gsd-core/workflows/manager.md +37 -37
  81. package/gsd-core/workflows/pr-branch.md +156 -0
  82. package/gsd-core/workflows/quick.md +6 -1
  83. package/gsd-core/workflows/review.md +10 -2
  84. package/gsd-core/workflows/spec-phase.md +8 -3
  85. package/gsd-core/workflows/verify-phase.md +2 -2
  86. package/package.json +6 -3
  87. package/scripts/gen-capability-matrix.cjs +284 -0
  88. package/scripts/gen-capability-registry.cjs +96 -1853
  89. package/scripts/lint-regression-test-names.allowlist.json +1 -0
  90. package/scripts/lint-resolution-provenance.allowlist.json +1 -0
  91. package/scripts/lint-resolution-provenance.cjs +192 -0
  92. package/scripts/lint-test-file-count.allowlist.json +9 -0
  93. package/scripts/prompt-injection-scan.sh +1 -0
  94. package/scripts/run-tests.cjs +14 -0
  95. package/scripts/sync-manifest-versions.cjs +77 -5
@@ -0,0 +1,471 @@
1
+ "use strict";
2
+ /**
3
+ * Markdown Sectionizer — canonical markdown-structure parsing seam
4
+ *
5
+ * Pure functions, Node built-ins only (no external deps). String-in → value-out, no I/O.
6
+ * Promoted from `uat-predicate.cts` `_stripFencedBlocks` (CommonMark-correct state machine)
7
+ * and extended with heading tokenisation, section collection, and bullet iteration.
8
+ *
9
+ * ADR-1372 — T0 foundational seam. Migration tiers T1–T7 progressively adopt this seam.
10
+ *
11
+ * ADR-457 build-at-publish: compiled by tsc to gsd-core/bin/lib/markdown-sectionizer.cjs.
12
+ */
13
+ Object.defineProperty(exports, "__esModule", { value: true });
14
+ exports.stripFencedCode = stripFencedCode;
15
+ exports.tokenizeHeadings = tokenizeHeadings;
16
+ exports.collectSections = collectSections;
17
+ exports.collectSection = collectSection;
18
+ exports.iterateBullets = iterateBullets;
19
+ exports.extractTaggedBlocks = extractTaggedBlocks;
20
+ exports.replaceSection = replaceSection;
21
+ // ─── stripFencedCode ──────────────────────────────────────────────────────────
22
+ /**
23
+ * CommonMark-correct fenced-code-block stripper.
24
+ *
25
+ * Ported from `uat-predicate.cts` `_stripFencedBlocks` — the reference
26
+ * implementation for the repo. DO NOT modify `uat-predicate.cts` (its
27
+ * migration is T5); this is a tracked duplication until T5 lands.
28
+ *
29
+ * Rules:
30
+ * - Opening delimiter: a line whose non-indent portion begins with ≥3 backticks
31
+ * or tildes (≤3 leading spaces tolerated per CommonMark §4.5).
32
+ * - Closing delimiter: same character, run length ≥ opening, no trailing
33
+ * non-whitespace text.
34
+ * - A tilde fence inside a backtick fence (or vice versa) is fence *content*,
35
+ * not a closing delimiter — delimiter char must match.
36
+ * - Both delimiter lines and all content lines are dropped from the output.
37
+ * - CRLF-safe: trailing `\r` is stripped before delimiter matching; the kept
38
+ * non-fence lines are returned as-is (including any `\r`).
39
+ * - `unterminatedFence` signals EOF inside an open fence.
40
+ */
41
+ function stripFencedCode(content) {
42
+ if (typeof content !== 'string') {
43
+ return { text: '', unterminatedFence: false };
44
+ }
45
+ const lines = content.split('\n');
46
+ const kept = [];
47
+ let openFence = null;
48
+ // Matches: optional indent (≤3 spaces per CommonMark), fence run, optional info string
49
+ const delimRe = /^( {0,3})(`{3,}|~{3,})(.*)$/;
50
+ for (const rawLine of lines) {
51
+ // Strip trailing \r for delimiter matching (CRLF safety)
52
+ const line = rawLine.replace(/\r$/, '');
53
+ const m = delimRe.exec(line);
54
+ if (m) {
55
+ const char = m[2][0];
56
+ const len = m[2].length;
57
+ const trailing = m[3];
58
+ if (openFence === null) {
59
+ // CommonMark §4.5: backtick fence info string must not contain a backtick.
60
+ // If it does, this line is NOT a valid fence opener (treat as ordinary content).
61
+ if (char === '`' && trailing.includes('`')) {
62
+ kept.push(rawLine);
63
+ continue;
64
+ }
65
+ // Opening delimiter — record fence state, drop this line
66
+ openFence = { char, len };
67
+ }
68
+ else if (char === openFence.char && len >= openFence.len && /^\s*$/.test(trailing)) {
69
+ // Closing delimiter (same char, sufficient length, no trailing content) — close and drop
70
+ openFence = null;
71
+ }
72
+ // else: mismatched delimiter inside fence — treat as content, still drop (it's a fence line)
73
+ continue; // all delimiter lines are dropped
74
+ }
75
+ if (openFence === null) {
76
+ kept.push(rawLine); // non-fence content: keep as-is (preserve original \r if any)
77
+ }
78
+ // Lines inside a fence are silently dropped
79
+ }
80
+ return { text: kept.join('\n'), unterminatedFence: openFence !== null };
81
+ }
82
+ // ─── tokenizeHeadings ─────────────────────────────────────────────────────────
83
+ /**
84
+ * Extract all ATX headings from `content` in document order.
85
+ *
86
+ * Only headings OUTSIDE fenced code blocks are returned — `stripFencedCode` is
87
+ * applied first so that a `## heading` inside a ``` fence is not tokenised.
88
+ *
89
+ * Each token records `{ level, text, line, offset }` where `offset` is relative
90
+ * to the ORIGINAL `content` (before fence-stripping), enabling callers to use
91
+ * `collectSection` on the original string.
92
+ */
93
+ function tokenizeHeadings(content) {
94
+ if (typeof content !== 'string' || content.length === 0)
95
+ return [];
96
+ // Strip fences first so headings inside code blocks are ignored.
97
+ // We need the original line positions, so we map stripped-text line numbers
98
+ // back to original by tracking which original lines survived stripping.
99
+ const originalLines = content.split('\n');
100
+ const tokens = [];
101
+ // We re-run the fence state machine to know which lines are "kept", so we
102
+ // can map line index in original to whether it survived.
103
+ const delimRe = /^( {0,3})(`{3,}|~{3,})(.*)$/;
104
+ let openFence = null;
105
+ // Accumulate character offset as we iterate lines
106
+ let charOffset = 0;
107
+ for (let i = 0; i < originalLines.length; i++) {
108
+ const rawLine = originalLines[i];
109
+ const line = rawLine.replace(/\r$/, '');
110
+ const dm = delimRe.exec(line);
111
+ if (dm) {
112
+ const char = dm[2][0];
113
+ const len = dm[2].length;
114
+ const trailing = dm[3];
115
+ if (openFence === null) {
116
+ // CommonMark §4.5: backtick fence info string must not contain a backtick.
117
+ if (char === '`' && trailing.includes('`')) {
118
+ // Not a valid fence opener — check for heading on this line (will fall through)
119
+ }
120
+ else {
121
+ openFence = { char, len };
122
+ charOffset += rawLine.length + 1;
123
+ continue;
124
+ }
125
+ }
126
+ else if (char === openFence.char && len >= openFence.len && /^\s*$/.test(trailing)) {
127
+ openFence = null;
128
+ charOffset += rawLine.length + 1;
129
+ continue;
130
+ }
131
+ else {
132
+ // Mismatched/invalid delimiter inside fence — treat as content (still inside fence), skip heading check
133
+ charOffset += rawLine.length + 1;
134
+ continue;
135
+ }
136
+ }
137
+ if (openFence === null) {
138
+ // This line is outside any fence — check for ATX heading.
139
+ // CommonMark: ≤3 leading spaces, then 1–6 `#`, then either EOF (empty heading)
140
+ // or at least one space/tab followed by optional text, with optional closing `#` sequence.
141
+ const headingMatch = /^( {0,3})(#{1,6})([ \t]+.*|[ \t]*)?$/.exec(line);
142
+ if (headingMatch) {
143
+ const hashes = headingMatch[2];
144
+ const rest = headingMatch[3] ?? '';
145
+ // Strip optional closing `#` sequence: trailing whitespace + one or more `#` + optional whitespace
146
+ const rawText = rest.replace(/^[ \t]+/, '').replace(/[ \t]+#+[ \t]*$/, '').replace(/^#+[ \t]*$/, '');
147
+ tokens.push({
148
+ level: hashes.length,
149
+ text: rawText.trim(),
150
+ line: i + 1, // 1-based
151
+ offset: charOffset,
152
+ });
153
+ }
154
+ }
155
+ charOffset += rawLine.length + 1;
156
+ }
157
+ return tokens;
158
+ }
159
+ // ─── collectSections ─────────────────────────────────────────────────────────
160
+ /**
161
+ * Collect sections from `content`, calling `stopPredicate` on each heading to
162
+ * decide where sections end.
163
+ *
164
+ * Returns an array of `Section` objects, one per matched heading. The `body`
165
+ * of each section runs from the line after the heading up to (but not
166
+ * including) the next heading that satisfies `stopPredicate`, or EOF.
167
+ *
168
+ * Unlike a greedy-regex approach, this is a line-by-line walk — compatible
169
+ * with the repo's "line-by-line section collection" pattern.
170
+ */
171
+ function collectSections(content, stopPredicate) {
172
+ if (typeof content !== 'string' || content.length === 0)
173
+ return [];
174
+ const headings = tokenizeHeadings(content);
175
+ if (headings.length === 0)
176
+ return [];
177
+ const lines = content.split('\n');
178
+ const sections = [];
179
+ // Build a set of line numbers (1-based) that are heading lines
180
+ const headingsByLine = new Map();
181
+ for (const h of headings) {
182
+ headingsByLine.set(h.line, h);
183
+ }
184
+ // Build a byte-offset table: lineOffsets[i] = byte offset of the start of line i+1 (1-based: i=0 → line 1)
185
+ // The body of a section starts at the byte after the heading line's trailing '\n'.
186
+ const lineOffsets = new Array(lines.length);
187
+ let acc = 0;
188
+ for (let i = 0; i < lines.length; i++) {
189
+ lineOffsets[i] = acc;
190
+ acc += lines[i].length + 1; // +1 for the '\n' we split on
191
+ }
192
+ // lineOffsets[i] is the byte offset of line (i+1) (1-based). EOF sentinel:
193
+ const eofOffset = acc; // === content.length + (content.endsWith('\n') ? 0 : 0) ≈ content.length
194
+ let currentHeading = null;
195
+ let currentBodyStart = 0;
196
+ let bodyLines = [];
197
+ const flush = (_bodyEndOffset) => {
198
+ if (currentHeading !== null) {
199
+ const rawBody = bodyLines.join('\n');
200
+ const body = rawBody.trimEnd();
201
+ // INVARIANT: content.slice(bodyStart, bodyEnd) === body
202
+ // bodyEnd is derived from body.length, NOT from the raw separator offset,
203
+ // so round-trips via replaceSection(content, section, section.body) are exact.
204
+ sections.push({
205
+ heading: currentHeading,
206
+ body,
207
+ bodyStart: currentBodyStart,
208
+ bodyEnd: currentBodyStart + body.length,
209
+ });
210
+ currentHeading = null;
211
+ bodyLines = [];
212
+ }
213
+ };
214
+ for (let i = 0; i < lines.length; i++) {
215
+ const lineNo = i + 1; // 1-based
216
+ const h = headingsByLine.get(lineNo);
217
+ if (h !== undefined && stopPredicate(h)) {
218
+ // This heading is a stop boundary — flush current section, start new one.
219
+ // The body ends at the start of this heading line.
220
+ flush(lineOffsets[i]);
221
+ currentHeading = h;
222
+ // Body starts at the beginning of the line AFTER the heading line
223
+ const headingLineIdx = h.line - 1; // 0-based
224
+ currentBodyStart = lineOffsets[headingLineIdx] + lines[headingLineIdx].length + 1;
225
+ }
226
+ else if (currentHeading !== null) {
227
+ bodyLines.push(lines[i]);
228
+ }
229
+ }
230
+ flush(eofOffset);
231
+ return sections;
232
+ }
233
+ // ─── collectSection ───────────────────────────────────────────────────────────
234
+ /**
235
+ * Collect a single section whose heading satisfies `headingPredicate`.
236
+ *
237
+ * Options:
238
+ * - `levelBounded` (default: `true`): the section ends at the next heading of
239
+ * the same or higher level (lower level number = higher in the hierarchy).
240
+ * When `false`, the section body runs until any heading or EOF.
241
+ * Ignored when `stopAtLevel` is provided.
242
+ * - `stopAtLevel` (optional): when provided, the section ends at the next heading
243
+ * whose `level <= stopAtLevel`, regardless of the opener's level. This enables
244
+ * modeling sections like a `##`-opened section that also stops at `###`
245
+ * (pass `stopAtLevel: 3`). Takes precedence over `levelBounded` when set.
246
+ * - `stripFences` (default: `false`): apply `stripFencedCode` to the body
247
+ * before returning. The `heading` in the result always refers to the original
248
+ * heading (pre-strip).
249
+ *
250
+ * Returns `null` when no matching heading is found.
251
+ */
252
+ function collectSection(content, headingPredicate, opts = {}) {
253
+ if (typeof content !== 'string' || content.length === 0)
254
+ return null;
255
+ const { levelBounded = true, stopAtLevel, stripFences = false } = opts;
256
+ const headings = tokenizeHeadings(content);
257
+ const targetIdx = headings.findIndex(headingPredicate);
258
+ if (targetIdx === -1)
259
+ return null;
260
+ const target = headings[targetIdx];
261
+ const lines = content.split('\n');
262
+ // Determine which headings act as stops after the target
263
+ const bodyStartLine = target.line + 1; // 1-based, first line of body
264
+ let bodyEndLine = lines.length + 1; // 1-based, exclusive (default: EOF+1)
265
+ for (let j = targetIdx + 1; j < headings.length; j++) {
266
+ const next = headings[j];
267
+ let isStop;
268
+ if (stopAtLevel !== undefined) {
269
+ // stopAtLevel: stop at the next heading whose level <= stopAtLevel
270
+ isStop = next.level <= stopAtLevel;
271
+ }
272
+ else {
273
+ isStop = levelBounded ? next.level <= target.level : true;
274
+ }
275
+ if (isStop) {
276
+ bodyEndLine = next.line; // stop before this line (1-based)
277
+ break;
278
+ }
279
+ }
280
+ // Compute character offsets for bodyStart.
281
+ // lineOffsets[i] = character offset of line (i+1) in content (1-based).
282
+ const lineOffsets = new Array(lines.length);
283
+ let acc = 0;
284
+ for (let i = 0; i < lines.length; i++) {
285
+ lineOffsets[i] = acc;
286
+ acc += lines[i].length + 1; // +1 for the '\n' separator
287
+ }
288
+ const eofOffset = acc; // byte offset past the last line
289
+ // bodyStart: character offset of first line of body (bodyStartLine is 1-based)
290
+ const bodyStartOffset = bodyStartLine <= lines.length ? lineOffsets[bodyStartLine - 1] : eofOffset;
291
+ // Slice body lines (0-based array: bodyStartLine-1 to bodyEndLine-2 inclusive)
292
+ const bodyRaw = lines.slice(bodyStartLine - 1, bodyEndLine - 1).join('\n').trimEnd();
293
+ const body = stripFences ? stripFencedCode(bodyRaw).text : bodyRaw;
294
+ // INVARIANT: content.slice(bodyStart, bodyEnd) === body
295
+ // bodyEnd is derived from body.length so that replaceSection(content, section, section.body) === content.
296
+ return { heading: target, body, bodyStart: bodyStartOffset, bodyEnd: bodyStartOffset + body.length };
297
+ }
298
+ // ─── iterateBullets ───────────────────────────────────────────────────────────
299
+ /**
300
+ * Extract bullet items from `sectionText`.
301
+ *
302
+ * Recognises three marker families:
303
+ * - **Checkbox**: `- [ ] text` (unchecked) and `- [x] text` / `- [X] text` (checked)
304
+ * - **Dash**: `- text`, `* text`, `+ text` (plain unordered list item)
305
+ * - **Numbered**: `1. text`, `42. text` (ordered list item)
306
+ *
307
+ * Indented continuation lines (lines that are not themselves bullet openers and
308
+ * have at least one leading space or tab) are accumulated into the current
309
+ * bullet's `text`.
310
+ *
311
+ * Blank lines terminate the current bullet (consistent with CommonMark block
312
+ * handling and the repo's existing bullet parsers).
313
+ */
314
+ function iterateBullets(sectionText) {
315
+ if (typeof sectionText !== 'string' || sectionText.length === 0)
316
+ return [];
317
+ const lines = sectionText.split('\n');
318
+ const items = [];
319
+ // Checkbox bullet: `<indent>- [ ] text` or `<indent>- [x] text`
320
+ const checkboxRe = /^(\s*)- \[([xX ])\] (.*)$/;
321
+ // Plain dash/asterisk/plus bullet: `<indent>- text`, `<indent>* text`, `<indent>+ text`
322
+ const dashRe = /^(\s*)[-*+] (.*)$/;
323
+ // Numbered bullet: `<indent>1. text`
324
+ const numberedRe = /^(\s*)\d+\. (.*)$/;
325
+ // Continuation: non-empty, indented, NOT a bullet opener
326
+ const continuationRe = /^[ \t]/;
327
+ let current = null;
328
+ const flush = () => {
329
+ if (current !== null) {
330
+ current.text = current.text.trim();
331
+ items.push(current);
332
+ current = null;
333
+ }
334
+ };
335
+ for (const rawLine of lines) {
336
+ // Strip trailing \r (CRLF safety)
337
+ const line = rawLine.replace(/\r$/, '');
338
+ const trimmed = line.trim();
339
+ // Blank line terminates current bullet
340
+ if (trimmed === '') {
341
+ flush();
342
+ continue;
343
+ }
344
+ // Checkbox bullet (checked or unchecked) — must test before dashRe
345
+ const cbm = checkboxRe.exec(line);
346
+ if (cbm) {
347
+ flush();
348
+ const stateChar = cbm[2];
349
+ const checked = stateChar === 'x' || stateChar === 'X';
350
+ current = {
351
+ marker: checked ? 'checkbox-checked' : 'checkbox-unchecked',
352
+ text: cbm[3],
353
+ indent: cbm[1],
354
+ checked,
355
+ };
356
+ continue;
357
+ }
358
+ // Numbered bullet
359
+ const nm = numberedRe.exec(line);
360
+ if (nm) {
361
+ flush();
362
+ current = {
363
+ marker: 'numbered',
364
+ text: nm[2],
365
+ indent: nm[1],
366
+ checked: null,
367
+ };
368
+ continue;
369
+ }
370
+ // Plain dash / asterisk / plus bullet
371
+ const dm = dashRe.exec(line);
372
+ if (dm) {
373
+ flush();
374
+ current = {
375
+ marker: 'dash',
376
+ text: dm[2],
377
+ indent: dm[1],
378
+ checked: null,
379
+ };
380
+ continue;
381
+ }
382
+ // Continuation line (indented, non-bullet) — append to current bullet
383
+ if (current !== null && continuationRe.test(line)) {
384
+ current.text += ' ' + trimmed;
385
+ continue;
386
+ }
387
+ // Non-bullet, non-continuation line (e.g. a paragraph, heading) — flush
388
+ flush();
389
+ }
390
+ flush();
391
+ return items;
392
+ }
393
+ // ─── extractTaggedBlocks ──────────────────────────────────────────────────────
394
+ /**
395
+ * Return the inner text of every `<tagName>…</tagName>` block in `content`,
396
+ * in document order.
397
+ *
398
+ * Designed for extracting structured XML-like annotation blocks that live in
399
+ * markdown prose (e.g. `<decisions>…</decisions>`, `<requirements>…</requirements>`).
400
+ * Returns `[]` when no matching blocks are found.
401
+ *
402
+ * The `tagName` argument is regex-escaped, so names that contain regex
403
+ * metacharacters (e.g. `foo.bar`, `my+tag`) are matched literally.
404
+ *
405
+ * **Input contract:** the caller decides whether to pass raw or fence-stripped
406
+ * content. `extractTaggedBlocks` is a pure block extractor — it does NOT strip
407
+ * fenced code blocks itself. If a `<tagName>` block appears inside a fenced code
408
+ * block and should be excluded, the caller should apply `stripFencedCode` first.
409
+ *
410
+ * **Nested tags are NOT supported.** The underlying regex uses a non-greedy
411
+ * `[\s\S]*?` match, which means it closes at the FIRST `</tagName>` encountered.
412
+ * Given `<x><x>inner</x></x>`, `extractTaggedBlocks(content, 'x')` returns
413
+ * `['<x>inner']` — the inner `<x>` is captured as literal text, and the second
414
+ * `</x>` is left unmatched (or matched as a second block with empty inner text
415
+ * if another `<x>` follows). Callers that need to handle nested tags must
416
+ * pre-process the input or use a proper XML/HTML parser.
417
+ *
418
+ * Generalises `decisions.cts`'s bespoke `matchAll(/<decisions>([\s\S]*?)<\/decisions>/g)`
419
+ * so tier T1 can drop its own copy (tracked duplication until T1 lands).
420
+ */
421
+ function extractTaggedBlocks(content, tagName) {
422
+ if (typeof content !== 'string' || content.length === 0)
423
+ return [];
424
+ if (typeof tagName !== 'string' || tagName.length === 0)
425
+ return [];
426
+ // Escape the tag name for safe interpolation into a RegExp.
427
+ const escapedTag = tagName.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
428
+ const pattern = new RegExp(`<${escapedTag}>([\\s\\S]*?)</${escapedTag}>`, 'g');
429
+ const results = [];
430
+ let match;
431
+ while ((match = pattern.exec(content)) !== null) {
432
+ results.push(match[1]);
433
+ }
434
+ return results;
435
+ }
436
+ // ─── replaceSection ───────────────────────────────────────────────────────────
437
+ /**
438
+ * Splice `newBody` in place of a section's body and return the resulting
439
+ * full content string.
440
+ *
441
+ * Uses the `bodyStart`/`bodyEnd` character offsets carried by the `Section`
442
+ * type to perform a pure string splice — no regex, no line-counting. The
443
+ * heading is preserved verbatim; only the bytes between `bodyStart` and
444
+ * `bodyEnd` are replaced.
445
+ *
446
+ * The `newBody` is inserted as-is between `content.slice(0, bodyStart)` and
447
+ * `content.slice(bodyEnd)`. If `newBody` should end with a trailing newline
448
+ * before the next section's heading, the caller is responsible for including
449
+ * it (consistent with how `trimEnd()` is applied to collected bodies — see
450
+ * `collectSections`/`collectSection`).
451
+ *
452
+ * Typical read-modify-write pattern (T6 state.cts use case):
453
+ * ```
454
+ * const section = collectSection(content, h => h.text === 'Name');
455
+ * if (section) {
456
+ * content = replaceSection(content, section, newBody);
457
+ * }
458
+ * ```
459
+ *
460
+ * CRLF-safe: the splice is purely character-offset-based, so CRLF sequences
461
+ * are preserved in the surrounding content unchanged.
462
+ */
463
+ function replaceSection(content, section, newBody) {
464
+ if (typeof content !== 'string')
465
+ return content;
466
+ if (typeof newBody !== 'string')
467
+ return content;
468
+ return content.slice(0, section.bodyStart) + newBody + content.slice(section.bodyEnd);
469
+ }
470
+ // Consumers: require('../gsd-core/bin/lib/markdown-sectionizer.cjs')
471
+ // Named CJS exports are the canonical surface (ADR-457 .cts → .cjs build-at-publish).
@@ -289,7 +289,7 @@ function cmdMilestoneComplete(cwd, version, options, raw) {
289
289
  stateContent = stateReplaceFieldWithFallback(stateContent, 'Last Activity Description', null, `${version} milestone completed and archived`);
290
290
  // Reset Current Position narrative so resume/progress flows do not keep
291
291
  // pointing at closed-phase execution instructions.
292
- const positionPattern = /(##\s*Current Position\s*\n)([\s\S]*?)(?=\n##|$)/i;
292
+ const positionPattern = /(##\s*Current Position\s*\n)([\s\S]*?)(?=\n##|$)/i; // allow-adhoc-markdown: pre-seam section write-modify in milestone.cts; pending collectSection migration #1372
293
293
  const closedPositionBody = `\nPhase: Milestone ${version} complete\n` +
294
294
  `Plan: —\n` +
295
295
  `Status: Awaiting next milestone\n` +
@@ -301,7 +301,7 @@ function cmdMilestoneComplete(cwd, version, options, raw) {
301
301
  stateContent = `${stateContent.trimEnd()}\n\n## Current Position\n${closedPositionBody}`;
302
302
  }
303
303
  // Normalize operator-next-step tails that can become stale after close.
304
- const operatorPattern = /(##\s*Operator Next Steps\s*\n)([\s\S]*?)(?=\n##|$)/i;
304
+ const operatorPattern = /(##\s*Operator Next Steps\s*\n)([\s\S]*?)(?=\n##|$)/i; // allow-adhoc-markdown: pre-seam section write-modify in milestone.cts; pending collectSection migration #1372
305
305
  if (operatorPattern.test(stateContent)) {
306
306
  stateContent = stateContent.replace(operatorPattern, `$1\n- Start the next milestone with ${(0, runtime_slash_cjs_1.formatGsdSlash)('new-milestone', (0, runtime_slash_cjs_1.resolveRuntime)(cwd))}\n\n`);
307
307
  }
@@ -353,6 +353,9 @@ function cmdMilestoneComplete(cwd, version, options, raw) {
353
353
  function cmdPhasesClear(cwd, raw, args) {
354
354
  const phasesDir = planningPaths(cwd).phases;
355
355
  const confirm = Array.isArray(args) && args.includes('--confirm');
356
+ // --force bypasses the uncommitted-changes guard. Only use when the caller
357
+ // has already archived or explicitly accepts loss of uncommitted work. (#1447)
358
+ const force = Array.isArray(args) && args.includes('--force');
356
359
  let cleared = 0;
357
360
  if (node_fs_1.default.existsSync(phasesDir)) {
358
361
  const entries = node_fs_1.default.readdirSync(phasesDir, { withFileTypes: true });
@@ -361,6 +364,42 @@ function cmdPhasesClear(cwd, raw, args) {
361
364
  error(`phases clear would delete ${dirs.length} phase director${dirs.length === 1 ? 'y' : 'ies'}. ` +
362
365
  `Pass --confirm to proceed.`);
363
366
  }
367
+ // Guard (#1447): refuse to hard-delete phase directories that contain
368
+ // uncommitted changes. This prevents data loss when `new-milestone` runs
369
+ // `phases.clear --confirm` before the operator has archived or committed
370
+ // phase work from the outgoing milestone.
371
+ // Use `--force` to bypass this guard only when you have verified that
372
+ // archive or commit of the outgoing phases is already done.
373
+ if (dirs.length > 0 && !force) {
374
+ // Compute the path relative to cwd for git status
375
+ let relPhasesDir;
376
+ try {
377
+ relPhasesDir = node_path_1.default.relative(cwd, phasesDir);
378
+ }
379
+ catch {
380
+ relPhasesDir = phasesDir;
381
+ }
382
+ let gitStatusOutput = '';
383
+ try {
384
+ const gitResult = (0, shell_command_projection_cjs_1.execGit)(['status', '--porcelain', relPhasesDir], { cwd, timeout: 10_000 });
385
+ if (gitResult.exitCode === 0) {
386
+ gitStatusOutput = gitResult.stdout ?? '';
387
+ }
388
+ // If git is not available or this is not a git repo, skip the guard
389
+ // (gitResult.exitCode non-zero → not a git repo → no uncommitted changes to protect).
390
+ }
391
+ catch {
392
+ // git unavailable — skip guard
393
+ }
394
+ const uncommittedLines = gitStatusOutput
395
+ .split('\n')
396
+ .filter((line) => line.trim().length > 0);
397
+ if (uncommittedLines.length > 0) {
398
+ error(`phases clear aborted: ${uncommittedLines.length} uncommitted change${uncommittedLines.length === 1 ? '' : 's'} detected in phase directories. ` +
399
+ `Archive or commit outgoing phase work before running this command, ` +
400
+ `or pass --force to skip this check and permanently delete the phase directories. (#1447)`);
401
+ }
402
+ }
364
403
  try {
365
404
  for (const entry of dirs) {
366
405
  node_fs_1.default.rmSync(node_path_1.default.join(phasesDir, entry.name), { recursive: true, force: true });
@@ -160,6 +160,11 @@ function routePhaseCommand({ phase, args, cwd, raw, error }) {
160
160
  phase.cmdPhaseUatPassed(cwd, positional[0], raw, { policy: { requireVerification } });
161
161
  return { ok: true, data: null };
162
162
  },
163
+ // #1437 — list plan files for a phase
164
+ 'list-plans': (_ctx) => {
165
+ phase.cmdPhaseListPlans(cwd, args[2], raw);
166
+ return { ok: true, data: null };
167
+ },
163
168
  },
164
169
  };
165
170
  // ── Build manifest (available subcommands for UnknownCommand detection) ─────
@@ -14,10 +14,24 @@
14
14
  function escapeRegex(value) {
15
15
  return String(value).replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
16
16
  }
17
+ // project_code values start with an uppercase letter (e.g. PROJ, APP_CODE);
18
+ // leading underscores are not valid project codes per .planning/config.json.
19
+ const PROJECT_CODE_PREFIX_STRIP_RE = /^[A-Z][A-Z0-9_]*-(?=\d)/;
20
+ const PROJECT_CODE_PREFIX_STRIP_RE_I = /^[A-Z][A-Z0-9_]*-(?=\d)/i;
21
+ const PROJECT_CODE_PREFIX_CAPTURE_RE_I = /^([A-Z][A-Z0-9_]*)-(\d.*)/i;
22
+ const OPTIONAL_PROJECT_CODE_PREFIX_SOURCE = '(?:[A-Z][A-Z0-9_]*-)?';
23
+ function stripProjectCodePrefix(value, caseInsensitive = true) {
24
+ const input = String(value);
25
+ const re = caseInsensitive ? PROJECT_CODE_PREFIX_STRIP_RE_I : PROJECT_CODE_PREFIX_STRIP_RE;
26
+ return input.replace(re, '');
27
+ }
28
+ function hasProjectCodePrefix(value) {
29
+ return PROJECT_CODE_PREFIX_STRIP_RE_I.test(String(value));
30
+ }
17
31
  function normalizePhaseName(phase) {
18
32
  const str = String(phase);
19
33
  // Strip optional project_code prefix (e.g., 'CK-01' → '01')
20
- const stripped = str.replace(/^[A-Z]{1,6}-(?=\d)/, '');
34
+ const stripped = stripProjectCodePrefix(str, false);
21
35
  // Milestone-prefixed phase IDs: M-NN or M-N-N (deep decomposition).
22
36
  const milestoneMatch = stripped.match(/^(\d+)((?:-\d+)+)([A-Z]?(?:\.\d+)*)$/i);
23
37
  if (milestoneMatch) {
@@ -39,8 +53,7 @@ function normalizePhaseName(phase) {
39
53
  return str;
40
54
  }
41
55
  function getMilestoneFromPhaseId(phaseId) {
42
- const str = String(phaseId);
43
- const stripped = str.replace(/^[A-Z]{1,6}-(?=\d)/i, '');
56
+ const stripped = stripProjectCodePrefix(phaseId);
44
57
  const m = stripped.match(/^0*(\d+)-\d/);
45
58
  if (!m)
46
59
  return null;
@@ -50,8 +63,7 @@ function getMilestoneFromPhaseId(phaseId) {
50
63
  return `v${major}.0`;
51
64
  }
52
65
  function getPhaseDirFromPhaseId(phaseId, phaseName, projectCode) {
53
- const str = String(phaseId);
54
- const stripped = str.replace(/^[A-Z]{1,6}-(?=\d)/i, '');
66
+ const stripped = stripProjectCodePrefix(phaseId);
55
67
  const m = stripped.match(/^0*(\d+)-(0*(\d+(?:-\d+)*))$/);
56
68
  if (!m)
57
69
  return null;
@@ -70,7 +82,7 @@ function getPhaseDirFromPhaseId(phaseId, phaseName, projectCode) {
70
82
  * prose regardless of zero-padding on either side.
71
83
  */
72
84
  function phaseMarkdownRegexSource(phaseNum) {
73
- const stripped = String(phaseNum).replace(/^[A-Z]{1,6}-(?=\d)/i, '');
85
+ const stripped = stripProjectCodePrefix(phaseNum);
74
86
  // Milestone-prefixed IDs: M-NN or M-N-N (deep).
75
87
  const milestoneSegments = stripped.match(/^(\d+)((?:-\d+)*)([A-Z]?(?:\.\d+)*)$/i);
76
88
  if (milestoneSegments && milestoneSegments[2]) {
@@ -99,14 +111,14 @@ function phaseMarkdownRegexSource(phaseNum) {
99
111
  */
100
112
  function phaseMarkdownRegexSourceExact(phaseNum) {
101
113
  const raw = String(phaseNum);
102
- if (!/^[A-Z]{1,6}-(?=\d)/i.test(raw))
114
+ if (!hasProjectCodePrefix(raw))
103
115
  return null;
104
116
  return escapeRegex(raw);
105
117
  }
106
118
  function comparePhaseNum(a, b) {
107
119
  // Strip optional project_code prefix before comparing
108
- const sa = String(a).replace(/^[A-Z]{1,6}-(?=\d)/i, '');
109
- const sb = String(b).replace(/^[A-Z]{1,6}-(?=\d)/i, '');
120
+ const sa = stripProjectCodePrefix(a);
121
+ const sb = stripProjectCodePrefix(b);
110
122
  const milestoneA = sa.match(/^(\d+)((?:-\d+)+)([A-Z]?(?:\.\d+)*)$/i);
111
123
  const milestoneB = sb.match(/^(\d+)((?:-\d+)+)([A-Z]?(?:\.\d+)*)$/i);
112
124
  if (milestoneA && milestoneB) {
@@ -162,7 +174,7 @@ function comparePhaseNum(a, b) {
162
174
  * Extract the phase token from a directory name.
163
175
  */
164
176
  function extractPhaseToken(dirName) {
165
- const codePrefixMatch = dirName.match(/^([A-Z]{1,6})-(\d.*)/i);
177
+ const codePrefixMatch = dirName.match(PROJECT_CODE_PREFIX_CAPTURE_RE_I);
166
178
  let prefix = '';
167
179
  let rest = dirName;
168
180
  if (codePrefixMatch) {
@@ -192,7 +204,7 @@ function phaseTokenMatches(dirName, normalized) {
192
204
  const token = extractPhaseToken(dirName);
193
205
  if (token.toUpperCase() === normalized.toUpperCase())
194
206
  return true;
195
- const stripped = dirName.replace(/^[A-Z]{1,6}-(?=\d)/i, '');
207
+ const stripped = stripProjectCodePrefix(dirName);
196
208
  if (stripped !== dirName) {
197
209
  const strippedToken = extractPhaseToken(stripped);
198
210
  if (strippedToken.toUpperCase() === normalized.toUpperCase())
@@ -202,6 +214,8 @@ function phaseTokenMatches(dirName, normalized) {
202
214
  }
203
215
  module.exports = {
204
216
  escapeRegex,
217
+ OPTIONAL_PROJECT_CODE_PREFIX_SOURCE,
218
+ stripProjectCodePrefix,
205
219
  normalizePhaseName,
206
220
  getMilestoneFromPhaseId,
207
221
  getPhaseDirFromPhaseId,