@yeison.restrepo.r/code-conductor 1.43.0 → 1.45.0
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/README.md +36 -4
- package/bin/code-conductor.mjs +6 -3
- package/global/commands/cc-compact.md +1 -1
- package/global/commands/cc-stack.md +31 -1
- package/lib/installer/deploy.mjs +13 -1
- package/package.json +1 -1
- package/project-template/.claude/agents/audit.md +12 -3
- package/project-template/.claude/agents/plan.md +3 -3
- package/project-template/.claude/agents/spec.md +3 -3
- package/project-template/.claude/commands/cc-orchestrate.md +9 -6
- package/project-template/.claude/commands/cc-resume.md +16 -2
- package/project-template/.claude/hooks/pre-tool-use.mjs +21 -2
- package/project-template/.claude/review-loop.settings.json +1 -1
- package/project-template/.opencode/plugin/conductor-guard.js +157 -0
- package/scripts/adopt-claude-md.mjs +229 -0
- package/scripts/detect-stack.mjs +38 -17
- package/scripts/doc-locations.mjs +193 -0
- package/scripts/orchestrate.mjs +92 -12
- package/scripts/snap-build.mjs +42 -6
- package/scripts/snap-contract.mjs +3 -0
- package/scripts/snap-validate.mjs +2 -2
|
@@ -0,0 +1,193 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
// scripts/doc-locations.mjs
|
|
3
|
+
// Spec and plan location resolver (FEAT-047). Resolves the folder pair a run writes its
|
|
4
|
+
// spec and plan into: recorded in CLAUDE.md, else discovered, else docs/specs + docs/plans,
|
|
5
|
+
// and the backlog group the item's documents sit under. Zero dependencies, node: builtins only.
|
|
6
|
+
// orchestrate.mjs imports this module, so it has no top-level side effects, installs no
|
|
7
|
+
// process handler, writes nothing, and sets an exit code only from its CLI entry.
|
|
8
|
+
import { readFileSync, readdirSync, realpathSync, statSync } from 'node:fs';
|
|
9
|
+
import { isAbsolute, join, resolve } from 'node:path';
|
|
10
|
+
import { pathToFileURL } from 'node:url';
|
|
11
|
+
// Imported, not hardcoded: the spec derives DIR_MAX from this cap, and snap-contract.mjs is
|
|
12
|
+
// itself zero-dependency, so the import costs nothing and a cap change cannot drift.
|
|
13
|
+
import { V3_CAPS } from './snap-contract.mjs';
|
|
14
|
+
|
|
15
|
+
export const CANDIDATE_PAIRS = [
|
|
16
|
+
{ specs: '.claude/specs', plans: '.claude/plans' },
|
|
17
|
+
{ specs: 'docs/specs', plans: 'docs/plans' },
|
|
18
|
+
{ specs: 'docs/superpowers/specs', plans: 'docs/superpowers/plans' },
|
|
19
|
+
];
|
|
20
|
+
export const DEFAULT_PAIR = { specs: 'docs/specs', plans: 'docs/plans' };
|
|
21
|
+
export const GROUP_MAX = 47;
|
|
22
|
+
// A scope element is `<dir>/<group>/**`, so the folder leaves room for the longest group.
|
|
23
|
+
export const DIR_MAX = V3_CAPS['ops.scope'][1] - (GROUP_MAX + '/'.length + '/**'.length);
|
|
24
|
+
|
|
25
|
+
const CODE = 'ORCH_DOC_LOCATION_INVALID';
|
|
26
|
+
// A recorded folder becomes the spec and plan agents' Guard 5 write scope, so it may not cover
|
|
27
|
+
// the orchestrator write surface, git internals, or any folder that holds enforcement code
|
|
28
|
+
// (`.opencode` holds the OpenCode guard). Inside `.claude`, only specs and plans may hold
|
|
29
|
+
// documents: everything else there is agent instructions or configuration (skills, settings,
|
|
30
|
+
// rules), so the rule below it is an allowlist, not this deny list.
|
|
31
|
+
const RESERVED = ['.claude/memory', '.claude/hooks', '.claude/agents', '.claude/commands', '.claude/scripts', '.conductor', '.git', '.github', '.opencode', 'scripts'];
|
|
32
|
+
const CLAUDE_DOCS = ['.claude/specs', '.claude/plans'];
|
|
33
|
+
const GROUP_RE = /^(#{1,5})\s+(phase|epic|pillar)\b[\s:#-]*(\d+)?[\s:.-]*(.*)$/i;
|
|
34
|
+
const HEADING_RE = /^(#{1,6})\s/;
|
|
35
|
+
|
|
36
|
+
export class DocLocationError extends Error {
|
|
37
|
+
constructor(reason) {
|
|
38
|
+
super(`${CODE}: ${reason}`);
|
|
39
|
+
this.name = 'DocLocationError';
|
|
40
|
+
this.code = CODE;
|
|
41
|
+
this.reason = reason;
|
|
42
|
+
}
|
|
43
|
+
}
|
|
44
|
+
|
|
45
|
+
const stripSlash = (value) => value.replace(/\/+$/, '');
|
|
46
|
+
const underRoot = (value, base) => value === base || value.startsWith(`${base}/`);
|
|
47
|
+
const overlaps = (a, b) => a === b || a.startsWith(`${b}/`) || b.startsWith(`${a}/`);
|
|
48
|
+
|
|
49
|
+
// Case-folded because Windows and macOS file systems treat `.Claude/Hooks` as `.claude/hooks`.
|
|
50
|
+
function reservedReason(value) {
|
|
51
|
+
const folded = value.toLowerCase();
|
|
52
|
+
const base = RESERVED.find((entry) => overlaps(folded, entry));
|
|
53
|
+
if (base) {
|
|
54
|
+
if (underRoot(folded, base)) return `sits in the reserved \`${base}\``;
|
|
55
|
+
return `covers the reserved \`${base}\``;
|
|
56
|
+
}
|
|
57
|
+
if (underRoot(folded, '.claude') && !CLAUDE_DOCS.some((ok) => underRoot(folded, ok))) {
|
|
58
|
+
return 'sits in `.claude`, where only `.claude/specs` and `.claude/plans` may hold documents';
|
|
59
|
+
}
|
|
60
|
+
return '';
|
|
61
|
+
}
|
|
62
|
+
|
|
63
|
+
export function checkDocDir(rel) {
|
|
64
|
+
const value = stripSlash(String(rel ?? ''));
|
|
65
|
+
if (value === '' || value === '<command>') return 'is empty or the template placeholder';
|
|
66
|
+
if (isAbsolute(value) || /^[A-Za-z]:/.test(value) || value.startsWith('/')) return 'is absolute; use a path relative to the repository root';
|
|
67
|
+
if (value.split('/').includes('..')) return 'climbs out with a `..` segment';
|
|
68
|
+
if (value.includes('\\')) return 'uses `\\`; separate segments with `/`';
|
|
69
|
+
if (/[*?[\]{}]/.test(value)) return 'carries a glob character';
|
|
70
|
+
if (value === '.') return 'is the repository root, which covers every reserved folder';
|
|
71
|
+
if (value.split('/').some((seg) => seg === '' || seg === '.')) return 'carries an empty or `.` segment; write the plain path from the repository root';
|
|
72
|
+
const reserved = reservedReason(value);
|
|
73
|
+
if (reserved) return reserved;
|
|
74
|
+
if (value.length > DIR_MAX) return `is ${value.length} characters; the cap is ${DIR_MAX}`;
|
|
75
|
+
return '';
|
|
76
|
+
}
|
|
77
|
+
|
|
78
|
+
function readText(path) {
|
|
79
|
+
try { return readFileSync(path, 'utf8').replace(/\r\n/g, '\n'); } catch { return null; }
|
|
80
|
+
}
|
|
81
|
+
|
|
82
|
+
export function readRecordedPair(root) {
|
|
83
|
+
const text = readText(join(root, 'CLAUDE.md'));
|
|
84
|
+
if (text === null) return null;
|
|
85
|
+
const specs = text.match(/^- Specs: (\S+)$/m)?.[1];
|
|
86
|
+
const plans = text.match(/^- Plans: (\S+)$/m)?.[1];
|
|
87
|
+
if (!specs && !plans) return null;
|
|
88
|
+
if (!specs || !plans) throw new DocLocationError('CLAUDE.md records `- Specs:` but not `- Plans:` (or the reverse); add the missing line, or remove both');
|
|
89
|
+
for (const [label, value] of [['Specs', specs], ['Plans', plans]]) {
|
|
90
|
+
const why = checkDocDir(value);
|
|
91
|
+
if (why) throw new DocLocationError(`\`- ${label}: ${value}\` ${why}; fix that line`);
|
|
92
|
+
}
|
|
93
|
+
const pair = { specs: stripSlash(specs), plans: stripSlash(plans) };
|
|
94
|
+
if (overlaps(pair.specs, pair.plans)) throw new DocLocationError('`- Specs:` and `- Plans:` overlap; use two disjoint folders');
|
|
95
|
+
return pair;
|
|
96
|
+
}
|
|
97
|
+
|
|
98
|
+
function isDir(path) {
|
|
99
|
+
try { return statSync(path).isDirectory(); } catch { return false; }
|
|
100
|
+
}
|
|
101
|
+
|
|
102
|
+
// Hand-written, not readdirSync({ recursive: true }): engines is >=20 and that option arrived
|
|
103
|
+
// in 20.1. Dirent.isDirectory() is false for a symlink, so symlinked folders are not followed.
|
|
104
|
+
function countMarkdown(dir) {
|
|
105
|
+
let entries;
|
|
106
|
+
try { entries = readdirSync(dir, { withFileTypes: true }); } catch { return 0; }
|
|
107
|
+
let count = 0;
|
|
108
|
+
for (const entry of entries) {
|
|
109
|
+
if (entry.isDirectory()) count += countMarkdown(join(dir, entry.name));
|
|
110
|
+
else if (entry.isFile() && entry.name.endsWith('.md')) count += 1;
|
|
111
|
+
}
|
|
112
|
+
return count;
|
|
113
|
+
}
|
|
114
|
+
|
|
115
|
+
export function discoverPair(root) {
|
|
116
|
+
let best = null;
|
|
117
|
+
let bestCount = -1;
|
|
118
|
+
for (const pair of CANDIDATE_PAIRS) {
|
|
119
|
+
if (!isDir(join(root, pair.specs)) && !isDir(join(root, pair.plans))) continue;
|
|
120
|
+
const count = countMarkdown(join(root, pair.specs)) + countMarkdown(join(root, pair.plans));
|
|
121
|
+
// Strict: on a tie the earlier pair keeps the win.
|
|
122
|
+
if (count > bestCount) { best = pair; bestCount = count; }
|
|
123
|
+
}
|
|
124
|
+
return best ? { ...best } : null;
|
|
125
|
+
}
|
|
126
|
+
|
|
127
|
+
function groupName(kind, n, rest) {
|
|
128
|
+
const prefix = kind.toLowerCase();
|
|
129
|
+
if (n) return checkGroupLength(`${prefix}-${n}`);
|
|
130
|
+
const slug = rest.toLowerCase().replace(/[^a-z0-9]+/g, '-').replace(/^-+|-+$/g, '').slice(0, 40).replace(/-+$/, '');
|
|
131
|
+
if (!slug) return null;
|
|
132
|
+
return checkGroupLength(`${prefix}-${slug}`);
|
|
133
|
+
}
|
|
134
|
+
const checkGroupLength = (name) => (name.length > GROUP_MAX ? null : name);
|
|
135
|
+
|
|
136
|
+
function backlogFiles(root) {
|
|
137
|
+
try { return readdirSync(root).filter((name) => /backlog/i.test(name) && name.endsWith('.md')).sort(); } catch { return []; }
|
|
138
|
+
}
|
|
139
|
+
|
|
140
|
+
function hitsInText(text, itemRe) {
|
|
141
|
+
const hits = [];
|
|
142
|
+
let open = null;
|
|
143
|
+
for (const line of text.split('\n')) {
|
|
144
|
+
const heading = line.match(HEADING_RE);
|
|
145
|
+
if (!heading) continue;
|
|
146
|
+
const group = line.match(GROUP_RE);
|
|
147
|
+
if (group) { open = { level: group[1].length, name: groupName(group[2], group[3], group[4]) }; continue; }
|
|
148
|
+
// Close before the item check, so an item heading at the group's own level is flat.
|
|
149
|
+
if (open && heading[1].length <= open.level) open = null;
|
|
150
|
+
if (itemRe.test(line)) hits.push(open?.name ?? null);
|
|
151
|
+
}
|
|
152
|
+
return hits;
|
|
153
|
+
}
|
|
154
|
+
|
|
155
|
+
export function backlogGroup(root, item) {
|
|
156
|
+
const escaped = String(item).replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
|
|
157
|
+
const itemRe = new RegExp(`(?<![A-Za-z0-9_-])${escaped}(?![A-Za-z0-9_-])`);
|
|
158
|
+
const hits = [];
|
|
159
|
+
for (const name of backlogFiles(root)) {
|
|
160
|
+
const text = readText(join(root, name));
|
|
161
|
+
if (text !== null) hits.push(...hitsInText(text, itemRe));
|
|
162
|
+
}
|
|
163
|
+
// Ruling 5: group only when the item is placed exactly once.
|
|
164
|
+
return hits.length === 1 ? hits[0] : null;
|
|
165
|
+
}
|
|
166
|
+
|
|
167
|
+
export function resolveDocLocations(root, item) {
|
|
168
|
+
const group = item ? backlogGroup(root, item) : null;
|
|
169
|
+
const recorded = readRecordedPair(root);
|
|
170
|
+
if (recorded) return { ...recorded, group, source: 'claude-md' };
|
|
171
|
+
const discovered = discoverPair(root);
|
|
172
|
+
if (discovered) return { ...discovered, group, source: 'discovered' };
|
|
173
|
+
return { ...DEFAULT_PAIR, group, source: 'default' };
|
|
174
|
+
}
|
|
175
|
+
|
|
176
|
+
export function cli(argv) {
|
|
177
|
+
try {
|
|
178
|
+
const root = resolve(argv[0] ?? process.cwd());
|
|
179
|
+
if (!isDir(root)) throw new Error(`${root} is not a directory`);
|
|
180
|
+
const { specs, plans, source } = resolveDocLocations(root, null);
|
|
181
|
+
process.stdout.write(`${JSON.stringify({ specs, plans, source })}\n`);
|
|
182
|
+
return 0;
|
|
183
|
+
} catch (e) {
|
|
184
|
+
const line = e instanceof DocLocationError ? e.message : `doc-locations: ${e.message}`;
|
|
185
|
+
process.stderr.write(`${line.replace(/\s*\n\s*/g, ' ')}\n`);
|
|
186
|
+
return 1;
|
|
187
|
+
}
|
|
188
|
+
}
|
|
189
|
+
|
|
190
|
+
function invokedDirectly() {
|
|
191
|
+
try { return Boolean(process.argv[1]) && pathToFileURL(realpathSync(process.argv[1])).href === import.meta.url; } catch { return false; }
|
|
192
|
+
}
|
|
193
|
+
if (invokedDirectly()) process.exitCode = cli(process.argv.slice(2));
|
package/scripts/orchestrate.mjs
CHANGED
|
@@ -8,9 +8,10 @@ import { spawnSync } from 'node:child_process';
|
|
|
8
8
|
import { homedir, tmpdir } from 'node:os';
|
|
9
9
|
import { dirname, isAbsolute, join, relative, resolve } from 'node:path';
|
|
10
10
|
import { fileURLToPath, pathToFileURL } from 'node:url';
|
|
11
|
-
import { GATES, ROLE_BAND, V3_CAPS } from './snap-contract.mjs';
|
|
11
|
+
import { GATES, ROLE_BAND, V3_CAPS, elementLength } from './snap-contract.mjs';
|
|
12
12
|
// Imported, not spawned: ticket.mjs holds the four import-safety conditions (FEAT-031 B1.7, T2).
|
|
13
13
|
import { TicketHalt, intake, writeSnapshot } from './ticket.mjs';
|
|
14
|
+
import { DocLocationError, resolveDocLocations } from './doc-locations.mjs';
|
|
14
15
|
|
|
15
16
|
const HERE = dirname(fileURLToPath(import.meta.url));
|
|
16
17
|
|
|
@@ -29,9 +30,10 @@ const REVIEW_OUTCOME = /^(clean|cap|skipped:[a-z][a-z0-9-]{0,39})$/;
|
|
|
29
30
|
const REVIEW_USAGE = 'usage: orchestrate.mjs review <spec|plan> --round | --close <clean|cap|skipped:<reason>>';
|
|
30
31
|
|
|
31
32
|
// D5: the reviewed role-artifact table. Code's scope comes from its plan task instead.
|
|
33
|
+
// Spec and plan scopes come from run.docs, pinned at start, so no folder is named here (FEAT-047).
|
|
32
34
|
export const ROLE_ARTIFACTS = {
|
|
33
|
-
spec: { tk: 'RW', scope:
|
|
34
|
-
plan: { tk: 'RW', scope:
|
|
35
|
+
spec: { tk: 'RW', scope: null },
|
|
36
|
+
plan: { tk: 'RW', scope: null },
|
|
35
37
|
code: { tk: 'RW', scope: null },
|
|
36
38
|
audit: { tk: 'R', scope: null },
|
|
37
39
|
qa: { tk: 'X', scope: null },
|
|
@@ -155,11 +157,38 @@ export function taskScope(task, planRel) {
|
|
|
155
157
|
const scope = [...new Set([...task.files, planRel])];
|
|
156
158
|
const [cap, elemCap] = V3_CAPS['ops.scope'];
|
|
157
159
|
if (scope.length > cap) throw new Halt('ORCH_SCOPE_OVER_CAP', `${task.id} needs ${scope.length} scope entries; the cap is ${cap}`);
|
|
158
|
-
const long = scope.find((p) => p
|
|
159
|
-
if (long) throw new Halt('ORCH_SCOPE_OVER_CAP', `${task.id} has a ${long
|
|
160
|
+
const long = scope.find((p) => elementLength(p) > elemCap);
|
|
161
|
+
if (long) throw new Halt('ORCH_SCOPE_OVER_CAP', `${task.id} has a ${elementLength(long)}-character path; the cap is ${elemCap}`);
|
|
160
162
|
return scope;
|
|
161
163
|
}
|
|
162
164
|
|
|
165
|
+
// FEAT-047: one glob per role, checked against the element cap once, at start.
|
|
166
|
+
export function docScopes({ specs, plans, group }) {
|
|
167
|
+
const elemCap = V3_CAPS['ops.scope'][1];
|
|
168
|
+
const scopes = {};
|
|
169
|
+
for (const [role, dir] of [['spec', specs], ['plan', plans]]) {
|
|
170
|
+
const glob = `${dir}${group ? `/${group}` : ''}/**`;
|
|
171
|
+
if (glob.length > elemCap) {
|
|
172
|
+
throw new Halt('ORCH_SCOPE_OVER_CAP', `${role} scope is ${glob.length} characters; the cap is ${elemCap}; shorten the folder`);
|
|
173
|
+
}
|
|
174
|
+
scopes[role] = [glob];
|
|
175
|
+
}
|
|
176
|
+
return scopes;
|
|
177
|
+
}
|
|
178
|
+
|
|
179
|
+
// The resolver's halts keep its code and become the router's own start halts.
|
|
180
|
+
function resolveDocs(root, item) {
|
|
181
|
+
try {
|
|
182
|
+
const docs = resolveDocLocations(root, item);
|
|
183
|
+
return { ...docs, scopes: docScopes(docs) };
|
|
184
|
+
} catch (e) {
|
|
185
|
+
if (e instanceof DocLocationError) throw new Halt(e.code, e.reason);
|
|
186
|
+
throw e;
|
|
187
|
+
}
|
|
188
|
+
}
|
|
189
|
+
|
|
190
|
+
const docsNote = (d) => `docs: specs ${d.specs}, plans ${d.plans} (${d.source})${d.group ? `; group ${d.group}` : ''}; `;
|
|
191
|
+
|
|
163
192
|
function readPlan(root, planRel) {
|
|
164
193
|
if (!planRel || isAbsolute(planRel) || planRel.split(/[\\/]/).includes('..')) {
|
|
165
194
|
throw new Refusal('usage: orchestrate.mjs approve plan <plan path relative to the run root>');
|
|
@@ -205,8 +234,8 @@ function hasTestScript(pkgPath) {
|
|
|
205
234
|
}
|
|
206
235
|
|
|
207
236
|
// D6: the one command code and qa may run, resolved before anything is recorded. The script
|
|
208
|
-
// is checked before detect-stack runs, because a non-string script
|
|
209
|
-
//
|
|
237
|
+
// is checked before detect-stack runs, because detect-stack drops a non-string script and may
|
|
238
|
+
// offer its own default runner, which the run must not take in place of the owner's script.
|
|
210
239
|
export function resolveTestCommand(root) {
|
|
211
240
|
const pkgPath = join(root, 'package.json');
|
|
212
241
|
if (existsSync(pkgPath)) {
|
|
@@ -253,6 +282,12 @@ function envelopeFields(run, root, step) {
|
|
|
253
282
|
if (step.role === 'code') {
|
|
254
283
|
const task = extractTasks(readPlan(root, run.plan)).find((t) => t.id === step.task);
|
|
255
284
|
fields.scope = taskScope(task ?? { id: step.task, files: [] }, run.plan);
|
|
285
|
+
} else if (step.role === 'spec' || step.role === 'plan') {
|
|
286
|
+
// Read as pinned, never re-checked: the cap was enforced once, at start.
|
|
287
|
+
if (!isPlainObject(run.docs?.scopes) || !Array.isArray(run.docs.scopes[step.role])) {
|
|
288
|
+
throw new Halt('ORCH_DOC_LOCATION_UNRESOLVED', `run ${run.item} records no docs location (started before FEAT-047); run end, then start`);
|
|
289
|
+
}
|
|
290
|
+
fields.scope = run.docs.scopes[step.role];
|
|
256
291
|
} else if (scope) fields.scope = scope;
|
|
257
292
|
// Ruling 2: ticket identity rides the spec envelope only, never its content.
|
|
258
293
|
if (step.role === 'spec' && run.ticket) {
|
|
@@ -280,8 +315,15 @@ function install(root, sessionId, role, check) {
|
|
|
280
315
|
return built.out.trim();
|
|
281
316
|
}
|
|
282
317
|
|
|
283
|
-
|
|
284
|
-
|
|
318
|
+
// FEAT-060: the second line behind the halt; verify_pass is forwarded only over an approving audit.
|
|
319
|
+
function withholdUnlessApproved(run) {
|
|
320
|
+
const verdict = run.handbacks.find((h) => h.role === 'audit')?.verdict;
|
|
321
|
+
if (verdict !== 'APPROVE') throw new Halt('ORCH_GATE_WITHHELD', `qa may not forward verify_pass: the audit verdict is ${verdict ?? 'absent'}`);
|
|
322
|
+
}
|
|
323
|
+
|
|
324
|
+
export function recordHandback(run, role, gate, verdict) {
|
|
325
|
+
if (role === 'qa' && gate === 'verify_pass') withholdUnlessApproved(run);
|
|
326
|
+
const entry = { role, gate, at: new Date().toISOString(), ...(role === 'code' ? { task: run.tasks.ids[run.tasks.done] } : {}), ...(verdict ? { verdict } : {}) };
|
|
285
327
|
const tasks = role === 'code' ? { ...run.tasks, done: run.tasks.done + 1 } : run.tasks;
|
|
286
328
|
return { ...run, role: null, gate: forwardGate(run, role, gate), tasks, handbacks: [...run.handbacks, entry] };
|
|
287
329
|
}
|
|
@@ -297,6 +339,40 @@ function parseHandback(text) {
|
|
|
297
339
|
return env;
|
|
298
340
|
}
|
|
299
341
|
|
|
342
|
+
function auditStop({ verdict, blockers }) {
|
|
343
|
+
if (verdict === 'RETURN') return new Halt('ORCH_AUDIT_RETURN', `audit returned the change with ${blockers} blocker/major finding(s); see ${HANDBACK_DIR}/audit.txt`);
|
|
344
|
+
return new Halt('ORCH_AUDIT_ESCALATE', `audit escalated a decision only the owner takes; see ${HANDBACK_DIR}/audit.txt`);
|
|
345
|
+
}
|
|
346
|
+
|
|
347
|
+
// FEAT-060: a candidate is wider than the valid form, so a near-miss halts by name instead of passing unseen.
|
|
348
|
+
const VERDICT_CANDIDATE = /^verdict\s*:/i;
|
|
349
|
+
const VERDICT_LINE = /^VERDICT: (APPROVE|RETURN|ESCALATE)$/;
|
|
350
|
+
const FINDING_LINE = /^- \[(blocker|major|minor)\] \S+:\d+ /;
|
|
351
|
+
const QUOTE_CAP = 120;
|
|
352
|
+
|
|
353
|
+
const countSevere = (lines) => lines.map((l) => FINDING_LINE.exec(l)?.[1]).filter((s) => s === 'blocker' || s === 'major').length;
|
|
354
|
+
|
|
355
|
+
// ESCALATE carries no count rule: its cause can be an owner decision with no code defect.
|
|
356
|
+
function checkConsistent(verdict, blockers) {
|
|
357
|
+
if ((verdict === 'APPROVE' && blockers > 0) || (verdict === 'RETURN' && blockers === 0)) {
|
|
358
|
+
throw new Halt('ORCH_VERDICT_INCONSISTENT', `VERDICT: ${verdict} with ${blockers} blocker/major finding(s)`);
|
|
359
|
+
}
|
|
360
|
+
return { verdict, blockers };
|
|
361
|
+
}
|
|
362
|
+
|
|
363
|
+
export function parseVerdict(text) {
|
|
364
|
+
const lines = text.split(/\r?\n/).map((l) => l.trim());
|
|
365
|
+
const candidates = lines.filter((l) => VERDICT_CANDIDATE.test(l));
|
|
366
|
+
if (candidates.length === 0) throw new Halt('ORCH_VERDICT_MISSING', 'the audit report has no VERDICT: APPROVE | RETURN | ESCALATE line');
|
|
367
|
+
if (candidates.length > 1) throw new Halt('ORCH_VERDICT_INVALID', `expected exactly one VERDICT line, found ${candidates.length}`);
|
|
368
|
+
const match = VERDICT_LINE.exec(candidates[0]);
|
|
369
|
+
if (!match) throw new Halt('ORCH_VERDICT_INVALID', `${JSON.stringify(candidates[0].slice(0, QUOTE_CAP))} is not VERDICT: APPROVE | RETURN | ESCALATE`);
|
|
370
|
+
const at = lines.findIndex((l) => l.startsWith('SNAP_HANDBACK '));
|
|
371
|
+
const report = lines.slice(0, Math.max(at, 0)).filter(Boolean);
|
|
372
|
+
if (at === -1 || report.at(-1) !== candidates[0]) throw new Halt('ORCH_VERDICT_INVALID', 'the VERDICT line must immediately precede SNAP_HANDBACK');
|
|
373
|
+
return checkConsistent(match[1], countSevere(report));
|
|
374
|
+
}
|
|
375
|
+
|
|
300
376
|
function handback(root, sessionId, role, text) {
|
|
301
377
|
const run = liveRun(root, sessionId);
|
|
302
378
|
// The binary refuses a second SubagentHandback, yet an agent can still report again (V1, F4).
|
|
@@ -309,7 +385,10 @@ function handback(root, sessionId, role, text) {
|
|
|
309
385
|
if (!MAY_HAND_BACK[role].includes(env.ops.gate)) {
|
|
310
386
|
throw new Halt('ORCH_GATE_UNEARNED', `${role} may hand back ${MAY_HAND_BACK[role].join('|')}, not ${env.ops.gate}`);
|
|
311
387
|
}
|
|
312
|
-
|
|
388
|
+
const verdict = role === 'audit' ? parseVerdict(text) : null;
|
|
389
|
+
saveRun(root, recordHandback(run, role, env.ops.gate, verdict?.verdict));
|
|
390
|
+
// Saved first, so the halt cli records lands on top of the audit entry (spec, Alternative paths).
|
|
391
|
+
if (verdict && verdict.verdict !== 'APPROVE') throw auditStop(verdict);
|
|
313
392
|
return `${role} handed back ${env.ops.gate}`;
|
|
314
393
|
}
|
|
315
394
|
|
|
@@ -394,17 +473,18 @@ function start(root, sessionId, args) {
|
|
|
394
473
|
if (old && old.session_id === sessionId) throw new Halt('ORCH_RUN_ACTIVE', `run ${old.item} is live in this session; end it first`);
|
|
395
474
|
// Resolved before a stale run is cleared, so a halt here leaves everything as it was.
|
|
396
475
|
const testCommand = checkTestCommand(resolveTestCommand(root));
|
|
476
|
+
const docs = resolveDocs(root, item);
|
|
397
477
|
const bound = ticket === undefined ? null : ticketIntake(root, item, ticket);
|
|
398
478
|
if (old) clearRunFiles(root);
|
|
399
479
|
if (bound) writeSnapshot(root, bound.path, bound.text);
|
|
400
480
|
saveRun(root, {
|
|
401
481
|
v: 1, session_id: sessionId, item, mode: auto ? 'auto' : 'step', started: new Date().toISOString(),
|
|
402
482
|
band: 'boundary', role: null, gate: 'boundary_routed', approvals: { spec: null, plan: null },
|
|
403
|
-
plan: null, tasks: { ids: [], done: 0 }, handbacks: [], halt: null, test_command: testCommand,
|
|
483
|
+
plan: null, tasks: { ids: [], done: 0 }, handbacks: [], halt: null, test_command: testCommand, docs,
|
|
404
484
|
...(bound ? { ticket: { ...bound.binding, snapshot: bound.path } } : {}),
|
|
405
485
|
});
|
|
406
486
|
const begun = old ? `replaced the stale run ${old.item} started ${old.started}` : `run ${item} started`;
|
|
407
|
-
return `${begun}; ${bound ? ticketNote(bound) : ''}test command: ${testCommand}`;
|
|
487
|
+
return `${begun}; ${bound ? ticketNote(bound) : ''}${docsNote(docs)}test command: ${testCommand}`;
|
|
408
488
|
}
|
|
409
489
|
|
|
410
490
|
function clearRunFiles(root) {
|
package/scripts/snap-build.mjs
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
import { readFileSync } from 'node:fs';
|
|
2
|
-
import { CAPS, PRE_PARSE_MAX_BYTES as MAX_SNAP_BYTES, V1_MAX_CHARS, V3_CAPS } from './snap-contract.mjs';
|
|
2
|
+
import { CAPS, PRE_PARSE_MAX_BYTES as MAX_SNAP_BYTES, V1_MAX_CHARS, V3_CAPS, elementLength } from './snap-contract.mjs';
|
|
3
3
|
|
|
4
4
|
const die = (msg) => { process.stderr.write(`SNAP_BUILD_ERROR: ${msg}\n`); process.exit(1); };
|
|
5
5
|
const byteLen = (s) => Buffer.byteLength(s, 'utf8');
|
|
@@ -9,21 +9,57 @@ const byteLen = (s) => Buffer.byteLength(s, 'utf8');
|
|
|
9
9
|
// after an async write truncates the un-flushed tail; the drain callback avoids both.
|
|
10
10
|
function writeOut(s) { process.stdout.write(s + '\n', () => process.exit(0)); }
|
|
11
11
|
|
|
12
|
+
// Issue #132: cut to the validator's measure, one code point at a time, so the cut never
|
|
13
|
+
// splits a surrogate pair or an escape. JSON escapes each code point on its own, so the
|
|
14
|
+
// per-code-point sum equals elementLength of the prefix and the result always validates.
|
|
15
|
+
function truncateToCap(str, elemCap) {
|
|
16
|
+
if (elementLength(str) <= elemCap) return str;
|
|
17
|
+
let used = 0; let end = 0;
|
|
18
|
+
for (const ch of str) {
|
|
19
|
+
used += elementLength(ch);
|
|
20
|
+
if (used > elemCap) break;
|
|
21
|
+
end += ch.length;
|
|
22
|
+
}
|
|
23
|
+
return str.slice(0, end);
|
|
24
|
+
}
|
|
25
|
+
|
|
26
|
+
// Issue #136: an ops.f entry is `<path>:<C|M|D>` and the validator requires that suffix, so an
|
|
27
|
+
// over-cap entry loses path, never its action code. Without a code there is nothing valid to keep.
|
|
28
|
+
function truncateFileEntry(entry, elemCap, index) {
|
|
29
|
+
const size = elementLength(entry);
|
|
30
|
+
if (size <= elemCap) return entry;
|
|
31
|
+
const code = entry.slice(-2);
|
|
32
|
+
if (!/^:[CMD]$/.test(code)) die(`SNAP_FILE_NO_ACTION: ops.f[${index}] is ${size} characters, over the cap of ${elemCap}, and has no :C, :M or :D suffix to keep`);
|
|
33
|
+
return truncateToCap(entry.slice(0, -2), elemCap - code.length) + code;
|
|
34
|
+
}
|
|
35
|
+
|
|
12
36
|
// filter empties, dedup (first wins), Unicode-safe per-element truncation, head-drop to count cap
|
|
13
|
-
function normArray(raw, [cap, elemCap]) {
|
|
37
|
+
function normArray(raw, [cap, elemCap], truncate = truncateToCap) {
|
|
14
38
|
const arr = Array.isArray(raw) ? raw : [];
|
|
15
39
|
const seen = new Set(); const out = [];
|
|
16
|
-
for (const item of arr) {
|
|
40
|
+
for (const [index, item] of arr.entries()) {
|
|
17
41
|
if (typeof item !== 'string') continue;
|
|
18
42
|
const t = item.trim();
|
|
19
43
|
if (!t || seen.has(t)) continue;
|
|
20
44
|
seen.add(t);
|
|
21
|
-
out.push(
|
|
45
|
+
out.push(truncate(t, elemCap, index));
|
|
22
46
|
}
|
|
23
47
|
while (out.length > cap) out.shift();
|
|
24
48
|
return out;
|
|
25
49
|
}
|
|
26
50
|
|
|
51
|
+
// D9 (issue #119): a scope is a Guard 5 envelope, so it is refused at its caps, never truncated.
|
|
52
|
+
// Blanks and duplicates still drop: they narrow nothing.
|
|
53
|
+
function scopeArray(raw) {
|
|
54
|
+
const [cap, elemCap] = V3_CAPS['ops.scope'];
|
|
55
|
+
const charLen = (el) => elementLength(el.trim());
|
|
56
|
+
const long = raw.findIndex((el) => typeof el === 'string' && charLen(el) > elemCap);
|
|
57
|
+
if (long >= 0) die(`SNAP_SCOPE_OVER_CAP: ops.scope[${long}] is ${charLen(raw[long])} characters; the cap is ${elemCap}`);
|
|
58
|
+
const scope = normArray(raw, [Infinity, elemCap]);
|
|
59
|
+
if (scope.length > cap) die(`SNAP_SCOPE_OVER_CAP: ops.scope has ${scope.length} entries; the cap is ${cap}`);
|
|
60
|
+
return scope;
|
|
61
|
+
}
|
|
62
|
+
|
|
27
63
|
// back off one unit if the boundary would keep a lone high surrogate
|
|
28
64
|
function surrogateSafe(str, n) {
|
|
29
65
|
if (n > 0 && n <= str.length) {
|
|
@@ -45,7 +81,7 @@ for (const k of ['ph', 'c', 's']) {
|
|
|
45
81
|
}
|
|
46
82
|
|
|
47
83
|
const sys = { ph: obj.ph, c: obj.c, s: obj.s };
|
|
48
|
-
const ops = { n: normArray(obj.n, CAPS['ops.n']), f: normArray(obj.f, CAPS['ops.f']) };
|
|
84
|
+
const ops = { n: normArray(obj.n, CAPS['ops.n']), f: normArray(obj.f, CAPS['ops.f'], truncateFileEntry) };
|
|
49
85
|
const mem = { d: normArray(obj.d, CAPS['mem.d']), x: normArray(obj.x, CAPS['mem.x']) };
|
|
50
86
|
const pr = typeof obj.pr === 'string' ? obj.pr : '';
|
|
51
87
|
|
|
@@ -59,7 +95,7 @@ if (band) {
|
|
|
59
95
|
if (obj.p !== undefined && (typeof obj.p !== 'object' || obj.p === null || Array.isArray(obj.p))) die('p must be a plain object');
|
|
60
96
|
// Assignment order is serialization order: BLOCK_FIELDS[3] lists scope before gate.
|
|
61
97
|
Object.assign(sys, { role: obj.role, tk: obj.tk });
|
|
62
|
-
if (obj.scope !== undefined) ops.scope =
|
|
98
|
+
if (obj.scope !== undefined) ops.scope = scopeArray(obj.scope);
|
|
63
99
|
ops.gate = obj.gate;
|
|
64
100
|
if (obj.p !== undefined) mem.p = obj.p;
|
|
65
101
|
}
|
|
@@ -32,6 +32,9 @@ export const CAPS = {
|
|
|
32
32
|
};
|
|
33
33
|
// Same scheme, v3 only: ops.scope exists in no earlier version, so it cannot join CAPS.
|
|
34
34
|
export const V3_CAPS = { 'ops.scope': [20, 300] };
|
|
35
|
+
// The one measure every element cap is checked in (FEAT-010 spec): the element's JSON-escaped
|
|
36
|
+
// length without its quotes. Router, builder and validator all call this (issue #128).
|
|
37
|
+
export const elementLength = (el) => JSON.stringify(el).slice(1, -1).length;
|
|
35
38
|
|
|
36
39
|
// Field sets, both per version. v1 and v2 share one block map, unchanged since v1;
|
|
37
40
|
// v3 adds the band fields reserved by FEAT-010 (ARCH-010).
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { readFileSync } from 'node:fs'; import { BLOCK_FIELDS, CAPS, GATES, MAX_VERSION, POST_PARSE_MAX, PRE_PARSE_MAX_BYTES, ROLES, TOOL_KINDS, TOP_FIELDS, V3_CAPS, expectedGate } from './snap-contract.mjs';
|
|
1
|
+
import { readFileSync } from 'node:fs'; import { BLOCK_FIELDS, CAPS, GATES, MAX_VERSION, POST_PARSE_MAX, PRE_PARSE_MAX_BYTES, ROLES, TOOL_KINDS, TOP_FIELDS, V3_CAPS, elementLength, expectedGate } from './snap-contract.mjs';
|
|
2
2
|
const err = (m) => { process.stderr.write(`SNAP_ERROR: ${m}\n`); process.exit(1); };
|
|
3
3
|
const [path, flag, to] = process.argv.slice(2); if (path === undefined) err('no path provided');
|
|
4
4
|
if (flag !== undefined && (flag !== '--to' || !ROLES.includes(to))) err(`usage: snap-validate.mjs <file> [--to ${ROLES.join('|')}]`);
|
|
@@ -27,7 +27,7 @@ const p = snap.mem.p; if (p !== undefined && (typeof p !== 'object' || p === nul
|
|
|
27
27
|
const arrayCaps = { ...CAPS, ...(snap.ops.scope === undefined ? {} : V3_CAPS) };
|
|
28
28
|
for (const [key, [cap, elemCap]] of Object.entries(arrayCaps)) {
|
|
29
29
|
const [blk, sub] = key.split('.'); const arr = snap[blk][sub]; if (!Array.isArray(arr)) err(`${key} must be an array`); if (arr.length > cap) err(`${key} exceeds cap`);
|
|
30
|
-
arr.forEach((el, i) => { if (typeof el !== 'string' || el.trim() === '') err(`empty element in ${key}[${i}]`); if (
|
|
30
|
+
arr.forEach((el, i) => { if (typeof el !== 'string' || el.trim() === '') err(`empty element in ${key}[${i}]`); if (elementLength(el) > elemCap) err(`element too long in ${key}[${i}]`); });
|
|
31
31
|
}
|
|
32
32
|
snap.ops.f.forEach((el, i) => {
|
|
33
33
|
if (el.includes('\\')) err(`backslash in ops.f[${i}]`);
|