@opengsd/gsd-core 1.4.2 → 1.5.0-rc.1
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.
- package/.claude-plugin/plugin.json +1 -1
- package/README.md +3 -3
- package/agents/gsd-executor.md +1 -1
- package/agents/gsd-plan-checker.md +11 -2
- package/agents/gsd-planner.md +11 -7
- package/agents/gsd-verifier.md +3 -3
- package/bin/install.js +947 -149
- package/commands/gsd/autonomous.md +5 -1
- package/commands/gsd/ns-manage.md +8 -1
- package/commands/gsd/ns-project.md +5 -0
- package/commands/gsd/ns-review.md +4 -1
- package/commands/gsd/ns-workflow.md +7 -1
- package/commands/gsd/plan-review-convergence.md +6 -5
- package/commands/gsd/surface.md +12 -5
- package/gemini-extension.json +1 -1
- package/gsd-core/bin/gsd-tools.cjs +198 -101
- package/gsd-core/bin/lib/audit-command-router.cjs +61 -0
- package/gsd-core/bin/lib/capability-registry.cjs +417 -0
- package/gsd-core/bin/lib/capability-state.cjs +336 -0
- package/gsd-core/bin/lib/cli-exit.cjs +22 -3
- package/gsd-core/bin/lib/config-loader.cjs +716 -0
- package/gsd-core/bin/lib/configuration.cjs +4 -34
- package/gsd-core/bin/lib/core-utils.cjs +198 -0
- package/gsd-core/bin/lib/core.cjs +57 -1817
- package/gsd-core/bin/lib/federated-config.cjs +182 -0
- package/gsd-core/bin/lib/graphify-command-router.cjs +74 -0
- package/gsd-core/bin/lib/init.cjs +58 -12
- package/gsd-core/bin/lib/install-profiles.cjs +157 -3
- package/gsd-core/bin/lib/installer-migrations/004-prune-stale-pristine-snapshots.cjs +123 -0
- package/gsd-core/bin/lib/intel-command-router.cjs +116 -0
- package/gsd-core/bin/lib/io.cjs +167 -0
- package/gsd-core/bin/lib/loop-host-contract.cjs +105 -0
- package/gsd-core/bin/lib/loop-resolver.cjs +460 -0
- package/gsd-core/bin/lib/model-resolver.cjs +426 -0
- package/gsd-core/bin/lib/phase-id.cjs +215 -0
- package/gsd-core/bin/lib/phase-locator.cjs +148 -0
- package/gsd-core/bin/lib/profile-pipeline.cjs +2 -2
- package/gsd-core/bin/lib/roadmap-parser.cjs +443 -0
- package/gsd-core/bin/lib/roadmap.cjs +4 -1
- package/gsd-core/bin/lib/runtime-artifact-layout.cjs +96 -9
- package/gsd-core/bin/lib/runtime-config-adapter-registry.cjs +2 -1
- package/gsd-core/bin/lib/runtime-homes.cjs +40 -0
- package/gsd-core/bin/lib/runtime-name-policy.cjs +1 -0
- package/gsd-core/bin/lib/shell-command-projection.cjs +13 -0
- package/gsd-core/bin/lib/state.cjs +114 -2
- package/gsd-core/bin/lib/surface.cjs +66 -14
- package/gsd-core/bin/lib/verify.cjs +1 -1
- package/gsd-core/bin/shared/model-catalog.json +5 -0
- package/gsd-core/bin/shared/runtime-aliases.manifest.json +3 -0
- package/gsd-core/bin/verify-reapply-patches.cjs +57 -7
- package/gsd-core/references/planner-reviews.md +5 -2
- package/gsd-core/templates/phase-prompt.md +7 -7
- package/gsd-core/templates/project.md +19 -2
- package/gsd-core/templates/summary-complex.md +1 -0
- package/gsd-core/templates/summary-minimal.md +1 -0
- package/gsd-core/templates/summary-standard.md +1 -0
- package/gsd-core/templates/summary.md +1 -0
- package/gsd-core/workflows/_runtime-launcher.snippet.sh +1 -1
- package/gsd-core/workflows/add-backlog.md +1 -1
- package/gsd-core/workflows/add-phase.md +1 -1
- package/gsd-core/workflows/add-tests.md +1 -1
- package/gsd-core/workflows/add-todo.md +1 -1
- package/gsd-core/workflows/ai-integration-phase.md +1 -1
- package/gsd-core/workflows/audit-fix.md +1 -1
- package/gsd-core/workflows/audit-milestone.md +1 -1
- package/gsd-core/workflows/audit-uat.md +1 -1
- package/gsd-core/workflows/autonomous.md +86 -15
- package/gsd-core/workflows/check-todos.md +1 -1
- package/gsd-core/workflows/cleanup.md +1 -1
- package/gsd-core/workflows/code-review-fix.md +6 -4
- package/gsd-core/workflows/code-review.md +3 -2
- package/gsd-core/workflows/complete-milestone.md +11 -5
- package/gsd-core/workflows/debug.md +1 -1
- package/gsd-core/workflows/diagnose-issues.md +1 -1
- package/gsd-core/workflows/discuss-phase/modes/advisor.md +1 -1
- package/gsd-core/workflows/discuss-phase/modes/auto.md +1 -1
- package/gsd-core/workflows/discuss-phase/modes/chain.md +1 -1
- package/gsd-core/workflows/discuss-phase-assumptions.md +1 -1
- package/gsd-core/workflows/discuss-phase.md +8 -1
- package/gsd-core/workflows/do.md +1 -1
- package/gsd-core/workflows/docs-update.md +1 -1
- package/gsd-core/workflows/edit-phase.md +1 -1
- package/gsd-core/workflows/eval-review.md +4 -1
- package/gsd-core/workflows/execute-phase/steps/codebase-drift-gate.md +1 -1
- package/gsd-core/workflows/execute-phase/steps/post-merge-gate.md +1 -1
- package/gsd-core/workflows/execute-phase.md +8 -1
- package/gsd-core/workflows/execute-plan.md +1 -1
- package/gsd-core/workflows/explore.md +1 -1
- package/gsd-core/workflows/extract-learnings.md +1 -1
- package/gsd-core/workflows/forensics.md +1 -1
- package/gsd-core/workflows/graduation.md +1 -1
- package/gsd-core/workflows/health.md +1 -1
- package/gsd-core/workflows/help/modes/full.md +1 -1
- package/gsd-core/workflows/import.md +1 -1
- package/gsd-core/workflows/ingest-docs.md +1 -1
- package/gsd-core/workflows/insert-phase.md +1 -1
- package/gsd-core/workflows/list-workspaces.md +1 -1
- package/gsd-core/workflows/manager.md +1 -1
- package/gsd-core/workflows/map-codebase.md +1 -1
- package/gsd-core/workflows/milestone-summary.md +1 -1
- package/gsd-core/workflows/mvp-phase.md +1 -1
- package/gsd-core/workflows/new-milestone.md +1 -1
- package/gsd-core/workflows/new-project.md +1 -1
- package/gsd-core/workflows/new-workspace.md +1 -1
- package/gsd-core/workflows/next.md +1 -1
- package/gsd-core/workflows/pause-work.md +1 -1
- package/gsd-core/workflows/plan-milestone-gaps.md +1 -1
- package/gsd-core/workflows/plan-phase.md +27 -2
- package/gsd-core/workflows/plan-review-convergence.md +76 -63
- package/gsd-core/workflows/plant-seed.md +1 -1
- package/gsd-core/workflows/profile-user.md +1 -1
- package/gsd-core/workflows/progress.md +1 -1
- package/gsd-core/workflows/quick.md +2 -2
- package/gsd-core/workflows/reapply-patches.md +18 -1
- package/gsd-core/workflows/remove-phase.md +1 -1
- package/gsd-core/workflows/remove-workspace.md +1 -1
- package/gsd-core/workflows/resume-project.md +1 -1
- package/gsd-core/workflows/review.md +1 -1
- package/gsd-core/workflows/scan.md +1 -1
- package/gsd-core/workflows/secure-phase.md +1 -1
- package/gsd-core/workflows/settings-advanced.md +1 -1
- package/gsd-core/workflows/settings-integrations.md +1 -1
- package/gsd-core/workflows/settings.md +1 -1
- package/gsd-core/workflows/ship.md +8 -1
- package/gsd-core/workflows/sketch-wrap-up.md +1 -1
- package/gsd-core/workflows/sketch.md +1 -1
- package/gsd-core/workflows/spec-phase.md +1 -1
- package/gsd-core/workflows/spike-wrap-up.md +1 -1
- package/gsd-core/workflows/spike.md +1 -1
- package/gsd-core/workflows/stats.md +1 -1
- package/gsd-core/workflows/thread.md +1 -1
- package/gsd-core/workflows/transition.md +1 -1
- package/gsd-core/workflows/ui-phase.md +1 -1
- package/gsd-core/workflows/ui-review.md +1 -1
- package/gsd-core/workflows/ultraplan-phase.md +1 -1
- package/gsd-core/workflows/update.md +20 -15
- package/gsd-core/workflows/validate-phase.md +1 -1
- package/gsd-core/workflows/verify-phase.md +1 -1
- package/gsd-core/workflows/verify-work.md +8 -1
- package/package.json +7 -2
- package/scripts/base64-scan.sh +1 -1
- package/scripts/changeset/cli.cjs +9 -2
- package/scripts/changeset/lint.cjs +38 -2
- package/scripts/ci-test-scope.cjs +21 -10
- package/scripts/gen-capability-registry.cjs +1808 -0
- package/scripts/gen-loop-host-contract.cjs +471 -0
- package/scripts/lint-regression-test-names.allowlist.json +269 -0
- package/scripts/lint-regression-test-names.cjs +117 -0
- package/scripts/lint-test-file-count.allowlist.json +12 -4
- package/scripts/prompt-injection-scan.sh +4 -4
- package/scripts/run-tests.cjs +79 -16
- package/scripts/secret-scan.sh +3 -3
- package/scripts/run-cross-platform-tests.cjs +0 -67
|
@@ -0,0 +1,1808 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
'use strict';
|
|
3
|
+
|
|
4
|
+
/**
|
|
5
|
+
* gen-capability-registry.cjs — generates gsd-core/bin/lib/capability-registry.cjs
|
|
6
|
+
* from every capabilities/<id>/capability.json declaration.
|
|
7
|
+
*
|
|
8
|
+
* Usage:
|
|
9
|
+
* node scripts/gen-capability-registry.cjs # print to stdout
|
|
10
|
+
* node scripts/gen-capability-registry.cjs --write # write capability-registry.cjs
|
|
11
|
+
* node scripts/gen-capability-registry.cjs --check # exit 1 if committed registry is stale
|
|
12
|
+
*
|
|
13
|
+
* ADR-894 phase 3a-impl. Validates each capability against the schema, enforces
|
|
14
|
+
* cross-capability invariants, materializes hook ordering, and emits a role-
|
|
15
|
+
* partitioned CommonJS registry module.
|
|
16
|
+
*/
|
|
17
|
+
|
|
18
|
+
const fs = require('node:fs');
|
|
19
|
+
const path = require('node:path');
|
|
20
|
+
|
|
21
|
+
const { ExitError, runMain } = require('./lib/cli-exit.cjs');
|
|
22
|
+
|
|
23
|
+
const ROOT = path.resolve(__dirname, '..');
|
|
24
|
+
const CAPABILITIES_DIR = path.join(ROOT, 'capabilities');
|
|
25
|
+
const REGISTRY_PATH = path.join(ROOT, 'gsd-core', 'bin', 'lib', 'capability-registry.cjs');
|
|
26
|
+
const CONFIG_SCHEMA_PATH = path.join(ROOT, 'gsd-core', 'bin', 'shared', 'config-schema.manifest.json');
|
|
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
|
+
// Canonical point order — explicit constant (do NOT rely on Set insertion order).
|
|
38
|
+
// Used for point-ordering semantics in consumes-satisfiability validation and topo-sort.
|
|
39
|
+
const POINT_ORDER = [
|
|
40
|
+
'discuss:pre',
|
|
41
|
+
'discuss:post',
|
|
42
|
+
'plan:pre',
|
|
43
|
+
'plan:post',
|
|
44
|
+
'execute:pre',
|
|
45
|
+
'execute:wave:pre',
|
|
46
|
+
'execute:wave:post',
|
|
47
|
+
'execute:post',
|
|
48
|
+
'verify:pre',
|
|
49
|
+
'verify:post',
|
|
50
|
+
'ship:pre',
|
|
51
|
+
'ship:post',
|
|
52
|
+
];
|
|
53
|
+
|
|
54
|
+
// C1: Artifact availability — host-produced artifacts become available at their step's :post
|
|
55
|
+
// point. Build a map: artifact → earliest POINT_ORDER index at which it is available.
|
|
56
|
+
// (discuss produces CONTEXT.md → discuss:post = index 1;
|
|
57
|
+
// plan produces PLAN.md → plan:post = index 3;
|
|
58
|
+
// execute produces SUMMARY.md → execute:post = index 7;
|
|
59
|
+
// verify produces UAT.md → verify:post = index 9)
|
|
60
|
+
//
|
|
61
|
+
// NOTE: this map covers ONLY host artifacts. Hook-produced artifacts are handled per-run
|
|
62
|
+
// during consumes-satisfiability validation (C2 global pass).
|
|
63
|
+
const HOST_ARTIFACT_EARLIEST_POINT_IDX = (() => {
|
|
64
|
+
const m = Object.create(null);
|
|
65
|
+
for (const entry of LOOP_HOST_CONTRACT) {
|
|
66
|
+
// The :post point is the last point in each step's points array.
|
|
67
|
+
const postPoint = entry.points[entry.points.length - 1];
|
|
68
|
+
const postIdx = POINT_ORDER.indexOf(postPoint);
|
|
69
|
+
for (const artifact of entry.coreArtifacts.produces) {
|
|
70
|
+
// Only record the earliest (should be unique, but take min to be safe).
|
|
71
|
+
if (m[artifact] === undefined || postIdx < m[artifact]) {
|
|
72
|
+
m[artifact] = postIdx;
|
|
73
|
+
}
|
|
74
|
+
}
|
|
75
|
+
}
|
|
76
|
+
return m;
|
|
77
|
+
})();
|
|
78
|
+
|
|
79
|
+
// Flatten all valid loop points into a Set for O(1) validation
|
|
80
|
+
const VALID_LOOP_POINTS = new Set(POINT_ORDER);
|
|
81
|
+
|
|
82
|
+
// Map point → step contract (agentRoles + coreArtifacts)
|
|
83
|
+
const POINT_TO_CONTRACT = new Map();
|
|
84
|
+
for (const entry of LOOP_HOST_CONTRACT) {
|
|
85
|
+
for (const point of entry.points) {
|
|
86
|
+
POINT_TO_CONTRACT.set(point, entry);
|
|
87
|
+
}
|
|
88
|
+
}
|
|
89
|
+
|
|
90
|
+
// ─── Central config-schema loader ────────────────────────────────────────────
|
|
91
|
+
|
|
92
|
+
/**
|
|
93
|
+
* Loads the set of keys from the central config-schema manifest.
|
|
94
|
+
* Returns a Set<string>. Used for collision detection.
|
|
95
|
+
*
|
|
96
|
+
* TODO: distinguish file-not-found (ok, return empty Set) from JSON-parse-error
|
|
97
|
+
* (should warn — a parse error means the schema is broken, not just absent).
|
|
98
|
+
*/
|
|
99
|
+
function loadCentralConfigKeys() {
|
|
100
|
+
try {
|
|
101
|
+
const manifest = JSON.parse(fs.readFileSync(CONFIG_SCHEMA_PATH, 'utf8'));
|
|
102
|
+
return new Set(Array.isArray(manifest.validKeys) ? manifest.validKeys : []);
|
|
103
|
+
} catch (_) {
|
|
104
|
+
return new Set();
|
|
105
|
+
}
|
|
106
|
+
}
|
|
107
|
+
|
|
108
|
+
// ─── Config-slice validation ──────────────────────────────────────────────────
|
|
109
|
+
|
|
110
|
+
const VALID_CONFIG_SLICE_TYPES = new Set(['boolean', 'string', 'number', 'enum']);
|
|
111
|
+
|
|
112
|
+
/**
|
|
113
|
+
* Validate a single config-slice entry (one key's { type, default, description }).
|
|
114
|
+
* Returns an array of error strings. Empty = valid.
|
|
115
|
+
*
|
|
116
|
+
* @param {string} capId Capability id (for error messages)
|
|
117
|
+
* @param {string} key Config key (for error messages)
|
|
118
|
+
* @param {object} slice The slice object from cap.config[key]
|
|
119
|
+
* @returns {string[]}
|
|
120
|
+
*/
|
|
121
|
+
function validateConfigSliceEntry(capId, key, slice) {
|
|
122
|
+
const errors = [];
|
|
123
|
+
|
|
124
|
+
if (typeof slice !== 'object' || slice === null || Array.isArray(slice)) {
|
|
125
|
+
errors.push('capability "' + capId + '" config["' + key + '"]: slice must be a non-null object');
|
|
126
|
+
return errors;
|
|
127
|
+
}
|
|
128
|
+
|
|
129
|
+
// type must be one of the allowed set
|
|
130
|
+
if (!VALID_CONFIG_SLICE_TYPES.has(slice.type)) {
|
|
131
|
+
errors.push(
|
|
132
|
+
'capability "' + capId + '" config["' + key + '"]: type must be one of ' +
|
|
133
|
+
[...VALID_CONFIG_SLICE_TYPES].join(', ') + ' (got: ' + JSON.stringify(slice.type) + ')',
|
|
134
|
+
);
|
|
135
|
+
}
|
|
136
|
+
|
|
137
|
+
// default must be present
|
|
138
|
+
if (!Object.prototype.hasOwnProperty.call(slice, 'default')) {
|
|
139
|
+
errors.push(
|
|
140
|
+
'capability "' + capId + '" config["' + key + '"]: default is required',
|
|
141
|
+
);
|
|
142
|
+
} else {
|
|
143
|
+
// type-consistency check
|
|
144
|
+
const def = slice.default;
|
|
145
|
+
if (slice.type === 'boolean') {
|
|
146
|
+
if (typeof def !== 'boolean') {
|
|
147
|
+
errors.push(
|
|
148
|
+
'capability "' + capId + '" config["' + key + '"]: default must be a boolean for type:"boolean" (got: ' + typeof def + ')',
|
|
149
|
+
);
|
|
150
|
+
}
|
|
151
|
+
} else if (slice.type === 'string') {
|
|
152
|
+
if (typeof def !== 'string') {
|
|
153
|
+
errors.push(
|
|
154
|
+
'capability "' + capId + '" config["' + key + '"]: default must be a string for type:"string" (got: ' + typeof def + ')',
|
|
155
|
+
);
|
|
156
|
+
}
|
|
157
|
+
} else if (slice.type === 'number') {
|
|
158
|
+
if (typeof def !== 'number') {
|
|
159
|
+
errors.push(
|
|
160
|
+
'capability "' + capId + '" config["' + key + '"]: default must be a number for type:"number" (got: ' + typeof def + ')',
|
|
161
|
+
);
|
|
162
|
+
} else if (!Number.isFinite(def)) {
|
|
163
|
+
// FIX 6a: Reject NaN and non-finite number defaults
|
|
164
|
+
errors.push(
|
|
165
|
+
'capability "' + capId + '" config["' + key + '"]: default for type:"number" must be a finite number (got: ' + String(def) + ')',
|
|
166
|
+
);
|
|
167
|
+
}
|
|
168
|
+
} else if (slice.type === 'enum') {
|
|
169
|
+
// FIX 5a: enum REQUIRES a non-empty values array (all strings), and default must be in it
|
|
170
|
+
if (!Array.isArray(slice.values) || slice.values.length === 0) {
|
|
171
|
+
errors.push(
|
|
172
|
+
'capability "' + capId + '" config["' + key + '"]: type:"enum" requires a non-empty "values" array of strings',
|
|
173
|
+
);
|
|
174
|
+
} else if (!slice.values.every((v) => typeof v === 'string')) {
|
|
175
|
+
errors.push(
|
|
176
|
+
'capability "' + capId + '" config["' + key + '"]: type:"enum" values array must contain only strings',
|
|
177
|
+
);
|
|
178
|
+
}
|
|
179
|
+
if (typeof def !== 'string') {
|
|
180
|
+
errors.push(
|
|
181
|
+
'capability "' + capId + '" config["' + key + '"]: default must be a string for type:"enum" (got: ' + typeof def + ')',
|
|
182
|
+
);
|
|
183
|
+
} else if (Array.isArray(slice.values) && slice.values.length > 0 && !slice.values.includes(def)) {
|
|
184
|
+
errors.push(
|
|
185
|
+
'capability "' + capId + '" config["' + key + '"]: default "' + def +
|
|
186
|
+
'" is not one of the declared enum values [' + slice.values.join(', ') + ']',
|
|
187
|
+
);
|
|
188
|
+
}
|
|
189
|
+
}
|
|
190
|
+
}
|
|
191
|
+
|
|
192
|
+
// description must be a non-empty string
|
|
193
|
+
if (typeof slice.description !== 'string' || slice.description.length === 0) {
|
|
194
|
+
errors.push(
|
|
195
|
+
'capability "' + capId + '" config["' + key + '"]: description must be a non-empty string (got: ' + JSON.stringify(slice.description) + ')',
|
|
196
|
+
);
|
|
197
|
+
}
|
|
198
|
+
|
|
199
|
+
return errors;
|
|
200
|
+
}
|
|
201
|
+
|
|
202
|
+
// ─── Per-capability validation ────────────────────────────────────────────────
|
|
203
|
+
|
|
204
|
+
const KEBAB_RE = /^[a-z][a-z0-9-]*$/;
|
|
205
|
+
const VALID_ROLES = new Set(['feature', 'runtime']);
|
|
206
|
+
const VALID_TIERS = new Set(['core', 'standard', 'full']);
|
|
207
|
+
const VALID_ON_ERROR = new Set(['skip', 'halt']);
|
|
208
|
+
|
|
209
|
+
/**
|
|
210
|
+
* Validate a single capability declaration.
|
|
211
|
+
*
|
|
212
|
+
* @param {object} cap The parsed JSON object.
|
|
213
|
+
* @param {string} folderId The folder name (must equal cap.id).
|
|
214
|
+
* @returns {string[]} Array of error strings; empty = valid.
|
|
215
|
+
*/
|
|
216
|
+
function validateCapability(cap, folderId) {
|
|
217
|
+
const errors = [];
|
|
218
|
+
|
|
219
|
+
if (typeof cap !== 'object' || cap === null || Array.isArray(cap)) {
|
|
220
|
+
return ['capability must be a JSON object'];
|
|
221
|
+
}
|
|
222
|
+
|
|
223
|
+
// ── Common envelope ────────────────────────────────────────────────────────
|
|
224
|
+
|
|
225
|
+
if (typeof cap.id !== 'string' || !KEBAB_RE.test(cap.id)) {
|
|
226
|
+
errors.push('id must be a kebab-case string');
|
|
227
|
+
} else if (cap.id !== folderId) {
|
|
228
|
+
errors.push('id "' + cap.id + '" must equal the folder name "' + folderId + '"');
|
|
229
|
+
}
|
|
230
|
+
|
|
231
|
+
if (!VALID_ROLES.has(cap.role)) {
|
|
232
|
+
errors.push('role must be one of: feature, runtime (got: ' + cap.role + ')');
|
|
233
|
+
}
|
|
234
|
+
|
|
235
|
+
if (typeof cap.title !== 'string' || cap.title.length === 0) {
|
|
236
|
+
errors.push('title must be a non-empty string');
|
|
237
|
+
}
|
|
238
|
+
|
|
239
|
+
// C4: description is required
|
|
240
|
+
if (typeof cap.description !== 'string' || cap.description.length === 0) {
|
|
241
|
+
errors.push('description must be a non-empty string');
|
|
242
|
+
}
|
|
243
|
+
|
|
244
|
+
if (!VALID_TIERS.has(cap.tier)) {
|
|
245
|
+
errors.push('tier must be one of: core, standard, full (got: ' + cap.tier + ')');
|
|
246
|
+
}
|
|
247
|
+
|
|
248
|
+
if (!Array.isArray(cap.requires)) {
|
|
249
|
+
errors.push('requires must be an array of capability ids');
|
|
250
|
+
} else {
|
|
251
|
+
for (const req of cap.requires) {
|
|
252
|
+
if (typeof req !== 'string') {
|
|
253
|
+
errors.push('requires entries must be strings (got: ' + JSON.stringify(req) + ')');
|
|
254
|
+
}
|
|
255
|
+
}
|
|
256
|
+
}
|
|
257
|
+
|
|
258
|
+
// ── Role-specific body ────────────────────────────────────────────────────
|
|
259
|
+
|
|
260
|
+
if (cap.role === 'feature') {
|
|
261
|
+
errors.push(...validateFeatureBody(cap));
|
|
262
|
+
} else if (cap.role === 'runtime') {
|
|
263
|
+
errors.push(...validateRuntimeBody(cap));
|
|
264
|
+
}
|
|
265
|
+
|
|
266
|
+
return errors;
|
|
267
|
+
}
|
|
268
|
+
|
|
269
|
+
/**
|
|
270
|
+
* ADR-959: Validate a single commands[] entry on a feature-role capability.
|
|
271
|
+
* { family: string, module: string, router: string, subcommands?: string[] }
|
|
272
|
+
*
|
|
273
|
+
* - family: non-empty string, no reserved names
|
|
274
|
+
* - module: non-empty string, no path traversal, no absolute paths, no "/"
|
|
275
|
+
* segments other than a bare basename (expected form: "foo.cjs")
|
|
276
|
+
* - router: non-empty string
|
|
277
|
+
* - subcommands: optional array of strings (doc/introspection only)
|
|
278
|
+
*
|
|
279
|
+
* @param {string} capId Capability id (for error messages)
|
|
280
|
+
* @param {*} entry The entry to validate
|
|
281
|
+
* @param {string} prefix Path prefix (e.g. "commands[0]")
|
|
282
|
+
* @returns {string[]} Array of error strings; empty = valid.
|
|
283
|
+
*/
|
|
284
|
+
function validateCommandEntry(capId, entry, prefix) {
|
|
285
|
+
const errors = [];
|
|
286
|
+
const ctx = 'capability "' + capId + '" ' + prefix;
|
|
287
|
+
|
|
288
|
+
if (typeof entry !== 'object' || entry === null || Array.isArray(entry)) {
|
|
289
|
+
errors.push(ctx + ' must be an object with family, module, and router');
|
|
290
|
+
return errors;
|
|
291
|
+
}
|
|
292
|
+
|
|
293
|
+
// family: non-empty string, no reserved names
|
|
294
|
+
if (typeof entry.family !== 'string' || entry.family.length === 0) {
|
|
295
|
+
errors.push(ctx + '.family must be a non-empty string');
|
|
296
|
+
} else if (entry.family === '__proto__' || entry.family === 'constructor' || entry.family === 'prototype') {
|
|
297
|
+
// S2a: inline literal reserved-name guard (CodeQL barrier)
|
|
298
|
+
errors.push(ctx + '.family "' + entry.family + '" is a reserved name');
|
|
299
|
+
}
|
|
300
|
+
|
|
301
|
+
// module: must be a safe bare basename matching /^[A-Za-z0-9._-]+\.cjs$/ —
|
|
302
|
+
// no path separators, no "..", no NUL bytes, no absolute paths, ends in .cjs.
|
|
303
|
+
// This conservative pattern subsumes all earlier traversal/absolute/separator checks.
|
|
304
|
+
if (typeof entry.module !== 'string' || entry.module.length === 0) {
|
|
305
|
+
errors.push(ctx + '.module must be a non-empty string');
|
|
306
|
+
} else {
|
|
307
|
+
const mod = entry.module;
|
|
308
|
+
const SAFE_BASENAME = /^[A-Za-z0-9._-]+\.cjs$/;
|
|
309
|
+
if (!SAFE_BASENAME.test(mod)) {
|
|
310
|
+
errors.push(
|
|
311
|
+
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: ' +
|
|
312
|
+
JSON.stringify(mod),
|
|
313
|
+
);
|
|
314
|
+
}
|
|
315
|
+
}
|
|
316
|
+
|
|
317
|
+
// router: non-empty string
|
|
318
|
+
if (typeof entry.router !== 'string' || entry.router.length === 0) {
|
|
319
|
+
errors.push(ctx + '.router must be a non-empty string');
|
|
320
|
+
}
|
|
321
|
+
|
|
322
|
+
// subcommands: optional array of non-empty strings (doc/introspection only)
|
|
323
|
+
if (entry.subcommands !== undefined) {
|
|
324
|
+
if (!Array.isArray(entry.subcommands)) {
|
|
325
|
+
errors.push(ctx + '.subcommands must be an array of strings if present');
|
|
326
|
+
} else {
|
|
327
|
+
for (let i = 0; i < entry.subcommands.length; i++) {
|
|
328
|
+
if (typeof entry.subcommands[i] !== 'string') {
|
|
329
|
+
errors.push(ctx + '.subcommands[' + i + '] must be a string');
|
|
330
|
+
} else if (entry.subcommands[i].length === 0) {
|
|
331
|
+
errors.push(ctx + '.subcommands[' + i + '] must be a non-empty string');
|
|
332
|
+
}
|
|
333
|
+
}
|
|
334
|
+
}
|
|
335
|
+
}
|
|
336
|
+
|
|
337
|
+
return errors;
|
|
338
|
+
}
|
|
339
|
+
|
|
340
|
+
function validateFeatureBody(cap) {
|
|
341
|
+
const errors = [];
|
|
342
|
+
|
|
343
|
+
if (!Array.isArray(cap.skills)) {
|
|
344
|
+
errors.push('skills must be an array of strings');
|
|
345
|
+
} else {
|
|
346
|
+
for (const s of cap.skills) {
|
|
347
|
+
if (typeof s !== 'string') {
|
|
348
|
+
errors.push('skills entries must be strings');
|
|
349
|
+
} else if (s === '__proto__' || s === 'constructor' || s === 'prototype') {
|
|
350
|
+
// S2a: inline literal reserved-name guard (CodeQL barrier)
|
|
351
|
+
errors.push('skills entry "' + s + '" is a reserved name');
|
|
352
|
+
}
|
|
353
|
+
}
|
|
354
|
+
}
|
|
355
|
+
|
|
356
|
+
// ADR-959: optional commands array
|
|
357
|
+
if (cap.commands !== undefined) {
|
|
358
|
+
if (!Array.isArray(cap.commands)) {
|
|
359
|
+
errors.push('commands must be an array of {family, module, router} objects');
|
|
360
|
+
} else {
|
|
361
|
+
for (let i = 0; i < cap.commands.length; i++) {
|
|
362
|
+
errors.push(...validateCommandEntry(cap.id || cap.role, cap.commands[i], 'commands[' + i + ']'));
|
|
363
|
+
}
|
|
364
|
+
}
|
|
365
|
+
}
|
|
366
|
+
|
|
367
|
+
if (!Array.isArray(cap.agents)) {
|
|
368
|
+
errors.push('agents must be an array of strings');
|
|
369
|
+
} else {
|
|
370
|
+
for (const a of cap.agents) {
|
|
371
|
+
if (typeof a !== 'string') {
|
|
372
|
+
errors.push('agents entries must be strings');
|
|
373
|
+
} else if (a === '__proto__' || a === 'constructor' || a === 'prototype') {
|
|
374
|
+
// S2a: inline literal reserved-name guard (CodeQL barrier)
|
|
375
|
+
errors.push('agents entry "' + a + '" is a reserved name');
|
|
376
|
+
}
|
|
377
|
+
}
|
|
378
|
+
}
|
|
379
|
+
|
|
380
|
+
if (typeof cap.config !== 'object' || cap.config === null || Array.isArray(cap.config)) {
|
|
381
|
+
errors.push('config must be an object');
|
|
382
|
+
} else {
|
|
383
|
+
// C5: validate config key names and value shapes
|
|
384
|
+
for (const key of Object.keys(cap.config)) {
|
|
385
|
+
if (key === '' ) {
|
|
386
|
+
errors.push('config keys must be non-empty strings');
|
|
387
|
+
} else if (key === '__proto__' || key === 'constructor' || key === 'prototype') {
|
|
388
|
+
// S2a: inline literal reserved-name guard (CodeQL barrier)
|
|
389
|
+
errors.push('config key "' + key + '" is a reserved name');
|
|
390
|
+
}
|
|
391
|
+
const val = cap.config[key];
|
|
392
|
+
if (val === null || typeof val !== 'object' || Array.isArray(val)) {
|
|
393
|
+
errors.push('config["' + key + '"] must be an object (got: ' + (val === null ? 'null' : typeof val) + ')');
|
|
394
|
+
} else if (typeof val.type !== 'string' || val.type.length === 0) {
|
|
395
|
+
errors.push('config["' + key + '"] must have a string "type" field (e.g. "boolean", "string", "number", "enum")');
|
|
396
|
+
}
|
|
397
|
+
}
|
|
398
|
+
}
|
|
399
|
+
|
|
400
|
+
// C4: hooks, when present, must be an array of {event: string, script: string}
|
|
401
|
+
if (cap.hooks !== undefined) {
|
|
402
|
+
if (!Array.isArray(cap.hooks)) {
|
|
403
|
+
errors.push('hooks must be an array of {event, script} objects');
|
|
404
|
+
} else {
|
|
405
|
+
for (let i = 0; i < cap.hooks.length; i++) {
|
|
406
|
+
const h = cap.hooks[i];
|
|
407
|
+
if (typeof h !== 'object' || h === null || Array.isArray(h)) {
|
|
408
|
+
errors.push('hooks[' + i + '] must be an object with event and script keys');
|
|
409
|
+
} else {
|
|
410
|
+
if (typeof h.event !== 'string' || h.event.length === 0) {
|
|
411
|
+
errors.push('hooks[' + i + '].event must be a non-empty string');
|
|
412
|
+
}
|
|
413
|
+
if (typeof h.script !== 'string' || h.script.length === 0) {
|
|
414
|
+
errors.push('hooks[' + i + '].script must be a non-empty string');
|
|
415
|
+
}
|
|
416
|
+
}
|
|
417
|
+
}
|
|
418
|
+
}
|
|
419
|
+
}
|
|
420
|
+
|
|
421
|
+
if (!Array.isArray(cap.steps)) {
|
|
422
|
+
errors.push('steps must be an array');
|
|
423
|
+
} else {
|
|
424
|
+
for (let i = 0; i < cap.steps.length; i++) {
|
|
425
|
+
errors.push(...validateStep(cap.steps[i], 'steps[' + i + ']'));
|
|
426
|
+
}
|
|
427
|
+
}
|
|
428
|
+
|
|
429
|
+
if (!Array.isArray(cap.contributions)) {
|
|
430
|
+
errors.push('contributions must be an array');
|
|
431
|
+
} else {
|
|
432
|
+
for (let i = 0; i < cap.contributions.length; i++) {
|
|
433
|
+
errors.push(...validateContribution(cap.contributions[i], 'contributions[' + i + ']'));
|
|
434
|
+
}
|
|
435
|
+
}
|
|
436
|
+
|
|
437
|
+
if (!Array.isArray(cap.gates)) {
|
|
438
|
+
errors.push('gates must be an array');
|
|
439
|
+
} else {
|
|
440
|
+
for (let i = 0; i < cap.gates.length; i++) {
|
|
441
|
+
errors.push(...validateGate(cap.gates[i], 'gates[' + i + ']'));
|
|
442
|
+
}
|
|
443
|
+
}
|
|
444
|
+
|
|
445
|
+
return errors;
|
|
446
|
+
}
|
|
447
|
+
|
|
448
|
+
// C3: Validate role:runtime body
|
|
449
|
+
const VALID_CONFIG_FORMATS = new Set(['settings-json', 'toml', 'markdown', 'markdown-dir', 'none']);
|
|
450
|
+
const FEATURE_FIELDS_FORBIDDEN_ON_RUNTIME = ['skills', 'agents', 'steps', 'contributions', 'gates', 'hooks'];
|
|
451
|
+
|
|
452
|
+
function validateRuntimeBody(cap) {
|
|
453
|
+
const errors = [];
|
|
454
|
+
|
|
455
|
+
// C3: feature-only fields must NOT appear on a runtime cap
|
|
456
|
+
for (const field of FEATURE_FIELDS_FORBIDDEN_ON_RUNTIME) {
|
|
457
|
+
if (cap[field] !== undefined) {
|
|
458
|
+
errors.push('role:runtime capability must not have "' + field + '" (feature-only field)');
|
|
459
|
+
}
|
|
460
|
+
}
|
|
461
|
+
|
|
462
|
+
// C3: require a runtime object
|
|
463
|
+
if (typeof cap.runtime !== 'object' || cap.runtime === null || Array.isArray(cap.runtime)) {
|
|
464
|
+
errors.push('role:runtime capability must have a "runtime" object');
|
|
465
|
+
return errors; // can't validate further without the object
|
|
466
|
+
}
|
|
467
|
+
|
|
468
|
+
const r = cap.runtime;
|
|
469
|
+
if (typeof r.configHome !== 'string' || r.configHome.length === 0) {
|
|
470
|
+
errors.push('runtime.configHome must be a non-empty string');
|
|
471
|
+
}
|
|
472
|
+
if (!VALID_CONFIG_FORMATS.has(r.configFormat)) {
|
|
473
|
+
errors.push('runtime.configFormat must be one of: ' + [...VALID_CONFIG_FORMATS].join(', ') + ' (got: ' + r.configFormat + ')');
|
|
474
|
+
}
|
|
475
|
+
if (!Array.isArray(r.artifactLayout)) {
|
|
476
|
+
errors.push('runtime.artifactLayout must be an array');
|
|
477
|
+
}
|
|
478
|
+
if (typeof r.commandStyle !== 'string' || r.commandStyle.length === 0) {
|
|
479
|
+
errors.push('runtime.commandStyle must be a non-empty string');
|
|
480
|
+
}
|
|
481
|
+
if (typeof r.hooksSurface !== 'string' || r.hooksSurface.length === 0) {
|
|
482
|
+
errors.push('runtime.hooksSurface must be a non-empty string');
|
|
483
|
+
}
|
|
484
|
+
if (typeof r.sandboxTier !== 'string' || r.sandboxTier.length === 0) {
|
|
485
|
+
errors.push('runtime.sandboxTier must be a non-empty string');
|
|
486
|
+
}
|
|
487
|
+
if (r.supportTier !== 1 && r.supportTier !== 2) {
|
|
488
|
+
errors.push('runtime.supportTier must be 1 or 2 (got: ' + r.supportTier + ')');
|
|
489
|
+
}
|
|
490
|
+
|
|
491
|
+
return errors;
|
|
492
|
+
}
|
|
493
|
+
|
|
494
|
+
function validateStep(step, prefix) {
|
|
495
|
+
const errors = [];
|
|
496
|
+
|
|
497
|
+
if (!VALID_LOOP_POINTS.has(step.point)) {
|
|
498
|
+
errors.push(prefix + '.point "' + step.point + '" is not a valid loop point');
|
|
499
|
+
}
|
|
500
|
+
|
|
501
|
+
if (typeof step.ref !== 'object' || step.ref === null) {
|
|
502
|
+
errors.push(prefix + '.ref must be an object with skill or agent key');
|
|
503
|
+
} else {
|
|
504
|
+
const hasSkill = Object.prototype.hasOwnProperty.call(step.ref, 'skill');
|
|
505
|
+
const hasAgent = Object.prototype.hasOwnProperty.call(step.ref, 'agent');
|
|
506
|
+
if (!hasSkill && !hasAgent) {
|
|
507
|
+
errors.push(prefix + '.ref must have a "skill" or "agent" key');
|
|
508
|
+
} else if (hasSkill && hasAgent) {
|
|
509
|
+
// Fix #4: ref must be exclusive {skill} XOR {agent}
|
|
510
|
+
errors.push(prefix + '.ref must have exactly one of "skill" or "agent", not both');
|
|
511
|
+
}
|
|
512
|
+
if (hasSkill && typeof step.ref.skill !== 'string') {
|
|
513
|
+
errors.push(prefix + '.ref.skill must be a string');
|
|
514
|
+
}
|
|
515
|
+
if (hasAgent && typeof step.ref.agent !== 'string') {
|
|
516
|
+
errors.push(prefix + '.ref.agent must be a string');
|
|
517
|
+
}
|
|
518
|
+
}
|
|
519
|
+
|
|
520
|
+
if (!Array.isArray(step.produces)) {
|
|
521
|
+
errors.push(prefix + '.produces must be an array');
|
|
522
|
+
} else {
|
|
523
|
+
for (const p of step.produces) {
|
|
524
|
+
if (typeof p !== 'string') errors.push(prefix + '.produces entries must be strings');
|
|
525
|
+
}
|
|
526
|
+
}
|
|
527
|
+
|
|
528
|
+
if (!Array.isArray(step.consumes)) {
|
|
529
|
+
errors.push(prefix + '.consumes must be an array');
|
|
530
|
+
} else {
|
|
531
|
+
for (const c of step.consumes) {
|
|
532
|
+
if (typeof c !== 'string') errors.push(prefix + '.consumes entries must be strings');
|
|
533
|
+
}
|
|
534
|
+
}
|
|
535
|
+
|
|
536
|
+
if (step.when !== undefined && typeof step.when !== 'string') {
|
|
537
|
+
errors.push(prefix + '.when must be a string if present');
|
|
538
|
+
}
|
|
539
|
+
|
|
540
|
+
if (!VALID_ON_ERROR.has(step.onError)) {
|
|
541
|
+
errors.push(prefix + '.onError must be "skip" or "halt" (got: ' + step.onError + ')');
|
|
542
|
+
}
|
|
543
|
+
|
|
544
|
+
return errors;
|
|
545
|
+
}
|
|
546
|
+
|
|
547
|
+
function validateContribution(contrib, prefix) {
|
|
548
|
+
const errors = [];
|
|
549
|
+
|
|
550
|
+
if (!VALID_LOOP_POINTS.has(contrib.point)) {
|
|
551
|
+
errors.push(prefix + '.point "' + contrib.point + '" is not a valid loop point');
|
|
552
|
+
}
|
|
553
|
+
|
|
554
|
+
if (typeof contrib.into !== 'string') {
|
|
555
|
+
errors.push(prefix + '.into must be a string (agent role name)');
|
|
556
|
+
}
|
|
557
|
+
|
|
558
|
+
if (typeof contrib.fragment !== 'object' || contrib.fragment === null) {
|
|
559
|
+
errors.push(prefix + '.fragment must be an object with path or inline key');
|
|
560
|
+
} else {
|
|
561
|
+
const hasPath = Object.prototype.hasOwnProperty.call(contrib.fragment, 'path');
|
|
562
|
+
const hasInline = Object.prototype.hasOwnProperty.call(contrib.fragment, 'inline');
|
|
563
|
+
if (!hasPath && !hasInline) {
|
|
564
|
+
errors.push(prefix + '.fragment must have a "path" or "inline" key');
|
|
565
|
+
}
|
|
566
|
+
// S1: fragment.path traversal guard — must be a relative path with no ".." segments
|
|
567
|
+
if (hasPath) {
|
|
568
|
+
const p = contrib.fragment.path;
|
|
569
|
+
if (typeof p !== 'string' || p === '' || path.isAbsolute(p) || p.split(/[\\/]/).includes('..')) {
|
|
570
|
+
errors.push(prefix + '.fragment.path must be a relative path with no ".." segments');
|
|
571
|
+
}
|
|
572
|
+
}
|
|
573
|
+
}
|
|
574
|
+
|
|
575
|
+
if (contrib.when !== undefined && typeof contrib.when !== 'string') {
|
|
576
|
+
errors.push(prefix + '.when must be a string if present');
|
|
577
|
+
}
|
|
578
|
+
|
|
579
|
+
if (contrib.onError !== undefined && !VALID_ON_ERROR.has(contrib.onError)) {
|
|
580
|
+
errors.push(prefix + '.onError must be "skip" or "halt" if present');
|
|
581
|
+
}
|
|
582
|
+
|
|
583
|
+
return errors;
|
|
584
|
+
}
|
|
585
|
+
|
|
586
|
+
function validateGate(gate, prefix) {
|
|
587
|
+
const errors = [];
|
|
588
|
+
|
|
589
|
+
if (!VALID_LOOP_POINTS.has(gate.point)) {
|
|
590
|
+
errors.push(prefix + '.point "' + gate.point + '" is not a valid loop point');
|
|
591
|
+
}
|
|
592
|
+
|
|
593
|
+
if (typeof gate.check !== 'object' || gate.check === null) {
|
|
594
|
+
errors.push(prefix + '.check must be an object');
|
|
595
|
+
} else {
|
|
596
|
+
const hasQuery = Object.prototype.hasOwnProperty.call(gate.check, 'query');
|
|
597
|
+
const hasPredicate = Object.prototype.hasOwnProperty.call(gate.check, 'predicate');
|
|
598
|
+
const hasAgentVerdict = Object.prototype.hasOwnProperty.call(gate.check, 'agentVerdict');
|
|
599
|
+
const count = [hasQuery, hasPredicate, hasAgentVerdict].filter(Boolean).length;
|
|
600
|
+
if (count !== 1) {
|
|
601
|
+
errors.push(prefix + '.check must have exactly one of: query, predicate, agentVerdict');
|
|
602
|
+
}
|
|
603
|
+
// agentVerdict forces blocking: false (advisory only)
|
|
604
|
+
if (hasAgentVerdict && gate.blocking === true) {
|
|
605
|
+
errors.push(
|
|
606
|
+
prefix + '.check.agentVerdict forces blocking: false (non-deterministic checks may not halt the loop)',
|
|
607
|
+
);
|
|
608
|
+
}
|
|
609
|
+
}
|
|
610
|
+
|
|
611
|
+
if (gate.when !== undefined && typeof gate.when !== 'string') {
|
|
612
|
+
errors.push(prefix + '.when must be a string if present');
|
|
613
|
+
}
|
|
614
|
+
|
|
615
|
+
if (typeof gate.blocking !== 'boolean') {
|
|
616
|
+
errors.push(prefix + '.blocking must be a boolean');
|
|
617
|
+
}
|
|
618
|
+
|
|
619
|
+
if (!VALID_ON_ERROR.has(gate.onError)) {
|
|
620
|
+
errors.push(prefix + '.onError must be "skip" or "halt" (got: ' + gate.onError + ')');
|
|
621
|
+
}
|
|
622
|
+
|
|
623
|
+
return errors;
|
|
624
|
+
}
|
|
625
|
+
|
|
626
|
+
// ─── Contract validation ──────────────────────────────────────────────────────
|
|
627
|
+
|
|
628
|
+
/**
|
|
629
|
+
* Validate per-capability contract constraints against the Loop Host Contract.
|
|
630
|
+
* This covers:
|
|
631
|
+
* - contribution.into ∈ step's agentRoles
|
|
632
|
+
* - when references a config key in cap.config
|
|
633
|
+
*
|
|
634
|
+
* NOTE: step.consumes satisfiability is NOT checked here — it requires the full
|
|
635
|
+
* set of validated capabilities (cross-capability produces). It runs in
|
|
636
|
+
* validateConsumesGlobal() after loadAndValidate builds capMap.
|
|
637
|
+
*
|
|
638
|
+
* @param {object} cap Validated capability object
|
|
639
|
+
* @param {string} capId Capability id (for error messages)
|
|
640
|
+
*/
|
|
641
|
+
function validateAgainstContract(cap, capId) {
|
|
642
|
+
if (cap.role !== 'feature') return [];
|
|
643
|
+
const errors = [];
|
|
644
|
+
const prefix = 'capability "' + capId + '"';
|
|
645
|
+
|
|
646
|
+
// contribution.into must be in the step's agentRoles
|
|
647
|
+
for (const contrib of cap.contributions) {
|
|
648
|
+
if (!VALID_LOOP_POINTS.has(contrib.point)) continue; // already reported
|
|
649
|
+
const contract = POINT_TO_CONTRACT.get(contrib.point);
|
|
650
|
+
if (contract && !contract.agentRoles.includes(contrib.into)) {
|
|
651
|
+
errors.push(
|
|
652
|
+
prefix + ' contribution.into "' + contrib.into + '" at point "' + contrib.point +
|
|
653
|
+
'" is not in the step\'s agentRoles [' + contract.agentRoles.join(', ') + ']',
|
|
654
|
+
);
|
|
655
|
+
}
|
|
656
|
+
}
|
|
657
|
+
|
|
658
|
+
// when references a plausibly-valid config key (string — we require it's in cap.config)
|
|
659
|
+
for (const step of cap.steps) {
|
|
660
|
+
if (step.when !== undefined) {
|
|
661
|
+
if (typeof step.when !== 'string') continue; // already reported above
|
|
662
|
+
if (
|
|
663
|
+
typeof cap.config === 'object' &&
|
|
664
|
+
cap.config !== null &&
|
|
665
|
+
!Object.prototype.hasOwnProperty.call(cap.config, step.when)
|
|
666
|
+
) {
|
|
667
|
+
errors.push(
|
|
668
|
+
prefix + ' step.when "' + step.when + '" is not defined in capability config keys',
|
|
669
|
+
);
|
|
670
|
+
}
|
|
671
|
+
}
|
|
672
|
+
}
|
|
673
|
+
|
|
674
|
+
for (const contrib of cap.contributions) {
|
|
675
|
+
if (contrib.when !== undefined) {
|
|
676
|
+
if (typeof contrib.when !== 'string') continue;
|
|
677
|
+
if (
|
|
678
|
+
typeof cap.config === 'object' &&
|
|
679
|
+
cap.config !== null &&
|
|
680
|
+
!Object.prototype.hasOwnProperty.call(cap.config, contrib.when)
|
|
681
|
+
) {
|
|
682
|
+
errors.push(
|
|
683
|
+
prefix + ' contribution.when "' + contrib.when + '" is not defined in capability config keys',
|
|
684
|
+
);
|
|
685
|
+
}
|
|
686
|
+
}
|
|
687
|
+
}
|
|
688
|
+
|
|
689
|
+
for (const gate of cap.gates) {
|
|
690
|
+
if (gate.when !== undefined) {
|
|
691
|
+
if (typeof gate.when !== 'string') continue;
|
|
692
|
+
if (
|
|
693
|
+
typeof cap.config === 'object' &&
|
|
694
|
+
cap.config !== null &&
|
|
695
|
+
!Object.prototype.hasOwnProperty.call(cap.config, gate.when)
|
|
696
|
+
) {
|
|
697
|
+
errors.push(
|
|
698
|
+
prefix + ' gate.when "' + gate.when + '" is not defined in capability config keys',
|
|
699
|
+
);
|
|
700
|
+
}
|
|
701
|
+
}
|
|
702
|
+
}
|
|
703
|
+
|
|
704
|
+
return errors;
|
|
705
|
+
}
|
|
706
|
+
|
|
707
|
+
/**
|
|
708
|
+
* C1+C2: Global consumes-satisfiability validation.
|
|
709
|
+
*
|
|
710
|
+
* A hook at point P consuming artifact A is satisfiable iff:
|
|
711
|
+
* - A is a host-produced artifact available from its step's :post point (C1), and
|
|
712
|
+
* that :post point's POINT_ORDER index ≤ P's index; OR
|
|
713
|
+
* - A is produced by any capability hook step at a point whose POINT_ORDER index ≤ P's index
|
|
714
|
+
* (same-point is OK — topoSortSteps enforces intra-point order); OR
|
|
715
|
+
* - A is never produced anywhere → rejected.
|
|
716
|
+
*
|
|
717
|
+
* Runs after capMap is fully built so cross-capability produces are visible.
|
|
718
|
+
*
|
|
719
|
+
* @param {Map<string, object>} capMap Fully-validated capability map.
|
|
720
|
+
* @returns {string[]} Array of error strings.
|
|
721
|
+
*/
|
|
722
|
+
function validateConsumesGlobal(capMap) {
|
|
723
|
+
const errors = [];
|
|
724
|
+
|
|
725
|
+
// Build producedAtPoint: artifact → earliest POINT_ORDER index at which it is produced.
|
|
726
|
+
// Seed with host artifacts (C1: available from their step's :post point).
|
|
727
|
+
// Host-artifact entries are tagged {pointIdx, isHost:true} so they are never excluded by
|
|
728
|
+
// the self-consume check.
|
|
729
|
+
const producedAtPoint = Object.create(null);
|
|
730
|
+
for (const [artifact, postIdx] of Object.entries(HOST_ARTIFACT_EARLIEST_POINT_IDX)) {
|
|
731
|
+
if (artifact === '__proto__' || artifact === 'constructor' || artifact === 'prototype') continue;
|
|
732
|
+
producedAtPoint[artifact] = postIdx;
|
|
733
|
+
}
|
|
734
|
+
|
|
735
|
+
// Build a richer per-artifact producer list for the self-consume check.
|
|
736
|
+
// Each entry: { pointIdx, capId, stepIdx } — identifies which cap+step produced the artifact.
|
|
737
|
+
// Host artifacts are seeded separately (no capId) and always satisfy the consume check.
|
|
738
|
+
// capHookProducers[artifact] = [{pointIdx, capId, stepIdx}, ...]
|
|
739
|
+
const capHookProducers = Object.create(null);
|
|
740
|
+
|
|
741
|
+
// Add hook-produced artifacts from all capabilities.
|
|
742
|
+
for (const [capId, cap] of capMap) {
|
|
743
|
+
if (cap.role !== 'feature') continue;
|
|
744
|
+
for (let si = 0; si < (cap.steps || []).length; si++) {
|
|
745
|
+
const step = cap.steps[si];
|
|
746
|
+
if (!VALID_LOOP_POINTS.has(step.point)) continue;
|
|
747
|
+
const pointIdx = POINT_ORDER.indexOf(step.point);
|
|
748
|
+
for (const artifact of (step.produces || [])) {
|
|
749
|
+
if (typeof artifact !== 'string') continue;
|
|
750
|
+
if (artifact === '__proto__' || artifact === 'constructor' || artifact === 'prototype') continue;
|
|
751
|
+
if (producedAtPoint[artifact] === undefined || pointIdx < producedAtPoint[artifact]) {
|
|
752
|
+
producedAtPoint[artifact] = pointIdx;
|
|
753
|
+
}
|
|
754
|
+
if (!capHookProducers[artifact]) capHookProducers[artifact] = [];
|
|
755
|
+
capHookProducers[artifact].push({ pointIdx, capId, stepIdx: si });
|
|
756
|
+
}
|
|
757
|
+
}
|
|
758
|
+
}
|
|
759
|
+
|
|
760
|
+
// TODO: duplicate-producer invariant — if two capability steps produce the same artifact
|
|
761
|
+
// at the same point, that's ambiguous. Detect and reject as a follow-up.
|
|
762
|
+
|
|
763
|
+
// Now check every hook step's consumes.
|
|
764
|
+
// Self-consume rule: a step H cannot satisfy its own consumes[A] from its own produces[A].
|
|
765
|
+
// A is satisfiable for H iff:
|
|
766
|
+
// (a) A is a host artifact with pointIdx <= stepPointIdx, OR
|
|
767
|
+
// (b) A is produced by a DIFFERENT cap/step at pointIdx <= stepPointIdx.
|
|
768
|
+
// "Different" means capId != H.capId OR stepIdx != H.stepIdx.
|
|
769
|
+
for (const [capId, cap] of capMap) {
|
|
770
|
+
if (cap.role !== 'feature') continue;
|
|
771
|
+
const prefix = 'capability "' + capId + '"';
|
|
772
|
+
for (let si = 0; si < (cap.steps || []).length; si++) {
|
|
773
|
+
const step = cap.steps[si];
|
|
774
|
+
if (!VALID_LOOP_POINTS.has(step.point)) continue;
|
|
775
|
+
const stepPointIdx = POINT_ORDER.indexOf(step.point);
|
|
776
|
+
for (const artifact of (step.consumes || [])) {
|
|
777
|
+
if (typeof artifact !== 'string') continue;
|
|
778
|
+
|
|
779
|
+
// Check host-artifact satisfaction first (never excluded by self-consume).
|
|
780
|
+
const hostIdx = HOST_ARTIFACT_EARLIEST_POINT_IDX[artifact];
|
|
781
|
+
const hostSatisfied = hostIdx !== undefined && hostIdx <= stepPointIdx;
|
|
782
|
+
if (hostSatisfied) continue; // fast-path: host artifact is available
|
|
783
|
+
|
|
784
|
+
// Check cap-hook producers, excluding this step itself.
|
|
785
|
+
const producers = capHookProducers[artifact];
|
|
786
|
+
if (!producers || producers.length === 0) {
|
|
787
|
+
// Not a host artifact and never produced by any hook.
|
|
788
|
+
errors.push(
|
|
789
|
+
prefix + ' step at point "' + step.point + '" consumes "' + artifact +
|
|
790
|
+
'" which is never produced by any host artifact or capability hook',
|
|
791
|
+
);
|
|
792
|
+
continue;
|
|
793
|
+
}
|
|
794
|
+
|
|
795
|
+
// Find any non-self producer at pointIdx <= stepPointIdx.
|
|
796
|
+
const otherEarliestIdx = producers.reduce((best, p) => {
|
|
797
|
+
const isSelf = p.capId === capId && p.stepIdx === si;
|
|
798
|
+
if (isSelf) return best;
|
|
799
|
+
return (best === undefined || p.pointIdx < best) ? p.pointIdx : best;
|
|
800
|
+
}, undefined);
|
|
801
|
+
|
|
802
|
+
if (otherEarliestIdx === undefined) {
|
|
803
|
+
// Only producer is this step itself — self-consume violation.
|
|
804
|
+
errors.push(
|
|
805
|
+
prefix + ' step at point "' + step.point + '" consumes "' + artifact +
|
|
806
|
+
'" which is only produced by this step itself (a step cannot consume its own output)',
|
|
807
|
+
);
|
|
808
|
+
} else if (otherEarliestIdx > stepPointIdx) {
|
|
809
|
+
errors.push(
|
|
810
|
+
prefix + ' step at point "' + step.point + '" consumes "' + artifact +
|
|
811
|
+
'" which is only produced after this point (earliest available at POINT_ORDER index ' +
|
|
812
|
+
otherEarliestIdx + ' = "' + POINT_ORDER[otherEarliestIdx] + '")',
|
|
813
|
+
);
|
|
814
|
+
}
|
|
815
|
+
// else: satisfied by another cap/step at an earlier-or-same point — OK.
|
|
816
|
+
}
|
|
817
|
+
}
|
|
818
|
+
}
|
|
819
|
+
|
|
820
|
+
return errors;
|
|
821
|
+
}
|
|
822
|
+
|
|
823
|
+
// ─── Cross-capability invariants ──────────────────────────────────────────────
|
|
824
|
+
|
|
825
|
+
const TIER_RANK = { core: 0, standard: 1, full: 2 };
|
|
826
|
+
|
|
827
|
+
/**
|
|
828
|
+
* Enforce cross-capability invariants.
|
|
829
|
+
*
|
|
830
|
+
* @param {Map<string, object>} capMap id → validated capability object
|
|
831
|
+
* @param {Set<string>} centralKeys Set of keys in the central config-schema
|
|
832
|
+
* @returns {string[]} Array of error strings; empty = all pass.
|
|
833
|
+
*/
|
|
834
|
+
function validateCrossCapability(capMap, centralKeys) {
|
|
835
|
+
const errors = [];
|
|
836
|
+
|
|
837
|
+
// Ownership: one owner per skill stem + agent name
|
|
838
|
+
const skillOwner = new Map(); // skill → capId
|
|
839
|
+
const agentOwner = new Map(); // agent → capId
|
|
840
|
+
const familyOwner = new Map(); // command family → capId (ADR-959)
|
|
841
|
+
for (const [capId, cap] of capMap) {
|
|
842
|
+
if (cap.role !== 'feature') continue;
|
|
843
|
+
for (const skill of cap.skills) {
|
|
844
|
+
if (skillOwner.has(skill)) {
|
|
845
|
+
errors.push(
|
|
846
|
+
'skill "' + skill + '" is owned by both "' + skillOwner.get(skill) + '" and "' + capId + '"',
|
|
847
|
+
);
|
|
848
|
+
} else {
|
|
849
|
+
skillOwner.set(skill, capId);
|
|
850
|
+
}
|
|
851
|
+
}
|
|
852
|
+
for (const agent of cap.agents) {
|
|
853
|
+
if (agentOwner.has(agent)) {
|
|
854
|
+
errors.push(
|
|
855
|
+
'agent "' + agent + '" is owned by both "' + agentOwner.get(agent) + '" and "' + capId + '"',
|
|
856
|
+
);
|
|
857
|
+
} else {
|
|
858
|
+
agentOwner.set(agent, capId);
|
|
859
|
+
}
|
|
860
|
+
}
|
|
861
|
+
// ADR-959: single family ownership across the whole registry
|
|
862
|
+
if (Array.isArray(cap.commands)) {
|
|
863
|
+
for (const cmd of cap.commands) {
|
|
864
|
+
if (typeof cmd.family !== 'string' || cmd.family.length === 0) continue; // already reported
|
|
865
|
+
if (cmd.family === '__proto__' || cmd.family === 'constructor' || cmd.family === 'prototype') continue;
|
|
866
|
+
if (familyOwner.has(cmd.family)) {
|
|
867
|
+
errors.push(
|
|
868
|
+
'command family "' + cmd.family + '" is owned by both "' + familyOwner.get(cmd.family) + '" and "' + capId + '"',
|
|
869
|
+
);
|
|
870
|
+
} else {
|
|
871
|
+
familyOwner.set(cmd.family, capId);
|
|
872
|
+
}
|
|
873
|
+
}
|
|
874
|
+
}
|
|
875
|
+
}
|
|
876
|
+
|
|
877
|
+
// Config key ownership: exclusive AND absent from central schema
|
|
878
|
+
const configKeyOwner = new Map(); // key → capId
|
|
879
|
+
for (const [capId, cap] of capMap) {
|
|
880
|
+
if (cap.role !== 'feature' || typeof cap.config !== 'object' || cap.config === null) continue;
|
|
881
|
+
for (const key of Object.keys(cap.config)) {
|
|
882
|
+
if (configKeyOwner.has(key)) {
|
|
883
|
+
errors.push(
|
|
884
|
+
'config key "' + key + '" is owned by both "' + configKeyOwner.get(key) + '" and "' + capId + '"',
|
|
885
|
+
);
|
|
886
|
+
} else {
|
|
887
|
+
configKeyOwner.set(key, capId);
|
|
888
|
+
}
|
|
889
|
+
if (centralKeys.has(key)) {
|
|
890
|
+
errors.push(
|
|
891
|
+
'config key "' + key + '" is declared in capability "' + capId +
|
|
892
|
+
'" AND exists in the central config-schema — migration mid-flight: ' +
|
|
893
|
+
'remove from central config-schema before adding to the capability',
|
|
894
|
+
);
|
|
895
|
+
}
|
|
896
|
+
}
|
|
897
|
+
}
|
|
898
|
+
|
|
899
|
+
// requires: all ids exist
|
|
900
|
+
for (const [capId, cap] of capMap) {
|
|
901
|
+
if (!Array.isArray(cap.requires)) continue;
|
|
902
|
+
for (const req of cap.requires) {
|
|
903
|
+
if (!capMap.has(req)) {
|
|
904
|
+
errors.push(
|
|
905
|
+
'capability "' + capId + '" requires "' + req + '" which does not exist',
|
|
906
|
+
);
|
|
907
|
+
}
|
|
908
|
+
}
|
|
909
|
+
}
|
|
910
|
+
|
|
911
|
+
// requires: acyclic
|
|
912
|
+
const cycleErrors = detectRequiresCycles(capMap);
|
|
913
|
+
errors.push(...cycleErrors);
|
|
914
|
+
|
|
915
|
+
// requires: tier-monotone (core may not require standard/full; standard may not require full)
|
|
916
|
+
for (const [capId, cap] of capMap) {
|
|
917
|
+
if (!Array.isArray(cap.requires) || !VALID_TIERS.has(cap.tier)) continue;
|
|
918
|
+
const myRank = TIER_RANK[cap.tier];
|
|
919
|
+
for (const req of cap.requires) {
|
|
920
|
+
const reqCap = capMap.get(req);
|
|
921
|
+
if (!reqCap || !VALID_TIERS.has(reqCap.tier)) continue;
|
|
922
|
+
const reqRank = TIER_RANK[reqCap.tier];
|
|
923
|
+
if (reqRank > myRank) {
|
|
924
|
+
errors.push(
|
|
925
|
+
'tier-monotone violation: capability "' + capId + '" (tier: ' + cap.tier +
|
|
926
|
+
') requires "' + req + '" (tier: ' + reqCap.tier +
|
|
927
|
+
') — a capability may not require a higher-tier capability',
|
|
928
|
+
);
|
|
929
|
+
}
|
|
930
|
+
}
|
|
931
|
+
}
|
|
932
|
+
|
|
933
|
+
return errors;
|
|
934
|
+
}
|
|
935
|
+
|
|
936
|
+
/**
|
|
937
|
+
* Detect cycles in the requires graph using DFS.
|
|
938
|
+
*/
|
|
939
|
+
function detectRequiresCycles(capMap) {
|
|
940
|
+
const errors = [];
|
|
941
|
+
const WHITE = 0, GRAY = 1, BLACK = 2;
|
|
942
|
+
const color = new Map([...capMap.keys()].map((k) => [k, WHITE]));
|
|
943
|
+
|
|
944
|
+
function dfs(id, stack) {
|
|
945
|
+
if (color.get(id) === GRAY) {
|
|
946
|
+
const cycleStr = [...stack, id].join(' → ');
|
|
947
|
+
errors.push('requires cycle detected: ' + cycleStr);
|
|
948
|
+
return;
|
|
949
|
+
}
|
|
950
|
+
if (color.get(id) === BLACK) return;
|
|
951
|
+
color.set(id, GRAY);
|
|
952
|
+
stack.push(id);
|
|
953
|
+
const cap = capMap.get(id);
|
|
954
|
+
if (cap && Array.isArray(cap.requires)) {
|
|
955
|
+
for (const req of cap.requires) {
|
|
956
|
+
if (capMap.has(req)) dfs(req, stack);
|
|
957
|
+
}
|
|
958
|
+
}
|
|
959
|
+
stack.pop();
|
|
960
|
+
color.set(id, BLACK);
|
|
961
|
+
}
|
|
962
|
+
|
|
963
|
+
for (const id of capMap.keys()) {
|
|
964
|
+
if (color.get(id) === WHITE) dfs(id, []);
|
|
965
|
+
}
|
|
966
|
+
|
|
967
|
+
return errors;
|
|
968
|
+
}
|
|
969
|
+
|
|
970
|
+
// ─── requiresClosure ─────────────────────────────────────────────────────────
|
|
971
|
+
|
|
972
|
+
/**
|
|
973
|
+
* Compute the transitive requires closure for a capability id.
|
|
974
|
+
* Returns a Set<string> of all transitively required capability ids.
|
|
975
|
+
*
|
|
976
|
+
* @param {string} id
|
|
977
|
+
* @param {Map<string, object>} capMap
|
|
978
|
+
*/
|
|
979
|
+
function computeRequiresClosure(id, capMap) {
|
|
980
|
+
const visited = new Set();
|
|
981
|
+
const queue = [id];
|
|
982
|
+
while (queue.length > 0) {
|
|
983
|
+
const current = queue.shift();
|
|
984
|
+
const cap = capMap.get(current);
|
|
985
|
+
if (!cap || !Array.isArray(cap.requires)) continue;
|
|
986
|
+
for (const req of cap.requires) {
|
|
987
|
+
if (!visited.has(req)) {
|
|
988
|
+
visited.add(req);
|
|
989
|
+
queue.push(req);
|
|
990
|
+
}
|
|
991
|
+
}
|
|
992
|
+
}
|
|
993
|
+
return visited;
|
|
994
|
+
}
|
|
995
|
+
|
|
996
|
+
// ─── Topological ordering ─────────────────────────────────────────────────────
|
|
997
|
+
|
|
998
|
+
/**
|
|
999
|
+
* Topologically sort steps at a given point by produces/consumes.
|
|
1000
|
+
* Capability-id tiebreak for determinism.
|
|
1001
|
+
*
|
|
1002
|
+
* @param {{ capId: string, step: object }[]} entries
|
|
1003
|
+
* @returns {{ capId: string, step: object }[]}
|
|
1004
|
+
*/
|
|
1005
|
+
function topoSortSteps(entries) {
|
|
1006
|
+
if (entries.length <= 1) return entries;
|
|
1007
|
+
|
|
1008
|
+
// Build adjacency: entry A must come before entry B if B consumes something A produces
|
|
1009
|
+
const n = entries.length;
|
|
1010
|
+
const inDegree = new Array(n).fill(0);
|
|
1011
|
+
const adj = Array.from({ length: n }, () => []);
|
|
1012
|
+
|
|
1013
|
+
for (let i = 0; i < n; i++) {
|
|
1014
|
+
const producesI = new Set(entries[i].step.produces || []);
|
|
1015
|
+
for (let j = 0; j < n; j++) {
|
|
1016
|
+
if (i === j) continue;
|
|
1017
|
+
const consumesJ = entries[j].step.consumes || [];
|
|
1018
|
+
for (const artifact of consumesJ) {
|
|
1019
|
+
if (producesI.has(artifact)) {
|
|
1020
|
+
adj[i].push(j);
|
|
1021
|
+
inDegree[j]++;
|
|
1022
|
+
break;
|
|
1023
|
+
}
|
|
1024
|
+
}
|
|
1025
|
+
}
|
|
1026
|
+
}
|
|
1027
|
+
|
|
1028
|
+
// Kahn's algorithm with stable tiebreak on capId
|
|
1029
|
+
const queue = [];
|
|
1030
|
+
for (let i = 0; i < n; i++) {
|
|
1031
|
+
if (inDegree[i] === 0) queue.push(i);
|
|
1032
|
+
}
|
|
1033
|
+
// Sort queue by capId for determinism
|
|
1034
|
+
queue.sort((a, b) => entries[a].capId.localeCompare(entries[b].capId));
|
|
1035
|
+
|
|
1036
|
+
const result = [];
|
|
1037
|
+
while (queue.length > 0) {
|
|
1038
|
+
// Take the first (sorted) ready node
|
|
1039
|
+
const idx = queue.shift();
|
|
1040
|
+
result.push(entries[idx]);
|
|
1041
|
+
const newReady = [];
|
|
1042
|
+
for (const neighbor of adj[idx]) {
|
|
1043
|
+
inDegree[neighbor]--;
|
|
1044
|
+
if (inDegree[neighbor] === 0) newReady.push(neighbor);
|
|
1045
|
+
}
|
|
1046
|
+
newReady.sort((a, b) => entries[a].capId.localeCompare(entries[b].capId));
|
|
1047
|
+
queue.push(...newReady);
|
|
1048
|
+
}
|
|
1049
|
+
|
|
1050
|
+
// Fix #2: if result.length < n, Kahn's could not complete — there is a produces/consumes
|
|
1051
|
+
// cycle. Do NOT silently fall back to declaration order; throw a clear error.
|
|
1052
|
+
if (result.length < n) {
|
|
1053
|
+
const sortedIds = entries.map((e) => e.capId).join(', ');
|
|
1054
|
+
throw new Error(
|
|
1055
|
+
'produces/consumes cycle detected in steps at point "' +
|
|
1056
|
+
(entries[0] && entries[0].step ? entries[0].step.point : '?') +
|
|
1057
|
+
'" among capabilities [' + sortedIds + ']: ' +
|
|
1058
|
+
'a cycle in hook produces/consumes prevents deterministic ordering',
|
|
1059
|
+
);
|
|
1060
|
+
}
|
|
1061
|
+
return result;
|
|
1062
|
+
}
|
|
1063
|
+
|
|
1064
|
+
// ─── ADR-857 Phase 4a: Derived views ─────────────────────────────────────────
|
|
1065
|
+
|
|
1066
|
+
// FIX 5 (lazy requires): paths are declared at top level but the actual require()
|
|
1067
|
+
// calls are deferred into lazy accessor functions so importing this generator for
|
|
1068
|
+
// its other exports does NOT fail at module-load time on a fresh/unbuilt worktree.
|
|
1069
|
+
const INSTALL_PROFILES_PATH = path.join(ROOT, 'gsd-core', 'bin', 'lib', 'install-profiles.cjs');
|
|
1070
|
+
const CLUSTERS_PATH = path.join(ROOT, 'gsd-core', 'bin', 'lib', 'clusters.cjs');
|
|
1071
|
+
|
|
1072
|
+
let _installProfilesMod = null;
|
|
1073
|
+
let _clustersMod = null;
|
|
1074
|
+
|
|
1075
|
+
function getInstallProfiles() {
|
|
1076
|
+
if (!_installProfilesMod) _installProfilesMod = require(INSTALL_PROFILES_PATH);
|
|
1077
|
+
return _installProfilesMod;
|
|
1078
|
+
}
|
|
1079
|
+
|
|
1080
|
+
function getClusters() {
|
|
1081
|
+
if (!_clustersMod) _clustersMod = require(CLUSTERS_PATH);
|
|
1082
|
+
return _clustersMod;
|
|
1083
|
+
}
|
|
1084
|
+
|
|
1085
|
+
/**
|
|
1086
|
+
* Derive capabilityClusters: { <capId>: [<skill stems>] }
|
|
1087
|
+
* Each capability's own skills array, sorted for determinism.
|
|
1088
|
+
*
|
|
1089
|
+
* FIX 3: scope rule = "capabilities that own skills" (non-empty skills array).
|
|
1090
|
+
* Both capabilityClusters and profileMembership use this same predicate so a
|
|
1091
|
+
* future non-feature role carrying skills is treated identically in both, and a
|
|
1092
|
+
* feature cap with no skills appears in neither.
|
|
1093
|
+
*
|
|
1094
|
+
* @param {Map<string, object>} capMap
|
|
1095
|
+
* @returns {object} Object.create(null) — prototype-pollution safe
|
|
1096
|
+
*/
|
|
1097
|
+
function deriveCapabilityClusters(capMap) {
|
|
1098
|
+
const result = Object.create(null);
|
|
1099
|
+
for (const [capId, cap] of capMap) {
|
|
1100
|
+
// S2b: inline literal guard at each write site (CodeQL barrier)
|
|
1101
|
+
if (capId === '__proto__' || capId === 'constructor' || capId === 'prototype') continue;
|
|
1102
|
+
// FIX 3: include any cap that owns skills (non-empty skills array), regardless of role
|
|
1103
|
+
if (!Array.isArray(cap.skills) || cap.skills.length === 0) continue;
|
|
1104
|
+
// Sort for determinism
|
|
1105
|
+
const sorted = [...cap.skills].sort();
|
|
1106
|
+
result[capId] = sorted;
|
|
1107
|
+
}
|
|
1108
|
+
return result;
|
|
1109
|
+
}
|
|
1110
|
+
|
|
1111
|
+
/**
|
|
1112
|
+
* Derive profileMembership: { <capId>: { tier: <t>, profiles: [<names>] } }
|
|
1113
|
+
* profiles = suffix of PROFILE_RANK starting at the capability's tier index.
|
|
1114
|
+
* tier 'core' → ['core', 'standard', 'full']
|
|
1115
|
+
* tier 'standard' → ['standard', 'full']
|
|
1116
|
+
* tier 'full' → ['full']
|
|
1117
|
+
*
|
|
1118
|
+
* FIX 3: scope rule = "capabilities that own skills" (non-empty skills array),
|
|
1119
|
+
* consistent with deriveCapabilityClusters. Both derived views cover the same set.
|
|
1120
|
+
*
|
|
1121
|
+
* FIX 5: tierIdx === -1 means VALID_TIERS and PROFILE_RANK have drifted; throw
|
|
1122
|
+
* loudly instead of silently producing ['full'] for the affected capability.
|
|
1123
|
+
*
|
|
1124
|
+
* @param {Map<string, object>} capMap
|
|
1125
|
+
* @returns {object} Object.create(null) — prototype-pollution safe
|
|
1126
|
+
*/
|
|
1127
|
+
function deriveProfileMembership(capMap) {
|
|
1128
|
+
const { PROFILE_RANK } = getInstallProfiles();
|
|
1129
|
+
const result = Object.create(null);
|
|
1130
|
+
for (const [capId, cap] of capMap) {
|
|
1131
|
+
// S2b: inline literal guard at each write site (CodeQL barrier)
|
|
1132
|
+
if (capId === '__proto__' || capId === 'constructor' || capId === 'prototype') continue;
|
|
1133
|
+
if (!VALID_TIERS.has(cap.tier)) continue;
|
|
1134
|
+
// FIX 3: consistent scope — only capabilities that own skills (non-empty skills array)
|
|
1135
|
+
if (!Array.isArray(cap.skills) || cap.skills.length === 0) continue;
|
|
1136
|
+
const tierIdx = PROFILE_RANK.indexOf(cap.tier);
|
|
1137
|
+
// FIX 5: throw loudly on VALID_TIERS/PROFILE_RANK drift (was silent continue)
|
|
1138
|
+
if (tierIdx === -1) {
|
|
1139
|
+
throw new Error(
|
|
1140
|
+
'deriveProfileMembership: capability "' + capId + '" tier "' + cap.tier +
|
|
1141
|
+
'" is in VALID_TIERS but not in PROFILE_RANK — VALID_TIERS/PROFILE_RANK drift detected',
|
|
1142
|
+
);
|
|
1143
|
+
}
|
|
1144
|
+
const profiles = PROFILE_RANK.slice(tierIdx);
|
|
1145
|
+
result[capId] = { tier: cap.tier, profiles: [...profiles] };
|
|
1146
|
+
}
|
|
1147
|
+
return result;
|
|
1148
|
+
}
|
|
1149
|
+
|
|
1150
|
+
/**
|
|
1151
|
+
* Run consistency gates:
|
|
1152
|
+
* - HARD: for each capId that matches a CLUSTERS key, derived skills must match
|
|
1153
|
+
* the hand-authored CLUSTERS[capId] set (order-insensitive). Throws on mismatch.
|
|
1154
|
+
* - SOFT: for each capability, for each skill not yet in all non-full profiles it
|
|
1155
|
+
* belongs to (closure-resolved), emit ONE pending-reconciliation warning listing
|
|
1156
|
+
* the missing profiles together. Warnings are collected and returned — NOT thrown.
|
|
1157
|
+
*
|
|
1158
|
+
* FIX 1: load the REAL skills manifest (same as bin/install.js) so resolveProfile
|
|
1159
|
+
* expands requires:-closure. Loaded once and reused across all capabilities.
|
|
1160
|
+
*
|
|
1161
|
+
* FIX 3: iterate capabilityClusters (which already covers "capabilities that own
|
|
1162
|
+
* skills") rather than profileMembership, so both derived views share one scope.
|
|
1163
|
+
*
|
|
1164
|
+
* FIX 4: one warning per (capability, skill) gap, listing all missing non-full
|
|
1165
|
+
* profiles together, instead of one warning per (capability, skill, profile).
|
|
1166
|
+
*
|
|
1167
|
+
* @param {object} capabilityClusters From deriveCapabilityClusters()
|
|
1168
|
+
* @param {object} profileMembership From deriveProfileMembership()
|
|
1169
|
+
* @param {Map<string, object>} capMap Original capMap for skill lists
|
|
1170
|
+
* @returns {string[]} Array of pending-reconciliation warning strings
|
|
1171
|
+
*/
|
|
1172
|
+
function runConsistencyGate(capabilityClusters, profileMembership, capMap) {
|
|
1173
|
+
const { CLUSTERS: clustersObj } = getClusters();
|
|
1174
|
+
const { resolveProfile, loadSkillsManifest } = getInstallProfiles();
|
|
1175
|
+
|
|
1176
|
+
// ── HARD gate: cluster set comparison ──────────────────────────────────────
|
|
1177
|
+
for (const capId of Object.keys(capabilityClusters)) {
|
|
1178
|
+
// S2b: inline literal guard (CodeQL barrier)
|
|
1179
|
+
if (capId === '__proto__' || capId === 'constructor' || capId === 'prototype') continue;
|
|
1180
|
+
// Only check if a CLUSTERS entry with the same name exists
|
|
1181
|
+
if (!Object.prototype.hasOwnProperty.call(clustersObj, capId)) continue;
|
|
1182
|
+
const derivedSet = new Set(capabilityClusters[capId]);
|
|
1183
|
+
const handAuthored = clustersObj[capId];
|
|
1184
|
+
const handAuthoredSet = new Set(handAuthored);
|
|
1185
|
+
// Compare sets (order-insensitive)
|
|
1186
|
+
let mismatch = derivedSet.size !== handAuthoredSet.size;
|
|
1187
|
+
if (!mismatch) {
|
|
1188
|
+
for (const s of derivedSet) {
|
|
1189
|
+
if (!handAuthoredSet.has(s)) { mismatch = true; break; }
|
|
1190
|
+
}
|
|
1191
|
+
}
|
|
1192
|
+
if (mismatch) {
|
|
1193
|
+
throw new Error(
|
|
1194
|
+
'capability-cluster consistency gate FAILED for capId "' + capId + '":\n' +
|
|
1195
|
+
' derived set: [' + [...derivedSet].sort().join(', ') + ']\n' +
|
|
1196
|
+
' hand-authored set: [' + [...handAuthoredSet].sort().join(', ') + ']\n' +
|
|
1197
|
+
'The capability\'s skills array must match the hand-authored CLUSTERS["' + capId + '"] at cutover.',
|
|
1198
|
+
);
|
|
1199
|
+
}
|
|
1200
|
+
}
|
|
1201
|
+
|
|
1202
|
+
// ── SOFT gate: profile reconciliation warnings ─────────────────────────────
|
|
1203
|
+
|
|
1204
|
+
// FIX 1: load the REAL skills manifest once (same path as bin/install.js uses),
|
|
1205
|
+
// so resolveProfile expands requires:-closure and the effective set is accurate.
|
|
1206
|
+
const commandsGsdDir = path.join(ROOT, 'commands', 'gsd');
|
|
1207
|
+
const skillsManifest = loadSkillsManifest(commandsGsdDir);
|
|
1208
|
+
|
|
1209
|
+
// FIX 1: resolve each profile's effective set once and cache — don't reload per-capability.
|
|
1210
|
+
const profileEffectiveSetCache = Object.create(null);
|
|
1211
|
+
function getEffectiveSet(profileName) {
|
|
1212
|
+
if (profileName in profileEffectiveSetCache) return profileEffectiveSetCache[profileName];
|
|
1213
|
+
const resolved = resolveProfile({ modes: [profileName], manifest: skillsManifest });
|
|
1214
|
+
const effectiveSet = resolved.skills === '*' ? null : resolved.skills;
|
|
1215
|
+
profileEffectiveSetCache[profileName] = effectiveSet;
|
|
1216
|
+
return effectiveSet;
|
|
1217
|
+
}
|
|
1218
|
+
|
|
1219
|
+
const warnings = [];
|
|
1220
|
+
|
|
1221
|
+
// FIX 3: iterate capabilityClusters (same set as profileMembership after FIX 3 scoping).
|
|
1222
|
+
for (const capId of Object.keys(capabilityClusters)) {
|
|
1223
|
+
// S2b: inline literal guard (CodeQL barrier)
|
|
1224
|
+
if (capId === '__proto__' || capId === 'constructor' || capId === 'prototype') continue;
|
|
1225
|
+
const membership = profileMembership[capId];
|
|
1226
|
+
if (!membership) continue; // no profile membership (e.g. cap has skills but invalid tier)
|
|
1227
|
+
const cap = capMap.get(capId);
|
|
1228
|
+
if (!cap || !Array.isArray(cap.skills)) continue;
|
|
1229
|
+
|
|
1230
|
+
// Collect the non-full profiles for this capability
|
|
1231
|
+
const nonFullProfiles = membership.profiles.filter((p) => p !== 'full');
|
|
1232
|
+
|
|
1233
|
+
// FIX 4: one warning per (capability, skill) gap — list all missing profiles together
|
|
1234
|
+
for (const skill of cap.skills) {
|
|
1235
|
+
// S2b: inline literal guard (CodeQL barrier)
|
|
1236
|
+
if (skill === '__proto__' || skill === 'constructor' || skill === 'prototype') continue;
|
|
1237
|
+
|
|
1238
|
+
const missingProfiles = [];
|
|
1239
|
+
for (const profileName of nonFullProfiles) {
|
|
1240
|
+
const effectiveSet = getEffectiveSet(profileName);
|
|
1241
|
+
if (effectiveSet === null) continue; // profile resolved to full (unexpected but safe)
|
|
1242
|
+
if (!effectiveSet.has(skill)) {
|
|
1243
|
+
missingProfiles.push(profileName);
|
|
1244
|
+
}
|
|
1245
|
+
}
|
|
1246
|
+
|
|
1247
|
+
if (missingProfiles.length > 0) {
|
|
1248
|
+
warnings.push(
|
|
1249
|
+
'⚠ pending-reconciliation: capability \'' + capId + '\' (tier ' + membership.tier + ')' +
|
|
1250
|
+
' skill \'' + skill + '\' not yet in hand-authored profile(s): <' + missingProfiles.join(', ') +
|
|
1251
|
+
'>; add at cutover',
|
|
1252
|
+
);
|
|
1253
|
+
}
|
|
1254
|
+
}
|
|
1255
|
+
}
|
|
1256
|
+
|
|
1257
|
+
return warnings;
|
|
1258
|
+
}
|
|
1259
|
+
|
|
1260
|
+
// ─── Registry builder ─────────────────────────────────────────────────────────
|
|
1261
|
+
|
|
1262
|
+
/**
|
|
1263
|
+
* Read + validate all capabilities/<id>/capability.json files.
|
|
1264
|
+
* Returns { capMap, errors } where capMap is Map<id, cap>.
|
|
1265
|
+
*
|
|
1266
|
+
* @param {Set<string>} [centralKeys] Keys in central config-schema for collision detection.
|
|
1267
|
+
* If omitted, reads from disk. Pass new Set() to skip central-collision checks
|
|
1268
|
+
* (used during 3a-impl while migration is in-progress).
|
|
1269
|
+
* @param {string} [capabilitiesDir] Override capabilities dir (for testing with fixtures).
|
|
1270
|
+
*/
|
|
1271
|
+
function loadAndValidate(centralKeys, capabilitiesDir) {
|
|
1272
|
+
const resolvedCentralKeys = centralKeys !== undefined ? centralKeys : loadCentralConfigKeys();
|
|
1273
|
+
const resolvedCapDir = capabilitiesDir !== undefined ? capabilitiesDir : CAPABILITIES_DIR;
|
|
1274
|
+
const errors = [];
|
|
1275
|
+
const capMap = new Map();
|
|
1276
|
+
|
|
1277
|
+
if (!fs.existsSync(resolvedCapDir)) {
|
|
1278
|
+
return { capMap, errors };
|
|
1279
|
+
}
|
|
1280
|
+
|
|
1281
|
+
const folderEntries = fs.readdirSync(resolvedCapDir, { withFileTypes: true })
|
|
1282
|
+
.filter((e) => e.isDirectory())
|
|
1283
|
+
.map((e) => e.name)
|
|
1284
|
+
.sort();
|
|
1285
|
+
|
|
1286
|
+
for (const folderId of folderEntries) {
|
|
1287
|
+
const capPath = path.join(resolvedCapDir, folderId, 'capability.json');
|
|
1288
|
+
if (!fs.existsSync(capPath)) continue;
|
|
1289
|
+
|
|
1290
|
+
let cap;
|
|
1291
|
+
try {
|
|
1292
|
+
cap = JSON.parse(fs.readFileSync(capPath, 'utf8'));
|
|
1293
|
+
} catch (err) {
|
|
1294
|
+
errors.push(folderId + '/capability.json: JSON parse error: ' + String(err.message));
|
|
1295
|
+
continue;
|
|
1296
|
+
}
|
|
1297
|
+
|
|
1298
|
+
const capErrors = validateCapability(cap, folderId);
|
|
1299
|
+
if (capErrors.length > 0) {
|
|
1300
|
+
for (const e of capErrors) errors.push(folderId + '/capability.json: ' + e);
|
|
1301
|
+
continue; // skip cross-validation if basic schema fails
|
|
1302
|
+
}
|
|
1303
|
+
|
|
1304
|
+
const contractErrors = validateAgainstContract(cap, cap.id);
|
|
1305
|
+
if (contractErrors.length > 0) {
|
|
1306
|
+
for (const e of contractErrors) errors.push(folderId + '/capability.json: ' + e);
|
|
1307
|
+
// Fix #6: do NOT add contract-invalid caps to capMap — validateCrossCapability should
|
|
1308
|
+
// only see fully-valid capabilities so its invariants are meaningful.
|
|
1309
|
+
continue;
|
|
1310
|
+
}
|
|
1311
|
+
|
|
1312
|
+
capMap.set(cap.id, cap);
|
|
1313
|
+
}
|
|
1314
|
+
|
|
1315
|
+
// Cross-capability invariants — capMap contains only fully-valid capabilities at this point.
|
|
1316
|
+
const crossErrors = validateCrossCapability(capMap, resolvedCentralKeys);
|
|
1317
|
+
errors.push(...crossErrors);
|
|
1318
|
+
|
|
1319
|
+
// C2: Global consumes-satisfiability — runs after capMap is fully built so cross-capability
|
|
1320
|
+
// produces are visible. A capability with consumes errors is kept in capMap (it passed per-cap
|
|
1321
|
+
// validation) but the errors are surfaced so the build fails.
|
|
1322
|
+
const consumesErrors = validateConsumesGlobal(capMap);
|
|
1323
|
+
errors.push(...consumesErrors);
|
|
1324
|
+
|
|
1325
|
+
return { capMap, errors };
|
|
1326
|
+
}
|
|
1327
|
+
|
|
1328
|
+
/**
|
|
1329
|
+
* Build the registry object from a validated capMap.
|
|
1330
|
+
*
|
|
1331
|
+
* @param {Map<string, object>} capMap
|
|
1332
|
+
*/
|
|
1333
|
+
function buildRegistry(capMap) {
|
|
1334
|
+
// S2b: Use Object.create(null) for all accumulator maps so prototype-pollution
|
|
1335
|
+
// can't touch Object.prototype even if a reserved name slips through validation.
|
|
1336
|
+
const capabilities = Object.create(null);
|
|
1337
|
+
const bySkill = Object.create(null);
|
|
1338
|
+
const byAgent = Object.create(null);
|
|
1339
|
+
const byLoopPoint = Object.create(null);
|
|
1340
|
+
const configKeys = Object.create(null);
|
|
1341
|
+
const configSchema = Object.create(null);
|
|
1342
|
+
const runtimes = Object.create(null);
|
|
1343
|
+
|
|
1344
|
+
// Initialize byLoopPoint for all valid points
|
|
1345
|
+
for (const point of VALID_LOOP_POINTS) {
|
|
1346
|
+
byLoopPoint[point] = { steps: [], contributions: [], gates: [] };
|
|
1347
|
+
}
|
|
1348
|
+
|
|
1349
|
+
// Phase 1: collect per-point entries grouped by point
|
|
1350
|
+
const pointSteps = new Map(); // point → [{ capId, step }]
|
|
1351
|
+
const pointContribs = new Map(); // point → [{ capId, contrib }]
|
|
1352
|
+
const pointGates = new Map(); // point → [{ capId, gate }]
|
|
1353
|
+
|
|
1354
|
+
for (const point of VALID_LOOP_POINTS) {
|
|
1355
|
+
pointSteps.set(point, []);
|
|
1356
|
+
pointContribs.set(point, []);
|
|
1357
|
+
pointGates.set(point, []);
|
|
1358
|
+
}
|
|
1359
|
+
|
|
1360
|
+
for (const [capId, cap] of capMap) {
|
|
1361
|
+
// S2b: inline literal guard at each write site (CodeQL barrier)
|
|
1362
|
+
if (capId === '__proto__' || capId === 'constructor' || capId === 'prototype') continue;
|
|
1363
|
+
capabilities[capId] = cap;
|
|
1364
|
+
|
|
1365
|
+
if (cap.role === 'feature') {
|
|
1366
|
+
for (const skill of (cap.skills || [])) {
|
|
1367
|
+
// S2b: inline literal guard at each write site (CodeQL barrier)
|
|
1368
|
+
if (skill === '__proto__' || skill === 'constructor' || skill === 'prototype') continue;
|
|
1369
|
+
bySkill[skill] = capId;
|
|
1370
|
+
}
|
|
1371
|
+
for (const agent of (cap.agents || [])) {
|
|
1372
|
+
// S2b: inline literal guard at each write site (CodeQL barrier)
|
|
1373
|
+
if (agent === '__proto__' || agent === 'constructor' || agent === 'prototype') continue;
|
|
1374
|
+
byAgent[agent] = capId;
|
|
1375
|
+
}
|
|
1376
|
+
for (const key of Object.keys(cap.config || {})) {
|
|
1377
|
+
// S2b: inline literal guard at each write site (CodeQL barrier)
|
|
1378
|
+
if (key === '__proto__' || key === 'constructor' || key === 'prototype') continue;
|
|
1379
|
+
configKeys[key] = capId;
|
|
1380
|
+
|
|
1381
|
+
// Build configSchema entry — validate the slice first (throw on violation)
|
|
1382
|
+
const slice = (cap.config || {})[key];
|
|
1383
|
+
const sliceErrors = validateConfigSliceEntry(capId, key, slice);
|
|
1384
|
+
if (sliceErrors.length > 0) {
|
|
1385
|
+
throw new Error(
|
|
1386
|
+
'configSchema validation failed during registry build:\n' +
|
|
1387
|
+
sliceErrors.map((e) => ' ' + e).join('\n'),
|
|
1388
|
+
);
|
|
1389
|
+
}
|
|
1390
|
+
// S2b: inline literal guard for configSchema write site
|
|
1391
|
+
if (key !== '__proto__' && key !== 'constructor' && key !== 'prototype') {
|
|
1392
|
+
configSchema[key] = {
|
|
1393
|
+
owner: capId,
|
|
1394
|
+
type: slice.type,
|
|
1395
|
+
default: slice.default,
|
|
1396
|
+
description: slice.description,
|
|
1397
|
+
};
|
|
1398
|
+
// Preserve values array for enum types if present
|
|
1399
|
+
if (slice.type === 'enum' && Array.isArray(slice.values)) {
|
|
1400
|
+
configSchema[key].values = slice.values;
|
|
1401
|
+
}
|
|
1402
|
+
}
|
|
1403
|
+
}
|
|
1404
|
+
|
|
1405
|
+
for (const step of (cap.steps || [])) {
|
|
1406
|
+
if (VALID_LOOP_POINTS.has(step.point)) {
|
|
1407
|
+
pointSteps.get(step.point).push({ capId, step });
|
|
1408
|
+
}
|
|
1409
|
+
}
|
|
1410
|
+
for (const contrib of (cap.contributions || [])) {
|
|
1411
|
+
if (VALID_LOOP_POINTS.has(contrib.point)) {
|
|
1412
|
+
// Group contributions by into, then cap-id order
|
|
1413
|
+
pointContribs.get(contrib.point).push({ capId, contrib });
|
|
1414
|
+
}
|
|
1415
|
+
}
|
|
1416
|
+
for (const gate of (cap.gates || [])) {
|
|
1417
|
+
if (VALID_LOOP_POINTS.has(gate.point)) {
|
|
1418
|
+
pointGates.get(gate.point).push({ capId, gate });
|
|
1419
|
+
}
|
|
1420
|
+
}
|
|
1421
|
+
} else if (cap.role === 'runtime') {
|
|
1422
|
+
// S2b: inline literal guard at each write site (CodeQL barrier) — capId already guarded above
|
|
1423
|
+
runtimes[capId] = cap;
|
|
1424
|
+
}
|
|
1425
|
+
}
|
|
1426
|
+
|
|
1427
|
+
// Phase 2: materialize ordering
|
|
1428
|
+
for (const point of VALID_LOOP_POINTS) {
|
|
1429
|
+
// Steps: topological sort by produces/consumes, cap-id tiebreak
|
|
1430
|
+
const sortedSteps = topoSortSteps(pointSteps.get(point));
|
|
1431
|
+
byLoopPoint[point].steps = sortedSteps.map((e) => ({
|
|
1432
|
+
capId: e.capId,
|
|
1433
|
+
...e.step,
|
|
1434
|
+
}));
|
|
1435
|
+
|
|
1436
|
+
// Contributions: group by into, then capability-id order within group
|
|
1437
|
+
const contribs = pointContribs.get(point);
|
|
1438
|
+
contribs.sort((a, b) => {
|
|
1439
|
+
const intoCompare = a.contrib.into.localeCompare(b.contrib.into);
|
|
1440
|
+
if (intoCompare !== 0) return intoCompare;
|
|
1441
|
+
return a.capId.localeCompare(b.capId);
|
|
1442
|
+
});
|
|
1443
|
+
byLoopPoint[point].contributions = contribs.map((e) => ({
|
|
1444
|
+
capId: e.capId,
|
|
1445
|
+
...e.contrib,
|
|
1446
|
+
}));
|
|
1447
|
+
|
|
1448
|
+
// Gates: as declared (stable by capId order)
|
|
1449
|
+
const gates = pointGates.get(point);
|
|
1450
|
+
gates.sort((a, b) => a.capId.localeCompare(b.capId));
|
|
1451
|
+
byLoopPoint[point].gates = gates.map((e) => ({
|
|
1452
|
+
capId: e.capId,
|
|
1453
|
+
...e.gate,
|
|
1454
|
+
}));
|
|
1455
|
+
}
|
|
1456
|
+
|
|
1457
|
+
// ── ADR-959: commandFamilies index ─────────────────────────────────────────
|
|
1458
|
+
// family → { capId, module, router }
|
|
1459
|
+
// Built from all feature capabilities' commands arrays.
|
|
1460
|
+
const commandFamilies = Object.create(null);
|
|
1461
|
+
for (const [capId, cap] of capMap) {
|
|
1462
|
+
// S2b: inline literal guard at each write site (CodeQL barrier)
|
|
1463
|
+
if (capId === '__proto__' || capId === 'constructor' || capId === 'prototype') continue;
|
|
1464
|
+
if (cap.role !== 'feature' || !Array.isArray(cap.commands)) continue;
|
|
1465
|
+
for (const cmd of cap.commands) {
|
|
1466
|
+
if (typeof cmd.family !== 'string' || cmd.family.length === 0) continue;
|
|
1467
|
+
// S2b: inline literal guard at family key write site (CodeQL barrier)
|
|
1468
|
+
if (cmd.family === '__proto__' || cmd.family === 'constructor' || cmd.family === 'prototype') continue;
|
|
1469
|
+
if (typeof cmd.module !== 'string' || cmd.module.length === 0) continue;
|
|
1470
|
+
if (typeof cmd.router !== 'string' || cmd.router.length === 0) continue;
|
|
1471
|
+
commandFamilies[cmd.family] = { capId, module: cmd.module, router: cmd.router };
|
|
1472
|
+
}
|
|
1473
|
+
}
|
|
1474
|
+
|
|
1475
|
+
// ── ADR-857 phase 4a: derived views ────────────────────────────────────────
|
|
1476
|
+
const capabilityClusters = deriveCapabilityClusters(capMap);
|
|
1477
|
+
const profileMembership = deriveProfileMembership(capMap);
|
|
1478
|
+
// runConsistencyGate: hard gate throws on mismatch; returns soft warning strings.
|
|
1479
|
+
// Warnings are returned in the registry object so callers can emit them to stderr
|
|
1480
|
+
// without affecting the serialized file content (determinism gate stays clean).
|
|
1481
|
+
const reconciliationWarnings = runConsistencyGate(capabilityClusters, profileMembership, capMap);
|
|
1482
|
+
|
|
1483
|
+
return {
|
|
1484
|
+
version: SCHEMA_VERSION,
|
|
1485
|
+
capabilities,
|
|
1486
|
+
bySkill,
|
|
1487
|
+
byAgent,
|
|
1488
|
+
byLoopPoint,
|
|
1489
|
+
configKeys,
|
|
1490
|
+
configSchema,
|
|
1491
|
+
runtimes,
|
|
1492
|
+
commandFamilies,
|
|
1493
|
+
capabilityClusters,
|
|
1494
|
+
profileMembership,
|
|
1495
|
+
// warnings are NOT serialized — returned only for caller consumption via stderr
|
|
1496
|
+
_reconciliationWarnings: reconciliationWarnings,
|
|
1497
|
+
};
|
|
1498
|
+
}
|
|
1499
|
+
|
|
1500
|
+
// ─── Registry serialization ───────────────────────────────────────────────────
|
|
1501
|
+
|
|
1502
|
+
/**
|
|
1503
|
+
* Serialize the registry to a CommonJS module string.
|
|
1504
|
+
*
|
|
1505
|
+
* @param {object} registry The registry object from buildRegistry()
|
|
1506
|
+
* @param {Map<string, object>} capMap Used for requiresClosure()
|
|
1507
|
+
*/
|
|
1508
|
+
function serializeRegistry(registry, capMap) {
|
|
1509
|
+
const lines = [];
|
|
1510
|
+
|
|
1511
|
+
lines.push("'use strict';");
|
|
1512
|
+
lines.push('');
|
|
1513
|
+
lines.push('/**');
|
|
1514
|
+
lines.push(' * capability-registry.cjs — generated by scripts/gen-capability-registry.cjs');
|
|
1515
|
+
lines.push(' * DO NOT EDIT BY HAND. Run: node scripts/gen-capability-registry.cjs --write');
|
|
1516
|
+
lines.push(' * ADR-894 §5 — role-partitioned Capability Registry.');
|
|
1517
|
+
lines.push(' */');
|
|
1518
|
+
lines.push('');
|
|
1519
|
+
|
|
1520
|
+
// Serialize each section as a variable to keep the file readable
|
|
1521
|
+
lines.push('const capabilities = ' + JSON.stringify(registry.capabilities, null, 2) + ';');
|
|
1522
|
+
lines.push('');
|
|
1523
|
+
lines.push('const bySkill = ' + JSON.stringify(registry.bySkill, null, 2) + ';');
|
|
1524
|
+
lines.push('');
|
|
1525
|
+
lines.push('const byAgent = ' + JSON.stringify(registry.byAgent, null, 2) + ';');
|
|
1526
|
+
lines.push('');
|
|
1527
|
+
lines.push('const byLoopPoint = ' + JSON.stringify(registry.byLoopPoint, null, 2) + ';');
|
|
1528
|
+
lines.push('');
|
|
1529
|
+
lines.push('const configKeys = ' + JSON.stringify(registry.configKeys, null, 2) + ';');
|
|
1530
|
+
lines.push('');
|
|
1531
|
+
lines.push('const configSchema = ' + JSON.stringify(registry.configSchema, null, 2) + ';');
|
|
1532
|
+
lines.push('');
|
|
1533
|
+
lines.push('const runtimes = ' + JSON.stringify(registry.runtimes, null, 2) + ';');
|
|
1534
|
+
lines.push('');
|
|
1535
|
+
|
|
1536
|
+
// ADR-959: commandFamilies index — sort family keys for determinism.
|
|
1537
|
+
const sortedCommandFamilies = Object.create(null);
|
|
1538
|
+
const commandFamilyKeys = Object.keys(registry.commandFamilies || {}).sort();
|
|
1539
|
+
for (const family of commandFamilyKeys) {
|
|
1540
|
+
// S2b: inline literal guard at write site (CodeQL barrier)
|
|
1541
|
+
if (family === '__proto__' || family === 'constructor' || family === 'prototype') continue;
|
|
1542
|
+
sortedCommandFamilies[family] = registry.commandFamilies[family];
|
|
1543
|
+
}
|
|
1544
|
+
lines.push('const commandFamilies = ' + JSON.stringify(sortedCommandFamilies, null, 2) + ';');
|
|
1545
|
+
lines.push('');
|
|
1546
|
+
|
|
1547
|
+
// ADR-857 phase 4a: derived views — globally sorted capIds for determinism.
|
|
1548
|
+
// FIX 2: collect ALL capIds across both views and sort globally so feature + runtime
|
|
1549
|
+
// capIds interleave correctly when both are present (phase 5 readiness).
|
|
1550
|
+
const allClusterCapIds = new Set(Object.keys(registry.capabilityClusters));
|
|
1551
|
+
const allProfileCapIds = new Set(Object.keys(registry.profileMembership));
|
|
1552
|
+
const allCapIds = new Set([...allClusterCapIds, ...allProfileCapIds]);
|
|
1553
|
+
// FIX 5: inline literal guard at write sites (CodeQL barrier)
|
|
1554
|
+
allCapIds.delete('__proto__');
|
|
1555
|
+
allCapIds.delete('constructor');
|
|
1556
|
+
allCapIds.delete('prototype');
|
|
1557
|
+
const globalSortedCapIds = [...allCapIds].sort();
|
|
1558
|
+
|
|
1559
|
+
const sortedCapabilityClusters = Object.create(null);
|
|
1560
|
+
for (const capId of globalSortedCapIds) {
|
|
1561
|
+
// S2b: inline literal guard at each write site (CodeQL barrier)
|
|
1562
|
+
if (capId === '__proto__' || capId === 'constructor' || capId === 'prototype') continue;
|
|
1563
|
+
if (registry.capabilityClusters[capId] !== undefined) {
|
|
1564
|
+
sortedCapabilityClusters[capId] = registry.capabilityClusters[capId];
|
|
1565
|
+
}
|
|
1566
|
+
}
|
|
1567
|
+
lines.push('const capabilityClusters = ' + JSON.stringify(sortedCapabilityClusters, null, 2) + ';');
|
|
1568
|
+
lines.push('');
|
|
1569
|
+
|
|
1570
|
+
const sortedProfileMembership = Object.create(null);
|
|
1571
|
+
for (const capId of globalSortedCapIds) {
|
|
1572
|
+
// S2b: inline literal guard at each write site (CodeQL barrier)
|
|
1573
|
+
if (capId === '__proto__' || capId === 'constructor' || capId === 'prototype') continue;
|
|
1574
|
+
if (registry.profileMembership[capId] !== undefined) {
|
|
1575
|
+
sortedProfileMembership[capId] = registry.profileMembership[capId];
|
|
1576
|
+
}
|
|
1577
|
+
}
|
|
1578
|
+
lines.push('const profileMembership = ' + JSON.stringify(sortedProfileMembership, null, 2) + ';');
|
|
1579
|
+
lines.push('');
|
|
1580
|
+
|
|
1581
|
+
// Inline the requires graph so requiresClosure() works without re-reading files
|
|
1582
|
+
const requiresGraph = {};
|
|
1583
|
+
for (const [id, cap] of capMap) {
|
|
1584
|
+
requiresGraph[id] = Array.isArray(cap.requires) ? cap.requires : [];
|
|
1585
|
+
}
|
|
1586
|
+
lines.push('const _requiresGraph = ' + JSON.stringify(requiresGraph, null, 2) + ';');
|
|
1587
|
+
lines.push('');
|
|
1588
|
+
|
|
1589
|
+
// requiresClosure function
|
|
1590
|
+
lines.push('function requiresClosure(id) {');
|
|
1591
|
+
lines.push(' const visited = new Set();');
|
|
1592
|
+
lines.push(' const queue = [id];');
|
|
1593
|
+
lines.push(' while (queue.length > 0) {');
|
|
1594
|
+
lines.push(' const current = queue.shift();');
|
|
1595
|
+
lines.push(' const reqs = _requiresGraph[current] || [];');
|
|
1596
|
+
lines.push(' for (const req of reqs) {');
|
|
1597
|
+
lines.push(' if (!visited.has(req)) {');
|
|
1598
|
+
lines.push(' visited.add(req);');
|
|
1599
|
+
lines.push(' queue.push(req);');
|
|
1600
|
+
lines.push(' }');
|
|
1601
|
+
lines.push(' }');
|
|
1602
|
+
lines.push(' }');
|
|
1603
|
+
lines.push(' return visited;');
|
|
1604
|
+
lines.push('}');
|
|
1605
|
+
lines.push('');
|
|
1606
|
+
|
|
1607
|
+
lines.push('module.exports = {');
|
|
1608
|
+
lines.push(" version: '" + registry.version + "',");
|
|
1609
|
+
lines.push(' capabilities,');
|
|
1610
|
+
lines.push(' bySkill,');
|
|
1611
|
+
lines.push(' byAgent,');
|
|
1612
|
+
lines.push(' byLoopPoint,');
|
|
1613
|
+
lines.push(' configKeys,');
|
|
1614
|
+
lines.push(' configSchema,');
|
|
1615
|
+
lines.push(' runtimes,');
|
|
1616
|
+
lines.push(' commandFamilies,');
|
|
1617
|
+
lines.push(' capabilityClusters,');
|
|
1618
|
+
lines.push(' profileMembership,');
|
|
1619
|
+
lines.push(' requiresClosure,');
|
|
1620
|
+
lines.push('};');
|
|
1621
|
+
lines.push('');
|
|
1622
|
+
|
|
1623
|
+
return lines.join('\n');
|
|
1624
|
+
}
|
|
1625
|
+
|
|
1626
|
+
// ─── --check diff helper ──────────────────────────────────────────────────────
|
|
1627
|
+
|
|
1628
|
+
/**
|
|
1629
|
+
* Compare committed registry with live registry (for --check).
|
|
1630
|
+
* Strips the generated comment line for comparison.
|
|
1631
|
+
*/
|
|
1632
|
+
function stripGeneratedComment(content) {
|
|
1633
|
+
return content
|
|
1634
|
+
.split('\n')
|
|
1635
|
+
.filter((line) => !line.includes('generated by scripts/gen-capability-registry.cjs'))
|
|
1636
|
+
.join('\n');
|
|
1637
|
+
}
|
|
1638
|
+
|
|
1639
|
+
/**
|
|
1640
|
+
* Normalize line endings to LF.
|
|
1641
|
+
* The generator always writes LF, but Windows git (autocrlf) checks out committed files with
|
|
1642
|
+
* CRLF. The --check comparison must be line-ending-agnostic so it only fails on REAL content
|
|
1643
|
+
* differences, not on checkout-introduced whitespace differences.
|
|
1644
|
+
*
|
|
1645
|
+
* @param {string} content
|
|
1646
|
+
* @returns {string}
|
|
1647
|
+
*/
|
|
1648
|
+
function normalizeLineEndings(content) {
|
|
1649
|
+
return content.replace(/\r/g, '');
|
|
1650
|
+
}
|
|
1651
|
+
|
|
1652
|
+
// ─── Main ─────────────────────────────────────────────────────────────────────
|
|
1653
|
+
|
|
1654
|
+
/**
|
|
1655
|
+
* Fix #3: Emit pending-migration WARNINGs for config keys that collide with the central
|
|
1656
|
+
* config-schema. Per ADR-894 staged cutover, a collision during the registry-only phase is
|
|
1657
|
+
* NOT a hard error — the capability pipeline is being established before the atomic cutover
|
|
1658
|
+
* PR for each feature. The registry still generates; the warning tells the maintainer which
|
|
1659
|
+
* keys need to be moved out of the central schema at cutover time.
|
|
1660
|
+
*
|
|
1661
|
+
* A NEW unexpected collision (a key that shouldn't be in both) is also surfaced — the
|
|
1662
|
+
* maintainer sees it in build output rather than it being silently swallowed.
|
|
1663
|
+
*
|
|
1664
|
+
* Reference: ADR-894 §4 "config-key ownership exclusive AND complete — presence in both =
|
|
1665
|
+
* collision = a mid-flight migration; finish the move."
|
|
1666
|
+
*
|
|
1667
|
+
* @param {string[]} crossErrors Errors from validateCrossCapability (may include collision msgs)
|
|
1668
|
+
* @param {Map<string, object>} capMap
|
|
1669
|
+
* @returns {{ hardErrors: string[], pendingMigrationWarnings: string[] }}
|
|
1670
|
+
*/
|
|
1671
|
+
function classifyCrossErrors(crossErrors) {
|
|
1672
|
+
const hardErrors = [];
|
|
1673
|
+
const pendingMigrationWarnings = [];
|
|
1674
|
+
const collisionRe = /config key "([^"]+)" is declared in capability "([^"]+)" AND exists in the central config-schema/;
|
|
1675
|
+
|
|
1676
|
+
for (const e of crossErrors) {
|
|
1677
|
+
const m = collisionRe.exec(e);
|
|
1678
|
+
if (m) {
|
|
1679
|
+
// Collision = pending-migration warning, not a hard error during 3a-impl staged cutover
|
|
1680
|
+
pendingMigrationWarnings.push(
|
|
1681
|
+
'⚠ pending-migration: capability \'' + m[2] + '\' declares config key \'' + m[1] +
|
|
1682
|
+
'\' still present in central config-schema; finish the move at cutover',
|
|
1683
|
+
);
|
|
1684
|
+
} else {
|
|
1685
|
+
hardErrors.push(e);
|
|
1686
|
+
}
|
|
1687
|
+
}
|
|
1688
|
+
return { hardErrors, pendingMigrationWarnings };
|
|
1689
|
+
}
|
|
1690
|
+
|
|
1691
|
+
function main() {
|
|
1692
|
+
const flag = process.argv[2];
|
|
1693
|
+
|
|
1694
|
+
if (flag === '--check') {
|
|
1695
|
+
// Fix #3: read the REAL central config keys so collision detection fires and is visible.
|
|
1696
|
+
const centralKeys = loadCentralConfigKeys();
|
|
1697
|
+
const { capMap, errors } = loadAndValidate(centralKeys);
|
|
1698
|
+
|
|
1699
|
+
// Separate pending-migration warnings from hard errors
|
|
1700
|
+
const { hardErrors, pendingMigrationWarnings } = classifyCrossErrors(errors);
|
|
1701
|
+
for (const w of pendingMigrationWarnings) process.stderr.write(w + '\n');
|
|
1702
|
+
if (hardErrors.length > 0) {
|
|
1703
|
+
for (const e of hardErrors) process.stderr.write(' ERROR ' + e + '\n');
|
|
1704
|
+
throw new ExitError(1, 'capability validation failed (' + hardErrors.length + ' error(s))');
|
|
1705
|
+
}
|
|
1706
|
+
|
|
1707
|
+
const registry = buildRegistry(capMap);
|
|
1708
|
+
// ADR-857 phase 4a: emit pending-reconciliation warnings to stderr only
|
|
1709
|
+
// (they do NOT affect the generated file content, so --check stays clean)
|
|
1710
|
+
for (const w of (registry._reconciliationWarnings || [])) process.stderr.write(w + '\n');
|
|
1711
|
+
const live = serializeRegistry(registry, capMap);
|
|
1712
|
+
|
|
1713
|
+
if (!fs.existsSync(REGISTRY_PATH)) {
|
|
1714
|
+
process.stderr.write(
|
|
1715
|
+
'gsd-core/bin/lib/capability-registry.cjs does not exist. Run:\n' +
|
|
1716
|
+
' node scripts/gen-capability-registry.cjs --write\n',
|
|
1717
|
+
);
|
|
1718
|
+
throw new ExitError(1);
|
|
1719
|
+
}
|
|
1720
|
+
|
|
1721
|
+
const committed = fs.readFileSync(REGISTRY_PATH, 'utf8');
|
|
1722
|
+
if (normalizeLineEndings(stripGeneratedComment(committed)) !== normalizeLineEndings(stripGeneratedComment(live))) {
|
|
1723
|
+
process.stderr.write(
|
|
1724
|
+
'gsd-core/bin/lib/capability-registry.cjs is stale. Run:\n' +
|
|
1725
|
+
' node scripts/gen-capability-registry.cjs --write\n',
|
|
1726
|
+
);
|
|
1727
|
+
throw new ExitError(1);
|
|
1728
|
+
}
|
|
1729
|
+
|
|
1730
|
+
process.stdout.write('gsd-core/bin/lib/capability-registry.cjs is up to date.\n');
|
|
1731
|
+
} else if (flag === '--write') {
|
|
1732
|
+
// Fix #3: read the REAL central config keys so collision detection fires and is visible.
|
|
1733
|
+
const centralKeys = loadCentralConfigKeys();
|
|
1734
|
+
const { capMap, errors } = loadAndValidate(centralKeys);
|
|
1735
|
+
|
|
1736
|
+
// Separate pending-migration warnings from hard errors
|
|
1737
|
+
const { hardErrors, pendingMigrationWarnings } = classifyCrossErrors(errors);
|
|
1738
|
+
for (const w of pendingMigrationWarnings) process.stderr.write(w + '\n');
|
|
1739
|
+
if (hardErrors.length > 0) {
|
|
1740
|
+
for (const e of hardErrors) process.stderr.write(' ERROR ' + e + '\n');
|
|
1741
|
+
throw new ExitError(1, 'capability validation failed — registry not written');
|
|
1742
|
+
}
|
|
1743
|
+
|
|
1744
|
+
const registry = buildRegistry(capMap);
|
|
1745
|
+
// ADR-857 phase 4a: emit pending-reconciliation warnings to stderr only
|
|
1746
|
+
for (const w of (registry._reconciliationWarnings || [])) process.stderr.write(w + '\n');
|
|
1747
|
+
const content = serializeRegistry(registry, capMap);
|
|
1748
|
+
// Fix #5: mkdir-p before writing so --write doesn't ENOENT in a fresh worktree.
|
|
1749
|
+
fs.mkdirSync(path.dirname(REGISTRY_PATH), { recursive: true });
|
|
1750
|
+
fs.writeFileSync(REGISTRY_PATH, content, 'utf8');
|
|
1751
|
+
process.stdout.write('Wrote ' + REGISTRY_PATH + '\n');
|
|
1752
|
+
} else {
|
|
1753
|
+
// Default: print to stdout — use real central keys for visibility
|
|
1754
|
+
const centralKeys = loadCentralConfigKeys();
|
|
1755
|
+
const { capMap, errors } = loadAndValidate(centralKeys);
|
|
1756
|
+
|
|
1757
|
+
const { hardErrors, pendingMigrationWarnings } = classifyCrossErrors(errors);
|
|
1758
|
+
for (const w of pendingMigrationWarnings) process.stderr.write(w + '\n');
|
|
1759
|
+
if (hardErrors.length > 0) {
|
|
1760
|
+
for (const e of hardErrors) process.stderr.write(' ERROR ' + e + '\n');
|
|
1761
|
+
throw new ExitError(1, 'capability validation failed');
|
|
1762
|
+
}
|
|
1763
|
+
const registry = buildRegistry(capMap);
|
|
1764
|
+
// ADR-857 phase 4a: emit pending-reconciliation warnings to stderr only
|
|
1765
|
+
for (const w of (registry._reconciliationWarnings || [])) process.stderr.write(w + '\n');
|
|
1766
|
+
process.stdout.write(serializeRegistry(registry, capMap) + '\n');
|
|
1767
|
+
}
|
|
1768
|
+
}
|
|
1769
|
+
|
|
1770
|
+
// ─── Exports (for tests) ──────────────────────────────────────────────────────
|
|
1771
|
+
|
|
1772
|
+
module.exports = {
|
|
1773
|
+
validateCapability,
|
|
1774
|
+
validateAgainstContract,
|
|
1775
|
+
validateConsumesGlobal,
|
|
1776
|
+
validateCrossCapability,
|
|
1777
|
+
classifyCrossErrors,
|
|
1778
|
+
loadAndValidate,
|
|
1779
|
+
buildRegistry,
|
|
1780
|
+
serializeRegistry,
|
|
1781
|
+
computeRequiresClosure,
|
|
1782
|
+
topoSortSteps,
|
|
1783
|
+
normalizeLineEndings,
|
|
1784
|
+
validateConfigSliceEntry,
|
|
1785
|
+
VALID_CONFIG_SLICE_TYPES,
|
|
1786
|
+
LOOP_HOST_CONTRACT,
|
|
1787
|
+
VALID_LOOP_POINTS,
|
|
1788
|
+
POINT_ORDER,
|
|
1789
|
+
POINT_TO_CONTRACT,
|
|
1790
|
+
HOST_ARTIFACT_EARLIEST_POINT_IDX,
|
|
1791
|
+
SCHEMA_VERSION,
|
|
1792
|
+
// ADR-857 phase 4a: derived views + gates
|
|
1793
|
+
deriveCapabilityClusters,
|
|
1794
|
+
deriveProfileMembership,
|
|
1795
|
+
runConsistencyGate,
|
|
1796
|
+
// ADR-959: command entry validation
|
|
1797
|
+
validateCommandEntry,
|
|
1798
|
+
// FIX 5 (lazy): PROFILE_RANK and CLUSTERS are loaded on first access via getters
|
|
1799
|
+
// so importing the generator on a fresh/unbuilt worktree doesn't fail at module load.
|
|
1800
|
+
get PROFILE_RANK() { return getInstallProfiles().PROFILE_RANK; },
|
|
1801
|
+
get CLUSTERS() { return getClusters().CLUSTERS; },
|
|
1802
|
+
};
|
|
1803
|
+
|
|
1804
|
+
// ─── CLI entry point ──────────────────────────────────────────────────────────
|
|
1805
|
+
|
|
1806
|
+
if (require.main === module) {
|
|
1807
|
+
runMain(main);
|
|
1808
|
+
}
|