@yeison.restrepo.r/code-conductor 1.42.0 → 1.44.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.
@@ -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));
@@ -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: ['docs/superpowers/specs/**'] },
34
- plan: { tk: 'RW', scope: ['docs/superpowers/plans/**'] },
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.length > elemCap);
159
- if (long) throw new Halt('ORCH_SCOPE_OVER_CAP', `${task.id} has a ${long.length}-character path; the cap is ${elemCap}`);
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 makes detect-stack fail
209
- // whole and the halt would then name the wrong cause.
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) {
@@ -394,17 +429,18 @@ function start(root, sessionId, args) {
394
429
  if (old && old.session_id === sessionId) throw new Halt('ORCH_RUN_ACTIVE', `run ${old.item} is live in this session; end it first`);
395
430
  // Resolved before a stale run is cleared, so a halt here leaves everything as it was.
396
431
  const testCommand = checkTestCommand(resolveTestCommand(root));
432
+ const docs = resolveDocs(root, item);
397
433
  const bound = ticket === undefined ? null : ticketIntake(root, item, ticket);
398
434
  if (old) clearRunFiles(root);
399
435
  if (bound) writeSnapshot(root, bound.path, bound.text);
400
436
  saveRun(root, {
401
437
  v: 1, session_id: sessionId, item, mode: auto ? 'auto' : 'step', started: new Date().toISOString(),
402
438
  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,
439
+ plan: null, tasks: { ids: [], done: 0 }, handbacks: [], halt: null, test_command: testCommand, docs,
404
440
  ...(bound ? { ticket: { ...bound.binding, snapshot: bound.path } } : {}),
405
441
  });
406
442
  const begun = old ? `replaced the stale run ${old.item} started ${old.started}` : `run ${item} started`;
407
- return `${begun}; ${bound ? ticketNote(bound) : ''}test command: ${testCommand}`;
443
+ return `${begun}; ${bound ? ticketNote(bound) : ''}${docsNote(docs)}test command: ${testCommand}`;
408
444
  }
409
445
 
410
446
  function clearRunFiles(root) {
@@ -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(Array.from(t).slice(0, elemCap).join(''));
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 = normArray(obj.scope, V3_CAPS['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 (JSON.stringify(el).slice(1, -1).length > elemCap) err(`element too long in ${key}[${i}]`); });
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}]`);