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

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 (131) hide show
  1. package/.claude-plugin/plugin.json +1 -1
  2. package/agents/gsd-advisor-researcher.md +1 -1
  3. package/agents/gsd-assumptions-analyzer.md +1 -1
  4. package/agents/gsd-code-fixer.md +1 -1
  5. package/agents/gsd-code-reviewer.md +1 -1
  6. package/agents/gsd-codebase-mapper.md +1 -1
  7. package/agents/gsd-debugger.md +1 -1
  8. package/agents/gsd-doc-writer.md +1 -1
  9. package/agents/gsd-eval-auditor.md +1 -1
  10. package/agents/gsd-executor.md +1 -1
  11. package/agents/gsd-integration-checker.md +1 -1
  12. package/agents/gsd-mempalace-curator.md +47 -0
  13. package/agents/gsd-nyquist-auditor.md +1 -0
  14. package/agents/gsd-phase-researcher.md +1 -1
  15. package/agents/gsd-plan-checker.md +1 -1
  16. package/agents/gsd-planner.md +1 -1
  17. package/agents/gsd-project-researcher.md +1 -1
  18. package/agents/gsd-research-synthesizer.md +1 -1
  19. package/agents/gsd-roadmapper.md +55 -2
  20. package/agents/gsd-security-auditor.md +1 -0
  21. package/agents/gsd-ui-auditor.md +1 -1
  22. package/agents/gsd-ui-checker.md +1 -1
  23. package/agents/gsd-ui-researcher.md +1 -1
  24. package/agents/gsd-verifier.md +13 -2
  25. package/bin/install.js +61 -64
  26. package/commands/gsd/mempalace-capture.md +71 -0
  27. package/commands/gsd/mempalace-recall.md +102 -0
  28. package/commands/gsd/ns-context.md +4 -2
  29. package/commands/gsd/progress.md +2 -1
  30. package/gemini-extension.json +1 -1
  31. package/gsd-core/bin/gsd-tools.cjs +277 -95
  32. package/gsd-core/bin/lib/active-workstream-store.cjs +6 -0
  33. package/gsd-core/bin/lib/capability-activation.cjs +86 -0
  34. package/gsd-core/bin/lib/capability-registry.cjs +1468 -11
  35. package/gsd-core/bin/lib/capability-state.cjs +128 -21
  36. package/gsd-core/bin/lib/capability-writer.cjs +354 -0
  37. package/gsd-core/bin/lib/check-command-router.cjs +328 -1
  38. package/gsd-core/bin/lib/clusters.cjs +2 -0
  39. package/gsd-core/bin/lib/command-roster.cjs +19 -0
  40. package/gsd-core/bin/lib/commands.cjs +33 -10
  41. package/gsd-core/bin/lib/config-loader.cjs +7 -8
  42. package/gsd-core/bin/lib/config-schema.cjs +32 -3
  43. package/gsd-core/bin/lib/config.cjs +81 -26
  44. package/gsd-core/bin/lib/core.cjs +5 -2
  45. package/gsd-core/bin/lib/edge-probe.cjs +25 -2
  46. package/gsd-core/bin/lib/frontmatter.cjs +53 -1
  47. package/gsd-core/bin/lib/git-base-branch.cjs +194 -0
  48. package/gsd-core/bin/lib/init.cjs +36 -11
  49. package/gsd-core/bin/lib/install-profiles.cjs +57 -1
  50. package/gsd-core/bin/lib/installer-migration-report.cjs +1 -0
  51. package/gsd-core/bin/lib/loop-resolver.cjs +157 -16
  52. package/gsd-core/bin/lib/model-resolver.cjs +47 -5
  53. package/gsd-core/bin/lib/phase.cjs +99 -23
  54. package/gsd-core/bin/lib/plan-drift-guard.cjs +117 -0
  55. package/gsd-core/bin/lib/probe-core.cjs +117 -1
  56. package/gsd-core/bin/lib/profile-output.cjs +45 -4
  57. package/gsd-core/bin/lib/profile-pipeline-command-router.cjs +138 -0
  58. package/gsd-core/bin/lib/roadmap-parser.cjs +13 -3
  59. package/gsd-core/bin/lib/roadmap.cjs +97 -7
  60. package/gsd-core/bin/lib/runtime-artifact-conversion.cjs +1946 -0
  61. package/gsd-core/bin/lib/runtime-artifact-layout.cjs +54 -30
  62. package/gsd-core/bin/lib/runtime-config-adapter-registry.cjs +27 -19
  63. package/gsd-core/bin/lib/runtime-homes.cjs +26 -20
  64. package/gsd-core/bin/lib/state-command-router.cjs +15 -3
  65. package/gsd-core/bin/lib/state-document.cjs +46 -1
  66. package/gsd-core/bin/lib/state.cjs +461 -94
  67. package/gsd-core/bin/lib/verify.cjs +92 -8
  68. package/gsd-core/bin/lib/worktree-safety.cjs +2 -1
  69. package/gsd-core/bin/shared/config-defaults.manifest.json +1 -2
  70. package/gsd-core/bin/shared/config-schema.manifest.json +0 -18
  71. package/gsd-core/bin/shared/model-catalog.json +1 -0
  72. package/gsd-core/references/edge-probe.md +11 -0
  73. package/gsd-core/references/loop-hook-dispatch.md +61 -0
  74. package/gsd-core/references/prohibition-probe-fixtures/01-streak-reminder/expected.json +14 -0
  75. package/gsd-core/references/prohibition-probe-fixtures/02-clean-utility/expected.json +4 -0
  76. package/gsd-core/references/prohibition-probe-fixtures/03-multi-prohibition/expected.json +32 -0
  77. package/gsd-core/references/prohibition-probe.md +248 -0
  78. package/gsd-core/templates/config.json +1 -1
  79. package/gsd-core/templates/spec.md +14 -0
  80. package/gsd-core/workflows/audit-milestone.md +5 -3
  81. package/gsd-core/workflows/autonomous.md +10 -5
  82. package/gsd-core/workflows/code-review-fix.md +9 -7
  83. package/gsd-core/workflows/code-review.md +8 -6
  84. package/gsd-core/workflows/complete-milestone.md +1 -5
  85. package/gsd-core/workflows/discuss-phase.md +14 -0
  86. package/gsd-core/workflows/execute-phase.md +86 -146
  87. package/gsd-core/workflows/execute-plan.md +21 -6
  88. package/gsd-core/workflows/help/modes/full.md +7 -1
  89. package/gsd-core/workflows/new-project.md +3 -3
  90. package/gsd-core/workflows/next.md +50 -2
  91. package/gsd-core/workflows/pause-work.md +7 -1
  92. package/gsd-core/workflows/plan-phase.md +91 -221
  93. package/gsd-core/workflows/plan-review-convergence.md +14 -4
  94. package/gsd-core/workflows/pr-branch.md +4 -2
  95. package/gsd-core/workflows/profile-user.md +3 -1
  96. package/gsd-core/workflows/progress.md +58 -1
  97. package/gsd-core/workflows/quick.md +12 -8
  98. package/gsd-core/workflows/resume-project.md +17 -1
  99. package/gsd-core/workflows/review.md +19 -2
  100. package/gsd-core/workflows/secure-phase.md +4 -2
  101. package/gsd-core/workflows/settings-advanced.md +2 -0
  102. package/gsd-core/workflows/settings.md +27 -1
  103. package/gsd-core/workflows/ship.md +58 -5
  104. package/gsd-core/workflows/spec-phase.md +75 -0
  105. package/gsd-core/workflows/validate-phase.md +4 -2
  106. package/gsd-core/workflows/verify-phase.md +14 -4
  107. package/gsd-core/workflows/verify-work.md +27 -11
  108. package/hooks/dist/gsd-ensure-canonical-path.js +305 -0
  109. package/hooks/dist/gsd-statusline.js +1 -1
  110. package/hooks/dist/managed-hooks-registry.cjs +1 -0
  111. package/hooks/gsd-ensure-canonical-path.js +305 -0
  112. package/hooks/gsd-statusline.js +1 -1
  113. package/hooks/hooks.json +1 -0
  114. package/hooks/managed-hooks-registry.cjs +1 -0
  115. package/package.json +5 -4
  116. package/scripts/affected-tests-lib.cjs +16 -4
  117. package/scripts/build-hooks.js +7 -0
  118. package/scripts/changeset/new.cjs +17 -3
  119. package/scripts/fix-slash-commands.cjs +15 -3
  120. package/scripts/gen-capability-registry.cjs +373 -49
  121. package/scripts/gen-inventory-manifest.cjs +1 -4
  122. package/scripts/gen-loop-host-contract.cjs +55 -0
  123. package/scripts/issue-version-gate.cjs +140 -0
  124. package/scripts/lint-allow-test-rule-refs.allowlist.json +327 -0
  125. package/scripts/lint-allow-test-rule-refs.cjs +162 -0
  126. package/scripts/lint-test-file-count.allowlist.json +14 -0
  127. package/scripts/mutation-matrix.cjs +108 -7
  128. package/scripts/pr-target-policy.cjs +63 -0
  129. package/scripts/release-tarball-smoke.cjs +7 -1
  130. package/scripts/research-profiles.cjs +5 -5
  131. package/scripts/run-tests.cjs +178 -17
@@ -4,8 +4,8 @@
4
4
  *
5
5
  * Unified capability-state resolver that composes the three toggle systems
6
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).
7
+ * view. The loop resolver consumes this state so workflow dispatch and the
8
+ * `gsd-tools capability state` diagnostic share the same enablement answer.
9
9
  *
10
10
  * Exports (three things, mirroring loop-resolver):
11
11
  * resolveCapabilityState({ registry, installedSkills, surfacedSkills, config, cwd })
@@ -19,9 +19,9 @@
19
19
  * cmdCapabilityState is the I/O handler.
20
20
  *
21
21
  * Dependencies (leaf modules only — no core.cjs circular risk):
22
- * - node:path (used by _resolveActivationValue via loop-resolver)
22
+ * - node:path
23
23
  * - ./core.cjs (output, error)
24
- * - ./loop-resolver.cjs (_resolveActivationValue — reuse the export)
24
+ * - ./capability-activation.cjs (_resolveActivationValue)
25
25
  * - ./install-profiles.cjs (readActiveProfile, loadSkillsManifest, resolveProfile)
26
26
  * - ./surface.cjs (resolveSurface)
27
27
  * - ./config-loader.cjs (loadConfig)
@@ -32,18 +32,19 @@ var __importDefault = (this && this.__importDefault) || function (mod) {
32
32
  return (mod && mod.__esModule) ? mod : { "default": mod };
33
33
  };
34
34
  const node_path_1 = __importDefault(require("node:path"));
35
+ const node_fs_1 = __importDefault(require("node:fs"));
35
36
  // eslint-disable-next-line @typescript-eslint/no-require-imports
36
37
  const core = require("./core.cjs");
37
38
  const { output: coreOutput, error: coreError } = core;
38
39
  // eslint-disable-next-line @typescript-eslint/no-require-imports
39
- const loopResolverMod = require("./loop-resolver.cjs");
40
- const { _resolveActivationValue } = loopResolverMod;
40
+ const activationMod = require("./capability-activation.cjs");
41
+ const { _resolveActivationValue } = activationMod;
41
42
  // eslint-disable-next-line @typescript-eslint/no-require-imports
42
43
  const configLoaderMod = require("./config-loader.cjs");
43
44
  const { loadConfig } = configLoaderMod;
44
45
  // eslint-disable-next-line @typescript-eslint/no-require-imports
45
46
  const installProfilesMod = require("./install-profiles.cjs");
46
- const { readActiveProfile, loadSkillsManifest, resolveProfile } = installProfilesMod;
47
+ const { readActiveProfile, loadSkillsManifest, resolveProfile, parseRequires } = installProfilesMod;
47
48
  // eslint-disable-next-line @typescript-eslint/no-require-imports
48
49
  const surfaceMod = require("./surface.cjs");
49
50
  const { resolveSurface } = surfaceMod;
@@ -133,6 +134,7 @@ function resolveCapabilityState(input) {
133
134
  else {
134
135
  surfaced = skills.every((s) => surfacedSkills.has(s));
135
136
  }
137
+ const enabled = installed && surfaced;
136
138
  // ── hooks ──────────────────────────────────────────────────────────────────
137
139
  // Collect from steps, gates, contributions. Each may have a `when` key.
138
140
  // Activation semantics (mirrors loop-resolver.isActive exactly):
@@ -149,21 +151,21 @@ function resolveCapabilityState(input) {
149
151
  const point = typeof h['point'] === 'string' ? h['point'] : '';
150
152
  // Carry the raw `when` value through for visibility
151
153
  const whenRaw = h['when'];
152
- let active;
154
+ let configured;
153
155
  if (whenRaw === undefined || whenRaw === null) {
154
156
  // No `when` field → unconditional, always active
155
- active = true;
157
+ configured = true;
156
158
  }
157
159
  else if (typeof whenRaw === 'string' && whenRaw.length > 0) {
158
160
  // Non-empty string `when` → resolve via _resolveActivationValue
159
- active = _resolveActivationValue(whenRaw, config, cwd, registry);
161
+ configured = _resolveActivationValue(whenRaw, config, cwd, registry);
160
162
  }
161
163
  else {
162
164
  // Present-but-empty-string or non-string `when` → malformed, inactive
163
165
  // (mirrors loop-resolver.isActive: `typeof when !== 'string' || when.length === 0` → false)
164
- active = false;
166
+ configured = false;
165
167
  }
166
- hooks.push({ point, kind, when: whenRaw, active });
168
+ hooks.push({ point, kind, when: whenRaw, configured, active: enabled && configured });
167
169
  }
168
170
  }
169
171
  const stepsRaw = capObj['steps'];
@@ -172,7 +174,7 @@ function resolveCapabilityState(input) {
172
174
  processHooks(Array.isArray(stepsRaw) ? stepsRaw : [], 'step');
173
175
  processHooks(Array.isArray(gatesRaw) ? gatesRaw : [], 'gate');
174
176
  processHooks(Array.isArray(contributionsRaw) ? contributionsRaw : [], 'contribution');
175
- results.push({ id: capId, tier, skills, installed, surfaced, hooks });
177
+ results.push({ id: capId, tier, skills, installed, surfaced, enabled, hooks });
176
178
  }
177
179
  // Deterministic sort by id for stable output across calls
178
180
  results.sort((a, b) => a.id < b.id ? -1 : a.id > b.id ? 1 : 0);
@@ -192,6 +194,93 @@ function _resolveCommandsGsdDir() {
192
194
  const repoRoot = node_path_1.default.resolve(__dirname, '..', '..', '..');
193
195
  return node_path_1.default.join(repoRoot, 'commands', 'gsd');
194
196
  }
197
+ /**
198
+ * Build a skill dependency manifest from an INSTALLED runtime's skills directory.
199
+ *
200
+ * In an installed runtime (e.g. Codex at ~/.codex), gsd skills live as
201
+ * configDir/skills/gsd-STEM/SKILL.md. There is no commands/gsd source tree.
202
+ * This function scans that installed layout and builds the same
203
+ * Map shape that loadSkillsManifest produces from sources.
204
+ *
205
+ * Stem extraction: a directory named gsd-secure-phase maps to stem secure-phase.
206
+ * Only directories whose names start with gsd- are included so user-created
207
+ * skills (without the gsd- prefix) are not accidentally pulled in.
208
+ *
209
+ * The requires: field is parsed via the shared parseRequires helper (the same
210
+ * parser loadSkillsManifest uses), so the two paths cannot drift.
211
+ *
212
+ * Returns an empty Map when the skills dir does not exist.
213
+ */
214
+ function _loadInstalledSkillsManifest(configDir) {
215
+ const manifest = new Map();
216
+ const skillsDir = node_path_1.default.join(configDir, 'skills');
217
+ if (!node_fs_1.default.existsSync(skillsDir))
218
+ return manifest;
219
+ let entries;
220
+ try {
221
+ entries = node_fs_1.default.readdirSync(skillsDir, { withFileTypes: true });
222
+ }
223
+ catch {
224
+ return manifest;
225
+ }
226
+ for (const entry of entries) {
227
+ if (!entry.isDirectory())
228
+ continue;
229
+ if (!entry.name.startsWith('gsd-'))
230
+ continue;
231
+ // Strip the 'gsd-' prefix to get the skill stem
232
+ const stem = entry.name.slice(4); // 'gsd-'.length === 4
233
+ if (!stem)
234
+ continue;
235
+ const skillMdPath = node_path_1.default.join(skillsDir, entry.name, 'SKILL.md');
236
+ // Parity with loadSkillsManifest: a stem exists only when its artifact
237
+ // file is present. loadSkillsManifest registers a stem per .md FILE (and
238
+ // tolerates an unreadable file as []), but never invents a stem for which
239
+ // no file exists. Mirror that here: a stale gsd-<stem>/ directory with no
240
+ // SKILL.md must NOT register the stem — otherwise the capability would be
241
+ // wrongly reported surfaced/enabled and a verify:post hook would render
242
+ // for a skill that cannot run.
243
+ if (!node_fs_1.default.existsSync(skillMdPath))
244
+ continue;
245
+ let content = '';
246
+ try {
247
+ content = node_fs_1.default.readFileSync(skillMdPath, 'utf8');
248
+ }
249
+ catch {
250
+ // SKILL.md present but unreadable — register with no deps (parity with
251
+ // loadSkillsManifest's readFileSync catch branch).
252
+ }
253
+ // Parse requires: via the SAME shared parser loadSkillsManifest uses, so
254
+ // installed-runtime dependency resolution can never silently diverge from
255
+ // the source-tree path (single source of truth — no duplicated regex).
256
+ manifest.set(stem, content ? parseRequires(content) : []);
257
+ // Mirror loadSkillsManifest's Map shape: it always sets a companion
258
+ // `_calls_agents_<stem>` key. Installed SKILL.md bodies carry no
259
+ // recoverable agent-call refs, so [] (the no-agents case) keeps the two
260
+ // manifest shapes identical and prevents undefined-vs-[] drift for any
261
+ // consumer that reads the agent-refs companion key.
262
+ manifest.set(`_calls_agents_${stem}`, []);
263
+ }
264
+ return manifest;
265
+ }
266
+ /**
267
+ * Resolve the skill dependency manifest for capability-state resolution.
268
+ *
269
+ * Resolution order (fixes #1160 — installed-runtime capability surface):
270
+ * 1. If commandsGsdDir exists, load from source (repo-checkout behavior).
271
+ * 2. Otherwise, fall back to installed skills at configDir/skills/gsd-[stem]/SKILL.md.
272
+ *
273
+ * In an installed runtime the commands/gsd source tree is absent; only the
274
+ * skills/ layout exists. Returning an empty manifest caused resolveSurface to
275
+ * materialise the full-sentinel to an empty Set, making every capability appear
276
+ * unsurfaced even when the skill was physically installed.
277
+ */
278
+ function _resolveManifest(commandsGsdDir, configDir) {
279
+ if (node_fs_1.default.existsSync(commandsGsdDir)) {
280
+ return loadSkillsManifest(commandsGsdDir);
281
+ }
282
+ return _loadInstalledSkillsManifest(configDir);
283
+ }
195
284
  /**
196
285
  * Command entry point: resolve install profile, surface, and config; compute
197
286
  * capability state; emit the envelope via core.output.
@@ -222,7 +311,7 @@ function _resolveCommandsGsdDir() {
222
311
  * @param raw Whether to emit raw JSON (core.output raw mode)
223
312
  * @param _options Reserved for future use
224
313
  */
225
- function cmdCapabilityState(cwd, runtimeConfigDir, raw, _options = {}) {
314
+ function resolveCapabilityRuntimeState(cwd, runtimeConfigDir) {
226
315
  const warnings = [];
227
316
  // Resolve runtimeConfigDir using the canonical runtime-homes resolver.
228
317
  // When not provided, getGlobalConfigDir(runtime) is called with 'claude'
@@ -264,7 +353,9 @@ function cmdCapabilityState(cwd, runtimeConfigDir, raw, _options = {}) {
264
353
  let installedSkills;
265
354
  try {
266
355
  const commandsGsdDir = _resolveCommandsGsdDir();
267
- const manifest = loadSkillsManifest(commandsGsdDir);
356
+ // Fix #1160: use _resolveManifest so installed-runtime layouts (where
357
+ // commands/gsd is absent) fall back to <configDir>/skills/gsd-*/SKILL.md.
358
+ const manifest = _resolveManifest(commandsGsdDir, resolvedConfigDir);
268
359
  const profileName = readActiveProfile(resolvedConfigDir) ?? 'full';
269
360
  const resolvedInstall = resolveProfile({
270
361
  modes: profileName.split(',').map((s) => s.trim()),
@@ -277,7 +368,6 @@ function cmdCapabilityState(cwd, runtimeConfigDir, raw, _options = {}) {
277
368
  // Genuine resolution failure — surface it so the caller is not misled.
278
369
  const msg = err instanceof Error ? err.message : String(err);
279
370
  warnings.push(`profile-resolution failed: ${msg}`);
280
- coreError(`capability state: profile resolution failed: ${msg}`);
281
371
  // Degrade to empty set (not '*') so installed=false is reported accurately.
282
372
  installedSkills = new Set();
283
373
  }
@@ -285,7 +375,9 @@ function cmdCapabilityState(cwd, runtimeConfigDir, raw, _options = {}) {
285
375
  let surfacedSkills;
286
376
  try {
287
377
  const commandsGsdDir = _resolveCommandsGsdDir();
288
- const manifest = loadSkillsManifest(commandsGsdDir);
378
+ // Fix #1160: use _resolveManifest so installed-runtime layouts (where
379
+ // commands/gsd is absent) fall back to <configDir>/skills/gsd-*/SKILL.md.
380
+ const manifest = _resolveManifest(commandsGsdDir, resolvedConfigDir);
289
381
  const surfaceResult = resolveSurface(resolvedConfigDir, manifest, undefined, registry);
290
382
  // resolveSurface returns { name, skills: Set<string>, agents: Set<string> }
291
383
  // (always a concrete Set — full profile is materialized)
@@ -297,7 +389,6 @@ function cmdCapabilityState(cwd, runtimeConfigDir, raw, _options = {}) {
297
389
  // Genuine surface resolution failure — surface it so the caller is not misled.
298
390
  const msg = err instanceof Error ? err.message : String(err);
299
391
  warnings.push(`surface-resolution failed: ${msg}`);
300
- coreError(`capability state: surface resolution failed: ${msg}`);
301
392
  surfacedSkills = new Set();
302
393
  }
303
394
  // ── Load config ───────────────────────────────────────────────────────────────
@@ -316,21 +407,37 @@ function cmdCapabilityState(cwd, runtimeConfigDir, raw, _options = {}) {
316
407
  config,
317
408
  cwd,
318
409
  });
410
+ return {
411
+ runtimeConfigDir: resolvedConfigDir,
412
+ warnings,
413
+ registry,
414
+ config,
415
+ capabilities: result.capabilities,
416
+ };
417
+ }
418
+ function cmdCapabilityState(cwd, runtimeConfigDir, raw, _options = {}) {
419
+ const result = resolveCapabilityRuntimeState(cwd, runtimeConfigDir);
420
+ for (const warning of result.warnings) {
421
+ coreError(`capability state: ${warning}`);
422
+ }
319
423
  // Build envelope — include warnings array only when non-empty so the nominal
320
424
  // path keeps the output clean and callers can check `warnings` for degraded state.
321
425
  const envelope = {
322
- runtimeConfigDir: resolvedConfigDir,
426
+ runtimeConfigDir: result.runtimeConfigDir,
323
427
  capabilities: result.capabilities,
324
428
  };
325
- if (warnings.length > 0) {
326
- envelope.warnings = warnings;
429
+ if (result.warnings.length > 0) {
430
+ envelope.warnings = result.warnings;
327
431
  }
328
432
  coreOutput(envelope, raw);
329
433
  }
330
434
  module.exports = {
331
435
  resolveCapabilityState,
436
+ resolveCapabilityRuntimeState,
332
437
  cmdCapabilityState,
333
438
  // Exported for tests
334
439
  _resolveCommandsGsdDir,
440
+ _loadInstalledSkillsManifest,
441
+ _resolveManifest,
335
442
  _isSafePropKey,
336
443
  };
@@ -0,0 +1,354 @@
1
+ "use strict";
2
+ /**
3
+ * Capability Writer — ADR-1213 write-side inverse of capability-state resolver.
4
+ *
5
+ * Exports:
6
+ * setCapabilityState(cwd, runtimeConfigDir, desired, opts?)
7
+ * → { capabilities: CapabilityStateEntry[], warnings: string[] }
8
+ * cmdCapabilitySet(cwd, runtimeConfigDir, capId, options, raw)
9
+ *
10
+ * Projection rules (three axes: install, surface, config):
11
+ * - enabled axis: mutates .gsd-surface.json via readSurface/writeSurface
12
+ * - gates axis: mutates .planning/config.json via setConfigValues (batched)
13
+ * - materialize: optionally calls applySurface to write skill files
14
+ * - re-resolve: always calls resolveCapabilityRuntimeState for the return value
15
+ *
16
+ * Dependencies (leaf modules only — no circular risk):
17
+ * - ./core.cjs (output, error)
18
+ * - ./capability-state.cjs (resolveCapabilityRuntimeState, _resolveManifest, _resolveCommandsGsdDir)
19
+ * - ./surface.cjs (readSurface, writeSurface, applySurface)
20
+ * - ./install-profiles.cjs (readActiveProfile)
21
+ * - ./config.cjs (setConfigValues)
22
+ * - ./runtime-artifact-layout.cjs (resolveRuntimeArtifactLayout)
23
+ * - capability-registry.cjs (loaded at call time)
24
+ */
25
+ // eslint-disable-next-line @typescript-eslint/no-require-imports
26
+ const core = require("./core.cjs");
27
+ const { output: coreOutput, error: coreError } = core;
28
+ // eslint-disable-next-line @typescript-eslint/no-require-imports
29
+ const capabilityStateMod = require("./capability-state.cjs");
30
+ const { resolveCapabilityRuntimeState, _resolveManifest, _resolveCommandsGsdDir } = capabilityStateMod;
31
+ // eslint-disable-next-line @typescript-eslint/no-require-imports
32
+ const surfaceMod = require("./surface.cjs");
33
+ const { readSurface, writeSurface, applySurface } = surfaceMod;
34
+ // eslint-disable-next-line @typescript-eslint/no-require-imports
35
+ const installProfilesMod = require("./install-profiles.cjs");
36
+ const { readActiveProfile } = installProfilesMod;
37
+ // eslint-disable-next-line @typescript-eslint/no-require-imports
38
+ const configMod = require("./config.cjs");
39
+ const { setConfigValues } = configMod;
40
+ // eslint-disable-next-line @typescript-eslint/no-require-imports
41
+ const planningWorkspaceMod = require("./planning-workspace.cjs");
42
+ const { planningDir } = planningWorkspaceMod;
43
+ // eslint-disable-next-line @typescript-eslint/no-require-imports
44
+ const nodefs = require("fs");
45
+ // eslint-disable-next-line @typescript-eslint/no-require-imports
46
+ const nodepath = require("path");
47
+ // ─── Implementation ───────────────────────────────────────────────────────────
48
+ /**
49
+ * Write-side capability state mutator.
50
+ *
51
+ * Applies desired capability state changes (enabled axis via surface, gates
52
+ * axis via config) then re-resolves and returns the full capability state.
53
+ *
54
+ * Control flow:
55
+ * 1. RESOLVE BEFORE STATE: call resolveCapabilityRuntimeState once to get the
56
+ * canonical runtimeConfigDir and current capability state.
57
+ * 2. VALIDATION PASS (no writes): validate each desired entry against the
58
+ * registry and `before` state; collect errors and warnings.
59
+ * 3. If errors → return early with before.capabilities (no writes performed).
60
+ * 4. APPLY PASS: compute new surface state, writeSurface once if changed,
61
+ * setConfigValues once for gate writes; materialize if opts provided.
62
+ * 5. RE-RESOLVE: call resolveCapabilityRuntimeState again to get final state.
63
+ * 6. POST CHECKS: enabled=true but not-surfaced (not-in-profile) error;
64
+ * present-but-dead warning; append resolver warnings.
65
+ * 7. Return { capabilities: after.capabilities, warnings, errors }.
66
+ */
67
+ function setCapabilityState(cwd, runtimeConfigDir, desired, opts) {
68
+ const warnings = [];
69
+ const errors = [];
70
+ // ── Step 1: Resolve BEFORE state once ────────────────────────────────────
71
+ const before = resolveCapabilityRuntimeState(cwd, runtimeConfigDir);
72
+ const resolvedConfigDir = before.runtimeConfigDir;
73
+ // ── Load registry ─────────────────────────────────────────────────────────
74
+ const registry = before.registry;
75
+ const capabilitiesMap = (registry['capabilities'] && typeof registry['capabilities'] === 'object' && !Array.isArray(registry['capabilities'])
76
+ ? registry['capabilities']
77
+ : {});
78
+ // ── Step 2: VALIDATION PASS (no writes) ──────────────────────────────────
79
+ // Accumulate all valid gate writes and surface deltas.
80
+ // If ANY error is found, we will return early without writing anything.
81
+ const pendingGateWrites = [];
82
+ // surface-delta accumulators: ids to add to / remove from disabledClusters
83
+ const idsToDisable = [];
84
+ const idsToEnable = [];
85
+ // Track which ids need surface loading (have skills + explicit enabled flag)
86
+ let needsSurface = false;
87
+ for (const entry of desired) {
88
+ const { id, enabled, gates } = entry;
89
+ // Validate capability id
90
+ if (!Object.prototype.hasOwnProperty.call(capabilitiesMap, id)) {
91
+ errors.push(`unknown capability: "${id}"`);
92
+ continue;
93
+ }
94
+ const capObj = capabilitiesMap[id];
95
+ const skillsRaw = capObj['skills'];
96
+ const skills = Array.isArray(skillsRaw)
97
+ ? skillsRaw.filter((s) => typeof s === 'string')
98
+ : [];
99
+ const configDef = (capObj['config'] && typeof capObj['config'] === 'object' && !Array.isArray(capObj['config'])
100
+ ? capObj['config']
101
+ : {});
102
+ // ── Validate gate keys / values ──────────────────────────────────────────
103
+ if (gates !== undefined) {
104
+ for (const [key, val] of Object.entries(gates)) {
105
+ if (!Object.prototype.hasOwnProperty.call(configDef, key)) {
106
+ errors.push(`unknown gate key "${key}" for capability "${id}"`);
107
+ continue;
108
+ }
109
+ if (typeof val !== 'boolean') {
110
+ errors.push(`gate value for "${key}" must be boolean, got ${typeof val}`);
111
+ continue;
112
+ }
113
+ pendingGateWrites.push({ keyPath: key, value: val });
114
+ }
115
+ }
116
+ // ── Validate enabled axis ────────────────────────────────────────────────
117
+ if (enabled !== undefined) {
118
+ if (skills.length === 0) {
119
+ // Advisory only — no surface effect possible
120
+ warnings.push(`capability "${id}" owns no skills; 'enabled' has no surface effect — use gates to toggle its hooks`);
121
+ continue;
122
+ }
123
+ // Install-floor check: cannot enable a capability whose skills are not installed
124
+ if (enabled === true) {
125
+ const beforeEntry = before.capabilities.find((c) => c.id === id);
126
+ if (beforeEntry && beforeEntry.installed === false) {
127
+ errors.push(`cannot enable "${id}": its skills are not in the install profile`);
128
+ continue;
129
+ }
130
+ }
131
+ needsSurface = true;
132
+ if (enabled === false) {
133
+ idsToDisable.push(id);
134
+ }
135
+ else {
136
+ idsToEnable.push(id);
137
+ }
138
+ }
139
+ }
140
+ // ── Fix D: Pre-validate config.json parseability before any write ────────
141
+ // If there are pending gate writes, attempt to read and parse the target
142
+ // config.json BEFORE writing anything. A malformed file would cause
143
+ // setConfigValues to error() mid-operation leaving a partial write.
144
+ if (pendingGateWrites.length > 0) {
145
+ try {
146
+ const configJsonPath = nodepath.join(planningDir(cwd), 'config.json');
147
+ if (nodefs.existsSync(configJsonPath)) {
148
+ const raw = nodefs.readFileSync(configJsonPath, 'utf-8');
149
+ try {
150
+ JSON.parse(raw);
151
+ }
152
+ catch (parseErr) {
153
+ const msg = parseErr instanceof Error ? parseErr.message : String(parseErr);
154
+ errors.push(`config.json is malformed: ${msg}`);
155
+ }
156
+ }
157
+ }
158
+ catch {
159
+ // Cannot read the file path — not an error (e.g. planningDir env-var issue); let setConfigValues handle it
160
+ }
161
+ }
162
+ // ── Step 3: Early return on validation errors ────────────────────────────
163
+ if (errors.length > 0) {
164
+ return {
165
+ capabilities: before.capabilities,
166
+ warnings,
167
+ errors,
168
+ };
169
+ }
170
+ // ── Step 4: APPLY PASS ────────────────────────────────────────────────────
171
+ // ── Surface writes ────────────────────────────────────────────────────────
172
+ if (needsSurface && (idsToDisable.length > 0 || idsToEnable.length > 0)) {
173
+ const existing = readSurface(resolvedConfigDir);
174
+ let pendingSurface = existing ?? {
175
+ baseProfile: readActiveProfile(resolvedConfigDir) ?? 'full',
176
+ disabledClusters: [],
177
+ explicitAdds: [],
178
+ explicitRemoves: [],
179
+ };
180
+ let surfaceChanged = false;
181
+ for (const id of idsToDisable) {
182
+ // Add id to disabledClusters (dedupe)
183
+ if (!pendingSurface.disabledClusters.includes(id)) {
184
+ pendingSurface = {
185
+ ...pendingSurface,
186
+ disabledClusters: [...pendingSurface.disabledClusters, id],
187
+ };
188
+ surfaceChanged = true;
189
+ }
190
+ // Fix A: explicitAdds contains SKILL STEMS, not capability ids.
191
+ // Remove the capability's skill stems from explicitAdds so that
192
+ // resolveSurface does not re-add those skills after the cluster disable.
193
+ const capObjForDisable = capabilitiesMap[id];
194
+ const skillsRawForDisable = capObjForDisable?.['skills'];
195
+ const skillStemsForDisable = Array.isArray(skillsRawForDisable)
196
+ ? skillsRawForDisable.filter((s) => typeof s === 'string')
197
+ : [];
198
+ const newExplicitAdds = pendingSurface.explicitAdds.filter((x) => !skillStemsForDisable.includes(x));
199
+ if (newExplicitAdds.length !== pendingSurface.explicitAdds.length) {
200
+ pendingSurface = { ...pendingSurface, explicitAdds: newExplicitAdds };
201
+ surfaceChanged = true;
202
+ }
203
+ }
204
+ for (const id of idsToEnable) {
205
+ // Remove id from disabledClusters
206
+ if (pendingSurface.disabledClusters.includes(id)) {
207
+ pendingSurface = {
208
+ ...pendingSurface,
209
+ disabledClusters: pendingSurface.disabledClusters.filter((x) => x !== id),
210
+ };
211
+ surfaceChanged = true;
212
+ }
213
+ // Fix A (enable branch): also remove the capability's skill stems from
214
+ // explicitRemoves so that resolveSurface does not subtract those skills.
215
+ // Do NOT add anything to explicitAdds — a cap that was only in explicitAdds
216
+ // and was disabled is caught by the post-check below.
217
+ const capObjForEnable = capabilitiesMap[id];
218
+ const skillsRawForEnable = capObjForEnable?.['skills'];
219
+ const skillStemsForEnable = Array.isArray(skillsRawForEnable)
220
+ ? skillsRawForEnable.filter((s) => typeof s === 'string')
221
+ : [];
222
+ const newExplicitRemoves = pendingSurface.explicitRemoves.filter((x) => !skillStemsForEnable.includes(x));
223
+ if (newExplicitRemoves.length !== pendingSurface.explicitRemoves.length) {
224
+ pendingSurface = { ...pendingSurface, explicitRemoves: newExplicitRemoves };
225
+ surfaceChanged = true;
226
+ }
227
+ }
228
+ if (surfaceChanged) {
229
+ writeSurface(resolvedConfigDir, pendingSurface);
230
+ }
231
+ }
232
+ // ── Config writes (once, batched) ─────────────────────────────────────────
233
+ if (pendingGateWrites.length > 0) {
234
+ setConfigValues(cwd, pendingGateWrites);
235
+ }
236
+ // ── Materialize (optional) ────────────────────────────────────────────────
237
+ if (opts?.materialize) {
238
+ const { runtime, scope } = opts.materialize;
239
+ try {
240
+ // eslint-disable-next-line @typescript-eslint/no-require-imports
241
+ const runtimeArtifactLayout = require('./runtime-artifact-layout.cjs');
242
+ // eslint-disable-next-line @typescript-eslint/no-unsafe-assignment
243
+ const layout = runtimeArtifactLayout.resolveRuntimeArtifactLayout(runtime, resolvedConfigDir, scope);
244
+ const commandsGsdDir = _resolveCommandsGsdDir();
245
+ const manifest = _resolveManifest(commandsGsdDir, resolvedConfigDir);
246
+ // eslint-disable-next-line @typescript-eslint/no-unsafe-argument
247
+ applySurface(resolvedConfigDir, layout, manifest, undefined, registry);
248
+ }
249
+ catch (err) {
250
+ const msg = err instanceof Error ? err.message : String(err);
251
+ // Fix C: materialise was explicitly requested — a failure is an error (non-zero exit),
252
+ // not merely advisory.
253
+ errors.push(`materialize failed: ${msg}`);
254
+ }
255
+ }
256
+ // ── Step 5: RE-RESOLVE ────────────────────────────────────────────────────
257
+ const after = resolveCapabilityRuntimeState(cwd, resolvedConfigDir);
258
+ // ── Step 6: POST CHECKS ───────────────────────────────────────────────────
259
+ // Check: desired enabled=true but not actually enabled after write
260
+ // (catches the not-in-profile / not-surfaced silent no-op case).
261
+ // The install-floor case (installed===false) was already caught in validation.
262
+ for (const entry of desired) {
263
+ if (entry.enabled === true) {
264
+ const afterCap = after.capabilities.find((c) => c.id === entry.id);
265
+ if (afterCap && afterCap.enabled !== true) {
266
+ errors.push(`cannot enable "${entry.id}": not in the active surface/profile (widen the profile or use /gsd:surface enable)`);
267
+ }
268
+ }
269
+ // Fix B: desired enabled=false — assert it is actually disabled after write.
270
+ // Prevents "off means off" silent failures (e.g. explicitAdds containing the
271
+ // cap's skill stems re-adds them after the cluster disable).
272
+ if (entry.enabled === false) {
273
+ const afterCap = after.capabilities.find((c) => c.id === entry.id);
274
+ if (afterCap && afterCap.enabled !== false) {
275
+ errors.push(`failed to disable "${entry.id}": still surfaced after write`);
276
+ }
277
+ }
278
+ }
279
+ // Check: present-but-dead — SCOPED to touched (desired) capabilities only.
280
+ const desiredIds = new Set(desired.map((d) => d.id));
281
+ for (const cap of after.capabilities) {
282
+ if (!desiredIds.has(cap.id))
283
+ continue;
284
+ if (cap.enabled === true &&
285
+ cap.hooks.length > 0 &&
286
+ cap.hooks.every((h) => !h.configured)) {
287
+ warnings.push(`capability "${cap.id}" is surfaced but every hook is gated off — did you mean enabled:false?`);
288
+ }
289
+ }
290
+ // Append resolver's own warnings
291
+ for (const w of after.warnings) {
292
+ warnings.push(w);
293
+ }
294
+ return {
295
+ capabilities: after.capabilities,
296
+ warnings,
297
+ errors,
298
+ };
299
+ }
300
+ /**
301
+ * CLI command entry point for `gsd-tools capability set`.
302
+ *
303
+ * Builds one DesiredCapability from the provided options, calls setCapabilityState,
304
+ * then prints the result. When raw=true emits JSON; else emits a human summary.
305
+ * Warnings are always printed to stderr.
306
+ */
307
+ function cmdCapabilitySet(cwd, runtimeConfigDir, capId, options, raw) {
308
+ const desired = [
309
+ {
310
+ id: capId,
311
+ ...(options.enabled !== undefined ? { enabled: options.enabled } : {}),
312
+ ...(options.gates ? { gates: options.gates } : {}),
313
+ },
314
+ ];
315
+ const opts = options.runtime
316
+ ? { materialize: { runtime: options.runtime, scope: options.scope ?? 'global' } }
317
+ : undefined;
318
+ const result = setCapabilityState(cwd, runtimeConfigDir, desired, opts);
319
+ if (raw) {
320
+ // Raw mode: emit JSON to stdout including errors; exit non-zero if errors present.
321
+ // Do NOT print human stderr lines — raw consumers parse the JSON.
322
+ coreOutput({ capabilities: result.capabilities, warnings: result.warnings, errors: result.errors }, true);
323
+ if (result.errors.length > 0) {
324
+ process.exit(1);
325
+ }
326
+ return;
327
+ }
328
+ // Human mode: print warnings and errors to stderr (non-fatally for warnings).
329
+ for (const w of result.warnings) {
330
+ process.stderr.write(`capability set: warning: ${w}\n`);
331
+ }
332
+ for (const e of result.errors) {
333
+ process.stderr.write(`capability set: error: ${e}\n`);
334
+ }
335
+ // Exit non-zero if any errors (hard failures — requested action was not realized).
336
+ if (result.errors.length > 0) {
337
+ coreError(`capability set: ${String(result.errors.length)} error(s) — see above`);
338
+ return; // unreachable — coreError calls process.exit(1)
339
+ }
340
+ // Human-readable summary: focus on the target capability
341
+ const cap = result.capabilities.find((c) => c.id === capId);
342
+ if (!cap) {
343
+ const msg = `capability "${capId}" not found in registry`;
344
+ coreOutput(msg, false, msg);
345
+ return;
346
+ }
347
+ const activeHooks = cap.hooks.filter((h) => h.active).length;
348
+ const summary = `capability ${capId}: enabled=${String(cap.enabled)}, surfaced=${String(cap.surfaced)}, installed=${String(cap.installed)}, activeHooks=${String(activeHooks)}/${String(cap.hooks.length)}`;
349
+ coreOutput({ id: cap.id, enabled: cap.enabled, surfaced: cap.surfaced, installed: cap.installed, warnings: result.warnings.length > 0 ? result.warnings : undefined }, false, summary);
350
+ }
351
+ module.exports = {
352
+ setCapabilityState,
353
+ cmdCapabilitySet,
354
+ };