@opengsd/gsd-core 1.5.0 → 1.6.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 (95) hide show
  1. package/.claude-plugin/plugin.json +1 -1
  2. package/agents/gsd-plan-checker.md +34 -0
  3. package/agents/gsd-planner.md +2 -0
  4. package/agents/gsd-roadmapper.md +6 -0
  5. package/bin/install.js +199 -365
  6. package/commands/gsd/capture.md +5 -1
  7. package/gemini-extension.json +1 -1
  8. package/gsd-core/bin/gsd-tools.cjs +695 -5
  9. package/gsd-core/bin/lib/adr-parser.cjs +45 -23
  10. package/gsd-core/bin/lib/audit.cjs +2 -2
  11. package/gsd-core/bin/lib/capability-consent.cjs +763 -0
  12. package/gsd-core/bin/lib/capability-ledger.cjs +831 -0
  13. package/gsd-core/bin/lib/capability-lifecycle.cjs +1551 -0
  14. package/gsd-core/bin/lib/capability-loader.cjs +764 -0
  15. package/gsd-core/bin/lib/capability-lock.cjs +553 -0
  16. package/gsd-core/bin/lib/capability-registry.cjs +198 -4
  17. package/gsd-core/bin/lib/capability-source.cjs +1242 -0
  18. package/gsd-core/bin/lib/capability-state.cjs +9 -6
  19. package/gsd-core/bin/lib/capability-trust.cjs +550 -0
  20. package/gsd-core/bin/lib/capability-validator.cjs +2066 -0
  21. package/gsd-core/bin/lib/capability-writer.cjs +14 -5
  22. package/gsd-core/bin/lib/check-command-router.cjs +69 -18
  23. package/gsd-core/bin/lib/command-aliases.cjs +8 -0
  24. package/gsd-core/bin/lib/commands.cjs +247 -0
  25. package/gsd-core/bin/lib/config-loader.cjs +98 -84
  26. package/gsd-core/bin/lib/config-schema.cjs +26 -7
  27. package/gsd-core/bin/lib/config.cjs +7 -1
  28. package/gsd-core/bin/lib/decisions.cjs +149 -60
  29. package/gsd-core/bin/lib/frontmatter.cjs +7 -3
  30. package/gsd-core/bin/lib/gap-checker.cjs +126 -11
  31. package/gsd-core/bin/lib/init.cjs +91 -22
  32. package/gsd-core/bin/lib/legacy-cleanup.cjs +96 -0
  33. package/gsd-core/bin/lib/loop-resolver.cjs +26 -2
  34. package/gsd-core/bin/lib/markdown-sectionizer.cjs +471 -0
  35. package/gsd-core/bin/lib/milestone.cjs +41 -2
  36. package/gsd-core/bin/lib/phase-command-router.cjs +5 -0
  37. package/gsd-core/bin/lib/phase-id.cjs +25 -11
  38. package/gsd-core/bin/lib/phase-lifecycle.cjs +14 -5
  39. package/gsd-core/bin/lib/phase.cjs +33 -4
  40. package/gsd-core/bin/lib/probe-core.cjs +7 -0
  41. package/gsd-core/bin/lib/prohibition-enforcement.cjs +59 -26
  42. package/gsd-core/bin/lib/project-root.cjs +89 -2
  43. package/gsd-core/bin/lib/resolution.cjs +26 -0
  44. package/gsd-core/bin/lib/roadmap-command-router.cjs +16 -3
  45. package/gsd-core/bin/lib/roadmap-parser.cjs +73 -106
  46. package/gsd-core/bin/lib/roadmap-upgrade.cjs +47 -17
  47. package/gsd-core/bin/lib/roadmap.cjs +5 -2
  48. package/gsd-core/bin/lib/runtime-artifact-conversion.cjs +423 -3
  49. package/gsd-core/bin/lib/runtime-artifact-install-plan.cjs +77 -0
  50. package/gsd-core/bin/lib/runtime-artifact-layout.cjs +1 -28
  51. package/gsd-core/bin/lib/runtime-homes.cjs +53 -1
  52. package/gsd-core/bin/lib/runtime-name-policy.cjs +44 -0
  53. package/gsd-core/bin/lib/semver-compare.cjs +127 -0
  54. package/gsd-core/bin/lib/shell-command-projection.cjs +55 -1
  55. package/gsd-core/bin/lib/state-document.cjs +4 -2
  56. package/gsd-core/bin/lib/state.cjs +317 -161
  57. package/gsd-core/bin/lib/surface.cjs +12 -19
  58. package/gsd-core/bin/lib/uat-predicate.cjs +7 -47
  59. package/gsd-core/bin/lib/uat.cjs +39 -26
  60. package/gsd-core/bin/lib/validate.cjs +5 -2
  61. package/gsd-core/bin/lib/verify.cjs +40 -15
  62. package/gsd-core/bin/lib/worktree-safety.cjs +202 -0
  63. package/gsd-core/bin/shared/config-defaults.manifest.json +6 -1
  64. package/gsd-core/bin/shared/config-schema.manifest.json +5 -1
  65. package/gsd-core/references/context-budget.md +8 -8
  66. package/gsd-core/references/execute-phase-between-wave-reset.md +43 -0
  67. package/gsd-core/references/execute-phase-context-guard.md +16 -0
  68. package/gsd-core/references/execute-phase-wave-guard.md +33 -0
  69. package/gsd-core/references/planner-antipatterns.md +48 -0
  70. package/gsd-core/references/planning-config.md +4 -0
  71. package/gsd-core/references/prohibition-probe.md +15 -9
  72. package/gsd-core/references/scout-codebase.md +2 -2
  73. package/gsd-core/workflows/autonomous.md +33 -33
  74. package/gsd-core/workflows/diagnose-issues.md +6 -1
  75. package/gsd-core/workflows/discuss-phase/templates/context.md +1 -1
  76. package/gsd-core/workflows/discuss-phase.md +1 -2
  77. package/gsd-core/workflows/execute-phase.md +12 -12
  78. package/gsd-core/workflows/help/modes/full.md +10 -0
  79. package/gsd-core/workflows/list-seeds.md +63 -0
  80. package/gsd-core/workflows/manager.md +37 -37
  81. package/gsd-core/workflows/pr-branch.md +156 -0
  82. package/gsd-core/workflows/quick.md +6 -1
  83. package/gsd-core/workflows/review.md +10 -2
  84. package/gsd-core/workflows/spec-phase.md +8 -3
  85. package/gsd-core/workflows/verify-phase.md +2 -2
  86. package/package.json +6 -3
  87. package/scripts/gen-capability-matrix.cjs +284 -0
  88. package/scripts/gen-capability-registry.cjs +96 -1853
  89. package/scripts/lint-regression-test-names.allowlist.json +1 -0
  90. package/scripts/lint-resolution-provenance.allowlist.json +1 -0
  91. package/scripts/lint-resolution-provenance.cjs +192 -0
  92. package/scripts/lint-test-file-count.allowlist.json +9 -0
  93. package/scripts/prompt-injection-scan.sh +1 -0
  94. package/scripts/run-tests.cjs +14 -0
  95. package/scripts/sync-manifest-versions.cjs +77 -5
@@ -25,1722 +25,115 @@ const CAPABILITIES_DIR = path.join(ROOT, 'capabilities');
25
25
  const REGISTRY_PATH = path.join(ROOT, 'gsd-core', 'bin', 'lib', 'capability-registry.cjs');
26
26
  const CONFIG_SCHEMA_PATH = path.join(ROOT, 'gsd-core', 'bin', 'shared', 'config-schema.manifest.json');
27
27
 
28
- const SCHEMA_VERSION = '1';
29
-
30
- // ─── Loop Host Contract ───────────────────────────────────────────────────────
31
- //
32
- // Generated from workflow markers by scripts/gen-loop-host-contract.cjs (ADR-894 §3).
33
- // Require the committed gsd-core/bin/lib/loop-host-contract.cjs artifact so the
34
- // registry generator and the loop-host-contract generator share one source of truth.
35
- const { LOOP_HOST_CONTRACT } = require('../gsd-core/bin/lib/loop-host-contract.cjs');
36
-
37
- // Wired-points helper — tells us which points actually have render-hooks call sites.
38
- const { getWiredLoopPoints } = require('./gen-loop-host-contract.cjs');
39
-
40
- // Canonical point order — explicit constant (do NOT rely on Set insertion order).
41
- // Used for point-ordering semantics in consumes-satisfiability validation and topo-sort.
42
- const POINT_ORDER = [
43
- 'discuss:pre',
44
- 'discuss:post',
45
- 'plan:pre',
46
- 'plan:post',
47
- 'execute:pre',
48
- 'execute:wave:pre',
49
- 'execute:wave:post',
50
- 'execute:post',
51
- 'verify:pre',
52
- 'verify:post',
53
- 'ship:pre',
54
- 'ship:post',
55
- ];
56
-
57
- // C1: Artifact availability — host-produced artifacts become available at their step's :post
58
- // point. Build a map: artifact → earliest POINT_ORDER index at which it is available.
59
- // (discuss produces CONTEXT.md → discuss:post = index 1;
60
- // plan produces PLAN.md → plan:post = index 3;
61
- // execute produces SUMMARY.md → execute:post = index 7;
62
- // verify produces UAT.md → verify:post = index 9)
63
- //
64
- // NOTE: this map covers ONLY host artifacts. Hook-produced artifacts are handled per-run
65
- // during consumes-satisfiability validation (C2 global pass).
66
- const HOST_ARTIFACT_EARLIEST_POINT_IDX = (() => {
67
- const m = Object.create(null);
68
- for (const entry of LOOP_HOST_CONTRACT) {
69
- // The :post point is the last point in each step's points array.
70
- const postPoint = entry.points[entry.points.length - 1];
71
- const postIdx = POINT_ORDER.indexOf(postPoint);
72
- for (const artifact of entry.coreArtifacts.produces) {
73
- // Only record the earliest (should be unique, but take min to be safe).
74
- if (m[artifact] === undefined || postIdx < m[artifact]) {
75
- m[artifact] = postIdx;
76
- }
77
- }
78
- }
79
- return m;
80
- })();
81
-
82
- // Flatten all valid loop points into a Set for O(1) validation
83
- const VALID_LOOP_POINTS = new Set(POINT_ORDER);
84
-
85
- // Map point → step contract (agentRoles + coreArtifacts)
86
- const POINT_TO_CONTRACT = new Map();
87
- for (const entry of LOOP_HOST_CONTRACT) {
88
- for (const point of entry.points) {
89
- POINT_TO_CONTRACT.set(point, entry);
90
- }
91
- }
92
-
93
- // ─── Central config-schema loader ────────────────────────────────────────────
94
-
95
- /**
96
- * Loads the set of keys from the central config-schema manifest.
97
- * Returns a Set<string>. Used for collision detection.
98
- *
99
- * Contract:
100
- * - ENOENT (file not found): returns empty Set silently — legitimate absent case.
101
- * - Any other read error OR JSON parse error: writes a prominent warning to stderr
102
- * naming the schema path and the underlying error, then throws ExitError(1).
103
- * A parse error clearly states the schema is broken (not merely absent).
104
- *
105
- * @param {string} [schemaPath] Path to the config-schema manifest. Defaults to
106
- * CONFIG_SCHEMA_PATH (the real production path).
107
- * Overridable for unit testing with fixture paths.
108
- * @returns {Set<string>}
109
- */
110
- function loadCentralConfigKeys(schemaPath = CONFIG_SCHEMA_PATH) {
111
- let raw;
112
- try {
113
- raw = fs.readFileSync(schemaPath, 'utf8');
114
- } catch (err) {
115
- if (err.code === 'ENOENT') {
116
- return new Set();
117
- }
118
- process.stderr.write(
119
- ' ERROR Failed to read config-schema manifest at ' + schemaPath + ': ' + err.message + '\n',
120
- );
121
- throw new ExitError(1, 'could not read config-schema manifest');
122
- }
123
-
124
- let manifest;
125
- try {
126
- manifest = JSON.parse(raw);
127
- } catch (err) {
128
- process.stderr.write(
129
- ' ERROR Config-schema manifest at ' + schemaPath + ' is broken (JSON parse error): ' + err.message + '\n',
130
- );
131
- throw new ExitError(1, 'config-schema manifest JSON is malformed');
132
- }
133
-
134
- return new Set(Array.isArray(manifest.validKeys) ? manifest.validKeys : []);
135
- }
136
-
137
- // ─── Config-slice validation ──────────────────────────────────────────────────
138
-
139
- const VALID_CONFIG_SLICE_TYPES = new Set(['boolean', 'string', 'number', 'enum']);
140
-
141
- /**
142
- * Validate a single config-slice entry (one key's { type, default, description }).
143
- * Returns an array of error strings. Empty = valid.
144
- *
145
- * @param {string} capId Capability id (for error messages)
146
- * @param {string} key Config key (for error messages)
147
- * @param {object} slice The slice object from cap.config[key]
148
- * @returns {string[]}
149
- */
150
- function validateConfigSliceEntry(capId, key, slice) {
151
- const errors = [];
152
-
153
- if (typeof slice !== 'object' || slice === null || Array.isArray(slice)) {
154
- errors.push('capability "' + capId + '" config["' + key + '"]: slice must be a non-null object');
155
- return errors;
156
- }
157
-
158
- // type must be one of the allowed set
159
- if (!VALID_CONFIG_SLICE_TYPES.has(slice.type)) {
160
- errors.push(
161
- 'capability "' + capId + '" config["' + key + '"]: type must be one of ' +
162
- [...VALID_CONFIG_SLICE_TYPES].join(', ') + ' (got: ' + JSON.stringify(slice.type) + ')',
163
- );
164
- }
165
-
166
- // default must be present
167
- if (!Object.prototype.hasOwnProperty.call(slice, 'default')) {
168
- errors.push(
169
- 'capability "' + capId + '" config["' + key + '"]: default is required',
170
- );
171
- } else {
172
- // type-consistency check
173
- const def = slice.default;
174
- if (slice.type === 'boolean') {
175
- if (typeof def !== 'boolean') {
176
- errors.push(
177
- 'capability "' + capId + '" config["' + key + '"]: default must be a boolean for type:"boolean" (got: ' + typeof def + ')',
178
- );
179
- }
180
- } else if (slice.type === 'string') {
181
- if (typeof def !== 'string') {
182
- errors.push(
183
- 'capability "' + capId + '" config["' + key + '"]: default must be a string for type:"string" (got: ' + typeof def + ')',
184
- );
185
- }
186
- } else if (slice.type === 'number') {
187
- if (typeof def !== 'number') {
188
- errors.push(
189
- 'capability "' + capId + '" config["' + key + '"]: default must be a number for type:"number" (got: ' + typeof def + ')',
190
- );
191
- } else if (!Number.isFinite(def)) {
192
- // FIX 6a: Reject NaN and non-finite number defaults
193
- errors.push(
194
- 'capability "' + capId + '" config["' + key + '"]: default for type:"number" must be a finite number (got: ' + String(def) + ')',
195
- );
196
- }
197
- } else if (slice.type === 'enum') {
198
- // FIX 5a: enum REQUIRES a non-empty values array (all strings), and default must be in it
199
- if (!Array.isArray(slice.values) || slice.values.length === 0) {
200
- errors.push(
201
- 'capability "' + capId + '" config["' + key + '"]: type:"enum" requires a non-empty "values" array of strings',
202
- );
203
- } else if (!slice.values.every((v) => typeof v === 'string')) {
204
- errors.push(
205
- 'capability "' + capId + '" config["' + key + '"]: type:"enum" values array must contain only strings',
206
- );
207
- }
208
- if (typeof def !== 'string') {
209
- errors.push(
210
- 'capability "' + capId + '" config["' + key + '"]: default must be a string for type:"enum" (got: ' + typeof def + ')',
211
- );
212
- } else if (Array.isArray(slice.values) && slice.values.length > 0 && !slice.values.includes(def)) {
213
- errors.push(
214
- 'capability "' + capId + '" config["' + key + '"]: default "' + def +
215
- '" is not one of the declared enum values [' + slice.values.join(', ') + ']',
216
- );
217
- }
218
- }
219
- }
220
-
221
- // description must be a non-empty string
222
- if (typeof slice.description !== 'string' || slice.description.length === 0) {
223
- errors.push(
224
- 'capability "' + capId + '" config["' + key + '"]: description must be a non-empty string (got: ' + JSON.stringify(slice.description) + ')',
225
- );
226
- }
227
-
228
- return errors;
229
- }
230
-
231
- // ─── Per-capability validation ────────────────────────────────────────────────
232
-
233
- const KEBAB_RE = /^[a-z][a-z0-9-]*$/;
234
- const VALID_ROLES = new Set(['feature', 'runtime']);
235
- const VALID_TIERS = new Set(['core', 'standard', 'full']);
236
- const VALID_ON_ERROR = new Set(['skip', 'halt']);
237
- const RUNTIME_COMPAT_WILDCARD = '*';
238
-
239
- /**
240
- * Validate a single capability declaration.
241
- *
242
- * @param {object} cap The parsed JSON object.
243
- * @param {string} folderId The folder name (must equal cap.id).
244
- * @returns {string[]} Array of error strings; empty = valid.
245
- */
246
- function validateCapability(cap, folderId) {
247
- const errors = [];
248
-
249
- if (typeof cap !== 'object' || cap === null || Array.isArray(cap)) {
250
- return ['capability must be a JSON object'];
251
- }
252
-
253
- // ── Common envelope ────────────────────────────────────────────────────────
254
-
255
- if (typeof cap.id !== 'string' || !KEBAB_RE.test(cap.id)) {
256
- errors.push('id must be a kebab-case string');
257
- } else if (cap.id !== folderId) {
258
- errors.push('id "' + cap.id + '" must equal the folder name "' + folderId + '"');
259
- }
260
-
261
- if (!VALID_ROLES.has(cap.role)) {
262
- errors.push('role must be one of: feature, runtime (got: ' + cap.role + ')');
263
- }
264
-
265
- if (typeof cap.title !== 'string' || cap.title.length === 0) {
266
- errors.push('title must be a non-empty string');
267
- }
268
-
269
- // C4: description is required
270
- if (typeof cap.description !== 'string' || cap.description.length === 0) {
271
- errors.push('description must be a non-empty string');
272
- }
273
-
274
- if (!VALID_TIERS.has(cap.tier)) {
275
- errors.push('tier must be one of: core, standard, full (got: ' + cap.tier + ')');
276
- }
277
-
278
- if (!Array.isArray(cap.requires)) {
279
- errors.push('requires must be an array of capability ids');
280
- } else {
281
- for (const req of cap.requires) {
282
- if (typeof req !== 'string') {
283
- errors.push('requires entries must be strings (got: ' + JSON.stringify(req) + ')');
284
- }
285
- }
286
- }
287
-
288
- // ── Role-specific body ────────────────────────────────────────────────────
289
-
290
- if (cap.role === 'feature') {
291
- errors.push(...validateFeatureBody(cap));
292
- } else if (cap.role === 'runtime') {
293
- errors.push(...validateRuntimeBody(cap));
294
- }
295
-
296
- return errors;
297
- }
298
-
299
- /**
300
- * ADR-959: Validate a single commands[] entry on a feature-role capability.
301
- * { family: string, module: string, router: string, subcommands?: string[] }
302
- *
303
- * - family: non-empty string, no reserved names
304
- * - module: non-empty string, no path traversal, no absolute paths, no "/"
305
- * segments other than a bare basename (expected form: "foo.cjs")
306
- * - router: non-empty string
307
- * - subcommands: optional array of strings (doc/introspection only)
308
- *
309
- * @param {string} capId Capability id (for error messages)
310
- * @param {*} entry The entry to validate
311
- * @param {string} prefix Path prefix (e.g. "commands[0]")
312
- * @returns {string[]} Array of error strings; empty = valid.
313
- */
314
- function validateCommandEntry(capId, entry, prefix) {
315
- const errors = [];
316
- const ctx = 'capability "' + capId + '" ' + prefix;
317
-
318
- if (typeof entry !== 'object' || entry === null || Array.isArray(entry)) {
319
- errors.push(ctx + ' must be an object with family, module, and router');
320
- return errors;
321
- }
322
-
323
- // family: non-empty string, no reserved names
324
- if (typeof entry.family !== 'string' || entry.family.length === 0) {
325
- errors.push(ctx + '.family must be a non-empty string');
326
- } else if (entry.family === '__proto__' || entry.family === 'constructor' || entry.family === 'prototype') {
327
- // S2a: inline literal reserved-name guard (CodeQL barrier)
328
- errors.push(ctx + '.family "' + entry.family + '" is a reserved name');
329
- }
330
-
331
- // module: must be a safe bare basename matching /^[A-Za-z0-9._-]+\.cjs$/ —
332
- // no path separators, no "..", no NUL bytes, no absolute paths, ends in .cjs.
333
- // This conservative pattern subsumes all earlier traversal/absolute/separator checks.
334
- if (typeof entry.module !== 'string' || entry.module.length === 0) {
335
- errors.push(ctx + '.module must be a non-empty string');
336
- } else {
337
- const mod = entry.module;
338
- const SAFE_BASENAME = /^[A-Za-z0-9._-]+\.cjs$/;
339
- if (!SAFE_BASENAME.test(mod)) {
340
- errors.push(
341
- ctx + '.module must be a safe bare basename (pattern: /^[A-Za-z0-9._-]+\\.cjs$/, no path separators, no "..", no NUL bytes, must end in ".cjs"); got: ' +
342
- JSON.stringify(mod),
343
- );
344
- }
345
- }
346
-
347
- // router: non-empty string
348
- if (typeof entry.router !== 'string' || entry.router.length === 0) {
349
- errors.push(ctx + '.router must be a non-empty string');
350
- }
351
-
352
- // subcommands: optional array of non-empty strings (doc/introspection only)
353
- if (entry.subcommands !== undefined) {
354
- if (!Array.isArray(entry.subcommands)) {
355
- errors.push(ctx + '.subcommands must be an array of strings if present');
356
- } else {
357
- for (let i = 0; i < entry.subcommands.length; i++) {
358
- if (typeof entry.subcommands[i] !== 'string') {
359
- errors.push(ctx + '.subcommands[' + i + '] must be a string');
360
- } else if (entry.subcommands[i].length === 0) {
361
- errors.push(ctx + '.subcommands[' + i + '] must be a non-empty string');
362
- }
363
- }
364
- }
365
- }
366
-
367
- return errors;
368
- }
369
-
370
- function validateRuntimeCompat(capId, runtimeCompat) {
371
- const errors = [];
372
- const ctx = 'capability "' + capId + '" runtimeCompat';
373
-
374
- if (typeof runtimeCompat !== 'object' || runtimeCompat === null || Array.isArray(runtimeCompat)) {
375
- errors.push(ctx + ' must be an object with supported and unsupported arrays');
376
- return errors;
377
- }
378
-
379
- const validateRuntimeArray = (field, { allowWildcard }) => {
380
- const value = runtimeCompat[field];
381
- if (!Array.isArray(value)) {
382
- errors.push(ctx + '.' + field + ' must be an array of runtime ids' + (allowWildcard ? ' or ["*"]' : ''));
383
- return;
384
- }
385
- if (field === 'supported' && value.length === 0) {
386
- errors.push(ctx + '.supported must be a non-empty array');
387
- }
388
- let hasWildcard = false;
389
- for (let i = 0; i < value.length; i++) {
390
- const entry = value[i];
391
- if (typeof entry !== 'string' || entry.length === 0) {
392
- errors.push(ctx + '.' + field + '[' + i + '] must be a non-empty string');
393
- continue;
394
- }
395
- if (entry === '__proto__' || entry === 'constructor' || entry === 'prototype') {
396
- errors.push(ctx + '.' + field + '[' + i + '] "' + entry + '" is a reserved name');
397
- }
398
- if (entry === RUNTIME_COMPAT_WILDCARD) {
399
- if (!allowWildcard) {
400
- errors.push(ctx + '.' + field + ' must not include wildcard "*"');
401
- }
402
- hasWildcard = true;
403
- } else if (!KEBAB_RE.test(entry)) {
404
- errors.push(ctx + '.' + field + '[' + i + '] must be a kebab-case runtime id or "*"');
405
- }
406
- }
407
- if (hasWildcard && value.length > 1) {
408
- errors.push(ctx + '.' + field + ' wildcard "*" cannot be mixed with runtime ids');
409
- }
410
- };
411
-
412
- validateRuntimeArray('supported', { allowWildcard: true });
413
- validateRuntimeArray('unsupported', { allowWildcard: false });
414
-
415
- if (runtimeCompat.notes !== undefined) {
416
- if (typeof runtimeCompat.notes !== 'object' || runtimeCompat.notes === null || Array.isArray(runtimeCompat.notes)) {
417
- errors.push(ctx + '.notes must be an object of runtime id to string if present');
418
- } else {
419
- for (const [key, value] of Object.entries(runtimeCompat.notes)) {
420
- if (key !== RUNTIME_COMPAT_WILDCARD && !KEBAB_RE.test(key)) {
421
- errors.push(ctx + '.notes key "' + key + '" must be a kebab-case runtime id or "*"');
422
- }
423
- if (typeof value !== 'string' || value.length === 0) {
424
- errors.push(ctx + '.notes["' + key + '"] must be a non-empty string');
425
- }
426
- }
427
- }
428
- }
429
-
430
- return errors;
431
- }
432
-
433
- function validateFeatureBody(cap) {
434
- const errors = [];
435
-
436
- errors.push(...validateRuntimeCompat(cap.id || '(unknown)', cap.runtimeCompat));
437
-
438
- if (!Array.isArray(cap.skills)) {
439
- errors.push('skills must be an array of strings');
440
- } else {
441
- for (const s of cap.skills) {
442
- if (typeof s !== 'string') {
443
- errors.push('skills entries must be strings');
444
- } else if (s === '__proto__' || s === 'constructor' || s === 'prototype') {
445
- // S2a: inline literal reserved-name guard (CodeQL barrier)
446
- errors.push('skills entry "' + s + '" is a reserved name');
447
- }
448
- }
449
- }
450
-
451
- // ADR-959: optional commands array
452
- if (cap.commands !== undefined) {
453
- if (!Array.isArray(cap.commands)) {
454
- errors.push('commands must be an array of {family, module, router} objects');
455
- } else {
456
- for (let i = 0; i < cap.commands.length; i++) {
457
- errors.push(...validateCommandEntry(cap.id || cap.role, cap.commands[i], 'commands[' + i + ']'));
458
- }
459
- }
460
- }
461
-
462
- if (!Array.isArray(cap.agents)) {
463
- errors.push('agents must be an array of strings');
464
- } else {
465
- for (const a of cap.agents) {
466
- if (typeof a !== 'string') {
467
- errors.push('agents entries must be strings');
468
- } else if (a === '__proto__' || a === 'constructor' || a === 'prototype') {
469
- // S2a: inline literal reserved-name guard (CodeQL barrier)
470
- errors.push('agents entry "' + a + '" is a reserved name');
471
- }
472
- }
473
- }
474
-
475
- if (typeof cap.config !== 'object' || cap.config === null || Array.isArray(cap.config)) {
476
- errors.push('config must be an object');
477
- } else {
478
- // C5: validate config key names and value shapes
479
- for (const key of Object.keys(cap.config)) {
480
- if (key === '' ) {
481
- errors.push('config keys must be non-empty strings');
482
- } else if (key === '__proto__' || key === 'constructor' || key === 'prototype') {
483
- // S2a: inline literal reserved-name guard (CodeQL barrier)
484
- errors.push('config key "' + key + '" is a reserved name');
485
- }
486
- const val = cap.config[key];
487
- if (val === null || typeof val !== 'object' || Array.isArray(val)) {
488
- errors.push('config["' + key + '"] must be an object (got: ' + (val === null ? 'null' : typeof val) + ')');
489
- } else if (typeof val.type !== 'string' || val.type.length === 0) {
490
- errors.push('config["' + key + '"] must have a string "type" field (e.g. "boolean", "string", "number", "enum")');
491
- }
492
- }
493
- }
494
-
495
- // C4: hooks, when present, must be an array of {event: string, script: string}
496
- if (cap.hooks !== undefined) {
497
- if (!Array.isArray(cap.hooks)) {
498
- errors.push('hooks must be an array of {event, script} objects');
499
- } else {
500
- for (let i = 0; i < cap.hooks.length; i++) {
501
- const h = cap.hooks[i];
502
- if (typeof h !== 'object' || h === null || Array.isArray(h)) {
503
- errors.push('hooks[' + i + '] must be an object with event and script keys');
504
- } else {
505
- if (typeof h.event !== 'string' || h.event.length === 0) {
506
- errors.push('hooks[' + i + '].event must be a non-empty string');
507
- }
508
- if (typeof h.script !== 'string' || h.script.length === 0) {
509
- errors.push('hooks[' + i + '].script must be a non-empty string');
510
- }
511
- }
512
- }
513
- }
514
- }
515
-
516
- // Build the declared skill/agent sets for ref membership checks (used in validateStep).
517
- // Only build these if the arrays are valid (already validated above).
518
- const declaredSkills = Array.isArray(cap.skills) ? new Set(cap.skills.filter((s) => typeof s === 'string')) : null;
519
- const declaredAgents = Array.isArray(cap.agents) ? new Set(cap.agents.filter((a) => typeof a === 'string')) : null;
520
-
521
- if (!Array.isArray(cap.steps)) {
522
- errors.push('steps must be an array');
523
- } else {
524
- for (let i = 0; i < cap.steps.length; i++) {
525
- errors.push(...validateStep(cap.steps[i], 'steps[' + i + ']', declaredSkills, declaredAgents));
526
- }
527
- }
528
-
529
- if (!Array.isArray(cap.contributions)) {
530
- errors.push('contributions must be an array');
531
- } else {
532
- for (let i = 0; i < cap.contributions.length; i++) {
533
- errors.push(...validateContribution(cap.contributions[i], 'contributions[' + i + ']'));
534
- }
535
- }
536
-
537
- if (!Array.isArray(cap.gates)) {
538
- errors.push('gates must be an array');
539
- } else {
540
- for (let i = 0; i < cap.gates.length; i++) {
541
- errors.push(...validateGate(cap.gates[i], 'gates[' + i + ']'));
542
- }
543
- }
544
-
545
- // activationKey: optional string naming the dotted config key that gates this capability.
546
- // If present: must be a non-empty string that is declared in this capability's own config slice.
547
- if (cap.activationKey !== undefined) {
548
- if (typeof cap.activationKey !== 'string' || cap.activationKey.length === 0) {
549
- errors.push(
550
- 'capability "' + (cap.id || '(unknown)') + '" activationKey must be a non-empty string (got: ' +
551
- JSON.stringify(cap.activationKey) + ')',
552
- );
553
- } else if (cap.activationKey === '__proto__' || cap.activationKey === 'constructor' || cap.activationKey === 'prototype') {
554
- // Prototype-pollution guard (inline literal, CodeQL barrier)
555
- errors.push(
556
- 'capability "' + (cap.id || '(unknown)') + '" activationKey "' + cap.activationKey +
557
- '" is a reserved JavaScript property name and cannot be used as an activationKey',
558
- );
559
- } else if (
560
- typeof cap.config !== 'object' ||
561
- cap.config === null ||
562
- !Object.prototype.hasOwnProperty.call(cap.config, cap.activationKey)
563
- ) {
564
- errors.push(
565
- 'capability "' + (cap.id || '(unknown)') + '" activationKey "' + cap.activationKey +
566
- '" is not declared in this capability\'s config slice — add it to the "config" object or use a key that is declared there',
567
- );
568
- }
569
- }
570
-
571
- return errors;
572
- }
573
-
574
- // ADR-857 phase 5e: Closed ConverterName enum — complete set used across 16 runtime descriptors,
575
- // all exported by bin/install.js (commands/skills) and src/runtime-artifact-conversion.cts (agents).
576
- // Any ArtifactKind with a non-null converter must use one of these.
577
- const VALID_CONVERTER_NAMES = new Set([
578
- // commands / skills converters (pre-existing)
579
- 'convertClaudeCommandToAntigravitySkill',
580
- 'convertClaudeCommandToAugmentSkill',
581
- 'convertClaudeCommandToClineSkill',
582
- 'convertClaudeCommandToClaudeSkill',
583
- 'convertClaudeCommandToCodebuddyCommand',
584
- 'convertClaudeCommandToCodebuddySkill',
585
- 'convertClaudeCommandToCodexSkill',
586
- 'convertClaudeCommandToCopilotSkill',
587
- 'convertClaudeCommandToCursorCommand',
588
- 'convertClaudeCommandToCursorSkill',
589
- 'convertClaudeCommandToKiloSkill',
590
- 'convertClaudeCommandToKimiSkill',
591
- 'convertClaudeCommandToOpencodeSkill',
592
- 'convertClaudeCommandToTraeSkill',
593
- 'convertClaudeCommandToWindsurfSkill',
594
- // agent converters (#1173 — descriptor-driven agent conversion wiring)
595
- 'convertClaudeAgentToCopilotAgent',
596
- 'convertClaudeAgentToAntigravityAgent',
597
- 'convertClaudeAgentToCursorAgent',
598
- 'convertClaudeAgentToWindsurfAgent',
599
- 'convertClaudeAgentToAugmentAgent',
600
- 'convertClaudeAgentToTraeAgent',
601
- 'convertClaudeAgentToCodebuddyAgent',
602
- 'convertClaudeAgentToClineAgent',
603
- 'convertClaudeAgentToCodexAgent',
604
- ]);
605
-
606
- // C3: Validate role:runtime body
607
- const VALID_CONFIG_FORMATS = new Set(['settings-json', 'toml', 'markdown', 'markdown-dir', 'none']);
608
- const VALID_CONFIG_HOME_KINDS = new Set(['dot-home', 'dot-home-nested', 'xdg', 'generic-agents-root']);
609
- const VALID_COMMAND_STYLES = new Set(['slash-hyphen', 'shell-var']);
610
- const VALID_HOOKS_SURFACES = new Set(['settings-json', 'codex-hooks-json', 'cursor-hooks-json', 'copilot-inline', 'cline-rules', 'none']);
611
- const VALID_HOOK_EVENTS = new Set(['claude', 'gemini', 'opencode-subset']);
612
- const VALID_SANDBOX_TIERS = new Set(['none', 'codex-agent-sandbox']);
613
- const VALID_ARTIFACT_KIND_NAMES = new Set(['commands', 'agents', 'skills', 'kimi-agents']);
614
- const VALID_ARTIFACT_NESTINGS = new Set(['flat', 'nested']);
615
- const FEATURE_FIELDS_FORBIDDEN_ON_RUNTIME = ['skills', 'agents', 'steps', 'contributions', 'gates', 'hooks', 'activationKey'];
616
- const VALID_INSTALL_SURFACES = new Set(['settings-json', 'codex-toml', 'copilot-instructions', 'cline-rules', 'cursor-hooks-json', 'profile-marker-only']);
617
- const VALID_PERMISSION_WRITERS = new Set(['opencode', 'kilo']);
618
- const VALID_EXTENDED_HOOK_EVENTS = new Set(['SubagentStop', 'Stop', 'PreCompact', 'FileChanged', 'BeforeAgent', 'AfterAgent', 'BeforeModel']);
619
-
620
- // GATE A: installSurface → allowed hooksSurface values (DEFECT.GENERATIVE-FIX: parity invariant)
621
- // Derived from the actual pairings in the 16 real runtime descriptors.
622
- const INSTALL_SURFACE_TO_ALLOWED_HOOKS_SURFACES = new Map([
623
- ['settings-json', new Set(['settings-json', 'none'])],
624
- ['codex-toml', new Set(['codex-hooks-json'])],
625
- ['copilot-instructions', new Set(['copilot-inline'])],
626
- ['cline-rules', new Set(['cline-rules'])],
627
- ['cursor-hooks-json', new Set(['cursor-hooks-json'])],
628
- ['profile-marker-only', new Set(['none'])],
629
- ]);
630
-
631
- // GATE B: extended hook event families → required hookEvents value
632
- // Gemini agent-events require hookEvents='gemini'; Claude-family events require hookEvents='claude'.
633
- const GEMINI_AGENT_EVENTS = new Set(['BeforeAgent', 'AfterAgent', 'BeforeModel']);
634
- const CLAUDE_FAMILY_EVENTS = new Set(['SubagentStop', 'Stop', 'PreCompact', 'FileChanged']);
635
-
636
- /**
637
- * Validate a runtime.configHome object per ADR-1016 Decision 1.
638
- * Returns an array of error strings.
639
- *
640
- * @param {string} capId Capability id (for error messages)
641
- * @param {*} ch The configHome value
642
- * @returns {string[]}
643
- */
644
- function validateConfigHome(capId, ch) {
645
- const errors = [];
646
- const ctx = 'capability "' + capId + '" runtime.configHome';
647
-
648
- if (typeof ch !== 'object' || ch === null || Array.isArray(ch)) {
649
- errors.push(ctx + ' must be an object (got: ' + (ch === null ? 'null' : typeof ch) + ')');
650
- return errors;
651
- }
652
-
653
- // kind — must be in closed vocab; inline literal guard (CodeQL barrier)
654
- if (ch.kind === '__proto__' || ch.kind === 'constructor' || ch.kind === 'prototype') {
655
- errors.push(ctx + '.kind "' + ch.kind + '" is a reserved name');
656
- } else if (!VALID_CONFIG_HOME_KINDS.has(ch.kind)) {
657
- errors.push(
658
- ctx + '.kind must be one of: ' + [...VALID_CONFIG_HOME_KINDS].join(', ') +
659
- ' (got: ' + JSON.stringify(ch.kind) + ')',
660
- );
661
- }
662
-
663
- // name — required string
664
- if (typeof ch.name !== 'string' || ch.name.length === 0) {
665
- errors.push(ctx + '.name must be a non-empty string');
666
- }
667
-
668
- // parent — required when kind == dot-home-nested
669
- if (ch.kind === 'dot-home-nested') {
670
- if (typeof ch.parent !== 'string' || ch.parent.length === 0) {
671
- errors.push(ctx + '.parent must be a non-empty string when kind is "dot-home-nested"');
672
- }
673
- }
674
-
675
- // env — required; must be an array of strings (every runtime has ≥0 env overrides)
676
- if (!Array.isArray(ch.env)) {
677
- errors.push(ctx + '.env is required and must be an array of strings (got: ' + JSON.stringify(ch.env) + ')');
678
- } else {
679
- for (let i = 0; i < ch.env.length; i++) {
680
- if (typeof ch.env[i] !== 'string') {
681
- errors.push(ctx + '.env[' + i + '] must be a string');
682
- }
683
- }
684
- }
685
-
686
- // probe — optional; if present must be an array of strings
687
- if (ch.probe !== undefined) {
688
- if (!Array.isArray(ch.probe)) {
689
- errors.push(ctx + '.probe must be an array of strings if present');
690
- } else {
691
- for (let i = 0; i < ch.probe.length; i++) {
692
- if (typeof ch.probe[i] !== 'string') {
693
- errors.push(ctx + '.probe[' + i + '] must be a string');
694
- }
695
- }
696
- }
697
- }
698
-
699
- // probeExists — optional; if present must be a non-empty string (sub-path existence check for probe)
700
- if (ch.probeExists !== undefined) {
701
- if (typeof ch.probeExists !== 'string' || ch.probeExists.length === 0) {
702
- errors.push(ctx + '.probeExists must be a non-empty string if present (got: ' + JSON.stringify(ch.probeExists) + ')');
703
- }
704
- }
705
-
706
- // skillsHome — optional; if present must be a full valid configHome object (recursive validation)
707
- if (ch.skillsHome !== undefined) {
708
- // Recursive call: validate skillsHome as a nested configHome.
709
- // Use a synthetic capId to surface the sub-path in error messages.
710
- const skillsHomeErrors = validateConfigHome(capId + '.skillsHome', ch.skillsHome);
711
- // Rewrite the inner ctx prefix so errors read as "...runtime.configHome.skillsHome..."
712
- for (const e of skillsHomeErrors) {
713
- errors.push(e.replace(
714
- 'capability "' + capId + '.skillsHome" runtime.configHome',
715
- ctx + '.skillsHome',
716
- ));
717
- }
718
- }
719
-
720
- return errors;
721
- }
722
-
723
- /**
724
- * Validate a single ArtifactKind entry per ADR-1016 Decision 3.
725
- * Returns an array of error strings.
726
- *
727
- * @param {string} capId Capability id (for error messages)
728
- * @param {*} entry The ArtifactKind object
729
- * @param {string} prefix Path prefix for error messages (e.g. "artifactLayout.global[0]")
730
- * @returns {string[]}
731
- */
732
- function validateArtifactKindEntry(capId, entry, prefix) {
733
- const errors = [];
734
- const ctx = 'capability "' + capId + '" runtime.' + prefix;
735
-
736
- if (typeof entry !== 'object' || entry === null || Array.isArray(entry)) {
737
- errors.push(ctx + ' must be an object');
738
- return errors;
739
- }
740
-
741
- // kind — must be in closed vocab; inline literal guard (CodeQL barrier)
742
- if (entry.kind === '__proto__' || entry.kind === 'constructor' || entry.kind === 'prototype') {
743
- errors.push(ctx + '.kind "' + entry.kind + '" is a reserved name');
744
- } else if (!VALID_ARTIFACT_KIND_NAMES.has(entry.kind)) {
745
- errors.push(
746
- ctx + '.kind must be one of: ' + [...VALID_ARTIFACT_KIND_NAMES].join(', ') +
747
- ' (got: ' + JSON.stringify(entry.kind) + ')',
748
- );
749
- }
750
-
751
- // destSubpath — required non-empty string
752
- if (typeof entry.destSubpath !== 'string' || entry.destSubpath.length === 0) {
753
- errors.push(ctx + '.destSubpath must be a non-empty string');
754
- }
755
-
756
- // nesting — required; must be in closed vocab (ADR-857 §5d: now drives install)
757
- if (entry.nesting === undefined || entry.nesting === null) {
758
- errors.push(ctx + '.nesting is required and must be one of: ' + [...VALID_ARTIFACT_NESTINGS].join(', '));
759
- } else if (!VALID_ARTIFACT_NESTINGS.has(entry.nesting)) {
760
- errors.push(
761
- ctx + '.nesting must be one of: ' + [...VALID_ARTIFACT_NESTINGS].join(', ') +
762
- ' (got: ' + JSON.stringify(entry.nesting) + ')',
763
- );
764
- }
765
-
766
- // prefix — required; must be a string (may be empty string '')
767
- if (entry.prefix === undefined || entry.prefix === null) {
768
- errors.push(ctx + '.prefix is required (must be a string, may be empty)');
769
- } else if (typeof entry.prefix !== 'string') {
770
- errors.push(ctx + '.prefix must be a string (got: ' + typeof entry.prefix + ')');
771
- }
772
-
773
- // recursive — optional; if present must be a boolean
774
- if (entry.recursive !== undefined) {
775
- if (typeof entry.recursive !== 'boolean') {
776
- errors.push(ctx + '.recursive must be a boolean if present (got: ' + typeof entry.recursive + ')');
777
- }
778
- }
779
-
780
- // converter — required; must be a string or null (closed ConverterName enum — now enforced in phase 5e)
781
- if (!Object.prototype.hasOwnProperty.call(entry, 'converter')) {
782
- errors.push(ctx + '.converter is required (must be a string or null)');
783
- } else if (entry.converter !== null && typeof entry.converter !== 'string') {
784
- errors.push(ctx + '.converter must be a string or null (got: ' + typeof entry.converter + ')');
785
- } else if (entry.converter !== null && typeof entry.converter === 'string' &&
786
- !VALID_CONVERTER_NAMES.has(entry.converter)) {
787
- // Closed ConverterName enum (ADR-857 phase 5e): reject unknown converter names
788
- errors.push(ctx + '.converter "' + entry.converter + '" is not a known ConverterName');
789
- }
790
-
791
- return errors;
792
- }
793
-
794
- /**
795
- * Validate runtime.artifactLayout per ADR-1016 Decision 3.
796
- * Accepts the structured { global, local } shape.
797
- * Returns an array of error strings.
798
- *
799
- * @param {string} capId Capability id (for error messages)
800
- * @param {*} layout The artifactLayout value
801
- * @returns {string[]}
802
- */
803
- function validateArtifactLayout(capId, layout) {
804
- const errors = [];
805
- const ctx = 'capability "' + capId + '" runtime.artifactLayout';
806
-
807
- if (typeof layout !== 'object' || layout === null || Array.isArray(layout)) {
808
- errors.push(ctx + ' must be an object with "global" and "local" arrays');
809
- return errors;
810
- }
811
-
812
- for (const scope of ['global', 'local']) {
813
- const arr = layout[scope];
814
- if (!Array.isArray(arr)) {
815
- errors.push(ctx + '.' + scope + ' must be an array');
816
- } else {
817
- for (let i = 0; i < arr.length; i++) {
818
- errors.push(...validateArtifactKindEntry(capId, arr[i], 'artifactLayout.' + scope + '[' + i + ']'));
819
- }
820
- }
821
- }
822
-
823
- return errors;
824
- }
825
-
826
- function validateRuntimeBody(cap) {
827
- const errors = [];
828
-
829
- // C3: feature-only fields must NOT appear on a runtime cap
830
- for (const field of FEATURE_FIELDS_FORBIDDEN_ON_RUNTIME) {
831
- if (cap[field] !== undefined) {
832
- errors.push('role:runtime capability must not have "' + field + '" (feature-only field)');
833
- }
834
- }
835
-
836
- // C3: require a runtime object
837
- if (typeof cap.runtime !== 'object' || cap.runtime === null || Array.isArray(cap.runtime)) {
838
- errors.push('role:runtime capability must have a "runtime" object');
839
- return errors; // can't validate further without the object
840
- }
841
-
842
- const r = cap.runtime;
843
-
844
- // configHome — must be a structured object (ADR-1016 Decision 1)
845
- errors.push(...validateConfigHome(cap.id || '(unknown)', r.configHome));
846
-
847
- // configFormat — closed 5-enum (unchanged)
848
- if (!VALID_CONFIG_FORMATS.has(r.configFormat)) {
849
- errors.push('runtime.configFormat must be one of: ' + [...VALID_CONFIG_FORMATS].join(', ') + ' (got: ' + r.configFormat + ')');
850
- }
851
-
852
- // artifactLayout — structured { global, local } per ADR-1016 Decision 3
853
- errors.push(...validateArtifactLayout(cap.id || '(unknown)', r.artifactLayout));
854
-
855
- // commandStyle — closed 2-enum (ADR-1016 Decision 4); inline literal guard (CodeQL barrier)
856
- if (r.commandStyle === '__proto__' || r.commandStyle === 'constructor' || r.commandStyle === 'prototype') {
857
- errors.push('runtime.commandStyle "' + r.commandStyle + '" is a reserved name');
858
- } else if (!VALID_COMMAND_STYLES.has(r.commandStyle)) {
859
- errors.push(
860
- 'runtime.commandStyle must be one of: ' + [...VALID_COMMAND_STYLES].join(', ') +
861
- ' (got: ' + JSON.stringify(r.commandStyle) + ')',
862
- );
863
- }
864
-
865
- // hooksSurface — closed 6-enum (ADR-1016 Decision 5); inline literal guard (CodeQL barrier)
866
- if (r.hooksSurface === '__proto__' || r.hooksSurface === 'constructor' || r.hooksSurface === 'prototype') {
867
- errors.push('runtime.hooksSurface "' + r.hooksSurface + '" is a reserved name');
868
- } else if (!VALID_HOOKS_SURFACES.has(r.hooksSurface)) {
869
- errors.push(
870
- 'runtime.hooksSurface must be one of: ' + [...VALID_HOOKS_SURFACES].join(', ') +
871
- ' (got: ' + JSON.stringify(r.hooksSurface) + ')',
872
- );
873
- }
874
-
875
- // hookEvents — optional; if present must be in closed 3-enum (ADR-1016 Decision 5)
876
- if (r.hookEvents !== undefined) {
877
- if (r.hookEvents === '__proto__' || r.hookEvents === 'constructor' || r.hookEvents === 'prototype') {
878
- errors.push('runtime.hookEvents "' + r.hookEvents + '" is a reserved name');
879
- } else if (!VALID_HOOK_EVENTS.has(r.hookEvents)) {
880
- errors.push(
881
- 'runtime.hookEvents must be one of: ' + [...VALID_HOOK_EVENTS].join(', ') +
882
- ' (got: ' + JSON.stringify(r.hookEvents) + ')',
883
- );
884
- }
885
- }
886
-
887
- // sandboxTier — closed 2-enum (ADR-1016 Decision 6); inline literal guard (CodeQL barrier)
888
- if (r.sandboxTier === '__proto__' || r.sandboxTier === 'constructor' || r.sandboxTier === 'prototype') {
889
- errors.push('runtime.sandboxTier "' + r.sandboxTier + '" is a reserved name');
890
- } else if (!VALID_SANDBOX_TIERS.has(r.sandboxTier)) {
891
- errors.push(
892
- 'runtime.sandboxTier must be one of: ' + [...VALID_SANDBOX_TIERS].join(', ') +
893
- ' (got: ' + JSON.stringify(r.sandboxTier) + ')',
894
- );
895
- }
896
-
897
- // supportTier — 1 or 2 (unchanged)
898
- if (r.supportTier !== 1 && r.supportTier !== 2) {
899
- errors.push('runtime.supportTier must be 1 or 2 (got: ' + r.supportTier + ')');
900
- }
901
-
902
- // installSurface — required string in closed enum
903
- if (!VALID_INSTALL_SURFACES.has(r.installSurface)) {
904
- errors.push(
905
- 'runtime.installSurface must be one of: ' + [...VALID_INSTALL_SURFACES].join(', ') +
906
- ' (got: ' + JSON.stringify(r.installSurface) + ')',
907
- );
908
- }
909
-
910
- // writesSharedSettings — required boolean
911
- if (typeof r.writesSharedSettings !== 'boolean') {
912
- errors.push(
913
- 'runtime.writesSharedSettings must be a boolean (got: ' + JSON.stringify(r.writesSharedSettings) + ')',
914
- );
915
- }
916
-
917
- // permissionWriter — required key; value must be null or a string in VALID_PERMISSION_WRITERS
918
- if (!Object.prototype.hasOwnProperty.call(r, 'permissionWriter')) {
919
- errors.push('runtime.permissionWriter is required (must be null or one of: ' + [...VALID_PERMISSION_WRITERS].join(', ') + ')');
920
- } else if (r.permissionWriter !== null && !VALID_PERMISSION_WRITERS.has(r.permissionWriter)) {
921
- errors.push(
922
- 'runtime.permissionWriter must be null or one of: ' + [...VALID_PERMISSION_WRITERS].join(', ') +
923
- ' (got: ' + JSON.stringify(r.permissionWriter) + ')',
924
- );
925
- }
926
-
927
- // extendedHookEvents — required array; every element must be in closed enum
928
- if (!Array.isArray(r.extendedHookEvents)) {
929
- errors.push(
930
- 'runtime.extendedHookEvents must be an array (got: ' + JSON.stringify(r.extendedHookEvents) + ')',
931
- );
932
- } else {
933
- for (let i = 0; i < r.extendedHookEvents.length; i++) {
934
- const ev = r.extendedHookEvents[i];
935
- if (typeof ev !== 'string' || !VALID_EXTENDED_HOOK_EVENTS.has(ev)) {
936
- errors.push(
937
- 'runtime.extendedHookEvents[' + i + '] must be one of: ' + [...VALID_EXTENDED_HOOK_EVENTS].join(', ') +
938
- ' (got: ' + JSON.stringify(ev) + ')',
939
- );
940
- }
941
- }
942
- }
943
-
944
- // GATE A: installSurface ↔ hooksSurface consistency (DEFECT.GENERATIVE-FIX)
945
- // Only check if both fields are valid strings (individual field validators above report type errors).
946
- if (typeof r.installSurface === 'string' && typeof r.hooksSurface === 'string') {
947
- const allowedHooksSurfaces = INSTALL_SURFACE_TO_ALLOWED_HOOKS_SURFACES.get(r.installSurface);
948
- if (allowedHooksSurfaces !== undefined && !allowedHooksSurfaces.has(r.hooksSurface)) {
949
- errors.push(
950
- 'runtime.hooksSurface "' + r.hooksSurface + '" is not valid for installSurface "' + r.installSurface + '"' +
951
- ' — allowed: ' + [...allowedHooksSurfaces].join(', ') +
952
- ' (src: INSTALL_SURFACE_TO_ALLOWED_HOOKS_SURFACES in scripts/gen-capability-registry.cjs)',
953
- );
954
- }
955
- }
956
-
957
- // GATE B: extendedHookEvents ↔ hookEvents consistency (DEFECT.GENERATIVE-FIX)
958
- // If extendedHookEvents contains Gemini agent-events, hookEvents must be 'gemini'.
959
- // If it contains Claude-family events, hookEvents must be 'claude'.
960
- // Empty extendedHookEvents imposes no constraint.
961
- if (Array.isArray(r.extendedHookEvents) && r.extendedHookEvents.length > 0) {
962
- const hasGeminiEvents = r.extendedHookEvents.some((ev) => GEMINI_AGENT_EVENTS.has(ev));
963
- const hasClaudeEvents = r.extendedHookEvents.some((ev) => CLAUDE_FAMILY_EVENTS.has(ev));
964
- if (hasGeminiEvents && r.hookEvents !== 'gemini') {
965
- errors.push(
966
- 'runtime.extendedHookEvents contains Gemini agent-events (' +
967
- r.extendedHookEvents.filter((ev) => GEMINI_AGENT_EVENTS.has(ev)).join(', ') +
968
- ') but runtime.hookEvents is "' + r.hookEvents + '" — must be "gemini"',
969
- );
970
- }
971
- if (hasClaudeEvents && r.hookEvents !== 'claude') {
972
- errors.push(
973
- 'runtime.extendedHookEvents contains Claude-family events (' +
974
- r.extendedHookEvents.filter((ev) => CLAUDE_FAMILY_EVENTS.has(ev)).join(', ') +
975
- ') but runtime.hookEvents is "' + r.hookEvents + '" — must be "claude"',
976
- );
977
- }
978
- }
979
-
980
- return errors;
981
- }
982
-
983
- function materializeHookFragments(cap, capDir) {
984
- const errors = [];
985
- const hookGroups = [
986
- ['steps', Array.isArray(cap.steps) ? cap.steps : []],
987
- ['contributions', Array.isArray(cap.contributions) ? cap.contributions : []],
988
- ];
989
-
990
- for (const [groupName, hooks] of hookGroups) {
991
- for (let i = 0; i < hooks.length; i++) {
992
- const hook = hooks[i];
993
- if (!hook || typeof hook !== 'object' || Array.isArray(hook)) continue;
994
- const fragment = hook.fragment;
995
- if (!fragment || typeof fragment !== 'object' || Array.isArray(fragment)) continue;
996
- if (typeof fragment.inline === 'string') continue;
997
- if (typeof fragment.path !== 'string') continue;
998
-
999
- const abs = path.resolve(capDir, fragment.path);
1000
- const capRoot = path.resolve(capDir);
1001
- if (abs !== capRoot && !abs.startsWith(capRoot + path.sep)) {
1002
- errors.push(
1003
- cap.id + '/' + groupName + '[' + i + '].fragment.path escapes capability directory: ' +
1004
- fragment.path,
1005
- );
1006
- continue;
1007
- }
1008
-
1009
- try {
1010
- fragment.inline = fs.readFileSync(abs, 'utf8');
1011
- } catch (err) {
1012
- errors.push(
1013
- cap.id + '/' + groupName + '[' + i + '].fragment.path could not be read: ' +
1014
- fragment.path + ' (' + err.message + ')',
1015
- );
1016
- }
1017
- }
1018
- }
1019
-
1020
- return errors;
1021
- }
1022
-
1023
- function validateFragment(fragment, prefix) {
1024
- const errors = [];
1025
-
1026
- if (typeof fragment !== 'object' || fragment === null || Array.isArray(fragment)) {
1027
- errors.push(prefix + ' must be an object with path or inline key');
1028
- return errors;
1029
- }
1030
-
1031
- const hasPath = Object.prototype.hasOwnProperty.call(fragment, 'path');
1032
- const hasInline = Object.prototype.hasOwnProperty.call(fragment, 'inline');
1033
- if (!hasPath && !hasInline) {
1034
- errors.push(prefix + ' must have a "path" or "inline" key');
1035
- }
1036
- if (hasInline) {
1037
- const inline = fragment.inline;
1038
- if (typeof inline !== 'string') {
1039
- errors.push(prefix + '.inline must be a string');
1040
- } else if (inline === '') {
1041
- errors.push(prefix + '.inline must be a non-empty string');
1042
- }
1043
- }
1044
- // S1: fragment.path traversal guard — must be a relative path with no ".." segments
1045
- if (hasPath) {
1046
- const p = fragment.path;
1047
- if (typeof p !== 'string' || p === '' || path.isAbsolute(p) || p.split(/[\\/]/).includes('..')) {
1048
- errors.push(prefix + '.path must be a relative path with no ".." segments');
1049
- }
1050
- }
1051
-
1052
- return errors;
1053
- }
1054
-
1055
- /**
1056
- * Validate a single step entry.
1057
- *
1058
- * @param {object} step The step to validate.
1059
- * @param {string} prefix Path prefix for error messages (e.g. "steps[0]").
1060
- * @param {Set|null} declaredSkills Set of skill stems declared in this capability's skills array,
1061
- * or null if the skills array was not valid (skip membership check).
1062
- * @param {Set|null} declaredAgents Set of agent names declared in this capability's agents array,
1063
- * or null if the agents array was not valid (skip membership check).
1064
- * @returns {string[]}
1065
- */
1066
- function validateStep(step, prefix, declaredSkills, declaredAgents) {
1067
- const errors = [];
1068
-
1069
- if (!VALID_LOOP_POINTS.has(step.point)) {
1070
- errors.push(prefix + '.point "' + step.point + '" is not a valid loop point');
1071
- }
1072
-
1073
- if (typeof step.ref !== 'object' || step.ref === null) {
1074
- errors.push(prefix + '.ref must be an object with skill, agent, or command key');
1075
- } else {
1076
- const hasSkill = Object.prototype.hasOwnProperty.call(step.ref, 'skill');
1077
- const hasAgent = Object.prototype.hasOwnProperty.call(step.ref, 'agent');
1078
- const hasCommand = Object.prototype.hasOwnProperty.call(step.ref, 'command');
1079
- const dispatchCount = [hasSkill, hasAgent, hasCommand].filter(Boolean).length;
1080
- if (dispatchCount === 0) {
1081
- errors.push(prefix + '.ref must have a "skill", "agent", or "command" key');
1082
- } else if (dispatchCount > 1) {
1083
- // ref must be exclusive: skill XOR agent XOR command
1084
- errors.push(prefix + '.ref must have exactly one of "skill", "agent", or "command", not multiple');
1085
- }
1086
- if (hasSkill && typeof step.ref.skill !== 'string') {
1087
- errors.push(prefix + '.ref.skill must be a string');
1088
- } else if (hasSkill && typeof step.ref.skill === 'string' && step.ref.skill.startsWith('gsd-')) {
1089
- // Double-prefix guard: ref.skill is an unprefixed stem (e.g. "ui-review").
1090
- // Workflow dispatch prepends "gsd-" at runtime → "gsd-ui-review".
1091
- // A stem that already starts with "gsd-" would produce "gsd-gsd-..." at dispatch.
1092
- errors.push(
1093
- prefix + '.ref.skill "' + step.ref.skill + '" must not start with "gsd-" ' +
1094
- '(it is an unprefixed stem; the workflow prepends "gsd-" at dispatch — ' +
1095
- 'starting with "gsd-" would produce "gsd-' + step.ref.skill + '")',
1096
- );
1097
- } else if (hasSkill && typeof step.ref.skill === 'string' && declaredSkills !== null && !declaredSkills.has(step.ref.skill)) {
1098
- // Membership check: ref.skill must be declared in this capability's skills array.
1099
- // This catches typos and ensures every dispatched skill is owned by this capability.
1100
- errors.push(
1101
- prefix + '.ref.skill "' + step.ref.skill + '" is not declared in this capability\'s skills: [' +
1102
- [...declaredSkills].join(', ') + ']',
1103
- );
1104
- }
1105
- if (hasAgent && typeof step.ref.agent !== 'string') {
1106
- errors.push(prefix + '.ref.agent must be a string');
1107
- } else if (hasAgent && typeof step.ref.agent === 'string' && declaredAgents !== null && !declaredAgents.has(step.ref.agent)) {
1108
- // Membership check: ref.agent must be declared in this capability's agents array.
1109
- errors.push(
1110
- prefix + '.ref.agent "' + step.ref.agent + '" is not declared in this capability\'s agents: [' +
1111
- [...declaredAgents].join(', ') + ']',
1112
- );
1113
- }
1114
- if (hasCommand && typeof step.ref.command !== 'string') {
1115
- errors.push(prefix + '.ref.command must be a string');
1116
- }
1117
- }
1118
-
1119
- if (!Array.isArray(step.produces)) {
1120
- errors.push(prefix + '.produces must be an array');
1121
- } else {
1122
- for (const p of step.produces) {
1123
- if (typeof p !== 'string') errors.push(prefix + '.produces entries must be strings');
1124
- }
1125
- }
1126
-
1127
- if (!Array.isArray(step.consumes)) {
1128
- errors.push(prefix + '.consumes must be an array');
1129
- } else {
1130
- for (const c of step.consumes) {
1131
- if (typeof c !== 'string') errors.push(prefix + '.consumes entries must be strings');
1132
- }
1133
- }
1134
-
1135
- if (step.when !== undefined && typeof step.when !== 'string') {
1136
- errors.push(prefix + '.when must be a string if present');
1137
- }
1138
-
1139
- if (step.fragment !== undefined) {
1140
- errors.push(...validateFragment(step.fragment, prefix + '.fragment'));
1141
- }
1142
-
1143
- if (!VALID_ON_ERROR.has(step.onError)) {
1144
- errors.push(prefix + '.onError must be "skip" or "halt" (got: ' + step.onError + ')');
1145
- }
1146
-
1147
- return errors;
1148
- }
1149
-
1150
- function validateContribution(contrib, prefix) {
1151
- const errors = [];
1152
-
1153
- if (!VALID_LOOP_POINTS.has(contrib.point)) {
1154
- errors.push(prefix + '.point "' + contrib.point + '" is not a valid loop point');
1155
- }
1156
-
1157
- if (typeof contrib.into !== 'string') {
1158
- errors.push(prefix + '.into must be a string (agent role name)');
1159
- }
1160
-
1161
- if (!Array.isArray(contrib.produces)) {
1162
- errors.push(prefix + '.produces must be an array');
1163
- } else {
1164
- for (const p of contrib.produces) {
1165
- if (typeof p !== 'string') errors.push(prefix + '.produces entries must be strings');
1166
- }
1167
- }
1168
-
1169
- if (!Array.isArray(contrib.consumes)) {
1170
- errors.push(prefix + '.consumes must be an array');
1171
- } else {
1172
- for (const c of contrib.consumes) {
1173
- if (typeof c !== 'string') errors.push(prefix + '.consumes entries must be strings');
1174
- }
1175
- }
1176
-
1177
- errors.push(...validateFragment(contrib.fragment, prefix + '.fragment'));
1178
-
1179
- if (contrib.when !== undefined && typeof contrib.when !== 'string') {
1180
- errors.push(prefix + '.when must be a string if present');
1181
- }
1182
-
1183
- if (contrib.onError !== undefined && !VALID_ON_ERROR.has(contrib.onError)) {
1184
- errors.push(prefix + '.onError must be "skip" or "halt" if present');
1185
- }
1186
-
1187
- return errors;
1188
- }
1189
-
1190
- function validateGate(gate, prefix) {
1191
- const errors = [];
1192
-
1193
- if (!VALID_LOOP_POINTS.has(gate.point)) {
1194
- errors.push(prefix + '.point "' + gate.point + '" is not a valid loop point');
1195
- }
1196
-
1197
- if (typeof gate.check !== 'object' || gate.check === null) {
1198
- errors.push(prefix + '.check must be an object');
1199
- } else {
1200
- const hasQuery = Object.prototype.hasOwnProperty.call(gate.check, 'query');
1201
- const hasPredicate = Object.prototype.hasOwnProperty.call(gate.check, 'predicate');
1202
- const hasAgentVerdict = Object.prototype.hasOwnProperty.call(gate.check, 'agentVerdict');
1203
- const count = [hasQuery, hasPredicate, hasAgentVerdict].filter(Boolean).length;
1204
- if (count !== 1) {
1205
- errors.push(prefix + '.check must have exactly one of: query, predicate, agentVerdict');
1206
- }
1207
- // agentVerdict forces blocking: false (advisory only)
1208
- if (hasAgentVerdict && gate.blocking === true) {
1209
- errors.push(
1210
- prefix + '.check.agentVerdict forces blocking: false (non-deterministic checks may not halt the loop)',
1211
- );
1212
- }
1213
- }
1214
-
1215
- if (gate.when !== undefined && typeof gate.when !== 'string') {
1216
- errors.push(prefix + '.when must be a string if present');
1217
- }
1218
-
1219
- if (typeof gate.blocking !== 'boolean') {
1220
- errors.push(prefix + '.blocking must be a boolean');
1221
- }
1222
-
1223
- if (!VALID_ON_ERROR.has(gate.onError)) {
1224
- errors.push(prefix + '.onError must be "skip" or "halt" (got: ' + gate.onError + ')');
1225
- }
1226
-
1227
- return errors;
1228
- }
1229
-
1230
- // ─── Contract validation ──────────────────────────────────────────────────────
1231
-
1232
- /**
1233
- * Validate per-capability contract constraints against the Loop Host Contract.
1234
- * This covers:
1235
- * - contribution.into ∈ step's agentRoles
1236
- * - when references a config key in cap.config
1237
- *
1238
- * NOTE: step.consumes satisfiability is NOT checked here — it requires the full
1239
- * set of validated capabilities (cross-capability produces). It runs in
1240
- * validateConsumesGlobal() after loadAndValidate builds capMap.
1241
- *
1242
- * @param {object} cap Validated capability object
1243
- * @param {string} capId Capability id (for error messages)
1244
- */
1245
- function validateAgainstContract(cap, capId) {
1246
- if (cap.role !== 'feature') return [];
1247
- const errors = [];
1248
- const prefix = 'capability "' + capId + '"';
1249
-
1250
- // contribution.into must be in the step's agentRoles
1251
- for (const contrib of cap.contributions) {
1252
- if (!VALID_LOOP_POINTS.has(contrib.point)) continue; // already reported
1253
- const contract = POINT_TO_CONTRACT.get(contrib.point);
1254
- if (contract && !contract.agentRoles.includes(contrib.into)) {
1255
- errors.push(
1256
- prefix + ' contribution.into "' + contrib.into + '" at point "' + contrib.point +
1257
- '" is not in the step\'s agentRoles [' + contract.agentRoles.join(', ') + ']',
1258
- );
1259
- }
1260
- }
1261
-
1262
- // when references a plausibly-valid config key (string — we require it's in cap.config)
1263
- for (const step of cap.steps) {
1264
- if (step.when !== undefined) {
1265
- if (typeof step.when !== 'string') continue; // already reported above
1266
- if (
1267
- typeof cap.config === 'object' &&
1268
- cap.config !== null &&
1269
- !Object.prototype.hasOwnProperty.call(cap.config, step.when)
1270
- ) {
1271
- errors.push(
1272
- prefix + ' step.when "' + step.when + '" is not defined in capability config keys',
1273
- );
1274
- }
1275
- }
1276
- }
1277
-
1278
- for (const contrib of cap.contributions) {
1279
- if (contrib.when !== undefined) {
1280
- if (typeof contrib.when !== 'string') continue;
1281
- if (
1282
- typeof cap.config === 'object' &&
1283
- cap.config !== null &&
1284
- !Object.prototype.hasOwnProperty.call(cap.config, contrib.when)
1285
- ) {
1286
- errors.push(
1287
- prefix + ' contribution.when "' + contrib.when + '" is not defined in capability config keys',
1288
- );
1289
- }
1290
- }
1291
- }
1292
-
1293
- for (const gate of cap.gates) {
1294
- if (gate.when !== undefined) {
1295
- if (typeof gate.when !== 'string') continue;
1296
- if (
1297
- typeof cap.config === 'object' &&
1298
- cap.config !== null &&
1299
- !Object.prototype.hasOwnProperty.call(cap.config, gate.when)
1300
- ) {
1301
- errors.push(
1302
- prefix + ' gate.when "' + gate.when + '" is not defined in capability config keys',
1303
- );
1304
- }
1305
- }
1306
- }
1307
-
1308
- return errors;
1309
- }
1310
-
1311
- /**
1312
- * C1+C2: Global consumes-satisfiability validation.
1313
- *
1314
- * A hook at point P consuming artifact A is satisfiable iff:
1315
- * - A is a host-produced artifact available from its step's :post point (C1), and
1316
- * that :post point's POINT_ORDER index ≤ P's index; OR
1317
- * - A is produced by any capability hook step at a point whose POINT_ORDER index ≤ P's index
1318
- * (same-point is OK — topoSortSteps enforces intra-point order); OR
1319
- * - A is never produced anywhere → rejected.
1320
- *
1321
- * Runs after capMap is fully built so cross-capability produces are visible.
1322
- *
1323
- * @param {Map<string, object>} capMap Fully-validated capability map.
1324
- * @returns {string[]} Array of error strings.
1325
- */
1326
- function validateConsumesGlobal(capMap) {
1327
- const errors = [];
1328
-
1329
- // Build producedAtPoint: artifact → earliest POINT_ORDER index at which it is produced.
1330
- // Seed with host artifacts (C1: available from their step's :post point).
1331
- // Host-artifact entries are tagged {pointIdx, isHost:true} so they are never excluded by
1332
- // the self-consume check.
1333
- const producedAtPoint = Object.create(null);
1334
- for (const [artifact, postIdx] of Object.entries(HOST_ARTIFACT_EARLIEST_POINT_IDX)) {
1335
- if (artifact === '__proto__' || artifact === 'constructor' || artifact === 'prototype') continue;
1336
- producedAtPoint[artifact] = postIdx;
1337
- }
1338
-
1339
- // Build a richer per-artifact producer list for the self-consume check.
1340
- // Each entry: { pointIdx, capId, stepIdx } — identifies which cap+step produced the artifact.
1341
- // Host artifacts are seeded separately (no capId) and always satisfy the consume check.
1342
- // capHookProducers[artifact] = [{pointIdx, capId, stepIdx}, ...]
1343
- const capHookProducers = Object.create(null);
1344
-
1345
- // Add hook-produced artifacts from all capabilities.
1346
- for (const [capId, cap] of capMap) {
1347
- if (cap.role !== 'feature') continue;
1348
- for (let si = 0; si < (cap.steps || []).length; si++) {
1349
- const step = cap.steps[si];
1350
- if (!VALID_LOOP_POINTS.has(step.point)) continue;
1351
- const pointIdx = POINT_ORDER.indexOf(step.point);
1352
- for (const artifact of (step.produces || [])) {
1353
- if (typeof artifact !== 'string') continue;
1354
- if (artifact === '__proto__' || artifact === 'constructor' || artifact === 'prototype') continue;
1355
- if (producedAtPoint[artifact] === undefined || pointIdx < producedAtPoint[artifact]) {
1356
- producedAtPoint[artifact] = pointIdx;
1357
- }
1358
- if (!capHookProducers[artifact]) capHookProducers[artifact] = [];
1359
- capHookProducers[artifact].push({ pointIdx, capId, stepIdx: si });
1360
- }
1361
- }
1362
- }
1363
-
1364
- // Duplicate-producer invariant: two capability steps may not produce the same artifact
1365
- // at the same Loop Extension Point. Same-point dual production makes data-flow resolution
1366
- // ambiguous and is rejected at gen time (Decision #6).
1367
- for (const artifact of Object.keys(capHookProducers)) {
1368
- if (artifact === '__proto__' || artifact === 'constructor' || artifact === 'prototype') continue;
1369
- const producers = capHookProducers[artifact];
1370
- // Group by pointIdx
1371
- const byPoint = Object.create(null);
1372
- for (const entry of producers) {
1373
- if (!byPoint[entry.pointIdx]) byPoint[entry.pointIdx] = [];
1374
- byPoint[entry.pointIdx].push(entry);
1375
- }
1376
- for (const pointIdxStr of Object.keys(byPoint)) {
1377
- const group = byPoint[pointIdxStr];
1378
- // Count distinct (capId, stepIdx) producer steps — a single step listing the same
1379
- // artifact twice in its produces array pushes duplicate entries but represents only
1380
- // ONE producer step and must not false-positive the cross-step gate.
1381
- const distinctProducers = new Set(group.map((e) => e.capId + ' ' + e.stepIdx));
1382
- if (distinctProducers.size >= 2) {
1383
- const pointIdx = Number(pointIdxStr);
1384
- const pointName = POINT_ORDER[pointIdx];
1385
- const capIds = [...new Set(group.map((e) => e.capId))].sort().join(', ');
1386
- throw new Error(
1387
- 'duplicate-producer invariant violated: artifact "' + artifact + '" is produced by ' +
1388
- 'two or more capability steps at the same Loop Extension Point "' + pointName + '" ' +
1389
- '(capabilities: ' + capIds + '). ' +
1390
- 'Two capability steps producing the same artifact at the same Loop Extension Point ' +
1391
- 'makes data-flow resolution ambiguous and is rejected at gen time.',
1392
- );
1393
- }
1394
- }
1395
- }
1396
-
1397
- // Now check every hook step's consumes.
1398
- // Self-consume rule: a step H cannot satisfy its own consumes[A] from its own produces[A].
1399
- // A is satisfiable for H iff:
1400
- // (a) A is a host artifact with pointIdx <= stepPointIdx, OR
1401
- // (b) A is produced by a DIFFERENT cap/step at pointIdx <= stepPointIdx.
1402
- // "Different" means capId != H.capId OR stepIdx != H.stepIdx.
1403
- for (const [capId, cap] of capMap) {
1404
- if (cap.role !== 'feature') continue;
1405
- const prefix = 'capability "' + capId + '"';
1406
- for (let si = 0; si < (cap.steps || []).length; si++) {
1407
- const step = cap.steps[si];
1408
- if (!VALID_LOOP_POINTS.has(step.point)) continue;
1409
- const stepPointIdx = POINT_ORDER.indexOf(step.point);
1410
- for (const artifact of (step.consumes || [])) {
1411
- if (typeof artifact !== 'string') continue;
1412
-
1413
- // Check host-artifact satisfaction first (never excluded by self-consume).
1414
- const hostIdx = HOST_ARTIFACT_EARLIEST_POINT_IDX[artifact];
1415
- const hostSatisfied = hostIdx !== undefined && hostIdx <= stepPointIdx;
1416
- if (hostSatisfied) continue; // fast-path: host artifact is available
1417
-
1418
- // Check cap-hook producers, excluding this step itself.
1419
- const producers = capHookProducers[artifact];
1420
- if (!producers || producers.length === 0) {
1421
- // Not a host artifact and never produced by any hook.
1422
- errors.push(
1423
- prefix + ' step at point "' + step.point + '" consumes "' + artifact +
1424
- '" which is never produced by any host artifact or capability hook',
1425
- );
1426
- continue;
1427
- }
1428
-
1429
- // Find any non-self producer at pointIdx <= stepPointIdx.
1430
- const otherEarliestIdx = producers.reduce((best, p) => {
1431
- const isSelf = p.capId === capId && p.stepIdx === si;
1432
- if (isSelf) return best;
1433
- return (best === undefined || p.pointIdx < best) ? p.pointIdx : best;
1434
- }, undefined);
1435
-
1436
- if (otherEarliestIdx === undefined) {
1437
- // Only producer is this step itself — self-consume violation.
1438
- errors.push(
1439
- prefix + ' step at point "' + step.point + '" consumes "' + artifact +
1440
- '" which is only produced by this step itself (a step cannot consume its own output)',
1441
- );
1442
- } else if (otherEarliestIdx > stepPointIdx) {
1443
- errors.push(
1444
- prefix + ' step at point "' + step.point + '" consumes "' + artifact +
1445
- '" which is only produced after this point (earliest available at POINT_ORDER index ' +
1446
- otherEarliestIdx + ' = "' + POINT_ORDER[otherEarliestIdx] + '")',
1447
- );
1448
- }
1449
- // else: satisfied by another cap/step at an earlier-or-same point — OK.
1450
- }
1451
- }
1452
- }
28
+ // ─── Loop Host Contract ───────────────────────────────────────────────────────
29
+ //
30
+ // Generated from workflow markers by scripts/gen-loop-host-contract.cjs (ADR-894 §3).
31
+ // Require the committed gsd-core/bin/lib/loop-host-contract.cjs artifact so the
32
+ // registry generator and the loop-host-contract generator share one source of truth.
33
+ const { LOOP_HOST_CONTRACT } = require('../gsd-core/bin/lib/loop-host-contract.cjs');
1453
34
 
1454
- return errors;
1455
- }
35
+ // Wired-points helper — tells us which points actually have render-hooks call sites.
36
+ const { getWiredLoopPoints } = require('./gen-loop-host-contract.cjs');
1456
37
 
1457
- // ─── Cross-capability invariants ──────────────────────────────────────────────
38
+ // Capability validator — shared runtime-callable module extracted per ADR-1244 D2.
39
+ const capValidator = require('../gsd-core/bin/lib/capability-validator.cjs');
40
+ // Destructure only what the generator's own function bodies reference directly.
41
+ // Everything else is re-exported from capValidator in module.exports below.
42
+ const {
43
+ POINT_ORDER,
44
+ HOST_ARTIFACT_EARLIEST_POINT_IDX,
45
+ VALID_LOOP_POINTS,
46
+ POINT_TO_CONTRACT,
47
+ VALID_CONFIG_SLICE_TYPES,
48
+ VALID_TIERS,
49
+ SEMVER_RE,
50
+ SEMVER_RANGE_RE,
51
+ SHA512_INTEGRITY_RE,
52
+ VALID_CONVERTER_NAMES,
53
+ VALID_CONFIG_HOME_KINDS,
54
+ VALID_COMMAND_STYLES,
55
+ VALID_HOOKS_SURFACES,
56
+ VALID_HOOK_EVENTS,
57
+ VALID_SANDBOX_TIERS,
58
+ VALID_ARTIFACT_KIND_NAMES,
59
+ VALID_ARTIFACT_NESTINGS,
60
+ VALID_INSTALL_SURFACES,
61
+ VALID_PERMISSION_WRITERS,
62
+ VALID_EXTENDED_HOOK_EVENTS,
63
+ INSTALL_SURFACE_TO_ALLOWED_HOOKS_SURFACES,
64
+ INSTALL_SURFACE_TO_CONFIG_FORMAT,
65
+ SCHEMA_VERSION,
66
+ validateVersionEnvelope,
67
+ validateCapability,
68
+ validateCommandEntry,
69
+ validateRuntimeCompat,
70
+ validateConfigHome,
71
+ validateArtifactKindEntry,
72
+ validateArtifactLayout,
73
+ validateRuntimeBody,
74
+ materializeHookFragments,
75
+ validateAgainstContract,
76
+ validateConsumesGlobal,
77
+ validateCrossCapability,
78
+ computeRequiresClosure,
79
+ topoSortSteps,
80
+ topoSortContributions,
81
+ validateHooksWired,
82
+ validateConfigSliceEntry,
83
+ classifyCrossErrors,
84
+ runConfigFormatParityGate,
85
+ } = capValidator;
1458
86
 
1459
- const TIER_RANK = { core: 0, standard: 1, full: 2 };
87
+ // ─── Central config-schema loader ────────────────────────────────────────────
1460
88
 
1461
89
  /**
1462
- * Enforce cross-capability invariants.
90
+ * Loads the set of keys from the central config-schema manifest.
91
+ * Returns a Set<string>. Used for collision detection.
1463
92
  *
1464
- * @param {Map<string, object>} capMap id → validated capability object
1465
- * @param {Set<string>} centralKeys Set of keys in the central config-schema
1466
- * @returns {string[]} Array of error strings; empty = all pass.
1467
- */
1468
- function validateCrossCapability(capMap, centralKeys) {
1469
- const errors = [];
1470
-
1471
- // Ownership: one owner per skill stem + agent name
1472
- const skillOwner = new Map(); // skill → capId
1473
- const agentOwner = new Map(); // agent → capId
1474
- const familyOwner = new Map(); // command family → capId (ADR-959)
1475
- for (const [capId, cap] of capMap) {
1476
- if (cap.role !== 'feature') continue;
1477
- for (const skill of cap.skills) {
1478
- if (skillOwner.has(skill)) {
1479
- errors.push(
1480
- 'skill "' + skill + '" is owned by both "' + skillOwner.get(skill) + '" and "' + capId + '"',
1481
- );
1482
- } else {
1483
- skillOwner.set(skill, capId);
1484
- }
1485
- }
1486
- for (const agent of cap.agents) {
1487
- if (agentOwner.has(agent)) {
1488
- errors.push(
1489
- 'agent "' + agent + '" is owned by both "' + agentOwner.get(agent) + '" and "' + capId + '"',
1490
- );
1491
- } else {
1492
- agentOwner.set(agent, capId);
1493
- }
1494
- }
1495
- // ADR-959: single family ownership across the whole registry
1496
- if (Array.isArray(cap.commands)) {
1497
- for (const cmd of cap.commands) {
1498
- if (typeof cmd.family !== 'string' || cmd.family.length === 0) continue; // already reported
1499
- if (cmd.family === '__proto__' || cmd.family === 'constructor' || cmd.family === 'prototype') continue;
1500
- if (familyOwner.has(cmd.family)) {
1501
- errors.push(
1502
- 'command family "' + cmd.family + '" is owned by both "' + familyOwner.get(cmd.family) + '" and "' + capId + '"',
1503
- );
1504
- } else {
1505
- familyOwner.set(cmd.family, capId);
1506
- }
1507
- }
1508
- }
1509
- }
1510
-
1511
- // Config key ownership: exclusive AND absent from central schema
1512
- const configKeyOwner = new Map(); // key → capId
1513
- for (const [capId, cap] of capMap) {
1514
- if (cap.role !== 'feature' || typeof cap.config !== 'object' || cap.config === null) continue;
1515
- for (const key of Object.keys(cap.config)) {
1516
- if (configKeyOwner.has(key)) {
1517
- errors.push(
1518
- 'config key "' + key + '" is owned by both "' + configKeyOwner.get(key) + '" and "' + capId + '"',
1519
- );
1520
- } else {
1521
- configKeyOwner.set(key, capId);
1522
- }
1523
- if (centralKeys.has(key)) {
1524
- errors.push(
1525
- 'config key "' + key + '" is declared in capability "' + capId +
1526
- '" AND exists in the central config-schema — migration mid-flight: ' +
1527
- 'remove from central config-schema before adding to the capability',
1528
- );
1529
- }
1530
- }
1531
- }
1532
-
1533
- // requires: all ids exist
1534
- for (const [capId, cap] of capMap) {
1535
- if (!Array.isArray(cap.requires)) continue;
1536
- for (const req of cap.requires) {
1537
- if (!capMap.has(req)) {
1538
- errors.push(
1539
- 'capability "' + capId + '" requires "' + req + '" which does not exist',
1540
- );
1541
- }
1542
- }
1543
- }
1544
-
1545
- // runtimeCompat: explicit runtime ids must reference runtime capabilities.
1546
- // The wildcard "*" means descriptor-backed runtimes are supported by default.
1547
- const runtimeIds = new Set();
1548
- for (const [id, cap] of capMap) {
1549
- if (cap.role === 'runtime') runtimeIds.add(id);
1550
- }
1551
- for (const [capId, cap] of capMap) {
1552
- if (cap.role !== 'feature' || typeof cap.runtimeCompat !== 'object' || cap.runtimeCompat === null) continue;
1553
- for (const field of ['supported', 'unsupported']) {
1554
- const entries = Array.isArray(cap.runtimeCompat[field]) ? cap.runtimeCompat[field] : [];
1555
- for (const runtimeId of entries) {
1556
- if (runtimeId === RUNTIME_COMPAT_WILDCARD) continue;
1557
- if (typeof runtimeId !== 'string' || runtimeId.length === 0) continue;
1558
- if (!runtimeIds.has(runtimeId)) {
1559
- errors.push(
1560
- 'capability "' + capId + '" runtimeCompat.' + field +
1561
- ' references unknown runtime "' + runtimeId + '"',
1562
- );
1563
- }
1564
- }
1565
- }
1566
- if (cap.runtimeCompat.notes && typeof cap.runtimeCompat.notes === 'object') {
1567
- for (const runtimeId of Object.keys(cap.runtimeCompat.notes)) {
1568
- if (runtimeId === RUNTIME_COMPAT_WILDCARD) continue;
1569
- if (!runtimeIds.has(runtimeId)) {
1570
- errors.push(
1571
- 'capability "' + capId + '" runtimeCompat.notes references unknown runtime "' + runtimeId + '"',
1572
- );
1573
- }
1574
- }
1575
- }
1576
- }
1577
-
1578
- // requires: acyclic
1579
- const cycleErrors = detectRequiresCycles(capMap);
1580
- errors.push(...cycleErrors);
1581
-
1582
- // requires: tier-monotone (core may not require standard/full; standard may not require full)
1583
- for (const [capId, cap] of capMap) {
1584
- if (!Array.isArray(cap.requires) || !VALID_TIERS.has(cap.tier)) continue;
1585
- const myRank = TIER_RANK[cap.tier];
1586
- for (const req of cap.requires) {
1587
- const reqCap = capMap.get(req);
1588
- if (!reqCap || !VALID_TIERS.has(reqCap.tier)) continue;
1589
- const reqRank = TIER_RANK[reqCap.tier];
1590
- if (reqRank > myRank) {
1591
- errors.push(
1592
- 'tier-monotone violation: capability "' + capId + '" (tier: ' + cap.tier +
1593
- ') requires "' + req + '" (tier: ' + reqCap.tier +
1594
- ') — a capability may not require a higher-tier capability',
1595
- );
1596
- }
1597
- }
1598
- }
1599
-
1600
- return errors;
1601
- }
1602
-
1603
- /**
1604
- * Detect cycles in the requires graph using DFS.
1605
- */
1606
- function detectRequiresCycles(capMap) {
1607
- const errors = [];
1608
- const WHITE = 0, GRAY = 1, BLACK = 2;
1609
- const color = new Map([...capMap.keys()].map((k) => [k, WHITE]));
1610
-
1611
- function dfs(id, stack) {
1612
- if (color.get(id) === GRAY) {
1613
- const cycleStr = [...stack, id].join(' → ');
1614
- errors.push('requires cycle detected: ' + cycleStr);
1615
- return;
1616
- }
1617
- if (color.get(id) === BLACK) return;
1618
- color.set(id, GRAY);
1619
- stack.push(id);
1620
- const cap = capMap.get(id);
1621
- if (cap && Array.isArray(cap.requires)) {
1622
- for (const req of cap.requires) {
1623
- if (capMap.has(req)) dfs(req, stack);
1624
- }
1625
- }
1626
- stack.pop();
1627
- color.set(id, BLACK);
1628
- }
1629
-
1630
- for (const id of capMap.keys()) {
1631
- if (color.get(id) === WHITE) dfs(id, []);
1632
- }
1633
-
1634
- return errors;
1635
- }
1636
-
1637
- // ─── requiresClosure ─────────────────────────────────────────────────────────
1638
-
1639
- /**
1640
- * Compute the transitive requires closure for a capability id.
1641
- * Returns a Set<string> of all transitively required capability ids.
93
+ * Contract:
94
+ * - ENOENT (file not found): returns empty Set silently — legitimate absent case.
95
+ * - Any other read error OR JSON parse error: writes a prominent warning to stderr
96
+ * naming the schema path and the underlying error, then throws ExitError(1).
97
+ * A parse error clearly states the schema is broken (not merely absent).
1642
98
  *
1643
- * @param {string} id
1644
- * @param {Map<string, object>} capMap
99
+ * @param {string} [schemaPath] Path to the config-schema manifest. Defaults to
100
+ * CONFIG_SCHEMA_PATH (the real production path).
101
+ * Overridable for unit testing with fixture paths.
102
+ * @returns {Set<string>}
1645
103
  */
1646
- function computeRequiresClosure(id, capMap) {
1647
- const visited = new Set();
1648
- const queue = [id];
1649
- while (queue.length > 0) {
1650
- const current = queue.shift();
1651
- const cap = capMap.get(current);
1652
- if (!cap || !Array.isArray(cap.requires)) continue;
1653
- for (const req of cap.requires) {
1654
- if (!visited.has(req)) {
1655
- visited.add(req);
1656
- queue.push(req);
1657
- }
1658
- }
1659
- }
1660
- return visited;
1661
- }
1662
-
1663
- // ─── Topological ordering ─────────────────────────────────────────────────────
1664
-
1665
- function topoSortHookEntries(entries, hookKey, hookKind) {
1666
- if (entries.length <= 1) return entries;
1667
-
1668
- // Build adjacency: entry A must come before entry B if B consumes something A produces
1669
- const n = entries.length;
1670
- const inDegree = new Array(n).fill(0);
1671
- const adj = Array.from({ length: n }, () => []);
1672
-
1673
- for (let i = 0; i < n; i++) {
1674
- const producesI = new Set(entries[i][hookKey].produces || []);
1675
- for (let j = 0; j < n; j++) {
1676
- if (i === j) continue;
1677
- const consumesJ = entries[j][hookKey].consumes || [];
1678
- for (const artifact of consumesJ) {
1679
- if (producesI.has(artifact)) {
1680
- adj[i].push(j);
1681
- inDegree[j]++;
1682
- break;
1683
- }
1684
- }
1685
- }
1686
- }
1687
-
1688
- // Kahn's algorithm with stable tiebreak on capId
1689
- const queue = [];
1690
- for (let i = 0; i < n; i++) {
1691
- if (inDegree[i] === 0) queue.push(i);
1692
- }
1693
- // Sort queue by capId for determinism
1694
- queue.sort((a, b) => entries[a].capId.localeCompare(entries[b].capId));
1695
-
1696
- const result = [];
1697
- while (queue.length > 0) {
1698
- // Take the first (sorted) ready node
1699
- const idx = queue.shift();
1700
- result.push(entries[idx]);
1701
- const newReady = [];
1702
- for (const neighbor of adj[idx]) {
1703
- inDegree[neighbor]--;
1704
- if (inDegree[neighbor] === 0) newReady.push(neighbor);
104
+ function loadCentralConfigKeys(schemaPath = CONFIG_SCHEMA_PATH) {
105
+ let raw;
106
+ try {
107
+ raw = fs.readFileSync(schemaPath, 'utf8');
108
+ } catch (err) {
109
+ if (err.code === 'ENOENT') {
110
+ return new Set();
1705
111
  }
1706
- newReady.sort((a, b) => entries[a].capId.localeCompare(entries[b].capId));
1707
- queue.push(...newReady);
112
+ process.stderr.write(
113
+ ' ERROR Failed to read config-schema manifest at ' + schemaPath + ': ' + err.message + '\n',
114
+ );
115
+ throw new ExitError(1, 'could not read config-schema manifest');
1708
116
  }
1709
117
 
1710
- // Fix #2: if result.length < n, Kahn's could not complete — there is a produces/consumes
1711
- // cycle. Do NOT silently fall back to declaration order; throw a clear error.
1712
- if (result.length < n) {
1713
- const sortedIds = entries.map((e) => e.capId).join(', ');
1714
- throw new Error(
1715
- 'produces/consumes cycle detected in ' + hookKind + ' at point "' +
1716
- (entries[0] && entries[0][hookKey] ? entries[0][hookKey].point : '?') +
1717
- '" among capabilities [' + sortedIds + ']: ' +
1718
- 'a cycle in hook produces/consumes prevents deterministic ordering',
118
+ let manifest;
119
+ try {
120
+ manifest = JSON.parse(raw);
121
+ } catch (err) {
122
+ process.stderr.write(
123
+ ' ERROR Config-schema manifest at ' + schemaPath + ' is broken (JSON parse error): ' + err.message + '\n',
1719
124
  );
125
+ throw new ExitError(1, 'config-schema manifest JSON is malformed');
1720
126
  }
1721
- return result;
1722
- }
1723
-
1724
- /**
1725
- * Topologically sort steps at a given point by produces/consumes.
1726
- * Capability-id tiebreak for determinism.
1727
- *
1728
- * @param {{ capId: string, step: object }[]} entries
1729
- * @returns {{ capId: string, step: object }[]}
1730
- */
1731
- function topoSortSteps(entries) {
1732
- return topoSortHookEntries(entries, 'step', 'steps');
1733
- }
1734
127
 
1735
- function topoSortContributions(entries) {
1736
- return topoSortHookEntries(entries, 'contrib', 'contributions');
128
+ return new Set(Array.isArray(manifest.validKeys) ? manifest.validKeys : []);
1737
129
  }
1738
130
 
1739
131
  // ─── ADR-857 Phase 4a: Derived views ─────────────────────────────────────────
1740
132
 
1741
- // FIX 5 (lazy requires): paths are declared at top level but the actual require()
1742
- // calls are deferred into lazy accessor functions so importing this generator for
1743
- // its other exports does NOT fail at module-load time on a fresh/unbuilt worktree.
133
+ // (Config-slice validation, per-capability validators, contract validators,
134
+ // cross-capability validators, topo-sort helpers, and classifyCrossErrors have
135
+ // been moved to gsd-core/bin/lib/capability-validator.cjs per ADR-1244 D2.)
136
+
1744
137
  const INSTALL_PROFILES_PATH = path.join(ROOT, 'gsd-core', 'bin', 'lib', 'install-profiles.cjs');
1745
138
  const CLUSTERS_PATH = path.join(ROOT, 'gsd-core', 'bin', 'lib', 'clusters.cjs');
1746
139
 
@@ -1932,125 +325,6 @@ function runConsistencyGate(capabilityClusters, profileMembership, capMap) {
1932
325
  return warnings;
1933
326
  }
1934
327
 
1935
- // ─── ADR-857 phase 5e: configFormat ↔ installSurface parity gate ─────────────
1936
-
1937
- // Map: installSurface → expected configFormat
1938
- // Derived from the pairing of capability.json descriptors (installSurface)
1939
- // and capability.json descriptors (configFormat). DEFECT.GENERATIVE-FIX: this map
1940
- // is the single parity contract between the two generated surfaces.
1941
- // NOTE: both values come from the descriptor bodies in capMap — no dependency on
1942
- // runtime-config-adapter-registry.cjs, which now requires capability-registry.cjs
1943
- // (the file this gen-script produces), and thus must not be required here.
1944
- const INSTALL_SURFACE_TO_CONFIG_FORMAT = new Map([
1945
- ['settings-json', 'settings-json'],
1946
- ['codex-toml', 'toml'],
1947
- ['copilot-instructions', 'markdown'],
1948
- ['cline-rules', 'markdown-dir'],
1949
- ['cursor-hooks-json', 'none'],
1950
- ['profile-marker-only', 'none'],
1951
- ]);
1952
-
1953
- /**
1954
- * ADR-857 phase 5e: configFormat ↔ installSurface parity gate.
1955
- *
1956
- * For each runtime capability that has an installSurface in its descriptor,
1957
- * assert that its configFormat matches the expected value derived from its
1958
- * installSurface. Both values are read directly from the capMap descriptor
1959
- * bodies — no dependency on runtime-config-adapter-registry.cjs.
1960
- *
1961
- * HARD gate — throws on mismatch (DEFECT.GENERATIVE-FIX: this invariant is
1962
- * derived from two parallel generated surfaces and must fail loudly).
1963
- *
1964
- * @param {Map<string, object>} capMap Fully-validated capability map.
1965
- * @returns {void} Throws on mismatch; returns normally on success.
1966
- */
1967
- function runConfigFormatParityGate(capMap) {
1968
- // Read installSurface directly from the descriptor bodies already loaded into
1969
- // capMap — eliminates the require cycle introduced when adapter-registry was
1970
- // changed to require capability-registry.cjs (ADR-857 phase 5g drive 2).
1971
- for (const [capId, cap] of capMap) {
1972
- if (cap.role !== 'runtime') continue;
1973
-
1974
- const r = cap.runtime;
1975
- if (!r || typeof r.configFormat !== 'string') continue; // already validated above
1976
-
1977
- // Only check runtimes that have an installSurface (i.e. are config-adapter runtimes)
1978
- if (typeof r.installSurface !== 'string') continue; // grok etc. excluded — no installSurface
1979
-
1980
- const installSurface = r.installSurface;
1981
- const expectedConfigFormat = INSTALL_SURFACE_TO_CONFIG_FORMAT.get(installSurface);
1982
-
1983
- if (expectedConfigFormat === undefined) {
1984
- // Unknown installSurface — the mapping needs to be updated
1985
- throw new Error(
1986
- 'configFormat parity gate: runtime "' + capId + '" has installSurface "' + installSurface +
1987
- '" which is not in the INSTALL_SURFACE_TO_CONFIG_FORMAT mapping — ' +
1988
- 'update the mapping in scripts/gen-capability-registry.cjs',
1989
- );
1990
- }
1991
-
1992
- if (r.configFormat !== expectedConfigFormat) {
1993
- throw new Error(
1994
- 'configFormat parity gate FAILED for runtime "' + capId + '":\n' +
1995
- ' installSurface: ' + installSurface + '\n' +
1996
- ' expected configFormat: ' + expectedConfigFormat + '\n' +
1997
- ' actual configFormat: ' + r.configFormat + '\n' +
1998
- 'The capability.json configFormat must match the value derived from installSurface ' +
1999
- '(src: scripts/gen-capability-registry.cjs INSTALL_SURFACE_TO_CONFIG_FORMAT)',
2000
- );
2001
- }
2002
- }
2003
- }
2004
-
2005
- // ─── Gen-time wired guard ─────────────────────────────────────────────────────
2006
-
2007
- /**
2008
- * Validate that every hook point declared by a capability has a corresponding
2009
- * `loop render-hooks <point>` call site in one of the host-loop workflow files.
2010
- *
2011
- * Only valid loop points (in VALID_LOOP_POINTS) are checked here. Invalid points
2012
- * are already caught by validateStep/validateContribution/validateGate — do not
2013
- * double-report.
2014
- *
2015
- * @param {object} cap Validated capability object.
2016
- * @param {Set<string>} wiredSet Set of points that have call sites in host workflows.
2017
- * @returns {string[]} Array of error strings; empty means all points are wired.
2018
- */
2019
- function validateHooksWired(cap, wiredSet) {
2020
- const errors = [];
2021
- const capId = cap.id || '(unknown)';
2022
-
2023
- function checkPoint(point, groupName, idx) {
2024
- // Only flag valid points that are unwired — invalid points are schema-validator's job.
2025
- if (!VALID_LOOP_POINTS.has(point)) return;
2026
- if (!wiredSet.has(point)) {
2027
- errors.push(
2028
- 'capability "' + capId + '" ' + groupName + '[' + idx + '].point "' + point +
2029
- '" is declared but not wired in any host-loop workflow ' +
2030
- '(no `loop render-hooks ' + point + '` call site). ' +
2031
- 'Wire the call site in the host workflow ' +
2032
- '(see scripts/gen-loop-host-contract.cjs STEP_WORKFLOWS) or remove the hook.',
2033
- );
2034
- }
2035
- }
2036
-
2037
- for (let i = 0; i < (cap.steps || []).length; i++) {
2038
- const hook = cap.steps[i];
2039
- if (hook.point !== undefined) checkPoint(hook.point, 'steps', i);
2040
- }
2041
- for (let i = 0; i < (cap.contributions || []).length; i++) {
2042
- const hook = cap.contributions[i];
2043
- if (hook.point !== undefined) checkPoint(hook.point, 'contributions', i);
2044
- }
2045
- for (let i = 0; i < (cap.gates || []).length; i++) {
2046
- const hook = cap.gates[i];
2047
- if (hook.point !== undefined) checkPoint(hook.point, 'gates', i);
2048
- }
2049
-
2050
- return errors;
2051
- }
2052
-
2053
- // ─── Registry builder ─────────────────────────────────────────────────────────
2054
328
 
2055
329
  /**
2056
330
  * Read + validate all capabilities/<id>/capability.json files.
@@ -2460,42 +734,6 @@ function normalizeLineEndings(content) {
2460
734
 
2461
735
  // ─── Main ─────────────────────────────────────────────────────────────────────
2462
736
 
2463
- /**
2464
- * Fix #3: Emit pending-migration WARNINGs for config keys that collide with the central
2465
- * config-schema. Per ADR-894 staged cutover, a collision during the registry-only phase is
2466
- * NOT a hard error — the capability pipeline is being established before the atomic cutover
2467
- * PR for each feature. The registry still generates; the warning tells the maintainer which
2468
- * keys need to be moved out of the central schema at cutover time.
2469
- *
2470
- * A NEW unexpected collision (a key that shouldn't be in both) is also surfaced — the
2471
- * maintainer sees it in build output rather than it being silently swallowed.
2472
- *
2473
- * Reference: ADR-894 §4 "config-key ownership exclusive AND complete — presence in both =
2474
- * collision = a mid-flight migration; finish the move."
2475
- *
2476
- * @param {string[]} crossErrors Errors from validateCrossCapability (may include collision msgs)
2477
- * @param {Map<string, object>} capMap
2478
- * @returns {{ hardErrors: string[], pendingMigrationWarnings: string[] }}
2479
- */
2480
- function classifyCrossErrors(crossErrors) {
2481
- const hardErrors = [];
2482
- const pendingMigrationWarnings = [];
2483
- const collisionRe = /config key "([^"]+)" is declared in capability "([^"]+)" AND exists in the central config-schema/;
2484
-
2485
- for (const e of crossErrors) {
2486
- const m = collisionRe.exec(e);
2487
- if (m) {
2488
- // Collision = pending-migration warning, not a hard error during 3a-impl staged cutover
2489
- pendingMigrationWarnings.push(
2490
- '⚠ pending-migration: capability \'' + m[2] + '\' declares config key \'' + m[1] +
2491
- '\' still present in central config-schema; finish the move at cutover',
2492
- );
2493
- } else {
2494
- hardErrors.push(e);
2495
- }
2496
- }
2497
- return { hardErrors, pendingMigrationWarnings };
2498
- }
2499
737
 
2500
738
  function main() {
2501
739
  const flag = process.argv[2];
@@ -2580,6 +818,11 @@ function main() {
2580
818
 
2581
819
  module.exports = {
2582
820
  validateCapability,
821
+ // ADR-1244 D1: versioned-manifest envelope validation (reused by the runtime overlay, D2)
822
+ validateVersionEnvelope,
823
+ SEMVER_RE,
824
+ SEMVER_RANGE_RE,
825
+ SHA512_INTEGRITY_RE,
2583
826
  validateAgainstContract,
2584
827
  validateConsumesGlobal,
2585
828
  validateCrossCapability,