@opengsd/gsd-core 1.9.1 → 1.11.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 (426) 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 +27 -3
  5. package/agents/gsd-debug-session-manager.md +11 -0
  6. package/agents/gsd-debugger.md +12 -246
  7. package/agents/gsd-doc-synthesizer.md +2 -4
  8. package/agents/gsd-executor.md +12 -10
  9. package/agents/gsd-integration-checker.md +3 -0
  10. package/agents/gsd-mempalace-curator.md +5 -2
  11. package/agents/gsd-phase-researcher.md +20 -1
  12. package/agents/gsd-plan-checker.md +46 -0
  13. package/agents/gsd-planner.md +49 -54
  14. package/agents/gsd-roadmapper.md +21 -3
  15. package/agents/gsd-user-profiler.md +3 -0
  16. package/agents/gsd-verifier.md +26 -73
  17. package/bin/install.js +1272 -1238
  18. package/bin/lib/ui-safety-gate.cjs +2 -0
  19. package/commands/gsd/code-review.md +1 -1
  20. package/commands/gsd/execute-phase.md +1 -1
  21. package/commands/gsd/map-codebase.md +1 -1
  22. package/commands/gsd/mempalace-capture.md +2 -2
  23. package/commands/gsd/mempalace-recall.md +1 -1
  24. package/commands/gsd/new-milestone.md +2 -2
  25. package/commands/gsd/plan-phase.md +1 -1
  26. package/commands/gsd/quick.md +1 -1
  27. package/commands/gsd/review-backlog.md +2 -1
  28. package/commands/gsd/verify-work.md +1 -1
  29. package/gsd-core/bin/gsd-tools.cjs +1009 -115
  30. package/gsd-core/bin/lib/active-workstream-store.cjs +153 -12
  31. package/gsd-core/bin/lib/agent-install-check.cjs +268 -38
  32. package/gsd-core/bin/lib/api-coverage.cjs +123 -5
  33. package/gsd-core/bin/lib/artifacts.cjs +3 -0
  34. package/gsd-core/bin/lib/assumption-delta.cjs +2 -4
  35. package/gsd-core/bin/lib/audit-command-router.cjs +9 -2
  36. package/gsd-core/bin/lib/audit.cjs +926 -202
  37. package/gsd-core/bin/lib/broken-windows.cjs +36 -6
  38. package/gsd-core/bin/lib/capability-consent.cjs +149 -15
  39. package/gsd-core/bin/lib/capability-lifecycle.cjs +45 -0
  40. package/gsd-core/bin/lib/capability-registry.cjs +608 -148
  41. package/gsd-core/bin/lib/capability-source.cjs +92 -0
  42. package/gsd-core/bin/lib/capability-trust.cjs +444 -25
  43. package/gsd-core/bin/lib/capability-validator.cjs +507 -24
  44. package/gsd-core/bin/lib/capability-writer.cjs +3 -2
  45. package/gsd-core/bin/lib/check-command-router.cjs +114 -38
  46. package/gsd-core/bin/lib/claude-orchestration.cjs +56 -3
  47. package/gsd-core/bin/lib/codex-agent-toml.cjs +329 -0
  48. package/gsd-core/bin/lib/command-aliases.cjs +94 -0
  49. package/gsd-core/bin/lib/command-roster.cjs +44 -1
  50. package/gsd-core/bin/lib/commands.cjs +665 -99
  51. package/gsd-core/bin/lib/commonjs-marker.cjs +142 -0
  52. package/gsd-core/bin/lib/complexity-trigger.cjs +1172 -0
  53. package/gsd-core/bin/lib/config-loader.cjs +76 -0
  54. package/gsd-core/bin/lib/config.cjs +22 -2
  55. package/gsd-core/bin/lib/context-composer.cjs +278 -0
  56. package/gsd-core/bin/lib/context-predicates.cjs +506 -0
  57. package/gsd-core/bin/lib/core-utils.cjs +217 -40
  58. package/gsd-core/bin/lib/decisions.cjs +23 -0
  59. package/gsd-core/bin/lib/docs.cjs +3 -2
  60. package/gsd-core/bin/lib/external-job.cjs +19 -4
  61. package/gsd-core/bin/lib/fallow-runner.cjs +20 -44
  62. package/gsd-core/bin/lib/frontmatter.cjs +239 -32
  63. package/gsd-core/bin/lib/gap-checker.cjs +68 -7
  64. package/gsd-core/bin/lib/gate-predicate-evaluator.cjs +57 -6
  65. package/gsd-core/bin/lib/git-base-branch.cjs +160 -15
  66. package/gsd-core/bin/lib/graphify.cjs +142 -27
  67. package/gsd-core/bin/lib/gsd2-import.cjs +37 -5
  68. package/gsd-core/bin/lib/health-diagnostic-rules/agent-install.cjs +101 -0
  69. package/gsd-core/bin/lib/health-diagnostic-rules/config-validation.cjs +348 -0
  70. package/gsd-core/bin/lib/health-diagnostic-rules/consistency.cjs +145 -0
  71. package/gsd-core/bin/lib/health-diagnostic-rules/install-surface-shadowing.cjs +98 -0
  72. package/gsd-core/bin/lib/health-diagnostic-rules/milestone-archive-hygiene.cjs +100 -0
  73. package/gsd-core/bin/lib/health-diagnostic-rules/phase-structure.cjs +222 -0
  74. package/gsd-core/bin/lib/health-diagnostic-rules/roadmap-disk-consistency.cjs +265 -0
  75. package/gsd-core/bin/lib/health-diagnostic-rules/root-existence.cjs +161 -0
  76. package/gsd-core/bin/lib/health-diagnostic-rules/state-consistency.cjs +303 -0
  77. package/gsd-core/bin/lib/health-diagnostic-rules/worktree-health.cjs +173 -0
  78. package/gsd-core/bin/lib/health-diagnostic-types.cjs +68 -0
  79. package/gsd-core/bin/lib/health-diagnostic.cjs +431 -0
  80. package/gsd-core/bin/lib/host-integration.cjs +13 -1
  81. package/gsd-core/bin/lib/host-runtime-detection.cjs +134 -0
  82. package/gsd-core/bin/lib/init-command-router.cjs +83 -8
  83. package/gsd-core/bin/lib/init.cjs +1325 -169
  84. package/gsd-core/bin/lib/install-effort-resolver.cjs +73 -30
  85. package/gsd-core/bin/lib/install-engine.cjs +805 -264
  86. package/gsd-core/bin/lib/install-fs-adapter.cjs +262 -0
  87. package/gsd-core/bin/lib/install-model-override-resolver.cjs +203 -0
  88. package/gsd-core/bin/lib/install-profiles.cjs +160 -57
  89. package/gsd-core/bin/lib/install-scope.cjs +270 -0
  90. package/gsd-core/bin/lib/install-shadow-report.cjs +385 -0
  91. package/gsd-core/bin/lib/installed-surface-resolver.cjs +381 -0
  92. package/gsd-core/bin/lib/installer-migration-authoring.cjs +3 -1
  93. package/gsd-core/bin/lib/installer-migration-report.cjs +4 -0
  94. package/gsd-core/bin/lib/installer-migrations/007-retire-config-root-commonjs-marker.cjs +149 -0
  95. package/gsd-core/bin/lib/installer-migrations/008-cursor-retire-commands-surface.cjs +55 -0
  96. package/gsd-core/bin/lib/installer-migrations/009-pi-retire-reserved-hooks-dir.cjs +199 -0
  97. package/gsd-core/bin/lib/installer-migrations.cjs +206 -13
  98. package/gsd-core/bin/lib/io.cjs +38 -3
  99. package/gsd-core/bin/lib/markdown-sectionizer.cjs +8 -1
  100. package/gsd-core/bin/lib/markdown-table.cjs +133 -20
  101. package/gsd-core/bin/lib/mcp-catalog.cjs +518 -0
  102. package/gsd-core/bin/lib/mcp-server.cjs +135 -3
  103. package/gsd-core/bin/lib/milestone-lock.cjs +248 -0
  104. package/gsd-core/bin/lib/milestone.cjs +821 -109
  105. package/gsd-core/bin/lib/model-catalog.cjs +59 -1
  106. package/gsd-core/bin/lib/model-resolver.cjs +183 -40
  107. package/gsd-core/bin/lib/normalize-test-command.cjs +1 -1
  108. package/gsd-core/bin/lib/pattern.cjs +122 -0
  109. package/gsd-core/bin/lib/phase-estimation.cjs +1 -1
  110. package/gsd-core/bin/lib/phase-id.cjs +507 -36
  111. package/gsd-core/bin/lib/phase-lifecycle.cjs +28 -3
  112. package/gsd-core/bin/lib/phase-locator.cjs +258 -58
  113. package/gsd-core/bin/lib/phase.cjs +891 -156
  114. package/gsd-core/bin/lib/plan-dependency-graph.cjs +303 -0
  115. package/gsd-core/bin/lib/plan-drift-guard.cjs +120 -0
  116. package/gsd-core/bin/lib/plan-scan.cjs +86 -2
  117. package/gsd-core/bin/lib/planning-scope.cjs +31 -0
  118. package/gsd-core/bin/lib/planning-snapshot.cjs +890 -0
  119. package/gsd-core/bin/lib/planning-workspace.cjs +60 -6
  120. package/gsd-core/bin/lib/probe-core.cjs +1 -1
  121. package/gsd-core/bin/lib/profile-output.cjs +1 -1
  122. package/gsd-core/bin/lib/prompt-budget.cjs +128 -165
  123. package/gsd-core/bin/lib/refactor-trigger-command-router.cjs +740 -0
  124. package/gsd-core/bin/lib/retired-artifact-cleanup.cjs +85 -0
  125. package/gsd-core/bin/lib/review-lane-descriptor.cjs +108 -0
  126. package/gsd-core/bin/lib/review-lane-invocation.cjs +30 -0
  127. package/gsd-core/bin/lib/review-lane-runner.cjs +447 -68
  128. package/gsd-core/bin/lib/review-reviewer-selection.cjs +13 -18
  129. package/gsd-core/bin/lib/roadmap-command-router.cjs +76 -9
  130. package/gsd-core/bin/lib/roadmap-parser.cjs +1035 -194
  131. package/gsd-core/bin/lib/roadmap-upgrade.cjs +37 -10
  132. package/gsd-core/bin/lib/roadmap.cjs +405 -84
  133. package/gsd-core/bin/lib/runtime-artifact-conversion.cjs +795 -100
  134. package/gsd-core/bin/lib/runtime-artifact-install-plan.cjs +14 -2
  135. package/gsd-core/bin/lib/runtime-artifact-layout.cjs +440 -57
  136. package/gsd-core/bin/lib/runtime-config-adapter-registry.cjs +3 -2
  137. package/gsd-core/bin/lib/runtime-homes.cjs +220 -41
  138. package/gsd-core/bin/lib/runtime-hooks-surface.cjs +220 -44
  139. package/gsd-core/bin/lib/runtime-name-policy.cjs +3 -1
  140. package/gsd-core/bin/lib/runtime-slash.cjs +27 -9
  141. package/gsd-core/bin/lib/section-manifest.cjs +209 -0
  142. package/gsd-core/bin/lib/security.cjs +104 -5
  143. package/gsd-core/bin/lib/shell-command-projection.cjs +388 -30
  144. package/gsd-core/bin/lib/smart-entry.cjs +154 -22
  145. package/gsd-core/bin/lib/state-command-router.cjs +5 -1
  146. package/gsd-core/bin/lib/state-document.cjs +152 -8
  147. package/gsd-core/bin/lib/state-transition.cjs +424 -105
  148. package/gsd-core/bin/lib/state.cjs +1927 -401
  149. package/gsd-core/bin/lib/surface.cjs +35 -10
  150. package/gsd-core/bin/lib/text-lines.cjs +80 -0
  151. package/gsd-core/bin/lib/token-scanner.cjs +76 -0
  152. package/gsd-core/bin/lib/uat-predicate.cjs +20 -4
  153. package/gsd-core/bin/lib/uat.cjs +706 -64
  154. package/gsd-core/bin/lib/ui-frontend-evidence.cjs +157 -0
  155. package/gsd-core/bin/lib/ui-safety-gate.cjs +14 -5
  156. package/gsd-core/bin/lib/unusable-input.cjs +33 -0
  157. package/gsd-core/bin/lib/update-context.cjs +8 -2
  158. package/gsd-core/bin/lib/user-artifact-staging.cjs +705 -0
  159. package/gsd-core/bin/lib/validate.cjs +20 -6
  160. package/gsd-core/bin/lib/vendor/README.md +37 -0
  161. package/gsd-core/bin/lib/vendor/re2js.cjs +6480 -0
  162. package/gsd-core/bin/lib/vendor/re2js.d.cts +938 -0
  163. package/gsd-core/bin/lib/verification-command-router.cjs +2 -1
  164. package/gsd-core/bin/lib/verification.cjs +287 -20
  165. package/gsd-core/bin/lib/verify.cjs +368 -880
  166. package/gsd-core/bin/lib/workflow-fragments.cjs +557 -0
  167. package/gsd-core/bin/lib/workstream-inventory-builder.cjs +203 -19
  168. package/gsd-core/bin/lib/workstream-inventory.cjs +576 -31
  169. package/gsd-core/bin/lib/workstream.cjs +8 -2
  170. package/gsd-core/bin/lib/worktree-base-ref.cjs +50 -6
  171. package/gsd-core/bin/lib/worktree-safety.cjs +450 -125
  172. package/gsd-core/bin/shared/config-defaults.manifest.json +1 -0
  173. package/gsd-core/bin/shared/config-schema.manifest.json +9 -1
  174. package/gsd-core/references/agent-contracts.md +43 -26
  175. package/gsd-core/references/artifact-types.md +10 -3
  176. package/gsd-core/references/autonomous-ui-design-contract.md +42 -0
  177. package/gsd-core/references/checkpoints.md +2 -2
  178. package/gsd-core/references/context-budget.md +1 -1
  179. package/gsd-core/references/debugger-techniques.md +255 -0
  180. package/gsd-core/references/dispatch-isolation-gate.md +138 -0
  181. package/gsd-core/references/doc-conflict-engine.md +1 -1
  182. package/gsd-core/references/execute-mvp-tdd.md +3 -3
  183. package/gsd-core/references/execute-phase-between-wave-reset.md +6 -2
  184. package/gsd-core/references/execute-phase-context-guard.md +1 -1
  185. package/gsd-core/references/execute-phase-response-language.md +1 -1
  186. package/gsd-core/references/execute-phase-wave-guard.md +6 -2
  187. package/gsd-core/references/gate-prompts.md +1 -1
  188. package/gsd-core/references/git-planning-commit.md +2 -1
  189. package/gsd-core/references/loop-hook-dispatch.md +39 -2
  190. package/gsd-core/references/model-profiles.md +12 -4
  191. package/gsd-core/references/mvp-concepts.md +9 -9
  192. package/gsd-core/references/planner-guidance.md +3 -9
  193. package/gsd-core/references/planner-preconditions.md +1 -1
  194. package/gsd-core/references/planner-reviews.md +1 -1
  195. package/gsd-core/references/planning-config.md +8 -6
  196. package/gsd-core/references/research-documentation-lookup.md +5 -3
  197. package/gsd-core/references/revision-loop.md +1 -1
  198. package/gsd-core/references/specless-probe-fallback.md +8 -7
  199. package/gsd-core/references/universal-anti-patterns.md +3 -3
  200. package/gsd-core/references/verifier-phase-gates.md +192 -0
  201. package/gsd-core/references/verifier-wiring-patterns.md +100 -0
  202. package/gsd-core/references/verify-mvp-mode.md +1 -1
  203. package/gsd-core/references/workstream-flag.md +22 -6
  204. package/gsd-core/references/worktree-branch-check.md +2 -2
  205. package/gsd-core/templates/discussion-log.md +1 -1
  206. package/gsd-core/templates/phase-prompt.md +2 -4
  207. package/gsd-core/templates/state.md +4 -4
  208. package/gsd-core/templates/summary-complex.md +2 -0
  209. package/gsd-core/templates/summary-minimal.md +2 -0
  210. package/gsd-core/templates/summary-standard.md +2 -0
  211. package/gsd-core/templates/summary.md +2 -0
  212. package/gsd-core/templates/verification-report.md +9 -1
  213. package/gsd-core/workflows/ai-integration-phase.md +9 -11
  214. package/gsd-core/workflows/audit-milestone.md +3 -0
  215. package/gsd-core/workflows/autonomous/steps/converge-banner.md +1 -0
  216. package/gsd-core/workflows/autonomous/steps/converge-dispatch-bg.md +11 -0
  217. package/gsd-core/workflows/autonomous/steps/converge-dispatch-inline.md +7 -0
  218. package/gsd-core/workflows/autonomous/steps/converge-fail-fast.md +21 -0
  219. package/gsd-core/workflows/autonomous/steps/converge-loop.md +7 -0
  220. package/gsd-core/workflows/autonomous.md +33 -70
  221. package/gsd-core/workflows/cleanup.md +62 -3
  222. package/gsd-core/workflows/code-review/steps/dispatch-fix.md +39 -0
  223. package/gsd-core/workflows/code-review/steps/structural-pre-pass.md +93 -0
  224. package/gsd-core/workflows/code-review-fix.md +37 -10
  225. package/gsd-core/workflows/code-review.md +74 -166
  226. package/gsd-core/workflows/complete-milestone/steps/git-tag.md +29 -0
  227. package/gsd-core/workflows/complete-milestone.md +160 -95
  228. package/gsd-core/workflows/debug.md +16 -17
  229. package/gsd-core/workflows/diagnose-issues.md +56 -8
  230. package/gsd-core/workflows/discuss-phase/modes/chain.md +2 -1
  231. package/gsd-core/workflows/discuss-phase/modes/default.md +1 -1
  232. package/gsd-core/workflows/discuss-phase-assumptions/steps/auto-advance-dispatch.md +15 -0
  233. package/gsd-core/workflows/discuss-phase-assumptions.md +7 -17
  234. package/gsd-core/workflows/docs-update/steps/dispatch-monorepo-packages.md +51 -0
  235. package/gsd-core/workflows/docs-update.md +8 -51
  236. package/gsd-core/workflows/edit-phase.md +26 -1
  237. package/gsd-core/workflows/eval-review.md +3 -5
  238. package/gsd-core/workflows/execute-phase/steps/executor-isolation-dispatch.md +64 -7
  239. package/gsd-core/workflows/execute-phase/steps/gap-closure-artifacts.md +50 -0
  240. package/gsd-core/workflows/execute-phase/steps/partial-wave.md +31 -0
  241. package/gsd-core/workflows/execute-phase/steps/per-plan-executor-routing.md +77 -0
  242. package/gsd-core/workflows/execute-phase/steps/per-plan-worktree-gate.md +21 -0
  243. package/gsd-core/workflows/execute-phase/steps/regression-gate-run.md +42 -0
  244. package/gsd-core/workflows/execute-phase/steps/regression-gate.md +43 -37
  245. package/gsd-core/workflows/execute-phase.md +103 -187
  246. package/gsd-core/workflows/execute-plan.md +36 -4
  247. package/gsd-core/workflows/explore.md +131 -4
  248. package/gsd-core/workflows/fast.md +10 -2
  249. package/gsd-core/workflows/health.md +73 -4
  250. package/gsd-core/workflows/help/modes/full.md +6 -1
  251. package/gsd-core/workflows/import.md +4 -4
  252. package/gsd-core/workflows/ingest-docs.md +7 -6
  253. package/gsd-core/workflows/mvp-phase.md +6 -3
  254. package/gsd-core/workflows/new-milestone/steps/project-md-milestone-write.md +16 -0
  255. package/gsd-core/workflows/new-milestone/steps/reset-phase-safety.md +19 -0
  256. package/gsd-core/workflows/new-milestone.md +35 -47
  257. package/gsd-core/workflows/new-project/steps/auto-mode-config.md +176 -0
  258. package/gsd-core/workflows/new-project/steps/auto-mode-detection.md +32 -0
  259. package/gsd-core/workflows/new-project/steps/codebase-map-offer.md +18 -0
  260. package/gsd-core/workflows/new-project.md +27 -240
  261. package/gsd-core/workflows/next.md +12 -0
  262. package/gsd-core/workflows/plan-phase/steps/adr-ingest-express-path.md +15 -0
  263. package/gsd-core/workflows/plan-phase/steps/chunked-planning-mode.md +110 -0
  264. package/gsd-core/workflows/plan-phase/steps/prd-express-gate.md +8 -0
  265. package/gsd-core/workflows/plan-phase/steps/research-only-early-exit.md +17 -0
  266. package/gsd-core/workflows/plan-phase/steps/research-only-modifiers.md +16 -0
  267. package/gsd-core/workflows/plan-phase/steps/reviews-prerequisite.md +17 -0
  268. package/gsd-core/workflows/plan-phase/steps/stall-detection-helpers.md +149 -0
  269. package/gsd-core/workflows/plan-phase.md +89 -209
  270. package/gsd-core/workflows/plan-review-convergence.md +50 -2
  271. package/gsd-core/workflows/progress/steps/forensic-audit.md +125 -0
  272. package/gsd-core/workflows/progress/steps/mvp-display.md +18 -0
  273. package/gsd-core/workflows/progress.md +45 -159
  274. package/gsd-core/workflows/quick/steps/discussion-phase.md +124 -0
  275. package/gsd-core/workflows/quick/steps/plan-checker-loop.md +111 -0
  276. package/gsd-core/workflows/quick/steps/quick-verification.md +67 -0
  277. package/gsd-core/workflows/quick/steps/research-phase.md +72 -0
  278. package/gsd-core/workflows/quick/steps/worktree-pre-dispatch-commit.md +37 -0
  279. package/gsd-core/workflows/quick.md +55 -405
  280. package/gsd-core/workflows/resume-project.md +3 -0
  281. package/gsd-core/workflows/review/steps/reviewer-instances-note-1.md +4 -0
  282. package/gsd-core/workflows/review/steps/reviewer-instances-note-2.md +3 -0
  283. package/gsd-core/workflows/review.md +41 -13
  284. package/gsd-core/workflows/section-manifest.json +219 -0
  285. package/gsd-core/workflows/secure-phase.md +1 -1
  286. package/gsd-core/workflows/session-report.md +2 -1
  287. package/gsd-core/workflows/settings.md +66 -2
  288. package/gsd-core/workflows/ship.md +104 -44
  289. package/gsd-core/workflows/sketch.md +1 -1
  290. package/gsd-core/workflows/spec-phase.md +41 -20
  291. package/gsd-core/workflows/spike-wrap-up.md +20 -5
  292. package/gsd-core/workflows/spike.md +50 -16
  293. package/gsd-core/workflows/sync-skills.md +106 -13
  294. package/gsd-core/workflows/transition/steps/workstream-collision-check.md +17 -0
  295. package/gsd-core/workflows/transition.md +53 -31
  296. package/gsd-core/workflows/ui-phase.md +13 -12
  297. package/gsd-core/workflows/ui-review.md +2 -2
  298. package/gsd-core/workflows/update/steps/channel-banner.md +7 -0
  299. package/gsd-core/workflows/update.md +19 -8
  300. package/gsd-core/workflows/validate-phase.md +1 -1
  301. package/gsd-core/workflows/verify-work/steps/automated-ui-verification.md +36 -0
  302. package/gsd-core/workflows/verify-work/steps/mvp-uat-framing.md +21 -0
  303. package/gsd-core/workflows/verify-work.md +17 -65
  304. package/hooks/dist/gsd-agent-isolation-guard.js +517 -0
  305. package/hooks/dist/gsd-check-update-worker.js +64 -12
  306. package/hooks/dist/gsd-check-update.js +19 -1
  307. package/hooks/dist/gsd-cursor-pre-tool.js +0 -3
  308. package/hooks/dist/gsd-cursor-subagent-start.js +607 -26
  309. package/hooks/dist/gsd-cursor-subagent-stop.js +3 -2
  310. package/hooks/dist/gsd-prompt-guard.js +21 -20
  311. package/hooks/dist/gsd-read-injection-scanner.js +45 -24
  312. package/hooks/dist/gsd-statusline.js +90 -6
  313. package/hooks/dist/gsd-update-banner.js +22 -1
  314. package/hooks/dist/gsd-workflow-guard.js +134 -36
  315. package/hooks/dist/gsd-worktree-path-guard.js +2 -1
  316. package/hooks/dist/gsd-write-guard.js +359 -0
  317. package/hooks/dist/lib/git-cmd.js +92 -59
  318. package/hooks/dist/lib/injection-patterns.js +45 -0
  319. package/hooks/dist/lib/isolation-deny-reason.js +39 -0
  320. package/hooks/dist/lib/isolation-sentinel.js +277 -0
  321. package/hooks/dist/managed-hooks-registry.cjs +2 -0
  322. package/hooks/gsd-agent-isolation-guard.js +517 -0
  323. package/hooks/gsd-check-update-worker.js +64 -12
  324. package/hooks/gsd-check-update.js +19 -1
  325. package/hooks/gsd-cursor-pre-tool.js +0 -3
  326. package/hooks/gsd-cursor-subagent-start.js +607 -26
  327. package/hooks/gsd-cursor-subagent-stop.js +3 -2
  328. package/hooks/gsd-prompt-guard.js +21 -20
  329. package/hooks/gsd-read-injection-scanner.js +45 -24
  330. package/hooks/gsd-statusline.js +90 -6
  331. package/hooks/gsd-update-banner.js +22 -1
  332. package/hooks/gsd-workflow-guard.js +134 -36
  333. package/hooks/gsd-worktree-path-guard.js +2 -1
  334. package/hooks/gsd-write-guard.js +359 -0
  335. package/hooks/hooks.json +12 -0
  336. package/hooks/lib/git-cmd.js +92 -59
  337. package/hooks/lib/injection-patterns.js +45 -0
  338. package/hooks/lib/isolation-deny-reason.js +39 -0
  339. package/hooks/lib/isolation-sentinel.js +277 -0
  340. package/hooks/managed-hooks-registry.cjs +2 -0
  341. package/package.json +31 -10
  342. package/pi/gsd.cjs +71 -12
  343. package/scripts/baselines/planning-prompt-drift-baseline.json +4 -0
  344. package/scripts/baselines/planning-snapshot-bypass-baseline.json +12 -0
  345. package/scripts/baselines/unreachable-guard-drift-baseline.json +4 -0
  346. package/scripts/build-hooks.js +9 -0
  347. package/scripts/changeset/lint.cjs +68 -6
  348. package/scripts/changeset/serialize.cjs +5 -1
  349. package/scripts/check-alias-drift.cjs +7 -43
  350. package/scripts/check-contract-drift.cjs +297 -0
  351. package/scripts/ci-test-scope.cjs +19 -2
  352. package/scripts/command-contract-helpers.cjs +903 -1
  353. package/scripts/gen-adr-index.cjs +728 -38
  354. package/scripts/gen-capability-matrix.cjs +1 -1
  355. package/scripts/gen-capability-registry.cjs +3 -15
  356. package/scripts/gen-context-index.cjs +439 -0
  357. package/scripts/gen-health-docs.cjs +390 -0
  358. package/scripts/gen-inventory-manifest.cjs +150 -4
  359. package/scripts/gen-loop-host-contract.cjs +4 -24
  360. package/scripts/gen-prompt-budget-parity-corpus.cjs +645 -0
  361. package/scripts/gen-registry.cjs +3 -14
  362. package/scripts/gen-section-manifest.cjs +638 -0
  363. package/scripts/generate-package-identity.cjs +4 -2
  364. package/scripts/lib/alias-drift-families.cjs +46 -0
  365. package/scripts/lib/drift-scan.cjs +278 -0
  366. package/scripts/lint-allow-test-rule-refs.allowlist.json +15 -54
  367. package/scripts/lint-allow-test-rule-refs.effective-ceiling.json +4 -0
  368. package/scripts/lint-allow-test-rule-refs.unverified-ceiling.json +3 -0
  369. package/scripts/lint-canary-version-leak.cjs +73 -0
  370. package/scripts/lint-command-contract.cjs +96 -13
  371. package/scripts/lint-compiled-artifact-sync.cjs +6 -1
  372. package/scripts/lint-completion-predicate-drift.cjs +933 -0
  373. package/scripts/lint-completion-ratio-drift.cjs +214 -0
  374. package/scripts/lint-default-flip-documentation.cjs +193 -0
  375. package/scripts/lint-docs-command-form.cjs +195 -0
  376. package/scripts/lint-docs-required.cjs +9 -1
  377. package/scripts/lint-emitted-drift-ack.cjs +215 -20
  378. package/scripts/lint-eslint-glob-coverage.allowlist.json +34 -0
  379. package/scripts/lint-eslint-glob-coverage.cjs +340 -0
  380. package/scripts/lint-example-parser-parity.cjs +395 -0
  381. package/scripts/lint-frontmatter-scalar-broad-grep.cjs +237 -0
  382. package/scripts/lint-health-diagnostic-rule-table.cjs +404 -0
  383. package/scripts/lint-hooks-runtime-build-seam.cjs +262 -0
  384. package/scripts/lint-milestone-window-drift.cjs +468 -0
  385. package/scripts/lint-phase-enumeration-drift.cjs +479 -0
  386. package/scripts/lint-plan-count-drift.cjs +318 -0
  387. package/scripts/lint-planning-artifact-writer-drift.cjs +398 -0
  388. package/scripts/lint-planning-prompt-drift.cjs +434 -0
  389. package/scripts/lint-planning-snapshot-bypass-drift.cjs +544 -0
  390. package/scripts/lint-regression-test-names.cjs +15 -13
  391. package/scripts/lint-removed-but-needed.cjs +320 -0
  392. package/scripts/lint-state-field-drift.cjs +805 -0
  393. package/scripts/lint-state-write-path-drift.cjs +1045 -0
  394. package/scripts/lint-test-file-count.allowlist.json +40 -3
  395. package/scripts/lint-unreachable-guard-drift.cjs +843 -0
  396. package/scripts/lint-vendored-deps.cjs +124 -0
  397. package/scripts/mutation-matrix.cjs +13 -0
  398. package/scripts/pr-changed-files.cjs +63 -0
  399. package/scripts/pr-template-policy.cjs +14 -4
  400. package/scripts/prompt-injection-scan.sh +52 -6
  401. package/scripts/require-issue-link-policy.cjs +192 -0
  402. package/scripts/state-write-path-drift-baseline.json +19 -0
  403. package/scripts/sync-runtime-launcher.cjs +2 -4
  404. package/skills/gsd-autonomous/SKILL.md +0 -1
  405. package/skills/gsd-code-review/SKILL.md +1 -1
  406. package/skills/gsd-execute-phase/SKILL.md +1 -2
  407. package/skills/gsd-map-codebase/SKILL.md +1 -1
  408. package/skills/gsd-mempalace-capture/SKILL.md +2 -2
  409. package/skills/gsd-mempalace-recall/SKILL.md +1 -1
  410. package/skills/gsd-new-milestone/SKILL.md +2 -2
  411. package/skills/gsd-next/SKILL.md +0 -1
  412. package/skills/gsd-plan-phase/SKILL.md +1 -2
  413. package/skills/gsd-progress/SKILL.md +0 -1
  414. package/skills/gsd-quick/SKILL.md +1 -1
  415. package/skills/gsd-review-backlog/SKILL.md +2 -1
  416. package/skills/gsd-stats/SKILL.md +0 -1
  417. package/skills/gsd-verify-work/SKILL.md +1 -1
  418. package/vscode/package.json +1 -1
  419. package/gsd-core/workflows/discovery-phase.md +0 -298
  420. package/gsd-core/workflows/plan-milestone-gaps.md +0 -281
  421. package/gsd-core/workflows/verify-phase.md +0 -577
  422. package/scripts/affected-tests-lib.cjs +0 -554
  423. package/scripts/gen-emitted-baseline.cjs +0 -145
  424. package/scripts/lint-allow-test-rule-refs.cjs +0 -162
  425. package/scripts/run-affected-tests.cjs +0 -7
  426. package/scripts/run-tests.cjs +0 -1050
@@ -0,0 +1,479 @@
1
+ #!/usr/bin/env node
2
+ 'use strict';
3
+
4
+ /**
5
+ * Anti-divergence drift guard for the PHASE-ENUMERATION seam (epic #3180,
6
+ * issue #3185, ADR-3180 Decision 1 row "Phase enumeration").
7
+ *
8
+ * `src/phase-locator.cts` is the SINGLE canonical owner of "which phase
9
+ * directories belong to the current milestone" — `listMilestonePhaseDirs`.
10
+ * `src/phase-id.cts` is the SINGLE canonical owner of "is this phase id a
11
+ * reserved sentinel (Phase 0 / Phase 999.x)" — `isSentinelPhaseId` /
12
+ * `SENTINEL_RANGES`. Before these existed the derivation had four
13
+ * independent implementations, and the sentinel rule had five copies across
14
+ * three different regexes that disagreed about Phase 0 (see
15
+ * `listMilestonePhaseDirs`'s own doc comment). Every other module that
16
+ * hand-rolls a `readdirSync` over the phases directory, or hand-rolls a
17
+ * `999`-shaped sentinel test, is a re-derivation that can silently drift
18
+ * from one of these two owners — the same generative-fix-divergence class
19
+ * `lint-plan-count-drift.cjs` and `lint-milestone-window-drift.cjs` exist to
20
+ * remove, now applied to the phase-enumeration seam.
21
+ *
22
+ * Per ADR-3180 Decision 4(a) this guard discovers call sites by SCANNING THE
23
+ * WHOLE `src/` TREE, not by consulting an allowlist of known files — an
24
+ * allowlist only measures re-derivations in files someone remembered to
25
+ * list. Exemptions below are FUNCTION-SCOPED with a written reason, never a
26
+ * bare file allowlist, mirroring `lint-plan-count-drift.cjs`'s and
27
+ * `lint-milestone-window-drift.cjs`'s precedent.
28
+ *
29
+ * TWO INDEPENDENT DETECTORS. A line matching EITHER is a violation:
30
+ *
31
+ * DETECTOR 1 (enumeration): a single source line carrying BOTH
32
+ * (a) `readdirSync`, AND
33
+ * (b) a phases-directory token — the identifier `phasesDir`, or a
34
+ * quoted/backticked `'phases'` string.
35
+ * This is the shape every consumer used before routing through the owner.
36
+ *
37
+ * DETECTOR 2 (sentinel): a single source line carrying a sentinel-range
38
+ * literal outside the owner —
39
+ * - a bare `999` inside a regex literal or a quoted/backticked string
40
+ * (e.g. `/^999\b/`, `/^999(?:\.|$)/`, `'999'`), OR
41
+ * - a numeric comparison against 999 (`=== 999`, `== 999`, `!== 999`),
42
+ * or a bare reference to `SENTINEL_RANGES` outside its owner.
43
+ * Deliberately NARROW, mirroring the sibling guards' token discipline: the
44
+ * `999` must be a STANDALONE digit run (no digit immediately before or
45
+ * after it, inside the literal or right after the comparison operator), so
46
+ * unrelated arithmetic (`total + 1999`, `=== 9990`) never fires — only a
47
+ * line that actually spells the reserved sentinel value fires.
48
+ *
49
+ * Owner files (exempt by construction — each not only DEFINES its half of
50
+ * the grammar but composes it at internal call sites that are the canonical
51
+ * implementation, not copies of it):
52
+ * - `src/phase-locator.cts` — defines `listMilestonePhaseDirs`, the
53
+ * enumeration owner, and legitimately calls `readdirSync` on the phases
54
+ * dir inside it.
55
+ * - `src/phase-id.cts` — defines `isSentinelPhaseId` and
56
+ * `SENTINEL_RANGES`, the sentinel owner.
57
+ *
58
+ * FUNCTION-SCOPED EXEMPTIONS (per ADR-3180 Decision 4(a) — a written reason,
59
+ * never a bare file allowlist, so an unrelated re-derivation added anywhere
60
+ * ELSE in these same files is still caught). Generalizing #3183's rule ("a
61
+ * diagnostic about file NAMING wants the physical set; only a question about
62
+ * outstanding WORK wants the live set"): a LOOKUP, DIAGNOSTIC or ARCHIVAL
63
+ * pass wants the physical set; only "which phases belong to this milestone"
64
+ * wants the scoped set.
65
+ * - `src/roadmap.cts` `cmdRoadmapAnalyze`: builds `_phaseDirNames` as a
66
+ * heading->directory LOOKUP INDEX, not a milestone enumeration. It must
67
+ * see the PHYSICAL set so a heading already scoped by
68
+ * `extractCurrentMilestoneScoped` can find its directory; filtering it
69
+ * through the owner would scope the same set twice.
70
+ * - `src/verify.cts` `cmdValidateHealth`: a project-wide HEALTH-CHECK sweep
71
+ * (config drift, phase-directory naming, duplicate-directory collisions,
72
+ * unsummarized-plan detection) — same "sweep everything, report gaps"
73
+ * shape as `collectDiskPhases` and the `audit.cts` scanners; it must see
74
+ * every phase directory regardless of milestone window to catch a
75
+ * naming/duplicate defect wherever it lives.
76
+ * - `src/verify.cts` `cmdVerifySchemaDrift`: resolves ONE caller-supplied
77
+ * `phase` argument to its directory (falling back to an exact-name
78
+ * match) — a single-phase LOOKUP, not a current-milestone enumeration.
79
+ * - `src/init.cts` `detectHasPriorPhases`: answers "has this project EVER
80
+ * completed a phase", explicitly excluding the current one. A history
81
+ * probe across all milestones, not a current-milestone enumeration.
82
+ * - `src/init.cts` `detectUiPhaseActive`: its `readdirSync` targets a
83
+ * SINGLE already-resolved phase directory's own FILES
84
+ * (`phases/<dirName>`) to check for a `*-UI-SPEC.md` file — not the
85
+ * phases directory itself. It never enumerates which phases exist at
86
+ * all, so it is not this derivation, only shaped like it textually.
87
+ * - `src/init.cts` `cmdInitMilestoneOp`: `diskPhaseDirs` is a heading->
88
+ * directory LOOKUP INDEX (same role as `cmdRoadmapAnalyze`'s
89
+ * `_phaseDirNames` below) — the ROADMAP heading scan just above it
90
+ * already scopes `roadmapPhaseNumbers` to the current milestone, so this
91
+ * map must see the PHYSICAL set to resolve each heading's phase number
92
+ * to its actual directory name; scoping it again would look up inside
93
+ * an already-scoped set for no benefit. Its sibling readdirSync (the
94
+ * no-ROADMAP-headings-found fallback, where there is no heading scope
95
+ * to look inside) is a real current-milestone enumeration and is routed
96
+ * through the owner, not exempted.
97
+ * - `src/milestone.cts` `archivePhaseDirectories`: archival MOVES the
98
+ * physical set. Scoping it would silently leave out-of-window
99
+ * directories behind in the live tree.
100
+ * - `src/milestone.cts` `cmdMilestoneComplete`: its one remaining
101
+ * unrouted readdirSync (`phaseDirEntries`, the unstarted-phase guard)
102
+ * is a token-match LOOKUP against ROADMAP headings already scoped by
103
+ * `sliceMilestoneWindow`/`extractCurrentMilestone` above it — same
104
+ * "physical set feeds an already-scoped lookup" shape as
105
+ * `cmdRoadmapAnalyze`'s `_phaseDirNames`. Its three OTHER former
106
+ * readdirSync call sites (the stats aggregation, the dry-run archive
107
+ * preview, and the real archive-move loop) all genuinely asked "which
108
+ * phases belong to the current milestone" and are routed through the
109
+ * owner with the resolved `version` as `versionOverride`.
110
+ * - `src/milestone.cts` `cmdPhasesClear`: a destructive CLEAR that must
111
+ * remove every live phase directory except sentinels, regardless of
112
+ * milestone window — `new-milestone` runs this to wipe the ENTIRE
113
+ * phases tree before starting fresh, not just the outgoing milestone's
114
+ * slice. Scoping it to one milestone's window would silently leave
115
+ * out-of-window directories behind instead of clearing/archiving them.
116
+ * - `src/phase.cts` `cmdPhasesList`: its `--phase <n>` lookup and
117
+ * `--include-archived` merge are phase LOCATION and archive
118
+ * enumeration, not current-milestone enumeration; both legitimately
119
+ * read the physical set. Its ENUMERATION path routes through the owner.
120
+ * - `src/roadmap-parser.cts` `getMilestonePhaseFilter` and its #3262-extracted
121
+ * set-building owner `scanMilestonePhaseIds` (the same two heading/
122
+ * #3577 `collectTablePhaseRows` — the table-scan sibling feeding the same
123
+ * membership set; its local 999-only exclusion mirrors the owner's
124
+ * deliberate NOT-isSentinelPhaseId choice (a leading 0 is a real decimal
125
+ * phase, #2554), so it cannot route through the sentinel owner either).
126
+ * bullet scans, lifted verbatim so the `roadmap milestone-scope` probe
127
+ * reads the identical derivation): both deliberately use the local
128
+ * `999`-only literal, NOT `isSentinelPhaseId`. That canonical predicate
129
+ * additionally treats a leading `0` as sentinel milestone 0 (via its
130
+ * `/^0*(\d+)/` backtrack), which would swallow #2554's decimal phase ids
131
+ * ("00.1" is a real phase, not milestone 0). This scan asks a narrower
132
+ * question — "which phase ids does this milestone's window declare" —
133
+ * where only the 999 icebox range is excluded.
134
+ * - `src/state.cts` `cmdStateValidate` ("Gate 1: Validate STATE.md against
135
+ * filesystem"): resolves ONE directory — the disk match for STATE.md's
136
+ * own `Current Phase` field — by prefix, a single-phase LOOKUP, not an
137
+ * enumeration of the current milestone's phase set.
138
+ * - `src/state.cts` `cmdStateSync` ("Gate 2: Sync STATE.md from filesystem
139
+ * ground truth"): a ground-truth RECONCILIATION pass, same family as
140
+ * `collectDiskPhases` below — it deliberately scans every phase
141
+ * directory on disk (minus #1514 retired-phase exclusion) so STATE.md's
142
+ * rewritten counters reflect the true disk state, not a re-derivation of
143
+ * "which phases belong to the current milestone" the way its sibling
144
+ * `buildStateFrontmatter` computes (that one IS routed through the
145
+ * owner, scoped to the stored milestone, because it exists specifically
146
+ * to answer the milestone-scoped question at STATE.md construction
147
+ * time).
148
+ * - `src/state.cts` `cmdStateRebuild`: its nested `phaseInventoryProvider`
149
+ * deliberately does NOT route through `listMilestonePhaseDirs`. `state
150
+ * rebuild` is a RECONCILIATION pass against ground truth — it must see
151
+ * every phase directory on disk so an orphan STATE.md row for a phase
152
+ * that no longer exists (or sits outside the current milestone window) is
153
+ * dropped. Scoping this enumeration would make the rebuild silently
154
+ * preserve stale rows instead of dropping them, and a non-`readdirSync`-
155
+ * shaped owner call also cannot propagate the original fault message the
156
+ * #3057 B1 contract requires to surface verbatim.
157
+ * - `src/phase.cts` `cmdPhaseNextDecimal`: computes the next free decimal
158
+ * sub-phase id (e.g. `2.3`) by scanning EVERY on-disk directory and the
159
+ * WHOLE ROADMAP (not milestone-scoped) for existing `2.N` ids — an id
160
+ * collision it must avoid can come from any milestone, so it needs the
161
+ * physical set, matching the CREATE-adjacent exemption category.
162
+ * - `src/phase.cts` `cmdPhasePlanIndex`: resolves ONE caller-supplied
163
+ * `phase` id to its directory — a single-phase LOCATION lookup, not an
164
+ * enumeration of the current milestone's phase set.
165
+ * - `src/phase.cts` `cmdPhaseInsert`: the same next-free-decimal-id scan as
166
+ * `cmdPhaseNextDecimal` (id collisions can come from any milestone),
167
+ * immediately followed by creating the new phase directory — a CREATE
168
+ * operation, physical set by definition.
169
+ * - `src/phase.cts` `renameDecimalPhases`, `renameIntegerPhases`: RENAME
170
+ * mutations. Each `readdirSync` targets a SINGLE just-renamed phase
171
+ * directory's own FILES (`phasesDir/newDirName`) to rename the files
172
+ * inside it to match — not an enumeration of the phases directory at
173
+ * all; only shaped like one because `phasesDir` is a substring of the
174
+ * joined path.
175
+ * - `src/audit.cts` `listAuditPhaseTargets` (#3458): the shared active-root
176
+ * enumeration for the pre-milestone-close audit gate (`gsd-tools.cjs
177
+ * audit-open`, called by `/gsd:complete-milestone`'s pre-close gate).
178
+ * `scanUatGaps`, `scanVerificationGaps`, `scanContextQuestions`, and
179
+ * `scanDeferredItems` used to each hand-roll this same readdirSync
180
+ * independently (four copies of one re-derivation — the very drift class
181
+ * this guard exists to catch); #3458 consolidated all four into this one
182
+ * function, so the exemption moved with the call site instead of
183
+ * multiplying. It deliberately SWEEPS EVERY phase directory on disk to
184
+ * report open UAT/VERIFICATION/CONTEXT/deferred-item gaps — the audit's
185
+ * whole purpose is catching stragglers before a milestone closes, so
186
+ * scoping it to the current milestone's window would hide exactly the
187
+ * drift (e.g. a still-open item in a phase that somehow fell outside the
188
+ * window) it exists to surface.
189
+ * - `src/roadmap-upgrade.cts` `computeMigrationPlan`: a legacy-id-to-
190
+ * milestone-prefixed-id MIGRATION. It must see and rename EVERY existing
191
+ * phase directory across every milestone in one pass (a legacy phase
192
+ * number can legitimately collide across milestones — that ambiguity is
193
+ * exactly what the migration resolves) — the physical set by definition.
194
+ * - `src/smart-entry.cts` `detectVerifyFailed`: resolves ONE phase — the
195
+ * current phase from STATE.md, falling back to the highest-numbered
196
+ * directory when STATE.md has none — to check its own verify/UAT
197
+ * artifacts. A single-phase LOOKUP (with an explicit fallback rule of
198
+ * its own), not a current-milestone enumeration.
199
+ * - `src/commands.cts` `cmdHistoryDigest`: explicitly builds `allPhaseDirs`
200
+ * as archived-milestone dirs (via `getArchivedPhaseDirs`) PLUS every
201
+ * live phase directory, to produce a project-wide historical digest
202
+ * spanning every milestone ever shipped — the union is a strict
203
+ * superset of any one milestone's window by design; scoping the live
204
+ * half would silently drop history the digest exists to preserve.
205
+ * - `src/planning-snapshot.cts` `buildAllPhaseDirNamesField` (Phase 11,
206
+ * #3309): the un-windowed twin of `phaseDirs`/`listMilestonePhaseDirs` —
207
+ * every directory actually present under the active `phases/` root,
208
+ * UNFILTERED by current-milestone-window membership. Backs the migrated
209
+ * `cmdValidateHealth`'s W007 rule ("an on-disk phase directory has no
210
+ * matching ROADMAP entry"): sourcing that check from the WINDOWED owner
211
+ * would make it structurally unable to fire on the exact orphan
212
+ * directory it exists to find (an orphan-by-definition can never be a
213
+ * member of a set defined as "directories the roadmap already
214
+ * declares") — see that field's own doc comment on `PlanningSnapshot`
215
+ * for the full, empirically-verified rationale. Same "must see the
216
+ * physical set by definition" shape as `collectDiskPhases`/
217
+ * `cmdValidateHealth` above, generalized from a raw `readdirSync` call
218
+ * site to a dedicated snapshot-builder function.
219
+ *
220
+ * The tree-walk / root-confinement / regex-literal-tokenizer / sanitizer
221
+ * machinery is SHARED with the sibling drift guards via
222
+ * `scripts/lib/drift-scan.cjs` (ADR-3180 Decision 4) — see that module for
223
+ * the `isInsideRoot` case-sensitivity note, the `walk` symlink-confinement
224
+ * rationale, and the `readRegexLiteralAt` ReDoS-avoidance rationale.
225
+ * `readStringLiteralAt` below is the same style, written locally for
226
+ * quoted/backticked strings, mirroring `lint-milestone-window-drift.cjs`'s
227
+ * own local copy (not shared — each guard's literal-bearing shape differs).
228
+ *
229
+ * KNOWN, ACCEPTED limits of a per-line textual scan (same tradeoff the
230
+ * sibling drift guards document): a re-derivation whose detector tokens are
231
+ * split across two DIFFERENT lines with no single line carrying both is not
232
+ * caught by this narrow shape. That is left to code review and the design's
233
+ * identity tests, not this regex.
234
+ */
235
+
236
+ const path = require('node:path');
237
+ const driftScan = require('./lib/drift-scan.cjs');
238
+ const { readRegexLiteralAt, MAX_REGEX_LITERAL_LEN, sanitizeForReport, scanTree } = driftScan;
239
+
240
+ // (1a) The enumeration primitive itself.
241
+ const READDIR_SYNC_RE = /readdirSync/;
242
+
243
+ // (1b1) The phases-directory identifier every routed call site used to bind
244
+ // its `readdirSync` target to.
245
+ const PHASES_DIR_ID_RE = /\bphasesDir\b/;
246
+
247
+ // (1b2) A quoted/backticked `'phases'` string — the other shape a phases-dir
248
+ // path segment takes at a call site that builds the path inline instead of
249
+ // through a `phasesDir` local.
250
+ const PHASES_STRING_RE = /['"`]phases['"`]/;
251
+
252
+ // (2b) A numeric comparison against the sentinel value, or a bare reference
253
+ // to the owner's exported range constant used outside the owner. The digit
254
+ // run is anchored on both sides (`\b`, and no digit can precede it inside
255
+ // the `\s*` gap immediately after the operator) so `=== 9990` / `=== 19999`
256
+ // never fire — only the standalone value `999` does.
257
+ const SENTINEL_COMPARISON_RE = /(?:===|==|!==)\s*999\b|\bSENTINEL_RANGES\b/;
258
+
259
+ // A standalone `999` inside an already-located literal's text: no digit
260
+ // immediately before or after, so `1999`/`9990`/`19999` inside a string or
261
+ // regex literal never fire — only the literal spelling of the reserved
262
+ // sentinel value does.
263
+ const STANDALONE_999_RE = /(?<!\d)999(?!\d)/;
264
+
265
+ // Authored TypeScript source only (the generated bin/lib/*.cjs mirror it).
266
+ const SCAN_DIRS = ['src'];
267
+ const SCAN_EXT = new Set(['.cts', '.ts', '.mts']);
268
+
269
+ // The two canonical owners; each defines and internally composes its half
270
+ // of the grammar and is exempt by construction (see header comment).
271
+ const OWNER_FILES = new Set([
272
+ path.join('src', 'phase-locator.cts'),
273
+ path.join('src', 'phase-id.cts'),
274
+ ]);
275
+
276
+ // Per ADR-3180 Decision 4(a): NOT a bare file allowlist — each entry below
277
+ // is scoped to the SPECIFIC function asking a documented, DIFFERENT
278
+ // question, so an unrelated re-derivation added anywhere else in these same
279
+ // files is still caught. Mirrors `lint-plan-count-drift.cjs`'s and
280
+ // `lint-milestone-window-drift.cjs`'s FUNCTION_SCOPED_EXEMPTIONS mechanism.
281
+ // See the header comment for the full written reason behind each entry.
282
+ const FUNCTION_SCOPED_EXEMPTIONS = new Map([
283
+ [path.join('src', 'roadmap.cts'), new Set(['cmdRoadmapAnalyze'])],
284
+ [path.join('src', 'verify.cts'), new Set(['cmdValidateHealth', 'cmdVerifySchemaDrift'])],
285
+ [path.join('src', 'init.cts'), new Set(['detectHasPriorPhases', 'detectUiPhaseActive', 'cmdInitMilestoneOp'])],
286
+ [path.join('src', 'milestone.cts'), new Set(['archivePhaseDirectories', 'cmdMilestoneComplete', 'cmdPhasesClear'])],
287
+ [path.join('src', 'phase.cts'), new Set(['cmdPhasesList', 'cmdPhaseNextDecimal', 'cmdPhasePlanIndex', 'cmdPhaseInsert', 'renameDecimalPhases', 'renameIntegerPhases'])],
288
+ [path.join('src', 'audit.cts'), new Set(['listAuditPhaseTargets'])],
289
+ [path.join('src', 'commands.cts'), new Set(['cmdHistoryDigest'])],
290
+ [path.join('src', 'state.cts'), new Set(['cmdStateValidate', 'cmdStateSync', 'cmdStateRebuild'])],
291
+ [path.join('src', 'roadmap-upgrade.cts'), new Set(['computeMigrationPlan'])],
292
+ [path.join('src', 'smart-entry.cts'), new Set(['detectVerifyFailed'])],
293
+ [path.join('src', 'roadmap-parser.cts'), new Set(['getMilestonePhaseFilter', 'scanMilestonePhaseIds', 'collectTablePhaseRows'])],
294
+ [path.join('src', 'planning-snapshot.cts'), new Set(['buildAllPhaseDirNamesField'])],
295
+ ]);
296
+
297
+ // Optional `export ` modifier, mirroring the sibling guards' function
298
+ // tracker — only a column-0 top-level `function` declaration updates the
299
+ // current-function tracker; a nested/arrow function does not reset it,
300
+ // matching every FUNCTION_SCOPED_EXEMPTIONS entry above (all top-level
301
+ // `function` declarations).
302
+ const TOP_LEVEL_FUNCTION_RE = /^(?:export\s+)?function\s+([A-Za-z0-9_]+)\s*\(/;
303
+
304
+ /**
305
+ * Read the quoted or backtick-delimited string/template literal starting at
306
+ * `line[start]` (which must be `'`, `"`, or `` ` ``). Returns `{ text, end }`
307
+ * — `text` includes both delimiters, `end` is the index one past the literal
308
+ * — or null if no matching close quote is found within MAX_REGEX_LITERAL_LEN
309
+ * characters. Same single left-to-right, no-backtracking, escape-aware style
310
+ * as the shared `readRegexLiteralAt` (`\x` escapes consume both characters,
311
+ * so an escaped quote never terminates the literal early) — written locally,
312
+ * mirroring `lint-milestone-window-drift.cjs`'s own copy (not shared — each
313
+ * guard's literal-bearing shape differs).
314
+ */
315
+ function readStringLiteralAt(line, start) {
316
+ const quote = line[start];
317
+ if (quote !== "'" && quote !== '"' && quote !== '`') return null;
318
+ const limit = Math.min(line.length, start + MAX_REGEX_LITERAL_LEN);
319
+ for (let i = start + 1; i < limit; i++) {
320
+ const ch = line[i];
321
+ if (ch === '\\') {
322
+ i++; // escape consumes the next character, whatever it is
323
+ continue;
324
+ }
325
+ if (ch === '\r' || ch === '\n') return null; // a literal cannot span lines in this per-line scan
326
+ if (ch === quote) return { text: line.slice(start, i + 1), end: i + 1 };
327
+ }
328
+ return null;
329
+ }
330
+
331
+ /**
332
+ * True when `line` contains a regex-literal or quoted/backtick-string
333
+ * literal whose text carries a STANDALONE `999` (see STANDALONE_999_RE).
334
+ */
335
+ function hasSentinelLiteral(line) {
336
+ for (let i = 0; i < line.length; i++) {
337
+ const ch = line[i];
338
+ let literal = null;
339
+ if (ch === '/') literal = readRegexLiteralAt(line, i);
340
+ else if (ch === "'" || ch === '"' || ch === '`') literal = readStringLiteralAt(line, i);
341
+ if (!literal) continue;
342
+ if (STANDALONE_999_RE.test(literal.text)) return true;
343
+ i = literal.end - 1; // resume scanning just past this literal
344
+ }
345
+ return false;
346
+ }
347
+
348
+ /**
349
+ * The first literal (regex OR quoted/backtick string) on `line` whose text
350
+ * contains a STANDALONE `999` or the exact `'phases'` token — the "smoking
351
+ * gun" fragment worth reporting, mirroring `extractFragment`'s role in
352
+ * `lint-milestone-window-drift.cjs`. Falls back to a bounded, trimmed slice
353
+ * of the raw line when neither is inside a located literal (the
354
+ * `phasesDir` identifier / `SENTINEL_RANGES` / bare numeric-comparison
355
+ * shapes never are).
356
+ */
357
+ function extractFragment(line) {
358
+ for (let i = 0; i < line.length; i++) {
359
+ const ch = line[i];
360
+ let literal = null;
361
+ if (ch === '/') literal = readRegexLiteralAt(line, i);
362
+ else if (ch === "'" || ch === '"' || ch === '`') literal = readStringLiteralAt(line, i);
363
+ if (!literal) continue;
364
+ if (STANDALONE_999_RE.test(literal.text) || /^['"`]phases['"`]$/.test(literal.text)) return literal.text;
365
+ i = literal.end - 1; // resume scanning just past this literal
366
+ }
367
+ return line.trim().slice(0, MAX_REGEX_LITERAL_LEN);
368
+ }
369
+
370
+ /**
371
+ * Strip comment text from a line before detection. A guard that fires on a
372
+ * COMMENT — including a comment documenting that the code below uses the
373
+ * canonical owner — reports prose as drift and trains readers to add
374
+ * exemptions for documentation. Handles the three shapes that appear in this
375
+ * codebase: a whole-line block-comment continuation (`*` or `/*` leading), a
376
+ * `//` line comment, and a trailing `//` after code.
377
+ *
378
+ * Deliberately simple and conservative: it does not attempt full block-comment
379
+ * state tracking across lines (this is a per-line scan, same tradeoff the
380
+ * sibling guards document). A `//` inside a string literal would be stripped
381
+ * early — accepted, because the effect is to UNDER-report on a pathological
382
+ * line, never to over-report prose as drift.
383
+ */
384
+ function stripComments(line) {
385
+ const trimmed = line.trim();
386
+ // Whole-line block comment or JSDoc continuation.
387
+ if (trimmed.startsWith('*') || trimmed.startsWith('/*') || trimmed.startsWith('//')) return '';
388
+ // Trailing line comment after code.
389
+ const idx = line.indexOf('//');
390
+ return idx === -1 ? line : line.slice(0, idx);
391
+ }
392
+
393
+ /**
394
+ * Pure: find every unsanctioned phase-enumeration re-derivation in `text`.
395
+ * `relPath` is the repo-relative path, used both to report file:line and to
396
+ * apply the narrow, function-scoped exemptions above.
397
+ * Returns [{ line, found }].
398
+ */
399
+ function findPhaseEnumerationDrift(text, relPath) {
400
+ const out = [];
401
+ const lines = text.split('\n');
402
+ const exemptFunctions = FUNCTION_SCOPED_EXEMPTIONS.get(relPath) || null;
403
+ let currentFunction = null;
404
+ for (let i = 0; i < lines.length; i++) {
405
+ const line = lines[i];
406
+ const fnMatch = TOP_LEVEL_FUNCTION_RE.exec(line);
407
+ if (fnMatch) currentFunction = fnMatch[1];
408
+
409
+ const code = stripComments(line);
410
+ if (!code.trim()) continue;
411
+
412
+ const isEnumerationDrift = READDIR_SYNC_RE.test(code) && (PHASES_DIR_ID_RE.test(code) || PHASES_STRING_RE.test(code));
413
+ const isSentinelDrift = SENTINEL_COMPARISON_RE.test(code) || hasSentinelLiteral(code);
414
+ if (!isEnumerationDrift && !isSentinelDrift) continue;
415
+
416
+ if (exemptFunctions && exemptFunctions.has(currentFunction)) continue;
417
+
418
+ out.push({ line: i + 1, found: extractFragment(line) });
419
+ }
420
+ return out;
421
+ }
422
+
423
+ /**
424
+ * Scan the authored source tree and return every unsanctioned re-derivation,
425
+ * each annotated with the repo-relative file path.
426
+ */
427
+ function scanRepo(root) {
428
+ return scanTree({
429
+ root,
430
+ scanDirs: SCAN_DIRS,
431
+ scanExt: SCAN_EXT,
432
+ onFile(rel, text) {
433
+ // `rel` is already the REAL (canonical) path (scanTree resolves
434
+ // symlinks before calling onFile), so this comparison — and
435
+ // FUNCTION_SCOPED_EXEMPTIONS above, also keyed on `rel` — match
436
+ // consistently regardless of which symlink reached the file.
437
+ if (OWNER_FILES.has(rel)) return [];
438
+ return findPhaseEnumerationDrift(text, rel).map((d) => ({ file: rel, ...d }));
439
+ },
440
+ });
441
+ }
442
+
443
+ function main() {
444
+ const root = path.join(__dirname, '..');
445
+ const violations = scanRepo(root);
446
+ if (violations.length === 0) {
447
+ process.stdout.write('ok phase-enumeration-drift: no unsanctioned phase-enumeration re-derivations outside phase-locator.cts / phase-id.cts\n');
448
+ return;
449
+ }
450
+ process.stderr.write('phase-enumeration-drift: independent re-derivation(s) of phase enumeration found.\n');
451
+ process.stderr.write('Use src/phase-locator.cjs `listMilestonePhaseDirs` instead of re-deriving a phases-directory\n');
452
+ process.stderr.write('readdirSync, and src/phase-id.cjs `isSentinelPhaseId` instead of re-deriving a `999` sentinel test:\n');
453
+ for (const d of violations) {
454
+ // `d.file` is exactly as attacker-controlled as `d.found`: a repo can
455
+ // legally track a filename containing control bytes / bidi overrides,
456
+ // and it is a fork-PR-authored value reaching a CI log the same way the
457
+ // matched literal does — sanitize it at the same reporting boundary.
458
+ process.stderr.write(` ${sanitizeForReport(d.file)}:${d.line} ${sanitizeForReport(d.found)}\n`);
459
+ }
460
+ process.exitCode = 1;
461
+ }
462
+
463
+ if (require.main === module) main();
464
+
465
+ module.exports = {
466
+ findPhaseEnumerationDrift,
467
+ scanRepo,
468
+ READDIR_SYNC_RE,
469
+ PHASES_DIR_ID_RE,
470
+ PHASES_STRING_RE,
471
+ SENTINEL_COMPARISON_RE,
472
+ STANDALONE_999_RE,
473
+ OWNER_FILES,
474
+ FUNCTION_SCOPED_EXEMPTIONS,
475
+ readStringLiteralAt,
476
+ hasSentinelLiteral,
477
+ extractFragment,
478
+ stripComments,
479
+ };