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

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (197) hide show
  1. package/.claude-plugin/plugin.json +1 -1
  2. package/README.md +3 -3
  3. package/agents/gsd-code-fixer.md +3 -2
  4. package/agents/gsd-debug-session-manager.md +2 -1
  5. package/agents/gsd-debugger.md +4 -3
  6. package/agents/gsd-executor.md +17 -16
  7. package/agents/gsd-intel-updater.md +38 -41
  8. package/agents/gsd-phase-researcher.md +8 -8
  9. package/agents/gsd-plan-checker.md +23 -13
  10. package/agents/gsd-planner.md +32 -188
  11. package/agents/gsd-project-researcher.md +5 -4
  12. package/agents/gsd-research-synthesizer.md +2 -1
  13. package/agents/gsd-ui-researcher.md +2 -1
  14. package/agents/gsd-verifier.md +12 -11
  15. package/bin/install.js +965 -1486
  16. package/commands/gsd/autonomous.md +5 -1
  17. package/commands/gsd/ns-manage.md +8 -1
  18. package/commands/gsd/ns-project.md +5 -0
  19. package/commands/gsd/ns-review.md +4 -1
  20. package/commands/gsd/ns-workflow.md +7 -1
  21. package/commands/gsd/plan-review-convergence.md +5 -4
  22. package/commands/gsd/surface.md +12 -5
  23. package/gemini-extension.json +1 -1
  24. package/gsd-core/bin/gsd-tools.cjs +198 -101
  25. package/gsd-core/bin/gsd_run +20 -0
  26. package/gsd-core/bin/lib/audit-command-router.cjs +61 -0
  27. package/gsd-core/bin/lib/capability-registry.cjs +2234 -0
  28. package/gsd-core/bin/lib/capability-state.cjs +336 -0
  29. package/gsd-core/bin/lib/check-command-router.cjs +133 -2
  30. package/gsd-core/bin/lib/cli-exit.cjs +22 -3
  31. package/gsd-core/bin/lib/config-loader.cjs +716 -0
  32. package/gsd-core/bin/lib/configuration.cjs +4 -34
  33. package/gsd-core/bin/lib/core-utils.cjs +198 -0
  34. package/gsd-core/bin/lib/core.cjs +107 -1817
  35. package/gsd-core/bin/lib/edge-probe.cjs +173 -0
  36. package/gsd-core/bin/lib/fallow-runner.cjs +63 -25
  37. package/gsd-core/bin/lib/federated-config.cjs +182 -0
  38. package/gsd-core/bin/lib/graphify-command-router.cjs +74 -0
  39. package/gsd-core/bin/lib/init.cjs +58 -12
  40. package/gsd-core/bin/lib/install-profiles.cjs +157 -3
  41. package/gsd-core/bin/lib/intel-command-router.cjs +116 -0
  42. package/gsd-core/bin/lib/intel.cjs +3 -3
  43. package/gsd-core/bin/lib/io.cjs +222 -0
  44. package/gsd-core/bin/lib/loop-host-contract.cjs +105 -0
  45. package/gsd-core/bin/lib/loop-resolver.cjs +460 -0
  46. package/gsd-core/bin/lib/model-resolver.cjs +426 -0
  47. package/gsd-core/bin/lib/phase-command-router.cjs +20 -0
  48. package/gsd-core/bin/lib/phase-id.cjs +215 -0
  49. package/gsd-core/bin/lib/phase-locator.cjs +148 -0
  50. package/gsd-core/bin/lib/phase.cjs +17 -0
  51. package/gsd-core/bin/lib/probe-core.cjs +257 -0
  52. package/gsd-core/bin/lib/profile-pipeline.cjs +2 -2
  53. package/gsd-core/bin/lib/roadmap-parser.cjs +443 -0
  54. package/gsd-core/bin/lib/roadmap.cjs +44 -1
  55. package/gsd-core/bin/lib/runtime-artifact-layout.cjs +92 -95
  56. package/gsd-core/bin/lib/runtime-config-adapter-registry.cjs +68 -29
  57. package/gsd-core/bin/lib/runtime-homes.cjs +163 -87
  58. package/gsd-core/bin/lib/runtime-hooks-surface.cjs +1439 -0
  59. package/gsd-core/bin/lib/runtime-name-policy.cjs +2 -1
  60. package/gsd-core/bin/lib/runtime-slash.cjs +7 -2
  61. package/gsd-core/bin/lib/shell-command-projection.cjs +13 -0
  62. package/gsd-core/bin/lib/state-document.cjs +8 -0
  63. package/gsd-core/bin/lib/state.cjs +114 -2
  64. package/gsd-core/bin/lib/surface.cjs +66 -14
  65. package/gsd-core/bin/lib/uat-predicate.cjs +329 -0
  66. package/gsd-core/bin/lib/update-context.cjs +4 -1
  67. package/gsd-core/bin/lib/verify.cjs +104 -1
  68. package/gsd-core/bin/lib/worktree-base-ref.cjs +33 -8
  69. package/gsd-core/bin/shared/model-catalog.json +11 -6
  70. package/gsd-core/bin/shared/runtime-aliases.manifest.json +5 -1
  71. package/gsd-core/references/edge-probe-fixtures/01-round-half-even/expected-coverage.json +7 -0
  72. package/gsd-core/references/edge-probe-fixtures/01-round-half-even/requirements.json +1 -0
  73. package/gsd-core/references/edge-probe-fixtures/02-merge-intervals/expected-coverage.json +8 -0
  74. package/gsd-core/references/edge-probe-fixtures/02-merge-intervals/requirements.json +1 -0
  75. package/gsd-core/references/edge-probe-fixtures/03-truncate-graphemes/expected-coverage.json +7 -0
  76. package/gsd-core/references/edge-probe-fixtures/03-truncate-graphemes/requirements.json +1 -0
  77. package/gsd-core/references/edge-probe-fixtures/04-money-rounding/expected-coverage.json +7 -0
  78. package/gsd-core/references/edge-probe-fixtures/04-money-rounding/requirements.json +1 -0
  79. package/gsd-core/references/edge-probe-fixtures/05-list-dedupe/expected-coverage.json +8 -0
  80. package/gsd-core/references/edge-probe-fixtures/05-list-dedupe/requirements.json +1 -0
  81. package/gsd-core/references/edge-probe-fixtures/06-resolved-mixed/expected-coverage.json +8 -0
  82. package/gsd-core/references/edge-probe-fixtures/06-resolved-mixed/requirements.json +1 -0
  83. package/gsd-core/references/edge-probe-fixtures/06-resolved-mixed/resolutions.json +4 -0
  84. package/gsd-core/references/edge-probe.md +261 -0
  85. package/gsd-core/references/planner-antipatterns.md +41 -0
  86. package/gsd-core/references/planner-guidance.md +186 -0
  87. package/gsd-core/references/planner-reviews.md +5 -2
  88. package/gsd-core/templates/phase-prompt.md +7 -7
  89. package/gsd-core/templates/project.md +19 -2
  90. package/gsd-core/templates/spec.md +12 -0
  91. package/gsd-core/templates/summary-complex.md +1 -0
  92. package/gsd-core/templates/summary-minimal.md +1 -0
  93. package/gsd-core/templates/summary-standard.md +1 -0
  94. package/gsd-core/templates/summary.md +1 -0
  95. package/gsd-core/workflows/_runtime-launcher.snippet.sh +1 -1
  96. package/gsd-core/workflows/add-backlog.md +1 -1
  97. package/gsd-core/workflows/add-phase.md +1 -1
  98. package/gsd-core/workflows/add-tests.md +1 -1
  99. package/gsd-core/workflows/add-todo.md +1 -1
  100. package/gsd-core/workflows/ai-integration-phase.md +1 -1
  101. package/gsd-core/workflows/audit-fix.md +1 -1
  102. package/gsd-core/workflows/audit-milestone.md +1 -1
  103. package/gsd-core/workflows/audit-uat.md +1 -1
  104. package/gsd-core/workflows/autonomous.md +111 -51
  105. package/gsd-core/workflows/check-todos.md +1 -1
  106. package/gsd-core/workflows/cleanup.md +1 -1
  107. package/gsd-core/workflows/code-review-fix.md +6 -4
  108. package/gsd-core/workflows/code-review.md +53 -17
  109. package/gsd-core/workflows/complete-milestone.md +11 -5
  110. package/gsd-core/workflows/debug.md +1 -1
  111. package/gsd-core/workflows/diagnose-issues.md +1 -1
  112. package/gsd-core/workflows/discuss-phase/modes/advisor.md +1 -1
  113. package/gsd-core/workflows/discuss-phase/modes/auto.md +1 -1
  114. package/gsd-core/workflows/discuss-phase/modes/chain.md +1 -1
  115. package/gsd-core/workflows/discuss-phase-assumptions.md +1 -1
  116. package/gsd-core/workflows/discuss-phase.md +8 -1
  117. package/gsd-core/workflows/do.md +1 -1
  118. package/gsd-core/workflows/docs-update.md +1 -1
  119. package/gsd-core/workflows/edit-phase.md +1 -1
  120. package/gsd-core/workflows/eval-review.md +4 -1
  121. package/gsd-core/workflows/execute-phase/steps/codebase-drift-gate.md +1 -1
  122. package/gsd-core/workflows/execute-phase/steps/post-merge-gate.md +1 -1
  123. package/gsd-core/workflows/execute-phase.md +8 -1
  124. package/gsd-core/workflows/execute-plan.md +1 -1
  125. package/gsd-core/workflows/explore.md +1 -1
  126. package/gsd-core/workflows/extract-learnings.md +1 -1
  127. package/gsd-core/workflows/forensics.md +1 -1
  128. package/gsd-core/workflows/graduation.md +1 -1
  129. package/gsd-core/workflows/health.md +1 -1
  130. package/gsd-core/workflows/help/modes/full.md +1 -1
  131. package/gsd-core/workflows/import.md +1 -1
  132. package/gsd-core/workflows/ingest-docs.md +1 -1
  133. package/gsd-core/workflows/insert-phase.md +1 -1
  134. package/gsd-core/workflows/list-workspaces.md +1 -1
  135. package/gsd-core/workflows/manager.md +1 -1
  136. package/gsd-core/workflows/map-codebase.md +1 -1
  137. package/gsd-core/workflows/milestone-summary.md +1 -1
  138. package/gsd-core/workflows/mvp-phase.md +1 -1
  139. package/gsd-core/workflows/new-milestone.md +9 -1
  140. package/gsd-core/workflows/new-project.md +9 -1
  141. package/gsd-core/workflows/new-workspace.md +1 -1
  142. package/gsd-core/workflows/next.md +1 -1
  143. package/gsd-core/workflows/pause-work.md +1 -1
  144. package/gsd-core/workflows/plan-milestone-gaps.md +1 -1
  145. package/gsd-core/workflows/plan-phase.md +65 -28
  146. package/gsd-core/workflows/plan-review-convergence.md +60 -33
  147. package/gsd-core/workflows/plant-seed.md +1 -1
  148. package/gsd-core/workflows/profile-user.md +1 -1
  149. package/gsd-core/workflows/progress.md +1 -1
  150. package/gsd-core/workflows/quick.md +2 -2
  151. package/gsd-core/workflows/remove-phase.md +1 -1
  152. package/gsd-core/workflows/remove-workspace.md +1 -1
  153. package/gsd-core/workflows/resume-project.md +1 -1
  154. package/gsd-core/workflows/review.md +1 -1
  155. package/gsd-core/workflows/scan.md +1 -1
  156. package/gsd-core/workflows/secure-phase.md +1 -1
  157. package/gsd-core/workflows/settings-advanced.md +7 -7
  158. package/gsd-core/workflows/settings-integrations.md +1 -1
  159. package/gsd-core/workflows/settings.md +2 -2
  160. package/gsd-core/workflows/ship.md +8 -1
  161. package/gsd-core/workflows/sketch-wrap-up.md +1 -1
  162. package/gsd-core/workflows/sketch.md +1 -1
  163. package/gsd-core/workflows/spec-phase.md +130 -1
  164. package/gsd-core/workflows/spike-wrap-up.md +1 -1
  165. package/gsd-core/workflows/spike.md +1 -1
  166. package/gsd-core/workflows/stats.md +1 -1
  167. package/gsd-core/workflows/thread.md +1 -1
  168. package/gsd-core/workflows/transition.md +1 -1
  169. package/gsd-core/workflows/ui-phase.md +1 -1
  170. package/gsd-core/workflows/ui-review.md +1 -1
  171. package/gsd-core/workflows/ultraplan-phase.md +1 -1
  172. package/gsd-core/workflows/update.md +2 -2
  173. package/gsd-core/workflows/validate-phase.md +1 -1
  174. package/gsd-core/workflows/verify-phase.md +1 -1
  175. package/gsd-core/workflows/verify-work.md +8 -1
  176. package/package.json +11 -3
  177. package/scripts/base64-scan.sh +1 -1
  178. package/scripts/changeset/cli.cjs +8 -1
  179. package/scripts/changeset/lint.cjs +38 -2
  180. package/scripts/ci-test-scope.cjs +21 -10
  181. package/scripts/gen-capability-registry.cjs +2293 -0
  182. package/scripts/gen-loop-host-contract.cjs +471 -0
  183. package/scripts/lib/allowlist-ratchet.cjs +101 -1
  184. package/scripts/lint-regression-test-names.allowlist.json +269 -0
  185. package/scripts/lint-regression-test-names.cjs +117 -0
  186. package/scripts/lint-test-file-count.allowlist.json +25 -4
  187. package/scripts/lint-windows-test-portability.cjs +178 -0
  188. package/scripts/prompt-injection-scan.sh +4 -4
  189. package/scripts/research-profiles.cjs +10 -10
  190. package/scripts/run-tests.cjs +133 -29
  191. package/scripts/secret-scan.sh +3 -3
  192. package/scripts/sync-next-version.cjs +133 -0
  193. package/scripts/sync-runtime-launcher.cjs +21 -5
  194. package/scripts/update-size-baseline.cjs +68 -0
  195. package/scripts/workflow-policy.cjs +42 -9
  196. package/scripts/workflow-size.cjs +90 -0
  197. package/scripts/run-cross-platform-tests.cjs +0 -67
@@ -0,0 +1,336 @@
1
+ "use strict";
2
+ /**
3
+ * Capability State Resolver — ADR-857 phase 4b
4
+ *
5
+ * Unified capability-state resolver that composes the three toggle systems
6
+ * (install profile, runtime surface, config activation) into one per-capability
7
+ * view. ADDITIVE — install/surface/workflows are untouched; this resolver is
8
+ * consumed by nothing yet (phase-6 wiring is out of scope).
9
+ *
10
+ * Exports (three things, mirroring loop-resolver):
11
+ * resolveCapabilityState({ registry, installedSkills, surfacedSkills, config, cwd })
12
+ * → { capabilities: CapabilityStateEntry[] }
13
+ * cmdCapabilityState(cwd, runtimeConfigDir, raw, options) — I/O entry point
14
+ *
15
+ * resolveCapabilityState is DETERMINISTIC given (registry, installedSkills,
16
+ * surfacedSkills, config) and — when `cwd` is provided — the project config
17
+ * files at `cwd` (.planning/config.json etc). Pass `cwd: undefined` for a
18
+ * pure, config-only resolution with no filesystem I/O.
19
+ * cmdCapabilityState is the I/O handler.
20
+ *
21
+ * Dependencies (leaf modules only — no core.cjs circular risk):
22
+ * - node:path (used by _resolveActivationValue via loop-resolver)
23
+ * - ./core.cjs (output, error)
24
+ * - ./loop-resolver.cjs (_resolveActivationValue — reuse the export)
25
+ * - ./install-profiles.cjs (readActiveProfile, loadSkillsManifest, resolveProfile)
26
+ * - ./surface.cjs (resolveSurface)
27
+ * - ./config-loader.cjs (loadConfig)
28
+ * - ./runtime-homes.cjs (getGlobalConfigDir — for runtimeConfigDir auto-detection)
29
+ * - capability-registry.cjs (loaded at call time)
30
+ */
31
+ var __importDefault = (this && this.__importDefault) || function (mod) {
32
+ return (mod && mod.__esModule) ? mod : { "default": mod };
33
+ };
34
+ const node_path_1 = __importDefault(require("node:path"));
35
+ // eslint-disable-next-line @typescript-eslint/no-require-imports
36
+ const core = require("./core.cjs");
37
+ const { output: coreOutput, error: coreError } = core;
38
+ // eslint-disable-next-line @typescript-eslint/no-require-imports
39
+ const loopResolverMod = require("./loop-resolver.cjs");
40
+ const { _resolveActivationValue } = loopResolverMod;
41
+ // eslint-disable-next-line @typescript-eslint/no-require-imports
42
+ const configLoaderMod = require("./config-loader.cjs");
43
+ const { loadConfig } = configLoaderMod;
44
+ // eslint-disable-next-line @typescript-eslint/no-require-imports
45
+ const installProfilesMod = require("./install-profiles.cjs");
46
+ const { readActiveProfile, loadSkillsManifest, resolveProfile } = installProfilesMod;
47
+ // eslint-disable-next-line @typescript-eslint/no-require-imports
48
+ const surfaceMod = require("./surface.cjs");
49
+ const { resolveSurface } = surfaceMod;
50
+ // ─── Prototype-pollution guard (inline literal, CodeQL barrier) ───────────────
51
+ function _isSafePropKey(key) {
52
+ // Inline literal guards — CodeQL barrier pattern
53
+ if (typeof key !== 'string')
54
+ return false;
55
+ if (key === '__proto__')
56
+ return false;
57
+ if (key === 'constructor')
58
+ return false;
59
+ if (key === 'prototype')
60
+ return false;
61
+ return true;
62
+ }
63
+ // ─── Pure resolver ─────────────────────────────────────────────────────────────
64
+ /**
65
+ * Deterministic resolver: for each capability in the registry, produce the
66
+ * three-dimension state view:
67
+ * 1. installed — does the install profile cover this capability?
68
+ * 2. surfaced — does the runtime surface enable this capability?
69
+ * 3. hooks — per-hook activation derived from config `when` keys.
70
+ *
71
+ * Determinism contract: given the same (registry, installedSkills,
72
+ * surfacedSkills, config) and — when `cwd` is set — the same project config
73
+ * files at `cwd`, the output is identical across calls. Pass `cwd: undefined`
74
+ * for a pure, config-only resolution with no filesystem I/O.
75
+ *
76
+ * Never throws for malformed registry/hook entries — skips/defaults defensively.
77
+ * An empty or missing capabilities object → { capabilities: [] }.
78
+ *
79
+ * @param input.registry The capability-registry.cjs module export.
80
+ * @param input.installedSkills Set<string> | '*' — from resolveProfile().skills.
81
+ * @param input.surfacedSkills Set<string> — from resolveSurface().skills.
82
+ * @param input.config Record from loadConfig(cwd).
83
+ * @param input.cwd Optional; when provided, enables raw .planning/config.json
84
+ * fallback reads (levels 2+3 of _resolveActivationValue
85
+ * precedence). Omit for a pure in-memory resolution.
86
+ */
87
+ function resolveCapabilityState(input) {
88
+ const { registry, installedSkills, surfacedSkills, config, cwd } = input;
89
+ // Guard: registry missing capabilities
90
+ if (!registry || typeof registry !== 'object' || Array.isArray(registry)) {
91
+ return { capabilities: [] };
92
+ }
93
+ const capabilitiesRaw = registry['capabilities'];
94
+ if (!capabilitiesRaw || typeof capabilitiesRaw !== 'object' || Array.isArray(capabilitiesRaw)) {
95
+ return { capabilities: [] };
96
+ }
97
+ const capabilitiesMap = capabilitiesRaw;
98
+ const results = [];
99
+ for (const capId of Object.keys(capabilitiesMap)) {
100
+ // Prototype-pollution guard on capability id
101
+ if (!_isSafePropKey(capId))
102
+ continue;
103
+ const cap = capabilitiesMap[capId];
104
+ if (!cap || typeof cap !== 'object' || Array.isArray(cap))
105
+ continue;
106
+ const capObj = cap;
107
+ // Extract tier
108
+ const tier = typeof capObj['tier'] === 'string' ? capObj['tier'] : 'unknown';
109
+ // Extract skills array
110
+ const skillsRaw = capObj['skills'];
111
+ const skills = Array.isArray(skillsRaw)
112
+ ? skillsRaw.filter((s) => typeof s === 'string')
113
+ : [];
114
+ // ── installed ──────────────────────────────────────────────────────────────
115
+ // Empty-skills cap → vacuously installed (no skills to be absent).
116
+ // installedSkills === '*' → installed = true for every cap.
117
+ let installed;
118
+ if (installedSkills === '*') {
119
+ installed = true;
120
+ }
121
+ else if (skills.length === 0) {
122
+ installed = true; // vacuous: no skills required
123
+ }
124
+ else {
125
+ installed = skills.every((s) => installedSkills.has(s));
126
+ }
127
+ // ── surfaced ───────────────────────────────────────────────────────────────
128
+ // Empty-skills cap → vacuously surfaced.
129
+ let surfaced;
130
+ if (skills.length === 0) {
131
+ surfaced = true; // vacuous
132
+ }
133
+ else {
134
+ surfaced = skills.every((s) => surfacedSkills.has(s));
135
+ }
136
+ // ── hooks ──────────────────────────────────────────────────────────────────
137
+ // Collect from steps, gates, contributions. Each may have a `when` key.
138
+ // Activation semantics (mirrors loop-resolver.isActive exactly):
139
+ // - No `when` field present (undefined/null) → unconditional, active=true
140
+ // - Non-empty string `when` → resolve via _resolveActivationValue
141
+ // - Present-but-empty-string or non-string `when` → malformed, active=false
142
+ // The original `when` value is carried through to the output for visibility.
143
+ const hooks = [];
144
+ function processHooks(arr, kind) {
145
+ for (const hookRaw of arr) {
146
+ if (!hookRaw || typeof hookRaw !== 'object' || Array.isArray(hookRaw))
147
+ continue;
148
+ const h = hookRaw;
149
+ const point = typeof h['point'] === 'string' ? h['point'] : '';
150
+ // Carry the raw `when` value through for visibility
151
+ const whenRaw = h['when'];
152
+ let active;
153
+ if (whenRaw === undefined || whenRaw === null) {
154
+ // No `when` field → unconditional, always active
155
+ active = true;
156
+ }
157
+ else if (typeof whenRaw === 'string' && whenRaw.length > 0) {
158
+ // Non-empty string `when` → resolve via _resolveActivationValue
159
+ active = _resolveActivationValue(whenRaw, config, cwd, registry);
160
+ }
161
+ else {
162
+ // Present-but-empty-string or non-string `when` → malformed, inactive
163
+ // (mirrors loop-resolver.isActive: `typeof when !== 'string' || when.length === 0` → false)
164
+ active = false;
165
+ }
166
+ hooks.push({ point, kind, when: whenRaw, active });
167
+ }
168
+ }
169
+ const stepsRaw = capObj['steps'];
170
+ const gatesRaw = capObj['gates'];
171
+ const contributionsRaw = capObj['contributions'];
172
+ processHooks(Array.isArray(stepsRaw) ? stepsRaw : [], 'step');
173
+ processHooks(Array.isArray(gatesRaw) ? gatesRaw : [], 'gate');
174
+ processHooks(Array.isArray(contributionsRaw) ? contributionsRaw : [], 'contribution');
175
+ results.push({ id: capId, tier, skills, installed, surfaced, hooks });
176
+ }
177
+ // Deterministic sort by id for stable output across calls
178
+ results.sort((a, b) => a.id < b.id ? -1 : a.id > b.id ? 1 : 0);
179
+ return { capabilities: results };
180
+ }
181
+ // ─── I/O command handler ───────────────────────────────────────────────────────
182
+ /**
183
+ * Derive the commands/gsd path from __dirname (which resolves to
184
+ * gsd-core/bin/lib/ at runtime). The source tree is:
185
+ * <repo>/gsd-core/bin/lib/capability-state.cjs
186
+ * <repo>/commands/gsd/*.md
187
+ * So we walk up three levels: lib/ → bin/ → gsd-core/ → <repo>/, then
188
+ * into commands/gsd/.
189
+ */
190
+ function _resolveCommandsGsdDir() {
191
+ // __dirname = gsd-core/bin/lib/
192
+ const repoRoot = node_path_1.default.resolve(__dirname, '..', '..', '..');
193
+ return node_path_1.default.join(repoRoot, 'commands', 'gsd');
194
+ }
195
+ /**
196
+ * Command entry point: resolve install profile, surface, and config; compute
197
+ * capability state; emit the envelope via core.output.
198
+ *
199
+ * Envelope: { runtimeConfigDir, warnings?: string[], capabilities: CapabilityStateEntry[] }
200
+ *
201
+ * runtimeConfigDir resolution (when not provided or empty):
202
+ * Uses the canonical getGlobalConfigDir from runtime-homes.cjs to detect the
203
+ * active runtime's config dir — the same resolver used by install.js. This
204
+ * correctly handles all supported runtimes (claude, codex, cursor, gemini,
205
+ * opencode, grok, etc.) and their env-var overrides. Defaults to claude
206
+ * (falls back to ~/.claude) if the resolver throws.
207
+ *
208
+ * Failure surfacing: genuine resolution failures (manifest/profile/surface
209
+ * errors) are reported in the `warnings` array in the envelope. The output
210
+ * remains useful — degraded to the best available state — but the caller can
211
+ * detect that the state is not fully resolved.
212
+ *
213
+ * Legitimate "no marker → default full profile" is NOT a warning.
214
+ * A thrown error during profile/surface resolution IS a warning.
215
+ *
216
+ * @param cwd Project root directory
217
+ * @param runtimeConfigDir Runtime config directory (e.g. ~/.claude). May be
218
+ * empty/undefined — falls back to auto-detection.
219
+ * Providing a value without a next token (e.g. the flag
220
+ * is last in argv with no following value) should be
221
+ * caught by the caller before invoking this function.
222
+ * @param raw Whether to emit raw JSON (core.output raw mode)
223
+ * @param _options Reserved for future use
224
+ */
225
+ function cmdCapabilityState(cwd, runtimeConfigDir, raw, _options = {}) {
226
+ const warnings = [];
227
+ // Resolve runtimeConfigDir using the canonical runtime-homes resolver.
228
+ // When not provided, getGlobalConfigDir(runtime) is called with 'claude'
229
+ // as the default runtime — the same fallback as install.js. The canonical
230
+ // resolver handles all env-var overrides (CLAUDE_CONFIG_DIR, CODEX_HOME,
231
+ // CURSOR_CONFIG_DIR, GROK_AGENTS_HOME, etc.) correctly and without
232
+ // fabricating env vars that don't exist upstream.
233
+ let resolvedConfigDir = runtimeConfigDir || '';
234
+ if (!resolvedConfigDir) {
235
+ try {
236
+ // eslint-disable-next-line @typescript-eslint/no-require-imports
237
+ const runtimeHomes = require('./runtime-homes.cjs');
238
+ // Delegate runtime detection entirely to getGlobalConfigDir: calling it
239
+ // with 'claude' causes it to check CLAUDE_CONFIG_DIR first, falling back
240
+ // to ~/.claude. The canonical resolver already encodes the correct env-var
241
+ // precedence for each runtime — we do not re-implement that logic here.
242
+ // For non-claude runtimes, the caller should pass --config-dir explicitly
243
+ // (or set the runtime-specific env var, which getGlobalConfigDir honors).
244
+ resolvedConfigDir = runtimeHomes.getGlobalConfigDir('claude');
245
+ }
246
+ catch {
247
+ // Defensive fallback: use ~/.claude if the canonical resolver throws.
248
+ // eslint-disable-next-line @typescript-eslint/no-require-imports
249
+ const os = require('node:os');
250
+ resolvedConfigDir = node_path_1.default.join(os.homedir(), '.claude');
251
+ }
252
+ }
253
+ // ── Load registry (ADR-857 phase 4c) ────────────────────────────────────────
254
+ // Load BEFORE resolveProfile and resolveSurface so both calls receive the
255
+ // registry and capability-contributed skills are reflected in installed/surfaced.
256
+ // No-op today (UI capability is tier:full → only adds to 'full', which returns
257
+ // '*' regardless) but cutover-ready for future tier:core/standard capabilities.
258
+ // eslint-disable-next-line @typescript-eslint/no-require-imports
259
+ const registry = require('./capability-registry.cjs');
260
+ // ── Resolve installed skills (from install profile) ──────────────────────────
261
+ // Distinguish "no profile marker → default full" (legitimate) from a thrown
262
+ // error (surface as a warning and degrade gracefully — do NOT silently report
263
+ // installedSkills='*' as if the install profile were truly unlimited).
264
+ let installedSkills;
265
+ try {
266
+ const commandsGsdDir = _resolveCommandsGsdDir();
267
+ const manifest = loadSkillsManifest(commandsGsdDir);
268
+ const profileName = readActiveProfile(resolvedConfigDir) ?? 'full';
269
+ const resolvedInstall = resolveProfile({
270
+ modes: profileName.split(',').map((s) => s.trim()),
271
+ manifest,
272
+ registry,
273
+ });
274
+ installedSkills = resolvedInstall.skills;
275
+ }
276
+ catch (err) {
277
+ // Genuine resolution failure — surface it so the caller is not misled.
278
+ const msg = err instanceof Error ? err.message : String(err);
279
+ warnings.push(`profile-resolution failed: ${msg}`);
280
+ coreError(`capability state: profile resolution failed: ${msg}`);
281
+ // Degrade to empty set (not '*') so installed=false is reported accurately.
282
+ installedSkills = new Set();
283
+ }
284
+ // ── Resolve surfaced skills (from runtime surface) ────────────────────────────
285
+ let surfacedSkills;
286
+ try {
287
+ const commandsGsdDir = _resolveCommandsGsdDir();
288
+ const manifest = loadSkillsManifest(commandsGsdDir);
289
+ const surfaceResult = resolveSurface(resolvedConfigDir, manifest, undefined, registry);
290
+ // resolveSurface returns { name, skills: Set<string>, agents: Set<string> }
291
+ // (always a concrete Set — full profile is materialized)
292
+ surfacedSkills = surfaceResult.skills instanceof Set
293
+ ? surfaceResult.skills
294
+ : new Set();
295
+ }
296
+ catch (err) {
297
+ // Genuine surface resolution failure — surface it so the caller is not misled.
298
+ const msg = err instanceof Error ? err.message : String(err);
299
+ warnings.push(`surface-resolution failed: ${msg}`);
300
+ coreError(`capability state: surface resolution failed: ${msg}`);
301
+ surfacedSkills = new Set();
302
+ }
303
+ // ── Load config ───────────────────────────────────────────────────────────────
304
+ let config;
305
+ try {
306
+ config = loadConfig(cwd);
307
+ }
308
+ catch {
309
+ config = {};
310
+ }
311
+ // ── Resolve state ────────────────────────────────────────────────────────────
312
+ const result = resolveCapabilityState({
313
+ registry,
314
+ installedSkills,
315
+ surfacedSkills,
316
+ config,
317
+ cwd,
318
+ });
319
+ // Build envelope — include warnings array only when non-empty so the nominal
320
+ // path keeps the output clean and callers can check `warnings` for degraded state.
321
+ const envelope = {
322
+ runtimeConfigDir: resolvedConfigDir,
323
+ capabilities: result.capabilities,
324
+ };
325
+ if (warnings.length > 0) {
326
+ envelope.warnings = warnings;
327
+ }
328
+ coreOutput(envelope, raw);
329
+ }
330
+ module.exports = {
331
+ resolveCapabilityState,
332
+ cmdCapabilityState,
333
+ // Exported for tests
334
+ _resolveCommandsGsdDir,
335
+ _isSafePropKey,
336
+ };
@@ -16,6 +16,10 @@ const node_child_process_1 = require("node:child_process");
16
16
  const core = require("./core.cjs");
17
17
  const { output, error, ERROR_REASON } = core;
18
18
  const decisions_cjs_1 = require("./decisions.cjs");
19
+ const ui_safety_gate_cjs_1 = require("./ui-safety-gate.cjs");
20
+ // eslint-disable-next-line @typescript-eslint/no-require-imports
21
+ const roadmapModule = require("./roadmap.cjs");
22
+ const { getRoadmapPhaseWithFallback } = roadmapModule;
19
23
  // ─── Helpers ──────────────────────────────────────────────────────────────────
20
24
  function normalizePhrase(text) {
21
25
  // eslint-disable-next-line @typescript-eslint/no-base-to-string
@@ -320,8 +324,130 @@ function cmdDecisionCoverageVerify(projectDir, args, raw) {
320
324
  message: buildVerifyMessage(notHonored),
321
325
  }, raw, undefined);
322
326
  }
327
+ // ─── ui-plan-gate ─────────────────────────────────────────────────────────────
328
+ /**
329
+ * ui-plan-gate: given a phase number, checks whether the phase has frontend
330
+ * indicators and whether a *-UI-SPEC.md already exists in the phase directory.
331
+ *
332
+ * Returns JSON: { frontend: boolean, hasUiSpec: boolean, block: boolean }
333
+ * block = frontend && !hasUiSpec (gate fires when UI work is detected but no spec exists)
334
+ *
335
+ * Invocable as: gsd_run check ui-plan-gate <phase>
336
+ *
337
+ * Uses checkUiPresence from ui-safety-gate.cjs — does NOT reimplement frontend detection.
338
+ * Uses getRoadmapPhaseInternal + findPhaseInternal from core.cjs for phase data.
339
+ */
340
+ function findUiSpecInDir(phaseDir) {
341
+ if (!phaseDir || !node_fs_1.default.existsSync(phaseDir))
342
+ return '';
343
+ try {
344
+ const files = node_fs_1.default.readdirSync(phaseDir);
345
+ const found = files.find((f) => /-UI-SPEC\.md$/.test(f));
346
+ return found ? node_path_1.default.join(phaseDir, found) : '';
347
+ }
348
+ catch {
349
+ return '';
350
+ }
351
+ }
352
+ /**
353
+ * Pure logic for ui-plan-gate — exposed for direct behavioral testing.
354
+ *
355
+ * Given a projectDir and phase number:
356
+ * (a) Reads the phase section from ROADMAP.md via getRoadmapPhaseWithFallback —
357
+ * same two-pass lookup (current milestone → full roadmap) as `roadmap.get-phase`
358
+ * (cmdRoadmapGetPhase). Cross-milestone / older frontend phases resolve correctly.
359
+ * If ROADMAP.md is missing, phaseSection is '' (ROADMAP.md not present = project
360
+ * has no roadmap = cannot be frontend). If the phase truly can't be found after
361
+ * both passes, phaseSection is '' and phaseLookupFailed is set so callers can
362
+ * surface the miss — we do NOT silently degrade to frontend:false if the roadmap
363
+ * exists but the phase header is absent.
364
+ * (b) Runs checkUiPresence (frontend detection) — no reimplementation.
365
+ * (c) Resolves the phase directory via core.findPhaseInternal; checks for *-UI-SPEC.md.
366
+ *
367
+ * Returns: { frontend, hasUiSpec, block, uiSpecPath, phaseLookupFailed }
368
+ * block = frontend && !hasUiSpec
369
+ * phaseLookupFailed = ROADMAP.md present but phase header not found (surfaced for
370
+ * onError:halt gates so a missing phase doesn't silently bypass)
371
+ */
372
+ function computeUiPlanGate(projectDir, phase) {
373
+ // (a) Read the phase section text using the same two-pass lookup as roadmap.get-phase.
374
+ // getRoadmapPhaseWithFallback: current-milestone first, then stripShippedMilestones
375
+ // fallback — mirrors cmdRoadmapGetPhase exactly.
376
+ let phaseSection = '';
377
+ let phaseLookupFailed;
378
+ try {
379
+ const section = getRoadmapPhaseWithFallback(projectDir, phase);
380
+ if (section === null) {
381
+ // Distinguish: ROADMAP.md missing (no-roadmap project) vs phase not found in ROADMAP.
382
+ // core.planningDir(cwd) resolves the .planning/ root for workstream-aware paths.
383
+ const planDir = typeof core['planningDir'] === 'function'
384
+ ? core['planningDir'](projectDir)
385
+ : node_path_1.default.join(projectDir, '.planning');
386
+ const roadmapPath = node_path_1.default.join(planDir, 'ROADMAP.md');
387
+ if (node_fs_1.default.existsSync(roadmapPath)) {
388
+ // ROADMAP.md exists but phase was not found → surface the miss
389
+ phaseLookupFailed = true;
390
+ }
391
+ // phaseSection stays ''
392
+ }
393
+ else {
394
+ phaseSection = section;
395
+ }
396
+ }
397
+ catch { /* roadmap read failure → treat as empty (non-frontend) */ }
398
+ // (b) Run checkUiPresence (frontend detection) — reuse existing helper; no reimplementation
399
+ const presenceResult = (0, ui_safety_gate_cjs_1.checkUiPresence)(phaseSection);
400
+ const frontend = presenceResult.hasUI;
401
+ // (c) Resolve phase directory via findPhaseInternal and check for *-UI-SPEC.md
402
+ const coreModule = core;
403
+ let phaseDir = '';
404
+ try {
405
+ const findPhase = coreModule['findPhaseInternal'];
406
+ if (typeof findPhase === 'function') {
407
+ const result = findPhase(projectDir, phase);
408
+ if (result && typeof result === 'object') {
409
+ // findPhaseInternal returns { directory: '<relative-posix-path>', ... }
410
+ // directory is relative to cwd — resolve it to absolute.
411
+ const relDir = typeof result['directory'] === 'string' ? result['directory'] : '';
412
+ if (relDir) {
413
+ phaseDir = node_path_1.default.resolve(projectDir, relDir);
414
+ }
415
+ }
416
+ else if (typeof result === 'string') {
417
+ phaseDir = result;
418
+ }
419
+ }
420
+ }
421
+ catch { /* phase dir lookup failure → hasUiSpec=false */ }
422
+ const uiSpecPath = findUiSpecInDir(phaseDir);
423
+ const hasUiSpec = uiSpecPath !== '';
424
+ // block = frontend phase with no UI-SPEC
425
+ const block = frontend && !hasUiSpec;
426
+ const result = {
427
+ frontend, hasUiSpec, block, uiSpecPath: hasUiSpec ? uiSpecPath : null,
428
+ };
429
+ if (phaseLookupFailed)
430
+ result.phaseLookupFailed = true;
431
+ return result;
432
+ }
433
+ function cmdUiPlanGate(projectDir, args, raw) {
434
+ // args[0] = 'check', args[1] = 'ui-plan-gate', args[2] = phase
435
+ const phase = args[2] || '';
436
+ if (!phase) {
437
+ error('ui-plan-gate requires a phase argument: check ui-plan-gate <phase>', ERROR_REASON.SDK_MISSING_ARG);
438
+ return;
439
+ }
440
+ output(computeUiPlanGate(projectDir, phase), raw, undefined);
441
+ }
323
442
  function routeCheckCommand({ args, cwd, raw }) {
324
- const subcommand = args[1];
443
+ // Normalize dots to hyphens in the subcommand so both forms are accepted.
444
+ // This makes `check.query = "ui.plan-gate"` (dotted form in capability.json gates)
445
+ // directly runnable as `gsd_run check ui.plan-gate` — the dot is normalized to
446
+ // `ui-plan-gate` before routing. The generic gate-dispatch in §5.6 reads
447
+ // `check.query` from the active gate hook and runs `gsd_run check ${hook.check.query}`,
448
+ // so the declared query must be dispatchable exactly as declared.
449
+ const rawSubcommand = args[1];
450
+ const subcommand = typeof rawSubcommand === 'string' ? rawSubcommand.replace(/\./g, '-') : rawSubcommand;
325
451
  if (subcommand === 'auto-mode') {
326
452
  cmdAutoMode(cwd, raw);
327
453
  return;
@@ -334,10 +460,15 @@ function routeCheckCommand({ args, cwd, raw }) {
334
460
  cmdDecisionCoverageVerify(cwd, args, raw);
335
461
  return;
336
462
  }
337
- error('Unknown check subcommand. Available: auto-mode, decision-coverage-plan, decision-coverage-verify', ERROR_REASON.SDK_UNKNOWN_COMMAND);
463
+ if (subcommand === 'ui-plan-gate') {
464
+ cmdUiPlanGate(cwd, args, raw);
465
+ return;
466
+ }
467
+ error('Unknown check subcommand. Available: auto-mode, decision-coverage-plan, decision-coverage-verify, ui-plan-gate', ERROR_REASON.SDK_UNKNOWN_COMMAND);
338
468
  }
339
469
  module.exports = {
340
470
  routeCheckCommand,
341
471
  decisionMentioned,
342
472
  extractPlanDesignatedSections,
473
+ computeUiPlanGate,
343
474
  };
@@ -1,4 +1,11 @@
1
1
  "use strict";
2
+ var __importDefault = (this && this.__importDefault) || function (mod) {
3
+ return (mod && mod.__esModule) ? mod : { "default": mod };
4
+ };
5
+ const node_fs_1 = __importDefault(require("node:fs"));
6
+ // eslint-disable-next-line @typescript-eslint/no-require-imports
7
+ const ioModule = require("./io.cjs");
8
+ const { getJsonErrorMode, ERROR_REASON } = ioModule;
2
9
  /**
3
10
  * Error carrying a process exit code. CLI logic throws this instead of calling
4
11
  * process.exit() (banned by n/no-process-exit); runMain() translates it into
@@ -20,7 +27,8 @@ class ExitError extends Error {
20
27
  * process.on('exit') cleanup still fires). main may be sync or async:
21
28
  * number return -> process.exitCode = it
22
29
  * thrown ExitError -> process.exitCode = err.code (+ stderr err.message if hasUserMessage && code!=0)
23
- * other throw -> stderr stack + process.exitCode = 1
30
+ * other throw -> when json-error mode is active, emits structured { ok:false, reason, message }
31
+ * to stderr; otherwise writes raw stack trace. exit code = 1 in either case.
24
32
  */
25
33
  function runMain(main) {
26
34
  Promise.resolve()
@@ -34,8 +42,19 @@ function runMain(main) {
34
42
  process.exitCode = err.code;
35
43
  return;
36
44
  }
37
- const e = err;
38
- process.stderr.write(`${e && e.stack ? e.stack : String(err)}\n`);
45
+ if (getJsonErrorMode()) {
46
+ const e = err;
47
+ const payload = JSON.stringify({
48
+ ok: false,
49
+ reason: ERROR_REASON.SDK_FAIL_FAST,
50
+ message: (e && e.message) ? e.message : String(err),
51
+ }) + '\n';
52
+ node_fs_1.default.writeSync(2, payload);
53
+ }
54
+ else {
55
+ const e = err;
56
+ process.stderr.write(`${e && e.stack ? e.stack : String(err)}\n`);
57
+ }
39
58
  process.exitCode = 1;
40
59
  });
41
60
  }