@yunhozz/arc 0.3.2 → 0.3.4
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 +105 -147
- package/README.md +3 -3
- package/claude/agents/arc-implementer.md +4 -4
- package/claude/agents/arc-planner.md +5 -5
- package/claude/agents/arc-qa.md +4 -4
- package/claude/agents/arc-reviewer.md +4 -4
- package/claude/agents/arc-scouter.md +5 -5
- package/claude/skill/SKILL.md +13 -8
- package/claude/skill/references/arc-visual-companion.md +5 -5
- package/claude/skill/references/commit.md +8 -8
- package/claude/skill/references/coordination.md +23 -21
- package/claude/skill/references/git-recovery.md +9 -4
- package/claude/skill/references/handoff-prep.md +13 -15
- package/claude/skill/references/handoff.md +22 -22
- package/claude/skill/references/limits.md +2 -2
- package/claude/skill/references/planning.md +20 -15
- package/claude/skill/references/verification.md +9 -9
- package/claude/skill/references/worktree-creation.md +14 -0
- package/codex/agents/arc-implementer.toml +4 -4
- package/codex/agents/arc-planner.toml +4 -4
- package/codex/agents/arc-qa.toml +4 -4
- package/codex/agents/arc-reviewer.toml +4 -4
- package/codex/agents/arc-scouter.toml +4 -4
- package/codex/skill/SKILL.md +12 -8
- package/codex/skill/references/arc-visual-companion.md +2 -2
- package/codex/skill/references/commit.md +8 -8
- package/codex/skill/references/coordination.md +22 -20
- package/codex/skill/references/git-recovery.md +5 -9
- package/codex/skill/references/handoff-prep.md +9 -9
- package/codex/skill/references/handoff.md +20 -20
- package/codex/skill/references/limits.md +2 -2
- package/codex/skill/references/planning.md +15 -15
- package/codex/skill/references/verification.md +10 -10
- package/codex/skill/references/worktree-creation.md +20 -0
- package/lib/installer/global-config.mjs +2 -2
- package/lib/installer/manifest.mjs +10 -9
- package/lib/installer/package-references.mjs +2 -2
- package/lib/installer/plan.mjs +3 -1
- package/lib/installer/skill-sources.mjs +23 -0
- package/lib/installer/superpowers.mjs +5 -5
- package/lib/policy/role-policy.json +10 -10
- package/lib/prompts/agent-fragments.json +16 -16
- package/lib/runtime/bootstrap.mjs +1 -1
- package/lib/runtime/local-cli.mjs +10 -20
- package/lib/runtime/role-bridge.mjs +2 -4
- package/lib/runtime/role-dispatch-policy.mjs +4 -9
- package/lib/runtime/role-routing.mjs +1 -2
- package/lib/watch/dispatch.mjs +10 -2
- package/lib/watch/git.mjs +4 -2
- package/lib/watch/index.mjs +16 -8
- package/lib/watch/model.mjs +8 -4
- package/lib/watch/normalize-claude.mjs +89 -7
- package/lib/watch/normalize-codex.mjs +15 -11
- package/lib/watch/render.mjs +73 -19
- package/lib/watch/scope.mjs +5 -5
- package/lib/watch/watcher.mjs +110 -10
- package/package.json +2 -1
- package/scripts/check-installer-parity.mjs +3 -1
- package/scripts/update-manifest.mjs +1 -1
- package/scripts/update-runtime-assets.mjs +1 -1
- package/{codex → shared}/skill/references/handoff-worktree.md +21 -20
- package/{codex → shared}/skill/runtime/bootstrap.mjs +1 -1
- package/{codex → shared}/skill/runtime/local-cli.mjs +10 -20
- package/{codex → shared}/skill/runtime/role-bridge.mjs +2 -4
- package/{claude → shared}/skill/runtime/role-dispatch-policy.mjs +4 -9
- package/{claude → shared}/skill/runtime/role-policy.json +10 -10
- package/{claude → shared}/skill/runtime/role-routing.mjs +1 -2
- package/claude/skill/runtime/bootstrap.mjs +0 -38
- package/claude/skill/runtime/local-cli.mjs +0 -248
- package/claude/skill/runtime/role-bridge.mjs +0 -227
- package/codex/skill/references/brainstorming.md +0 -316
- package/codex/skill/references/builder-check-prompt.md +0 -23
- package/codex/skill/references/scripts/frame-template.html +0 -213
- package/codex/skill/references/scripts/helper.js +0 -167
- package/codex/skill/references/scripts/server.cjs +0 -723
- package/codex/skill/references/scripts/start-server.sh +0 -216
- package/codex/skill/references/scripts/stop-server.sh +0 -120
- package/codex/skill/references/superpowers-LICENSE +0 -21
- package/codex/skill/references/superpowers-provenance.json +0 -26
- package/codex/skill/references/test-driven-development.md +0 -330
- package/codex/skill/references/visual-companion.md +0 -299
- package/codex/skill/references/writing-good-tests.md +0 -198
- package/codex/skill/references/writing-plans.md +0 -204
- package/codex/skill/runtime/acceptance.mjs +0 -68
- package/codex/skill/runtime/adapters/claude.mjs +0 -86
- package/codex/skill/runtime/adapters/codex.mjs +0 -65
- package/codex/skill/runtime/assignment.mjs +0 -42
- package/codex/skill/runtime/capabilities.mjs +0 -44
- package/codex/skill/runtime/cli.mjs +0 -8
- package/codex/skill/runtime/command.mjs +0 -38
- package/codex/skill/runtime/cooperative-schema.mjs +0 -87
- package/codex/skill/runtime/cooperative.mjs +0 -239
- package/codex/skill/runtime/evaluate.mjs +0 -331
- package/codex/skill/runtime/external.mjs +0 -51
- package/codex/skill/runtime/gate.mjs +0 -71
- package/codex/skill/runtime/git-evidence.mjs +0 -258
- package/codex/skill/runtime/git-query.mjs +0 -88
- package/codex/skill/runtime/identity.mjs +0 -49
- package/codex/skill/runtime/operations.mjs +0 -6
- package/codex/skill/runtime/role-bridge-args.mjs +0 -148
- package/codex/skill/runtime/role-dispatch-policy.mjs +0 -110
- package/codex/skill/runtime/role-dispatch-store.mjs +0 -134
- package/codex/skill/runtime/role-observe.mjs +0 -299
- package/codex/skill/runtime/role-policy.json +0 -654
- package/codex/skill/runtime/role-routing-config.mjs +0 -19
- package/codex/skill/runtime/role-routing.mjs +0 -233
- package/codex/skill/runtime/role-supervisor.mjs +0 -356
- package/codex/skill/runtime/schema.mjs +0 -98
- package/codex/skill/runtime/scope.mjs +0 -36
- package/codex/skill/runtime/store.mjs +0 -94
- package/codex/skill/runtime/target-preparation.mjs +0 -110
- package/codex/skill/runtime/verification.mjs +0 -125
- /package/{claude → shared}/skill/references/brainstorming.md +0 -0
- /package/{claude → shared}/skill/references/builder-check-prompt.md +0 -0
- /package/{claude → shared}/skill/references/scripts/frame-template.html +0 -0
- /package/{claude → shared}/skill/references/scripts/helper.js +0 -0
- /package/{claude → shared}/skill/references/scripts/server.cjs +0 -0
- /package/{claude → shared}/skill/references/scripts/start-server.sh +0 -0
- /package/{claude → shared}/skill/references/scripts/stop-server.sh +0 -0
- /package/{claude → shared}/skill/references/superpowers-LICENSE +0 -0
- /package/{claude → shared}/skill/references/superpowers-provenance.json +0 -0
- /package/{claude → shared}/skill/references/test-driven-development.md +0 -0
- /package/{claude → shared}/skill/references/visual-companion.md +0 -0
- /package/{claude → shared}/skill/references/writing-good-tests.md +0 -0
- /package/{claude → shared}/skill/references/writing-plans.md +0 -0
- /package/{claude → shared}/skill/runtime/acceptance.mjs +0 -0
- /package/{claude → shared}/skill/runtime/adapters/claude.mjs +0 -0
- /package/{claude → shared}/skill/runtime/adapters/codex.mjs +0 -0
- /package/{claude → shared}/skill/runtime/assignment.mjs +0 -0
- /package/{claude → shared}/skill/runtime/capabilities.mjs +0 -0
- /package/{claude → shared}/skill/runtime/cli.mjs +0 -0
- /package/{claude → shared}/skill/runtime/command.mjs +0 -0
- /package/{claude → shared}/skill/runtime/cooperative-schema.mjs +0 -0
- /package/{claude → shared}/skill/runtime/cooperative.mjs +0 -0
- /package/{claude → shared}/skill/runtime/evaluate.mjs +0 -0
- /package/{claude → shared}/skill/runtime/external.mjs +0 -0
- /package/{claude → shared}/skill/runtime/gate.mjs +0 -0
- /package/{claude → shared}/skill/runtime/git-evidence.mjs +0 -0
- /package/{claude → shared}/skill/runtime/git-query.mjs +0 -0
- /package/{claude → shared}/skill/runtime/identity.mjs +0 -0
- /package/{claude → shared}/skill/runtime/operations.mjs +0 -0
- /package/{claude → shared}/skill/runtime/role-bridge-args.mjs +0 -0
- /package/{claude → shared}/skill/runtime/role-dispatch-store.mjs +0 -0
- /package/{claude → shared}/skill/runtime/role-observe.mjs +0 -0
- /package/{claude → shared}/skill/runtime/role-routing-config.mjs +0 -0
- /package/{claude → shared}/skill/runtime/role-supervisor.mjs +0 -0
- /package/{claude → shared}/skill/runtime/schema.mjs +0 -0
- /package/{claude → shared}/skill/runtime/scope.mjs +0 -0
- /package/{claude → shared}/skill/runtime/store.mjs +0 -0
- /package/{claude → shared}/skill/runtime/target-preparation.mjs +0 -0
- /package/{claude → shared}/skill/runtime/verification.mjs +0 -0
|
@@ -1,110 +0,0 @@
|
|
|
1
|
-
// Fixed policy values for composite role dispatch. Gate results mirror the recorded G1-G8 outcomes.
|
|
2
|
-
export const SUPPORTED_CLI_VERSIONS = Object.freeze({
|
|
3
|
-
claude: Object.freeze({min: '2.1.322', below: '2.2.0'}),
|
|
4
|
-
codex: Object.freeze({min: '0.167.0', below: '0.168.0'})
|
|
5
|
-
});
|
|
6
|
-
export const BRIDGE_GATE_RESULTS = Object.freeze({G1: 'fail', G2: 'fail', G3: 'pass', G4: 'pass', G5: 'wide', G6: 'strict', G7: 'pass', G8: 'pass'});
|
|
7
|
-
// No sandbox settings JSON has been recorded: G1 failed, so there is nothing to apply.
|
|
8
|
-
const RECORDED_CLAUDE_SANDBOX_SETTINGS = null;
|
|
9
|
-
const isRecordedObject = value => value !== null && typeof value === 'object' && !Array.isArray(value) && Object.keys(value).length > 0;
|
|
10
|
-
export const CLAUDE_SANDBOX_SETTINGS = BRIDGE_GATE_RESULTS.G1 === 'pass' && isRecordedObject(RECORDED_CLAUDE_SANDBOX_SETTINGS) ? RECORDED_CLAUDE_SANDBOX_SETTINGS : null;
|
|
11
|
-
/** G1 counts as passed only with an explicitly recorded settings object; otherwise the settings are null. */
|
|
12
|
-
export const effectiveClaudeSandboxSettings = policy => policy?.gates?.G1 === 'pass' && isRecordedObject(policy.claudeSandboxSettings) ? policy.claudeSandboxSettings : null;
|
|
13
|
-
// Short Claude model aliases of the lib/models Claude catalog (claude-models.json). The runtime cannot import lib/models, so they are fixed here; a test keeps both in sync.
|
|
14
|
-
export const CATALOG_MODEL_ALIASES = Object.freeze(['fable', 'opus', 'sonnet', 'haiku']);
|
|
15
|
-
export const CODEX_DELEGATION_CALL_NAMES = Object.freeze(['spawn_agent', 'wait_agent']);
|
|
16
|
-
export const DESKTOP_CHECKLIST_PASSED = Object.freeze({'claude-desktop': false, 'codex-desktop': false});
|
|
17
|
-
export const ROLE_TIMEOUT_MINUTES = Object.freeze({arc_scouter: 20, arc_planner: 20, arc_implementer: 60, arc_qa: 30, arc_reviewer: 20});
|
|
18
|
-
export const HEARTBEAT_MS = 5000;
|
|
19
|
-
export const SUPERVISOR_LOST_MS = 30000;
|
|
20
|
-
export const OBSERVE_MAX_WAIT_MS = 540000;
|
|
21
|
-
export const BRIEF_MAX_BYTES = 262144;
|
|
22
|
-
export const EVENTS_MAX_BYTES = 4194304;
|
|
23
|
-
export const CANCEL_GRACE_MS = 10000;
|
|
24
|
-
export const LOCK_RETRY_MS = 2000;
|
|
25
|
-
export const LEASE_RETENTION_MS = 2592000000;
|
|
26
|
-
export const PROBE_TIMEOUT_MS = 10000;
|
|
27
|
-
|
|
28
|
-
export const DEFAULT_POLICY = Object.freeze({
|
|
29
|
-
supportedVersions: SUPPORTED_CLI_VERSIONS,
|
|
30
|
-
gates: BRIDGE_GATE_RESULTS,
|
|
31
|
-
claudeSandboxSettings: CLAUDE_SANDBOX_SETTINGS,
|
|
32
|
-
codexDelegationCallNames: CODEX_DELEGATION_CALL_NAMES,
|
|
33
|
-
desktopChecklist: DESKTOP_CHECKLIST_PASSED,
|
|
34
|
-
roleTimeoutMinutes: ROLE_TIMEOUT_MINUTES,
|
|
35
|
-
heartbeatMs: HEARTBEAT_MS,
|
|
36
|
-
supervisorLostMs: SUPERVISOR_LOST_MS,
|
|
37
|
-
observeMaxWaitMs: OBSERVE_MAX_WAIT_MS,
|
|
38
|
-
briefMaxBytes: BRIEF_MAX_BYTES,
|
|
39
|
-
eventsMaxBytes: EVENTS_MAX_BYTES,
|
|
40
|
-
cancelGraceMs: CANCEL_GRACE_MS,
|
|
41
|
-
lockRetryMs: LOCK_RETRY_MS,
|
|
42
|
-
leaseRetentionMs: LEASE_RETENTION_MS,
|
|
43
|
-
probeTimeoutMs: PROBE_TIMEOUT_MS
|
|
44
|
-
});
|
|
45
|
-
|
|
46
|
-
export const RELEASE_CONDITIONS = Object.freeze({
|
|
47
|
-
activation_unverified: 'Verify the active configuration, both prepared markers, installed bytes, host limits and the shared lock, and inspect the lease records in <CODEX_HOME>/arc-role-dispatch for unreadable or corrupted files.',
|
|
48
|
-
'Not Available': 'Install the target platform CLI so that it is found on PATH.',
|
|
49
|
-
Unauthorized: 'Authenticate the target platform CLI.',
|
|
50
|
-
Incomplete: 'Make the target platform CLI authentication status check complete successfully.',
|
|
51
|
-
environment_unverified: 'Desktop hosts are held in this release; use a CLI host or a later ARC update that changes the support status.',
|
|
52
|
-
host_sandbox_blocked: 'Allow the host to write the Codex home and keep a detached supervisor alive, with explicit user approval.',
|
|
53
|
-
capacity_exhausted: 'Finish or release active bridge executions, or raise the host limits.',
|
|
54
|
-
permission_scope_unverified: 'Use a supported CLI version or update ARC, and verify enforcement of the role permissions and approved scope before starting.',
|
|
55
|
-
native_profile_reload_unverified: 'Verify that the host session loaded the requested profile revision.',
|
|
56
|
-
revision_changed: 'Re-run routing-status and prepare a new dispatch under the current revision.',
|
|
57
|
-
duplicate_dispatch: 'Use a new requestId, or finish the existing dispatch for the same workflow, task and role.',
|
|
58
|
-
invalid_request: 'Provide a valid request with exactly the documented keys.',
|
|
59
|
-
permission_scope_mismatch: 'Inspect the recorded permission mismatch before dependent work.',
|
|
60
|
-
model_effort_mismatch: 'Inspect the observed model and effort against the requested values.',
|
|
61
|
-
auth_rejected: 'Authenticate the target platform CLI.',
|
|
62
|
-
model_rejected: 'Choose a model the target platform accepts.',
|
|
63
|
-
effort_rejected: 'Choose an effort the target platform accepts.',
|
|
64
|
-
permission_violation_observed: 'Reconcile the observed changes before dependent work.',
|
|
65
|
-
delegation_observed: 'Reconcile the observed delegation before dependent work.',
|
|
66
|
-
invalid_output: 'Inspect the dispatch record; the CLI produced no usable result.',
|
|
67
|
-
execution_failed: 'Inspect the dispatch record for the abnormal exit.',
|
|
68
|
-
timeout: 'Inspect the dispatch record and decide whether to resume or start a new dispatch.',
|
|
69
|
-
execution_identity_unverified: 'Verify the assignment-to-execution identity before observing or resuming.',
|
|
70
|
-
terminal_state_unverified: 'Inspect the supervisor and child process state; the slot stays occupied.',
|
|
71
|
-
model_effort_unverified: 'Provide a trusted observer for the requested model and effort.'
|
|
72
|
-
});
|
|
73
|
-
export const reason = code => {
|
|
74
|
-
if (!Object.hasOwn(RELEASE_CONDITIONS, code)) throw Error(`Unknown reason code: ${code}`);
|
|
75
|
-
return {code, releaseCondition: RELEASE_CONDITIONS[code]};
|
|
76
|
-
};
|
|
77
|
-
export const profileName = (platform, role) => {
|
|
78
|
-
const suffix = role.slice('arc_'.length);
|
|
79
|
-
return platform === 'claude' ? `arc-routing-${suffix}` : `arc_routing_${suffix}`;
|
|
80
|
-
};
|
|
81
|
-
export const revisionTag = revision => `[arc-routing rev ${revision}]`;
|
|
82
|
-
|
|
83
|
-
export function bridgeGateReasons({platform, role, hostPlatform, policy = DEFAULT_POLICY}) {
|
|
84
|
-
const gates = policy.gates ?? BRIDGE_GATE_RESULTS, codes = [];
|
|
85
|
-
if (platform === 'claude' && (role === 'arc_implementer' || role === 'arc_qa') && effectiveClaudeSandboxSettings({gates, claudeSandboxSettings: policy.claudeSandboxSettings}) === null) codes.push('permission_scope_unverified');
|
|
86
|
-
if (platform === 'codex' && gates.G4 === 'fail') codes.push('permission_scope_unverified');
|
|
87
|
-
if (hostPlatform === 'codex' && gates.G2 === 'fail') codes.push('host_sandbox_blocked');
|
|
88
|
-
return [...new Set(codes)];
|
|
89
|
-
}
|
|
90
|
-
export function environmentReasons(executionEnvironment, policy = DEFAULT_POLICY) {
|
|
91
|
-
const checklist = policy.desktopChecklist ?? DESKTOP_CHECKLIST_PASSED;
|
|
92
|
-
return typeof executionEnvironment === 'string' && executionEnvironment.endsWith('-desktop') && checklist[executionEnvironment] !== true ? ['environment_unverified'] : [];
|
|
93
|
-
}
|
|
94
|
-
/** route is 'native' or 'bridge'; requested optionally carries the requested model and effort for the claims. */
|
|
95
|
-
export function initialClaims(route, policy = DEFAULT_POLICY, requested = {}) {
|
|
96
|
-
void policy;
|
|
97
|
-
const attested = source => ({level: 'operator-attested', source});
|
|
98
|
-
if (route === 'native') return {
|
|
99
|
-
identity: attested('orchestrator'),
|
|
100
|
-
model: {...attested('orchestrator'), requested: requested.model ?? null},
|
|
101
|
-
effort: {...attested('orchestrator'), requested: requested.effort ?? null},
|
|
102
|
-
permissions: {...attested('prompt-contract'), details: 'Role permissions are a prompt contract, not enforced by ARC.'},
|
|
103
|
-
terminal: attested('orchestrator')
|
|
104
|
-
};
|
|
105
|
-
const unverified = {level: 'unverified', source: 'none'};
|
|
106
|
-
return {
|
|
107
|
-
identity: {...unverified}, model: {...unverified, requested: requested.model ?? null}, effort: {...unverified, requested: requested.effort ?? null},
|
|
108
|
-
permissions: {...unverified, details: null}, terminal: {...unverified}
|
|
109
|
-
};
|
|
110
|
-
}
|
|
@@ -1,134 +0,0 @@
|
|
|
1
|
-
// Global dispatch lease storage. Every write assumes the caller holds arc-role-platform-routing.lock.
|
|
2
|
-
import fs from 'node:fs';
|
|
3
|
-
import fsp from 'node:fs/promises';
|
|
4
|
-
import path from 'node:path';
|
|
5
|
-
import crypto from 'node:crypto';
|
|
6
|
-
|
|
7
|
-
export const NON_TERMINAL_STATES = Object.freeze(['reserved', 'starting', 'running', 'unknown']);
|
|
8
|
-
export const TERMINAL_STATES = Object.freeze(['completed', 'failed', 'cancelled']);
|
|
9
|
-
const KEYS = ['version', 'dispatchId', 'workflowId', 'taskId', 'requestId', 'role', 'route', 'hostPlatform', 'executionEnvironment', 'revision', 'profileHash', 'argsDigest', 'state', 'supervisor', 'child', 'sessionId', 'timeoutMinutes', 'claims', 'reasons', 'allowedPaths', 'resultPath', 'segment', 'nativeAgentId', 'createdAt', 'updatedAt'];
|
|
10
|
-
const ID = /^[A-Za-z0-9._-]{1,128}$/;
|
|
11
|
-
const isObject = value => value && typeof value === 'object' && !Array.isArray(value);
|
|
12
|
-
const text = value => typeof value === 'string' && value.length > 0;
|
|
13
|
-
const nullableText = value => value === null || text(value);
|
|
14
|
-
const process_ = value => value === null || isObject(value) && Object.keys(value).length === 2 && Number.isInteger(value.pid) && value.pid > 0 && text(value.startTime);
|
|
15
|
-
|
|
16
|
-
export const dispatchDirectory = codexHome => path.join(codexHome, 'arc-role-dispatch');
|
|
17
|
-
const leasePath = (codexHome, dispatchId) => {
|
|
18
|
-
if (typeof dispatchId !== 'string' || !ID.test(dispatchId) || dispatchId.startsWith('.')) throw Error('Invalid dispatch id');
|
|
19
|
-
return path.join(dispatchDirectory(codexHome), `${dispatchId}.json`);
|
|
20
|
-
};
|
|
21
|
-
export function validateLease(value) {
|
|
22
|
-
if (!isObject(value) || Object.keys(value).length !== KEYS.length || KEYS.some(key => !Object.hasOwn(value, key))) throw Error('Invalid lease keys');
|
|
23
|
-
const ok = value.version === 1 && typeof value.dispatchId === 'string' && ID.test(value.dispatchId) && !value.dispatchId.startsWith('.')
|
|
24
|
-
&& ['workflowId', 'taskId', 'requestId', 'role', 'executionEnvironment', 'revision', 'createdAt', 'updatedAt'].every(key => text(value[key]))
|
|
25
|
-
&& ['native', 'bridge'].includes(value.route) && ['codex', 'claude'].includes(value.hostPlatform)
|
|
26
|
-
&& nullableText(value.profileHash) && nullableText(value.argsDigest) && nullableText(value.sessionId) && nullableText(value.resultPath) && nullableText(value.nativeAgentId)
|
|
27
|
-
&& [...NON_TERMINAL_STATES, ...TERMINAL_STATES].includes(value.state) && process_(value.supervisor) && process_(value.child)
|
|
28
|
-
&& Number.isInteger(value.timeoutMinutes) && value.timeoutMinutes > 0 && Number.isInteger(value.segment) && value.segment >= 0
|
|
29
|
-
&& (value.claims === null || isObject(value.claims)) && Array.isArray(value.reasons) && Array.isArray(value.allowedPaths) && value.allowedPaths.every(text);
|
|
30
|
-
if (!ok) throw Error('Invalid lease values');
|
|
31
|
-
return structuredClone(value);
|
|
32
|
-
}
|
|
33
|
-
/** Creates the lease directory when missing. An existing one must be a real directory owned by the current user and has its group and other access removed (0700 when the owner has full access); anything else is refused. */
|
|
34
|
-
export async function ensureDispatchDirectory(codexHome, {uid = process.getuid?.()} = {}) {
|
|
35
|
-
const directory = dispatchDirectory(codexHome);
|
|
36
|
-
await fsp.mkdir(directory, {recursive: true, mode: 0o700});
|
|
37
|
-
const stat = await fsp.lstat(directory);
|
|
38
|
-
if (!stat.isDirectory()) throw Error('Dispatch path is not a directory');
|
|
39
|
-
if (uid !== undefined && stat.uid !== uid) throw Error('Dispatch directory is not owned by the current user');
|
|
40
|
-
if ((stat.mode & 0o077) !== 0) await fsp.chmod(directory, stat.mode & 0o700); // only tightens: owner bits are never widened, so a sandbox-restricted directory still fails on write
|
|
41
|
-
return directory;
|
|
42
|
-
}
|
|
43
|
-
export async function createLease(codexHome, lease) {
|
|
44
|
-
const value = validateLease(lease);
|
|
45
|
-
await ensureDispatchDirectory(codexHome);
|
|
46
|
-
const handle = await fsp.open(leasePath(codexHome, value.dispatchId), 'wx', 0o600);
|
|
47
|
-
try { await handle.writeFile(JSON.stringify(value, null, 2) + '\n'); await handle.sync(); } finally { await handle.close(); }
|
|
48
|
-
return value;
|
|
49
|
-
}
|
|
50
|
-
export async function readLease(codexHome, dispatchId) {
|
|
51
|
-
let bytes;
|
|
52
|
-
try { bytes = await fsp.readFile(leasePath(codexHome, dispatchId), 'utf8'); } catch (error) { if (error.code === 'ENOENT') return null; throw error; }
|
|
53
|
-
return validateLease(JSON.parse(bytes));
|
|
54
|
-
}
|
|
55
|
-
export async function writeLease(codexHome, lease, {now = Date.now()} = {}) {
|
|
56
|
-
await ensureDispatchDirectory(codexHome);
|
|
57
|
-
const value = validateLease({...lease, updatedAt: new Date(now).toISOString()}), target = leasePath(codexHome, value.dispatchId);
|
|
58
|
-
const temp = path.join(dispatchDirectory(codexHome), `.${value.dispatchId}.${crypto.randomUUID()}.tmp`);
|
|
59
|
-
try {
|
|
60
|
-
const handle = await fsp.open(temp, 'wx', 0o600);
|
|
61
|
-
try { await handle.writeFile(JSON.stringify(value, null, 2) + '\n'); await handle.sync(); } finally { await handle.close(); }
|
|
62
|
-
await fsp.rename(temp, target);
|
|
63
|
-
} catch (error) { await fsp.unlink(temp).catch(() => {}); throw error; }
|
|
64
|
-
return value;
|
|
65
|
-
}
|
|
66
|
-
const HEARTBEAT_SUFFIX = '.heartbeat.json';
|
|
67
|
-
const leaseFiles = async codexHome => {
|
|
68
|
-
try { return (await fsp.readdir(dispatchDirectory(codexHome))).filter(name => name.endsWith('.json') && !name.endsWith(HEARTBEAT_SUFFIX) && !name.startsWith('.')).sort(); }
|
|
69
|
-
catch (error) { if (error.code === 'ENOENT') return []; throw error; }
|
|
70
|
-
};
|
|
71
|
-
export async function listLeases(codexHome) {
|
|
72
|
-
const leases = [];
|
|
73
|
-
for (const name of await leaseFiles(codexHome)) leases.push(validateLease(JSON.parse(await fsp.readFile(path.join(dispatchDirectory(codexHome), name), 'utf8'))));
|
|
74
|
-
return leases;
|
|
75
|
-
}
|
|
76
|
-
/** Removes only terminal leases whose updatedAt is older than retentionMs. Failures are counted, never thrown. */
|
|
77
|
-
export async function pruneTerminalLeases(codexHome, {now = Date.now(), retentionMs}) {
|
|
78
|
-
let removed = 0, errors = 0, names;
|
|
79
|
-
try { names = await leaseFiles(codexHome); } catch { return {removed, errors: 1}; }
|
|
80
|
-
for (const name of names) {
|
|
81
|
-
const file = path.join(dispatchDirectory(codexHome), name);
|
|
82
|
-
try {
|
|
83
|
-
const lease = validateLease(JSON.parse(await fsp.readFile(file, 'utf8')));
|
|
84
|
-
const updated = Date.parse(lease.updatedAt);
|
|
85
|
-
if (!TERMINAL_STATES.includes(lease.state) || !Number.isFinite(updated) || now - updated <= retentionMs) continue;
|
|
86
|
-
await fsp.unlink(file); removed += 1;
|
|
87
|
-
for (const extra of [`${lease.dispatchId}${HEARTBEAT_SUFFIX}`, `${lease.dispatchId}.cancel`]) await fsp.unlink(path.join(dispatchDirectory(codexHome), extra)).catch(() => {});
|
|
88
|
-
} catch { errors += 1; }
|
|
89
|
-
}
|
|
90
|
-
return {removed, errors};
|
|
91
|
-
}
|
|
92
|
-
/** Reads only the three keys written by serializeLimits; any other content is rejected. */
|
|
93
|
-
export function readHostLimits(hostHome) {
|
|
94
|
-
const values = {};
|
|
95
|
-
for (const raw of fs.readFileSync(path.join(hostHome, 'skills', 'arc', 'limits.toml'), 'utf8').split(/\r?\n/)) {
|
|
96
|
-
const line = raw.trim();
|
|
97
|
-
if (!line || line.startsWith('#')) continue;
|
|
98
|
-
const match = /^([a-z_]+)[ \t]*=[ \t]*(\d{1,15})[ \t]*(?:#.*)?$/.exec(line);
|
|
99
|
-
if (!match || !['version', 'max_total_subagents', 'max_concurrent_subagents'].includes(match[1]) || Object.hasOwn(values, match[1])) throw Error('Invalid limits file');
|
|
100
|
-
values[match[1]] = Number(match[2]);
|
|
101
|
-
}
|
|
102
|
-
if (Object.keys(values).length !== 3 || values.version !== 1 || values.max_total_subagents < 1 || values.max_concurrent_subagents < 1) throw Error('Invalid limits file');
|
|
103
|
-
return {maxTotal: values.max_total_subagents, maxConcurrent: values.max_concurrent_subagents};
|
|
104
|
-
}
|
|
105
|
-
|
|
106
|
-
const sidecarPath = (codexHome, dispatchId, suffix) => path.join(dispatchDirectory(codexHome), `${path.basename(leasePath(codexHome, dispatchId), '.json')}${suffix}`);
|
|
107
|
-
/** The supervisor alone writes its heartbeat; no routing lock is needed because the file is replaced atomically and holds no lease state. */
|
|
108
|
-
export async function writeHeartbeat(codexHome, dispatchId, {at, pid}) {
|
|
109
|
-
if (!Number.isFinite(at) || !Number.isInteger(pid) || pid <= 0) throw Error('Invalid heartbeat');
|
|
110
|
-
const target = sidecarPath(codexHome, dispatchId, HEARTBEAT_SUFFIX), temp = path.join(dispatchDirectory(codexHome), `.${dispatchId}.${crypto.randomUUID()}.hb.tmp`);
|
|
111
|
-
try {
|
|
112
|
-
const handle = await fsp.open(temp, 'wx', 0o600);
|
|
113
|
-
try { await handle.writeFile(JSON.stringify({at, pid}) + '\n'); } finally { await handle.close(); }
|
|
114
|
-
await fsp.rename(temp, target);
|
|
115
|
-
} catch (error) { await fsp.unlink(temp).catch(() => {}); throw error; }
|
|
116
|
-
}
|
|
117
|
-
export async function readHeartbeat(codexHome, dispatchId) {
|
|
118
|
-
try {
|
|
119
|
-
const value = JSON.parse(await fsp.readFile(sidecarPath(codexHome, dispatchId, HEARTBEAT_SUFFIX), 'utf8'));
|
|
120
|
-
return isObject(value) && Number.isFinite(value.at) && Number.isInteger(value.pid) ? {at: value.at, pid: value.pid} : null;
|
|
121
|
-
} catch { return null; }
|
|
122
|
-
}
|
|
123
|
-
/** Marker file asking the supervisor to stop the child; the supervisor polls for it. */
|
|
124
|
-
export async function requestCancel(codexHome, dispatchId) {
|
|
125
|
-
const handle = await fsp.open(sidecarPath(codexHome, dispatchId, '.cancel'), 'a', 0o600);
|
|
126
|
-
await handle.close();
|
|
127
|
-
}
|
|
128
|
-
/** Removes a stale cancel marker before a resumed segment starts; the caller holds the routing lock. */
|
|
129
|
-
export async function clearCancel(codexHome, dispatchId) {
|
|
130
|
-
try { await fsp.unlink(sidecarPath(codexHome, dispatchId, '.cancel')); } catch (error) { if (error.code !== 'ENOENT') throw error; }
|
|
131
|
-
}
|
|
132
|
-
export async function cancelRequested(codexHome, dispatchId) {
|
|
133
|
-
try { await fsp.access(sidecarPath(codexHome, dispatchId, '.cancel')); return true; } catch { return false; }
|
|
134
|
-
}
|
|
@@ -1,299 +0,0 @@
|
|
|
1
|
-
// Pure observation helpers: stream/transcript/rollout normalization, model, permission and failure judgement, and worktree snapshot comparison.
|
|
2
|
-
// The only process started here is read-only `git` for snapshots; no CLI is ever run.
|
|
3
|
-
import crypto from 'node:crypto';
|
|
4
|
-
import fs from 'node:fs';
|
|
5
|
-
import fsp from 'node:fs/promises';
|
|
6
|
-
import path from 'node:path';
|
|
7
|
-
import readline from 'node:readline';
|
|
8
|
-
import zlib from 'node:zlib';
|
|
9
|
-
import {execFile} from 'node:child_process';
|
|
10
|
-
import {promisify} from 'node:util';
|
|
11
|
-
import {DEFAULT_POLICY, CATALOG_MODEL_ALIASES} from './role-dispatch-policy.mjs';
|
|
12
|
-
|
|
13
|
-
const execFileAsync = promisify(execFile);
|
|
14
|
-
const isObject = value => value !== null && typeof value === 'object' && !Array.isArray(value);
|
|
15
|
-
const text = value => typeof value === 'string' && value !== '' ? value : undefined;
|
|
16
|
-
const defined = object => Object.fromEntries(Object.entries(object).filter(([, value]) => value !== undefined));
|
|
17
|
-
|
|
18
|
-
/** Splits chunked output into JSON objects. Non-JSON lines are counted and ignored; lines over maxLineBytes are dropped and flagged. */
|
|
19
|
-
export function createLineParser(onLine, {maxLineBytes = 1048576} = {}) {
|
|
20
|
-
let parts = [], length = 0, skipping = false, overflow = false, ignored = 0;
|
|
21
|
-
const emit = buffer => {
|
|
22
|
-
const line = buffer.toString('utf8').trim();
|
|
23
|
-
if (line === '') return;
|
|
24
|
-
let value;
|
|
25
|
-
try { value = JSON.parse(line); } catch { ignored++; return; }
|
|
26
|
-
if (isObject(value)) onLine(value); else ignored++;
|
|
27
|
-
};
|
|
28
|
-
const drop = () => { overflow = true; skipping = true; parts = []; length = 0; };
|
|
29
|
-
return {
|
|
30
|
-
push(chunk) {
|
|
31
|
-
let start = 0;
|
|
32
|
-
for (;;) {
|
|
33
|
-
const newline = chunk.indexOf(10, start);
|
|
34
|
-
if (newline < 0) {
|
|
35
|
-
if (!skipping) {
|
|
36
|
-
const rest = chunk.subarray(start);
|
|
37
|
-
parts.push(rest); length += rest.length;
|
|
38
|
-
if (length > maxLineBytes) drop();
|
|
39
|
-
}
|
|
40
|
-
return;
|
|
41
|
-
}
|
|
42
|
-
const piece = chunk.subarray(start, newline); start = newline + 1;
|
|
43
|
-
if (skipping) { skipping = false; continue; }
|
|
44
|
-
if (length + piece.length > maxLineBytes) { overflow = true; parts = []; length = 0; continue; }
|
|
45
|
-
const line = parts.length ? Buffer.concat([...parts, piece]) : piece;
|
|
46
|
-
parts = []; length = 0;
|
|
47
|
-
emit(line);
|
|
48
|
-
}
|
|
49
|
-
},
|
|
50
|
-
end() {
|
|
51
|
-
if (!skipping && length > 0) emit(Buffer.concat(parts));
|
|
52
|
-
parts = []; length = 0; skipping = false;
|
|
53
|
-
},
|
|
54
|
-
get overflow() { return overflow; },
|
|
55
|
-
get ignored() { return ignored; }
|
|
56
|
-
};
|
|
57
|
-
}
|
|
58
|
-
|
|
59
|
-
export function normalizeClaudeStreamEvent(obj) {
|
|
60
|
-
if (!isObject(obj)) return null;
|
|
61
|
-
if (obj.type === 'system' && obj.subtype === 'init') {
|
|
62
|
-
return defined({kind: 'init', sessionId: text(obj.session_id), model: text(obj.model), tools: Array.isArray(obj.tools) && obj.tools.every(tool => typeof tool === 'string') ? obj.tools : undefined, permissionMode: text(obj.permissionMode)});
|
|
63
|
-
}
|
|
64
|
-
if (obj.type === 'result') {
|
|
65
|
-
return defined({kind: 'result', sessionId: text(obj.session_id), isError: obj.is_error === true || (obj.subtype !== undefined && obj.subtype !== 'success'), resultText: typeof obj.result === 'string' ? obj.result : undefined});
|
|
66
|
-
}
|
|
67
|
-
return {kind: 'other'};
|
|
68
|
-
}
|
|
69
|
-
|
|
70
|
-
export function normalizeCodexStreamEvent(obj) {
|
|
71
|
-
if (!isObject(obj)) return null;
|
|
72
|
-
if (obj.type === 'thread.started') return defined({kind: 'thread', threadId: text(obj.thread_id)});
|
|
73
|
-
if (obj.type === 'turn.completed') return {kind: 'turn_completed'};
|
|
74
|
-
if (obj.type === 'turn.failed') return defined({kind: 'turn_failed', message: text(obj.error?.message) ?? text(obj.message)});
|
|
75
|
-
if (obj.type === 'error') return defined({kind: 'warning', message: text(obj.message)});
|
|
76
|
-
if (obj.type === 'item.completed' && isObject(obj.item) && obj.item.type === 'error') return defined({kind: 'warning', message: text(obj.item.message)});
|
|
77
|
-
return {kind: 'other'};
|
|
78
|
-
}
|
|
79
|
-
|
|
80
|
-
/** events.jsonl record: free text (resultText, message) never leaves the normalized event. */
|
|
81
|
-
export function eventRecord(normalized) {
|
|
82
|
-
if (!isObject(normalized)) return {};
|
|
83
|
-
const {resultText, message, ...rest} = normalized;
|
|
84
|
-
void resultText; void message;
|
|
85
|
-
return rest;
|
|
86
|
-
}
|
|
87
|
-
|
|
88
|
-
export const matchModel = (requested, observed) => {
|
|
89
|
-
if (typeof requested !== 'string' || typeof observed !== 'string' || requested === '' || observed === '') return false;
|
|
90
|
-
return CATALOG_MODEL_ALIASES.includes(requested) ? observed.split('-').includes(requested) : requested === observed;
|
|
91
|
-
};
|
|
92
|
-
|
|
93
|
-
const sameSet = (left, right) => left.length === right.length && new Set(left).size === left.length && new Set(right).size === right.length && left.every(item => right.includes(item));
|
|
94
|
-
const observedClaim = (level, source, extra) => ({level, source, ...extra});
|
|
95
|
-
|
|
96
|
-
export function evaluateClaudeInit({init, expected}) {
|
|
97
|
-
if (!isObject(init) || init.kind !== 'init') {
|
|
98
|
-
const none = {level: 'unverified', source: 'none'};
|
|
99
|
-
return {reason: null, claims: {identity: {...none}, model: {...none, requested: expected?.model ?? null}, permissions: {...none, details: null}}};
|
|
100
|
-
}
|
|
101
|
-
const tools = Array.isArray(init.tools) ? init.tools : null;
|
|
102
|
-
const toolsOk = tools !== null && sameSet(tools, expected.tools) && !tools.some(tool => tool.startsWith('mcp__'));
|
|
103
|
-
const permissionOk = toolsOk && init.permissionMode === expected.permissionMode;
|
|
104
|
-
const modelMissing = init.model === undefined || init.model === null || init.model === '', modelOk = !modelMissing && matchModel(expected.model, init.model);
|
|
105
|
-
const claims = {
|
|
106
|
-
identity: observedClaim(init.sessionId ? 'runtime-observed' : 'unverified', 'claude-stream-init', {observed: init.sessionId ?? null}),
|
|
107
|
-
model: observedClaim(modelOk ? 'runtime-observed' : 'unverified', 'claude-stream-init', {requested: expected.model, observed: init.model ?? null, ...(modelMissing ? {label: 'model_effort_unverified'} : {})}),
|
|
108
|
-
permissions: observedClaim(permissionOk ? 'runtime-observed' : 'unverified', 'claude-stream-init', {details: permissionOk ? null : 'tools or permissionMode differ from the requested values', observed: {tools, permissionMode: init.permissionMode ?? null}})
|
|
109
|
-
};
|
|
110
|
-
return {reason: !permissionOk ? 'permission_scope_mismatch' : !modelOk && !modelMissing ? 'model_effort_mismatch' : null, claims};
|
|
111
|
-
}
|
|
112
|
-
|
|
113
|
-
const SAFE_ID = /^[A-Za-z0-9][A-Za-z0-9._-]*$/;
|
|
114
|
-
const readLines = async function* (filename) {
|
|
115
|
-
const reader = readline.createInterface({input: fs.createReadStream(filename, {encoding: 'utf8'}), crlfDelay: Infinity});
|
|
116
|
-
try {
|
|
117
|
-
for await (const line of reader) {
|
|
118
|
-
if (line === '') continue;
|
|
119
|
-
try { const value = JSON.parse(line); if (isObject(value)) yield value; } catch { /* unparsable lines are skipped */ }
|
|
120
|
-
}
|
|
121
|
-
} finally { reader.close(); }
|
|
122
|
-
};
|
|
123
|
-
|
|
124
|
-
/** Reads only the effort fields (output_config.effort or effort) from projects/<dir>/<sessionId>.jsonl; returns the last value or null. */
|
|
125
|
-
export async function readClaudeTranscriptEffort({claudeHome, sessionId}) {
|
|
126
|
-
if (typeof sessionId !== 'string' || !SAFE_ID.test(sessionId)) return null;
|
|
127
|
-
let directories;
|
|
128
|
-
try { directories = await fsp.readdir(path.join(claudeHome, 'projects'), {withFileTypes: true}); } catch { return null; }
|
|
129
|
-
let effort = null;
|
|
130
|
-
for (const entry of directories.filter(item => item.isDirectory()).sort((a, b) => a.name.localeCompare(b.name))) {
|
|
131
|
-
const filename = path.join(claudeHome, 'projects', entry.name, `${sessionId}.jsonl`);
|
|
132
|
-
try { await fsp.access(filename); } catch { continue; }
|
|
133
|
-
try {
|
|
134
|
-
for await (const line of readLines(filename)) {
|
|
135
|
-
const value = text(line.output_config?.effort) ?? text(line.effort);
|
|
136
|
-
if (value !== undefined) effort = value;
|
|
137
|
-
}
|
|
138
|
-
} catch { /* unreadable transcript: keep what was read */ }
|
|
139
|
-
}
|
|
140
|
-
return effort;
|
|
141
|
-
}
|
|
142
|
-
|
|
143
|
-
/** Collects rollout files named rollout-*-<threadId>.jsonl (suffix match only; also .jsonl.zst) up to three directories below sessions/. */
|
|
144
|
-
async function findRollouts(directory, suffixes, depth = 0, found = []) {
|
|
145
|
-
let entries;
|
|
146
|
-
try { entries = await fsp.readdir(directory, {withFileTypes: true}); } catch { return found; }
|
|
147
|
-
entries.sort((x, y) => x.name.localeCompare(y.name));
|
|
148
|
-
for (const entry of entries) if (entry.isFile() && entry.name.startsWith('rollout-') && suffixes.some(suffix => entry.name.endsWith(suffix))) found.push(path.join(directory, entry.name));
|
|
149
|
-
if (depth < 3) for (const entry of entries) if (entry.isDirectory()) await findRollouts(path.join(directory, entry.name), suffixes, depth + 1, found);
|
|
150
|
-
return found;
|
|
151
|
-
}
|
|
152
|
-
|
|
153
|
-
/** Returns every turn_context of the thread as turns[] (plus the last one's fields); null when the rollout is missing, ambiguous or has no turn_context. */
|
|
154
|
-
const THREAD_ID = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;
|
|
155
|
-
const ROLLOUT_MAX_BYTES = 64 * 1024 * 1024;
|
|
156
|
-
const parseJsonLines = function* (content) {
|
|
157
|
-
for (const line of content.split('\n')) {
|
|
158
|
-
if (line === '') continue;
|
|
159
|
-
try { const value = JSON.parse(line); if (isObject(value)) yield value; } catch { /* unparsable lines are skipped */ }
|
|
160
|
-
}
|
|
161
|
-
};
|
|
162
|
-
/** zstdDecompress is injectable for tests; null (or a missing zlib function) means compressed rollouts cannot be read. */
|
|
163
|
-
export async function readCodexTurnContext({codexHome, threadId, delegationNames = [], zstdDecompress = zlib.zstdDecompressSync}) {
|
|
164
|
-
if (typeof threadId !== 'string' || !THREAD_ID.test(threadId)) return null; // only a full thread UUID can match the -<threadId>.jsonl suffix unambiguously
|
|
165
|
-
const files = await findRollouts(path.join(codexHome, 'sessions'), [`-${threadId}.jsonl`, `-${threadId}.jsonl.zst`]);
|
|
166
|
-
if (files.length !== 1) return null;
|
|
167
|
-
const turns = []; let delegationObserved = false;
|
|
168
|
-
try {
|
|
169
|
-
let lines;
|
|
170
|
-
if (files[0].endsWith('.zst')) {
|
|
171
|
-
if (typeof zstdDecompress !== 'function') return null;
|
|
172
|
-
const compressed = await fsp.readFile(files[0]);
|
|
173
|
-
if (compressed.length > ROLLOUT_MAX_BYTES) return null;
|
|
174
|
-
const output = zstdDecompress(compressed, {maxOutputLength: ROLLOUT_MAX_BYTES});
|
|
175
|
-
if (!Buffer.isBuffer(output) || output.length > ROLLOUT_MAX_BYTES) return null;
|
|
176
|
-
lines = parseJsonLines(output.toString('utf8'));
|
|
177
|
-
} else lines = readLines(files[0]);
|
|
178
|
-
for await (const line of lines) {
|
|
179
|
-
if (line.type === 'turn_context' && isObject(line.payload)) {
|
|
180
|
-
const p = line.payload;
|
|
181
|
-
turns.push({model: text(p.model) ?? null, effort: text(p.effort) ?? text(p.collaboration_mode?.settings?.reasoning_effort) ?? null, sandboxMode: text(p.sandbox_policy?.type) ?? null, approvalPolicy: text(p.approval_policy) ?? null});
|
|
182
|
-
} else if (line.type === 'response_item' && line.payload?.type === 'function_call' && delegationNames.includes(line.payload.name)) delegationObserved = true;
|
|
183
|
-
}
|
|
184
|
-
} catch { return null; }
|
|
185
|
-
if (turns.length === 0) return null;
|
|
186
|
-
return {...turns.at(-1), delegationObserved, turns};
|
|
187
|
-
}
|
|
188
|
-
|
|
189
|
-
export function evaluateCodexContext({context, expected, policy = DEFAULT_POLICY}) {
|
|
190
|
-
const gates = policy.gates ?? DEFAULT_POLICY.gates;
|
|
191
|
-
if (!isObject(context)) {
|
|
192
|
-
const none = {level: 'unverified', source: 'none'};
|
|
193
|
-
return {reason: null, claims: {model: {...none, requested: expected.model}, effort: {...none, requested: expected.effort}, permissions: {...none, details: null}}};
|
|
194
|
-
}
|
|
195
|
-
const turns = Array.isArray(context.turns) && context.turns.length ? context.turns : [context];
|
|
196
|
-
const present = value => value !== undefined && value !== null && value !== '';
|
|
197
|
-
// Per field: 'ok' when every turn matches, 'mismatch' when any observed value differs, 'missing' when a value was not observed.
|
|
198
|
-
const judge = (field, same) => {
|
|
199
|
-
if (turns.some(item => present(item[field]) && !same(item[field]))) return 'mismatch';
|
|
200
|
-
return turns.every(item => present(item[field])) ? 'ok' : 'missing';
|
|
201
|
-
};
|
|
202
|
-
const model = judge('model', value => matchModel(expected.model, value)), effort = judge('effort', value => value === expected.effort);
|
|
203
|
-
const sandbox = judge('sandboxMode', value => value === expected.sandboxMode), approval = judge('approvalPolicy', value => value === expected.approvalPolicy);
|
|
204
|
-
const settings = sandbox === 'mismatch' || approval === 'mismatch' ? 'mismatch' : sandbox === 'ok' && approval === 'ok' ? 'ok' : 'missing';
|
|
205
|
-
const delegationDetectable = gates.G3 === 'pass', delegated = delegationDetectable && context.delegationObserved === true;
|
|
206
|
-
// The child loads the user's Codex config (MCP servers and so on), which ARC does not control: the claim never exceeds operator-attested.
|
|
207
|
-
const notes = ['user-config-mcp-not-controlled'];
|
|
208
|
-
if (gates.G5 === 'wide') notes.push('writable-root-wider-than-worktree');
|
|
209
|
-
if (!delegationDetectable) notes.push('delegation-not-detectable');
|
|
210
|
-
if (settings === 'mismatch') notes.push('sandbox or approval policy differs from the requested values');
|
|
211
|
-
if (settings === 'missing') notes.push('sandbox or approval policy not observed');
|
|
212
|
-
if (delegated) notes.push('delegation call observed');
|
|
213
|
-
const permissionLevel = settings !== 'ok' || delegated ? 'unverified' : 'operator-attested';
|
|
214
|
-
const claimOf = (state, requested, field) => observedClaim(state === 'ok' ? 'runtime-observed' : 'unverified', 'codex-rollout', {requested, observed: context[field] ?? null, ...(state === 'missing' ? {label: 'model_effort_unverified'} : {})});
|
|
215
|
-
const claims = {
|
|
216
|
-
model: claimOf(model, expected.model, 'model'), effort: claimOf(effort, expected.effort, 'effort'),
|
|
217
|
-
permissions: observedClaim(permissionLevel, 'codex-rollout', {details: notes.length ? notes.join('; ') : null, observed: {sandboxMode: context.sandboxMode ?? null, approvalPolicy: context.approvalPolicy ?? null}})
|
|
218
|
-
};
|
|
219
|
-
return {reason: settings === 'mismatch' ? 'permission_scope_mismatch' : model === 'mismatch' || effort === 'mismatch' ? 'model_effort_mismatch' : delegated ? 'delegation_observed' : null, claims};
|
|
220
|
-
}
|
|
221
|
-
|
|
222
|
-
const AUTH = /\b(401|unauthori[sz]ed|not logged in|authentication)\b/i;
|
|
223
|
-
const MODEL = /model\b.*\b(not found|not supported|does not exist|unavailable|invalid)\b/i;
|
|
224
|
-
const EFFORT = /(effort|reasoning)\b.*\b(invalid|unsupported|not supported)\b/i;
|
|
225
|
-
/**
|
|
226
|
-
* Returns null for a successful termination, otherwise the failure class.
|
|
227
|
-
* - terminal: true only when a terminal event was observed (Claude result, Codex turn.completed/turn.failed).
|
|
228
|
-
* - terminalError: true when that terminal event reports an error (Claude result.is_error, Codex turn.failed).
|
|
229
|
-
* - messages: error-source text only: Claude result/error text when is_error is true, Codex turn.failed/error event messages, and stderr.
|
|
230
|
-
* Never pass assistant output or successful result text; the auth/model/effort patterns would match ordinary prose.
|
|
231
|
-
*/
|
|
232
|
-
export function classifyFailure({exitCode, signal, terminal, terminalError = false, messages = []}) {
|
|
233
|
-
if (exitCode === 0 && (signal === null || signal === undefined) && terminal === true && terminalError !== true) return null;
|
|
234
|
-
const lines = (Array.isArray(messages) ? messages : []).filter(message => typeof message === 'string');
|
|
235
|
-
if (lines.some(line => AUTH.test(line))) return 'auth_rejected';
|
|
236
|
-
if (lines.some(line => MODEL.test(line))) return 'model_rejected';
|
|
237
|
-
if (lines.some(line => EFFORT.test(line))) return 'effort_rejected';
|
|
238
|
-
return terminal ? 'execution_failed' : 'invalid_output';
|
|
239
|
-
}
|
|
240
|
-
|
|
241
|
-
const gitEnv = () => {
|
|
242
|
-
const env = Object.fromEntries(Object.entries(process.env).filter(([key]) => !key.toUpperCase().startsWith('GIT_')));
|
|
243
|
-
return Object.assign(env, {GIT_CONFIG_NOSYSTEM: '1', GIT_CONFIG_GLOBAL: process.platform === 'win32' ? 'NUL' : '/dev/null', GIT_OPTIONAL_LOCKS: '0', GIT_NO_REPLACE_OBJECTS: '1', GIT_NO_LAZY_FETCH: '1', GIT_TERMINAL_PROMPT: '0'});
|
|
244
|
-
};
|
|
245
|
-
const git = async (cwd, args, {allowFailure = false} = {}) => {
|
|
246
|
-
try {
|
|
247
|
-
const {stdout} = await execFileAsync('git', ['--no-pager', '-c', 'core.fsmonitor=false', ...args], {cwd, env: gitEnv(), encoding: 'utf8', timeout: 60000, maxBuffer: 256 * 1024 * 1024});
|
|
248
|
-
return stdout;
|
|
249
|
-
} catch (error) {
|
|
250
|
-
if (allowFailure) return null;
|
|
251
|
-
throw Error(`Git observation failed: ${args[0]}${error.code ? ` (${error.code})` : ''}`);
|
|
252
|
-
}
|
|
253
|
-
};
|
|
254
|
-
const sha256 = value => crypto.createHash('sha256').update(value).digest('hex');
|
|
255
|
-
async function contentDigest(filename) {
|
|
256
|
-
let stat;
|
|
257
|
-
try { stat = await fsp.lstat(filename); } catch (error) { return error.code === 'ENOENT' ? sha256('deleted') : sha256('unreadable'); }
|
|
258
|
-
if (stat.isSymbolicLink()) { try { return sha256('link:' + await fsp.readlink(filename)); } catch { return sha256('unreadable'); } }
|
|
259
|
-
if (!stat.isFile()) return sha256('directory');
|
|
260
|
-
return await new Promise(resolve => {
|
|
261
|
-
const hash = crypto.createHash('sha256'), stream = fs.createReadStream(filename);
|
|
262
|
-
stream.on('data', chunk => hash.update(chunk)); stream.on('end', () => resolve(hash.digest('hex'))); stream.on('error', () => resolve(sha256('unreadable')));
|
|
263
|
-
});
|
|
264
|
-
}
|
|
265
|
-
|
|
266
|
-
/** 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. */
|
|
267
|
-
export async function snapshotWorktree(worktree) {
|
|
268
|
-
const root = (await git(worktree, ['rev-parse', '--show-toplevel'])).trim();
|
|
269
|
-
const head = (await git(root, ['rev-parse', '--verify', '--quiet', 'HEAD'], {allowFailure: true}))?.trim() || null;
|
|
270
|
-
const branch = (await git(root, ['symbolic-ref', '--quiet', '--short', 'HEAD'], {allowFailure: true}))?.trim() || null;
|
|
271
|
-
const refs = {};
|
|
272
|
-
for (const line of (await git(root, ['for-each-ref', '--format=%(refname) %(objectname)'])).split('\n')) {
|
|
273
|
-
const at = line.lastIndexOf(' ');
|
|
274
|
-
if (at > 0) refs[line.slice(0, at)] = line.slice(at + 1);
|
|
275
|
-
}
|
|
276
|
-
const status = await git(root, ['status', '--porcelain=v1', '-z', '--untracked-files=all']);
|
|
277
|
-
const tokens = status.split('\0'), entries = new Map();
|
|
278
|
-
for (let i = 0; i < tokens.length; i++) {
|
|
279
|
-
const token = tokens[i];
|
|
280
|
-
if (token === '') continue;
|
|
281
|
-
const code = token.slice(0, 2), file = token.slice(3);
|
|
282
|
-
entries.set(file, `${code}:${await contentDigest(path.join(root, file))}`);
|
|
283
|
-
if (code.includes('R') || code.includes('C')) { const origin = tokens[++i]; if (origin) entries.set(origin, `${code}:${sha256('deleted')}`); }
|
|
284
|
-
}
|
|
285
|
-
return {head, branch, refs, entries};
|
|
286
|
-
}
|
|
287
|
-
|
|
288
|
-
const allowedBy = (allowedPaths, file) => allowedPaths.some(entry => entry.endsWith('/') ? file.startsWith(entry) : file === entry);
|
|
289
|
-
/** 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 not observed. */
|
|
290
|
-
export function detectViolations({role, allowedPaths, before, after}) {
|
|
291
|
-
const headChanged = before.head !== after.head || before.branch !== after.branch;
|
|
292
|
-
const refsBefore = before.refs ?? {}, refsAfter = after.refs ?? {};
|
|
293
|
-
const refsChanged = [...new Set([...Object.keys(refsBefore), ...Object.keys(refsAfter)])].some(name => refsBefore[name] !== refsAfter[name]);
|
|
294
|
-
const allowed = (role === 'arc_implementer' || role === 'arc_qa') && Array.isArray(allowedPaths) ? allowedPaths : [];
|
|
295
|
-
const changed = new Set();
|
|
296
|
-
for (const file of new Set([...before.entries.keys(), ...after.entries.keys()])) if (before.entries.get(file) !== after.entries.get(file)) changed.add(file);
|
|
297
|
-
const changedPaths = [...changed].filter(file => !allowedBy(allowed, file)).sort();
|
|
298
|
-
return {reason: headChanged || refsChanged || changedPaths.length ? 'permission_violation_observed' : null, changedPaths, headChanged, refsChanged};
|
|
299
|
-
}
|