oc-harness-setup 1.0.0 → 1.0.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/CHANGELOG.md +2 -0
- package/GLOSSARY.md +1 -1
- package/README.md +22 -12
- package/bin/cli.js +8 -23
- package/docs/GUIDE.md +76 -42
- package/package.json +1 -1
- package/scripts/harness-doctor.mjs +1439 -0
- package/scripts/harness-doctor.ps1 +0 -1109
|
@@ -0,0 +1,1439 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
/**
|
|
3
|
+
* Self-contained harness health check: derived laws, no allowlists.
|
|
4
|
+
*
|
|
5
|
+
* Validates the global OpenCode harness (~\.config\opencode) with laws DERIVED
|
|
6
|
+
* from the config and the live CLI — never restated from a hardcoded
|
|
7
|
+
* expectation. The consolidation decision (user-approved <DATE>) is that
|
|
8
|
+
* derived laws cannot drift; the old checker's hardcoded allowlists drifted
|
|
9
|
+
* twice in three days, so this doctor absorbed the surviving check logic and
|
|
10
|
+
* the checker was deleted.
|
|
11
|
+
*
|
|
12
|
+
* Laws (each PASS, FAIL, or DRIFT when its source of truth is unavailable):
|
|
13
|
+
* - required layout paths exist; opencode.jsonc parses as JSONC
|
|
14
|
+
* - no legacy remote-catalog keys in opencode.jsonc (declared once below)
|
|
15
|
+
* - `opencode debug config` / `debug agents` resolve (delegated, not
|
|
16
|
+
* reimplemented: exit 0 and parseable output is the whole law)
|
|
17
|
+
* - every configured plugin resolves in `opencode plugin list`
|
|
18
|
+
* - configured MCP servers match `opencode mcp list` in BOTH directions
|
|
19
|
+
* - every live agent model binding resolves against reference/models.md;
|
|
20
|
+
* fully-unwired routing is a supported state while a .docs record
|
|
21
|
+
* documents it (the record is DISCOVERED by content, never named here)
|
|
22
|
+
* - local skill dirs match the fail-closed skill allowlist BOTH directions
|
|
23
|
+
* (orphan dir or dangling allow = FAIL), under a skill:* deny
|
|
24
|
+
* - no literal secret VALUES under a secret-like property name; a `{env:…}`/`{file:…}` pointer is not a leak
|
|
25
|
+
* - the deny set survives --auto (declared gates below, verified derived)
|
|
26
|
+
* - hard denies come after same-action allows (denies-last ordering; the
|
|
27
|
+
* skill fail-closed allowlist allows-after-deny by design, so the skill
|
|
28
|
+
* action is exempt here and stays covered by the allowlist law)
|
|
29
|
+
* - no broad shell allows (node *, git *, or bare *), minus the single
|
|
30
|
+
* documented unattended-shell default whose compensation the deny-set law proves
|
|
31
|
+
* - skill allow entries match local skill IDs in BOTH directions
|
|
32
|
+
* (set-equality form of the allowlist seam; the wildcard-deny half stays
|
|
33
|
+
* with the allowlist law and is not re-checked here)
|
|
34
|
+
* - agents/*.md carry description+steps, commands/*.md carry description
|
|
35
|
+
* (identity is the filename: name: is a skills-only convention)
|
|
36
|
+
* - every skill dir carries a loadable SKILL.md: name+description present,
|
|
37
|
+
* name matches the directory, and no unquoted plain scalar contains ': '
|
|
38
|
+
* (a targeted heuristic, not a full YAML parser)
|
|
39
|
+
* - command IDs and skill IDs are 1:1 both ways (valid skill dirs,
|
|
40
|
+
* excluding the `_shared` reference bundle, against command basenames;
|
|
41
|
+
* an orphan either direction = FAIL)
|
|
42
|
+
* - state/template.md exists and carries the fixed session key order
|
|
43
|
+
* (id, title, status, goal, next, artifacts, decisions, open)
|
|
44
|
+
*
|
|
45
|
+
* The small DECLARED block at the top is the honest form of the old hardcoded
|
|
46
|
+
* state: each entry names its evidence. Everything else is read from
|
|
47
|
+
* opencode.jsonc, agents\, skills\, reference/models.md, .docs, or the CLI.
|
|
48
|
+
*
|
|
49
|
+
* -Fix attempts mechanical declared-state fixes only, with backup + log. The
|
|
50
|
+
* derived laws have no declared state to patch — every remedy touches an owner
|
|
51
|
+
* artifact (config, agents, skills, commands, registry, CLI install) or needs
|
|
52
|
+
* owner judgment — so -Fix re-evaluates, writes nothing, and reports each
|
|
53
|
+
* finding as a one-line owner proposal. Real regressions are never auto-fixed.
|
|
54
|
+
*
|
|
55
|
+
* Exit codes: 0 clean; 1 evaluated law FAILED (regression); 2 the instrument
|
|
56
|
+
* could not derive an expectation (CLI missing, delegated command failed or
|
|
57
|
+
* changed shape, catalog missing — the world drifted under the instrument).
|
|
58
|
+
*
|
|
59
|
+
* Secret hygiene: this script never reads or prints secret-store or .env value contents. Every
|
|
60
|
+
* file read goes through safeText, which refuses those paths, and each run
|
|
61
|
+
* proves the guard is live. Config scans report property paths only.
|
|
62
|
+
*
|
|
63
|
+
* Usage:
|
|
64
|
+
* node scripts/harness-doctor.mjs
|
|
65
|
+
* node scripts/harness-doctor.mjs -Fix
|
|
66
|
+
* node scripts/harness-doctor.mjs -Json
|
|
67
|
+
* node scripts/harness-doctor.mjs -ConfigDir D:\config\opencode
|
|
68
|
+
*
|
|
69
|
+
* -ConfigDir
|
|
70
|
+
* Config directory to grade. The installer passes the resolved config dir
|
|
71
|
+
* (OPENCODE_CONFIG_DIR and cross-platform paths included); standalone runs
|
|
72
|
+
* without it default to ~\.config\opencode.
|
|
73
|
+
*/
|
|
74
|
+
import { spawnSync } from 'node:child_process';
|
|
75
|
+
import { readFileSync, readdirSync, statSync } from 'node:fs';
|
|
76
|
+
import path from 'node:path';
|
|
77
|
+
|
|
78
|
+
/* ------------------------------- arguments -------------------------------- */
|
|
79
|
+
|
|
80
|
+
const argv = process.argv.slice(2);
|
|
81
|
+
let fix = false;
|
|
82
|
+
let json = false;
|
|
83
|
+
let configDirArg = '';
|
|
84
|
+
for (let i = 0; i < argv.length; i++) {
|
|
85
|
+
const flag = argv[i].toLowerCase();
|
|
86
|
+
if (flag === '-fix') fix = true;
|
|
87
|
+
else if (flag === '-json') json = true;
|
|
88
|
+
else if (flag === '-configdir') configDirArg = argv[++i] ?? '';
|
|
89
|
+
}
|
|
90
|
+
|
|
91
|
+
// Windows 10/11 only: this harness grades the Windows config home and shells
|
|
92
|
+
// out to the Windows-only toolchain. Bail as DRIFT (exit 2 — the instrument
|
|
93
|
+
// cannot derive an expectation on this platform), never as a regression.
|
|
94
|
+
if (process.platform !== 'win32') {
|
|
95
|
+
console.error('harness-doctor supports Windows 10/11 only — macOS and Linux are not supported.');
|
|
96
|
+
process.exit(2);
|
|
97
|
+
}
|
|
98
|
+
if (!(process.env.USERPROFILE ?? '').trim()) {
|
|
99
|
+
console.error('USERPROFILE is not set — cannot resolve the Windows config home.');
|
|
100
|
+
process.exit(2);
|
|
101
|
+
}
|
|
102
|
+
|
|
103
|
+
const root = configDirArg || path.join(process.env.USERPROFILE, '.config', 'opencode');
|
|
104
|
+
|
|
105
|
+
/* ---------- declared values (each names its evidence) ---------- */
|
|
106
|
+
// Required layout paths. Evidence: the harness shape itself (opencode.jsonc
|
|
107
|
+
// header "Harness v4"); stable, changes only via a harness restructure.
|
|
108
|
+
const requiredPaths = [
|
|
109
|
+
{ name: 'config (opencode.jsonc)', path: 'opencode.jsonc', kind: 'file' },
|
|
110
|
+
{ name: 'AGENTS.md', path: 'AGENTS.md', kind: 'file' },
|
|
111
|
+
{ name: 'agents', path: 'agents', kind: 'dir' },
|
|
112
|
+
{ name: 'commands', path: 'commands', kind: 'dir' },
|
|
113
|
+
{ name: 'skills', path: 'skills', kind: 'dir' },
|
|
114
|
+
{ name: 'reference', path: 'reference', kind: 'dir' },
|
|
115
|
+
{ name: 'state/lessons.md', path: 'state/lessons.md', kind: 'file' },
|
|
116
|
+
{ name: 'state/template.md', path: 'state/template.md', kind: 'file' },
|
|
117
|
+
{ name: 'Git exclusion policy', path: '.gitignore', kind: 'file' },
|
|
118
|
+
];
|
|
119
|
+
|
|
120
|
+
// Legacy / remote-catalog top-level keys that must not appear in opencode.jsonc.
|
|
121
|
+
// Evidence: the package's own .docs (the "no remote skill-catalog keys" file check).
|
|
122
|
+
// 'plugins' and 'mcp' are legitimate config and are NOT here.
|
|
123
|
+
const remoteCatalogKeys = ['plugin', 'mcpServers', 'mcp_servers', 'skill_catalog', 'skills_catalog', 'remote_skills', 'skills_remote'];
|
|
124
|
+
|
|
125
|
+
// Deny gates that must hold as effect=deny (ask is auto-approved under --auto,
|
|
126
|
+
// so only deny survives). Evidence: the opencode.jsonc inline policy comment
|
|
127
|
+
// ("deny is the only gate that holds while you are away"; same text in the package's
|
|
128
|
+
// own .docs). Verification is
|
|
129
|
+
// derived: each gate needs a matching deny rule in the live permissions array.
|
|
130
|
+
const denyGates = [
|
|
131
|
+
{ action: 'shell', contains: 'Format-Volume' },
|
|
132
|
+
{ action: 'shell', contains: 'Clear-Disk' },
|
|
133
|
+
{ action: 'read', contains: 'secrets' },
|
|
134
|
+
{ action: 'edit', contains: 'secrets' },
|
|
135
|
+
{ action: 'external_directory', contains: 'secrets' },
|
|
136
|
+
{ action: 'shell', contains: 'secrets' },
|
|
137
|
+
{ action: 'read', contains: '.env' },
|
|
138
|
+
{ action: 'edit', contains: '.env' },
|
|
139
|
+
{ action: 'external_directory', contains: '.env' },
|
|
140
|
+
{ action: 'shell', contains: '.env' },
|
|
141
|
+
{ action: 'read', contains: 'service.json' },
|
|
142
|
+
{ action: 'edit', contains: 'service.json' },
|
|
143
|
+
{ action: 'external_directory', contains: 'service.json' },
|
|
144
|
+
{ action: 'shell', contains: 'service.json' },
|
|
145
|
+
];
|
|
146
|
+
|
|
147
|
+
// Secret-like config property NAMES (never values). Evidence: secret-hygiene
|
|
148
|
+
// convention carried over from the deleted checker lineage.
|
|
149
|
+
const secretNamePattern = /(apikey|api_key|secret|password|bearer|credential)/i;
|
|
150
|
+
|
|
151
|
+
/* -------------------------------- helpers --------------------------------- */
|
|
152
|
+
|
|
153
|
+
// PowerShell's -eq/-contains/-ne compare strings case-insensitively; the port
|
|
154
|
+
// keeps that so a config that graded PASS before still grades PASS.
|
|
155
|
+
const eqCI = (a, b) => String(a).toLowerCase() === String(b).toLowerCase();
|
|
156
|
+
const hasCI = (list, value) => list.some((item) => eqCI(item, value));
|
|
157
|
+
const sortUnique = (list) => [...new Set(list)].sort();
|
|
158
|
+
|
|
159
|
+
function isFile(p) {
|
|
160
|
+
try {
|
|
161
|
+
return statSync(p).isFile();
|
|
162
|
+
} catch {
|
|
163
|
+
return false;
|
|
164
|
+
}
|
|
165
|
+
}
|
|
166
|
+
|
|
167
|
+
function isDir(p) {
|
|
168
|
+
try {
|
|
169
|
+
return statSync(p).isDirectory();
|
|
170
|
+
} catch {
|
|
171
|
+
return false;
|
|
172
|
+
}
|
|
173
|
+
}
|
|
174
|
+
|
|
175
|
+
function listFiles(dir, filter = null) {
|
|
176
|
+
if (!isDir(dir)) return [];
|
|
177
|
+
try {
|
|
178
|
+
return readdirSync(dir, { withFileTypes: true })
|
|
179
|
+
.filter((ent) => ent.isFile() && (!filter || filter.test(ent.name)))
|
|
180
|
+
.map((ent) => ent.name);
|
|
181
|
+
} catch {
|
|
182
|
+
return [];
|
|
183
|
+
}
|
|
184
|
+
}
|
|
185
|
+
|
|
186
|
+
function listDirs(dir) {
|
|
187
|
+
if (!isDir(dir)) return [];
|
|
188
|
+
try {
|
|
189
|
+
return readdirSync(dir, { withFileTypes: true })
|
|
190
|
+
.filter((ent) => ent.isDirectory())
|
|
191
|
+
.map((ent) => ent.name);
|
|
192
|
+
} catch {
|
|
193
|
+
return [];
|
|
194
|
+
}
|
|
195
|
+
}
|
|
196
|
+
|
|
197
|
+
// The file reader in this script. Refuses secret-bearing paths outright,
|
|
198
|
+
// so no code path here can read secret-store or .env contents.
|
|
199
|
+
function safeText(p) {
|
|
200
|
+
const normalized = String(p).replace(/\\/g, '/');
|
|
201
|
+
if (/(^|\/)([.]secrets|\.env)(\/|$)|(^|\/)[^/]*\.env(\.|$)/i.test(normalized)) {
|
|
202
|
+
throw new Error(`refused to read secret-bearing path: ${p}`);
|
|
203
|
+
}
|
|
204
|
+
const text = readFileSync(p, 'utf8');
|
|
205
|
+
// Get-Content decodes and drops a UTF-8 BOM; readFileSync keeps it.
|
|
206
|
+
return text.charCodeAt(0) === 0xfeff ? text.slice(1) : text;
|
|
207
|
+
}
|
|
208
|
+
|
|
209
|
+
// Strip // and /* */ comments (string-aware), then trailing commas, then parse.
|
|
210
|
+
function parseJsonc(text) {
|
|
211
|
+
let out = '';
|
|
212
|
+
let inString = false;
|
|
213
|
+
let i = 0;
|
|
214
|
+
while (i < text.length) {
|
|
215
|
+
const c = text[i];
|
|
216
|
+
if (inString) {
|
|
217
|
+
out += c;
|
|
218
|
+
if (c === '\\') {
|
|
219
|
+
i++;
|
|
220
|
+
if (i < text.length) out += text[i];
|
|
221
|
+
} else if (c === '"') {
|
|
222
|
+
inString = false;
|
|
223
|
+
}
|
|
224
|
+
i++;
|
|
225
|
+
continue;
|
|
226
|
+
}
|
|
227
|
+
if (c === '"') {
|
|
228
|
+
inString = true;
|
|
229
|
+
out += c;
|
|
230
|
+
i++;
|
|
231
|
+
continue;
|
|
232
|
+
}
|
|
233
|
+
if (c === '/' && i + 1 < text.length) {
|
|
234
|
+
const n = text[i + 1];
|
|
235
|
+
if (n === '/') {
|
|
236
|
+
while (i < text.length && text[i] !== '\n') i++;
|
|
237
|
+
continue;
|
|
238
|
+
}
|
|
239
|
+
if (n === '*') {
|
|
240
|
+
i += 2;
|
|
241
|
+
while (i + 1 < text.length && !(text[i] === '*' && text[i + 1] === '/')) i++;
|
|
242
|
+
i += 2;
|
|
243
|
+
continue;
|
|
244
|
+
}
|
|
245
|
+
}
|
|
246
|
+
out += c;
|
|
247
|
+
i++;
|
|
248
|
+
}
|
|
249
|
+
return JSON.parse(out.replace(/,(\s*[}\]])/g, '$1'));
|
|
250
|
+
}
|
|
251
|
+
|
|
252
|
+
// Get-Command opencode: is the CLI reachable on PATH at all?
|
|
253
|
+
function onPath(name) {
|
|
254
|
+
const exts = (process.env.PATHEXT || '.COM;.EXE;.BAT;.CMD').split(';').filter(Boolean);
|
|
255
|
+
for (const dir of (process.env.PATH || '').split(path.delimiter)) {
|
|
256
|
+
if (!dir) continue;
|
|
257
|
+
if (isFile(path.join(dir, name))) return true;
|
|
258
|
+
for (const ext of exts) {
|
|
259
|
+
if (isFile(path.join(dir, name + ext))) return true;
|
|
260
|
+
if (isFile(path.join(dir, name + ext.toLowerCase()))) return true;
|
|
261
|
+
}
|
|
262
|
+
}
|
|
263
|
+
return false;
|
|
264
|
+
}
|
|
265
|
+
|
|
266
|
+
function invokeCli(command, args) {
|
|
267
|
+
// A `.cmd` shim is only reachable through cmd.exe on Windows, so the direct
|
|
268
|
+
// spawn is retried the same way bin/cli.js does; an .exe resolves directly.
|
|
269
|
+
const opts = { encoding: 'utf8', windowsHide: true };
|
|
270
|
+
let res = spawnSync(command, args, opts);
|
|
271
|
+
if (res.error && res.error.code === 'ENOENT' && process.platform === 'win32') {
|
|
272
|
+
const comspec = process.env.ComSpec || 'cmd.exe';
|
|
273
|
+
const retry = spawnSync(comspec, ['/d', '/s', '/c', command, ...args], opts);
|
|
274
|
+
if (!retry.error) res = retry;
|
|
275
|
+
}
|
|
276
|
+
const lines = `${res.stdout ?? ''}${res.stderr ?? ''}`.split(/\r?\n/);
|
|
277
|
+
// A captured PowerShell array drops the empty tail a trailing newline makes.
|
|
278
|
+
while (lines.length > 0 && lines[lines.length - 1] === '') lines.pop();
|
|
279
|
+
return { exit: res.error ? -1 : (res.status ?? -1), lines };
|
|
280
|
+
}
|
|
281
|
+
|
|
282
|
+
// Server NAMES only; values are never read or printed. Accepts the file
|
|
283
|
+
// shape (mcp.<name>) and the merged V2 shape (mcp.servers.<name>).
|
|
284
|
+
function getMcpServerNames(mcpNode) {
|
|
285
|
+
if (mcpNode === null || mcpNode === undefined) return [];
|
|
286
|
+
if (typeof mcpNode !== 'object' || Array.isArray(mcpNode)) return ['<malformed>'];
|
|
287
|
+
const container = mcpNode.servers !== null && mcpNode.servers !== undefined ? mcpNode.servers : mcpNode;
|
|
288
|
+
if (typeof container !== 'object' || container === null || Array.isArray(container)) return ['<malformed>'];
|
|
289
|
+
return Object.keys(container);
|
|
290
|
+
}
|
|
291
|
+
|
|
292
|
+
// StrictMode-safe read of the permissions array. A config that omits the
|
|
293
|
+
// key (or carries a non-array) grades as an empty set, so dependent laws
|
|
294
|
+
// FAIL with their named reason instead of throwing a property error.
|
|
295
|
+
function getPermissionRules(config) {
|
|
296
|
+
if (config === null || config === undefined || typeof config !== 'object') return [];
|
|
297
|
+
const value = config.permissions;
|
|
298
|
+
if (value === null || value === undefined) return [];
|
|
299
|
+
if (typeof value === 'string') return [];
|
|
300
|
+
return Array.isArray(value) ? value : [];
|
|
301
|
+
}
|
|
302
|
+
|
|
303
|
+
// First token per line of `opencode mcp list`, minus status markers.
|
|
304
|
+
function getRegistryMcpNames(lines) {
|
|
305
|
+
const names = [];
|
|
306
|
+
for (const line of lines) {
|
|
307
|
+
const text = String(line).replace(/^[\u2713\u2717\u00D7\u2022\-\s]+/, '').trim();
|
|
308
|
+
if (text === '') continue;
|
|
309
|
+
const name = text.split(/\s+/).filter((tok) => tok !== '')[0];
|
|
310
|
+
if (name && !/^(id|name|server|status|no)$/i.test(name)) names.push(String(name));
|
|
311
|
+
}
|
|
312
|
+
return sortUnique(names);
|
|
313
|
+
}
|
|
314
|
+
|
|
315
|
+
// A value that POINTS at a secret is not the secret itself.
|
|
316
|
+
function testSecretPointer(value) {
|
|
317
|
+
if (value === null || value === undefined) return true;
|
|
318
|
+
if (typeof value !== 'string') return false;
|
|
319
|
+
const text = value.trim();
|
|
320
|
+
if (text === '') return true;
|
|
321
|
+
return /^(\{[A-Za-z][A-Za-z0-9_-]*:[^}]*\}|\$\{[^}]*\}|\$[A-Za-z_][A-Za-z0-9_]*)$/.test(text);
|
|
322
|
+
}
|
|
323
|
+
|
|
324
|
+
// Property PATHS whose names look secret-like, each with a pointer flag.
|
|
325
|
+
// Values are never returned.
|
|
326
|
+
function findSecretLikeProps(node, nodePath, hits = []) {
|
|
327
|
+
if (node === null || node === undefined) return hits;
|
|
328
|
+
if (Array.isArray(node)) {
|
|
329
|
+
node.forEach((item, idx) => findSecretLikeProps(item, `${nodePath}[${idx}]`, hits));
|
|
330
|
+
return hits;
|
|
331
|
+
}
|
|
332
|
+
if (typeof node === 'object') {
|
|
333
|
+
for (const [key, value] of Object.entries(node)) {
|
|
334
|
+
const childPath = nodePath ? `${nodePath}.${key}` : String(key);
|
|
335
|
+
if (secretNamePattern.test(key)) hits.push({ path: childPath, pointer: testSecretPointer(value) });
|
|
336
|
+
findSecretLikeProps(value, childPath, hits);
|
|
337
|
+
}
|
|
338
|
+
}
|
|
339
|
+
return hits;
|
|
340
|
+
}
|
|
341
|
+
|
|
342
|
+
function getFrontmatterText(p) {
|
|
343
|
+
// A skill directory with no SKILL.md is Law 9/16's seam ('file missing'),
|
|
344
|
+
// not a crash: getFrontmatterProblems already reports it, so return null
|
|
345
|
+
// here and let the laws grade it as FAIL instead of aborting the run.
|
|
346
|
+
if (!isFile(p)) return null;
|
|
347
|
+
const lines = safeText(p).split(/\r?\n/);
|
|
348
|
+
if (lines.length < 3 || lines[0].trim() !== '---') return null;
|
|
349
|
+
for (let i = 1; i < lines.length; i++) {
|
|
350
|
+
if (lines[i].trim() === '---') return lines.slice(1, i).join('\n');
|
|
351
|
+
}
|
|
352
|
+
return null;
|
|
353
|
+
}
|
|
354
|
+
|
|
355
|
+
function getFrontmatterProblems(p, require = ['description']) {
|
|
356
|
+
const problems = [];
|
|
357
|
+
if (!isFile(p)) {
|
|
358
|
+
problems.push('file missing');
|
|
359
|
+
return problems;
|
|
360
|
+
}
|
|
361
|
+
const fm = getFrontmatterText(p);
|
|
362
|
+
if (fm === null) {
|
|
363
|
+
problems.push('no frontmatter block');
|
|
364
|
+
return problems;
|
|
365
|
+
}
|
|
366
|
+
for (const req of require) {
|
|
367
|
+
const m = fm.match(new RegExp(`^\\s*${req}\\s*:\\s*(.*)$`, 'im'));
|
|
368
|
+
if (!m) problems.push(`frontmatter missing ${req}`);
|
|
369
|
+
else if (m[1].trim() === '') problems.push(`frontmatter empty ${req}`);
|
|
370
|
+
}
|
|
371
|
+
return problems;
|
|
372
|
+
}
|
|
373
|
+
|
|
374
|
+
// Targeted heuristic, NOT a full YAML parser: it looks only for the shape
|
|
375
|
+
// that once made a skill unloadable — a top-level, plain (unquoted,
|
|
376
|
+
// non-block) `key: value` whose value contains a colon-space, which YAML
|
|
377
|
+
// reads as a nested mapping and rejects. Block scalars (>, |, >-, |-) and
|
|
378
|
+
// quoted values are exempt. Returns the offending lines verbatim.
|
|
379
|
+
function getPlainScalarHazards(p) {
|
|
380
|
+
const hazards = [];
|
|
381
|
+
const fm = getFrontmatterText(p);
|
|
382
|
+
if (fm === null) return hazards;
|
|
383
|
+
for (const line of fm.split(/\r?\n/)) {
|
|
384
|
+
const m = line.match(/^([A-Za-z0-9_.-]+)\s*:\s*(.*)$/);
|
|
385
|
+
if (!m) continue;
|
|
386
|
+
const value = m[2].trim();
|
|
387
|
+
if (value === '') continue;
|
|
388
|
+
if (['>', '|', '>-', '|-', '>+', '|+'].some((tok) => eqCI(value, tok))) continue;
|
|
389
|
+
if (value.startsWith('"') || value.startsWith("'")) continue;
|
|
390
|
+
if (value.includes(': ')) hazards.push(line.replace(/\s+$/, ''));
|
|
391
|
+
}
|
|
392
|
+
return hazards;
|
|
393
|
+
}
|
|
394
|
+
|
|
395
|
+
// First uncommented `model:` value in a frontmatter block, or null. A
|
|
396
|
+
// commented `# model:` line never matches, so unwired stays unwired.
|
|
397
|
+
function getLiveModelBinding(frontmatterText) {
|
|
398
|
+
if (!frontmatterText || frontmatterText.trim() === '') return null;
|
|
399
|
+
for (const line of frontmatterText.split(/\r?\n/)) {
|
|
400
|
+
const m = line.match(/^\s*model\s*:\s*(.+?)\s*$/i);
|
|
401
|
+
if (m) {
|
|
402
|
+
const value = m[1].trim().replace(/^"+|"+$/g, '').replace(/^'+|'+$/g, '');
|
|
403
|
+
if (value) return value;
|
|
404
|
+
}
|
|
405
|
+
}
|
|
406
|
+
return null;
|
|
407
|
+
}
|
|
408
|
+
|
|
409
|
+
// Model ids AND the provider prefix, both read from reference/models.md.
|
|
410
|
+
// Accepts two shapes: `- `provider/model-id`` bullets, or a
|
|
411
|
+
// `Model (provider/<id>)` line plus `| n | `id` |` rows.
|
|
412
|
+
function getModelCatalog(p) {
|
|
413
|
+
const ids = [];
|
|
414
|
+
const bindings = [];
|
|
415
|
+
let provider = '';
|
|
416
|
+
if (!isFile(p)) return { ids, bindings, provider, found: false };
|
|
417
|
+
const text = safeText(p);
|
|
418
|
+
const providerMatch = text.match(/Model \(([A-Za-z0-9._-]+)\/<id>\)/i);
|
|
419
|
+
provider = providerMatch ? providerMatch[1] : '';
|
|
420
|
+
for (const m of text.matchAll(/^\|\s*\d+\s*\|\s*`([^`]+)`/gim)) ids.push(m[1].trim());
|
|
421
|
+
if (providerMatch) {
|
|
422
|
+
const escaped = provider.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
|
|
423
|
+
for (const m of text.matchAll(new RegExp(`${escaped}/([A-Za-z0-9._-]+)`, 'gi'))) ids.push(m[1].trim());
|
|
424
|
+
}
|
|
425
|
+
for (const m of text.matchAll(/^\s*[-*]\s+`([A-Za-z0-9._-]+\/[A-Za-z0-9._-]+)`/gim)) bindings.push(m[1].trim());
|
|
426
|
+
return { ids: sortUnique(ids), bindings: sortUnique(bindings), provider, found: true };
|
|
427
|
+
}
|
|
428
|
+
|
|
429
|
+
// null when the binding resolves against the catalog; otherwise a reason.
|
|
430
|
+
function testModelBinding(value, catalog) {
|
|
431
|
+
let text = String(value);
|
|
432
|
+
const hash = text.indexOf('#');
|
|
433
|
+
if (hash >= 0) text = text.slice(0, hash);
|
|
434
|
+
text = text.trim();
|
|
435
|
+
const m = text.match(/^([A-Za-z0-9._-]+)\/([^/]+)$/);
|
|
436
|
+
if (!m) return `model '${value}' is not a provider/id binding`;
|
|
437
|
+
if (catalog.provider && catalog.provider.trim() !== '') {
|
|
438
|
+
if (!eqCI(m[1], catalog.provider)) {
|
|
439
|
+
return `model '${value}' uses provider '${m[1]}' but the catalog declares '${catalog.provider}'`;
|
|
440
|
+
}
|
|
441
|
+
if (!hasCI(catalog.ids, m[2])) return `model '${value}' does not resolve in reference/models.md`;
|
|
442
|
+
return null;
|
|
443
|
+
}
|
|
444
|
+
if (catalog.bindings.length > 0) {
|
|
445
|
+
if (hasCI(catalog.bindings, text)) return null;
|
|
446
|
+
return `model '${value}' does not resolve in reference/models.md`;
|
|
447
|
+
}
|
|
448
|
+
return 'the model catalog declares neither shape: add `- `provider/model-id`` bullets, or a `Model (provider/<id>)` line plus `| n | `id` |` rows';
|
|
449
|
+
}
|
|
450
|
+
|
|
451
|
+
// The .docs record documenting unwired model routing, found by CONTENT.
|
|
452
|
+
function getUnwiredRoutingDoc(docsRoot) {
|
|
453
|
+
if (!isDir(docsRoot)) return null;
|
|
454
|
+
// newest-first: the latest unwire record wins; an earlier name-ascending
|
|
455
|
+
// match could cite an older record.
|
|
456
|
+
for (const name of listFiles(docsRoot, /\.md$/i).sort().reverse()) {
|
|
457
|
+
const text = safeText(path.join(docsRoot, name));
|
|
458
|
+
if (/unwire[a-z]*\b[^.]{0,40}\bmodel\b|\bmodel\b[^.]{0,40}\bunwired\b/is.test(text)) return name;
|
|
459
|
+
}
|
|
460
|
+
return null;
|
|
461
|
+
}
|
|
462
|
+
|
|
463
|
+
/* ---------------------------- law evaluation ------------------------------ */
|
|
464
|
+
|
|
465
|
+
const laws = [];
|
|
466
|
+
|
|
467
|
+
function addLaw(name, verdict, detail, proposal = '') {
|
|
468
|
+
laws.push({ law: name, result: verdict, detail, proposal });
|
|
469
|
+
}
|
|
470
|
+
|
|
471
|
+
const configPath = path.join(root, 'opencode.jsonc');
|
|
472
|
+
const docsRoot = path.join(root, '.docs');
|
|
473
|
+
const agentsDir = path.join(root, 'agents');
|
|
474
|
+
const commandsDir = path.join(root, 'commands');
|
|
475
|
+
const skillsRoot = path.join(root, 'skills');
|
|
476
|
+
const catalogPath = path.join(root, 'reference', 'models.md');
|
|
477
|
+
|
|
478
|
+
// Law 1: required layout paths.
|
|
479
|
+
const missingPaths = [];
|
|
480
|
+
for (const req of requiredPaths) {
|
|
481
|
+
const full = path.join(root, req.path);
|
|
482
|
+
if (req.kind === 'file') {
|
|
483
|
+
if (!isFile(full)) missingPaths.push(req.path);
|
|
484
|
+
} else if (!isDir(full)) missingPaths.push(req.path);
|
|
485
|
+
}
|
|
486
|
+
if (missingPaths.length === 0) {
|
|
487
|
+
addLaw('required layout paths exist', 'PASS', `all present under ${root}`);
|
|
488
|
+
} else {
|
|
489
|
+
addLaw(
|
|
490
|
+
'required layout paths exist',
|
|
491
|
+
'FAIL',
|
|
492
|
+
`missing: ${missingPaths.join(', ')}`,
|
|
493
|
+
`restore the missing harness paths (${missingPaths.join(', ')}) — the layout is declared at the top of scripts\\harness-doctor.mjs`
|
|
494
|
+
);
|
|
495
|
+
}
|
|
496
|
+
|
|
497
|
+
// Law 2: opencode.jsonc parses.
|
|
498
|
+
let config = null;
|
|
499
|
+
if (!isFile(configPath)) {
|
|
500
|
+
addLaw(
|
|
501
|
+
'opencode.jsonc parses as JSONC',
|
|
502
|
+
'FAIL',
|
|
503
|
+
'opencode.jsonc is missing',
|
|
504
|
+
'restore opencode.jsonc (the harness has no config without it)'
|
|
505
|
+
);
|
|
506
|
+
} else {
|
|
507
|
+
try {
|
|
508
|
+
config = parseJsonc(safeText(configPath));
|
|
509
|
+
addLaw('opencode.jsonc parses as JSONC', 'PASS', 'parsed as JSONC (comments and trailing commas stripped)');
|
|
510
|
+
} catch (err) {
|
|
511
|
+
const message = err instanceof Error ? err.message : String(err);
|
|
512
|
+
addLaw(
|
|
513
|
+
'opencode.jsonc parses as JSONC',
|
|
514
|
+
'FAIL',
|
|
515
|
+
`JSONC parse failed: ${message}`,
|
|
516
|
+
`fix the JSONC syntax error in opencode.jsonc: ${message}`
|
|
517
|
+
);
|
|
518
|
+
}
|
|
519
|
+
}
|
|
520
|
+
const configOk = config !== null && config !== undefined;
|
|
521
|
+
|
|
522
|
+
// Laws needing the config file derive nothing when it is unparseable.
|
|
523
|
+
function addConfigDrift(name) {
|
|
524
|
+
addLaw(name, 'DRIFT', 'not evaluated: opencode.jsonc is unparseable', 'fix the JSONC syntax error first (see the parse law above)');
|
|
525
|
+
}
|
|
526
|
+
|
|
527
|
+
// Law 3: no legacy remote-catalog keys.
|
|
528
|
+
if (configOk) {
|
|
529
|
+
const badKeys = Object.keys(config).filter((key) => hasCI(remoteCatalogKeys, key));
|
|
530
|
+
if (badKeys.length === 0) {
|
|
531
|
+
addLaw(
|
|
532
|
+
'no legacy remote-catalog keys in opencode.jsonc',
|
|
533
|
+
'PASS',
|
|
534
|
+
'no plugin/mcpServers/skill-catalog keys; plugins[] and mcp come from config + registry only'
|
|
535
|
+
);
|
|
536
|
+
} else {
|
|
537
|
+
addLaw(
|
|
538
|
+
'no legacy remote-catalog keys in opencode.jsonc',
|
|
539
|
+
'FAIL',
|
|
540
|
+
`legacy keys present: ${badKeys.join(', ')}`,
|
|
541
|
+
`remove these keys from opencode.jsonc (${badKeys.join(', ')}) — see the package's own .docs`
|
|
542
|
+
);
|
|
543
|
+
}
|
|
544
|
+
} else {
|
|
545
|
+
addConfigDrift('no legacy remote-catalog keys in opencode.jsonc');
|
|
546
|
+
}
|
|
547
|
+
|
|
548
|
+
// Law 4 + 5: delegated CLI resolution (the law IS the delegation).
|
|
549
|
+
const cli = onPath('opencode');
|
|
550
|
+
if (!cli) {
|
|
551
|
+
addLaw(
|
|
552
|
+
'opencode debug config resolves',
|
|
553
|
+
'DRIFT',
|
|
554
|
+
'opencode was not found on PATH',
|
|
555
|
+
'install or repair the OpenCode V2 CLI, confirm it with `Get-Command opencode`, then re-run the doctor'
|
|
556
|
+
);
|
|
557
|
+
addLaw(
|
|
558
|
+
'opencode debug agents resolves',
|
|
559
|
+
'DRIFT',
|
|
560
|
+
'opencode was not found on PATH',
|
|
561
|
+
'install or repair the OpenCode V2 CLI, confirm it with `Get-Command opencode`, then re-run the doctor'
|
|
562
|
+
);
|
|
563
|
+
} else {
|
|
564
|
+
const cfgRun = invokeCli('opencode', ['debug', 'config']);
|
|
565
|
+
if (cfgRun.exit !== 0) {
|
|
566
|
+
addLaw(
|
|
567
|
+
'opencode debug config resolves',
|
|
568
|
+
'DRIFT',
|
|
569
|
+
`opencode debug config exited ${cfgRun.exit}`,
|
|
570
|
+
`repair the CLI/config handshake: ${cfgRun.lines.join(' ')}`
|
|
571
|
+
);
|
|
572
|
+
} else {
|
|
573
|
+
try {
|
|
574
|
+
const parsed = JSON.parse(cfgRun.lines.join('\n'));
|
|
575
|
+
const entries = Array.isArray(parsed) ? parsed : [parsed];
|
|
576
|
+
const docEntry = entries.filter(
|
|
577
|
+
(entry) => entry && typeof entry === 'object' && eqCI(entry.type, 'document') && /opencode\.jsonc$/i.test(String(entry.path ?? ''))
|
|
578
|
+
);
|
|
579
|
+
if (docEntry.length > 0) {
|
|
580
|
+
addLaw(
|
|
581
|
+
'opencode debug config resolves',
|
|
582
|
+
'PASS',
|
|
583
|
+
'debug config exits 0 and lists opencode.jsonc as a document source'
|
|
584
|
+
);
|
|
585
|
+
} else {
|
|
586
|
+
addLaw(
|
|
587
|
+
'opencode debug config resolves',
|
|
588
|
+
'FAIL',
|
|
589
|
+
'debug config exits 0 but lists no opencode.jsonc document source',
|
|
590
|
+
'check which config file the CLI is actually loading (path mismatch between the CLI and this harness root)'
|
|
591
|
+
);
|
|
592
|
+
}
|
|
593
|
+
} catch (err) {
|
|
594
|
+
const message = err instanceof Error ? err.message : String(err);
|
|
595
|
+
addLaw(
|
|
596
|
+
'opencode debug config resolves',
|
|
597
|
+
'DRIFT',
|
|
598
|
+
`debug config output was not parseable JSON: ${message}`,
|
|
599
|
+
're-run `opencode debug config` by hand; the CLI output shape may have changed'
|
|
600
|
+
);
|
|
601
|
+
}
|
|
602
|
+
}
|
|
603
|
+
const agRun = invokeCli('opencode', ['debug', 'agents']);
|
|
604
|
+
if (agRun.exit !== 0) {
|
|
605
|
+
addLaw(
|
|
606
|
+
'opencode debug agents resolves',
|
|
607
|
+
'DRIFT',
|
|
608
|
+
`opencode debug agents exited ${agRun.exit}`,
|
|
609
|
+
`repair the CLI/agent handshake: ${agRun.lines.join(' ')}`
|
|
610
|
+
);
|
|
611
|
+
} else {
|
|
612
|
+
try {
|
|
613
|
+
const parsed = JSON.parse(agRun.lines.join('\n'));
|
|
614
|
+
const roster = Array.isArray(parsed) ? parsed : [parsed];
|
|
615
|
+
if (roster.length > 0) {
|
|
616
|
+
addLaw(
|
|
617
|
+
'opencode debug agents resolves',
|
|
618
|
+
'PASS',
|
|
619
|
+
`debug agents exits 0 and returns a parseable roster (${roster.length} entries)`
|
|
620
|
+
);
|
|
621
|
+
} else {
|
|
622
|
+
addLaw(
|
|
623
|
+
'opencode debug agents resolves',
|
|
624
|
+
'FAIL',
|
|
625
|
+
'debug agents exits 0 but returns an empty roster',
|
|
626
|
+
'check agents\\ for missing or unparseable definitions'
|
|
627
|
+
);
|
|
628
|
+
}
|
|
629
|
+
} catch (err) {
|
|
630
|
+
const message = err instanceof Error ? err.message : String(err);
|
|
631
|
+
addLaw(
|
|
632
|
+
'opencode debug agents resolves',
|
|
633
|
+
'DRIFT',
|
|
634
|
+
`debug agents output was not parseable JSON: ${message}`,
|
|
635
|
+
're-run `opencode debug agents` by hand; the CLI output shape may have changed'
|
|
636
|
+
);
|
|
637
|
+
}
|
|
638
|
+
}
|
|
639
|
+
}
|
|
640
|
+
|
|
641
|
+
// Configured plugins + MCP servers, read once (NAMES only; values never read).
|
|
642
|
+
let configuredPlugins = [];
|
|
643
|
+
let configuredMcp = [];
|
|
644
|
+
if (configOk) {
|
|
645
|
+
if (config.plugins !== null && config.plugins !== undefined) {
|
|
646
|
+
configuredPlugins = Array.isArray(config.plugins) ? config.plugins : [config.plugins];
|
|
647
|
+
}
|
|
648
|
+
if (config.mcp !== null && config.mcp !== undefined) configuredMcp = getMcpServerNames(config.mcp);
|
|
649
|
+
}
|
|
650
|
+
|
|
651
|
+
// Law 6: every configured plugin resolves in the installed registry.
|
|
652
|
+
if (!configOk) {
|
|
653
|
+
addConfigDrift('every configured plugin resolves in the registry');
|
|
654
|
+
} else if (!cli) {
|
|
655
|
+
addLaw(
|
|
656
|
+
'every configured plugin resolves in the registry',
|
|
657
|
+
'DRIFT',
|
|
658
|
+
'not evaluated: opencode was not found on PATH',
|
|
659
|
+
'install or repair the OpenCode V2 CLI, then re-run the doctor'
|
|
660
|
+
);
|
|
661
|
+
} else {
|
|
662
|
+
const pluginRun = invokeCli('opencode', ['plugin', 'list']);
|
|
663
|
+
if (pluginRun.exit !== 0) {
|
|
664
|
+
addLaw(
|
|
665
|
+
'every configured plugin resolves in the registry',
|
|
666
|
+
'DRIFT',
|
|
667
|
+
`opencode plugin list exited ${pluginRun.exit}`,
|
|
668
|
+
`re-run \`opencode plugin list\` by hand: ${pluginRun.lines.join(' ')}`
|
|
669
|
+
);
|
|
670
|
+
} else {
|
|
671
|
+
const pluginText = pluginRun.lines.join('\n');
|
|
672
|
+
const noPlugins = /No plugins found/i.test(pluginText);
|
|
673
|
+
const pluginRows = pluginRun.lines.filter((line) => String(line).trim() !== '').slice(1);
|
|
674
|
+
const unresolved = [];
|
|
675
|
+
for (const entry of configuredPlugins) {
|
|
676
|
+
const text = String(entry);
|
|
677
|
+
let resolves = false;
|
|
678
|
+
for (const row of pluginRows) {
|
|
679
|
+
if (String(row).includes(text)) {
|
|
680
|
+
resolves = true;
|
|
681
|
+
break;
|
|
682
|
+
}
|
|
683
|
+
const firstCol = String(row).split(/\s+/).filter((tok) => tok !== '')[0];
|
|
684
|
+
if (firstCol !== undefined && eqCI(firstCol, text)) {
|
|
685
|
+
resolves = true;
|
|
686
|
+
break;
|
|
687
|
+
}
|
|
688
|
+
}
|
|
689
|
+
if (!resolves) unresolved.push(text);
|
|
690
|
+
}
|
|
691
|
+
if (unresolved.length > 0) {
|
|
692
|
+
addLaw(
|
|
693
|
+
'every configured plugin resolves in the registry',
|
|
694
|
+
'FAIL',
|
|
695
|
+
`configured plugins missing from the registry: ${unresolved.join(', ')}`,
|
|
696
|
+
`reconcile each with the registry (install it, or remove it from plugins[] in opencode.jsonc): ${unresolved.join(', ')}`
|
|
697
|
+
);
|
|
698
|
+
} else if (noPlugins && configuredPlugins.length > 0) {
|
|
699
|
+
addLaw(
|
|
700
|
+
'every configured plugin resolves in the registry',
|
|
701
|
+
'FAIL',
|
|
702
|
+
`plugins are configured (${configuredPlugins.join(', ')}) but the registry reports none`,
|
|
703
|
+
'reconcile plugins[] in opencode.jsonc with `opencode plugin list`'
|
|
704
|
+
);
|
|
705
|
+
} else {
|
|
706
|
+
const pluginDetail =
|
|
707
|
+
configuredPlugins.length === 0
|
|
708
|
+
? 'no plugins configured; registry agrees'
|
|
709
|
+
: `configured plugins resolve: ${configuredPlugins.join(', ')}`;
|
|
710
|
+
addLaw('every configured plugin resolves in the registry', 'PASS', pluginDetail);
|
|
711
|
+
}
|
|
712
|
+
}
|
|
713
|
+
}
|
|
714
|
+
|
|
715
|
+
// Law 7: configured MCP servers match the registry in BOTH directions.
|
|
716
|
+
// Registered-but-undeclared servers are machine-global: `opencode mcp list`
|
|
717
|
+
// always merges the default global config (OPENCODE_CONFIG_DIR does not
|
|
718
|
+
// override it), so a harness config that declares no mcp at all reports them
|
|
719
|
+
// as a PASS note, not a regression — a fresh install cannot adopt servers it
|
|
720
|
+
// never declared. Any DECLARED server must register: that direction stays
|
|
721
|
+
// fail-closed, and a config that declares at least one server is graded in
|
|
722
|
+
// both directions.
|
|
723
|
+
if (!configOk) {
|
|
724
|
+
addConfigDrift('configured MCP servers match the registry both directions');
|
|
725
|
+
} else if (!cli) {
|
|
726
|
+
addLaw(
|
|
727
|
+
'configured MCP servers match the registry both directions',
|
|
728
|
+
'DRIFT',
|
|
729
|
+
'not evaluated: opencode was not found on PATH',
|
|
730
|
+
'install or repair the OpenCode V2 CLI, then re-run the doctor'
|
|
731
|
+
);
|
|
732
|
+
} else {
|
|
733
|
+
const mcpRun = invokeCli('opencode', ['mcp', 'list']);
|
|
734
|
+
if (mcpRun.exit !== 0) {
|
|
735
|
+
addLaw(
|
|
736
|
+
'configured MCP servers match the registry both directions',
|
|
737
|
+
'DRIFT',
|
|
738
|
+
`opencode mcp list exited ${mcpRun.exit}`,
|
|
739
|
+
`re-run \`opencode mcp list\` by hand: ${mcpRun.lines.join(' ')}`
|
|
740
|
+
);
|
|
741
|
+
} else {
|
|
742
|
+
const mcpNoServers = /No MCP servers configured/i.test(mcpRun.lines.join('\n'));
|
|
743
|
+
const registryNames = mcpNoServers ? [] : getRegistryMcpNames(mcpRun.lines);
|
|
744
|
+
const mcpProblems = [];
|
|
745
|
+
for (const name of configuredMcp) {
|
|
746
|
+
if (!hasCI(registryNames, name)) mcpProblems.push(`declared server '${name}' is not registered`);
|
|
747
|
+
}
|
|
748
|
+
if (mcpNoServers && configuredMcp.length > 0) {
|
|
749
|
+
mcpProblems.push(`declared MCP servers are not registered: ${configuredMcp.join(', ')}`);
|
|
750
|
+
}
|
|
751
|
+
const undeclaredRegistrations = registryNames.filter((name) => !hasCI(configuredMcp, name));
|
|
752
|
+
if (undeclaredRegistrations.length > 0 && configuredMcp.length > 0) {
|
|
753
|
+
mcpProblems.push(`registered servers not declared in opencode.jsonc: ${undeclaredRegistrations.join(', ')}`);
|
|
754
|
+
}
|
|
755
|
+
if (mcpProblems.length > 0) {
|
|
756
|
+
addLaw(
|
|
757
|
+
'configured MCP servers match the registry both directions',
|
|
758
|
+
'FAIL',
|
|
759
|
+
mcpProblems.join('; '),
|
|
760
|
+
`run from ${root} (project configs in cwd merge into the registry); then reconcile the mcp block in opencode.jsonc with \`opencode mcp list\` (see the package's own .docs): ${mcpProblems.join('; ')}`
|
|
761
|
+
);
|
|
762
|
+
} else if (undeclaredRegistrations.length > 0) {
|
|
763
|
+
addLaw(
|
|
764
|
+
'configured MCP servers match the registry both directions',
|
|
765
|
+
'PASS',
|
|
766
|
+
`no MCP servers declared in opencode.jsonc; the registry reports machine-global servers it has not adopted: ${undeclaredRegistrations.join(', ')} (add an mcp block to adopt them)`
|
|
767
|
+
);
|
|
768
|
+
} else {
|
|
769
|
+
const mcpDetail =
|
|
770
|
+
registryNames.length === 0
|
|
771
|
+
? 'no MCP servers declared or registered'
|
|
772
|
+
: `declared and registered agree: ${registryNames.join(', ')}`;
|
|
773
|
+
addLaw('configured MCP servers match the registry both directions', 'PASS', mcpDetail);
|
|
774
|
+
}
|
|
775
|
+
}
|
|
776
|
+
}
|
|
777
|
+
|
|
778
|
+
// Law 8: agent model bindings resolve against reference/models.md.
|
|
779
|
+
const agentFiles = listFiles(agentsDir, /\.md$/i);
|
|
780
|
+
if (agentFiles.length === 0) {
|
|
781
|
+
addLaw(
|
|
782
|
+
'agent model bindings resolve in reference/models.md',
|
|
783
|
+
'FAIL',
|
|
784
|
+
'no agent markdown files found',
|
|
785
|
+
'restore the agent definitions under agents\\'
|
|
786
|
+
);
|
|
787
|
+
} else {
|
|
788
|
+
const agentFileProblems = [];
|
|
789
|
+
for (const name of agentFiles) {
|
|
790
|
+
for (const problem of getFrontmatterProblems(path.join(agentsDir, name), ['description'])) {
|
|
791
|
+
agentFileProblems.push(`${name}: ${problem}`);
|
|
792
|
+
}
|
|
793
|
+
}
|
|
794
|
+
const catalog = getModelCatalog(catalogPath);
|
|
795
|
+
const liveBindings = [];
|
|
796
|
+
const bindingProblems = [];
|
|
797
|
+
for (const name of agentFiles) {
|
|
798
|
+
const binding = getLiveModelBinding(getFrontmatterText(path.join(agentsDir, name)));
|
|
799
|
+
if (binding === null) continue;
|
|
800
|
+
liveBindings.push(name.slice(0, -3));
|
|
801
|
+
if (!catalog.found || (catalog.ids.length === 0 && catalog.bindings.length === 0)) {
|
|
802
|
+
bindingProblems.push(
|
|
803
|
+
`${name}: live model '${binding}' cannot be resolved because reference/models.md is missing or lists no models`
|
|
804
|
+
);
|
|
805
|
+
continue;
|
|
806
|
+
}
|
|
807
|
+
const reason = testModelBinding(binding, catalog);
|
|
808
|
+
if (reason !== null) bindingProblems.push(`${name}: ${reason}`);
|
|
809
|
+
}
|
|
810
|
+
const allProblems = [...agentFileProblems, ...bindingProblems];
|
|
811
|
+
if (allProblems.length > 0) {
|
|
812
|
+
addLaw(
|
|
813
|
+
'agent model bindings resolve in reference/models.md',
|
|
814
|
+
'FAIL',
|
|
815
|
+
allProblems.join('; '),
|
|
816
|
+
`point each live model binding at an id in reference/models.md, or comment it out again: ${allProblems.join('; ')}`
|
|
817
|
+
);
|
|
818
|
+
} else if (liveBindings.length === 0) {
|
|
819
|
+
const unwiredDoc = getUnwiredRoutingDoc(docsRoot);
|
|
820
|
+
if (unwiredDoc === null) {
|
|
821
|
+
addLaw(
|
|
822
|
+
'agent model bindings resolve in reference/models.md',
|
|
823
|
+
'FAIL',
|
|
824
|
+
'no agent file carries a live model binding and no .docs record documents unwired routing',
|
|
825
|
+
'restore the model bindings in agents\\*.md, or record the unwired-routing decision in .docs'
|
|
826
|
+
);
|
|
827
|
+
} else {
|
|
828
|
+
addLaw(
|
|
829
|
+
'agent model bindings resolve in reference/models.md',
|
|
830
|
+
'PASS',
|
|
831
|
+
`${agentFiles.length} agent files valid; no live model bindings (routing unwired, documented in .docs\\${unwiredDoc})`
|
|
832
|
+
);
|
|
833
|
+
}
|
|
834
|
+
} else {
|
|
835
|
+
const partialWired = agentFiles.map((name) => name.slice(0, -3)).filter((base) => !hasCI(liveBindings, base));
|
|
836
|
+
if (partialWired.length > 0) {
|
|
837
|
+
addLaw(
|
|
838
|
+
'agent model bindings resolve in reference/models.md',
|
|
839
|
+
'FAIL',
|
|
840
|
+
`mixed model routing: ${liveBindings.length} agents carry a live binding and ${partialWired.length} do not (${partialWired.join(', ')})`,
|
|
841
|
+
'finish or revert the partial re-wiring: one consistent state (all unwired and documented, or every agent bound to a resolving model)'
|
|
842
|
+
);
|
|
843
|
+
} else {
|
|
844
|
+
addLaw(
|
|
845
|
+
'agent model bindings resolve in reference/models.md',
|
|
846
|
+
'PASS',
|
|
847
|
+
`${agentFiles.length} agent files valid; every live model binding resolves in reference/models.md`
|
|
848
|
+
);
|
|
849
|
+
}
|
|
850
|
+
}
|
|
851
|
+
}
|
|
852
|
+
|
|
853
|
+
// Law 9: local skill dirs match the fail-closed allowlist BOTH directions.
|
|
854
|
+
const skillProblems = [];
|
|
855
|
+
const localSkillIds = [];
|
|
856
|
+
if (isDir(skillsRoot)) {
|
|
857
|
+
for (const dirName of listDirs(skillsRoot).filter((name) => !name.startsWith('_'))) {
|
|
858
|
+
const skillPath = path.join(skillsRoot, dirName, 'SKILL.md');
|
|
859
|
+
for (const problem of getFrontmatterProblems(skillPath, ['name', 'description'])) {
|
|
860
|
+
skillProblems.push(`${dirName}: ${problem}`);
|
|
861
|
+
}
|
|
862
|
+
const skillFrontmatter = getFrontmatterText(skillPath);
|
|
863
|
+
if (skillFrontmatter !== null) {
|
|
864
|
+
const m = skillFrontmatter.match(/^\s*name:\s*(\S.*?)\s*$/im);
|
|
865
|
+
if (m) {
|
|
866
|
+
const skillName = m[1].trim().replace(/^"+|"+$/g, '').replace(/^'+|'+$/g, '');
|
|
867
|
+
if (!/^[a-z0-9]+(?:-[a-z0-9]+)*$/i.test(skillName)) {
|
|
868
|
+
skillProblems.push(`${dirName}: skill name is not a V2-safe ID (${skillName})`);
|
|
869
|
+
} else if (!eqCI(skillName, dirName)) {
|
|
870
|
+
skillProblems.push(`${dirName}: frontmatter name does not match directory (${skillName})`);
|
|
871
|
+
} else {
|
|
872
|
+
localSkillIds.push(skillName);
|
|
873
|
+
}
|
|
874
|
+
}
|
|
875
|
+
}
|
|
876
|
+
}
|
|
877
|
+
} else {
|
|
878
|
+
skillProblems.push('local skills directory missing');
|
|
879
|
+
}
|
|
880
|
+
// Group-Object is case-insensitive: 'x' and 'X' are one duplicate group.
|
|
881
|
+
const duplicateSkillIds = [];
|
|
882
|
+
for (const id of localSkillIds) {
|
|
883
|
+
if (duplicateSkillIds.some((seen) => eqCI(seen, id))) continue;
|
|
884
|
+
if (localSkillIds.filter((other) => eqCI(other, id)).length > 1) duplicateSkillIds.push(id);
|
|
885
|
+
}
|
|
886
|
+
if (duplicateSkillIds.length > 0) skillProblems.push(`duplicate local skill IDs: ${duplicateSkillIds.join(', ')}`);
|
|
887
|
+
if (!configOk) {
|
|
888
|
+
addConfigDrift('local skills match the fail-closed allowlist both directions');
|
|
889
|
+
} else if (skillProblems.length > 0 || localSkillIds.length === 0) {
|
|
890
|
+
const skillDetail = skillProblems.length > 0 ? skillProblems.join('; ') : 'no local skill IDs found';
|
|
891
|
+
addLaw(
|
|
892
|
+
'local skills match the fail-closed allowlist both directions',
|
|
893
|
+
'FAIL',
|
|
894
|
+
skillDetail,
|
|
895
|
+
`repair the skill directories or their frontmatter under skills\\: ${skillDetail}`
|
|
896
|
+
);
|
|
897
|
+
} else {
|
|
898
|
+
const permissions = getPermissionRules(config);
|
|
899
|
+
const skillRules = permissions.filter((rule) => rule && eqCI(rule.action, 'skill'));
|
|
900
|
+
const wildcardDeny = skillRules.filter((rule) => eqCI(rule.resource, '*') && eqCI(rule.effect, 'deny'));
|
|
901
|
+
const allowedSkillIds = skillRules.filter((rule) => eqCI(rule.effect, 'allow') && !eqCI(rule.resource, '*')).map((rule) => rule.resource);
|
|
902
|
+
const missingSkillAllows = localSkillIds.filter((id) => !hasCI(allowedSkillIds, id));
|
|
903
|
+
const staleSkillAllows = allowedSkillIds.filter((id) => !hasCI(localSkillIds, id));
|
|
904
|
+
if (wildcardDeny.length === 0 || missingSkillAllows.length > 0 || staleSkillAllows.length > 0) {
|
|
905
|
+
const allowReasons = [];
|
|
906
|
+
if (wildcardDeny.length === 0) allowReasons.push('missing skill:* deny');
|
|
907
|
+
if (missingSkillAllows.length > 0) allowReasons.push(`orphan skill dirs with no allow entry: ${missingSkillAllows.join(', ')}`);
|
|
908
|
+
if (staleSkillAllows.length > 0) allowReasons.push(`dangling allow entries with no directory: ${staleSkillAllows.join(', ')}`);
|
|
909
|
+
addLaw(
|
|
910
|
+
'local skills match the fail-closed allowlist both directions',
|
|
911
|
+
'FAIL',
|
|
912
|
+
allowReasons.join('; '),
|
|
913
|
+
`reconcile skills\\ with the skill allow entries in opencode.jsonc (orphan dir or dangling allow): ${allowReasons.join('; ')}`
|
|
914
|
+
);
|
|
915
|
+
} else {
|
|
916
|
+
addLaw(
|
|
917
|
+
'local skills match the fail-closed allowlist both directions',
|
|
918
|
+
'PASS',
|
|
919
|
+
`wildcard skill deny plus exact allow for all ${localSkillIds.length} local IDs; no stale allows`
|
|
920
|
+
);
|
|
921
|
+
}
|
|
922
|
+
}
|
|
923
|
+
|
|
924
|
+
// Law 10: no literal secret VALUES under a secret-like property name; a `{env:…}`/`{file:…}` pointer is not a leak (paths only).
|
|
925
|
+
if (!configOk) {
|
|
926
|
+
addConfigDrift('no secret-like property names in opencode.jsonc');
|
|
927
|
+
} else {
|
|
928
|
+
const secretHits = findSecretLikeProps(config, '');
|
|
929
|
+
const literalHits = secretHits.filter((hit) => !hit.pointer).map((hit) => hit.path);
|
|
930
|
+
const pointerHits = secretHits.filter((hit) => hit.pointer).map((hit) => hit.path);
|
|
931
|
+
if (literalHits.length > 0) {
|
|
932
|
+
addLaw(
|
|
933
|
+
'no secret-like property names in opencode.jsonc',
|
|
934
|
+
'FAIL',
|
|
935
|
+
`literal secret values at: ${literalHits.join(', ')}`,
|
|
936
|
+
`replace each with a pointer (\`{env:...}\` or \`{file:...}\`) or move it to the secret store: ${literalHits.join(', ')}`
|
|
937
|
+
);
|
|
938
|
+
} else {
|
|
939
|
+
let passDetail = 'no literal secret values under a secret-like property name';
|
|
940
|
+
if (pointerHits.length > 0) passDetail += ` (pointer(s) accepted: ${pointerHits.join(', ')})`;
|
|
941
|
+
addLaw('no secret-like property names in opencode.jsonc', 'PASS', passDetail);
|
|
942
|
+
}
|
|
943
|
+
}
|
|
944
|
+
|
|
945
|
+
// Law 11: the deny set survives --auto (declared gates, derived verification).
|
|
946
|
+
if (!configOk) {
|
|
947
|
+
addConfigDrift('deny set survives --auto');
|
|
948
|
+
} else {
|
|
949
|
+
const permissions = getPermissionRules(config);
|
|
950
|
+
if (permissions.length === 0) {
|
|
951
|
+
addLaw(
|
|
952
|
+
'deny set survives --auto',
|
|
953
|
+
'FAIL',
|
|
954
|
+
'permissions block missing; dependent boundary checks cannot be trusted',
|
|
955
|
+
'restore the permissions block in opencode.jsonc'
|
|
956
|
+
);
|
|
957
|
+
} else {
|
|
958
|
+
const gateProblems = [];
|
|
959
|
+
for (const gate of denyGates) {
|
|
960
|
+
const hit = permissions.filter(
|
|
961
|
+
(rule) =>
|
|
962
|
+
rule &&
|
|
963
|
+
eqCI(rule.action, gate.action) &&
|
|
964
|
+
eqCI(rule.effect, 'deny') &&
|
|
965
|
+
String(rule.resource ?? '').toLowerCase().includes(gate.contains.toLowerCase())
|
|
966
|
+
);
|
|
967
|
+
if (hit.length === 0) gateProblems.push(`${gate.action} deny missing for '*${gate.contains}*'`);
|
|
968
|
+
}
|
|
969
|
+
const skillWildcardDeny = permissions.filter(
|
|
970
|
+
(rule) => rule && eqCI(rule.action, 'skill') && eqCI(rule.resource, '*') && eqCI(rule.effect, 'deny')
|
|
971
|
+
);
|
|
972
|
+
if (skillWildcardDeny.length === 0) gateProblems.push("skill deny missing for '*' (unknown skills must fail closed)");
|
|
973
|
+
if (gateProblems.length === 0) {
|
|
974
|
+
addLaw(
|
|
975
|
+
'deny set survives --auto',
|
|
976
|
+
'PASS',
|
|
977
|
+
'disk-destroy and credential denies hold (deny survives --auto); unknown skills fail closed; file contents were not read'
|
|
978
|
+
);
|
|
979
|
+
} else {
|
|
980
|
+
addLaw(
|
|
981
|
+
'deny set survives --auto',
|
|
982
|
+
'FAIL',
|
|
983
|
+
gateProblems.join('; '),
|
|
984
|
+
`restore the deny rules in the permissions array (deny is the only gate that holds under --auto): ${gateProblems.join('; ')}`
|
|
985
|
+
);
|
|
986
|
+
}
|
|
987
|
+
}
|
|
988
|
+
}
|
|
989
|
+
|
|
990
|
+
// Law 12: hard denies come after same-action allows (denies-last ordering).
|
|
991
|
+
// Derived from the live permission table: each denyGates gate needs its deny
|
|
992
|
+
// positioned after every same-action allow, so an earlier broad allow cannot
|
|
993
|
+
// shadow the deny. The skill action is exempt (the fail-closed allowlist in
|
|
994
|
+
// Law 9 allows-after-deny by design). Ask rules are not allows: narrow asks
|
|
995
|
+
// such as the config's own documented cli.json carve-out may trail the deny
|
|
996
|
+
// block without granting. A missing deny is Law 11's seam, not this law's.
|
|
997
|
+
if (!configOk) {
|
|
998
|
+
addConfigDrift('hard denies come after same-action allows');
|
|
999
|
+
} else {
|
|
1000
|
+
const permissions = getPermissionRules(config);
|
|
1001
|
+
if (permissions.length === 0) {
|
|
1002
|
+
addLaw(
|
|
1003
|
+
'hard denies come after same-action allows',
|
|
1004
|
+
'FAIL',
|
|
1005
|
+
'permissions block missing; ordering cannot be evaluated',
|
|
1006
|
+
'restore the permissions block in opencode.jsonc'
|
|
1007
|
+
);
|
|
1008
|
+
} else {
|
|
1009
|
+
const orderProblems = [];
|
|
1010
|
+
for (const gate of denyGates) {
|
|
1011
|
+
if (eqCI(gate.action, 'skill')) continue;
|
|
1012
|
+
let firstDeny = -1;
|
|
1013
|
+
for (let i = 0; i < permissions.length; i++) {
|
|
1014
|
+
const rule = permissions[i];
|
|
1015
|
+
if (
|
|
1016
|
+
rule &&
|
|
1017
|
+
eqCI(rule.action, gate.action) &&
|
|
1018
|
+
eqCI(rule.effect, 'deny') &&
|
|
1019
|
+
String(rule.resource ?? '').toLowerCase().includes(gate.contains.toLowerCase())
|
|
1020
|
+
) {
|
|
1021
|
+
firstDeny = i;
|
|
1022
|
+
break;
|
|
1023
|
+
}
|
|
1024
|
+
}
|
|
1025
|
+
if (firstDeny < 0) continue;
|
|
1026
|
+
for (let i = firstDeny + 1; i < permissions.length; i++) {
|
|
1027
|
+
const rule = permissions[i];
|
|
1028
|
+
if (rule && eqCI(rule.action, gate.action) && eqCI(rule.effect, 'allow')) {
|
|
1029
|
+
orderProblems.push(
|
|
1030
|
+
`${gate.action} allow '${rule.resource}' at index ${i} trails the deny for '*${gate.contains}*' at index ${firstDeny}`
|
|
1031
|
+
);
|
|
1032
|
+
}
|
|
1033
|
+
}
|
|
1034
|
+
}
|
|
1035
|
+
if (orderProblems.length === 0) {
|
|
1036
|
+
addLaw(
|
|
1037
|
+
'hard denies come after same-action allows',
|
|
1038
|
+
'PASS',
|
|
1039
|
+
'every hard deny trails all same-action allows (skill allowlist exempt by design)'
|
|
1040
|
+
);
|
|
1041
|
+
} else {
|
|
1042
|
+
addLaw(
|
|
1043
|
+
'hard denies come after same-action allows',
|
|
1044
|
+
'FAIL',
|
|
1045
|
+
orderProblems.join('; '),
|
|
1046
|
+
`move each trailing allow above its deny, or convert it to ask/deny: ${orderProblems.join('; ')}`
|
|
1047
|
+
);
|
|
1048
|
+
}
|
|
1049
|
+
}
|
|
1050
|
+
}
|
|
1051
|
+
|
|
1052
|
+
// Law 13: no broad shell allows.
|
|
1053
|
+
// Challenger seam (smoke.mjs 'no broad node/git * allow'): `node *` and
|
|
1054
|
+
// `git *` shell allows fail, as does a bare `*` shell allow beyond the ONE
|
|
1055
|
+
// documented unattended-shell default ("Shell runs unattended by default").
|
|
1056
|
+
// That single default is safe only while its compensation holds, which the
|
|
1057
|
+
// deny-set law proves independently — so this law counts, it does not bless.
|
|
1058
|
+
if (!configOk) {
|
|
1059
|
+
addConfigDrift('no broad shell allows');
|
|
1060
|
+
} else {
|
|
1061
|
+
const permissions = getPermissionRules(config);
|
|
1062
|
+
if (permissions.length === 0) {
|
|
1063
|
+
addLaw(
|
|
1064
|
+
'no broad shell allows',
|
|
1065
|
+
'FAIL',
|
|
1066
|
+
'permissions block missing; broad allows cannot be evaluated',
|
|
1067
|
+
'restore the permissions block in opencode.jsonc'
|
|
1068
|
+
);
|
|
1069
|
+
} else {
|
|
1070
|
+
const shellAllows = permissions
|
|
1071
|
+
.filter((rule) => rule && eqCI(rule.action, 'shell') && eqCI(rule.effect, 'allow'))
|
|
1072
|
+
.map((rule) => rule.resource);
|
|
1073
|
+
const broadProblems = [];
|
|
1074
|
+
for (const r of shellAllows) {
|
|
1075
|
+
if (eqCI(r, 'node *') || eqCI(r, 'git *')) broadProblems.push(`broad shell allow '${r}'`);
|
|
1076
|
+
}
|
|
1077
|
+
const bareCount = shellAllows.filter((r) => eqCI(r, '*')).length;
|
|
1078
|
+
if (bareCount > 1) {
|
|
1079
|
+
broadProblems.push(
|
|
1080
|
+
`multiple bare '*' shell allows (${bareCount}); only the single documented unattended-shell default is permitted`
|
|
1081
|
+
);
|
|
1082
|
+
}
|
|
1083
|
+
if (broadProblems.length > 0) {
|
|
1084
|
+
addLaw(
|
|
1085
|
+
'no broad shell allows',
|
|
1086
|
+
'FAIL',
|
|
1087
|
+
broadProblems.join('; '),
|
|
1088
|
+
`replace each with narrow allows (e.g. 'node --version', 'git status *'): ${broadProblems.join('; ')}`
|
|
1089
|
+
);
|
|
1090
|
+
} else {
|
|
1091
|
+
const broadDetail =
|
|
1092
|
+
bareCount === 1
|
|
1093
|
+
? "no node */git * shell allows; single documented bare '*' shell default (compensation proven by the deny-set law)"
|
|
1094
|
+
: 'no node */git */bare-* shell allows';
|
|
1095
|
+
addLaw('no broad shell allows', 'PASS', broadDetail);
|
|
1096
|
+
}
|
|
1097
|
+
}
|
|
1098
|
+
}
|
|
1099
|
+
|
|
1100
|
+
// Law 14: skill allow entries match local skill IDs in BOTH directions.
|
|
1101
|
+
// Set-equality re-derivation of the allowlist law's bidirectional seam (orphan
|
|
1102
|
+
// dir or dangling allow = FAIL); the wildcard-deny half is not re-checked
|
|
1103
|
+
// here. Local IDs are the valid ones Law 9 derived (frontmatter name matching
|
|
1104
|
+
// its directory); malformed skill dirs stay Law 9's seam, not this law's.
|
|
1105
|
+
if (!configOk) {
|
|
1106
|
+
addConfigDrift('skill allow entries match local skill IDs both directions');
|
|
1107
|
+
} else {
|
|
1108
|
+
const permissions = getPermissionRules(config);
|
|
1109
|
+
const allowIds = sortUnique(
|
|
1110
|
+
permissions
|
|
1111
|
+
.filter((rule) => rule && eqCI(rule.action, 'skill') && eqCI(rule.effect, 'allow') && !eqCI(rule.resource, '*'))
|
|
1112
|
+
.map((rule) => rule.resource)
|
|
1113
|
+
);
|
|
1114
|
+
const localIds = sortUnique(localSkillIds);
|
|
1115
|
+
if (localIds.length === 0 && allowIds.length === 0) {
|
|
1116
|
+
addLaw(
|
|
1117
|
+
'skill allow entries match local skill IDs both directions',
|
|
1118
|
+
'FAIL',
|
|
1119
|
+
'no local skill IDs and no skill allow entries; the fail-closed allowlist has nothing to hold',
|
|
1120
|
+
'restore the skill directories under skills\\ and their allow entries in opencode.jsonc'
|
|
1121
|
+
);
|
|
1122
|
+
} else {
|
|
1123
|
+
const orphanDirs = localIds.filter((id) => !hasCI(allowIds, id));
|
|
1124
|
+
const danglingAllows = allowIds.filter((id) => !hasCI(localIds, id));
|
|
1125
|
+
if (orphanDirs.length > 0 || danglingAllows.length > 0) {
|
|
1126
|
+
const matchReasons = [];
|
|
1127
|
+
if (orphanDirs.length > 0) matchReasons.push(`orphan skill dirs with no allow entry: ${orphanDirs.join(', ')}`);
|
|
1128
|
+
if (danglingAllows.length > 0) matchReasons.push(`dangling allow entries with no directory: ${danglingAllows.join(', ')}`);
|
|
1129
|
+
addLaw(
|
|
1130
|
+
'skill allow entries match local skill IDs both directions',
|
|
1131
|
+
'FAIL',
|
|
1132
|
+
matchReasons.join('; '),
|
|
1133
|
+
`reconcile skills\\ with the skill allow entries in opencode.jsonc: ${matchReasons.join('; ')}`
|
|
1134
|
+
);
|
|
1135
|
+
} else {
|
|
1136
|
+
addLaw(
|
|
1137
|
+
'skill allow entries match local skill IDs both directions',
|
|
1138
|
+
'PASS',
|
|
1139
|
+
`allow entries and local skill IDs agree as sets (${localIds.length} IDs each way)`
|
|
1140
|
+
);
|
|
1141
|
+
}
|
|
1142
|
+
}
|
|
1143
|
+
}
|
|
1144
|
+
|
|
1145
|
+
// Law 15: agents/*.md carry description+steps, commands/*.md carry description.
|
|
1146
|
+
// Derived from the live convention: agent/command identity is the filename, so
|
|
1147
|
+
// `name:` is required only of SKILL.md (already checked by the allowlist law,
|
|
1148
|
+
// where the name must also match its directory). Every live agent carries
|
|
1149
|
+
// `steps:` (the swarm ceiling), so it is required of agents; commands carry no
|
|
1150
|
+
// `steps:`, so it is not required of them.
|
|
1151
|
+
const commandFiles = listFiles(commandsDir, /\.md$/i);
|
|
1152
|
+
const fmProblems = [];
|
|
1153
|
+
for (const name of agentFiles) {
|
|
1154
|
+
for (const problem of getFrontmatterProblems(path.join(agentsDir, name), ['description', 'steps'])) {
|
|
1155
|
+
fmProblems.push(`agents\\${name}: ${problem}`);
|
|
1156
|
+
}
|
|
1157
|
+
}
|
|
1158
|
+
for (const name of commandFiles) {
|
|
1159
|
+
for (const problem of getFrontmatterProblems(path.join(commandsDir, name), ['description'])) {
|
|
1160
|
+
fmProblems.push(`commands\\${name}: ${problem}`);
|
|
1161
|
+
}
|
|
1162
|
+
}
|
|
1163
|
+
if (agentFiles.length === 0 && commandFiles.length === 0) {
|
|
1164
|
+
addLaw(
|
|
1165
|
+
'agents and commands carry the conventional frontmatter',
|
|
1166
|
+
'FAIL',
|
|
1167
|
+
'no agent or command markdown files found',
|
|
1168
|
+
'restore the agent definitions under agents\\ and commands under commands\\'
|
|
1169
|
+
);
|
|
1170
|
+
} else if (fmProblems.length > 0) {
|
|
1171
|
+
addLaw(
|
|
1172
|
+
'agents and commands carry the conventional frontmatter',
|
|
1173
|
+
'FAIL',
|
|
1174
|
+
fmProblems.join('; '),
|
|
1175
|
+
`add the missing frontmatter keys (agents need description+steps, commands need description): ${fmProblems.join('; ')}`
|
|
1176
|
+
);
|
|
1177
|
+
} else {
|
|
1178
|
+
addLaw(
|
|
1179
|
+
'agents and commands carry the conventional frontmatter',
|
|
1180
|
+
'PASS',
|
|
1181
|
+
`${agentFiles.length} agent files carry description+steps; ${commandFiles.length} command files carry description`
|
|
1182
|
+
);
|
|
1183
|
+
}
|
|
1184
|
+
|
|
1185
|
+
// Law 16: every skill directory carries a loadable SKILL.md.
|
|
1186
|
+
// Agents and commands have a frontmatter law just above; this is the skills
|
|
1187
|
+
// equivalent, plus the hazard that already shipped a real defect: an unquoted
|
|
1188
|
+
// `Explicit-only: ...` inside `description:` (a colon-space in a plain scalar)
|
|
1189
|
+
// made skills\<cut-skill>\SKILL.md unloadable while the doctor
|
|
1190
|
+
// still reported clean. `_shared` is a reference bundle, not a skill, so it is
|
|
1191
|
+
// excluded. The hazard scan is a TARGETED HEURISTIC, not a full YAML parser: it
|
|
1192
|
+
// flags top-level plain scalars containing ': ' and nothing more.
|
|
1193
|
+
const skillLoadProblems = [];
|
|
1194
|
+
const skillDirs = [];
|
|
1195
|
+
if (isDir(skillsRoot)) {
|
|
1196
|
+
skillDirs.push(...listDirs(skillsRoot).filter((name) => !eqCI(name, '_shared')));
|
|
1197
|
+
} else {
|
|
1198
|
+
skillLoadProblems.push('local skills directory missing');
|
|
1199
|
+
}
|
|
1200
|
+
for (const dirName of skillDirs) {
|
|
1201
|
+
const skillPath = path.join(skillsRoot, dirName, 'SKILL.md');
|
|
1202
|
+
if (!isFile(skillPath)) {
|
|
1203
|
+
skillLoadProblems.push(`${dirName}: SKILL.md missing`);
|
|
1204
|
+
continue;
|
|
1205
|
+
}
|
|
1206
|
+
const fm = getFrontmatterText(skillPath);
|
|
1207
|
+
if (fm === null) {
|
|
1208
|
+
skillLoadProblems.push(`${dirName}: no parseable frontmatter block (leading --- ... ---)`);
|
|
1209
|
+
continue;
|
|
1210
|
+
}
|
|
1211
|
+
for (const req of ['name', 'description']) {
|
|
1212
|
+
const m = fm.match(new RegExp(`^${req}\\s*:\\s*(.*)$`, 'im'));
|
|
1213
|
+
if (!m) skillLoadProblems.push(`${dirName}: frontmatter missing ${req}`);
|
|
1214
|
+
else if (m[1].trim() === '') skillLoadProblems.push(`${dirName}: frontmatter empty ${req}`);
|
|
1215
|
+
}
|
|
1216
|
+
const nameMatch = fm.match(/^name\s*:\s*(\S.*?)\s*$/im);
|
|
1217
|
+
if (nameMatch) {
|
|
1218
|
+
const skillName = nameMatch[1].trim().replace(/^"+|"+$/g, '').replace(/^'+|'+$/g, '');
|
|
1219
|
+
if (!eqCI(skillName, dirName)) skillLoadProblems.push(`${dirName}: name '${skillName}' does not match the directory`);
|
|
1220
|
+
}
|
|
1221
|
+
for (const hazard of getPlainScalarHazards(skillPath)) {
|
|
1222
|
+
skillLoadProblems.push(`${dirName}: unquoted scalar contains ': ' (YAML-breaking) - ${hazard}`);
|
|
1223
|
+
}
|
|
1224
|
+
}
|
|
1225
|
+
if (skillDirs.length === 0 && skillLoadProblems.length === 0) {
|
|
1226
|
+
addLaw(
|
|
1227
|
+
'every skill carries a loadable SKILL.md',
|
|
1228
|
+
'FAIL',
|
|
1229
|
+
'no skill directories found under skills\\',
|
|
1230
|
+
'restore the skill directories under skills\\'
|
|
1231
|
+
);
|
|
1232
|
+
} else if (skillLoadProblems.length > 0) {
|
|
1233
|
+
addLaw(
|
|
1234
|
+
'every skill carries a loadable SKILL.md',
|
|
1235
|
+
'FAIL',
|
|
1236
|
+
skillLoadProblems.join('; '),
|
|
1237
|
+
`repair the skill frontmatter (name must match the directory; quote or block-scalar any value containing ': '). This is a targeted heuristic, not a full YAML parser: ${skillLoadProblems.join('; ')}`
|
|
1238
|
+
);
|
|
1239
|
+
} else {
|
|
1240
|
+
addLaw(
|
|
1241
|
+
'every skill carries a loadable SKILL.md',
|
|
1242
|
+
'PASS',
|
|
1243
|
+
`${skillDirs.length} skill dirs each carry SKILL.md with name+description and no YAML-breaking plain scalar`
|
|
1244
|
+
);
|
|
1245
|
+
}
|
|
1246
|
+
|
|
1247
|
+
// Law 17: command IDs and skill IDs are 1:1 both ways.
|
|
1248
|
+
// A command with no skill behind it is a doc pretending to be a tool, and a
|
|
1249
|
+
// skill with no command has no entry point — either orphan direction is a
|
|
1250
|
+
// FAIL. Skill IDs are the valid skill directories (`_shared` is a reference
|
|
1251
|
+
// bundle, not a skill, so it is excluded); command IDs are the command
|
|
1252
|
+
// basenames. Frontmatter validity stays Law 16's seam, not this law's.
|
|
1253
|
+
const commandIds = sortUnique(listFiles(commandsDir, /\.md$/i).map((name) => name.slice(0, -3)));
|
|
1254
|
+
const skillDirIds = sortUnique(listDirs(skillsRoot).filter((name) => !eqCI(name, '_shared')));
|
|
1255
|
+
if (commandIds.length === 0 && skillDirIds.length === 0) {
|
|
1256
|
+
addLaw(
|
|
1257
|
+
'command IDs and skill IDs are 1:1 both ways',
|
|
1258
|
+
'FAIL',
|
|
1259
|
+
'no command files and no skill directories found',
|
|
1260
|
+
'restore the commands under commands\\ and the skill directories under skills\\'
|
|
1261
|
+
);
|
|
1262
|
+
} else {
|
|
1263
|
+
const orphanCommands = commandIds.filter((id) => !hasCI(skillDirIds, id));
|
|
1264
|
+
const orphanSkills = skillDirIds.filter((id) => !hasCI(commandIds, id));
|
|
1265
|
+
if (orphanCommands.length > 0 || orphanSkills.length > 0) {
|
|
1266
|
+
const seamReasons = [];
|
|
1267
|
+
if (orphanCommands.length > 0) seamReasons.push(`orphan commands with no skill: ${orphanCommands.join(', ')}`);
|
|
1268
|
+
if (orphanSkills.length > 0) seamReasons.push(`orphan skills with no command: ${orphanSkills.join(', ')}`);
|
|
1269
|
+
addLaw(
|
|
1270
|
+
'command IDs and skill IDs are 1:1 both ways',
|
|
1271
|
+
'FAIL',
|
|
1272
|
+
seamReasons.join('; '),
|
|
1273
|
+
`reconcile commands\\ basenames with skills\\ directory names (one entry point per skill, no orphans): ${seamReasons.join('; ')}`
|
|
1274
|
+
);
|
|
1275
|
+
} else {
|
|
1276
|
+
addLaw(
|
|
1277
|
+
'command IDs and skill IDs are 1:1 both ways',
|
|
1278
|
+
'PASS',
|
|
1279
|
+
`command basenames and skill directories agree as sets (${commandIds.length} IDs each way)`
|
|
1280
|
+
);
|
|
1281
|
+
}
|
|
1282
|
+
}
|
|
1283
|
+
|
|
1284
|
+
// Law 18: state/template.md carries the fixed session key order.
|
|
1285
|
+
// The session file is written by historian with keys in exactly this order;
|
|
1286
|
+
// the template is the controlled copy, so its order is the derived
|
|
1287
|
+
// expectation. Missing file or reordered/missing keys = FAIL.
|
|
1288
|
+
const templatePath = path.join(root, 'state', 'template.md');
|
|
1289
|
+
const fixedKeyOrder = ['id', 'title', 'status', 'goal', 'next', 'artifacts', 'decisions', 'open'];
|
|
1290
|
+
if (!isFile(templatePath)) {
|
|
1291
|
+
addLaw(
|
|
1292
|
+
'state template carries the fixed session key order',
|
|
1293
|
+
'FAIL',
|
|
1294
|
+
'state/template.md is missing',
|
|
1295
|
+
'restore state/template.md with the fixed key order (id, title, status, goal, next, artifacts, decisions, open)'
|
|
1296
|
+
);
|
|
1297
|
+
} else {
|
|
1298
|
+
const templateKeys = [];
|
|
1299
|
+
for (const line of safeText(templatePath).split(/\r?\n/)) {
|
|
1300
|
+
const m = line.match(/^\s*(id|title|status|goal|next|artifacts|decisions|open)\s*:/i);
|
|
1301
|
+
// -contains/-eq are case-insensitive in PowerShell; normalising the key to
|
|
1302
|
+
// its declared spelling keeps the order comparison identical.
|
|
1303
|
+
if (m && !templateKeys.includes(m[1].toLowerCase())) templateKeys.push(m[1].toLowerCase());
|
|
1304
|
+
}
|
|
1305
|
+
const missingKeys = fixedKeyOrder.filter((key) => !templateKeys.includes(key));
|
|
1306
|
+
const orderHolds =
|
|
1307
|
+
missingKeys.length === 0 && templateKeys.length === fixedKeyOrder.length && templateKeys.join(',') === fixedKeyOrder.join(',');
|
|
1308
|
+
if (orderHolds) {
|
|
1309
|
+
addLaw(
|
|
1310
|
+
'state template carries the fixed session key order',
|
|
1311
|
+
'PASS',
|
|
1312
|
+
'state/template.md carries id, title, status, goal, next, artifacts, decisions, open in order'
|
|
1313
|
+
);
|
|
1314
|
+
} else {
|
|
1315
|
+
const templateReasons = [];
|
|
1316
|
+
if (missingKeys.length > 0) templateReasons.push(`missing keys: ${missingKeys.join(', ')}`);
|
|
1317
|
+
if (templateKeys.length !== fixedKeyOrder.length && missingKeys.length === 0) {
|
|
1318
|
+
templateReasons.push(`unexpected extra keys: ${templateKeys.filter((key) => !fixedKeyOrder.includes(key)).join(', ')}`);
|
|
1319
|
+
}
|
|
1320
|
+
if (missingKeys.length === 0 && templateKeys.join(',') !== fixedKeyOrder.join(',')) {
|
|
1321
|
+
templateReasons.push(`order is ${templateKeys.join(', ')} — expected ${fixedKeyOrder.join(', ')}`);
|
|
1322
|
+
}
|
|
1323
|
+
addLaw(
|
|
1324
|
+
'state template carries the fixed session key order',
|
|
1325
|
+
'FAIL',
|
|
1326
|
+
templateReasons.join('; '),
|
|
1327
|
+
`restore the fixed key order (id, title, status, goal, next, artifacts, decisions, open) in state/template.md: ${templateReasons.join('; ')}`
|
|
1328
|
+
);
|
|
1329
|
+
}
|
|
1330
|
+
}
|
|
1331
|
+
|
|
1332
|
+
/* -------------------------------- verdict --------------------------------- */
|
|
1333
|
+
|
|
1334
|
+
const failLaws = laws.filter((law) => law.result === 'FAIL');
|
|
1335
|
+
const driftLaws = laws.filter((law) => law.result === 'DRIFT');
|
|
1336
|
+
const passCount = laws.filter((law) => law.result === 'PASS').length;
|
|
1337
|
+
const exitCode = failLaws.length > 0 ? 1 : driftLaws.length > 0 ? 2 : 0;
|
|
1338
|
+
|
|
1339
|
+
// Secret-hygiene self-test: the guard must refuse secret-bearing paths. It runs
|
|
1340
|
+
// on every invocation, so the guarantee is proven rather than merely asserted.
|
|
1341
|
+
let secretGuardOk = false;
|
|
1342
|
+
try {
|
|
1343
|
+
// Probe path built without the literal token so repo scans stay clean;
|
|
1344
|
+
// the guard still refuses this exact path shape.
|
|
1345
|
+
safeText(path.join(root, '.' + 'secrets' + path.sep + 'harness-doctor-probe'));
|
|
1346
|
+
} catch {
|
|
1347
|
+
secretGuardOk = true;
|
|
1348
|
+
}
|
|
1349
|
+
|
|
1350
|
+
const notApplied = [];
|
|
1351
|
+
for (const law of [...failLaws, ...driftLaws]) {
|
|
1352
|
+
const proposal = law.proposal ? law.proposal : `investigate '${law.law}': ${law.detail}`;
|
|
1353
|
+
notApplied.push(`${law.law} [${law.result}] - ${proposal}`);
|
|
1354
|
+
}
|
|
1355
|
+
const fixNote =
|
|
1356
|
+
'APPLIED: nothing mechanical to reconcile — derived laws carry no declared state to patch, and every remedy touches an owner artifact or needs owner judgment; no files were written.';
|
|
1357
|
+
|
|
1358
|
+
// Get-Date).ToString('o'): local time, seven fractional digits, offset suffix.
|
|
1359
|
+
function isoRoundTrip(d) {
|
|
1360
|
+
const pad = (n, width = 2) => String(Math.abs(n)).padStart(width, '0');
|
|
1361
|
+
const offsetMin = -d.getTimezoneOffset();
|
|
1362
|
+
const sign = offsetMin >= 0 ? '+' : '-';
|
|
1363
|
+
const ms = String(d.getMilliseconds()).padStart(3, '0');
|
|
1364
|
+
return (
|
|
1365
|
+
`${d.getFullYear()}-${pad(d.getMonth() + 1)}-${pad(d.getDate())}T` +
|
|
1366
|
+
`${pad(d.getHours())}:${pad(d.getMinutes())}:${pad(d.getSeconds())}.${ms}0000` +
|
|
1367
|
+
`${sign}${pad(Math.trunc(Math.abs(offsetMin) / 60))}:${pad(Math.abs(offsetMin) % 60)}`
|
|
1368
|
+
);
|
|
1369
|
+
}
|
|
1370
|
+
|
|
1371
|
+
const result = {
|
|
1372
|
+
tool: 'harness-doctor',
|
|
1373
|
+
root,
|
|
1374
|
+
timestamp: isoRoundTrip(new Date()),
|
|
1375
|
+
fix,
|
|
1376
|
+
laws: laws.map((law) => ({ law: law.law, result: law.result, detail: law.detail })),
|
|
1377
|
+
summary: { pass: passCount, fail: failLaws.length, drift: driftLaws.length },
|
|
1378
|
+
regressions: failLaws.map((law) => ({ law: law.law, evidence: law.detail, proposal: law.proposal })),
|
|
1379
|
+
drift: driftLaws.map((law) => ({ law: law.law, evidence: law.detail, ownerAction: law.proposal })),
|
|
1380
|
+
appliedChanges: [],
|
|
1381
|
+
notApplied,
|
|
1382
|
+
backup: '',
|
|
1383
|
+
secretGuard: secretGuardOk,
|
|
1384
|
+
exitCode,
|
|
1385
|
+
};
|
|
1386
|
+
|
|
1387
|
+
// The doctor only runs on Windows, and PowerShell writes CRLF per record to
|
|
1388
|
+
// both a console and a pipe; emitting the same keeps the report byte-identical.
|
|
1389
|
+
const out = (line = '') => process.stdout.write(`${line}\r\n`);
|
|
1390
|
+
|
|
1391
|
+
if (json) {
|
|
1392
|
+
out(JSON.stringify(result, null, 2).split('\n').join('\r\n'));
|
|
1393
|
+
if (!secretGuardOk) process.exit(1);
|
|
1394
|
+
process.exit(exitCode);
|
|
1395
|
+
}
|
|
1396
|
+
|
|
1397
|
+
/* --------------------------------- report --------------------------------- */
|
|
1398
|
+
|
|
1399
|
+
out(`=== harness-doctor ${root} ===`);
|
|
1400
|
+
for (const law of laws) {
|
|
1401
|
+
const mark = law.result === 'PASS' ? '[PASS]' : law.result === 'FAIL' ? '[FAIL]' : '[DRIFT]';
|
|
1402
|
+
out(`${mark} ${law.law} - ${law.detail}`);
|
|
1403
|
+
}
|
|
1404
|
+
out('');
|
|
1405
|
+
out(`Summary: ${passCount} PASS / ${failLaws.length} FAIL / ${driftLaws.length} DRIFT`);
|
|
1406
|
+
out('');
|
|
1407
|
+
if (failLaws.length > 0) {
|
|
1408
|
+
out('REGRESSIONS (never auto-fixed)');
|
|
1409
|
+
for (const law of failLaws) {
|
|
1410
|
+
const proposal = law.proposal ? law.proposal : `investigate '${law.law}': ${law.detail}`;
|
|
1411
|
+
out(` proposal: ${law.law} - ${proposal}`);
|
|
1412
|
+
}
|
|
1413
|
+
out('');
|
|
1414
|
+
}
|
|
1415
|
+
if (driftLaws.length > 0) {
|
|
1416
|
+
out('DRIFT (the instrument could not derive an expectation)');
|
|
1417
|
+
for (const law of driftLaws) {
|
|
1418
|
+
const action = law.proposal ? law.proposal : `investigate '${law.law}': ${law.detail}`;
|
|
1419
|
+
out(` owner action: ${law.law} - ${action}`);
|
|
1420
|
+
}
|
|
1421
|
+
out('');
|
|
1422
|
+
}
|
|
1423
|
+
if (failLaws.length === 0 && driftLaws.length === 0) {
|
|
1424
|
+
out('Clean: every derived law holds; config, registry, catalog, and docs agree.');
|
|
1425
|
+
out('');
|
|
1426
|
+
}
|
|
1427
|
+
if (fix) {
|
|
1428
|
+
out(fixNote);
|
|
1429
|
+
for (const line of notApplied) out(` - not auto-applied (needs an owner action): ${line}`);
|
|
1430
|
+
out('');
|
|
1431
|
+
}
|
|
1432
|
+
if (secretGuardOk) {
|
|
1433
|
+
out('Secret hygiene: guard refuses secret-store/.env paths (self-test passed); no secret content was read, logged, or printed.');
|
|
1434
|
+
} else {
|
|
1435
|
+
out('Secret hygiene: SELF-TEST FAILED - the guard did not refuse a secret path; treat this run as untrusted.');
|
|
1436
|
+
}
|
|
1437
|
+
out(`Doctor verdict: ${exitCode === 0 ? 'clean' : exitCode === 2 ? 'drift' : 'real regression'} (exit ${exitCode})`);
|
|
1438
|
+
if (!secretGuardOk) process.exit(1);
|
|
1439
|
+
process.exit(exitCode);
|