@yunhozz/arc 0.4.4 → 0.4.6
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 +56 -54
- package/README.md +2 -2
- package/claude/skill/SKILL.md +1 -1
- package/claude/skill/references/commit.md +6 -4
- package/claude/skill/references/coordination.md +87 -10
- package/claude/skill/references/handoff-prep.md +4 -4
- package/claude/skill/references/handoff.md +1 -1
- package/claude/skill/references/planning.md +5 -4
- package/claude/skill/references/verification.md +4 -4
- package/codex/skill/SKILL.md +1 -1
- package/codex/skill/references/commit.md +6 -4
- package/codex/skill/references/coordination.md +87 -10
- package/codex/skill/references/handoff-prep.md +4 -4
- package/codex/skill/references/handoff.md +1 -1
- package/codex/skill/references/planning.md +5 -4
- package/codex/skill/references/verification.md +4 -4
- package/gemini/skill/SKILL.md +1 -1
- package/gemini/skill/references/commit.md +6 -4
- package/gemini/skill/references/coordination.md +88 -11
- package/gemini/skill/references/handoff-prep.md +4 -4
- package/gemini/skill/references/handoff.md +1 -1
- package/gemini/skill/references/planning.md +5 -4
- package/gemini/skill/references/verification.md +4 -4
- package/grok/skill/SKILL.md +1 -1
- package/grok/skill/references/commit.md +6 -4
- package/grok/skill/references/coordination.md +91 -14
- package/grok/skill/references/handoff-prep.md +4 -4
- package/grok/skill/references/handoff.md +1 -1
- package/grok/skill/references/planning.md +5 -4
- package/grok/skill/references/verification.md +4 -4
- package/lib/installer/role-routing.mjs +2 -2
- package/lib/installer/runtime-assets.mjs +1 -0
- package/lib/management/operations.mjs +2 -2
- package/lib/platforms/claude.mjs +1 -0
- package/lib/platforms/codex.mjs +1 -0
- package/lib/platforms/index.mjs +7 -0
- package/lib/policy/role-policy.json +2 -2
- package/lib/runtime/bootstrap.mjs +1 -1
- package/lib/runtime/grok-sandbox.mjs +308 -0
- package/lib/runtime/platform-registry.mjs +2 -2
- package/lib/runtime/role-bridge-args.mjs +6 -4
- package/lib/runtime/role-bridge.mjs +14 -6
- package/lib/runtime/role-dispatch-policy.mjs +32 -5
- package/lib/runtime/role-observe.mjs +213 -3
- package/lib/runtime/role-routing.mjs +37 -4
- package/lib/runtime/role-supervisor.mjs +95 -27
- package/package.json +1 -1
- package/shared/skill/runtime/bootstrap.mjs +1 -1
- package/shared/skill/runtime/grok-sandbox.mjs +308 -0
- package/shared/skill/runtime/platform-registry.mjs +2 -2
- package/shared/skill/runtime/role-bridge-args.mjs +6 -4
- package/shared/skill/runtime/role-bridge.mjs +14 -6
- package/shared/skill/runtime/role-dispatch-policy.mjs +32 -5
- package/shared/skill/runtime/role-observe.mjs +213 -3
- package/shared/skill/runtime/role-policy.json +2 -2
- package/shared/skill/runtime/role-routing.mjs +37 -4
- package/shared/skill/runtime/role-supervisor.mjs +95 -27
|
@@ -7,9 +7,10 @@ import fsp from 'node:fs/promises';
|
|
|
7
7
|
import path from 'node:path';
|
|
8
8
|
import readline from 'node:readline';
|
|
9
9
|
import zlib from 'node:zlib';
|
|
10
|
-
import {execFile} from 'node:child_process';
|
|
10
|
+
import {execFile, spawnSync} from 'node:child_process';
|
|
11
11
|
import {promisify} from 'node:util';
|
|
12
12
|
import {DEFAULT_POLICY, CATALOG_MODEL_ALIASES} from './role-dispatch-policy.mjs';
|
|
13
|
+
import {observeCooperativeTarget} from './scope.mjs';
|
|
13
14
|
|
|
14
15
|
const execFileAsync = promisify(execFile);
|
|
15
16
|
const isObject = value => value !== null && typeof value === 'object' && !Array.isArray(value);
|
|
@@ -253,6 +254,14 @@ const git = async (cwd, args, {allowFailure = false} = {}) => {
|
|
|
253
254
|
}
|
|
254
255
|
};
|
|
255
256
|
const sha256 = value => crypto.createHash('sha256').update(value).digest('hex');
|
|
257
|
+
|
|
258
|
+
/** Resolve the worktree root for a cwd that may be a subdirectory. */
|
|
259
|
+
export async function resolveWorktree(cwd) {
|
|
260
|
+
const result = spawnSync('git', ['--no-pager', 'rev-parse', '--show-toplevel'], {cwd, env: gitEnv(), encoding: 'utf8', timeout: 10000});
|
|
261
|
+
if (result.error || result.status !== 0 || !result.stdout.endsWith('\n')) throw Error('Worktree root unavailable');
|
|
262
|
+
return observeCooperativeTarget(result.stdout.slice(0, -1));
|
|
263
|
+
}
|
|
264
|
+
|
|
256
265
|
async function contentDigest(filename) {
|
|
257
266
|
let stat;
|
|
258
267
|
try { stat = await fsp.lstat(filename); } catch (error) { return error.code === 'ENOENT' ? sha256('deleted') : sha256('unreadable'); }
|
|
@@ -264,6 +273,204 @@ async function contentDigest(filename) {
|
|
|
264
273
|
});
|
|
265
274
|
}
|
|
266
275
|
|
|
276
|
+
const missingTree = error => error.code === 'ENOENT' || error.code === 'ENOTDIR';
|
|
277
|
+
const CONTROL_TREE_LIMIT = 1000;
|
|
278
|
+
const controlStat = filename => fsp.lstat(filename).catch(error => {
|
|
279
|
+
if (missingTree(error)) return null;
|
|
280
|
+
throw error;
|
|
281
|
+
});
|
|
282
|
+
const sameControlEntry = (stat, current) => current?.dev === stat.dev && current?.ino === stat.ino;
|
|
283
|
+
const entryIntact = async (filename, stat) => sameControlEntry(stat, await controlStat(filename));
|
|
284
|
+
const rootIntact = async () => true;
|
|
285
|
+
|
|
286
|
+
async function controlFileState(filename, {project, stat, parentIntact = rootIntact} = {}) {
|
|
287
|
+
let handle, bytes, digest;
|
|
288
|
+
let intact = parentIntact;
|
|
289
|
+
try {
|
|
290
|
+
if (!await parentIntact()) return 'changed';
|
|
291
|
+
stat ??= await controlStat(filename);
|
|
292
|
+
if (!stat) return sha256('deleted');
|
|
293
|
+
intact = async () => await parentIntact() && await entryIntact(filename, stat);
|
|
294
|
+
if (!await intact()) return 'changed';
|
|
295
|
+
if (stat.isSymbolicLink()) {
|
|
296
|
+
const target = await fsp.readlink(filename);
|
|
297
|
+
return await intact() ? `symlink:${target}` : 'changed';
|
|
298
|
+
}
|
|
299
|
+
if (!stat.isFile()) return sha256('directory');
|
|
300
|
+
|
|
301
|
+
// Refuse a replacement symlink and verify the opened file before reading bytes.
|
|
302
|
+
const {O_RDONLY, O_NOFOLLOW, O_NONBLOCK} = fs.constants;
|
|
303
|
+
handle = await fsp.open(filename, O_RDONLY | O_NOFOLLOW | O_NONBLOCK);
|
|
304
|
+
if (!sameControlEntry(stat, await handle.stat()) || !await intact()) return 'changed';
|
|
305
|
+
if (project) {
|
|
306
|
+
bytes = await handle.readFile();
|
|
307
|
+
} else {
|
|
308
|
+
const hash = crypto.createHash('sha256');
|
|
309
|
+
for await (const chunk of handle.createReadStream({autoClose: false})) hash.update(chunk);
|
|
310
|
+
digest = hash.digest('hex');
|
|
311
|
+
}
|
|
312
|
+
if (!await intact()) return 'changed';
|
|
313
|
+
} catch {
|
|
314
|
+
return await intact().catch(() => true) ? sha256('unreadable') : 'changed';
|
|
315
|
+
} finally {
|
|
316
|
+
if (handle) await handle.close();
|
|
317
|
+
}
|
|
318
|
+
const projection = project ? project(bytes) : null;
|
|
319
|
+
return projection === null ? `${digest ?? sha256(bytes)}:${stat.dev}:${stat.ino}` : sha256('projection:' + projection);
|
|
320
|
+
}
|
|
321
|
+
|
|
322
|
+
async function snapshotControlTree(root, label) {
|
|
323
|
+
const entries = new Map();
|
|
324
|
+
const walk = async (dir, prefix, stat, parentIntact) => {
|
|
325
|
+
const intact = async () => await parentIntact() && await entryIntact(dir, stat);
|
|
326
|
+
const markChanged = () => {
|
|
327
|
+
for (const entry of entries.keys()) if (entry.startsWith(prefix + '/')) entries.delete(entry);
|
|
328
|
+
entries.set(prefix, 'changed');
|
|
329
|
+
};
|
|
330
|
+
if (!await intact()) return markChanged();
|
|
331
|
+
let names;
|
|
332
|
+
try { names = await fsp.readdir(dir); } catch (error) {
|
|
333
|
+
if (missingTree(error)) return markChanged();
|
|
334
|
+
const stillIntact = prefix === label ? await intact() : await intact().catch(() => true);
|
|
335
|
+
if (!stillIntact) return markChanged();
|
|
336
|
+
if (prefix !== label) {
|
|
337
|
+
entries.set(prefix + '/', 'unreadable');
|
|
338
|
+
return;
|
|
339
|
+
}
|
|
340
|
+
throw error;
|
|
341
|
+
}
|
|
342
|
+
if (!await intact()) return markChanged();
|
|
343
|
+
for (const name of names) {
|
|
344
|
+
if (name.endsWith('.lock')) continue;
|
|
345
|
+
if (!await intact()) return markChanged();
|
|
346
|
+
const filename = path.join(dir, name), entry = `${prefix}/${name}`;
|
|
347
|
+
let state;
|
|
348
|
+
try { state = await controlStat(filename); } catch {
|
|
349
|
+
entries.set(entry, sha256('unreadable'));
|
|
350
|
+
}
|
|
351
|
+
if (state?.isDirectory()) {
|
|
352
|
+
entries.set(entry + '/', `directory:${state.dev}:${state.ino}`);
|
|
353
|
+
if (entries.size <= CONTROL_TREE_LIMIT) await walk(filename, entry, state, intact);
|
|
354
|
+
} else if (state) {
|
|
355
|
+
entries.set(entry, await controlFileState(filename, {stat: state, parentIntact: intact}));
|
|
356
|
+
}
|
|
357
|
+
if (entries.size > CONTROL_TREE_LIMIT) break;
|
|
358
|
+
}
|
|
359
|
+
if (!await intact()) markChanged();
|
|
360
|
+
};
|
|
361
|
+
|
|
362
|
+
const stat = await controlStat(root);
|
|
363
|
+
if (!stat) return entries;
|
|
364
|
+
if (!stat.isDirectory()) return new Map([[label, await controlFileState(root, {stat})]]);
|
|
365
|
+
await walk(root, label, stat, rootIntact);
|
|
366
|
+
return entries.size > CONTROL_TREE_LIMIT ? new Map([[label, 'overflow']]) : entries;
|
|
367
|
+
}
|
|
368
|
+
|
|
369
|
+
async function snapshotWorktreeControlDirectory(worktree, name, files, entries) {
|
|
370
|
+
const dir = path.join(worktree, name), label = `worktree:${name}/`;
|
|
371
|
+
let stat;
|
|
372
|
+
try { stat = await controlStat(dir); } catch {
|
|
373
|
+
entries.set(label, sha256('unreadable'));
|
|
374
|
+
return;
|
|
375
|
+
}
|
|
376
|
+
if (stat && !stat.isDirectory()) {
|
|
377
|
+
entries.set(label, await controlFileState(dir, {stat}));
|
|
378
|
+
return;
|
|
379
|
+
}
|
|
380
|
+
const intact = async () => stat ? await entryIntact(dir, stat) : (await controlStat(dir)) === null;
|
|
381
|
+
const states = [];
|
|
382
|
+
for (const file of files) {
|
|
383
|
+
states.push(stat ? await controlFileState(path.join(dir, file), {parentIntact: intact}) : sha256('deleted'));
|
|
384
|
+
}
|
|
385
|
+
if (!await intact()) entries.set(label, 'changed');
|
|
386
|
+
else files.forEach((file, i) => entries.set(label + file, states[i]));
|
|
387
|
+
}
|
|
388
|
+
|
|
389
|
+
async function extraControlFileState({path: filename, project}) {
|
|
390
|
+
const parent = path.dirname(filename);
|
|
391
|
+
const stat = await controlStat(parent).catch(() => undefined);
|
|
392
|
+
if (stat === undefined) return sha256('unreadable');
|
|
393
|
+
if (!stat) return sha256('deleted');
|
|
394
|
+
|
|
395
|
+
const parentIntact = () => entryIntact(parent, stat).catch(() => false);
|
|
396
|
+
if (stat.isSymbolicLink()) {
|
|
397
|
+
const target = await fsp.readlink(parent).catch(() => null);
|
|
398
|
+
if (!await parentIntact()) return 'parent-changed';
|
|
399
|
+
return target === null ? sha256('unreadable') : `parent-symlink:${target}`;
|
|
400
|
+
}
|
|
401
|
+
if (!stat.isDirectory()) return 'parent-not-directory';
|
|
402
|
+
const state = await controlFileState(filename, {project, parentIntact});
|
|
403
|
+
return await parentIntact() ? state : 'parent-changed';
|
|
404
|
+
}
|
|
405
|
+
|
|
406
|
+
const CLAUDE_SAFE_ALLOW_TOOLS = new Set(['bash', 'read', 'grep', 'glob', 'webfetch', 'websearch']);
|
|
407
|
+
|
|
408
|
+
function claudeSettingsScopeReason(bytes) {
|
|
409
|
+
let settings;
|
|
410
|
+
try { settings = JSON.parse(bytes.toString('utf8')); } catch { return 'invalid JSON'; }
|
|
411
|
+
if (!isObject(settings)) return null;
|
|
412
|
+
if (Object.hasOwn(settings, 'hooks')) return 'hooks';
|
|
413
|
+
if (Object.hasOwn(settings, 'sandbox')) return 'sandbox';
|
|
414
|
+
const {permissions} = settings;
|
|
415
|
+
if (!isObject(permissions)) return null;
|
|
416
|
+
if (permissions.additionalDirectories?.length > 0) return 'permissions.additionalDirectories';
|
|
417
|
+
if (Object.hasOwn(permissions, 'allow')) {
|
|
418
|
+
const {allow} = permissions;
|
|
419
|
+
if (!Array.isArray(allow) || allow.some(rule =>
|
|
420
|
+
typeof rule !== 'string' || !CLAUDE_SAFE_ALLOW_TOOLS.has(rule.split('(', 1)[0].trim().toLowerCase())
|
|
421
|
+
)) return 'permissions.allow';
|
|
422
|
+
}
|
|
423
|
+
if (Object.hasOwn(permissions, 'defaultMode')) return 'permissions.defaultMode';
|
|
424
|
+
return null;
|
|
425
|
+
}
|
|
426
|
+
|
|
427
|
+
/** Check Claude project and local settings before starting a writing bridge. */
|
|
428
|
+
export async function claudeProjectSettingsWidenScope(worktree) {
|
|
429
|
+
for (const label of ['.claude/settings.json', '.claude/settings.local.json']) {
|
|
430
|
+
let scopeReason;
|
|
431
|
+
const state = await extraControlFileState({path: path.join(worktree, label), project: bytes => {
|
|
432
|
+
scopeReason = claudeSettingsScopeReason(bytes);
|
|
433
|
+
return 'claude-settings-read';
|
|
434
|
+
}}).catch(() => 'unreadable');
|
|
435
|
+
if (state === sha256('deleted')) continue;
|
|
436
|
+
if (state === sha256('projection:claude-settings-read')) {
|
|
437
|
+
if (scopeReason) return `${label}: ${scopeReason}`;
|
|
438
|
+
continue;
|
|
439
|
+
}
|
|
440
|
+
if (state === sha256('directory') || state.startsWith('symlink:')) return `${label}: not a regular file`;
|
|
441
|
+
return `${label}: settings path could not be verified`;
|
|
442
|
+
}
|
|
443
|
+
return null;
|
|
444
|
+
}
|
|
445
|
+
|
|
446
|
+
/** Snapshot of selected Git, worktree and optional platform control files. */
|
|
447
|
+
export async function snapshotControlFiles({gitCommonDir, gitDir, worktree, extra = []}) {
|
|
448
|
+
if (![gitCommonDir, gitDir, worktree].every(dir => typeof dir === 'string' && path.isAbsolute(dir))) {
|
|
449
|
+
throw Error('Control snapshot requires absolute Git and worktree paths');
|
|
450
|
+
}
|
|
451
|
+
if (!(await fsp.lstat(gitCommonDir)).isDirectory()) throw Error('Git common directory is not a directory');
|
|
452
|
+
const files = [
|
|
453
|
+
{label: 'git:config', path: path.join(gitCommonDir, 'config')},
|
|
454
|
+
{label: 'git:config.worktree', path: path.join(gitDir, 'config.worktree')},
|
|
455
|
+
];
|
|
456
|
+
const entries = new Map();
|
|
457
|
+
for (const file of files) entries.set(file.label, await controlFileState(file.path));
|
|
458
|
+
await snapshotWorktreeControlDirectory(worktree, '.claude', ['settings.json', 'settings.local.json'], entries);
|
|
459
|
+
await snapshotWorktreeControlDirectory(worktree, '.codex', ['config.toml'], entries);
|
|
460
|
+
for (const file of extra) entries.set(file.label, await extraControlFileState(file));
|
|
461
|
+
for (const tree of ['hooks', 'info']) {
|
|
462
|
+
for (const [label, state] of await snapshotControlTree(path.join(gitCommonDir, tree), `git:${tree}`)) entries.set(label, state);
|
|
463
|
+
}
|
|
464
|
+
return entries;
|
|
465
|
+
}
|
|
466
|
+
|
|
467
|
+
export function allowedPathsCoverControl(allowedPaths) {
|
|
468
|
+
return allowedPaths.some(entry => {
|
|
469
|
+
const normalized = path.posix.normalize(entry).replace(/\/$/, '').toLowerCase();
|
|
470
|
+
return normalized.startsWith('.git/') || ['.', '.git', '.claude', '.claude/settings.json', '.claude/settings.local.json', '.codex', '.codex/config.toml'].includes(normalized);
|
|
471
|
+
});
|
|
472
|
+
}
|
|
473
|
+
|
|
267
474
|
/** Snapshot of HEAD, branch, every ref (name and object) and every changed or untracked path; paths are relative to the worktree root even when worktree is a subdirectory. */
|
|
268
475
|
export async function snapshotWorktree(worktree) {
|
|
269
476
|
const root = (await git(worktree, ['rev-parse', '--show-toplevel'])).trim();
|
|
@@ -287,7 +494,7 @@ export async function snapshotWorktree(worktree) {
|
|
|
287
494
|
}
|
|
288
495
|
|
|
289
496
|
const allowedBy = (allowedPaths, file) => allowedPaths.some(entry => entry.endsWith('/') ? file.startsWith(entry) : file === entry);
|
|
290
|
-
/** Implementer and QA may change only allowedPaths (QA: none when empty or missing); read-only roles may change nothing; any HEAD, branch or ref change (created, deleted or moved) is a violation. Git-ignored paths are
|
|
497
|
+
/** Implementer and QA may change only allowedPaths (QA: none when empty or missing); read-only roles may change nothing; any HEAD, branch or ref change (created, deleted or moved) is a violation. Ordinary worktree snapshots omit Git-ignored paths; control files are compared regardless of allowedPaths and role. */
|
|
291
498
|
export function detectViolations({role, allowedPaths, before, after}) {
|
|
292
499
|
const headChanged = before.head !== after.head || before.branch !== after.branch;
|
|
293
500
|
const refsBefore = before.refs ?? {}, refsAfter = after.refs ?? {};
|
|
@@ -296,5 +503,8 @@ export function detectViolations({role, allowedPaths, before, after}) {
|
|
|
296
503
|
const changed = new Set();
|
|
297
504
|
for (const file of new Set([...before.entries.keys(), ...after.entries.keys()])) if (before.entries.get(file) !== after.entries.get(file)) changed.add(file);
|
|
298
505
|
const changedPaths = [...changed].filter(file => !allowedBy(allowed, file)).sort();
|
|
299
|
-
|
|
506
|
+
const controlBefore = before.control ?? new Map(), controlAfter = after.control ?? new Map();
|
|
507
|
+
const controlChanged = [...new Set([...controlBefore.keys(), ...controlAfter.keys()])]
|
|
508
|
+
.filter(label => controlBefore.get(label) !== controlAfter.get(label)).sort();
|
|
509
|
+
return {reason: headChanged || refsChanged || changedPaths.length || controlChanged.length ? 'permission_violation_observed' : null, changedPaths, headChanged, refsChanged, controlChanged};
|
|
300
510
|
}
|
|
@@ -7,8 +7,9 @@ import {COOPERATIVE_RUNTIME_MODULES, cooperativeVersions} from './bootstrap.mjs'
|
|
|
7
7
|
import {inspectPath} from './scope.mjs';
|
|
8
8
|
import {resolveConfigHome, resolveLocalCli, probePlatformAuth, probeCodexAuthStatus, probeCliVersion} from './local-cli.mjs';
|
|
9
9
|
import {ROUTING_ROLES, parseRoleRoutingConfig} from './role-routing-config.mjs';
|
|
10
|
-
import {DEFAULT_POLICY, reason, profileName, revisionTag, bridgeGateReasons, environmentReasons, initialClaims, capabilityReasons} from './role-dispatch-policy.mjs';
|
|
10
|
+
import {DEFAULT_POLICY, HOST_SANDBOX_GATES, reason, profileName, revisionTag, hostGateReasons, bridgeGateReasons, environmentReasons, initialClaims, capabilityReasons} from './role-dispatch-policy.mjs';
|
|
11
11
|
import {NON_TERMINAL_STATES, createLease, listLeases, pruneTerminalLeases, readHostLimits} from './role-dispatch-store.mjs';
|
|
12
|
+
import {allowedPathsCoverControl, claudeProjectSettingsWidenScope, resolveWorktree} from './role-observe.mjs';
|
|
12
13
|
|
|
13
14
|
const exact=(value,keys)=>value&&typeof value==='object'&&!Array.isArray(value)&&Object.keys(value).length===keys.length&&keys.every(key=>Object.hasOwn(value,key));
|
|
14
15
|
const hash=bytes=>'sha256:'+crypto.createHash('sha256').update(bytes).digest('hex');
|
|
@@ -114,6 +115,27 @@ export async function readActivation(homes,expectedRevision,{anchorHome=homes.co
|
|
|
114
115
|
|
|
115
116
|
|
|
116
117
|
const HOST_ERRORS=['EACCES','EPERM','EROFS'];
|
|
118
|
+
export async function probeHomeWritable(home, {unlink = fs.unlink} = {}) {
|
|
119
|
+
const file = path.join(home, '.arc-host-probe-' + crypto.randomUUID());
|
|
120
|
+
let handle;
|
|
121
|
+
try {
|
|
122
|
+
handle = await fs.open(file, constants.O_WRONLY | constants.O_CREAT | constants.O_EXCL | constants.O_NOFOLLOW, 0o600);
|
|
123
|
+
} catch (error) {
|
|
124
|
+
return {ok: false, code: HOST_ERRORS.includes(error?.code) ? 'host_sandbox_blocked' : 'activation_unverified'};
|
|
125
|
+
}
|
|
126
|
+
let closed = false;
|
|
127
|
+
try {
|
|
128
|
+
await handle.close();
|
|
129
|
+
closed = true;
|
|
130
|
+
} catch { /* Attempt to remove the file even if close fails. */ }
|
|
131
|
+
try {
|
|
132
|
+
await unlink(file);
|
|
133
|
+
} catch {
|
|
134
|
+
return {ok: false, code: 'host_sandbox_blocked', residualPaths: [file]};
|
|
135
|
+
}
|
|
136
|
+
return closed ? {ok: true} : {ok: false, code: 'activation_unverified'};
|
|
137
|
+
}
|
|
138
|
+
|
|
117
139
|
const sleep=ms=>new Promise(resolve=>setTimeout(resolve,ms));
|
|
118
140
|
const lockFile=codexHome=>path.join(codexHome,'arc-role-platform-routing.lock');
|
|
119
141
|
/** Runs fn under the shared routing lock. Only EEXIST is retried; the lock file is never removed except by its owner. */
|
|
@@ -218,6 +240,11 @@ export async function prepareRoleDispatch({context,assignment,expectedRevision,n
|
|
|
218
240
|
let config;try{config=await readActivation(homes,expectedRevision,{anchorHome,host,runtimePlatforms});}catch{result.reasons=[reason('activation_unverified')];return;}
|
|
219
241
|
const requested=config.roles[role],route=requested.platform===host?'native':'bridge';
|
|
220
242
|
result.requested={...requested};result.route=route;result.profileName=profileName(requested.platform,role,{runtimePlatforms});
|
|
243
|
+
if(route==='bridge'&&allowedPathsCoverControl(assignment.allowedPaths??[])){result.reasons=[reason('permission_scope_unverified')];return;}
|
|
244
|
+
if(route==='bridge'&&requested.platform==='claude'&&(role==='arc_implementer'||role==='arc_qa')){
|
|
245
|
+
const target=typeof context.cwd==='string'?await resolveWorktree(context.cwd).catch(()=>null):null;
|
|
246
|
+
if(!target||await claudeProjectSettingsWidenScope(target.realpath)){result.reasons=[reason('permission_scope_unverified')];return;}
|
|
247
|
+
}
|
|
221
248
|
const capabilities=capabilityReasons({hostPlatform:host,targetPlatform:requested.platform,route,runtimePlatforms});
|
|
222
249
|
if(capabilities.length){result.reasons=capabilities.map(reason);return;}
|
|
223
250
|
await pruneTerminalLeases(anchorHome,{now,retentionMs:policy.leaseRetentionMs,runtimePlatforms});
|
|
@@ -231,14 +258,20 @@ export async function prepareRoleDispatch({context,assignment,expectedRevision,n
|
|
|
231
258
|
const leases=await listLeases(anchorHome,{runtimePlatforms});
|
|
232
259
|
const live=leases.filter(lease=>NON_TERMINAL_STATES.includes(lease.state));
|
|
233
260
|
if(leases.some(lease=>lease.requestId===assignment.requestId)||live.some(lease=>lease.workflowId===context.workflowId&&lease.taskId===assignment.taskId&&lease.role===role)){duplicate=true;codes.add('duplicate_dispatch');}
|
|
234
|
-
|
|
235
|
-
if(host==='gemini'&&(policy.gates?.GG2??DEFAULT_POLICY.gates.GG2)!=='pass')codes.add('host_sandbox_blocked');
|
|
261
|
+
for(const code of hostGateReasons({hostPlatform:host,policy}))codes.add(code);
|
|
236
262
|
if(route==='bridge'){
|
|
237
263
|
let limits;try{limits=readHostLimits(resolveConfigHome(host,context));}catch{codes.add('activation_unverified');}
|
|
238
264
|
if(limits){
|
|
239
265
|
const bridges=leases.filter(lease=>lease.route==='bridge');
|
|
240
266
|
if(bridges.filter(lease=>NON_TERMINAL_STATES.includes(lease.state)).length>=limits.maxConcurrent||bridges.filter(lease=>lease.workflowId===context.workflowId).length>=limits.maxTotal)codes.add('capacity_exhausted');
|
|
241
267
|
}
|
|
268
|
+
if(Object.hasOwn(HOST_SANDBOX_GATES,host)){
|
|
269
|
+
const probe=await probeHomeWritable(homes[requested.platform]);
|
|
270
|
+
if(!probe.ok){
|
|
271
|
+
codes.add(probe.code);
|
|
272
|
+
if(probe.residualPaths)result.residualPaths=probe.residualPaths;
|
|
273
|
+
}
|
|
274
|
+
}
|
|
242
275
|
for(const code of bridgeGateReasons({platform:requested.platform,role,hostPlatform:host,policy}))codes.add(code);
|
|
243
276
|
}
|
|
244
277
|
result.reasons=[...codes].map(reason);
|
|
@@ -254,7 +287,7 @@ export async function prepareRoleDispatch({context,assignment,expectedRevision,n
|
|
|
254
287
|
}else{
|
|
255
288
|
Object.assign(result,{decision:'hold',routeStatus:'held',dispatchId:null,claims:null,reasons:[reason(classify(error))]});
|
|
256
289
|
}
|
|
257
|
-
const residual=residualOf(error);if(residual)result.residualPaths=residual;
|
|
290
|
+
const residual=residualOf(error);if(residual)result.residualPaths=[...(result.residualPaths??[]),...residual];
|
|
258
291
|
}
|
|
259
292
|
return result;
|
|
260
293
|
}
|
|
@@ -7,14 +7,14 @@ import crypto from 'node:crypto';
|
|
|
7
7
|
import {spawn, spawnSync} from 'node:child_process';
|
|
8
8
|
import {fileURLToPath} from 'node:url';
|
|
9
9
|
import {GROK_CONTRACT, normalizeGrokStreamEvent, evaluateGrokObservation} from './grok-stream.mjs';
|
|
10
|
+
import {GROK_SANDBOX_RELATIVE, grokSandboxProfileName, renderGrokSandboxProfile, grokProfileCovered, inspectGrokProfileSlot, checkGrokHome, createGrokSandboxProfile, verifyGrokSandboxProfile, removeGrokSandboxProfile, grokEventsBaseline, readGrokProfileApplied, grokConfigSecurityProjection} from './grok-sandbox.mjs';
|
|
10
11
|
import {GEMINI_CONTRACT, normalizeGeminiStreamEvent, evaluateGeminiObservation} from './gemini-stream.mjs';
|
|
11
12
|
import {DEFAULT_POLICY, reason, bridgeGateReasons} from './role-dispatch-policy.mjs';
|
|
12
13
|
import {readLease, writeLease, writeHeartbeat, cancelRequested, TERMINAL_STATES} from './role-dispatch-store.mjs';
|
|
13
14
|
import {withRoutingLock, readActivation, resolveRuntimeHomes} from './role-routing.mjs';
|
|
14
|
-
import {observeCooperativeTarget} from './scope.mjs';
|
|
15
15
|
import {resolveLocalCli, localCliEnvironment} from './local-cli.mjs';
|
|
16
16
|
import {parseCompositeProfile, buildBridgeArgs, argsDigest, ROLE_BRIDGE_PERMISSIONS} from './role-bridge-args.mjs';
|
|
17
|
-
import {createLineParser, normalizeClaudeStreamEvent, normalizeCodexStreamEvent, eventRecord, evaluateClaudeInit, evaluateCodexContext, readClaudeTranscriptEffort, readCodexTurnContext, classifyFailure, snapshotWorktree, detectViolations} from './role-observe.mjs';
|
|
17
|
+
import {createLineParser, normalizeClaudeStreamEvent, normalizeCodexStreamEvent, eventRecord, evaluateClaudeInit, evaluateCodexContext, readClaudeTranscriptEffort, readCodexTurnContext, classifyFailure, snapshotWorktree, snapshotControlFiles, detectViolations, allowedPathsCoverControl, claudeProjectSettingsWidenScope, resolveWorktree} from './role-observe.mjs';
|
|
18
18
|
import {getPlatform, routingProfileFile} from './platform-registry.mjs';
|
|
19
19
|
|
|
20
20
|
const sleep = ms => new Promise(resolve => setTimeout(resolve, ms));
|
|
@@ -89,13 +89,7 @@ export function processAlive({pid, startTime} = {}) {
|
|
|
89
89
|
return current !== null && current === startTime;
|
|
90
90
|
}
|
|
91
91
|
|
|
92
|
-
|
|
93
|
-
export async function resolveWorktree(cwd) {
|
|
94
|
-
const env = Object.fromEntries(Object.entries(process.env).filter(([key]) => !key.toUpperCase().startsWith('GIT_')));
|
|
95
|
-
const result = spawnSync('git', ['--no-pager', 'rev-parse', '--show-toplevel'], {cwd, env: {...env, GIT_CONFIG_NOSYSTEM: '1', GIT_OPTIONAL_LOCKS: '0'}, encoding: 'utf8', timeout: 10000});
|
|
96
|
-
if (result.error || result.status !== 0 || !result.stdout.endsWith('\n')) throw Error('Worktree root unavailable');
|
|
97
|
-
return observeCooperativeTarget(result.stdout.slice(0, -1));
|
|
98
|
-
}
|
|
92
|
+
export {resolveWorktree};
|
|
99
93
|
export const artifactDirectory = (target, workflowId, dispatchId) => path.join(target.gitCommonDir, 'arc', 'workflows', workflowId, 'dispatches', dispatchId);
|
|
100
94
|
/** Segment 0 (the first run) keeps its files in the dispatch directory; resumed segments use segments/<n>/. */
|
|
101
95
|
export const segmentDirectory = (target, workflowId, dispatchId, segment) => segment > 0 ? path.join(artifactDirectory(target, workflowId, dispatchId), 'segments', String(segment)) : artifactDirectory(target, workflowId, dispatchId);
|
|
@@ -117,6 +111,19 @@ export async function buildBridgeInvocation({lease, config, homes, worktree, res
|
|
|
117
111
|
}
|
|
118
112
|
if ((platform === 'gemini' || platform === 'grok') && lease.segment > 0 && !['on', 'verified'].includes(implementation?.resume)) throw fail('resume_unverified', platform === 'grok' ? 'Grok resume is not verified' : 'Gemini resume is not verified');
|
|
119
113
|
if (!implementation) throw fail('permission_scope_unverified', 'Invalid composite profile: unknown platform');
|
|
114
|
+
const permissions = ROLE_BRIDGE_PERMISSIONS[platform][lease.role];
|
|
115
|
+
if (Array.isArray(lease.allowedPaths) && allowedPathsCoverControl(lease.allowedPaths)) throw fail('permission_scope_unverified', 'allowedPaths cover a control file');
|
|
116
|
+
if (platform === 'claude' && permissions.sandbox) {
|
|
117
|
+
const scopeReason = await claudeProjectSettingsWidenScope(worktree);
|
|
118
|
+
if (scopeReason) throw fail('permission_scope_unverified', scopeReason);
|
|
119
|
+
}
|
|
120
|
+
let grokSandbox;
|
|
121
|
+
if (platform === 'grok' && permissions.sandbox === 'custom') {
|
|
122
|
+
const name = grokSandboxProfileName(lease.dispatchId);
|
|
123
|
+
if (!name || grokProfileCovered(lease.allowedPaths)) throw fail('permission_scope_unverified', 'Grok sandbox profile scope is unavailable');
|
|
124
|
+
inspectGrokProfileSlot(worktree);
|
|
125
|
+
grokSandbox = {name, path: path.join(worktree, GROK_SANDBOX_RELATIVE), bytes: renderGrokSandboxProfile(name)};
|
|
126
|
+
}
|
|
120
127
|
const file = path.join(homes[platform], 'agents', routingProfileFile(getPlatform(platform), lease.role));
|
|
121
128
|
let bytes;
|
|
122
129
|
try { bytes = await fsp.readFile(file); } catch { throw fail('activation_unverified', 'Profile unreadable'); }
|
|
@@ -124,14 +131,13 @@ export async function buildBridgeInvocation({lease, config, homes, worktree, res
|
|
|
124
131
|
let profile, args;
|
|
125
132
|
try {
|
|
126
133
|
profile = parseCompositeProfile(platform, bytes);
|
|
127
|
-
args = buildBridgeArgs(platform, {role: lease.role, profile, sessionId: lease.sessionId, worktree, resultPath, threadId: lease.sessionId, policy, policyFile: geminiPolicyFile(homes, lease.role), ...(platform === 'grok' ? {promptFile: grokPromptFile(resultPath)} : {}), resume: lease.segment > 0});
|
|
134
|
+
args = buildBridgeArgs(platform, {role: lease.role, profile, sessionId: lease.sessionId, worktree, resultPath, threadId: lease.sessionId, policy, policyFile: geminiPolicyFile(homes, lease.role), ...(platform === 'grok' ? {promptFile: grokPromptFile(resultPath), sandboxProfile: grokSandbox?.name} : {}), resume: lease.segment > 0});
|
|
128
135
|
} catch { throw fail('permission_scope_unverified', 'Profile arguments unavailable'); }
|
|
129
|
-
const permissions = ROLE_BRIDGE_PERMISSIONS[platform][lease.role];
|
|
130
136
|
const expected = platform === 'claude'
|
|
131
137
|
? {model: requested.model, effort: requested.effort, tools: profile.tools, permissionMode: permissions.permissionMode}
|
|
132
138
|
: platform === 'gemini' || platform === 'grok' ? {model: requested.model, effort: 'default'}
|
|
133
139
|
: {model: requested.model, effort: requested.effort, sandboxMode: permissions.sandboxMode, approvalPolicy: 'never'};
|
|
134
|
-
return {platform, args, argsDigest: argsDigest(args), expected, requested, ...(platform === 'gemini' ? {stdinInstructions: profile.instructions} : {}), ...(platform === 'grok' ? {promptFile: {path: grokPromptFile(resultPath), instructions: profile.instructions}, childEnv: GROK_CONTRACT.childEnv} : {})};
|
|
140
|
+
return {platform, args, argsDigest: argsDigest(args), expected, requested, ...(platform === 'gemini' ? {stdinInstructions: profile.instructions} : {}), ...(platform === 'grok' ? {promptFile: {path: grokPromptFile(resultPath), instructions: profile.instructions}, childEnv: GROK_CONTRACT.childEnv} : {}), ...(grokSandbox ? {grokSandbox} : {})};
|
|
135
141
|
}
|
|
136
142
|
|
|
137
143
|
/** Starts this module as a detached supervisor process (own session, stdio ignored, unref'd). env defaults to the inherited environment. */
|
|
@@ -197,10 +203,31 @@ export async function runSupervisor(options) {
|
|
|
197
203
|
await writeLease(codexHome, {...current, state, claims: claims ?? current.claims, reasons: [...new Set(codes)].map(reason), sessionId: extra.sessionId ?? current.sessionId, resultPath: extra.resultPath ?? null}, {runtimePlatforms});
|
|
198
204
|
});
|
|
199
205
|
};
|
|
200
|
-
|
|
206
|
+
let createdGrokProfile, grokSandboxProfile, spawnAtMs, profileViolation = false;
|
|
207
|
+
const grokProfileRecord = () => grokSandboxProfile ? {grokSandboxProfile, ...(spawnAtMs === undefined ? {} : {spawnAtMs})} : {};
|
|
208
|
+
const cleanGrokProfile = () => {
|
|
209
|
+
if (!grokSandboxProfile || grokSandboxProfile.removed !== null) return;
|
|
210
|
+
const {removed, dirRemoved, violation} = removeGrokSandboxProfile(createdGrokProfile);
|
|
211
|
+
Object.assign(grokSandboxProfile, {removed, dirRemoved});
|
|
212
|
+
profileViolation = violation;
|
|
213
|
+
};
|
|
214
|
+
const retainGrokProfile = () => {
|
|
215
|
+
if (grokSandboxProfile?.removed === null) Object.assign(grokSandboxProfile, {removed: false, reason: 'child_unobserved'});
|
|
216
|
+
return grokProfileRecord();
|
|
217
|
+
};
|
|
218
|
+
const earlyFailure = async (code, spawned = null, extra = {}) => {
|
|
201
219
|
const claims = {...(lease.claims ?? {}), terminal: {level: 'runtime-observed', source: 'supervisor'}};
|
|
202
|
-
|
|
203
|
-
|
|
220
|
+
const codes = [code];
|
|
221
|
+
if (profileViolation) {
|
|
222
|
+
codes.push('permission_violation_observed');
|
|
223
|
+
claims.permissions = {...claims.permissions, level: 'unverified', details: 'permission violation observed'};
|
|
224
|
+
}
|
|
225
|
+
await writeRecord({state: 'failed', reasons: codes, spawned: spawned !== null, ...(spawned !== null ? {childPid: spawned} : {}), ...extra}).catch(() => {});
|
|
226
|
+
await commit('failed', codes, claims);
|
|
227
|
+
};
|
|
228
|
+
const failWithProfileCleanup = (code, spawned = null) => {
|
|
229
|
+
cleanGrokProfile();
|
|
230
|
+
return earlyFailure(code, spawned, grokProfileRecord());
|
|
204
231
|
};
|
|
205
232
|
|
|
206
233
|
let child = null, eventsFd = null, killTimers = [], terminating = null, termAt = 0;
|
|
@@ -229,8 +256,31 @@ export async function runSupervisor(options) {
|
|
|
229
256
|
const brief = await fsp.readFile(path.join(artifactDir, 'brief.md'), 'utf8');
|
|
230
257
|
const cli = resolveLocalCli(platform, context);
|
|
231
258
|
if (cli.reason) return await earlyFailure(cli.reason === 'cli_not_found' ? 'Not Available' : 'execution_failed');
|
|
259
|
+
const childEnv = {...localCliEnvironment(cli), ...invocation.childEnv};
|
|
260
|
+
if (invocation.grokSandbox) {
|
|
261
|
+
if (Object.hasOwn(invocation.childEnv, 'GROK_HOME') || !checkGrokHome({grokHome: homes.grok, userHome, childEnv})) return await earlyFailure('permission_scope_unverified');
|
|
262
|
+
try { createdGrokProfile = createGrokSandboxProfile({worktree: target.realpath, bytes: invocation.grokSandbox.bytes}); }
|
|
263
|
+
catch (error) {
|
|
264
|
+
const cleanup = error.cleanup;
|
|
265
|
+
if (cleanup?.violation) {
|
|
266
|
+
profileViolation = true;
|
|
267
|
+
grokSandboxProfile = {name: invocation.grokSandbox.name, path: cleanup.path, created: true, removed: !cleanup.retained, dirRemoved: cleanup.dirRemoved, reason: 'profile_creation_cleanup_failed'};
|
|
268
|
+
}
|
|
269
|
+
return await earlyFailure(error.reasonCode ?? 'permission_scope_unverified', null, grokProfileRecord());
|
|
270
|
+
}
|
|
271
|
+
const {path, sha256, dirCreated} = createdGrokProfile;
|
|
272
|
+
grokSandboxProfile = {name: invocation.grokSandbox.name, path, sha256, dirCreated, created: true, removed: null, dirRemoved: false, eventsBaseline: null, applied: null};
|
|
273
|
+
}
|
|
274
|
+
const extra = invocation.grokSandbox ? [
|
|
275
|
+
{label: 'grok-home:config.toml', path: path.join(homes.grok, 'config.toml'), project: grokConfigSecurityProjection},
|
|
276
|
+
{label: 'grok-home:sandbox.toml', path: path.join(homes.grok, 'sandbox.toml')},
|
|
277
|
+
] : [];
|
|
278
|
+
const snapshot = async () => ({
|
|
279
|
+
...await snapshotWorktree(target.realpath),
|
|
280
|
+
control: await snapshotControlFiles({gitCommonDir: target.gitCommonDir, gitDir: target.gitDir, worktree: target.realpath, extra}),
|
|
281
|
+
});
|
|
232
282
|
let before;
|
|
233
|
-
try { before = await
|
|
283
|
+
try { before = await snapshot(); } catch { return await failWithProfileCleanup('execution_failed'); }
|
|
234
284
|
|
|
235
285
|
if (invocation.promptFile) {
|
|
236
286
|
let promptFd;
|
|
@@ -238,12 +288,21 @@ export async function runSupervisor(options) {
|
|
|
238
288
|
promptFd = fs.openSync(invocation.promptFile.path, fs.constants.O_WRONLY | fs.constants.O_CREAT | fs.constants.O_EXCL, 0o600);
|
|
239
289
|
fs.writeFileSync(promptFd, `${invocation.promptFile.instructions}\n\n${brief}`);
|
|
240
290
|
fs.fchmodSync(promptFd, 0o600);
|
|
241
|
-
} catch { return await
|
|
291
|
+
} catch { return await failWithProfileCleanup('execution_failed'); }
|
|
242
292
|
finally { if (promptFd !== undefined) fs.closeSync(promptFd); }
|
|
243
293
|
}
|
|
244
294
|
eventsFd = fs.openSync(path.join(artifactDir, 'events.jsonl'), 'a', 0o600);
|
|
295
|
+
if (grokSandboxProfile) {
|
|
296
|
+
try { grokSandboxProfile.eventsBaseline = grokEventsBaseline(homes.grok); }
|
|
297
|
+
catch { return await failWithProfileCleanup('permission_scope_unverified'); }
|
|
298
|
+
if (!verifyGrokSandboxProfile(createdGrokProfile)) {
|
|
299
|
+
Object.assign(grokSandboxProfile, {removed: false, reason: 'profile_changed_before_spawn'});
|
|
300
|
+
return await earlyFailure('permission_scope_unverified', null, grokProfileRecord());
|
|
301
|
+
}
|
|
302
|
+
spawnAtMs = Date.now();
|
|
303
|
+
}
|
|
245
304
|
// The child is a process-group leader so one signal reaches its descendants. The prompt uses the platform-specific input channel.
|
|
246
|
-
child = spawn(cli.executable, invocation.args, {cwd: target.realpath, env: {...
|
|
305
|
+
child = spawn(cli.executable, invocation.args, {cwd: target.realpath, env: {...childEnv, ARC_BRIDGE_CHILD: dispatchId}, detached: true, stdio: ['pipe', 'pipe', 'pipe'], shell: false});
|
|
247
306
|
let exitResolve, exited = false;
|
|
248
307
|
const exitPromise = new Promise(resolve => { exitResolve = resolve; });
|
|
249
308
|
child.on('exit', (code, signal) => { exited = true; exitResolve({code, signal}); });
|
|
@@ -382,7 +441,7 @@ export async function runSupervisor(options) {
|
|
|
382
441
|
if (exit.unobserved) {
|
|
383
442
|
// The child was signalled but its exit was never observed: the slot stays occupied.
|
|
384
443
|
const claims = {...lease.claims, terminal: {level: 'unverified', source: 'none'}};
|
|
385
|
-
await writeRecord({state: 'unknown', reasons: [...(terminating === 'timeout' ? ['timeout'] : []), 'terminal_state_unverified'], terminatedBy: terminating, eventsTruncated, ignoredLines: parser.ignored, lineOverflow: parser.overflow}).catch(() => {});
|
|
444
|
+
await writeRecord({state: 'unknown', reasons: [...(terminating === 'timeout' ? ['timeout'] : []), 'terminal_state_unverified'], terminatedBy: terminating, eventsTruncated, ignoredLines: parser.ignored, lineOverflow: parser.overflow, ...retainGrokProfile()}).catch(() => {});
|
|
386
445
|
await locked(async () => {
|
|
387
446
|
const current = await readLease(codexHome, dispatchId, {runtimePlatforms});
|
|
388
447
|
if (current && !TERMINAL_STATES.includes(current.state)) await writeLease(codexHome, {...current, state: 'unknown', claims, reasons: [...(terminating === 'timeout' ? ['timeout'] : []), 'terminal_state_unverified'].map(reason)}, {runtimePlatforms});
|
|
@@ -391,8 +450,8 @@ export async function runSupervisor(options) {
|
|
|
391
450
|
}
|
|
392
451
|
|
|
393
452
|
let after = null;
|
|
394
|
-
try { after = await
|
|
395
|
-
const violations = after ? detectViolations({role: lease.role, allowedPaths: lease.allowedPaths, before, after}) : {reason: null, changedPaths: [], headChanged: false, refsChanged: false};
|
|
453
|
+
try { after = await snapshot(); } catch { after = null; }
|
|
454
|
+
const violations = after ? detectViolations({role: lease.role, allowedPaths: lease.allowedPaths, before, after}) : {reason: null, changedPaths: [], headChanged: false, refsChanged: false, controlChanged: []};
|
|
396
455
|
const codes = [];
|
|
397
456
|
if (state.mismatch) codes.push(state.mismatch);
|
|
398
457
|
if (state.internal) codes.push(state.internal);
|
|
@@ -405,9 +464,16 @@ export async function runSupervisor(options) {
|
|
|
405
464
|
if (platform === 'gemini' && terminating !== 'cancel' && (exit.code !== 0 || exit.signal || state.terminalError)) codes.push('execution_failed');
|
|
406
465
|
if (platform === 'grok' && terminating !== 'cancel' && (exit.code !== 0 || exit.signal || state.terminalError || !state.terminal)) codes.push('execution_failed');
|
|
407
466
|
if (effortMismatch) codes.push('model_effort_mismatch');
|
|
408
|
-
if (
|
|
467
|
+
if (grokSandboxProfile) {
|
|
468
|
+
const {eventsBaseline: baseline, name} = grokSandboxProfile;
|
|
469
|
+
const {ok, reason, applied} = readGrokProfileApplied({grokHome: homes.grok, baseline, spawnAtMs, name, worktreeRealpath: target.realpath});
|
|
470
|
+
if (ok) grokSandboxProfile.applied = applied;
|
|
471
|
+
else if (!(terminating === 'cancel' && reason === 'no_candidate')) codes.push('permission_scope_mismatch');
|
|
472
|
+
}
|
|
473
|
+
cleanGrokProfile();
|
|
474
|
+
if (violations.reason || profileViolation) codes.push(violations.reason ?? 'permission_violation_observed');
|
|
409
475
|
if (after === null) claims.permissions = {level: 'unverified', source: 'worktree-snapshot', details: 'post-run snapshot unavailable'};
|
|
410
|
-
|
|
476
|
+
if (violations.reason || profileViolation) claims.permissions = {...claims.permissions, level: 'unverified', details: 'permission violation observed'};
|
|
411
477
|
if (terminating === 'timeout') codes.push('timeout');
|
|
412
478
|
|
|
413
479
|
const resultPath = platform === 'grok' && (exit.code !== 0 || exit.signal) ? null : await implementation.resultPath(state, resultFile);
|
|
@@ -434,7 +500,9 @@ export async function runSupervisor(options) {
|
|
|
434
500
|
claims.identity = {level: 'unverified', source: 'none'};
|
|
435
501
|
}
|
|
436
502
|
if (exit.spawnError && !codes.length) { codes.push('execution_failed'); finalState = 'failed'; }
|
|
437
|
-
|
|
503
|
+
if ((finalState === 'completed' || finalState === 'cancelled') && codes.includes('permission_scope_mismatch')) finalState = 'failed';
|
|
504
|
+
const controlFiles = violations.controlChanged.length ? {controlFiles: {changed: violations.controlChanged}} : {};
|
|
505
|
+
await writeRecord({state: finalState, reasons: [...new Set(codes)], exit: {code: exit.code, signal: exit.signal}, terminatedBy: terminating, eventsTruncated, ignoredLines: parser.ignored, lineOverflow: parser.overflow, violations: {changedPaths: violations.changedPaths, headChanged: violations.headChanged, refsChanged: violations.refsChanged}, ...controlFiles, ...(orphanGroupReaped ? {orphanGroupReaped: true} : {}), argsDigest: invocation.argsDigest, resultPath, ...grokProfileRecord(), ...(platform === 'gemini' ? {unverifiedContracts: {delegation: GEMINI_CONTRACT.delegation}} : platform === 'grok' ? {unverifiedContracts: {delegation: GROK_CONTRACT.delegation}} : {})});
|
|
438
506
|
await commit(finalState, codes, claims, {sessionId, resultPath});
|
|
439
507
|
} catch {
|
|
440
508
|
// Unexpected failure after the child started: stop it, then record a failed state if the child is gone.
|
|
@@ -443,11 +511,10 @@ export async function runSupervisor(options) {
|
|
|
443
511
|
if (spawnedPid) { if (!termAt) { termAt = Date.now(); killGroup('SIGTERM'); } stopped = await reapGroup().catch(() => false); }
|
|
444
512
|
for (const timer of timers) { clearInterval(timer); clearTimeout(timer); }
|
|
445
513
|
for (const timer of killTimers) clearTimeout(timer);
|
|
446
|
-
if (
|
|
447
|
-
if (stopped) await earlyFailure('execution_failed', spawnedPid).catch(() => {});
|
|
514
|
+
if (stopped) await failWithProfileCleanup('execution_failed', spawnedPid).catch(() => {});
|
|
448
515
|
else {
|
|
449
516
|
const codes = ['execution_failed', 'terminal_state_unverified'];
|
|
450
|
-
await writeRecord({state: 'unknown', reasons: codes, spawned: true, childPid: spawnedPid}).catch(() => {});
|
|
517
|
+
await writeRecord({state: 'unknown', reasons: codes, spawned: true, childPid: spawnedPid, ...retainGrokProfile()}).catch(() => {});
|
|
451
518
|
await locked(async () => {
|
|
452
519
|
const current = await readLease(codexHome, dispatchId, {runtimePlatforms});
|
|
453
520
|
if (current && !TERMINAL_STATES.includes(current.state)) await writeLease(codexHome, {...current, state: 'unknown', reasons: codes.map(reason)}, {runtimePlatforms});
|
|
@@ -455,6 +522,7 @@ export async function runSupervisor(options) {
|
|
|
455
522
|
}
|
|
456
523
|
} finally {
|
|
457
524
|
for (const timer of timers) { clearInterval(timer); clearTimeout(timer); }
|
|
525
|
+
if (eventsFd !== null) { try { fs.closeSync(eventsFd); } catch { /* closed */ } }
|
|
458
526
|
}
|
|
459
527
|
}
|
|
460
528
|
|
package/package.json
CHANGED
|
@@ -8,7 +8,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'
|
|
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'
|
|
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}){
|