@yeison.restrepo.r/code-conductor 1.43.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.
@@ -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}]`);