@opengsd/gsd-core 1.9.0 → 1.10.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (223) hide show
  1. package/.claude-plugin/marketplace.json +1 -1
  2. package/.claude-plugin/plugin.json +2 -3
  3. package/.opencode/plugins/gsd-core.js +8 -1
  4. package/agents/gsd-code-fixer.md +131 -34
  5. package/agents/gsd-debugger.md +12 -246
  6. package/agents/gsd-executor.md +7 -5
  7. package/agents/gsd-integration-checker.md +3 -0
  8. package/agents/gsd-plan-checker.md +9 -0
  9. package/agents/gsd-planner.md +5 -8
  10. package/agents/gsd-roadmapper.md +21 -3
  11. package/agents/gsd-verifier.md +14 -70
  12. package/bin/install.js +503 -341
  13. package/commands/gsd/mempalace-capture.md +1 -1
  14. package/commands/gsd/new-milestone.md +1 -1
  15. package/commands/gsd/plan-phase.md +1 -1
  16. package/gsd-core/bin/gsd-tools.cjs +607 -63
  17. package/gsd-core/bin/lib/active-workstream-store.cjs +25 -0
  18. package/gsd-core/bin/lib/agent-install-check.cjs +38 -6
  19. package/gsd-core/bin/lib/api-coverage.cjs +120 -0
  20. package/gsd-core/bin/lib/audit.cjs +89 -1
  21. package/gsd-core/bin/lib/broken-windows.cjs +36 -6
  22. package/gsd-core/bin/lib/capability-registry.cjs +96 -110
  23. package/gsd-core/bin/lib/capability-validator.cjs +12 -2
  24. package/gsd-core/bin/lib/check-command-router.cjs +43 -1
  25. package/gsd-core/bin/lib/command-aliases.cjs +72 -0
  26. package/gsd-core/bin/lib/commands.cjs +26 -25
  27. package/gsd-core/bin/lib/commonjs-marker.cjs +136 -0
  28. package/gsd-core/bin/lib/config-loader.cjs +1 -0
  29. package/gsd-core/bin/lib/config.cjs +12 -1
  30. package/gsd-core/bin/lib/context-composer.cjs +278 -0
  31. package/gsd-core/bin/lib/context-predicates.cjs +506 -0
  32. package/gsd-core/bin/lib/core-utils.cjs +91 -12
  33. package/gsd-core/bin/lib/docs.cjs +3 -2
  34. package/gsd-core/bin/lib/external-job.cjs +19 -4
  35. package/gsd-core/bin/lib/frontmatter.cjs +84 -12
  36. package/gsd-core/bin/lib/gate-predicate-evaluator.cjs +57 -6
  37. package/gsd-core/bin/lib/git-base-branch.cjs +58 -15
  38. package/gsd-core/bin/lib/graphify.cjs +142 -27
  39. package/gsd-core/bin/lib/gsd2-import.cjs +27 -4
  40. package/gsd-core/bin/lib/host-integration.cjs +13 -1
  41. package/gsd-core/bin/lib/init-command-router.cjs +83 -8
  42. package/gsd-core/bin/lib/init.cjs +1021 -57
  43. package/gsd-core/bin/lib/install-engine.cjs +64 -10
  44. package/gsd-core/bin/lib/install-profiles.cjs +27 -1
  45. package/gsd-core/bin/lib/installer-migration-authoring.cjs +3 -1
  46. package/gsd-core/bin/lib/installer-migration-report.cjs +4 -0
  47. package/gsd-core/bin/lib/installer-migrations/007-retire-config-root-commonjs-marker.cjs +149 -0
  48. package/gsd-core/bin/lib/installer-migrations/008-cursor-retire-commands-surface.cjs +55 -0
  49. package/gsd-core/bin/lib/installer-migrations/009-pi-retire-reserved-hooks-dir.cjs +199 -0
  50. package/gsd-core/bin/lib/installer-migrations.cjs +87 -1
  51. package/gsd-core/bin/lib/io.cjs +28 -3
  52. package/gsd-core/bin/lib/markdown-sectionizer.cjs +6 -0
  53. package/gsd-core/bin/lib/mcp-catalog.cjs +518 -0
  54. package/gsd-core/bin/lib/mcp-server.cjs +135 -3
  55. package/gsd-core/bin/lib/milestone.cjs +106 -51
  56. package/gsd-core/bin/lib/phase-id.cjs +63 -0
  57. package/gsd-core/bin/lib/phase-locator.cjs +138 -45
  58. package/gsd-core/bin/lib/phase.cjs +260 -25
  59. package/gsd-core/bin/lib/plan-dependency-graph.cjs +232 -0
  60. package/gsd-core/bin/lib/planning-workspace.cjs +4 -0
  61. package/gsd-core/bin/lib/project-root.cjs +48 -0
  62. package/gsd-core/bin/lib/prompt-budget.cjs +128 -165
  63. package/gsd-core/bin/lib/retired-artifact-cleanup.cjs +80 -0
  64. package/gsd-core/bin/lib/review-lane-descriptor.cjs +99 -0
  65. package/gsd-core/bin/lib/review-lane-runner.cjs +30 -6
  66. package/gsd-core/bin/lib/roadmap-command-router.cjs +42 -9
  67. package/gsd-core/bin/lib/roadmap-parser.cjs +100 -18
  68. package/gsd-core/bin/lib/roadmap.cjs +37 -7
  69. package/gsd-core/bin/lib/runtime-artifact-conversion.cjs +195 -62
  70. package/gsd-core/bin/lib/runtime-artifact-layout.cjs +15 -3
  71. package/gsd-core/bin/lib/runtime-homes.cjs +154 -41
  72. package/gsd-core/bin/lib/runtime-hooks-surface.cjs +105 -41
  73. package/gsd-core/bin/lib/section-manifest.cjs +209 -0
  74. package/gsd-core/bin/lib/shell-command-projection.cjs +113 -27
  75. package/gsd-core/bin/lib/smart-entry.cjs +12 -0
  76. package/gsd-core/bin/lib/state-transition.cjs +73 -8
  77. package/gsd-core/bin/lib/state.cjs +151 -62
  78. package/gsd-core/bin/lib/surface.cjs +12 -1
  79. package/gsd-core/bin/lib/uat-predicate.cjs +11 -1
  80. package/gsd-core/bin/lib/uat.cjs +320 -21
  81. package/gsd-core/bin/lib/unusable-input.cjs +9 -0
  82. package/gsd-core/bin/lib/verification.cjs +29 -12
  83. package/gsd-core/bin/lib/verify.cjs +29 -5
  84. package/gsd-core/bin/lib/workflow-fragments.cjs +557 -0
  85. package/gsd-core/bin/lib/workstream-inventory-builder.cjs +181 -18
  86. package/gsd-core/bin/lib/workstream-inventory.cjs +519 -27
  87. package/gsd-core/bin/lib/workstream.cjs +6 -0
  88. package/gsd-core/bin/lib/worktree-base-ref.cjs +50 -6
  89. package/gsd-core/bin/lib/worktree-safety.cjs +276 -118
  90. package/gsd-core/bin/shared/config-schema.manifest.json +2 -0
  91. package/gsd-core/references/artifact-types.md +10 -3
  92. package/gsd-core/references/autonomous-ui-design-contract.md +42 -0
  93. package/gsd-core/references/debugger-techniques.md +255 -0
  94. package/gsd-core/references/research-documentation-lookup.md +5 -3
  95. package/gsd-core/references/specless-probe-fallback.md +7 -6
  96. package/gsd-core/references/verifier-wiring-patterns.md +100 -0
  97. package/gsd-core/references/worktree-branch-check.md +2 -2
  98. package/gsd-core/templates/summary-complex.md +2 -0
  99. package/gsd-core/templates/summary-minimal.md +2 -0
  100. package/gsd-core/templates/summary-standard.md +2 -0
  101. package/gsd-core/templates/summary.md +2 -0
  102. package/gsd-core/workflows/audit-milestone.md +3 -0
  103. package/gsd-core/workflows/autonomous/steps/converge-banner.md +1 -0
  104. package/gsd-core/workflows/autonomous/steps/converge-dispatch-bg.md +11 -0
  105. package/gsd-core/workflows/autonomous/steps/converge-dispatch-inline.md +7 -0
  106. package/gsd-core/workflows/autonomous/steps/converge-fail-fast.md +21 -0
  107. package/gsd-core/workflows/autonomous/steps/converge-loop.md +7 -0
  108. package/gsd-core/workflows/autonomous.md +32 -69
  109. package/gsd-core/workflows/code-review/steps/dispatch-fix.md +39 -0
  110. package/gsd-core/workflows/code-review/steps/structural-pre-pass.md +83 -0
  111. package/gsd-core/workflows/code-review.md +42 -145
  112. package/gsd-core/workflows/complete-milestone/steps/git-tag.md +29 -0
  113. package/gsd-core/workflows/complete-milestone.md +23 -81
  114. package/gsd-core/workflows/debug.md +9 -12
  115. package/gsd-core/workflows/diagnose-issues.md +22 -0
  116. package/gsd-core/workflows/discovery-phase.md +4 -4
  117. package/gsd-core/workflows/discuss-phase-assumptions/steps/auto-advance-dispatch.md +15 -0
  118. package/gsd-core/workflows/discuss-phase-assumptions.md +5 -16
  119. package/gsd-core/workflows/docs-update/steps/dispatch-monorepo-packages.md +51 -0
  120. package/gsd-core/workflows/docs-update.md +8 -51
  121. package/gsd-core/workflows/execute-phase/steps/executor-isolation-dispatch.md +34 -2
  122. package/gsd-core/workflows/execute-phase/steps/gap-closure-artifacts.md +50 -0
  123. package/gsd-core/workflows/execute-phase/steps/partial-wave.md +31 -0
  124. package/gsd-core/workflows/execute-phase/steps/per-plan-worktree-gate.md +19 -0
  125. package/gsd-core/workflows/execute-phase/steps/regression-gate-run.md +42 -0
  126. package/gsd-core/workflows/execute-phase/steps/regression-gate.md +43 -37
  127. package/gsd-core/workflows/execute-phase.md +65 -137
  128. package/gsd-core/workflows/execute-plan.md +1 -1
  129. package/gsd-core/workflows/help/modes/full.md +6 -1
  130. package/gsd-core/workflows/ingest-docs.md +2 -1
  131. package/gsd-core/workflows/new-milestone/steps/project-md-milestone-write.md +16 -0
  132. package/gsd-core/workflows/new-milestone/steps/reset-phase-safety.md +19 -0
  133. package/gsd-core/workflows/new-milestone.md +21 -38
  134. package/gsd-core/workflows/new-project/steps/auto-mode-config.md +176 -0
  135. package/gsd-core/workflows/new-project/steps/auto-mode-detection.md +32 -0
  136. package/gsd-core/workflows/new-project/steps/codebase-map-offer.md +18 -0
  137. package/gsd-core/workflows/new-project.md +13 -226
  138. package/gsd-core/workflows/plan-phase/steps/adr-ingest-express-path.md +15 -0
  139. package/gsd-core/workflows/plan-phase/steps/chunked-planning-mode.md +110 -0
  140. package/gsd-core/workflows/plan-phase/steps/prd-express-gate.md +8 -0
  141. package/gsd-core/workflows/plan-phase/steps/research-only-early-exit.md +17 -0
  142. package/gsd-core/workflows/plan-phase/steps/research-only-modifiers.md +16 -0
  143. package/gsd-core/workflows/plan-phase/steps/reviews-prerequisite.md +17 -0
  144. package/gsd-core/workflows/plan-phase/steps/stall-detection-helpers.md +149 -0
  145. package/gsd-core/workflows/plan-phase.md +49 -193
  146. package/gsd-core/workflows/progress/steps/forensic-audit.md +125 -0
  147. package/gsd-core/workflows/progress/steps/mvp-display.md +18 -0
  148. package/gsd-core/workflows/progress.md +11 -153
  149. package/gsd-core/workflows/quick/steps/discussion-phase.md +124 -0
  150. package/gsd-core/workflows/quick/steps/plan-checker-loop.md +111 -0
  151. package/gsd-core/workflows/quick/steps/quick-verification.md +46 -0
  152. package/gsd-core/workflows/quick/steps/research-phase.md +72 -0
  153. package/gsd-core/workflows/quick/steps/worktree-pre-dispatch-commit.md +37 -0
  154. package/gsd-core/workflows/quick.md +20 -390
  155. package/gsd-core/workflows/resume-project.md +3 -0
  156. package/gsd-core/workflows/review/steps/reviewer-instances-note-1.md +4 -0
  157. package/gsd-core/workflows/review/steps/reviewer-instances-note-2.md +3 -0
  158. package/gsd-core/workflows/review.md +15 -8
  159. package/gsd-core/workflows/section-manifest.json +219 -0
  160. package/gsd-core/workflows/sketch.md +1 -1
  161. package/gsd-core/workflows/spec-phase.md +17 -14
  162. package/gsd-core/workflows/spike-wrap-up.md +20 -5
  163. package/gsd-core/workflows/spike.md +50 -16
  164. package/gsd-core/workflows/sync-skills.md +49 -11
  165. package/gsd-core/workflows/transition/steps/workstream-collision-check.md +17 -0
  166. package/gsd-core/workflows/transition.md +8 -21
  167. package/gsd-core/workflows/ui-phase.md +8 -7
  168. package/gsd-core/workflows/update/steps/channel-banner.md +7 -0
  169. package/gsd-core/workflows/update.md +18 -7
  170. package/gsd-core/workflows/verify-phase.md +4 -7
  171. package/gsd-core/workflows/verify-work/steps/automated-ui-verification.md +36 -0
  172. package/gsd-core/workflows/verify-work/steps/mvp-uat-framing.md +21 -0
  173. package/gsd-core/workflows/verify-work.md +8 -58
  174. package/hooks/dist/gsd-agent-isolation-guard.js +428 -0
  175. package/hooks/dist/gsd-check-update-worker.js +14 -5
  176. package/hooks/dist/gsd-cursor-subagent-start.js +532 -26
  177. package/hooks/dist/gsd-read-injection-scanner.js +7 -0
  178. package/hooks/dist/gsd-statusline.js +72 -6
  179. package/hooks/dist/gsd-worktree-path-guard.js +2 -1
  180. package/hooks/dist/gsd-write-guard.js +359 -0
  181. package/hooks/dist/lib/isolation-sentinel.js +268 -0
  182. package/hooks/dist/managed-hooks-registry.cjs +2 -0
  183. package/hooks/gsd-agent-isolation-guard.js +428 -0
  184. package/hooks/gsd-check-update-worker.js +14 -5
  185. package/hooks/gsd-cursor-subagent-start.js +532 -26
  186. package/hooks/gsd-read-injection-scanner.js +7 -0
  187. package/hooks/gsd-statusline.js +72 -6
  188. package/hooks/gsd-worktree-path-guard.js +2 -1
  189. package/hooks/gsd-write-guard.js +359 -0
  190. package/hooks/hooks.json +12 -0
  191. package/hooks/lib/isolation-sentinel.js +268 -0
  192. package/hooks/managed-hooks-registry.cjs +2 -0
  193. package/package.json +14 -5
  194. package/pi/gsd.cjs +57 -12
  195. package/scripts/build-hooks.js +9 -0
  196. package/scripts/changeset/lint.cjs +9 -2
  197. package/scripts/changeset/serialize.cjs +5 -1
  198. package/scripts/gen-capability-matrix.cjs +1 -1
  199. package/scripts/gen-context-index.cjs +448 -0
  200. package/scripts/gen-inventory-manifest.cjs +101 -1
  201. package/scripts/gen-prompt-budget-parity-corpus.cjs +645 -0
  202. package/scripts/gen-registry.cjs +39 -15
  203. package/scripts/gen-section-manifest.cjs +638 -0
  204. package/scripts/generate-package-identity.cjs +4 -2
  205. package/scripts/lint-allow-test-rule-refs.allowlist.json +17 -31
  206. package/scripts/lint-compiled-artifact-sync.cjs +6 -1
  207. package/scripts/lint-docs-command-form.cjs +195 -0
  208. package/scripts/lint-docs-required.cjs +9 -1
  209. package/scripts/lint-emitted-drift-ack.cjs +215 -20
  210. package/scripts/lint-example-parser-parity.cjs +395 -0
  211. package/scripts/lint-test-file-count.allowlist.json +27 -1
  212. package/scripts/mutation-matrix.cjs +13 -0
  213. package/scripts/prompt-injection-scan.sh +27 -6
  214. package/scripts/registry-schema.cjs +323 -94
  215. package/scripts/run-tests.cjs +3 -2
  216. package/scripts/validate-registry.cjs +10 -6
  217. package/skills/gsd-autonomous/SKILL.md +1 -1
  218. package/skills/gsd-execute-phase/SKILL.md +1 -1
  219. package/skills/gsd-mempalace-capture/SKILL.md +1 -1
  220. package/skills/gsd-new-milestone/SKILL.md +1 -1
  221. package/skills/gsd-plan-phase/SKILL.md +2 -2
  222. package/vscode/package.json +1 -1
  223. package/scripts/gen-emitted-baseline.cjs +0 -145
@@ -0,0 +1,557 @@
1
+ "use strict";
2
+ /**
3
+ * Workflow Fragments — in-file `<!-- gsd:section -->` marker parser/composer
4
+ * for GSD workflow markdown files (ADR-1671 epic #1671, Phase 3 / issue #2930,
5
+ * `.gsd/phase/chore-2930-fragmentize-xl-workflow/40-design.md`).
6
+ *
7
+ * Pure module: no I/O, no dependency beyond node built-ins and the shared
8
+ * budget-trim seam `context-composer.cjs` (issue #2929). Emission order is
9
+ * `parseWorkflowSections` -> `toFragments` -> `composeWithinBudget` ->
10
+ * `renderFragments` (= `composeWorkflow`), run BEFORE the per-runtime
11
+ * converters so a marker attribute never reaches a path-rewrite regex.
12
+ *
13
+ * ## Marker grammar (CLOSED)
14
+ *
15
+ * Open: a line whose only content (after trimming leading/trailing
16
+ * whitespace) is `<!-- gsd:section id="<id>" when="<when>" -->`.
17
+ * Close: a line whose only content is `<!-- /gsd:section -->`.
18
+ *
19
+ * Attribute order is free and inner spacing is flexible (Postel on FORMAT);
20
+ * `id` and `when` VALUES are validated strictly and fail closed (Postel is
21
+ * deliberately NOT applied to semantics — an unrecognized `when` is an
22
+ * authoring instruction that must never be silently dropped). `id` matches
23
+ * `/^[a-z0-9](?:[a-z0-9-]*[a-z0-9])?$/`; `when` must be `===` exactly one
24
+ * entry of the frozen {@link WHEN_VOCABULARY} — no operators, no negation,
25
+ * no nesting (Greenspun's Tenth Rule: extending the vocabulary is a
26
+ * coordinated ADR amendment, never an organic edit).
27
+ *
28
+ * ## Partition invariant
29
+ *
30
+ * `parseWorkflowSections` returns sections that PARTITION the document:
31
+ * every byte that is not part of a marker LINE belongs to exactly one
32
+ * section, in document order. Text outside any marker pair becomes a
33
+ * synthesized gap section (`explicit: false`, id `gap-<n>`, n from 0). A
34
+ * marker line is removed IN FULL — text and its original line terminator —
35
+ * so an unmarked document (88 of 89 workflows today) parses to exactly one
36
+ * implicit gap fragment and composes back byte-identical.
37
+ *
38
+ * Line splitting is CRLF-aware per line (not `content.split('\n')`, which
39
+ * would leave a stray `\r` glued to `.text` and cannot express a mixed
40
+ * CRLF-marker/LF-body document): {@link splitLinesPreservingEol} records
41
+ * each line's own terminator (`''`, `'\n'`, or `'\r\n'`) so reassembly is
42
+ * exact regardless of line-ending mixture.
43
+ *
44
+ * ## Fence + comment interleaving (the highest-risk code here)
45
+ *
46
+ * A marker is structural only when it is NOT inside a fenced code block and
47
+ * NOT inside an unrelated HTML comment (`<!-- gsd:loop-host ... -->` is a
48
+ * different marker family entirely and is left untouched by construction —
49
+ * it does not match the `gsd:section` token). Fences and comments are
50
+ * scanned in ONE left-to-right interleaved pass with two mutually exclusive
51
+ * states (`fence`, `inComment`), copying the discipline documented in
52
+ * `src/context-predicates.cts`'s module comment (DEFECT.CONTEXT-PREDICATES-
53
+ * COMMENT-FENCE-BLIND, #2928): while a fence is open, only a matching closer
54
+ * can end it (a `<!--`/`-->` token on a fenced line is fence content, never
55
+ * a comment boundary); while a comment is open, only a `-->` token can end
56
+ * it (a fence delimiter inside it is comment content, never a fence
57
+ * boundary); when neither is open, a comment opener is checked BEFORE a
58
+ * fence opener (HTML comments are lexically outermost). A two-pass design
59
+ * (mask one construct, then scan for the other) resolves this wrongly in
60
+ * one direction and silently skips to EOF — that is the exact defect this
61
+ * module avoids by construction. An unclosed fence at EOF does NOT throw;
62
+ * everything after it is simply literal.
63
+ *
64
+ * One deliberate refinement beyond a naive "does the trimmed line START
65
+ * WITH `<!--` and END WITH `-->`" check: whether a comment PERSISTS past
66
+ * the current line is decided by `.includes('-->')` (does a close token
67
+ * appear anywhere on the line), not by `.endsWith('-->')`. A line like
68
+ * `<!-- TODO: fix --> some trailing prose` closes its comment on the same
69
+ * line and must not swallow the rest of the document — it is simply not a
70
+ * `gsd:section` marker (a marker's grammar requires the comment to be the
71
+ * line's ONLY content), and is left as ordinary content in whichever
72
+ * section/gap contains it.
73
+ *
74
+ * Known inherited limitation (shared with `context-predicates.cts`, not a
75
+ * regression introduced here): comment-open detection is anchored to the
76
+ * start of the trimmed line. An HTML comment that opens *mid-line* (prose
77
+ * followed by an unclosed `<!--`) is not tracked, so a `gsd:section`-shaped
78
+ * line appearing on a later line inside that comment would be misread as
79
+ * real. GSD workflow markers are always authored on their own line, so this
80
+ * does not affect the production shape; documented here rather than papered
81
+ * over.
82
+ *
83
+ * ADR-457 build-at-publish: compiled by tsc to
84
+ * gsd-core/bin/lib/workflow-fragments.cjs (gitignored).
85
+ */
86
+ Object.defineProperty(exports, "__esModule", { value: true });
87
+ exports.REASON = exports.WHEN_VOCABULARY = void 0;
88
+ exports.parseWorkflowSections = parseWorkflowSections;
89
+ exports.toFragments = toFragments;
90
+ exports.renderFragments = renderFragments;
91
+ exports.composeWorkflow = composeWorkflow;
92
+ // eslint-disable-next-line @typescript-eslint/no-require-imports -- context-composer.cjs is a CommonJS module compiled from a sibling .cts source; `import x = require()` reads its module.exports namespace directly.
93
+ const contextComposer = require("./context-composer.cjs");
94
+ /**
95
+ * Frozen, CLOSED applicability vocabulary for the `when=` attribute.
96
+ * Extending this list requires an ADR amendment, not an organic edit
97
+ * (Greenspun's Tenth Rule — see the module doc comment).
98
+ *
99
+ * Widened from 4 to 14 entries via the ADR-1671 amendment for #2992 (epic
100
+ * #1671 Phase 6.1; see `.gsd/phase/chore-2992-widen-when-vocabulary/
101
+ * 40-design.md`), then from 14 to 19 via the ADR-1671 amendment for #2993
102
+ * (epic #1671 Phase 6.2; see `.gsd/phase/chore-2993-fragmentize-plan-phase/
103
+ * 40-design.md`), then from 19 to 20 via the ADR-1671 amendment for #2994
104
+ * (epic #1671 Phase 6.3, `verify-work.md`), then from 20 to 23 via a further
105
+ * #2994 amendment fragmentizing `code-review.md` and `complete-milestone.md`,
106
+ * then from 23 to 24 via a further #2994 amendment fragmentizing
107
+ * `autonomous.md`, then from 24 to 26 via a still further #2994 amendment
108
+ * fragmentizing `review.md` and `discuss-phase-assumptions.md`, then from 26
109
+ * to 30 (then 29; `flag:--full` retired as dead vocabulary) via the FINAL
110
+ * #2994 slice (epic #1671 Phase 6.3) fragmentizing
111
+ * `docs-update.md`, `update.md`, `transition.md`, and `new-milestone.md` —
112
+ * every one of the 13 workflows targeted by ADR-1671 is now on the fragment
113
+ * model. The vocabulary remains CLOSED: no operators, no negation, no nesting.
114
+ * Cardinality is not expressiveness — a 29-entry flat list with no
115
+ * composition is still not a language.
116
+ *
117
+ * Held at 14, not wider: an atom whose fact is never computed always
118
+ * evaluates FALSE, so a section marked with it would silently never
119
+ * include — a silent-exclusion bug, not a feature. One further atom
120
+ * (`flag:--verify-only`) was surveyed but is NOT admitted even now that
121
+ * `docs-update` has its own `cmdInit*` entry point (`cmdInitDocsUpdate`):
122
+ * the flag's control flow is INTERLEAVED across three non-contiguous
123
+ * touch-points in `docs-update.md` (an inline early-exit check in
124
+ * `init_context` — "If `--verify-only` is present…skip to
125
+ * verify_only_report" — a "Skip condition" note embedded in another step's
126
+ * body, and the `verify_only_report` step itself) rather than a single
127
+ * contiguous, whole-line, purely-additive region — admitting the atom to
128
+ * gate only the `verify_only_report` step would leave the other two
129
+ * touch-points as un-migrated raw `$ARGUMENTS` checks. `state:is-monorepo`
130
+ * (`dispatch-monorepo-packages` section) IS admitted in this slice — see the
131
+ * paragraph below.
132
+ * `flag:--fix`, `state:fallow-enabled`, and `state:git-create-tag` were
133
+ * withheld for the same reason until a further #2994 amendment gave
134
+ * `code-review` and `complete-milestone` their own dedicated `cmdInit*`
135
+ * entry points (`cmdInitCodeReview`, `cmdInitCompleteMilestone`). The
136
+ * originally-surveyed `flag:--converge` never shipped under that name: once
137
+ * `autonomous` gained its own dedicated `cmdInitAutonomous` entry point, the
138
+ * admitted atom is `state:plan-strategy-converge` instead — `--cross-ai` is
139
+ * a documented alias for `--converge` (`autonomous.md`'s own `PLAN_STRATEGY`
140
+ * resolver folds both into one value), so a `flag:--converge`-only atom
141
+ * would have left `--cross-ai`-only invocations silently excluded from the
142
+ * same sections; see the `state:plan-strategy-converge` paragraph below.
143
+ * `state:reviewer-instances-configured` and `state:auto-advance-active` were
144
+ * withheld the same way until `review` and `discuss-phase-assumptions`
145
+ * gained their own dedicated `cmdInit*` entry points (`cmdInitReview`,
146
+ * `cmdInitDiscussPhaseAssumptions`).
147
+ *
148
+ * The #2993 widening adds 5 entries fragmentizing `plan-phase.md`:
149
+ * `flag:--ingest`, `flag:--prd`, `flag:--research-phase`, `flag:--reviews`,
150
+ * `state:chunked-mode`. `state:chunked-mode` is a disjunction (`--chunked`
151
+ * flag OR `.planning/config.json` `workflow.plan_chunked`) resolved to a
152
+ * single boolean FACT by the init seam (`src/init.cts`) — the grammar still
153
+ * sees exactly one atom with no operator, preserving the same guard.
154
+ *
155
+ * The #2994 widening adds 1 entry fragmentizing `verify-work.md`:
156
+ * `state:ui-phase-active`. Like `state:chunked-mode`, it is a disjunction —
157
+ * the phase's active `plan:pre` loop hooks include the `ui-phase` step OR
158
+ * the phase directory already contains a `*-UI-SPEC.md` — resolved to a
159
+ * single boolean FACT by the init seam before it ever reaches this grammar.
160
+ *
161
+ * A further #2994 widening (epic #1671 Phase 6.3) adds 3 entries
162
+ * fragmentizing `code-review.md` and `complete-milestone.md`: `flag:--fix`
163
+ * (`dispatch-fix` section), `state:fallow-enabled` (`structural-pre-pass`
164
+ * section — the fallow config-gate resolver, previously re-derived inside
165
+ * the section body itself, is hoisted into `cmdInitCodeReview` and exposed
166
+ * as top-level `fallow_*` init-bundle fields), and `state:git-create-tag`
167
+ * (`git-tag` section — the `git.create_tag` config-gate resolver is hoisted
168
+ * into `cmdInitCompleteMilestone`).
169
+ *
170
+ * A still further #2994 widening (epic #1671 Phase 6.3) adds 1 entry
171
+ * fragmentizing `autonomous.md`: `state:plan-strategy-converge`, gating five
172
+ * sections (`converge-fail-fast`, `converge-banner`, `converge-dispatch-bg`,
173
+ * `converge-dispatch-inline`, `converge-loop`) that all share the same atom
174
+ * — legal and precedented (`plan-phase.md`'s `research-only-*` pair already
175
+ * shares `flag:--research-phase`). It is a disjunction — `--converge` OR its
176
+ * documented alias `--cross-ai` — resolved to a single boolean FACT by the
177
+ * new `cmdInitAutonomous` entry point (`flags.has('--converge') ||
178
+ * flags.has('--cross-ai')`) before it ever reaches this grammar, same
179
+ * discipline as `state:chunked-mode`/`state:ui-phase-active` above.
180
+ *
181
+ * A still further #2994 widening (epic #1671 Phase 6.3) adds 2 entries
182
+ * fragmentizing `review.md` and `discuss-phase-assumptions.md`:
183
+ * `state:reviewer-instances-configured` (`reviewer-instances-note-1` and
184
+ * `reviewer-instances-note-2` sections — two peripheral notes sharing one
185
+ * atom, the same sharing pattern `plan-phase.md`'s `research-only-*` pair
186
+ * already established) and `state:auto-advance-active` (`auto-advance-dispatch`
187
+ * section — a disjunction, `--auto` flag OR a consolidated auto-mode config
188
+ * fact, resolved to a single boolean FACT by the new
189
+ * `cmdInitDiscussPhaseAssumptions` entry point before it ever reaches this
190
+ * grammar, same discipline as `state:chunked-mode` above).
191
+ *
192
+ * The FINAL #2994 widening (epic #1671 Phase 6.3) adds 4 entries, closing
193
+ * out the last four workflows on ADR-1671's fragmentization list —
194
+ * `docs-update.md`, `update.md`, `transition.md`, `new-milestone.md` — none
195
+ * of which carried a `gsd_run query init.*` call before this slice:
196
+ * `state:is-monorepo` (`dispatch-monorepo-packages` section, new
197
+ * `cmdInitDocsUpdate` entry point — reuses `docs.cts`'s own
198
+ * `detectMonorepoWorkspaces` detector rather than a second scan);
199
+ * `state:next-channel` (`channel-banner` section, new `cmdInitUpdate` entry
200
+ * point — `--next` OR its documented alias `--rc`, resolved in PARALLEL
201
+ * with, not in place of, `update.md`'s own `TAG="next"` case-statement,
202
+ * which issue #815's regression test requires to stay literal in the
203
+ * workflow); `state:workstream-active` (`workstream-collision-check`
204
+ * section, new `cmdInitTransition` entry point — a workstream is active,
205
+ * `GSD_WORKSTREAM` env falling back to the stored active-workstream
206
+ * pointer, the same authoritative source `cmdInitProgress` already uses);
207
+ * and `state:flat-mode` (`project-md-milestone-write` section,
208
+ * `cmdInitNewMilestone` — the positively-phrased INVERSE of
209
+ * `state:workstream-active`, introduced because the grammar has no negation
210
+ * operator and `new-milestone.md`'s Step 4 Part A is gated on the OPPOSITE
211
+ * condition from `transition.md`'s section).
212
+ */
213
+ exports.WHEN_VOCABULARY = Object.freeze([
214
+ 'always',
215
+ 'flag:--wave',
216
+ 'state:gap-closure-phase',
217
+ 'state:has-prior-phases',
218
+ 'flag:--auto',
219
+ 'flag:--discuss',
220
+ 'flag:--fix',
221
+ 'flag:--forensic',
222
+ 'flag:--ingest',
223
+ 'flag:--prd',
224
+ 'flag:--research',
225
+ 'flag:--research-phase',
226
+ 'flag:--reset-phase-numbers',
227
+ 'flag:--reviews',
228
+ 'flag:--validate',
229
+ 'state:auto-advance-active',
230
+ 'state:chunked-mode',
231
+ 'state:fallow-enabled',
232
+ 'state:flat-mode',
233
+ 'state:git-create-tag',
234
+ 'state:is-monorepo',
235
+ 'state:needs-codebase-map',
236
+ 'state:next-channel',
237
+ 'state:phase-mvp-mode',
238
+ 'state:plan-strategy-converge',
239
+ 'state:reviewer-instances-configured',
240
+ 'state:ui-phase-active',
241
+ 'state:workstream-active',
242
+ 'state:worktrees-enabled',
243
+ ]);
244
+ /**
245
+ * Frozen, stable reason codes for every `fail()` throw site in this module.
246
+ * Tests assert via `assert.equal(err.reason, REASON.X)` rather than
247
+ * regex-/substring-matching the human-readable message (CONTRIBUTING.md
248
+ * "Prohibited: Raw Text Matching on Test Outputs"; shape copied from this
249
+ * repo's own `gsd-core/bin/verify-reapply-patches.cjs` REASON enum) — a
250
+ * message reword must never silently pass a test that exists to catch a
251
+ * behavior regression.
252
+ *
253
+ * Adding a new reason requires updating this map AND the test that locks
254
+ * `Object.keys(REASON).sort()` as a coordinated change.
255
+ */
256
+ exports.REASON = Object.freeze({
257
+ UNCLOSED_SECTION: 'unclosed_section',
258
+ UNMATCHED_CLOSE: 'unmatched_close',
259
+ NESTED_SECTION: 'nested_section',
260
+ DUPLICATE_ID: 'duplicate_id',
261
+ MISSING_ID: 'missing_id',
262
+ MISSING_WHEN: 'missing_when',
263
+ MALFORMED_ID: 'malformed_id',
264
+ UNKNOWN_WHEN: 'unknown_when',
265
+ MALFORMED_ATTRIBUTES: 'malformed_attributes',
266
+ UNRECOGNIZED_ATTRIBUTE: 'unrecognized_attribute',
267
+ CLOSE_WITH_ATTRIBUTES: 'close_with_attributes',
268
+ });
269
+ /**
270
+ * Split `content` into per-line records that each carry their OWN original
271
+ * terminator, so CRLF/LF mixes and a missing trailing terminator reassemble
272
+ * byte-for-byte via `record.text + record.eol` concatenation. See the
273
+ * module doc comment's "Line splitting is CRLF-aware" note for why a bare
274
+ * `content.split('\n')` cannot serve this.
275
+ *
276
+ * @param content - full source document text
277
+ */
278
+ function splitLinesPreservingEol(content) {
279
+ const lines = [];
280
+ let i = 0;
281
+ while (i < content.length) {
282
+ const nlIdx = content.indexOf('\n', i);
283
+ if (nlIdx === -1) {
284
+ lines.push({ text: content.slice(i), eol: '' });
285
+ break;
286
+ }
287
+ const hasCr = content[nlIdx - 1] === '\r';
288
+ const end = hasCr ? nlIdx - 1 : nlIdx;
289
+ lines.push({ text: content.slice(i, end), eol: hasCr ? '\r\n' : '\n' });
290
+ i = nlIdx + 1;
291
+ }
292
+ return lines;
293
+ }
294
+ // Fence delimiter line matcher — mirrors `context-predicates.cts`'s (itself
295
+ // mirroring `markdown-sectionizer.cts`'s `scanFencedBlocks`) exactly: >=3
296
+ // backticks/tildes, <=3-space indent tolerance. This is a single-line
297
+ // fence-OPENER/CLOSER probe, not a multiline fence-block-strip regex — it
298
+ // does not trip `local/no-adhoc-markdown-parsing`'s fenceRegex fingerprint
299
+ // (no `[\s\S]` multiline body in the pattern).
300
+ const FENCE_DELIM_RE = /^( {0,3})(`{3,}|~{3,})(.*)$/;
301
+ const OPEN_TAG_RE = /^gsd:section(?=\s|$)/;
302
+ const CLOSE_TAG = '/gsd:section';
303
+ const ID_RE = /^[a-z0-9](?:[a-z0-9-]*[a-z0-9])?$/;
304
+ /**
305
+ * Parse a candidate marker's attribute string (everything after `gsd:section`,
306
+ * already trimmed) into a `key -> value` map, or `null` if it does not
307
+ * consist entirely of zero-or-more `key="value"` tokens (attribute order is
308
+ * free; spacing around `=` and between tokens is flexible — Postel on
309
+ * FORMAT). Returns `null` on a duplicate attribute key too.
310
+ *
311
+ * @param attrsPart - the marker's attribute text, e.g. `id="x" when="always"`
312
+ */
313
+ function parseAttrs(attrsPart) {
314
+ const attrs = new Map();
315
+ let remaining = attrsPart;
316
+ const ATTR_RE = /^\s*([A-Za-z][A-Za-z0-9_-]*)\s*=\s*"([^"]*)"/;
317
+ while (remaining.length > 0) {
318
+ const m = ATTR_RE.exec(remaining);
319
+ if (!m)
320
+ return null;
321
+ const [full, key, value] = m;
322
+ if (attrs.has(key))
323
+ return null;
324
+ attrs.set(key, value);
325
+ remaining = remaining.slice(full.length);
326
+ }
327
+ return attrs;
328
+ }
329
+ /**
330
+ * Throws a `TypeError` naming `sourcePath` (when given) and the 1-based
331
+ * `line`, carrying `reason` (one of {@link REASON}) as a typed property so
332
+ * callers/tests never need to pattern-match the message prose.
333
+ */
334
+ function fail(sourcePath, line, reason, message) {
335
+ const loc = sourcePath ? `${sourcePath}:${line}` : `line ${line}`;
336
+ const err = new TypeError(`workflow-fragments: ${message} (${loc})`);
337
+ err.reason = reason;
338
+ throw err;
339
+ }
340
+ /**
341
+ * Classify a complete one-line HTML comment's inner text (already stripped
342
+ * of `<!--`/`-->` and trimmed) as a `gsd:section` open attempt, a close
343
+ * marker, or "not a marker at all" — including `gsd:loop-host` and any
344
+ * other unrelated comment, which never match the `gsd:section` token and
345
+ * fall through to `{kind: 'none'}` untouched. Throws on any STRUCTURAL
346
+ * violation of a recognized open/close attempt (fail-closed grammar).
347
+ *
348
+ * @param inner - the comment's inner text, e.g. `gsd:section id="x" when="always"`
349
+ * @param sourcePath - optional file path named in thrown errors
350
+ * @param lineNo - 1-based line number named in thrown errors
351
+ */
352
+ function classifyMarker(inner, sourcePath, lineNo) {
353
+ if (inner === CLOSE_TAG) {
354
+ return { kind: 'close' };
355
+ }
356
+ if (inner.startsWith(CLOSE_TAG) && /^\s/.test(inner.slice(CLOSE_TAG.length))) {
357
+ fail(sourcePath, lineNo, exports.REASON.CLOSE_WITH_ATTRIBUTES, 'close marker must not carry attributes');
358
+ }
359
+ if (!OPEN_TAG_RE.test(inner)) {
360
+ return { kind: 'none' };
361
+ }
362
+ const attrsPart = inner.slice('gsd:section'.length).trim();
363
+ const attrs = parseAttrs(attrsPart);
364
+ if (attrs === null) {
365
+ fail(sourcePath, lineNo, exports.REASON.MALFORMED_ATTRIBUTES, 'malformed section marker attributes');
366
+ }
367
+ const extraKeys = [...attrs.keys()].filter((k) => k !== 'id' && k !== 'when');
368
+ if (extraKeys.length > 0) {
369
+ fail(sourcePath, lineNo, exports.REASON.UNRECOGNIZED_ATTRIBUTE, `unrecognized attribute "${extraKeys[0]}" on section marker`);
370
+ }
371
+ const id = attrs.get('id');
372
+ const when = attrs.get('when');
373
+ if (id === undefined) {
374
+ fail(sourcePath, lineNo, exports.REASON.MISSING_ID, 'section marker missing required "id" attribute');
375
+ }
376
+ if (when === undefined) {
377
+ fail(sourcePath, lineNo, exports.REASON.MISSING_WHEN, 'section marker missing required "when" attribute');
378
+ }
379
+ if (!ID_RE.test(id)) {
380
+ fail(sourcePath, lineNo, exports.REASON.MALFORMED_ID, `section marker "id" value "${id}" does not match ${ID_RE}`);
381
+ }
382
+ if (!exports.WHEN_VOCABULARY.includes(when)) {
383
+ fail(sourcePath, lineNo, exports.REASON.UNKNOWN_WHEN, `section marker "when" value "${when}" is not in the frozen WHEN_VOCABULARY`);
384
+ }
385
+ return { kind: 'open', id, when };
386
+ }
387
+ /**
388
+ * Parse a workflow document's `<!-- gsd:section -->` markers into a
389
+ * document-order partition of {@link WorkflowSection}s. See the module doc
390
+ * comment for the full grammar, partition invariant, and fence/comment
391
+ * interleaving discipline.
392
+ *
393
+ * @param content - full workflow markdown source
394
+ * @param sourcePath - optional file path named in thrown errors
395
+ */
396
+ function parseWorkflowSections(content, sourcePath) {
397
+ const lines = splitLinesPreservingEol(content);
398
+ const sections = [];
399
+ let fence = null;
400
+ let inComment = false;
401
+ let currentOpen = null;
402
+ const seenIds = new Set();
403
+ let gapCounter = 0;
404
+ let cursor = 0;
405
+ const joinRange = (from, to) => {
406
+ let out = '';
407
+ for (let k = from; k <= to; k++) {
408
+ out += lines[k].text + lines[k].eol;
409
+ }
410
+ return out;
411
+ };
412
+ const flushGapBefore = (nextIndex) => {
413
+ if (nextIndex > cursor) {
414
+ sections.push({
415
+ id: `gap-${gapCounter}`,
416
+ when: 'always',
417
+ body: joinRange(cursor, nextIndex - 1),
418
+ explicit: false,
419
+ startLine: cursor + 1,
420
+ });
421
+ gapCounter += 1;
422
+ }
423
+ };
424
+ for (let i = 0; i < lines.length; i++) {
425
+ const lineNo = i + 1;
426
+ const rawText = lines[i].text;
427
+ if (fence !== null) {
428
+ // Inside a real fence: only a matching closer can end it. Any
429
+ // `<!--`/`-->` on this line is fence content, never a comment
430
+ // boundary (row 5/6 of 50-test-matrix.md).
431
+ const m = FENCE_DELIM_RE.exec(rawText);
432
+ if (m) {
433
+ const char = m[2][0];
434
+ const len = m[2].length;
435
+ const trailing = m[3];
436
+ if (char === fence.char && len >= fence.len && /^\s*$/.test(trailing)) {
437
+ fence = null;
438
+ }
439
+ }
440
+ continue;
441
+ }
442
+ if (inComment) {
443
+ // Inside a real (unrelated) comment: only '-->' can end it. Any
444
+ // fence delimiter on this line is comment content, never a fence
445
+ // boundary (row 7 of 50-test-matrix.md).
446
+ if (rawText.includes('-->'))
447
+ inComment = false;
448
+ continue;
449
+ }
450
+ const trimmed = rawText.trim();
451
+ if (trimmed.startsWith('<!--')) {
452
+ // Persistence is decided by whether a close token appears ANYWHERE on
453
+ // the line, not by whether the line ENDS with one — see the module
454
+ // doc comment's "deliberate refinement" note. Marker-hood additionally
455
+ // requires the comment to be the line's ENTIRE content.
456
+ const hasClose = trimmed.includes('-->');
457
+ if (hasClose && trimmed.endsWith('-->')) {
458
+ const inner = trimmed.slice(4, trimmed.length - 3).trim();
459
+ const classification = classifyMarker(inner, sourcePath, lineNo);
460
+ if (classification.kind === 'open') {
461
+ if (currentOpen !== null) {
462
+ fail(sourcePath, lineNo, exports.REASON.NESTED_SECTION, `nested gsd:section marker (already inside "${currentOpen.id}")`);
463
+ }
464
+ if (seenIds.has(classification.id)) {
465
+ fail(sourcePath, lineNo, exports.REASON.DUPLICATE_ID, `duplicate section id "${classification.id}"`);
466
+ }
467
+ flushGapBefore(i);
468
+ seenIds.add(classification.id);
469
+ currentOpen = { id: classification.id, when: classification.when, startLineIndex: i };
470
+ cursor = i + 1;
471
+ }
472
+ else if (classification.kind === 'close') {
473
+ if (currentOpen === null) {
474
+ fail(sourcePath, lineNo, exports.REASON.UNMATCHED_CLOSE, 'unmatched /gsd:section close marker');
475
+ }
476
+ sections.push({
477
+ id: currentOpen.id,
478
+ when: currentOpen.when,
479
+ body: joinRange(currentOpen.startLineIndex + 1, i - 1),
480
+ explicit: true,
481
+ startLine: currentOpen.startLineIndex + 1,
482
+ });
483
+ currentOpen = null;
484
+ cursor = i + 1;
485
+ }
486
+ // classification.kind === 'none': ordinary self-contained comment
487
+ // (e.g. a one-line `gsd:loop-host` or unrelated comment) — no state change.
488
+ }
489
+ if (!hasClose) {
490
+ inComment = true; // multi-line: stays open until a later '-->'
491
+ }
492
+ continue;
493
+ }
494
+ const fenceMatch = FENCE_DELIM_RE.exec(rawText);
495
+ if (fenceMatch) {
496
+ const char = fenceMatch[2][0];
497
+ const trailing = fenceMatch[3];
498
+ // CommonMark §4.5: a backtick fence opener's info string must not
499
+ // itself contain a backtick.
500
+ if (!(char === '`' && trailing.includes('`'))) {
501
+ fence = { char, len: fenceMatch[2].length };
502
+ }
503
+ }
504
+ }
505
+ if (currentOpen !== null) {
506
+ fail(sourcePath, currentOpen.startLineIndex + 1, exports.REASON.UNCLOSED_SECTION, `unclosed gsd:section marker "${currentOpen.id}"`);
507
+ }
508
+ flushGapBefore(lines.length);
509
+ return sections;
510
+ }
511
+ /**
512
+ * Map parsed sections to `context-composer` fragments. Every strategy is
513
+ * `{kind: 'verbatim'}` (design row 23 / test matrix rows 26-29): non-
514
+ * lossiness in this phase is a STRUCTURAL guarantee of the strategy choice,
515
+ * never a large-budget trick.
516
+ *
517
+ * @param sections - document-order sections from {@link parseWorkflowSections}
518
+ */
519
+ function toFragments(sections) {
520
+ return sections.map((section) => ({
521
+ id: section.id,
522
+ content: section.body,
523
+ strategy: { kind: 'verbatim' },
524
+ }));
525
+ }
526
+ /**
527
+ * Concatenate a {@link contextComposer.ComposeResult}'s fragment contents,
528
+ * in declaration order, back into a document. Every fragment here is
529
+ * `verbatim` with an empty wrapper, so this is a plain join.
530
+ *
531
+ * @param result - the plan returned by `composeWithinBudget`
532
+ */
533
+ function renderFragments(result) {
534
+ return result.fragments.map((f) => f.content).join('');
535
+ }
536
+ /**
537
+ * THE emission entry point: parse -> toFragments -> composeWithinBudget ->
538
+ * render. `budget` defaults to `Number.MAX_SAFE_INTEGER` (no pressure).
539
+ * Because every fragment is `verbatim`, the output is identical regardless
540
+ * of the budget value (design row 23) — this is never relied upon as the
541
+ * source of non-lossiness; the strategy set is.
542
+ *
543
+ * @param content - full workflow markdown source
544
+ * @param opts - `sourcePath` named in thrown parse errors; `budget` in bytes
545
+ */
546
+ function composeWorkflow(content, opts = {}) {
547
+ const { sourcePath, budget = Number.MAX_SAFE_INTEGER } = opts;
548
+ const sections = parseWorkflowSections(content, sourcePath);
549
+ const fragments = toFragments(sections);
550
+ const composed = contextComposer.composeWithinBudget({
551
+ fragments,
552
+ budget,
553
+ measure: (text) => Buffer.byteLength(text, 'utf8'),
554
+ options: { charsPerUnit: 1 },
555
+ });
556
+ return renderFragments(composed);
557
+ }