@yunhozz/arc 0.5.1 → 0.5.3
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/MANIFEST.sha256 +146 -139
- package/README.md +12 -3
- package/claude/agents/arc-implementer.md +7 -7
- package/claude/agents/arc-planner.md +5 -5
- package/claude/agents/arc-reviewer.md +6 -6
- package/claude/agents/arc-scouter.md +5 -5
- package/claude/agents/{arc-qa.md → arc-tester.md} +10 -10
- package/claude/skill/SKILL.md +6 -6
- package/claude/skill/models.toml +2 -2
- package/claude/skill/references/arc-visual-companion.md +2 -2
- package/claude/skill/references/commit.md +3 -3
- package/claude/skill/references/coordination.md +27 -21
- package/claude/skill/references/git-recovery.md +3 -1
- package/claude/skill/references/handoff-prep.md +3 -3
- package/claude/skill/references/handoff.md +16 -14
- package/claude/skill/references/limits.md +2 -2
- package/claude/skill/references/planning.md +12 -10
- package/claude/skill/references/verification.md +67 -35
- package/claude/skill/references/worktree-creation.md +2 -0
- package/claude/skill/scripts/model_config.py +25 -9
- package/codex/agents/arc-implementer.toml +7 -7
- package/codex/agents/arc-planner.toml +6 -6
- package/codex/agents/arc-reviewer.toml +7 -7
- package/codex/agents/arc-scouter.toml +6 -6
- package/codex/agents/{arc-qa.toml → arc-tester.toml} +10 -10
- package/codex/skill/SKILL.md +7 -7
- package/codex/skill/models.toml +2 -2
- package/codex/skill/references/arc-visual-companion.md +3 -3
- package/codex/skill/references/commit.md +4 -4
- package/codex/skill/references/coordination.md +26 -20
- package/codex/skill/references/git-recovery.md +2 -0
- package/codex/skill/references/handoff-prep.md +4 -4
- package/codex/skill/references/handoff.md +17 -15
- package/codex/skill/references/limits.md +2 -2
- package/codex/skill/references/planning.md +13 -11
- package/codex/skill/references/verification.md +68 -36
- package/codex/skill/references/worktree-creation.md +2 -0
- package/codex/skill/scripts/model_config.py +28 -15
- package/gemini/agents/arc-implementer.md +7 -7
- package/gemini/agents/arc-planner.md +5 -5
- package/gemini/agents/arc-reviewer.md +6 -6
- package/gemini/agents/arc-scouter.md +5 -5
- package/gemini/agents/{arc-qa.md → arc-tester.md} +10 -10
- package/gemini/skill/SKILL.md +6 -6
- package/gemini/skill/models.toml +2 -2
- package/gemini/skill/references/arc-visual-companion.md +2 -2
- package/gemini/skill/references/commit.md +3 -3
- package/gemini/skill/references/coordination.md +27 -21
- package/gemini/skill/references/git-recovery.md +3 -1
- package/gemini/skill/references/handoff-prep.md +3 -3
- package/gemini/skill/references/handoff.md +16 -14
- package/gemini/skill/references/limits.md +2 -2
- package/gemini/skill/references/planning.md +12 -10
- package/gemini/skill/references/verification.md +67 -35
- package/gemini/skill/references/worktree-creation.md +2 -0
- package/grok/agents/arc-implementer.md +7 -7
- package/grok/agents/arc-planner.md +5 -5
- package/grok/agents/arc-reviewer.md +6 -6
- package/grok/agents/arc-scouter.md +5 -5
- package/grok/agents/{arc-qa.md → arc-tester.md} +10 -10
- package/grok/skill/SKILL.md +6 -6
- package/grok/skill/models.toml +2 -2
- package/grok/skill/references/arc-visual-companion.md +2 -2
- package/grok/skill/references/commit.md +3 -3
- package/grok/skill/references/coordination.md +27 -21
- package/grok/skill/references/git-recovery.md +3 -1
- package/grok/skill/references/handoff-prep.md +3 -3
- package/grok/skill/references/handoff.md +16 -14
- package/grok/skill/references/limits.md +2 -2
- package/grok/skill/references/planning.md +12 -10
- package/grok/skill/references/verification.md +67 -35
- package/grok/skill/references/worktree-creation.md +2 -0
- package/lib/installer/install-mode.mjs +4 -2
- package/lib/installer/install.mjs +4 -3
- package/lib/installer/language.mjs +1 -1
- package/lib/installer/legacy-profiles.mjs +51 -0
- package/lib/installer/manifest.mjs +1 -1
- package/lib/installer/plan.mjs +5 -3
- package/lib/installer/preset.mjs +2 -2
- package/lib/installer/role-routing.mjs +49 -18
- package/lib/installer/runtime-assets.mjs +3 -0
- package/lib/installer/targets.mjs +1 -1
- package/lib/installer/transaction.mjs +35 -4
- package/lib/installer/uninstall.mjs +13 -10
- package/lib/installer/upgrade-state.mjs +13 -1
- package/lib/management/operations.mjs +10 -10
- package/lib/management/reapply.mjs +5 -3
- package/lib/models/config.mjs +25 -7
- package/lib/models/profiles.mjs +1 -1
- package/lib/platforms/formats/gemini-markdown.mjs +3 -3
- package/lib/platforms/formats/grok-markdown.mjs +3 -3
- package/lib/platforms/formats/markdown.mjs +2 -2
- package/lib/platforms/formats/toml.mjs +2 -2
- package/lib/policy/placement.mjs +1 -1
- package/lib/policy/render.mjs +3 -3
- package/lib/policy/role-policy.json +28 -28
- package/lib/prompts/agent-fragments.json +24 -24
- package/lib/prompts/render.mjs +9 -9
- package/lib/runtime/acceptance.mjs +4 -3
- package/lib/runtime/bootstrap.mjs +4 -2
- package/lib/runtime/command.mjs +29 -3
- package/lib/runtime/cooperative-schema.mjs +16 -5
- package/lib/runtime/cooperative.mjs +6 -3
- package/lib/runtime/evaluate.mjs +10 -7
- package/lib/runtime/handoff-record.mjs +58 -0
- package/lib/runtime/host-service.mjs +155 -0
- package/lib/runtime/identity.mjs +10 -7
- package/lib/runtime/operations.mjs +41 -3
- package/lib/runtime/role-bridge-args.mjs +115 -13
- package/lib/runtime/role-bridge.mjs +57 -22
- package/lib/runtime/role-dispatch-policy.mjs +15 -5
- package/lib/runtime/role-dispatch-store.mjs +9 -2
- package/lib/runtime/role-observe.mjs +12 -7
- package/lib/runtime/role-routing-config.mjs +20 -6
- package/lib/runtime/role-routing.mjs +17 -4
- package/lib/runtime/role-supervisor.mjs +248 -9
- package/lib/runtime/schema.mjs +8 -5
- package/lib/runtime/scope.mjs +1 -1
- package/lib/runtime/store.mjs +2 -2
- package/lib/runtime/tool-access.mjs +560 -0
- package/lib/runtime/verification.mjs +15 -7
- package/lib/tui/setup.mjs +1 -1
- package/lib/watch/labels.mjs +2 -1
- package/lib/watch/model.mjs +2 -2
- package/lib/watch/render.mjs +2 -2
- package/lib/watch/watcher.mjs +46 -25
- package/package.json +1 -1
- package/shared/skill/runtime/acceptance.mjs +4 -3
- package/shared/skill/runtime/bootstrap.mjs +4 -2
- package/shared/skill/runtime/command.mjs +29 -3
- package/shared/skill/runtime/cooperative-schema.mjs +16 -5
- package/shared/skill/runtime/cooperative.mjs +6 -3
- package/shared/skill/runtime/evaluate.mjs +10 -7
- package/shared/skill/runtime/handoff-record.mjs +58 -0
- package/shared/skill/runtime/host-service.mjs +155 -0
- package/shared/skill/runtime/identity.mjs +10 -7
- package/shared/skill/runtime/operations.mjs +41 -3
- package/shared/skill/runtime/role-bridge-args.mjs +115 -13
- package/shared/skill/runtime/role-bridge.mjs +57 -22
- package/shared/skill/runtime/role-dispatch-policy.mjs +15 -5
- package/shared/skill/runtime/role-dispatch-store.mjs +9 -2
- package/shared/skill/runtime/role-observe.mjs +12 -7
- package/shared/skill/runtime/role-policy.json +28 -28
- package/shared/skill/runtime/role-routing-config.mjs +20 -6
- package/shared/skill/runtime/role-routing.mjs +17 -4
- package/shared/skill/runtime/role-supervisor.mjs +248 -9
- package/shared/skill/runtime/schema.mjs +8 -5
- package/shared/skill/runtime/scope.mjs +1 -1
- package/shared/skill/runtime/store.mjs +2 -2
- package/shared/skill/runtime/tool-access.mjs +560 -0
- package/shared/skill/runtime/verification.mjs +15 -7
package/lib/watch/model.mjs
CHANGED
|
@@ -5,7 +5,7 @@ export function classifyMessageKind(event) {
|
|
|
5
5
|
return event.kind === 'user' && (event.parentId || event.dispatchId) ? 'prompt' : event.kind;
|
|
6
6
|
}
|
|
7
7
|
export const VERBOSE_KINDS = Object.freeze(['settings','turn_start','reasoning','other']);
|
|
8
|
-
export const ROLE_NAMES = Object.freeze(['scouter','planner','implementer','
|
|
8
|
+
export const ROLE_NAMES = Object.freeze(['scouter','planner','implementer','tester','reviewer']);
|
|
9
9
|
|
|
10
10
|
export const WATCH_LIMITS = Object.freeze({
|
|
11
11
|
filePollMs:500, discoveryMs:2000, worktreeRefreshMs:30000, holdMs:2000,
|
|
@@ -37,7 +37,7 @@ export const WATCH_LIMITS = Object.freeze({
|
|
|
37
37
|
* @property {string} [parentId]
|
|
38
38
|
* @property {number} [depth]
|
|
39
39
|
* @property {string} label
|
|
40
|
-
* @property {'scouter'|'planner'|'implementer'|'
|
|
40
|
+
* @property {'scouter'|'planner'|'implementer'|'tester'|'reviewer'|'orchestrator'} [role]
|
|
41
41
|
* @property {string} [dispatchId]
|
|
42
42
|
* @property {string} [workflowId]
|
|
43
43
|
* @property {'session'|'settings'|'turn_start'|'turn_end'|'turn_failed'|'user'|'prompt'|'agent'|'reasoning'|'command'|'tool'|'tool_failed'|'file_change'|'file_create'|'file_delete'|'spawn'|'approval'|'dispatch'|'error'|'other'|'notice'} kind
|
package/lib/watch/render.mjs
CHANGED
|
@@ -9,11 +9,11 @@ export {displayWidth, wrapLine} from './text-width.mjs';
|
|
|
9
9
|
|
|
10
10
|
const roleLabels = new Map([
|
|
11
11
|
['scouter','SCOUTER'], ['planner','PLANNER'], ['implementer','IMPLEMENTER'],
|
|
12
|
-
['
|
|
12
|
+
['tester','TESTER'], ['reviewer','REVIEWER'], ['orchestrator','ORCHESTRATOR'],
|
|
13
13
|
]);
|
|
14
14
|
const roleBadgeColors = new Map([
|
|
15
15
|
['scouter','1;38;5;16;48;5;117'], ['planner','1;38;5;231;48;5;98'],
|
|
16
|
-
['implementer','1;38;5;16;48;5;214'], ['
|
|
16
|
+
['implementer','1;38;5;16;48;5;214'], ['tester','1;38;5;16;48;5;228'],
|
|
17
17
|
['reviewer','1;38;5;231;48;5;161'], ['orchestrator','1;38;5;16;48;5;255'],
|
|
18
18
|
]);
|
|
19
19
|
export const PLATFORM_COLORS = Object.freeze({codex:'36', claude:'38;5;208', gemini:'38;5;135', other:'2'});
|
package/lib/watch/watcher.mjs
CHANGED
|
@@ -46,7 +46,7 @@ export function createWatcher({options, homes, scope: initialScope, git, now, re
|
|
|
46
46
|
if (item.platform != null && item.platform!==platform) continue;
|
|
47
47
|
rememberStart({...item,platform},startup);
|
|
48
48
|
if (item.compressed) {
|
|
49
|
-
if (!compressed.has(item.file)) debug(out,`compressed session skipped: ${path.basename(item.file)}`);
|
|
49
|
+
if (platforms.includes(platform) && !compressed.has(item.file)) debug(out,`compressed session skipped: ${path.basename(item.file)}`);
|
|
50
50
|
compressed.add(item.file); continue;
|
|
51
51
|
}
|
|
52
52
|
if ([...followed.values()].some(row=>row.file===item.file)) continue;
|
|
@@ -91,6 +91,8 @@ export function createWatcher({options, homes, scope: initialScope, git, now, re
|
|
|
91
91
|
},
|
|
92
92
|
}],
|
|
93
93
|
]);
|
|
94
|
+
const tracked = new Set([...TRANSCRIPT_HANDLERS.keys()].filter(platform=>homes[platform]
|
|
95
|
+
&& (platforms.includes(platform) || registry.getPlatform(platform)?.capabilities.watch.state==='verified')));
|
|
94
96
|
const stamp = () => new Date(now()).toISOString();
|
|
95
97
|
const notice = text => ({v:1,ts:stamp(),observedAt:stamp(),source:'watch',label:'watch',kind:'notice',text});
|
|
96
98
|
const debug = (out, text) => { if (verbose) out.push(notice(text)); };
|
|
@@ -106,12 +108,12 @@ export function createWatcher({options, homes, scope: initialScope, git, now, re
|
|
|
106
108
|
return e;
|
|
107
109
|
};
|
|
108
110
|
const dispatchInScope = ref => ref.inScope && (ref.cwd ? inScope(scope,ref.cwd)
|
|
109
|
-
: [...followed.values()].some(row
|
|
111
|
+
: [...followed.values()].some(row=>!row.hidden && ref.sessionIds.includes(row.id) && cwdInScope(row.cwd)));
|
|
110
112
|
function mapped(row) {
|
|
111
113
|
const ref = dispatch.bySession(row.id);
|
|
112
114
|
return ref && ref.inScope && (ref.cwd ? inScope(scope,ref.cwd) : cwdInScope(row.cwd)) ? ref : null;
|
|
113
115
|
}
|
|
114
|
-
const followedDispatchRow = ref => [...followed.values()].find(row
|
|
116
|
+
const followedDispatchRow = ref => [...followed.values()].find(row=>!row.hidden && ref.sessionIds.includes(row.id) && mapped(row)===ref);
|
|
115
117
|
function dispatchPlatforms(ref, followedRow) {
|
|
116
118
|
const target = ref.targetPlatform ?? followedRow?.platform
|
|
117
119
|
?? (ref.route==='native' ? ref.hostPlatform : undefined) ?? ref.childPlatform;
|
|
@@ -173,7 +175,7 @@ export function createWatcher({options, homes, scope: initialScope, git, now, re
|
|
|
173
175
|
row.root=await sessionRoot(cwd);
|
|
174
176
|
}
|
|
175
177
|
async function ensureShellRoot(row, out) {
|
|
176
|
-
if (row.gitTop && !shellRoots.has(row.gitTop) && shellRoots.size < L.maxRepos) {
|
|
178
|
+
if (!row.hidden && row.gitTop && !shellRoots.has(row.gitTop) && shellRoots.size < L.maxRepos) {
|
|
177
179
|
const state = {snapshot:null,pending:false,pendingSince:undefined,lastTriggerAt:-Infinity,
|
|
178
180
|
lastScanAt:-Infinity,claims:new Map(),candidates:new Map(),failures:0,off:false};
|
|
179
181
|
shellRoots.set(row.gitTop,state);
|
|
@@ -219,7 +221,7 @@ export function createWatcher({options, homes, scope: initialScope, git, now, re
|
|
|
219
221
|
}
|
|
220
222
|
const inside=lineGate(row), entering=row.inScopeNow===false && inside;
|
|
221
223
|
if (entering) events.push(clean({...identity(row),ts:line.timestamp??stamp(),kind:'session',text:sessionText(row)}));
|
|
222
|
-
if (row.inScopeNow===true && !inside) debug(out,`session ${row.id.slice(0,8)} left scope: cwd=${row.cwd}`);
|
|
224
|
+
if (!row.hidden && row.inScopeNow===true && !inside) debug(out,`session ${row.id.slice(0,8)} left scope: cwd=${row.cwd}`);
|
|
223
225
|
row.inScopeNow=inside;
|
|
224
226
|
const normalized=handler.normalize(line,row.state,homes[row.platform]);
|
|
225
227
|
if (inside) {
|
|
@@ -251,6 +253,10 @@ export function createWatcher({options, homes, scope: initialScope, git, now, re
|
|
|
251
253
|
return {events,sawInScope,firstSession};
|
|
252
254
|
}
|
|
253
255
|
function emit(row, events, out) {
|
|
256
|
+
if (row.hidden) {
|
|
257
|
+
row.held=[];
|
|
258
|
+
return;
|
|
259
|
+
}
|
|
254
260
|
if (row.holdUntil !== undefined && !mapped(row) && now() < row.holdUntil) row.held.push(...events);
|
|
255
261
|
else {
|
|
256
262
|
// Held events receive the final identity only when released.
|
|
@@ -286,7 +292,7 @@ export function createWatcher({options, homes, scope: initialScope, git, now, re
|
|
|
286
292
|
}
|
|
287
293
|
}
|
|
288
294
|
function eligible(row) {
|
|
289
|
-
if (!
|
|
295
|
+
if (!tracked.has(row.platform) || row.origin === 'Codex Desktop') return false;
|
|
290
296
|
if (row.parentId) {
|
|
291
297
|
const chain=ancestry(row);
|
|
292
298
|
if (chain.desktop) {ignored.set(row.file,row.size);return false;}
|
|
@@ -304,7 +310,10 @@ export function createWatcher({options, homes, scope: initialScope, git, now, re
|
|
|
304
310
|
const previous = detached.get(row.file) ?? (!startup && !pending.has(row.file) ? seenAtStart.get(row.file) : undefined);
|
|
305
311
|
let history;
|
|
306
312
|
try { history = previous ? {endOffset:previous.offset} : await readTail(row.file); }
|
|
307
|
-
catch (error) {
|
|
313
|
+
catch (error) {
|
|
314
|
+
if (!row.hidden) debug(out,`session file unreadable: ${row.id.slice(0,8)} (${error.code ?? 'error'})`);
|
|
315
|
+
ignored.set(row.file,row.size); return;
|
|
316
|
+
}
|
|
308
317
|
row.headCwd=row.cwd;
|
|
309
318
|
row.tail=createTail(row.file,{offset:previous?.offset ?? history.endOffset});
|
|
310
319
|
const handler=TRANSCRIPT_HANDLERS.get(row.platform);
|
|
@@ -313,17 +322,17 @@ export function createWatcher({options, homes, scope: initialScope, git, now, re
|
|
|
313
322
|
await setCwd(row,previous?.cwd??row.headCwd,out);
|
|
314
323
|
await verifyCwd(row.cwd,out);
|
|
315
324
|
followed.set(row.id,row); pending.delete(row.file); detached.delete(row.file);
|
|
316
|
-
if (!startup && !previous && !row.parentId && !mapped(row) && handler.shouldHold(row.origin) && now()-row.mtimeMs<=L.holdCreatedWithinMs) row.holdUntil=now()+L.holdMs;
|
|
325
|
+
if (!row.hidden && !startup && !previous && !row.parentId && !mapped(row) && handler.shouldHold(row.origin) && now()-row.mtimeMs<=L.holdCreatedWithinMs) row.holdUntil=now()+L.holdMs;
|
|
317
326
|
const showHistory = startup ? tailCount > 0 && now()-row.mtimeMs<=L.historyWindowMs : !previous;
|
|
318
327
|
const {events,firstSession}=await normalize(row,history.lines??[],false,out);
|
|
319
|
-
if (showHistory) {
|
|
328
|
+
if (!row.hidden && showHistory) {
|
|
320
329
|
if (!events.some(e=>e.kind==='session')) {
|
|
321
330
|
const initialSession=firstSession ?? (lineGate(row)
|
|
322
331
|
? clean({...identity(row),ts:stamp(),kind:'session',text:sessionText(row)}) : undefined);
|
|
323
332
|
if (initialSession) events.unshift(initialSession);
|
|
324
333
|
}
|
|
325
334
|
emit(row,events,out);
|
|
326
|
-
} else if (startup && skipped) skipped.push(...events);
|
|
335
|
+
} else if (!row.hidden && startup && skipped) skipped.push(...events);
|
|
327
336
|
if (row.inScopeNow===undefined) row.inScopeNow=lineGate(row);
|
|
328
337
|
if (lineGate(row)) await ensureShellRoot(row,out);
|
|
329
338
|
if (seenAtStart.has(row.file)) seenAtStart.get(row.file).cwd=row.cwd;
|
|
@@ -431,8 +440,7 @@ export function createWatcher({options, homes, scope: initialScope, git, now, re
|
|
|
431
440
|
const updates = probe ? [] : await scanDispatch();
|
|
432
441
|
for (const file of pending.keys()) if (!await details(file)) pending.delete(file);
|
|
433
442
|
for (const [platform, handler] of TRANSCRIPT_HANDLERS) {
|
|
434
|
-
|
|
435
|
-
if (home && platforms.includes(platform)) await handler.discover({platform,home,startup,out,rows});
|
|
443
|
+
if (tracked.has(platform)) await handler.discover({platform,home:homes[platform],startup,out,rows});
|
|
436
444
|
}
|
|
437
445
|
rows.sort((a,b)=>b.mtimeMs-a.mtimeMs||a.file.localeCompare(b.file));
|
|
438
446
|
let remaining=rows.filter(row=> {
|
|
@@ -442,6 +450,7 @@ export function createWatcher({options, homes, scope: initialScope, git, now, re
|
|
|
442
450
|
return !previous || row.size>previous.size || pending.has(row.file);
|
|
443
451
|
});
|
|
444
452
|
for (const row of remaining) {
|
|
453
|
+
row.hidden=!platforms.includes(row.platform);
|
|
445
454
|
const previous=detached.get(row.file) ?? seenAtStart.get(row.file);
|
|
446
455
|
if (startup || !previous || row.size>previous.size) {
|
|
447
456
|
const extract=TRANSCRIPT_HANDLERS.get(row.platform).lineCwd;
|
|
@@ -458,10 +467,13 @@ export function createWatcher({options, homes, scope: initialScope, git, now, re
|
|
|
458
467
|
for(const row of remaining) {
|
|
459
468
|
if (!eligible(row)) {next.push(row);continue;}
|
|
460
469
|
if (!probe && followed.size>=L.maxFollowed) {
|
|
461
|
-
const
|
|
462
|
-
if (
|
|
463
|
-
|
|
464
|
-
|
|
470
|
+
const peers=[...followed.values()].filter(followedRow=>followedRow.hidden===row.hidden);
|
|
471
|
+
if (peers.length>=L.maxFollowed) {
|
|
472
|
+
const oldest=peers.sort((a,b)=>a.mtimeMs-b.mtimeMs)[0];
|
|
473
|
+
if (!row.hidden && !capped) {out.push(notice('following the newest 64 sessions; others are skipped'));capped=true;}
|
|
474
|
+
if (oldest.mtimeMs>=row.mtimeMs || row.parentId===oldest.id) continue;
|
|
475
|
+
followed.delete(oldest.id); detached.set(oldest.file,{file:oldest.file,platform:oldest.platform,offset:oldest.tail.offset,size:oldest.size,cwd:oldest.cwd});
|
|
476
|
+
}
|
|
465
477
|
}
|
|
466
478
|
await attach(row,startup,out,skipped);progress=true;
|
|
467
479
|
}
|
|
@@ -474,7 +486,10 @@ export function createWatcher({options, homes, scope: initialScope, git, now, re
|
|
|
474
486
|
if (row.parentId && (!missingParent || chain.desktop)) pending.delete(row.file);
|
|
475
487
|
if (row.parentId && row.origin!=='Codex Desktop' && missingParent && !chain.desktop) {
|
|
476
488
|
const wait=pending.get(row.file) ?? {...row,until:now()+L.holdMs};
|
|
477
|
-
if (now()>=wait.until) {
|
|
489
|
+
if (now()>=wait.until) {
|
|
490
|
+
pending.delete(row.file);ignored.set(row.file,row.size);
|
|
491
|
+
if (!row.hidden) debug(out,`parent session not found for ${row.id}`);
|
|
492
|
+
}
|
|
478
493
|
else pending.set(row.file,wait);
|
|
479
494
|
}
|
|
480
495
|
}
|
|
@@ -482,7 +497,7 @@ export function createWatcher({options, homes, scope: initialScope, git, now, re
|
|
|
482
497
|
for (const row of followed.values()) {
|
|
483
498
|
const ref=mapped(row);
|
|
484
499
|
if (ref && row.dispatchId!==ref.dispatchId) {
|
|
485
|
-
if (row.emitted) out.push(notice(`session ${row.id.slice(0,8)} is dispatch ${ref.dispatchId} (${ref.role??'dispatch'})`));
|
|
500
|
+
if (!row.hidden && row.emitted) out.push(notice(`session ${row.id.slice(0,8)} is dispatch ${ref.dispatchId} (${ref.role??'dispatch'})`));
|
|
486
501
|
row.dispatchId=ref.dispatchId;
|
|
487
502
|
}
|
|
488
503
|
emit(row,[],out);
|
|
@@ -496,22 +511,28 @@ export function createWatcher({options, homes, scope: initialScope, git, now, re
|
|
|
496
511
|
try { result=await row.tail.poll(); }
|
|
497
512
|
catch (error) {
|
|
498
513
|
followed.delete(id);ignored.set(row.file,row.size);
|
|
499
|
-
debug(out,`session file unreadable: ${row.id.slice(0,8)} (${error.code??'error'})`);
|
|
514
|
+
if (!row.hidden) debug(out,`session file unreadable: ${row.id.slice(0,8)} (${error.code??'error'})`);
|
|
515
|
+
continue;
|
|
516
|
+
}
|
|
517
|
+
if (result.gone) {
|
|
518
|
+
followed.delete(id);
|
|
519
|
+
if (!row.hidden) debug(out,`session file removed: ${row.id.slice(0,8)}`);
|
|
520
|
+
continue;
|
|
500
521
|
}
|
|
501
|
-
if (result.gone) {followed.delete(id);debug(out,`session file removed: ${row.id.slice(0,8)}`);continue;}
|
|
502
522
|
if (result.reset) {
|
|
503
523
|
row.state=TRANSCRIPT_HANDLERS.get(row.platform).createState();row.active=false;
|
|
504
524
|
await setCwd(row,row.headCwd,out);row.inScopeNow=lineGate(row);
|
|
505
|
-
debug(out,`session restarted from the beginning: ${row.id.slice(0,8)}`);
|
|
525
|
+
if (!row.hidden) debug(out,`session restarted from the beginning: ${row.id.slice(0,8)}`);
|
|
506
526
|
}
|
|
507
|
-
if (result.overflowed && !row.overflowed) debug(out,`line over 4 MiB skipped in ${row.id.slice(0,8)}`);
|
|
527
|
+
if (!row.hidden && result.overflowed && !row.overflowed) debug(out,`line over 4 MiB skipped in ${row.id.slice(0,8)}`);
|
|
508
528
|
row.overflowed=result.overflowed;
|
|
509
529
|
row.size=row.tail.offset;
|
|
510
530
|
const {events,sawInScope}=await normalize(row,result.lines,true,out);
|
|
511
531
|
if (sawInScope) row.lastActivity=now();
|
|
512
532
|
emit(row,events,out);
|
|
513
533
|
if (now()-row.lastActivity>=L.idleDetachMs && !row.held.length) {
|
|
514
|
-
followed.delete(id);detached.set(row.file,{file:row.file,platform:row.platform,offset:row.tail.offset,size:row.size,cwd:row.cwd});
|
|
534
|
+
followed.delete(id);detached.set(row.file,{file:row.file,platform:row.platform,offset:row.tail.offset,size:row.size,cwd:row.cwd});
|
|
535
|
+
if (!row.hidden) debug(out,`detached idle session ${row.id.slice(0,8)}`);
|
|
515
536
|
}
|
|
516
537
|
}
|
|
517
538
|
}
|
|
@@ -635,11 +656,11 @@ export function createWatcher({options, homes, scope: initialScope, git, now, re
|
|
|
635
656
|
return markEmitted(sort(out));
|
|
636
657
|
},
|
|
637
658
|
listActivity() {
|
|
638
|
-
return [...followed.values()].map(row=>({
|
|
659
|
+
return [...followed.values()].filter(row=>!row.hidden).map(row=>({
|
|
639
660
|
platform:row.platform,mtimeMs:row.mtimeMs,cwd:row.latestCwd ?? row.cwd,main:!row.parentId,
|
|
640
661
|
}));
|
|
641
662
|
},
|
|
642
|
-
busy() {return [...followed.values()].some(row
|
|
663
|
+
busy() {return [...followed.values()].some(row=>!row.hidden && row.active && (row.inScopeNow || mapped(row)) && now()-row.lastActivity<=L.spinnerIdleMs);},
|
|
643
664
|
async close() {closed=true;followed.clear();pending.clear();earlierBacklog=undefined;},
|
|
644
665
|
};
|
|
645
666
|
}
|
package/package.json
CHANGED
|
@@ -2,6 +2,7 @@ import path from 'node:path';
|
|
|
2
2
|
import {fingerprintRequest} from './store.mjs';
|
|
3
3
|
import {validateGitPreflight,validateGitCommitResult} from './git-evidence.mjs';
|
|
4
4
|
import {within} from './scope.mjs';
|
|
5
|
+
import {canonicalCooperativeRole} from './operations.mjs';
|
|
5
6
|
const reconciliations=new WeakMap();
|
|
6
7
|
export function verifiedCooperativeReconciliation(decision,state){const proof=reconciliations.get(decision);return !!proof&&proof.before===fingerprintRequest(state)&&proof.after===fingerprintRequest(decision.proposedTransition);}
|
|
7
8
|
const completed=(state,id)=>state.tasks?.some(t=>t.id===id&&t.status==='committed'&&!t.invalidated)&&state.commits?.some(c=>c.taskId===id&&c.observationSource==='local-git'&&state.intents.some(i=>i.operation==='commit'&&i.requestId===c.requestId&&i.taskId===id&&i.status==='succeeded'));
|
|
@@ -20,9 +21,9 @@ function checkEvidence(state,task,a,changes){
|
|
|
20
21
|
if(!same(a.criteria,task.criteria)||!task.criteria.length||!list(a.checkIds)||!list(a.findingIds)||a.changeFingerprint!==changes?.tasks?.[task.id])return false;
|
|
21
22
|
const checks=state.checks.filter(c=>c.scope==='task'&&c.taskId===task.id);
|
|
22
23
|
const latest=task.requiredChecks.map(d=>checks.filter(c=>same(c.descriptor,d)).at(-1));
|
|
23
|
-
if(!task.requiredChecks.length||latest.some(c=>!c||c.stale||c.status!=='passed'||c.verdict!=='proven'||!text(c.resultRef)||c.source!=='operator-attested'||c.verificationActor?.role!=='
|
|
24
|
+
if(!task.requiredChecks.length||latest.some(c=>!c||c.stale||c.status!=='passed'||c.verdict!=='proven'||!text(c.resultRef)||c.source!=='operator-attested'||canonicalCooperativeRole(c.verificationActor?.role)!=='tester'||!text(c.verificationActor.id)||state.assignments.some(a=>a.agentId===c.verificationActor.id)||c.changeFingerprint!==a.changeFingerprint)||!exact(a.checkIds,latest.map(c=>c?.id)))return false;
|
|
24
25
|
const findings=state.findings.filter(f=>f.scope==='task'&&f.taskId===task.id);
|
|
25
|
-
return exact(a.findingIds,findings.map(f=>f.id))&&findings.every(f=>f.status==='closed'&&text(f.resolutionRef)&&text(f.recheckRef)&&f.resolutionActor?.role==='implementer'&&f.recheckActor?.role==='
|
|
26
|
+
return exact(a.findingIds,findings.map(f=>f.id))&&findings.every(f=>f.status==='closed'&&text(f.resolutionRef)&&text(f.recheckRef)&&f.resolutionActor?.role==='implementer'&&canonicalCooperativeRole(f.recheckActor?.role)==='tester'&&f.changeFingerprint===a.changeFingerprint);
|
|
26
27
|
}
|
|
27
28
|
function waitingFor(state,task,predecessor){
|
|
28
29
|
if(task.status!=='pending'||state.intents.some(i=>i.taskId===task.id&&i.operation==='assign-agent'&&['prepared','unknown','mismatch','succeeded'].includes(i.status)))return false;
|
|
@@ -34,7 +35,7 @@ function freshAcceptance(state,task,acceptance,changes){return acceptance&&!acce
|
|
|
34
35
|
export function evaluateCooperativeAcceptance({state,request,evidence}={}){
|
|
35
36
|
const task=state?.tasks?.find(t=>t.id===request?.taskId),a=request?.arguments,g=evidence?.git;
|
|
36
37
|
if(request?.expectedRevision!==state?.revision||request.actor?.role!=='orchestrator'||!authorized(state,task)||task.status!=='pending'||state.acceptances.some(v=>v.taskId===task.id&&!v.stale)||state.commits.some(v=>v.taskId===task.id))return hold(state,'Current pending approved task and Orchestrator acceptance required');
|
|
37
|
-
if(!fields(a,['messageRef','criteria','checkIds','findingIds','changeFingerprint'])||!text(a.messageRef)||!checkEvidence(state,task,a,evidence?.changes)||state.checks.some(c=>a.checkIds?.includes(c.id)&&c.verificationActor?.id===request.actor.id))return hold(state,'Exact criteria, current required
|
|
38
|
+
if(!fields(a,['messageRef','criteria','checkIds','findingIds','changeFingerprint'])||!text(a.messageRef)||!checkEvidence(state,task,a,evidence?.changes)||state.checks.some(c=>a.checkIds?.includes(c.id)&&c.verificationActor?.id===request.actor.id))return hold(state,'Exact criteria, current required Tester checks and closed findings required');
|
|
38
39
|
const descriptor={kind:'task',parent:state.target.head,indexTree:g?.indexTree,fingerprint:g?.stagedFingerprint,paths:g?.stagedPaths};
|
|
39
40
|
const invalid=validateGitPreflight({target:state.target,descriptor,scope:task.paths,gitEvidence:g});
|
|
40
41
|
if(invalid||dirtyOtherTask(state,task,g))return hold(state,invalid??'Index includes another task changes');
|
|
@@ -1,14 +1,14 @@
|
|
|
1
1
|
import fs from 'node:fs/promises';
|
|
2
2
|
import path from 'node:path';
|
|
3
3
|
import crypto from 'node:crypto';
|
|
4
|
-
import {validateCooperativeCommand,validateCooperativeState} from './cooperative-schema.mjs';
|
|
4
|
+
import {legacyCooperativeRoleDenial,validateCooperativeCommand,validateCooperativeState} from './cooperative-schema.mjs';
|
|
5
5
|
import {observeCooperativeTarget,validateObservedTarget,validateWorkflowId,workflowStatePath,inspectPath} from './scope.mjs';
|
|
6
6
|
import {saveDurableState} from './store.mjs';
|
|
7
7
|
export const COOPERATIVE_RUNTIME_MODULES=Object.freeze([
|
|
8
8
|
'cli.mjs','command.mjs','bootstrap.mjs','cooperative-schema.mjs','cooperative.mjs','evaluate.mjs',
|
|
9
9
|
'scope.mjs','store.mjs','git-evidence.mjs','assignment.mjs','verification.mjs','acceptance.mjs','external.mjs','schema.mjs','operations.mjs','gate.mjs','adapters/codex.mjs','adapters/claude.mjs','capabilities.mjs','identity.mjs','git-query.mjs','target-preparation.mjs',
|
|
10
10
|
'local-cli.mjs','role-routing-config.mjs','role-routing.mjs','role-bridge.mjs',
|
|
11
|
-
'role-dispatch-policy.mjs','role-dispatch-store.mjs','role-bridge-args.mjs','role-observe.mjs','role-supervisor.mjs','platform-registry.mjs','gemini-stream.mjs','grok-stream.mjs','grok-sandbox.mjs'
|
|
11
|
+
'role-dispatch-policy.mjs','role-dispatch-store.mjs','role-bridge-args.mjs','role-observe.mjs','role-supervisor.mjs','platform-registry.mjs','gemini-stream.mjs','grok-stream.mjs','grok-sandbox.mjs','tool-access.mjs','host-service.mjs'
|
|
12
12
|
]);
|
|
13
13
|
export const cooperativeCoverage=()=>({enforcement:'cooperative',provenance:'operator-attested',nativeVerified:false});
|
|
14
14
|
export function commandResult({workflowId,state,input,decision='allow',ruleId='cooperative.recorded',persisted=false,...extra}){
|
|
@@ -22,6 +22,8 @@ export async function cooperativeVersions(){
|
|
|
22
22
|
}
|
|
23
23
|
export async function initializeCooperativeWorkflow({cwd,workflowId,input,observe=observeCooperativeTarget,storage={}}){
|
|
24
24
|
validateWorkflowId(workflowId);validateCooperativeCommand({command:'init',input});
|
|
25
|
+
const denial=legacyCooperativeRoleDenial(input);
|
|
26
|
+
if(denial)return commandResult({workflowId,input,...denial});
|
|
25
27
|
if(input.mode!=='plan')return commandResult({workflowId,input,decision:'hold',ruleId:'cooperative.unsupported'});
|
|
26
28
|
const target=await validateObservedTarget(cwd,await observe(cwd));const statePath=await workflowStatePath(target,workflowId);
|
|
27
29
|
const parent=path.dirname(statePath);await fs.mkdir(parent,{recursive:true,mode:0o700});await inspectPath(parent,{directory:true});
|
|
@@ -3,11 +3,37 @@ import path from 'node:path';
|
|
|
3
3
|
import os from 'node:os';
|
|
4
4
|
import {initializeCooperativeWorkflow,commandResult} from './bootstrap.mjs';
|
|
5
5
|
import {runCooperativeCommand} from './cooperative.mjs';
|
|
6
|
-
import {validateWorkflowId} from './scope.mjs';
|
|
6
|
+
import {absolute,validateWorkflowId} from './scope.mjs';
|
|
7
|
+
import {writeHandoffRecord} from './handoff-record.mjs';
|
|
7
8
|
import {prepareRoleDispatch,routingStatus,invalidRoutingRequest} from './role-routing.mjs';
|
|
8
9
|
import {runBridgeDispatch,recordRoleObservation,resumeRoleDispatch,cancelRoleDispatch,heldRoutingResult} from './role-bridge.mjs';
|
|
10
|
+
async function runHandoffRecordCommand([command,...args],io,output){
|
|
11
|
+
const options={};
|
|
12
|
+
try{
|
|
13
|
+
if(command!=='write')throw Error('Expected handoff-record write');
|
|
14
|
+
for(let i=0;i<args.length;i+=2){
|
|
15
|
+
const key=args[i];
|
|
16
|
+
if(!['--cwd','--slug','--input'].includes(key)||options[key]!==undefined||typeof args[i+1]!=='string')throw Error('Invalid handoff-record option');
|
|
17
|
+
options[key]=args[i+1];
|
|
18
|
+
}
|
|
19
|
+
const cwd=options['--cwd'],slug=options['--slug'];
|
|
20
|
+
if(!absolute(cwd))throw Error('Absolute workspace required');
|
|
21
|
+
if(slug===undefined||options['--input']!=='-')throw Error('Handoff record write requires --slug and --input -');
|
|
22
|
+
const rawInput=io.input??fs.readFileSync(0,'utf8');
|
|
23
|
+
let input;
|
|
24
|
+
try{input=JSON.parse(rawInput);}catch{throw Error('Expected JSON handoff input');}
|
|
25
|
+
if(typeof input?.content!=='string'||!input.content.length)throw Error('Expected nonempty handoff content');
|
|
26
|
+
const result=await writeHandoffRecord({cwd,slug,content:input.content});
|
|
27
|
+
output.write(JSON.stringify(result)+'\n');
|
|
28
|
+
return result.decision==='deny'?2:result.decision==='hold'?3:0;
|
|
29
|
+
}catch(error){
|
|
30
|
+
output.write(JSON.stringify({decision:'hold',reasonCode:'handoff_write_failed',message:error.message,fallback:'inline'})+'\n');
|
|
31
|
+
return 1;
|
|
32
|
+
}
|
|
33
|
+
}
|
|
9
34
|
export async function runWorkflowCommand(args,io={}){
|
|
10
35
|
const output=io.output??process.stdout;let workflowId=null,isRouting=false;
|
|
36
|
+
if(args[0]==='handoff-record')return runHandoffRecordCommand(args.slice(1),io,output);
|
|
11
37
|
try{
|
|
12
38
|
const [command,...rest]=args,options={};
|
|
13
39
|
isRouting=['routing-status','prepare-dispatch','run-dispatch','observe','resume','cancel'].includes(command);
|
|
@@ -25,9 +51,9 @@ export async function runWorkflowCommand(args,io={}){
|
|
|
25
51
|
if(isRouting){
|
|
26
52
|
if(!input||typeof input!=='object'||Array.isArray(input))throw Error('Invalid routing input');
|
|
27
53
|
const context={cwd,userHome:os.homedir(),env:process.env,workflowId,hostPlatform:input.hostPlatform,executionEnvironment:input.executionEnvironment};
|
|
28
|
-
const keys=Object.keys(input),allowed={'routing-status':[['hostPlatform','executionEnvironment'],[]],'prepare-dispatch':[['hostPlatform','executionEnvironment','role','expectedRevision','requestId','taskId'],['allowedPaths']],'run-dispatch':[['hostPlatform','executionEnvironment','dispatchId','brief'],[]],observe:[['hostPlatform','executionEnvironment','dispatchId'],['waitMs','event','nativeAgentId']],resume:[['hostPlatform','executionEnvironment','dispatchId','brief'],[]],cancel:[['hostPlatform','executionEnvironment','dispatchId'],[]]}[command];
|
|
54
|
+
const keys=Object.keys(input),allowed={'routing-status':[['hostPlatform','executionEnvironment'],[]],'prepare-dispatch':[['hostPlatform','executionEnvironment','role','expectedRevision','requestId','taskId'],['allowedPaths','toolAccess']],'run-dispatch':[['hostPlatform','executionEnvironment','dispatchId','brief'],[]],observe:[['hostPlatform','executionEnvironment','dispatchId'],['waitMs','event','nativeAgentId']],resume:[['hostPlatform','executionEnvironment','dispatchId','brief'],[]],cancel:[['hostPlatform','executionEnvironment','dispatchId'],[]]}[command];
|
|
29
55
|
if(allowed&&(allowed[0].some(key=>!Object.hasOwn(input,key))||keys.some(key=>!allowed[0].includes(key)&&!allowed[1].includes(key))))result=invalidRoutingRequest(context);
|
|
30
|
-
else result=command==='routing-status'?await routingStatus({context}):command==='prepare-dispatch'?await prepareRoleDispatch({context,assignment:{role:input.role,requestId:input.requestId,taskId:input.taskId,...(Object.hasOwn(input,'allowedPaths')?{allowedPaths:input.allowedPaths}:{})},expectedRevision:input.expectedRevision}):command==='run-dispatch'?await runBridgeDispatch({context,dispatchId:input.dispatchId,brief:input.brief}):command==='observe'?await recordRoleObservation({context,dispatchId:input.dispatchId,...(Object.hasOwn(input,'waitMs')?{waitMs:input.waitMs}:{}),...(Object.hasOwn(input,'event')?{event:input.event}:{}),...(Object.hasOwn(input,'nativeAgentId')?{nativeAgentId:input.nativeAgentId}:{})}):command==='resume'?await resumeRoleDispatch({context,dispatchId:input.dispatchId,brief:input.brief}):await cancelRoleDispatch({context,dispatchId:input.dispatchId});
|
|
56
|
+
else result=command==='routing-status'?await routingStatus({context}):command==='prepare-dispatch'?await prepareRoleDispatch({context,assignment:{role:input.role,requestId:input.requestId,taskId:input.taskId,...(Object.hasOwn(input,'allowedPaths')?{allowedPaths:input.allowedPaths}:{}),...(Object.hasOwn(input,'toolAccess')?{toolAccess:input.toolAccess}:{})},expectedRevision:input.expectedRevision}):command==='run-dispatch'?await runBridgeDispatch({context,dispatchId:input.dispatchId,brief:input.brief}):command==='observe'?await recordRoleObservation({context,dispatchId:input.dispatchId,...(Object.hasOwn(input,'waitMs')?{waitMs:input.waitMs}:{}),...(Object.hasOwn(input,'event')?{event:input.event}:{}),...(Object.hasOwn(input,'nativeAgentId')?{nativeAgentId:input.nativeAgentId}:{})}):command==='resume'?await resumeRoleDispatch({context,dispatchId:input.dispatchId,brief:input.brief}):await cancelRoleDispatch({context,dispatchId:input.dispatchId});
|
|
31
57
|
result={workflowId,...result};
|
|
32
58
|
}else result=await(command==='init'?initializeCooperativeWorkflow({cwd,workflowId,input}):runCooperativeCommand({cwd,workflowId,command,input}));
|
|
33
59
|
output.write(JSON.stringify(result)+'\n');return result.decision==='deny'?2:result.decision==='hold'?3:0;
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import {ROLES} from './operations.mjs';
|
|
1
|
+
import {ROLES,canonicalCooperativeRole,hasNewStoredOperationAliases,isLegacyOperation,normalizeStoredOperations} from './operations.mjs';
|
|
2
2
|
import {assertSecretFree} from './external.mjs';
|
|
3
3
|
import {object,text,validatePlannerLedger} from './schema.mjs';
|
|
4
4
|
import {absolute,validateWorkflowId} from './scope.mjs';
|
|
@@ -6,10 +6,17 @@ import {validateTargetPreparationRecord} from './target-preparation.mjs';
|
|
|
6
6
|
const fail=message=>{throw Error('Cooperative schema: '+message);};
|
|
7
7
|
const hash=value=>typeof value==='string'&&/^sha256:[a-f0-9]{64}$/.test(value);
|
|
8
8
|
const revision=value=>Number.isSafeInteger(value)&&value>=0;
|
|
9
|
-
const actor=value=>object(value)&&text(value.id)&&Object.keys(value).every(k=>['id','role'].includes(k))&&(value.role===undefined||ROLES.includes(value.role));
|
|
9
|
+
const actor=value=>object(value)&&text(value.id)&&Object.keys(value).every(k=>['id','role'].includes(k))&&(value.role===undefined||ROLES.includes(canonicalCooperativeRole(value.role)));
|
|
10
10
|
const statement=value=>object(value)&&text(value.messageRef)&&object(value.data);
|
|
11
11
|
function fields(value,allowed){if(!object(value)||Object.keys(value).some(k=>!allowed.includes(k)))fail('unexpected input field');}
|
|
12
12
|
function json(value){try{const encoded=JSON.stringify(value);if(encoded===undefined)fail('JSON input');}catch{fail('JSON input');}}
|
|
13
|
+
export function legacyCooperativeRoleDenial(input){
|
|
14
|
+
let ruleId;
|
|
15
|
+
if(input?.actor?.role==='qa')ruleId='cooperative.verification-actor';
|
|
16
|
+
else if(input?.arguments?.actor?.role==='qa'||input?.result?.data?.actor?.role==='qa')ruleId='cooperative.verification-independence';
|
|
17
|
+
else if(input?.evidence?.kind==='finding'&&input.evidence.data?.actor?.role==='qa')ruleId='cooperative.finding-resolution';
|
|
18
|
+
if(ruleId)return {decision:'deny',ruleIds:[ruleId],reason:'legacy_role_qa'};
|
|
19
|
+
}
|
|
13
20
|
export function validateCooperativeCommand(command){
|
|
14
21
|
assertSecretFree(command);fields(command,['command','input']);const {input,command:name}=command;
|
|
15
22
|
if(!['init','record','status','reconcile','prepare','result'].includes(name))fail('command');
|
|
@@ -17,6 +24,7 @@ export function validateCooperativeCommand(command){
|
|
|
17
24
|
const resultStatement=name==='reconcile'||name==='result'&&input?.operation===undefined;
|
|
18
25
|
const allowed=name==='init'?['mode','actor','selection']:name==='record'?['requestId','expectedRevision','actor','evidence']:resultStatement?['requestId','expectedRevision','actor','intentId','result']:['requestId','expectedRevision','actor','operation','taskId','arguments'];
|
|
19
26
|
fields(input,allowed);json(input);
|
|
27
|
+
// Recognize this input shape so command entry points can return the role denial.
|
|
20
28
|
if(!actor(input.actor))fail('actor attestation');
|
|
21
29
|
if(name==='init'){
|
|
22
30
|
if(!['plan','no-plan','small-task'].includes(input.mode)||!object(input.selection)||!text(input.selection.messageRef)||!hash(input.selection.contentHash)||Object.keys(input.selection).some(k=>!['messageRef','contentHash'].includes(k)))fail('target selection');
|
|
@@ -33,10 +41,10 @@ export function validateCooperativeCommand(command){
|
|
|
33
41
|
if(!text(input.intentId)||!statement(input.result)||!['succeeded','failed','unknown','mismatch','cancelled'].includes(input.result.status))fail('result evidence');
|
|
34
42
|
if(input.result.status==='cancelled'&&(!object(input.result.notExecutedEvidence)||!text(input.result.notExecutedEvidence.messageRef)))fail('cancel requires not-executed evidence');
|
|
35
43
|
}
|
|
36
|
-
if((name==='prepare'||name==='result'&&!resultStatement)
|
|
44
|
+
if((name==='prepare'||name==='result'&&!resultStatement)&&(!text(input.operation)||isLegacyOperation(input.operation)))fail('operation');
|
|
37
45
|
return command;
|
|
38
46
|
}
|
|
39
|
-
export function validateCooperativeState(state){
|
|
47
|
+
export function validateCooperativeState(state,{allowLegacyOperations=true,preserveStoredOperations=false,legacyOperationsFrom}={}){
|
|
40
48
|
if(!object(state)||state.workflowKind!=='cooperative'||state.contractVersion!==1||state.schemaVersion!==1||!revision(state.revision)||state.mode!=='plan')fail('explicit cooperative contract');
|
|
41
49
|
validateWorkflowId(state.workflowId);
|
|
42
50
|
if(!object(state.target)||!absolute(state.target.realpath)||!absolute(state.target.gitCommonDir)||!absolute(state.target.gitDir)||!/^(?:[a-f0-9]{40}|[a-f0-9]{64})$/.test(state.target.head)||!(state.target.branch===null||text(state.target.branch)))fail('target');
|
|
@@ -60,5 +68,8 @@ export function validateCooperativeState(state){
|
|
|
60
68
|
for(const checkpoint of checkpoints){try{validateTargetPreparationRecord('checkpoint',{type:'checkpoint',...checkpoint});}catch{fail('target checkpoint');}if(checkpoint.source!=='operator-attested'||!text(checkpoint.messageRef)||!preparationIntents.some(i=>i.id===checkpoint.intentId&&i.firstStageId===checkpoint.stageId)||!state.records.some(r=>r.kind==='target-preparation'&&r.messageRef===checkpoint.messageRef&&r.source==='operator-attested'))fail('target checkpoint provenance');}
|
|
61
69
|
for(const transition of transitions){const request=transition.validation?.request;try{validateTargetPreparationRecord('transition',request);}catch{fail('target transition');}if(!object(transition.target)||!text(transition.messageRef)||!Number.isSafeInteger(transition.targetVersion)||transition.targetVersion!==transition.sourceTargetVersion+1||request.intentId!==transition.intentId||request.checkpointRef!==transition.checkpointRef||!preparationIntents.some(i=>i.id===transition.intentId)||!checkpoints.some(c=>c.intentId===transition.intentId&&c.messageRef===transition.checkpointRef)||!state.records.some(r=>r.kind==='target-preparation'&&r.messageRef===transition.messageRef&&r.source==='operator-attested'))fail('target transition provenance');}
|
|
62
70
|
for(const document of documents){try{validateTargetPreparationRecord('destination',document);}catch{fail('target document');}if(document.sourceLink!=='operator-attested'||document.verification?.status!=='verified'||document.verification?.source!=='local-bytes'||!text(document.messageRef)||!transitions.some(t=>t.intentId===document.intentId&&t.messageRef===document.transitionRef&&t.targetVersion===document.targetVersion)||!state.records.some(r=>r.kind==='target-preparation'&&r.messageRef===document.messageRef&&r.source==='operator-attested'))fail('target document provenance');}
|
|
63
|
-
assertSecretFree(state);json(state);
|
|
71
|
+
assertSecretFree(state);json(state);
|
|
72
|
+
const normalized=normalizeStoredOperations(state);
|
|
73
|
+
if(!allowLegacyOperations&&normalized!==state&&(!legacyOperationsFrom||hasNewStoredOperationAliases(state,legacyOperationsFrom)))fail('legacy operation in new state');
|
|
74
|
+
return preserveStoredOperations?state:normalized;
|
|
64
75
|
}
|
|
@@ -7,7 +7,7 @@ import fs from 'node:fs/promises';
|
|
|
7
7
|
import {constants} from 'node:fs';
|
|
8
8
|
import path from 'node:path';
|
|
9
9
|
import {createHash} from 'node:crypto';
|
|
10
|
-
import {validateCooperativeCommand,validateCooperativeState} from './cooperative-schema.mjs';
|
|
10
|
+
import {legacyCooperativeRoleDenial,validateCooperativeCommand,validateCooperativeState} from './cooperative-schema.mjs';
|
|
11
11
|
import {observeCooperativeTarget,validateObservedTarget,validateWorkflowId,workflowStatePath,inspectPath,absolute,within} from './scope.mjs';
|
|
12
12
|
import {fingerprintRequest,saveDurableState,applyCooperativeCommitTransition,applyCooperativeTargetTransition} from './store.mjs';
|
|
13
13
|
import {commandResult,cooperativeVersions} from './bootstrap.mjs';
|
|
@@ -18,9 +18,11 @@ const sameCheckout=(a,b)=>['realpath','gitCommonDir','gitDir'].every(k=>a[k]===b
|
|
|
18
18
|
/** Only trusted code may inject observation/storage. CLI JSON cannot set either. */
|
|
19
19
|
export async function runCooperativeCommand({cwd,workflowId,command,input,observe=observeCooperativeTarget,storage={},readGit=readAssignmentGitEvidence,readChanges=readCooperativeChanges,readCommitGit=readCooperativeCommitGitEvidence}){
|
|
20
20
|
validateWorkflowId(workflowId);validateCooperativeCommand({command,input});
|
|
21
|
+
const denial=legacyCooperativeRoleDenial(input);
|
|
22
|
+
if(denial)return commandResult({workflowId,input,...denial});
|
|
21
23
|
if(command==='init')throw Error('Use initializeCooperativeWorkflow for init');
|
|
22
24
|
const target=await validateObservedTarget(cwd,await observe(cwd)),statePath=await workflowStatePath(target,workflowId);
|
|
23
|
-
const read=async()=>{await inspectPath(statePath);const state=validateCooperativeState(JSON.parse(await fs.readFile(statePath,'utf8')));if(state.workflowId!==workflowId)throw Error('Workflow identity mismatch');return state;};
|
|
25
|
+
const read=async()=>{await inspectPath(statePath);const state=validateCooperativeState(JSON.parse(await fs.readFile(statePath,'utf8')),{preserveStoredOperations:command!=='status'});if(state.workflowId!==workflowId)throw Error('Workflow identity mismatch');return state;};
|
|
24
26
|
const result=(state,decision,extra={})=>commandResult({workflowId,state,input,...decision,...extra});
|
|
25
27
|
const removedDecision=state=>{const decision=evaluateCooperative({state,request:{command,input}});return decision.ruleIds[0]==='cooperative.plan-amend-removed'?decision:null;};
|
|
26
28
|
if(command==='status'){
|
|
@@ -35,6 +37,7 @@ export async function runCooperativeCommand({cwd,workflowId,command,input,observ
|
|
|
35
37
|
let lock,plannerLock;
|
|
36
38
|
try{
|
|
37
39
|
lock=await fs.open(statePath+'.lock','wx',0o600);let state=await read();
|
|
40
|
+
const previousOperations={approvals:[...state.approvals],assignments:[...state.assignments],audit:[...state.audit]};
|
|
38
41
|
const removed=removedDecision(state);if(removed)return result(state,removed);
|
|
39
42
|
const plannerWork=command==='prepare'&&input.operation==='planner-call'||command==='record'&&input.evidence.kind.startsWith('planner-');
|
|
40
43
|
if(plannerWork)plannerLock=await fs.open(path.join(target.gitCommonDir,'arc','planner.lock'),'wx',0o600);
|
|
@@ -182,7 +185,7 @@ export async function runCooperativeCommand({cwd,workflowId,command,input,observ
|
|
|
182
185
|
const output=result(state,decision,{persisted:true});
|
|
183
186
|
state.requests.push({requestId:input.requestId,requestFingerprint,request:structuredClone({command,input}),decision:output});
|
|
184
187
|
state.audit.push({command,requestId:input.requestId,revision:state.revision,decision:output.decision,ruleIds:output.ruleIds,source:'operator-attested',actor:input.actor,...(input.intentId?{intentId:input.intentId,resolution:state.results.at(-1)?.status}:{}),...(input.operation?{operation:input.operation}:{})});
|
|
185
|
-
validateCooperativeState(state);await inspectPath(statePath);await saveDurableState({statePath,state,storage});return output;
|
|
188
|
+
validateCooperativeState(state,{allowLegacyOperations:false,legacyOperationsFrom:previousOperations});await inspectPath(statePath);await saveDurableState({statePath,state,storage});return output;
|
|
186
189
|
}finally{if(plannerLock){await plannerLock.close();await fs.unlink(path.join(target.gitCommonDir,'arc','planner.lock'));}if(lock){await lock.close();await fs.unlink(statePath+'.lock');}}
|
|
187
190
|
}
|
|
188
191
|
|
|
@@ -14,20 +14,21 @@ import {prepareCooperativeAssignment} from './assignment.mjs';
|
|
|
14
14
|
* @property {object} coverage
|
|
15
15
|
*/
|
|
16
16
|
import path from 'node:path';
|
|
17
|
-
import {validateCooperativeState,validateCooperativeCommand} from './cooperative-schema.mjs';
|
|
17
|
+
import {legacyCooperativeRoleDenial,validateCooperativeState,validateCooperativeCommand} from './cooperative-schema.mjs';
|
|
18
18
|
import {validateWorkflowState, validateRequest, validateEvidence,validatePlannerStage} from './schema.mjs';
|
|
19
|
-
import {ROLES, ROLE_OPERATIONS, GIT_OPERATIONS, EXTERNAL_OPERATIONS} from './operations.mjs';
|
|
19
|
+
import {ROLES, ROLE_OPERATIONS, GIT_OPERATIONS, EXTERNAL_OPERATIONS, canonicalCooperativeRole} from './operations.mjs';
|
|
20
20
|
const same=(a,b)=>JSON.stringify(a)===JSON.stringify(b);
|
|
21
21
|
const within=(base,file)=>{const relative=path.relative(base,file);return relative===''||(!relative.startsWith('..'+path.sep)&&relative!=='..'&&!path.isAbsolute(relative));};
|
|
22
22
|
/** Pure policy decision. Evidence is supplied by a trusted adapter/provider, never tool arguments. */
|
|
23
23
|
export function evaluate(policy, state, request, evidence){
|
|
24
|
+
const stored=state;
|
|
24
25
|
const result=(decision,id,reason,requiredEvidence=[])=>({decision,ruleIds:[id],reason,requiredEvidence,expectedRevision:state?.revision??0,proposedTransition:null,coverage:{platform:request?.platform??'unknown',enforcement:'decision-only'}});
|
|
25
|
-
try{validateWorkflowState(state);validateRequest(request);validateEvidence(evidence);}catch(error){return result('hold','runtime.schema',error.message,['valid-state-request-evidence']);}
|
|
26
|
+
try{state=validateWorkflowState(state);validateRequest(request);validateEvidence(evidence);}catch(error){return result('hold','runtime.schema',error.message,['valid-state-request-evidence']);}
|
|
26
27
|
if(policy?.runtime?.schemaVersion!==1||!same(policy.runtime.roles,ROLES)||!Array.isArray(policy.runtime.ruleIds)||!Array.isArray(policy.runtime.requiredEvidence)||policy.runtime.status!=='decision-only')return result('hold','runtime.policy','runtime policy unavailable',['runtime-policy']);
|
|
27
28
|
const actor=state.identities.find(i=>i.actorRef===request.actorRef);
|
|
28
29
|
if(!actor)return result('hold','runtime.identity','platform identity unresolved',['platform-identity']);
|
|
29
30
|
const role=actor.role;
|
|
30
|
-
const roleRule={orchestrator:'role.orchestrator-boundary',scouter:'role.scouter-read-only',planner:'role.planner-draft-only',implementer:'role.implementer-implementation',
|
|
31
|
+
const roleRule={orchestrator:'role.orchestrator-boundary',scouter:'role.scouter-read-only',planner:'role.planner-draft-only',implementer:'role.implementer-implementation',tester:'role.tester-verification',reviewer:'role.reviewer-independent'}[role]??'runtime.identity';
|
|
31
32
|
if(!ROLE_OPERATIONS[role]?.includes(request.operation))return result('deny',GIT_OPERATIONS.includes(request.operation)?'git.specialists-deny':roleRule,'operation forbidden for assigned role');
|
|
32
33
|
const lease=state.leases.find(l=>l.actorRef===actor.actorRef);
|
|
33
34
|
if(lease?.status==='retired')return result('deny','runtime.identity','retired identity');
|
|
@@ -53,7 +54,7 @@ export function evaluate(policy, state, request, evidence){
|
|
|
53
54
|
if(role==='implementer'&&['accepted','committed'].includes(task.status))return result('deny','runtime.identity','task execution ended');
|
|
54
55
|
if(request.operation==='temporary-write'){
|
|
55
56
|
const temporary=assignment.temporary;
|
|
56
|
-
if(!temporary||temporary.cleanupOwner!==request.actorRef||!Number.isFinite(Date.parse(temporary.expiresAt))||!Number.isFinite(Date.parse(evidence.observedAt))||Date.parse(temporary.expiresAt)<=Date.parse(evidence.observedAt)||!request.paths.every(p=>temporary.paths?.some(base=>within(base,p))))return result('hold','role.
|
|
57
|
+
if(!temporary||temporary.cleanupOwner!==request.actorRef||!Number.isFinite(Date.parse(temporary.expiresAt))||!Number.isFinite(Date.parse(evidence.observedAt))||Date.parse(temporary.expiresAt)<=Date.parse(evidence.observedAt)||!request.paths.every(p=>temporary.paths?.some(base=>within(base,p))))return result('hold','role.tester-verification','temporary scope lifetime and cleanup ownership required',['temporary-assignment']);
|
|
57
58
|
}
|
|
58
59
|
if(request.operation==='check'){
|
|
59
60
|
if(!assignment.checks?.some(c=>same(c,request.descriptor)))return result('hold',roleRule,'exact assigned check descriptor required',['check-descriptor']);
|
|
@@ -82,7 +83,7 @@ export function evaluate(policy, state, request, evidence){
|
|
|
82
83
|
if(d.checks&&(!Array.isArray(approval.scope.checks)||d.checks.some(c=>!approval.scope.checks.some(approved=>same(approved,c)))))return result('hold','runtime.assignment','delegated checks not approved',['delegated-checks']);
|
|
83
84
|
if(d.temporary&&!same(d.temporary,approval.scope.temporary))return result('hold','runtime.assignment','delegated temporary scope not approved',['delegated-temporary-scope']);
|
|
84
85
|
if(state.assignments.some(a=>a.assignmentId===request.requestId||a.correlationRef===d.correlationRef))return result('hold','runtime.identity','assignment correlation already registered',['new-assignment-correlation']);
|
|
85
|
-
const next=structuredClone(
|
|
86
|
+
const next=structuredClone(stored);
|
|
86
87
|
if(d.role==='planner'){
|
|
87
88
|
const stage=state.plannerLedger?.stages.find(s=>s.id===d.plannerCall?.stageId),proof=fact('planner-call');
|
|
88
89
|
const contract=stage&&{document:stage.document,inputVersion:stage.inputVersion,criteriaVersion:stage.criteriaVersion,scopeVersion:stage.scopeVersion};
|
|
@@ -98,7 +99,7 @@ export function evaluate(policy, state, request, evidence){
|
|
|
98
99
|
}
|
|
99
100
|
if(request.operation==='accept'){
|
|
100
101
|
const d=request.descriptor;const observed=fact('acceptance')?.data;
|
|
101
|
-
const checks=Array.isArray(d.checkIds)&&task.requiredChecks?.every(id=>d.checkIds?.includes(id)&&state.checks.some(c=>c.id===id&&c.taskId===task.id&&c.status==='passed'&&c.fingerprint===d.fingerprint&&c.resultRef&&c.actorRef!==actor.actorRef&&state.identities.some(i=>i.actorRef===c.actorRef&&i.taskId===task.id&&i.role==='
|
|
102
|
+
const checks=Array.isArray(d.checkIds)&&task.requiredChecks?.every(id=>d.checkIds?.includes(id)&&state.checks.some(c=>c.id===id&&c.taskId===task.id&&c.status==='passed'&&c.fingerprint===d.fingerprint&&c.resultRef&&c.actorRef!==actor.actorRef&&state.identities.some(i=>i.actorRef===c.actorRef&&i.taskId===task.id&&canonicalCooperativeRole(i.role)==='tester')));
|
|
102
103
|
const findings=state.findings.filter(f=>f.taskId===task.id);
|
|
103
104
|
if(!observed||!same(observed,d)||!d.fingerprint||!task.criteria?.length||!same(task.criteria,d.criteria)||!checks||findings.some(f=>!Array.isArray(d.findingIds)||!d.findingIds.includes(f.id)||!f.resolutionRef))return result('hold','git.orchestrator-accept-commit','criteria checks findings and fingerprint verification required',['acceptance-evidence']);
|
|
104
105
|
}
|
|
@@ -123,6 +124,8 @@ export function evaluateCooperative({policy,state,request,evidence}={}){
|
|
|
123
124
|
const base={expectedRevision:state?.revision??0,coverage:{enforcement:'cooperative',provenance:'operator-attested',nativeVerified:false}};
|
|
124
125
|
const hold=(id,reason)=>({...base,decision:'hold',ruleIds:[id],reason,requiredEvidence:[],nextActions:[],proposedTransition:null});
|
|
125
126
|
try{validateCooperativeState(state);validateCooperativeCommand(request);}catch(error){return hold('cooperative.schema',error.message);}
|
|
127
|
+
const denial=legacyCooperativeRoleDenial(request.input);
|
|
128
|
+
if(denial)return {...base,...denial,requiredEvidence:[],nextActions:[],proposedTransition:null};
|
|
126
129
|
if(state.intents.some(i=>i.operation==='plan-amend'&&['prepared','unknown','mismatch','failed'].includes(i.status)))return {...hold('cooperative.plan-amend-removed','Legacy plan-amend intent is no longer supported; inspect Git history and any refs/arc/recovery/* refs manually, then start a new workflow'),nextActions:['inspect-legacy-plan-amend','start-new-workflow']};
|
|
127
130
|
if(request.command==='prepare'&&request.input?.operation==='plan-amend')return hold('cooperative.plan-amend-removed','Plan-amend operation is no longer supported');
|
|
128
131
|
if(policy!==undefined&&policy.workflowKind!=='cooperative')return hold('cooperative.contract','Explicit cooperative policy required');
|
|
@@ -0,0 +1,58 @@
|
|
|
1
|
+
import fs from 'node:fs/promises';
|
|
2
|
+
import path from 'node:path';
|
|
3
|
+
import {randomUUID} from 'node:crypto';
|
|
4
|
+
import {inspectPath, observeCooperativeTarget, within} from './scope.mjs';
|
|
5
|
+
|
|
6
|
+
export async function writeHandoffRecord({cwd, slug, content}) {
|
|
7
|
+
if (typeof slug !== 'string' || !/^[A-Za-z0-9][A-Za-z0-9._-]{0,127}$/.test(slug) || slug.includes('..')) {
|
|
8
|
+
return {decision: 'deny', reasonCode: 'invalid_slug', message: 'Invalid handoff record slug.'};
|
|
9
|
+
}
|
|
10
|
+
|
|
11
|
+
let gitCommonDir;
|
|
12
|
+
let filename;
|
|
13
|
+
let temporaryFile;
|
|
14
|
+
try {
|
|
15
|
+
if (typeof content !== 'string' || !content.length) throw Error('Expected nonempty handoff content.');
|
|
16
|
+
({gitCommonDir} = await observeCooperativeTarget(cwd));
|
|
17
|
+
const directory = path.join(gitCommonDir, 'arc', 'handoff');
|
|
18
|
+
filename = path.join(directory, `${slug}.md`);
|
|
19
|
+
if (!within(gitCommonDir, filename)) {
|
|
20
|
+
return {decision: 'deny', reasonCode: 'path_outside_common_dir', message: 'Handoff record path must stay inside the Git common directory.'};
|
|
21
|
+
}
|
|
22
|
+
|
|
23
|
+
await inspectPath(filename, {missing: true});
|
|
24
|
+
await fs.mkdir(directory, {recursive: true, mode: 0o700});
|
|
25
|
+
await inspectPath(filename, {missing: true});
|
|
26
|
+
let created = false;
|
|
27
|
+
try {
|
|
28
|
+
await fs.lstat(filename);
|
|
29
|
+
} catch (error) {
|
|
30
|
+
if (error.code !== 'ENOENT') throw error;
|
|
31
|
+
created = true;
|
|
32
|
+
}
|
|
33
|
+
|
|
34
|
+
const candidate = path.join(directory, `.handoff-${randomUUID()}.tmp`);
|
|
35
|
+
const file = await fs.open(candidate, 'wx', 0o600);
|
|
36
|
+
temporaryFile = candidate;
|
|
37
|
+
try {
|
|
38
|
+
await file.writeFile(content, 'utf8');
|
|
39
|
+
await file.sync();
|
|
40
|
+
} finally {
|
|
41
|
+
await file.close();
|
|
42
|
+
}
|
|
43
|
+
await fs.rename(temporaryFile, filename);
|
|
44
|
+
temporaryFile = undefined;
|
|
45
|
+
return {decision: 'allow', path: filename, created};
|
|
46
|
+
} catch (error) {
|
|
47
|
+
if (gitCommonDir && error.symlinkPath && within(gitCommonDir, error.symlinkPath)) {
|
|
48
|
+
const destination = await fs.readlink(error.symlinkPath).catch(() => null);
|
|
49
|
+
if (destination !== null && !within(gitCommonDir, path.resolve(path.dirname(error.symlinkPath), destination))) {
|
|
50
|
+
return {decision: 'deny', reasonCode: 'path_outside_common_dir', message: `Handoff record path must stay inside the Git common directory: ${filename}`};
|
|
51
|
+
}
|
|
52
|
+
}
|
|
53
|
+
const failedPath = error.symlinkPath ?? filename;
|
|
54
|
+
return {decision: 'hold', reasonCode: 'handoff_write_failed', message: failedPath ? `${failedPath}: ${error.message}` : error.message, fallback: 'inline'};
|
|
55
|
+
} finally {
|
|
56
|
+
if (temporaryFile) await fs.rm(temporaryFile, {force: true}).catch(() => {});
|
|
57
|
+
}
|
|
58
|
+
}
|