@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,843 @@
1
+ #!/usr/bin/env node
2
+ 'use strict';
3
+
4
+ /**
5
+ * Prompt-layer drift guard for #3409 — shell guards that cannot observe
6
+ * their own failure arm.
7
+ *
8
+ * Design: .gsd/phase/feat-3409-unreachable-shell-guard-lint/40-design.md
9
+ * Test matrix: .gsd/phase/feat-3409-unreachable-shell-guard-lint/50-test-matrix.md
10
+ *
11
+ * `gsd-tools.cjs`'s `--pick <field>` extractor coerces a missing/absent
12
+ * field to the empty string and exits **0** (probe-confirmed in
13
+ * 40-design.md). So in `$(gsd_run query V --pick F 2>/dev/null || echo D)`
14
+ * the `|| echo D` arm can fire only on a typo in the verb name — never on
15
+ * the field absence it was written to handle. Three shipped shell guards
16
+ * silently relied on that unreachable arm (#3365's Walking Skeleton gate,
17
+ * `PHASE_REQ_IDS`, and `complete-milestone.md`'s bare `cat <glob>`, all
18
+ * fixed alongside this guard — see `tests/unreachable-shell-guard.test.cjs`,
19
+ * which this file does not touch).
20
+ *
21
+ * TWO detectors, each narrow by design (mirroring the sibling drift guards'
22
+ * precedent of a small, specific shape rather than a wide heuristic):
23
+ *
24
+ * Detector A — a line carrying BOTH a `--pick` token AND a `|| echo`
25
+ * fallback. `--pick` is the discriminator: a `|| echo` default WITHOUT
26
+ * `--pick` (e.g. `config-get k 2>/dev/null || echo "default"`, ~132 of the
27
+ * 141 `$(… || echo …)` lines in the prompt layer) genuinely observes a
28
+ * nonzero exit code and is left alone — see 40-design.md's Rejected #2
29
+ * ("detect on `gsd_run` + `|| echo`" was tried and reverted for exactly
30
+ * this false-positive volume).
31
+ *
32
+ * Detector B — `cat` or `ls` invoked in COMMAND POSITION with an operand
33
+ * containing an unquoted glob metacharacter (`*` or `?`). Both detectors
34
+ * are, at bottom, the SAME shape: a fallback/guard arm that a
35
+ * success-on-empty case silently defeats. Detector A is `--pick … ||
36
+ * echo`; Detector B-ii below is `ls <glob> … || echo` — the identical
37
+ * defect, one level down the stack, with `ls`'s own nullglob-driven
38
+ * success-on-empty standing in for `--pick`'s absence-coerced-to-''.
39
+ * SCOPED to exactly three fired shapes, per a full measurement across the
40
+ * four SCAN_DIRS (measured counts recorded in the PR description; 0 sites
41
+ * for B-iii today, by design — see KNOWN LIMITS):
42
+ *
43
+ * B-i. `cat <glob>` fires UNCONDITIONALLY. This is the stdin-hang
44
+ * shape (measured rc=137 at 3s under an unmatched glob +
45
+ * nullglob): `cat` reads from stdin the moment it gets zero
46
+ * operands, regardless of what — if anything — consumes its own
47
+ * exit code. There is no fallback arm to inspect; the hang
48
+ * happens before one could run.
49
+ * B-ii. `ls <glob>` fires when its exit code feeds a REAL fallback:
50
+ * `… || <arm>` where `<arm>` is not the no-op `true`/`:`. Under
51
+ * nullglob `ls` SUCCEEDS listing the cwd on an unmatched glob,
52
+ * so the fallback never runs and the intended message/default is
53
+ * silently replaced by a directory listing — exactly Detector
54
+ * A's shape, with `ls`'s exit code standing in for `--pick`'s
55
+ * stdout.
56
+ * B-iii. `ls <glob>` fires at the head of an `if`/`elif`/`while` test —
57
+ * the #3300 "existence guard that is always true under
58
+ * nullglob" shape the issue names directly: an unmatched glob
59
+ * makes `ls` list the CWD instead of erroring, so the guard is
60
+ * always true. Zero sites today (the #3300 fix already removed
61
+ * them); this arm exists solely so a REINTRODUCED instance of
62
+ * the shape does not ship silently.
63
+ *
64
+ * NOT fired on:
65
+ * - `ls <glob> … || true` / `… || :` — suppressing a failure is not a
66
+ * guard, and there is no fallback VALUE being defeated (the whole
67
+ * point of `true`/`:` is "do nothing, either way"). Measured: ~15
68
+ * sites in this tree, all this exact defensive idiom.
69
+ * - an `ls <glob>` whose STDOUT is what's consumed (`ls foo/*.md
70
+ * 2>/dev/null`, `X=$(ls -d …)`, `ls … | head`) — neither the stdin
71
+ * hang nor a defeated fallback nor an always-true guard. Measured: 97
72
+ * sites, explicitly out of this issue's scope ("Explicit non-goal:
73
+ * … Only the shapes above move.").
74
+ * - markdown prose describing either command, INCLUDING the specific
75
+ * shape `` `Bash(cat << 'EOF')` `` (a heredoc operator immediately
76
+ * after the command name is never a glob operand — see the heredoc
77
+ * guard below, and matrix row B8).
78
+ *
79
+ * `|| echo <default>` vs `|| true`/`|| :` is the discriminator for B-ii,
80
+ * exactly as `--pick` is Detector A's: both distinguish "a fallback VALUE
81
+ * this shape can silently defeat" from "no fallback value exists to
82
+ * defeat, so there is nothing here for nullglob's success-on-empty to
83
+ * break."
84
+ *
85
+ * Conservative BY CONSTRUCTION where it still applies (40-design.md's
86
+ * B10/B11 and "Law of Leaky Abstractions" section): whether a `nullglob`
87
+ * is in effect is not locally decidable from the line alone, so `cat`
88
+ * still fires unconditionally (B-i) and `ls`'s two exit-code-consuming
89
+ * shapes (B-ii, B-iii) still fire regardless of whether a guard already
90
+ * exists nearby. The remedy (an array expansion, or an existence test
91
+ * before the read) is correct either way, and array expansions carry no
92
+ * `*`/`?` character at all so they are never flagged — the detector does
93
+ * not punish its own fix.
94
+ *
95
+ * Regexes are small, bounded, and non-backtracking BY CONSTRUCTION —
96
+ * `npm run lint:ci` runs CodeQL js/redos over this repo, the same
97
+ * discipline `lint-planning-prompt-drift.cjs` documents in its own header:
98
+ *
99
+ * - PICK_RE / ECHO_FALLBACK_RE carry only a single bounded `\s*`
100
+ * quantifier each, over a fixed literal — no nesting, nothing to
101
+ * backtrack.
102
+ * - CAT_LS_COMMAND_RE's alternation is a FIXED, non-overlapping set (a
103
+ * handful of literal command-position anchors, then a fixed
104
+ * `(cat|ls)`), with one `[ \t]*` quantifier between the anchor and the
105
+ * command name — again no nesting.
106
+ * - HEREDOC_AFTER_COMMAND_RE and FALLBACK_TOKEN_RE are each a single
107
+ * bounded quantifier over a fixed/negated class, same shape as above.
108
+ * - The B-ii/B-iii "does this clause carry a glob, and what terminates
109
+ * it" question is answered by `scanClauseAfterCommand`, a plain
110
+ * LINEAR, single left-to-right character walk — not a regex at all, and
111
+ * therefore not a ReDoS surface by construction rather than by
112
+ * argument: it inspects each character of the remainder exactly once
113
+ * and returns at the first clause-terminating token it finds.
114
+ * - MARKER_RE (the escape-marker parser) is two more `\s*` quantifiers
115
+ * over fixed literals, then a single trailing `(.*)$` — again one
116
+ * quantifier, no nesting.
117
+ *
118
+ * ESCAPE MARKER. A line carrying `# gsd-scan-ignore: <reason>` is exempt
119
+ * ONLY when `<reason>` names an issue (`#NNN`, N a positive integer) or an
120
+ * `http(s)://` URL with an actual host after the scheme — the repo's
121
+ * existing precedent from `tests/commit-files-pathspec.test.cjs`
122
+ * (CONTRIBUTING.md, "Every `commit` invocation in shipped content must
123
+ * declare `--files`"), STARTING from that precedent's predicate
124
+ * (`/#\d+|https?:\/\//`) but DELIBERATELY DIVERGING from it (see
125
+ * `ISSUE_REF_RE`'s own comment for exactly what changed and why) rather than
126
+ * copying it verbatim. The sibling file still carries the looser, unpatched
127
+ * form — this guard's escape hatch is a stricter gate than a commit-message
128
+ * pathspec check needs to be, since an accepted reason here silently
129
+ * exempts a real violation from ever being reported. A marker whose reason is free text, empty, or
130
+ * whitespace-only is reported as a DISTINCT "malformed declaration" error —
131
+ * never silently exempted (that would defeat the guard) and never folded
132
+ * into the ordinary violation list (that would tell an author who already
133
+ * explained themselves that they hadn't, the exact mangle-until-CI-shuts-up
134
+ * loop the marker exists to prevent). Simplification versus the sibling
135
+ * predicate this mirrors: that guard's marker parser tokenizes the whole
136
+ * line to rule out a marker surviving inside quoted argv text (a commit
137
+ * MESSAGE quoting the token). This guard's two detectors never process
138
+ * commit-message-shaped free text, so a plain `#\s*gsd-scan-ignore:` literal
139
+ * match is sufficient here and is not widened to match that guard's
140
+ * quote-awareness it has no corresponding hazard for.
141
+ *
142
+ * RATCHET, not an allowlist. `scripts/baselines/unreachable-guard-drift-baseline.json`
143
+ * mirrors `lint-planning-prompt-drift.cjs`'s shrink-only, count-aware
144
+ * baseline exactly (see that module's header for the full "COUNT, not
145
+ * duplicate rows" rationale) — a recorded `(file, text)` pair acknowledges
146
+ * `count` byte-identical occurrences; fewer this run is a PARTIAL migration
147
+ * (stale), more is an unacknowledged new copy (fresh), zero is a fully
148
+ * migrated pair (stale). Matched on `(file, TRIMMED text)`, never the line
149
+ * number, for the same reason: a workflow `.md` file's line numbers churn on
150
+ * every unrelated edit. Malformed declarations are NEVER ratchet-eligible —
151
+ * they are an authoring mistake in the escape hatch itself, not a
152
+ * migration-in-progress, and always hard-fail (40-design.md's Goodhart's Law
153
+ * section names "run `--update` and record the violation as acknowledged
154
+ * instead of fixing it" as the ratchet's own cheapest gaming path; a
155
+ * malformed marker is exactly the shape of a half-hearted attempt at that,
156
+ * and it is refused rather than laundered into the baseline).
157
+ *
158
+ * SHARED TREE-WALK. `scanTree` / `sanitizeForReport` are consumed from
159
+ * `scripts/lib/drift-scan.cjs`, NOT reimplemented — ADR-3180 Decision 4
160
+ * explicitly rejected "let the new drift guard copy Phase 1's tree-walk",
161
+ * and 40-design.md's Greenspun's Tenth Rule section states the binding
162
+ * consequence plainly: "the 46th guard MUST consume `drift-scan.cjs`, not
163
+ * copy it." See that module for the `toPosixRel`-equivalent rationale
164
+ * (below), the symlink-confinement contract, and the ReDoS-avoidance
165
+ * rationale for its own regex-literal reader (unused by this guard's
166
+ * regexes, which need no literal tokenizer — shared here only for the walk
167
+ * and the report sanitizer).
168
+ *
169
+ * Surfaces scanned (SCAN_DIRS): `gsd-core/workflows`, `commands`, `agents`,
170
+ * `skills` — the prompt-layer markdown that ships to every runtime.
171
+ * SCAN_EXT: `.md` only.
172
+ *
173
+ * KNOWN, ACCEPTED limits (same tradeoffs the sibling guards document):
174
+ * - A cross-line split defeats Detector A (`--pick` on one line, `|| echo`
175
+ * on the next) — left to code review, per-line textual scan only.
176
+ * - `|| printf` and other non-`echo` fallbacks are not detected by
177
+ * Detector A — narrow by design; widening is a one-line change if a
178
+ * site ever appears.
179
+ * - Detector B's command-position anchor set (line start; `;`, `&`, `|`,
180
+ * `(`; the keywords `if`/`then`/`elif`/`while`/`do`) is what lets
181
+ * `$(cat …)` / `$(ls …)` — the dominant real invocation idiom in this
182
+ * tree — reach the glob check through the `(` anchor. The heredoc guard
183
+ * (`HEREDOC_AFTER_COMMAND_RE`) is what keeps that same `(` anchor from
184
+ * flagging the specific markdown prose shape `` `Bash(cat << 'EOF')` ``
185
+ * — measured against the real tree, it eliminates every such occurrence
186
+ * (a heredoc operator immediately after the command name is, by
187
+ * definition, never a glob operand). A prose sentence that put a real
188
+ * `*`/`?`-bearing word directly after `cat`/`ls` with NO heredoc
189
+ * operator between them (unobserved in this tree) would still be a
190
+ * residual over-flag in the same conservative-by-construction spirit as
191
+ * B10/B11 — accepted for the same reason: removing the `(` anchor
192
+ * entirely would blind the guard to most of the real `$(cat …)` sites
193
+ * it exists to catch, the strictly worse direction (silent false
194
+ * negative vs. a visible, ratchet-acknowledgeable false positive).
195
+ * - B-iii's `if`/`elif`/`while` head-position check is per-token, not a
196
+ * full parse of the conditional's grammar: `if [ -f x ] && ls
197
+ * glob; then` (a compound condition where `ls` is not literally the
198
+ * first word after `if`) is not reachable through the keyword anchor
199
+ * and falls through to B-ii's `||`-fallback check instead, which is the
200
+ * right outcome only when a `||`-fallback is present that isn't a
201
+ * no-op. A compound `if` condition ending the `ls` clause with `;`/end
202
+ * of line and no `||` arm is a genuine, unmeasured (zero observed)
203
+ * miss — left to code review, matching the design's stated per-line
204
+ * textual-scan tradeoff throughout.
205
+ * - The `|| true` / `|| :` no-op carve-out (FALLBACK_TOKEN_RE) inspects
206
+ * only the FIRST token after `||`; a real fallback dressed up as `||
207
+ * (true; echo "surprise")` would read as the no-op and miss — no such
208
+ * shape exists in this tree today (measured), and widening the
209
+ * no-op-detection is a one-line change if one ever appears.
210
+ */
211
+
212
+ const fs = require('node:fs');
213
+ const path = require('node:path');
214
+ const driftScan = require('./lib/drift-scan.cjs');
215
+ const { sanitizeForReport, scanTree } = driftScan;
216
+
217
+ // ─── Detector A — `--pick` + `|| echo` ────────────────────────────────────
218
+ //
219
+ // `--pick` is the discriminator (see module header); `|| echo` is the
220
+ // unreachable fallback arm it silently defeats. Both must be present on the
221
+ // SAME line for the shape to be the exact unreachable-arm defect #3409
222
+ // fixes — see the module header for why a bare "`gsd_run` + `|| echo`" rule
223
+ // was tried and reverted (Rejected #2).
224
+ const PICK_RE = /--pick\b/;
225
+ const ECHO_FALLBACK_RE = /\|\|\s*echo\b/;
226
+
227
+ // ─── Detector B — cat <glob> (B-i), ls <glob> … || <real fallback> (B-ii),
228
+ // or ls <glob> at the head of if/elif/while (B-iii) ────────────────────────
229
+ //
230
+ // Command-position anchor: start of line, a shell separator/opener
231
+ // (`;`, `&`, `|`, `(`), or one of the keywords that precede a command
232
+ // (`if`, `then`, `elif`, `while`, `do`) — each followed by optional
233
+ // horizontal whitespace and then the literal command name. Group 1 captures
234
+ // WHICH anchor matched (`''` for start-of-line, since `^` itself consumes no
235
+ // characters; the literal separator char; or the literal keyword) so
236
+ // detectGlobOperand can tell a true `if`/`elif`/`while` head position (B-iii)
237
+ // apart from `then`/`do`/a bare separator, which do not themselves test the
238
+ // following command's exit status. Group 2 captures the command name. A
239
+ // FIXED alternation with one `[ \t]*` quantifier between the anchor and the
240
+ // command name; no nesting, nothing to backtrack.
241
+ const CAT_LS_COMMAND_RE = /(^|[;&|(]|\bif\b|\bthen\b|\belif\b|\bwhile\b|\bdo\b)[ \t]*(cat|ls)\b/;
242
+
243
+ // A heredoc operator immediately after the command name (optional
244
+ // horizontal whitespace, then `<<`) is never a glob operand — matrix row B8,
245
+ // and the mechanism that keeps the markdown-prose shape `` `Bash(cat <<
246
+ // 'EOF')` `` (whose surrounding `**bold**` carries literal `*` characters
247
+ // elsewhere on the line) from ever reaching the glob scan at all. Single
248
+ // bounded quantifier, no nesting.
249
+ const HEREDOC_AFTER_COMMAND_RE = /^[ \t]*<</;
250
+
251
+ // Only `if`/`elif`/`while` test the command that follows THEM directly —
252
+ // `then` and `do` introduce what runs AFTER a test has already passed, not
253
+ // the test itself, so they do not, on their own, make `ls`'s exit code the
254
+ // thing being consumed (B-iii). `cat` (B-i) never consults this set: it
255
+ // fires unconditionally regardless of anchor.
256
+ const EXIT_TESTING_KEYWORDS = new Set(['if', 'elif', 'while']);
257
+
258
+ // The first whitespace/`;`/`)`/`|`/`&`-delimited token of the text
259
+ // immediately after a `||` — used to tell a REAL fallback (B-ii) from the
260
+ // no-op `true`/`:` idiom (~15 measured sites in this tree, all defensive
261
+ // failure-suppression with no fallback value being defeated). Single
262
+ // bounded negated-class quantifier, no nesting.
263
+ const FALLBACK_TOKEN_RE = /^[ \t]*([^\s;)|&]+)/;
264
+
265
+ function isNoopFallback(fallbackText) {
266
+ const m = FALLBACK_TOKEN_RE.exec(fallbackText);
267
+ if (!m) return true; // nothing after `||` at all — no fallback value to defeat
268
+ return m[1] === 'true' || m[1] === ':';
269
+ }
270
+
271
+ /**
272
+ * Plain LINEAR left-to-right character walk over `rest` (the line remainder
273
+ * immediately after a cat/ls command match) — not a regex, and therefore
274
+ * not a ReDoS surface by construction. Inspects each character exactly
275
+ * once and returns as soon as it finds a clause-terminating token:
276
+ * `;` -> the clause ends with no chain at all.
277
+ * `&&` -> a short-circuit "glob matched, so proceed" chain.
278
+ * `||` -> a short-circuit fallback chain; `fallback` is
279
+ * everything after the `||` (for isNoopFallback to
280
+ * classify).
281
+ * a lone `|` -> the clause's STDOUT is piped onward (informational,
282
+ * never a hazard shape this detector fires on).
283
+ * a lone `&` -> backgrounded; not a chain this detector recognizes.
284
+ * end of string -> no chain of any kind.
285
+ * `hasGlob` is tracked across the WHOLE walk regardless of where the scan
286
+ * stops, since a `*`/`?` can appear anywhere in the operand region before
287
+ * the terminator.
288
+ */
289
+ function scanClauseAfterCommand(rest) {
290
+ let hasGlob = false;
291
+ for (let i = 0; i < rest.length; i++) {
292
+ const ch = rest[i];
293
+ if (ch === '*' || ch === '?') { hasGlob = true; continue; }
294
+ if (ch === ';') return { hasGlob, terminator: ';', fallback: null };
295
+ if (ch === '&' && rest[i + 1] === '&') return { hasGlob, terminator: '&&', fallback: null };
296
+ if (ch === '|' && rest[i + 1] === '|') return { hasGlob, terminator: '||', fallback: rest.slice(i + 2) };
297
+ if (ch === '|') return { hasGlob, terminator: '|', fallback: null };
298
+ if (ch === '&') return { hasGlob, terminator: '&', fallback: null };
299
+ }
300
+ return { hasGlob, terminator: null, fallback: null };
301
+ }
302
+
303
+ /**
304
+ * Pure: does `line` carry one of Detector B's three fired shapes? Returns
305
+ * `{ command }` (`cat` or `ls`) or `null`. See the module header for the
306
+ * B-i/B-ii/B-iii scoping and what deliberately does NOT fire.
307
+ */
308
+ function detectGlobOperand(line) {
309
+ const anchor = CAT_LS_COMMAND_RE.exec(line);
310
+ if (!anchor) return null;
311
+ const anchorToken = anchor[1];
312
+ const command = anchor[2];
313
+ const rest = line.slice(anchor.index + anchor[0].length);
314
+ if (HEREDOC_AFTER_COMMAND_RE.test(rest)) return null;
315
+
316
+ const { hasGlob, terminator, fallback } = scanClauseAfterCommand(rest);
317
+ if (!hasGlob) return null;
318
+
319
+ if (command === 'cat') return { command }; // B-i: unconditional.
320
+
321
+ // command === 'ls': B-iii (head of a real conditional test) or B-ii (a
322
+ // real, non-no-op `||` fallback). Neither a lone `|` (stdout piped
323
+ // onward) nor `|| true`/`|| :` nor a bare `;`/end-of-line qualifies.
324
+ if (EXIT_TESTING_KEYWORDS.has(anchorToken)) return { command };
325
+ if (terminator === '||' && fallback !== null && !isNoopFallback(fallback)) return { command };
326
+ return null;
327
+ }
328
+
329
+ // ─── Escape marker ─────────────────────────────────────────────────────────
330
+ //
331
+ // `# gsd-scan-ignore: <reason>`. Two `\s*` quantifiers over fixed literals,
332
+ // then a single trailing `(.*)$` — one quantifier, no nesting. Lines are
333
+ // split via `/\r?\n/` (see findUnreachableGuardDrift) before this ever runs,
334
+ // so `.` never has to reason about a trailing `\r` — the pitfall the CRLF
335
+ // coverage in the test matrix (P1-P4) exists to catch.
336
+ const MARKER_RE = /#\s*gsd-scan-ignore:\s*(.*)$/;
337
+
338
+ // DELIBERATE DIVERGENCE from tests/commit-files-pathspec.test.cjs's own
339
+ // `ISSUE_REF_RE` (`/#\d+|https?:\/\//`), which this predicate started as a
340
+ // copy of. That sibling form validates FORMAT only, and two shapes satisfy
341
+ // it while naming nothing real:
342
+ // - `#0` matches `#\d+` (`\d+` allows a leading zero / an all-zero run),
343
+ // silently exempting a violation under a reason that names no positive
344
+ // issue number.
345
+ // - a bare `http://` / `https://` matches `https?:\/\/` with nothing
346
+ // after the scheme — no host, so no URL is actually named.
347
+ // Both are closed here: an issue ref requires a POSITIVE integer
348
+ // (`#[1-9]\d*` — no leading-zero/all-zero match), and a URL requires at
349
+ // least one non-whitespace character after the scheme as its host
350
+ // (`https?:\/\/[^\s]+`). This guard's escape hatch is a stricter gate than
351
+ // the sibling's commit-message pathspec check needs to be — an accepted
352
+ // reason here silently exempts a real violation from ever being reported —
353
+ // so the sibling is intentionally left at its own, looser form (not edited
354
+ // by this change) rather than tightened to match.
355
+ // Still one bounded quantifier per alternative, no nesting: `\d*` over a
356
+ // fixed digit class, `[^\s]+` over a fixed negated class. Non-backtracking,
357
+ // same as every other regex in this module (see the module header's ReDoS
358
+ // section).
359
+ const ISSUE_REF_RE = /#[1-9]\d*|https?:\/\/[^\s]+/;
360
+
361
+ // `scanTree` (scripts/lib/drift-scan.cjs) builds its repo-relative path via
362
+ // `path.relative()`, which uses NATIVE separators: on Windows that is
363
+ // `gsd-core\workflows\plan-phase.md`, while the committed baseline stores
364
+ // POSIX paths. Normalized UNCONDITIONALLY — never gated on
365
+ // `process.platform` — for the exact reason `lint-planning-prompt-drift.cjs`
366
+ // documents at its own `toPosixRel`: a platform-conditional normalizer is
367
+ // itself the bug, since it makes the POSIX path the only tested case
368
+ // (PR #3223).
369
+ function toPosixRel(relPath) {
370
+ return relPath.replace(/\\/g, '/');
371
+ }
372
+
373
+ // Prompt-layer markdown that ships to every runtime.
374
+ const SCAN_DIRS = ['gsd-core/workflows', 'commands', 'agents', 'skills'];
375
+ const SCAN_EXT = new Set(['.md']);
376
+
377
+ const BASELINE_REL_PATH = path.join('scripts', 'baselines', 'unreachable-guard-drift-baseline.json');
378
+
379
+ // The tracking issue this guard's own baseline entries are owned by, absent
380
+ // a more specific site owner named at `--update` time. #3409 is this
381
+ // guard's own issue: any site it finds that this PR does not convert is a
382
+ // "one careless line from the same class" per 40-design.md's Postel's Law
383
+ // section, tracked here until the upstream `--pick` contract fix (#3473)
384
+ // or a per-site conversion lands.
385
+ const RATCHET_OWNER_ISSUE = '#3409';
386
+
387
+ /**
388
+ * Pure: scan `text` (one file's content) for Detector A / Detector B
389
+ * violations and malformed escape-marker declarations. `relPath` is the
390
+ * repo-relative path (native separators or POSIX, either accepted) —
391
+ * normalized via `toPosixRel` and attached as `file` on every result.
392
+ *
393
+ * Returns `{ violations, malformed }`:
394
+ * - `violations`: `[{ file, line, kind: 'A'|'B', found, text }]` — `text`
395
+ * is the TRIMMED source line (the baseline key), `found` names the
396
+ * discriminating token (`--pick` for A, `cat`/`ls` for B).
397
+ * - `malformed`: `[{ file, line, text, reason }]` — an ATTEMPTED
398
+ * `# gsd-scan-ignore:` declaration whose reason names no issue and no
399
+ * URL. Checked on EVERY line independent of whether that line also
400
+ * matches a detector (a comment-only malformed declaration is still a
401
+ * malformed declaration) — never ratchet-eligible.
402
+ *
403
+ * Lines are split on `/\r?\n/` so CRLF input carries no trailing `\r` into
404
+ * either the detector regexes or the baseline key (`text.trim()` would
405
+ * catch most of this anyway, per `String.prototype.trim`'s LineTerminator
406
+ * handling, but MARKER_RE's trailing `(.*)$` specifically needs the split
407
+ * to have already happened — `.` excludes `\r` from its own match).
408
+ */
409
+ function findUnreachableGuardDrift(text, relPath) {
410
+ const file = toPosixRel(relPath);
411
+ const violations = [];
412
+ const malformed = [];
413
+ const lines = text.split(/\r?\n/);
414
+ for (let i = 0; i < lines.length; i++) {
415
+ const line = lines[i];
416
+ const lineNo = i + 1;
417
+
418
+ let exempt = false;
419
+ const markerMatch = MARKER_RE.exec(line);
420
+ if (markerMatch) {
421
+ const reason = markerMatch[1];
422
+ if (ISSUE_REF_RE.test(reason)) {
423
+ exempt = true;
424
+ } else {
425
+ malformed.push({ file, line: lineNo, text: line.trim(), reason: reason.trim() });
426
+ exempt = true; // malformed declarations are reported on their own terms, never as a plain violation too (design A14 / matrix M3-M5)
427
+ }
428
+ }
429
+ if (exempt) continue;
430
+
431
+ if (PICK_RE.test(line) && ECHO_FALLBACK_RE.test(line)) {
432
+ violations.push({ file, line: lineNo, kind: 'A', found: '--pick', text: line.trim() });
433
+ }
434
+ const globInfo = detectGlobOperand(line);
435
+ if (globInfo) {
436
+ violations.push({ file, line: lineNo, kind: 'B', found: globInfo.command, text: line.trim() });
437
+ }
438
+ }
439
+ return { violations, malformed };
440
+ }
441
+
442
+ /**
443
+ * Scan the prompt-layer markdown tree and return every violation and
444
+ * malformed declaration, each annotated with the repo-relative file path
445
+ * (POSIX-normalized — see `toPosixRel`).
446
+ */
447
+ function scanRepo(root) {
448
+ const violations = [];
449
+ const malformed = [];
450
+ scanTree({
451
+ root,
452
+ scanDirs: SCAN_DIRS,
453
+ scanExt: SCAN_EXT,
454
+ onFile(rel, text) {
455
+ const found = findUnreachableGuardDrift(text, rel);
456
+ violations.push(...found.violations);
457
+ malformed.push(...found.malformed);
458
+ return []; // scanTree's own accumulator is unused; we track both lists ourselves so its single flat list is never asked to carry two shapes.
459
+ },
460
+ });
461
+ return { violations, malformed };
462
+ }
463
+
464
+ /**
465
+ * Frozen outcome-reason enum. CONTRIBUTING.md's "Prohibited: Raw Text
466
+ * Matching on Test Outputs" requires a typed structured surface wherever
467
+ * this module produces human-readable text — mirrors
468
+ * `gsd-core/bin/verify-reapply-patches.cjs`'s own `REASON` map exactly:
469
+ * `main()`'s `--json` mode and every `loadBaseline` per-error object carry
470
+ * one of these codes instead of free prose, and tests assert on the code,
471
+ * never on the rendered message. Adding a new reason requires updating this
472
+ * enum, the `--json` emission/`loadBaseline` call site that produces it, AND
473
+ * the test that locks `Object.keys(REASON).sort()` — three coordinated
474
+ * changes that keep the code surface from drifting from the test surface.
475
+ */
476
+ const REASON = Object.freeze({
477
+ // main() top-level outcomes (non---update and --update paths).
478
+ OK_NO_VIOLATIONS: 'ok_no_violations',
479
+ OK_BASELINE_UPDATED: 'ok_baseline_updated',
480
+ FAIL_FRESH_VIOLATION: 'fail_fresh_violation',
481
+ FAIL_STALE_ENTRY: 'fail_stale_entry',
482
+ FAIL_MALFORMED_MARKER: 'fail_malformed_marker',
483
+ FAIL_BASELINE_LOAD: 'fail_baseline_load',
484
+ // loadBaseline per-error outcomes — each a distinct baseline-load failure
485
+ // class (mirrors lint-planning-prompt-drift.cjs's loadBaseline validation).
486
+ FAIL_BASELINE_MISSING: 'fail_baseline_missing',
487
+ FAIL_BASELINE_EMPTY: 'fail_baseline_empty',
488
+ FAIL_BASELINE_INVALID_JSON: 'fail_baseline_invalid_json',
489
+ FAIL_BASELINE_NOT_OBJECT: 'fail_baseline_not_object',
490
+ FAIL_BASELINE_ENTRIES_NOT_ARRAY: 'fail_baseline_entries_not_array',
491
+ FAIL_BASELINE_ENTRY_NOT_OBJECT: 'fail_baseline_entry_not_object',
492
+ FAIL_BASELINE_ENTRY_FIELD_INVALID: 'fail_baseline_entry_field_invalid',
493
+ FAIL_BASELINE_ENTRY_COUNT_INVALID: 'fail_baseline_entry_count_invalid',
494
+ });
495
+
496
+ /**
497
+ * Read and parse the ratchet baseline. Returns `{ entries, errors }` —
498
+ * `entries` is `[]` and `errors` is an array of STRUCTURED error objects
499
+ * (`{ reason: REASON.*, message, ... }`) when the file is missing, empty,
500
+ * invalid JSON, or malformed. Mirrors `lint-planning-prompt-drift.cjs`'s
501
+ * `loadBaseline` validation exactly (same failure classes: missing, empty,
502
+ * invalid JSON, non-object JSON — including the `null`/array/scalar cases a
503
+ * bare `typeof === 'object'` check would miss — a non-array `entries`
504
+ * field, and per-entry validation of `file`/`text`/`count`). `message` is a
505
+ * human-readable string for the console formatter only; callers (and
506
+ * tests) must key off `reason`, never parse `message`.
507
+ */
508
+ function loadBaseline(root) {
509
+ const baselinePath = path.join(root, BASELINE_REL_PATH);
510
+ if (!fs.existsSync(baselinePath)) {
511
+ return {
512
+ entries: [],
513
+ errors: [{
514
+ reason: REASON.FAIL_BASELINE_MISSING,
515
+ message: `${BASELINE_REL_PATH} is missing — run \`node scripts/lint-unreachable-guard-drift.cjs --update\` to generate it`,
516
+ }],
517
+ };
518
+ }
519
+ const raw = fs.readFileSync(baselinePath, 'utf8');
520
+ if (raw.trim() === '') {
521
+ return {
522
+ entries: [],
523
+ errors: [{ reason: REASON.FAIL_BASELINE_EMPTY, message: `${BASELINE_REL_PATH} is present but empty` }],
524
+ };
525
+ }
526
+ let doc;
527
+ try {
528
+ doc = JSON.parse(raw);
529
+ } catch (err) {
530
+ return {
531
+ entries: [],
532
+ errors: [{
533
+ reason: REASON.FAIL_BASELINE_INVALID_JSON,
534
+ message: `${BASELINE_REL_PATH} is not valid JSON: ${err.message}`,
535
+ parseError: err.message,
536
+ }],
537
+ };
538
+ }
539
+ if (doc === null || typeof doc !== 'object' || Array.isArray(doc)) {
540
+ const gotType = Array.isArray(doc) ? 'array' : typeof doc;
541
+ return {
542
+ entries: [],
543
+ errors: [{
544
+ reason: REASON.FAIL_BASELINE_NOT_OBJECT,
545
+ message: `${BASELINE_REL_PATH} must be a JSON object, got ${gotType}`,
546
+ gotType,
547
+ }],
548
+ };
549
+ }
550
+ if (!Array.isArray(doc.entries)) {
551
+ return {
552
+ entries: [],
553
+ errors: [{
554
+ reason: REASON.FAIL_BASELINE_ENTRIES_NOT_ARRAY,
555
+ message: `${BASELINE_REL_PATH}: "entries" must be an array, got ${JSON.stringify(doc.entries)}`,
556
+ entriesValue: doc.entries,
557
+ }],
558
+ };
559
+ }
560
+ const errors = [];
561
+ const entries = [];
562
+ doc.entries.forEach((entry, i) => {
563
+ const where = `${BASELINE_REL_PATH}.entries[${i}]`;
564
+ if (entry === null || typeof entry !== 'object' || Array.isArray(entry)) {
565
+ errors.push({
566
+ reason: REASON.FAIL_BASELINE_ENTRY_NOT_OBJECT,
567
+ message: `${where} must be an object, got ${JSON.stringify(entry)}`,
568
+ index: i,
569
+ where,
570
+ });
571
+ return;
572
+ }
573
+ if (typeof entry.file !== 'string' || entry.file === '') {
574
+ errors.push({
575
+ reason: REASON.FAIL_BASELINE_ENTRY_FIELD_INVALID,
576
+ message: `${where}.file must be a non-empty string, got ${JSON.stringify(entry.file)}`,
577
+ index: i,
578
+ where,
579
+ field: 'file',
580
+ value: entry.file,
581
+ });
582
+ return;
583
+ }
584
+ if (typeof entry.text !== 'string' || entry.text === '') {
585
+ errors.push({
586
+ reason: REASON.FAIL_BASELINE_ENTRY_FIELD_INVALID,
587
+ message: `${where}.text must be a non-empty string, got ${JSON.stringify(entry.text)}`,
588
+ index: i,
589
+ where,
590
+ field: 'text',
591
+ value: entry.text,
592
+ });
593
+ return;
594
+ }
595
+ // `count` is optional on read (diffAgainstBaseline defaults an absent
596
+ // count to 1) but when present must be a positive integer.
597
+ if (entry.count !== undefined && !(Number.isInteger(entry.count) && entry.count >= 1)) {
598
+ errors.push({
599
+ reason: REASON.FAIL_BASELINE_ENTRY_COUNT_INVALID,
600
+ message: `${where}.count must be a positive integer when present, got ${JSON.stringify(entry.count)}`,
601
+ index: i,
602
+ where,
603
+ value: entry.count,
604
+ });
605
+ return;
606
+ }
607
+ entries.push(entry);
608
+ });
609
+ return { entries, errors };
610
+ }
611
+
612
+ /**
613
+ * Diff scanned `violations` against baseline `entries`, matched by the pair
614
+ * (`file`, TRIMMED `text`) — never the line number — and COUNT-aware, same
615
+ * semantics as `lint-planning-prompt-drift.cjs`'s `diffAgainstBaseline`:
616
+ * - `fresh`: violations whose `(file, text)` pair is not in the baseline
617
+ * at all, PLUS any occurrences of a KNOWN pair beyond its acknowledged
618
+ * `count`.
619
+ * - `stale`: baseline entries whose actual occurrence count this run is
620
+ * LESS than their acknowledged `count` (zero is the fully-migrated
621
+ * case; a positive-but-short count is a PARTIAL migration).
622
+ */
623
+ function diffAgainstBaseline(violations, baseline) {
624
+ const key = (file, text) => `${file} ${text}`;
625
+
626
+ const actualByKey = new Map();
627
+ for (const v of violations) {
628
+ const k = key(v.file, v.text);
629
+ let vs = actualByKey.get(k);
630
+ if (!vs) { vs = []; actualByKey.set(k, vs); }
631
+ vs.push(v);
632
+ }
633
+
634
+ const knownKeys = new Set(baseline.map((e) => key(e.file, e.text)));
635
+
636
+ const fresh = [];
637
+ const stale = [];
638
+
639
+ for (const [k, vs] of actualByKey) {
640
+ if (!knownKeys.has(k)) fresh.push(...vs);
641
+ }
642
+
643
+ for (const entry of baseline) {
644
+ const k = key(entry.file, entry.text);
645
+ const expected = entry.count ?? 1;
646
+ const vs = actualByKey.get(k) || [];
647
+ const actual = vs.length;
648
+ if (actual < expected) {
649
+ stale.push({ ...entry, count: expected, actualCount: actual });
650
+ } else if (actual > expected) {
651
+ fresh.push(...vs.slice(expected));
652
+ }
653
+ }
654
+
655
+ return { fresh, stale };
656
+ }
657
+
658
+ /** Stable sort: by `file`, then by `text`. */
659
+ function sortEntries(entries) {
660
+ return [...entries].sort((a, b) => {
661
+ if (a.file !== b.file) return a.file < b.file ? -1 : 1;
662
+ if (a.text !== b.text) return a.text < b.text ? -1 : 1;
663
+ return 0;
664
+ });
665
+ }
666
+
667
+ /**
668
+ * Collapse `violations` into one baseline row per distinct (file, text)
669
+ * pair, carrying a `count` of how many occurrences that pair has in THIS
670
+ * run. Pure; no I/O.
671
+ */
672
+ function dedupeViolationsForBaseline(violations) {
673
+ const order = [];
674
+ const byKey = new Map();
675
+ for (const v of violations) {
676
+ const k = `${v.file} ${v.text}`;
677
+ let entry = byKey.get(k);
678
+ if (!entry) {
679
+ entry = { file: v.file, text: v.text, kind: v.kind, owner_issue: RATCHET_OWNER_ISSUE, count: 0 };
680
+ byKey.set(k, entry);
681
+ order.push(entry);
682
+ }
683
+ entry.count += 1;
684
+ }
685
+ return order;
686
+ }
687
+
688
+ function writeBaseline(root, violations) {
689
+ const entries = sortEntries(dedupeViolationsForBaseline(violations));
690
+ const doc = {
691
+ $comment:
692
+ '#3409 unreachable-shell-guard ratchet. See scripts/lint-unreachable-guard-drift.cjs. '
693
+ + 'SHRINK-ONLY: entries are removed as sites migrate off the unreachable-arm shape; new or '
694
+ + 'changed entries fail lint:ci. `count` is the number of byte-identical (file, text) '
695
+ + 'occurrences acknowledged at this site — a run producing fewer fails as a partial migration, '
696
+ + 'more fails as an unacknowledged new copy.',
697
+ entries,
698
+ };
699
+ const baselinePath = path.join(root, BASELINE_REL_PATH);
700
+ fs.mkdirSync(path.dirname(baselinePath), { recursive: true });
701
+ fs.writeFileSync(baselinePath, `${JSON.stringify(doc, null, 2)}\n`, 'utf8');
702
+ return entries;
703
+ }
704
+
705
+ /**
706
+ * `--json` mode emits ONE structured JSON object to stdout in place of the
707
+ * human formatter below — the typed IR CONTRIBUTING.md's "Prohibited: Raw
708
+ * Text Matching on Test Outputs" requires. The human formatter's wording is
709
+ * untouched (operator console use only); `emitJson` is the only new output
710
+ * surface, gated on `json` so the two never interleave on the same stream.
711
+ */
712
+ function main() {
713
+ const root = path.join(__dirname, '..');
714
+ const update = process.argv.includes('--update');
715
+ const json = process.argv.includes('--json');
716
+ const { violations, malformed } = scanRepo(root);
717
+
718
+ function emitJson(report) {
719
+ if (json) process.stdout.write(`${JSON.stringify(report, null, 2)}\n`);
720
+ }
721
+
722
+ if (update) {
723
+ if (malformed.length > 0) {
724
+ if (!json) {
725
+ process.stderr.write('unreachable-guard-drift: malformed `# gsd-scan-ignore:` declaration(s) — fix these before regenerating the baseline (they are never ratchet-eligible):\n');
726
+ for (const m of malformed) {
727
+ process.stderr.write(` ${sanitizeForReport(m.file)}:${m.line} ${sanitizeForReport(m.text)}\n`);
728
+ }
729
+ process.stderr.write('\n remedy: the reason after `# gsd-scan-ignore:` must name a tracking issue (#NNN) or an http(s):// URL.\n');
730
+ }
731
+ emitJson({ reason: REASON.FAIL_MALFORMED_MARKER, violations: [], malformed, stale: [], baselineErrors: [] });
732
+ process.exitCode = 1;
733
+ return;
734
+ }
735
+ const entries = writeBaseline(root, violations);
736
+ if (!json) {
737
+ process.stdout.write(`ok unreachable-guard-drift: baseline regenerated with ${entries.length} entr${entries.length === 1 ? 'y' : 'ies'}\n`);
738
+ }
739
+ emitJson({ reason: REASON.OK_BASELINE_UPDATED, violations: [], malformed: [], stale: [], baselineErrors: [], updatedEntryCount: entries.length });
740
+ return;
741
+ }
742
+
743
+ const { entries: baseline, errors } = loadBaseline(root);
744
+ if (errors.length > 0) {
745
+ if (!json) {
746
+ process.stderr.write('unreachable-guard-drift: baseline load error(s):\n');
747
+ // OUTPUT SEAM: `loadBaseline`'s `message` strings embed
748
+ // `JSON.stringify(entry.file)` / `JSON.stringify(entry.text)` /
749
+ // `JSON.stringify(entry)` verbatim, and `JSON.stringify` escapes only
750
+ // code points below 0x20 — it passes C1 controls (0x7F-0x9F) and the
751
+ // bidi/zero-width controls (U+202E RTL override, U+2066-U+2069,
752
+ // U+2028, U+2029) through UNESCAPED. Without `sanitizeForReport` here, a
753
+ // crafted `entries[].file`/`.text` value in the baseline JSON could
754
+ // land an active bidi override straight into CI console output — the
755
+ // exact report-spoofing class every violation/malformed field below is
756
+ // already routed through `sanitizeForReport` to prevent.
757
+ for (const e of errors) process.stderr.write(` ${sanitizeForReport(e.message)}\n`);
758
+ }
759
+ emitJson({ reason: REASON.FAIL_BASELINE_LOAD, violations: [], malformed: [], stale: [], baselineErrors: errors });
760
+ process.exitCode = 1;
761
+ return;
762
+ }
763
+
764
+ const { fresh, stale } = diffAgainstBaseline(violations, baseline);
765
+
766
+ if (fresh.length === 0 && stale.length === 0 && malformed.length === 0) {
767
+ if (!json) {
768
+ process.stdout.write(`ok unreachable-guard-drift: no unacknowledged unreachable shell-guard shapes in the prompt layer (${baseline.length} known)\n`);
769
+ }
770
+ emitJson({ reason: REASON.OK_NO_VIOLATIONS, violations: [], malformed: [], stale: [], baselineErrors: [], knownCount: baseline.length });
771
+ return;
772
+ }
773
+
774
+ if (!json) {
775
+ if (fresh.length > 0) {
776
+ process.stderr.write('unreachable-guard-drift: NEW unreachable shell-guard shape(s) found in the prompt layer.\n');
777
+ process.stderr.write('Detector A (--pick + || echo): the fallback can never fire on field absence — replace with an\n');
778
+ process.stderr.write('explicit -z/empty-string test on the resolved value.\n');
779
+ process.stderr.write('Detector B (cat/ls over a glob operand): under a nullglob set elsewhere in the same shell\n');
780
+ process.stderr.write('session, an unmatched glob reads from stdin (cat) or lists the cwd (ls) — use an array\n');
781
+ process.stderr.write('expansion or an existence test instead.\n');
782
+ process.stderr.write(`Or, if this is a deliberate wrong-example, declare it with # gsd-scan-ignore: #NNN, or add an\n`);
783
+ process.stderr.write(`acknowledged entry to ${BASELINE_REL_PATH} via --update:\n`);
784
+ for (const v of fresh) {
785
+ process.stderr.write(` ${sanitizeForReport(v.file)}:${v.line} [${v.kind}] ${sanitizeForReport(v.found)} ${sanitizeForReport(v.text)}\n`);
786
+ }
787
+ }
788
+
789
+ if (stale.length > 0) {
790
+ process.stderr.write('\nunreachable-guard-drift: STALE baseline entr' + (stale.length === 1 ? 'y' : 'ies') + " (fully migrated, or a PARTIAL migration — fewer occurrences found than acknowledged; delete or re-record the row):\n");
791
+ for (const e of stale) {
792
+ process.stderr.write(` ${sanitizeForReport(e.file)} ${sanitizeForReport(e.text)} (found ${e.actualCount}/${e.count} acknowledged occurrence${e.count === 1 ? '' : 's'})\n`);
793
+ }
794
+ process.stderr.write(`\n remedy: node scripts/lint-unreachable-guard-drift.cjs --update\n`);
795
+ }
796
+
797
+ if (malformed.length > 0) {
798
+ process.stderr.write('\nunreachable-guard-drift: malformed `# gsd-scan-ignore:` declaration(s) — never ratchet-eligible, must be fixed directly:\n');
799
+ for (const m of malformed) {
800
+ process.stderr.write(` ${sanitizeForReport(m.file)}:${m.line} ${sanitizeForReport(m.text)}\n`);
801
+ }
802
+ process.stderr.write('\n remedy: the reason after `# gsd-scan-ignore:` must name a tracking issue (#NNN) or an http(s):// URL.\n');
803
+ }
804
+ }
805
+
806
+ const reason = fresh.length > 0
807
+ ? REASON.FAIL_FRESH_VIOLATION
808
+ : stale.length > 0
809
+ ? REASON.FAIL_STALE_ENTRY
810
+ : REASON.FAIL_MALFORMED_MARKER;
811
+ emitJson({ reason, violations: fresh, malformed, stale, baselineErrors: [] });
812
+
813
+ process.exitCode = 1;
814
+ }
815
+
816
+ if (require.main === module) main();
817
+
818
+ module.exports = {
819
+ findUnreachableGuardDrift,
820
+ detectGlobOperand,
821
+ scanRepo,
822
+ toPosixRel,
823
+ loadBaseline,
824
+ diffAgainstBaseline,
825
+ dedupeViolationsForBaseline,
826
+ sortEntries,
827
+ writeBaseline,
828
+ PICK_RE,
829
+ ECHO_FALLBACK_RE,
830
+ CAT_LS_COMMAND_RE,
831
+ HEREDOC_AFTER_COMMAND_RE,
832
+ EXIT_TESTING_KEYWORDS,
833
+ FALLBACK_TOKEN_RE,
834
+ isNoopFallback,
835
+ scanClauseAfterCommand,
836
+ MARKER_RE,
837
+ ISSUE_REF_RE,
838
+ SCAN_DIRS,
839
+ SCAN_EXT,
840
+ BASELINE_REL_PATH,
841
+ RATCHET_OWNER_ISSUE,
842
+ REASON,
843
+ };