@yunhozz/arc 0.4.4 → 0.4.5
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 +53 -51
- package/claude/skill/SKILL.md +1 -1
- package/claude/skill/references/commit.md +6 -4
- package/claude/skill/references/coordination.md +84 -9
- 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 +84 -9
- 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 +85 -10
- 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 +88 -13
- 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 +234 -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 +30 -5
- package/lib/runtime/role-routing.mjs +31 -4
- package/lib/runtime/role-supervisor.mjs +77 -16
- package/package.json +1 -1
- package/shared/skill/runtime/bootstrap.mjs +1 -1
- package/shared/skill/runtime/grok-sandbox.mjs +234 -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 +30 -5
- package/shared/skill/runtime/role-policy.json +2 -2
- package/shared/skill/runtime/role-routing.mjs +31 -4
- package/shared/skill/runtime/role-supervisor.mjs +77 -16
|
@@ -3,9 +3,9 @@ import {runtimeRegistryOf, DEFAULT_PLATFORM_REGISTRY} from './platform-registry.
|
|
|
3
3
|
// run-dispatch only asks the supervisor (the sole child spawner) to start; observe reads and records state under the routing lock.
|
|
4
4
|
import fsp from 'node:fs/promises';
|
|
5
5
|
import path from 'node:path';
|
|
6
|
-
import {DEFAULT_POLICY, reason, profileName, bridgeGateReasons, environmentReasons, capabilityReasons} from './role-dispatch-policy.mjs';
|
|
6
|
+
import {DEFAULT_POLICY, HOST_SANDBOX_GATES, reason, profileName, bridgeGateReasons, environmentReasons, capabilityReasons} from './role-dispatch-policy.mjs';
|
|
7
7
|
import {readLease, writeLease, listLeases, readHostLimits, NON_TERMINAL_STATES, readHeartbeat, requestCancel, clearCancel, TERMINAL_STATES, validateLease} from './role-dispatch-store.mjs';
|
|
8
|
-
import {withRoutingLock, readActivation, readRevision, authenticate, resolveRuntimeHomes, locateAnchorHome} from './role-routing.mjs';
|
|
8
|
+
import {withRoutingLock, readActivation, readRevision, authenticate, resolveRuntimeHomes, locateAnchorHome, probeHomeWritable} from './role-routing.mjs';
|
|
9
9
|
import {SUPERVISOR_IMPLEMENTATIONS, startSupervisor, processAlive, resolveWorktree, artifactDirectory, segmentDirectory, buildBridgeInvocation} from './role-supervisor.mjs';
|
|
10
10
|
|
|
11
11
|
export const heldRoutingResult=(code,releaseCondition)=>({decision:'hold',routeStatus:'held',supportStatus:'unverified',route:null,executionEnvironment:null,hostPlatform:null,role:null,requested:null,authentication:null,reasons:[{code,releaseCondition}]});
|
|
@@ -47,16 +47,20 @@ export async function runBridgeDispatch({context,dispatchId,brief,now=Date.now()
|
|
|
47
47
|
await withRoutingLock(anchorHome,async()=>{
|
|
48
48
|
const lease=await readLease(anchorHome,dispatchId,{runtimePlatforms});
|
|
49
49
|
if(!lease||lease.workflowId!==context.workflowId||lease.hostPlatform!==context.hostPlatform||lease.route!=='bridge'||lease.state!=='reserved'){result=blank(context,dispatchId,'deny','invalid_request');return;}
|
|
50
|
-
leaseTargetPlatform(lease,runtimePlatforms);
|
|
50
|
+
const platform=leaseTargetPlatform(lease,runtimePlatforms);
|
|
51
51
|
let config;try{config=await readActivation(homes,lease.revision,{anchorHome,host:context.hostPlatform,runtimePlatforms});}catch{result=blank(context,dispatchId,'hold','activation_unverified');return;}
|
|
52
52
|
validateLease(lease,{runtimePlatforms,config});
|
|
53
|
-
const capabilities=capabilityReasons({hostPlatform:lease.hostPlatform,targetPlatform:
|
|
53
|
+
const capabilities=capabilityReasons({hostPlatform:lease.hostPlatform,targetPlatform:platform,route:lease.route,runtimePlatforms});
|
|
54
54
|
if(capabilities.length){result=blank(context,dispatchId,'hold',capabilities[0]);return;}
|
|
55
55
|
let target;try{target=await resolveWorktree(context.cwd);}catch{result=blank(context,dispatchId,'hold','activation_unverified');return;}
|
|
56
56
|
const directory=artifactDirectory(target,lease.workflowId,dispatchId),resultPath=path.join(directory,'result.md');
|
|
57
57
|
let invocation;try{invocation=await buildBridgeInvocation({lease,config,homes,worktree:target.realpath,resultPath,policy});}catch(error){result=blank(context,dispatchId,'hold',error.reasonCode??'activation_unverified');return;}
|
|
58
58
|
await fsp.mkdir(directory,{recursive:true,mode:0o700});await fsp.chmod(directory,0o700);
|
|
59
59
|
await fsp.writeFile(path.join(directory,'brief.md'),brief,{mode:0o600,flag:'w'});await fsp.chmod(path.join(directory,'brief.md'),0o600);
|
|
60
|
+
if(Object.hasOwn(HOST_SANDBOX_GATES,lease.hostPlatform)){
|
|
61
|
+
const probe=await probeHomeWritable(homes[platform]);
|
|
62
|
+
if(!probe.ok){result=hold(context,dispatchId,probe.code,probe);return;}
|
|
63
|
+
}
|
|
60
64
|
let supervisor;
|
|
61
65
|
try{supervisor=await starter({codexHome:anchorHome,dispatchId,cwd:target.realpath,userHome:context.userHome,env:context.env??process.env});}
|
|
62
66
|
catch{result=blank(context,dispatchId,'hold','host_sandbox_blocked');return;}
|
|
@@ -67,7 +71,7 @@ export async function runBridgeDispatch({context,dispatchId,brief,now=Date.now()
|
|
|
67
71
|
if(error?.code==='ARC_ROUTING_LOCK_RELEASE'&&!error.failure&&result){residual=residualOf(error);}
|
|
68
72
|
else return hold(context,dispatchId,classifyLock(error),error);
|
|
69
73
|
}
|
|
70
|
-
if(residual)result.residualPaths=residual;
|
|
74
|
+
if(residual)result.residualPaths=[...(result.residualPaths??[]),...residual];
|
|
71
75
|
return result;
|
|
72
76
|
}
|
|
73
77
|
|
|
@@ -165,6 +169,10 @@ export async function resumeRoleDispatch({context,dispatchId,brief,now=Date.now(
|
|
|
165
169
|
let invocation;try{invocation=await buildBridgeInvocation({lease:{...lease,segment},config,homes,worktree:target.realpath,resultPath,policy,supervisorImplementations});}catch(error){result=blank(context,dispatchId,'hold',error.reasonCode??'activation_unverified');return;}
|
|
166
170
|
await fsp.mkdir(directory,{recursive:true,mode:0o700});await fsp.chmod(path.dirname(directory),0o700);await fsp.chmod(directory,0o700);
|
|
167
171
|
await fsp.writeFile(path.join(directory,'brief.md'),brief,{mode:0o600,flag:'w'});await fsp.chmod(path.join(directory,'brief.md'),0o600);
|
|
172
|
+
if(Object.hasOwn(HOST_SANDBOX_GATES,lease.hostPlatform)){
|
|
173
|
+
const probe=await probeHomeWritable(homes[platform]);
|
|
174
|
+
if(!probe.ok){result=hold(context,dispatchId,probe.code,probe);return;}
|
|
175
|
+
}
|
|
168
176
|
await clearCancel(anchorHome,dispatchId);
|
|
169
177
|
let supervisor;
|
|
170
178
|
try{supervisor=await starter({codexHome:anchorHome,dispatchId,cwd:target.realpath,userHome:context.userHome,env:context.env??process.env});}
|
|
@@ -177,7 +185,7 @@ export async function resumeRoleDispatch({context,dispatchId,brief,now=Date.now(
|
|
|
177
185
|
if(error?.code==='ARC_ROUTING_LOCK_RELEASE'&&!error.failure&&result){residual=residualOf(error);}
|
|
178
186
|
else return hold(context,dispatchId,classifyLock(error),error);
|
|
179
187
|
}
|
|
180
|
-
if(residual)result.residualPaths=residual;
|
|
188
|
+
if(residual)result.residualPaths=[...(result.residualPaths??[]),...residual];
|
|
181
189
|
return result;
|
|
182
190
|
}
|
|
183
191
|
|
|
@@ -1,8 +1,28 @@
|
|
|
1
1
|
import {runtimeRegistryOf} from './platform-registry.mjs';
|
|
2
2
|
// Fixed policy values for composite role dispatch. G2 'escalation' means the bridge runs only with per-call user escalation approval on a Codex host; it is not a verified pass.
|
|
3
|
-
|
|
4
|
-
//
|
|
5
|
-
|
|
3
|
+
// GK2/GG2 'approval' means a Grok/Gemini host keeps its platform-default sandbox (off), runs in ask mode, and obtains user approval for each runtime command; it is not a verified pass.
|
|
4
|
+
// GK2 evidence: Grok 1.0.89, 2026-11-19, ask mode with the sandbox off.
|
|
5
|
+
// GK1 evidence: Grok 1.0.89, 2026-11-19, writing roles only, with mandatory ProfileApplied verification.
|
|
6
|
+
export const BRIDGE_GATE_RESULTS = Object.freeze({G1: 'pass', G2: 'escalation', G3: 'pass', G4: 'pass', G5: 'wide', G6: 'strict', G7: 'pass', G8: 'pass', GG1: 'fail', GG2: 'fail', GK1: 'pass', GK2: 'approval'});
|
|
7
|
+
export const HOST_SANDBOX_GATES = Object.freeze({grok: 'GK2', gemini: 'GG2'});
|
|
8
|
+
export const HOST_GATE_ALLOWED = Object.freeze(['pass', 'approval']);
|
|
9
|
+
|
|
10
|
+
function deepFreeze(value) {
|
|
11
|
+
for (const nested of Object.values(value)) {
|
|
12
|
+
if (nested !== null && typeof nested === 'object') deepFreeze(nested);
|
|
13
|
+
}
|
|
14
|
+
return Object.freeze(value);
|
|
15
|
+
}
|
|
16
|
+
|
|
17
|
+
// Claude 2.1.328, 2026-11-19, macOS Seatbelt: /private/tmp/claude-<uid> is writable, Bash exits 71 per command if sandboxing is unavailable, and M-C4 found no widening in trusted or untrusted workspaces.
|
|
18
|
+
const RECORDED_CLAUDE_SANDBOX_SETTINGS = deepFreeze({
|
|
19
|
+
sandbox: {
|
|
20
|
+
enabled: true,
|
|
21
|
+
autoAllowBashIfSandboxed: true,
|
|
22
|
+
allowUnsandboxedCommands: false,
|
|
23
|
+
failIfUnavailable: true,
|
|
24
|
+
},
|
|
25
|
+
});
|
|
6
26
|
const isRecordedObject = value => value !== null && typeof value === 'object' && !Array.isArray(value) && Object.keys(value).length > 0;
|
|
7
27
|
export const CLAUDE_SANDBOX_SETTINGS = BRIDGE_GATE_RESULTS.G1 === 'pass' && isRecordedObject(RECORDED_CLAUDE_SANDBOX_SETTINGS) ? RECORDED_CLAUDE_SANDBOX_SETTINGS : null;
|
|
8
28
|
/** G1 counts as passed only with an explicitly recorded settings object; otherwise the settings are null. */
|
|
@@ -83,13 +103,18 @@ export function capabilityReasons({hostPlatform, targetPlatform, route, runtimeP
|
|
|
83
103
|
&& (route !== 'bridge' || target?.capabilities.bridge.state === 'verified') ? [] : ['capability_not_verified'];
|
|
84
104
|
}
|
|
85
105
|
|
|
106
|
+
export function hostGateReasons({hostPlatform, policy = DEFAULT_POLICY}) {
|
|
107
|
+
if (!Object.hasOwn(HOST_SANDBOX_GATES, hostPlatform)) return [];
|
|
108
|
+
const gates = policy.gates ?? BRIDGE_GATE_RESULTS;
|
|
109
|
+
return HOST_GATE_ALLOWED.includes(gates[HOST_SANDBOX_GATES[hostPlatform]]) ? [] : ['host_sandbox_blocked'];
|
|
110
|
+
}
|
|
111
|
+
|
|
86
112
|
export function bridgeGateReasons({platform, role, hostPlatform, policy = DEFAULT_POLICY}) {
|
|
87
113
|
const gates = policy.gates ?? BRIDGE_GATE_RESULTS, codes = [];
|
|
88
114
|
if (platform === 'claude' && (role === 'arc_implementer' || role === 'arc_qa') && effectiveClaudeSandboxSettings({gates, claudeSandboxSettings: policy.claudeSandboxSettings}) === null) codes.push('permission_scope_unverified');
|
|
89
115
|
if (platform === 'gemini' && (role === 'arc_implementer' || role === 'arc_qa') && gates.GG1 !== 'pass') codes.push('permission_scope_unverified');
|
|
90
116
|
if (platform === 'grok' && (role === 'arc_implementer' || role === 'arc_qa') && gates.GK1 !== 'pass') codes.push('permission_scope_unverified');
|
|
91
|
-
|
|
92
|
-
if (hostPlatform === 'gemini' && gates.GG2 !== 'pass') codes.push('host_sandbox_blocked');
|
|
117
|
+
codes.push(...hostGateReasons({hostPlatform, policy}));
|
|
93
118
|
if (platform === 'codex' && gates.G4 === 'fail') codes.push('permission_scope_unverified');
|
|
94
119
|
if (hostPlatform === 'codex' && gates.G2 === 'fail') codes.push('host_sandbox_blocked');
|
|
95
120
|
return [...new Set(codes)];
|
|
@@ -7,7 +7,7 @@ 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
12
|
|
|
13
13
|
const exact=(value,keys)=>value&&typeof value==='object'&&!Array.isArray(value)&&Object.keys(value).length===keys.length&&keys.every(key=>Object.hasOwn(value,key));
|
|
@@ -114,6 +114,27 @@ export async function readActivation(homes,expectedRevision,{anchorHome=homes.co
|
|
|
114
114
|
|
|
115
115
|
|
|
116
116
|
const HOST_ERRORS=['EACCES','EPERM','EROFS'];
|
|
117
|
+
export async function probeHomeWritable(home, {unlink = fs.unlink} = {}) {
|
|
118
|
+
const file = path.join(home, '.arc-host-probe-' + crypto.randomUUID());
|
|
119
|
+
let handle;
|
|
120
|
+
try {
|
|
121
|
+
handle = await fs.open(file, constants.O_WRONLY | constants.O_CREAT | constants.O_EXCL | constants.O_NOFOLLOW, 0o600);
|
|
122
|
+
} catch (error) {
|
|
123
|
+
return {ok: false, code: HOST_ERRORS.includes(error?.code) ? 'host_sandbox_blocked' : 'activation_unverified'};
|
|
124
|
+
}
|
|
125
|
+
let closed = false;
|
|
126
|
+
try {
|
|
127
|
+
await handle.close();
|
|
128
|
+
closed = true;
|
|
129
|
+
} catch { /* Attempt to remove the file even if close fails. */ }
|
|
130
|
+
try {
|
|
131
|
+
await unlink(file);
|
|
132
|
+
} catch {
|
|
133
|
+
return {ok: false, code: 'host_sandbox_blocked', residualPaths: [file]};
|
|
134
|
+
}
|
|
135
|
+
return closed ? {ok: true} : {ok: false, code: 'activation_unverified'};
|
|
136
|
+
}
|
|
137
|
+
|
|
117
138
|
const sleep=ms=>new Promise(resolve=>setTimeout(resolve,ms));
|
|
118
139
|
const lockFile=codexHome=>path.join(codexHome,'arc-role-platform-routing.lock');
|
|
119
140
|
/** Runs fn under the shared routing lock. Only EEXIST is retried; the lock file is never removed except by its owner. */
|
|
@@ -231,14 +252,20 @@ export async function prepareRoleDispatch({context,assignment,expectedRevision,n
|
|
|
231
252
|
const leases=await listLeases(anchorHome,{runtimePlatforms});
|
|
232
253
|
const live=leases.filter(lease=>NON_TERMINAL_STATES.includes(lease.state));
|
|
233
254
|
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');
|
|
255
|
+
for(const code of hostGateReasons({hostPlatform:host,policy}))codes.add(code);
|
|
236
256
|
if(route==='bridge'){
|
|
237
257
|
let limits;try{limits=readHostLimits(resolveConfigHome(host,context));}catch{codes.add('activation_unverified');}
|
|
238
258
|
if(limits){
|
|
239
259
|
const bridges=leases.filter(lease=>lease.route==='bridge');
|
|
240
260
|
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
261
|
}
|
|
262
|
+
if(Object.hasOwn(HOST_SANDBOX_GATES,host)){
|
|
263
|
+
const probe=await probeHomeWritable(homes[requested.platform]);
|
|
264
|
+
if(!probe.ok){
|
|
265
|
+
codes.add(probe.code);
|
|
266
|
+
if(probe.residualPaths)result.residualPaths=probe.residualPaths;
|
|
267
|
+
}
|
|
268
|
+
}
|
|
242
269
|
for(const code of bridgeGateReasons({platform:requested.platform,role,hostPlatform:host,policy}))codes.add(code);
|
|
243
270
|
}
|
|
244
271
|
result.reasons=[...codes].map(reason);
|
|
@@ -254,7 +281,7 @@ export async function prepareRoleDispatch({context,assignment,expectedRevision,n
|
|
|
254
281
|
}else{
|
|
255
282
|
Object.assign(result,{decision:'hold',routeStatus:'held',dispatchId:null,claims:null,reasons:[reason(classify(error))]});
|
|
256
283
|
}
|
|
257
|
-
const residual=residualOf(error);if(residual)result.residualPaths=residual;
|
|
284
|
+
const residual=residualOf(error);if(residual)result.residualPaths=[...(result.residualPaths??[]),...residual];
|
|
258
285
|
}
|
|
259
286
|
return result;
|
|
260
287
|
}
|
|
@@ -7,6 +7,7 @@ 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} 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';
|
|
@@ -117,6 +118,14 @@ export async function buildBridgeInvocation({lease, config, homes, worktree, res
|
|
|
117
118
|
}
|
|
118
119
|
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
120
|
if (!implementation) throw fail('permission_scope_unverified', 'Invalid composite profile: unknown platform');
|
|
121
|
+
const permissions = ROLE_BRIDGE_PERMISSIONS[platform][lease.role];
|
|
122
|
+
let grokSandbox;
|
|
123
|
+
if (platform === 'grok' && permissions.sandbox === 'custom') {
|
|
124
|
+
const name = grokSandboxProfileName(lease.dispatchId);
|
|
125
|
+
if (!name || grokProfileCovered(lease.allowedPaths)) throw fail('permission_scope_unverified', 'Grok sandbox profile scope is unavailable');
|
|
126
|
+
inspectGrokProfileSlot(worktree);
|
|
127
|
+
grokSandbox = {name, path: path.join(worktree, GROK_SANDBOX_RELATIVE), bytes: renderGrokSandboxProfile(name)};
|
|
128
|
+
}
|
|
120
129
|
const file = path.join(homes[platform], 'agents', routingProfileFile(getPlatform(platform), lease.role));
|
|
121
130
|
let bytes;
|
|
122
131
|
try { bytes = await fsp.readFile(file); } catch { throw fail('activation_unverified', 'Profile unreadable'); }
|
|
@@ -124,14 +133,13 @@ export async function buildBridgeInvocation({lease, config, homes, worktree, res
|
|
|
124
133
|
let profile, args;
|
|
125
134
|
try {
|
|
126
135
|
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});
|
|
136
|
+
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
137
|
} catch { throw fail('permission_scope_unverified', 'Profile arguments unavailable'); }
|
|
129
|
-
const permissions = ROLE_BRIDGE_PERMISSIONS[platform][lease.role];
|
|
130
138
|
const expected = platform === 'claude'
|
|
131
139
|
? {model: requested.model, effort: requested.effort, tools: profile.tools, permissionMode: permissions.permissionMode}
|
|
132
140
|
: platform === 'gemini' || platform === 'grok' ? {model: requested.model, effort: 'default'}
|
|
133
141
|
: {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} : {})};
|
|
142
|
+
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
143
|
}
|
|
136
144
|
|
|
137
145
|
/** Starts this module as a detached supervisor process (own session, stdio ignored, unref'd). env defaults to the inherited environment. */
|
|
@@ -197,10 +205,31 @@ export async function runSupervisor(options) {
|
|
|
197
205
|
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
206
|
});
|
|
199
207
|
};
|
|
200
|
-
|
|
208
|
+
let createdGrokProfile, grokSandboxProfile, spawnAtMs, profileViolation = false;
|
|
209
|
+
const grokProfileRecord = () => grokSandboxProfile ? {grokSandboxProfile, ...(spawnAtMs === undefined ? {} : {spawnAtMs})} : {};
|
|
210
|
+
const cleanGrokProfile = () => {
|
|
211
|
+
if (!grokSandboxProfile || grokSandboxProfile.removed !== null) return;
|
|
212
|
+
const {removed, dirRemoved, violation} = removeGrokSandboxProfile(createdGrokProfile);
|
|
213
|
+
Object.assign(grokSandboxProfile, {removed, dirRemoved});
|
|
214
|
+
profileViolation = violation;
|
|
215
|
+
};
|
|
216
|
+
const retainGrokProfile = () => {
|
|
217
|
+
if (grokSandboxProfile?.removed === null) Object.assign(grokSandboxProfile, {removed: false, reason: 'child_unobserved'});
|
|
218
|
+
return grokProfileRecord();
|
|
219
|
+
};
|
|
220
|
+
const earlyFailure = async (code, spawned = null, extra = {}) => {
|
|
201
221
|
const claims = {...(lease.claims ?? {}), terminal: {level: 'runtime-observed', source: 'supervisor'}};
|
|
202
|
-
|
|
203
|
-
|
|
222
|
+
const codes = [code];
|
|
223
|
+
if (profileViolation) {
|
|
224
|
+
codes.push('permission_violation_observed');
|
|
225
|
+
claims.permissions = {...claims.permissions, level: 'unverified', details: 'permission violation observed'};
|
|
226
|
+
}
|
|
227
|
+
await writeRecord({state: 'failed', reasons: codes, spawned: spawned !== null, ...(spawned !== null ? {childPid: spawned} : {}), ...extra}).catch(() => {});
|
|
228
|
+
await commit('failed', codes, claims);
|
|
229
|
+
};
|
|
230
|
+
const failWithProfileCleanup = (code, spawned = null) => {
|
|
231
|
+
cleanGrokProfile();
|
|
232
|
+
return earlyFailure(code, spawned, grokProfileRecord());
|
|
204
233
|
};
|
|
205
234
|
|
|
206
235
|
let child = null, eventsFd = null, killTimers = [], terminating = null, termAt = 0;
|
|
@@ -229,8 +258,23 @@ export async function runSupervisor(options) {
|
|
|
229
258
|
const brief = await fsp.readFile(path.join(artifactDir, 'brief.md'), 'utf8');
|
|
230
259
|
const cli = resolveLocalCli(platform, context);
|
|
231
260
|
if (cli.reason) return await earlyFailure(cli.reason === 'cli_not_found' ? 'Not Available' : 'execution_failed');
|
|
261
|
+
const childEnv = {...localCliEnvironment(cli), ...invocation.childEnv};
|
|
262
|
+
if (invocation.grokSandbox) {
|
|
263
|
+
if (Object.hasOwn(invocation.childEnv, 'GROK_HOME') || !checkGrokHome({grokHome: homes.grok, userHome, childEnv})) return await earlyFailure('permission_scope_unverified');
|
|
264
|
+
try { createdGrokProfile = createGrokSandboxProfile({worktree: target.realpath, bytes: invocation.grokSandbox.bytes}); }
|
|
265
|
+
catch (error) {
|
|
266
|
+
const cleanup = error.cleanup;
|
|
267
|
+
if (cleanup?.violation) {
|
|
268
|
+
profileViolation = true;
|
|
269
|
+
grokSandboxProfile = {name: invocation.grokSandbox.name, path: cleanup.path, created: true, removed: !cleanup.retained, dirRemoved: cleanup.dirRemoved, reason: 'profile_creation_cleanup_failed'};
|
|
270
|
+
}
|
|
271
|
+
return await earlyFailure(error.reasonCode ?? 'permission_scope_unverified', null, grokProfileRecord());
|
|
272
|
+
}
|
|
273
|
+
const {path, sha256, dirCreated} = createdGrokProfile;
|
|
274
|
+
grokSandboxProfile = {name: invocation.grokSandbox.name, path, sha256, dirCreated, created: true, removed: null, dirRemoved: false, eventsBaseline: null, applied: null};
|
|
275
|
+
}
|
|
232
276
|
let before;
|
|
233
|
-
try { before = await snapshotWorktree(target.realpath); } catch { return await
|
|
277
|
+
try { before = await snapshotWorktree(target.realpath); } catch { return await failWithProfileCleanup('execution_failed'); }
|
|
234
278
|
|
|
235
279
|
if (invocation.promptFile) {
|
|
236
280
|
let promptFd;
|
|
@@ -238,12 +282,21 @@ export async function runSupervisor(options) {
|
|
|
238
282
|
promptFd = fs.openSync(invocation.promptFile.path, fs.constants.O_WRONLY | fs.constants.O_CREAT | fs.constants.O_EXCL, 0o600);
|
|
239
283
|
fs.writeFileSync(promptFd, `${invocation.promptFile.instructions}\n\n${brief}`);
|
|
240
284
|
fs.fchmodSync(promptFd, 0o600);
|
|
241
|
-
} catch { return await
|
|
285
|
+
} catch { return await failWithProfileCleanup('execution_failed'); }
|
|
242
286
|
finally { if (promptFd !== undefined) fs.closeSync(promptFd); }
|
|
243
287
|
}
|
|
244
288
|
eventsFd = fs.openSync(path.join(artifactDir, 'events.jsonl'), 'a', 0o600);
|
|
289
|
+
if (grokSandboxProfile) {
|
|
290
|
+
try { grokSandboxProfile.eventsBaseline = grokEventsBaseline(homes.grok); }
|
|
291
|
+
catch { return await failWithProfileCleanup('permission_scope_unverified'); }
|
|
292
|
+
if (!verifyGrokSandboxProfile(createdGrokProfile)) {
|
|
293
|
+
Object.assign(grokSandboxProfile, {removed: false, reason: 'profile_changed_before_spawn'});
|
|
294
|
+
return await earlyFailure('permission_scope_unverified', null, grokProfileRecord());
|
|
295
|
+
}
|
|
296
|
+
spawnAtMs = Date.now();
|
|
297
|
+
}
|
|
245
298
|
// 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: {...
|
|
299
|
+
child = spawn(cli.executable, invocation.args, {cwd: target.realpath, env: {...childEnv, ARC_BRIDGE_CHILD: dispatchId}, detached: true, stdio: ['pipe', 'pipe', 'pipe'], shell: false});
|
|
247
300
|
let exitResolve, exited = false;
|
|
248
301
|
const exitPromise = new Promise(resolve => { exitResolve = resolve; });
|
|
249
302
|
child.on('exit', (code, signal) => { exited = true; exitResolve({code, signal}); });
|
|
@@ -382,7 +435,7 @@ export async function runSupervisor(options) {
|
|
|
382
435
|
if (exit.unobserved) {
|
|
383
436
|
// The child was signalled but its exit was never observed: the slot stays occupied.
|
|
384
437
|
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(() => {});
|
|
438
|
+
await writeRecord({state: 'unknown', reasons: [...(terminating === 'timeout' ? ['timeout'] : []), 'terminal_state_unverified'], terminatedBy: terminating, eventsTruncated, ignoredLines: parser.ignored, lineOverflow: parser.overflow, ...retainGrokProfile()}).catch(() => {});
|
|
386
439
|
await locked(async () => {
|
|
387
440
|
const current = await readLease(codexHome, dispatchId, {runtimePlatforms});
|
|
388
441
|
if (current && !TERMINAL_STATES.includes(current.state)) await writeLease(codexHome, {...current, state: 'unknown', claims, reasons: [...(terminating === 'timeout' ? ['timeout'] : []), 'terminal_state_unverified'].map(reason)}, {runtimePlatforms});
|
|
@@ -405,9 +458,16 @@ export async function runSupervisor(options) {
|
|
|
405
458
|
if (platform === 'gemini' && terminating !== 'cancel' && (exit.code !== 0 || exit.signal || state.terminalError)) codes.push('execution_failed');
|
|
406
459
|
if (platform === 'grok' && terminating !== 'cancel' && (exit.code !== 0 || exit.signal || state.terminalError || !state.terminal)) codes.push('execution_failed');
|
|
407
460
|
if (effortMismatch) codes.push('model_effort_mismatch');
|
|
408
|
-
if (
|
|
461
|
+
if (grokSandboxProfile) {
|
|
462
|
+
const {eventsBaseline: baseline, name} = grokSandboxProfile;
|
|
463
|
+
const {ok, reason, applied} = readGrokProfileApplied({grokHome: homes.grok, baseline, spawnAtMs, name, worktreeRealpath: target.realpath});
|
|
464
|
+
if (ok) grokSandboxProfile.applied = applied;
|
|
465
|
+
else if (!(terminating === 'cancel' && reason === 'no_candidate')) codes.push('permission_scope_mismatch');
|
|
466
|
+
}
|
|
467
|
+
cleanGrokProfile();
|
|
468
|
+
if (violations.reason || profileViolation) codes.push(violations.reason ?? 'permission_violation_observed');
|
|
409
469
|
if (after === null) claims.permissions = {level: 'unverified', source: 'worktree-snapshot', details: 'post-run snapshot unavailable'};
|
|
410
|
-
|
|
470
|
+
if (violations.reason || profileViolation) claims.permissions = {...claims.permissions, level: 'unverified', details: 'permission violation observed'};
|
|
411
471
|
if (terminating === 'timeout') codes.push('timeout');
|
|
412
472
|
|
|
413
473
|
const resultPath = platform === 'grok' && (exit.code !== 0 || exit.signal) ? null : await implementation.resultPath(state, resultFile);
|
|
@@ -434,7 +494,8 @@ export async function runSupervisor(options) {
|
|
|
434
494
|
claims.identity = {level: 'unverified', source: 'none'};
|
|
435
495
|
}
|
|
436
496
|
if (exit.spawnError && !codes.length) { codes.push('execution_failed'); finalState = 'failed'; }
|
|
437
|
-
|
|
497
|
+
if ((finalState === 'completed' || finalState === 'cancelled') && codes.includes('permission_scope_mismatch')) finalState = 'failed';
|
|
498
|
+
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}, ...(orphanGroupReaped ? {orphanGroupReaped: true} : {}), argsDigest: invocation.argsDigest, resultPath, ...grokProfileRecord(), ...(platform === 'gemini' ? {unverifiedContracts: {delegation: GEMINI_CONTRACT.delegation}} : platform === 'grok' ? {unverifiedContracts: {delegation: GROK_CONTRACT.delegation}} : {})});
|
|
438
499
|
await commit(finalState, codes, claims, {sessionId, resultPath});
|
|
439
500
|
} catch {
|
|
440
501
|
// Unexpected failure after the child started: stop it, then record a failed state if the child is gone.
|
|
@@ -443,11 +504,10 @@ export async function runSupervisor(options) {
|
|
|
443
504
|
if (spawnedPid) { if (!termAt) { termAt = Date.now(); killGroup('SIGTERM'); } stopped = await reapGroup().catch(() => false); }
|
|
444
505
|
for (const timer of timers) { clearInterval(timer); clearTimeout(timer); }
|
|
445
506
|
for (const timer of killTimers) clearTimeout(timer);
|
|
446
|
-
if (
|
|
447
|
-
if (stopped) await earlyFailure('execution_failed', spawnedPid).catch(() => {});
|
|
507
|
+
if (stopped) await failWithProfileCleanup('execution_failed', spawnedPid).catch(() => {});
|
|
448
508
|
else {
|
|
449
509
|
const codes = ['execution_failed', 'terminal_state_unverified'];
|
|
450
|
-
await writeRecord({state: 'unknown', reasons: codes, spawned: true, childPid: spawnedPid}).catch(() => {});
|
|
510
|
+
await writeRecord({state: 'unknown', reasons: codes, spawned: true, childPid: spawnedPid, ...retainGrokProfile()}).catch(() => {});
|
|
451
511
|
await locked(async () => {
|
|
452
512
|
const current = await readLease(codexHome, dispatchId, {runtimePlatforms});
|
|
453
513
|
if (current && !TERMINAL_STATES.includes(current.state)) await writeLease(codexHome, {...current, state: 'unknown', reasons: codes.map(reason)}, {runtimePlatforms});
|
|
@@ -455,6 +515,7 @@ export async function runSupervisor(options) {
|
|
|
455
515
|
}
|
|
456
516
|
} finally {
|
|
457
517
|
for (const timer of timers) { clearInterval(timer); clearTimeout(timer); }
|
|
518
|
+
if (eventsFd !== null) { try { fs.closeSync(eventsFd); } catch { /* closed */ } }
|
|
458
519
|
}
|
|
459
520
|
}
|
|
460
521
|
|
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}){
|
|
@@ -0,0 +1,234 @@
|
|
|
1
|
+
import fs from 'node:fs';
|
|
2
|
+
import path from 'node:path';
|
|
3
|
+
import crypto from 'node:crypto';
|
|
4
|
+
import {EVENTS_MAX_BYTES} from './role-dispatch-policy.mjs';
|
|
5
|
+
|
|
6
|
+
export const GROK_SANDBOX_RELATIVE = '.grok/sandbox.toml';
|
|
7
|
+
export const GROK_SANDBOX_DENY = Object.freeze([
|
|
8
|
+
'.grok/sandbox.toml', '~/.grok/skills', '~/.grok/agents', '~/.grok/rules',
|
|
9
|
+
'~/.grok/workflows', '~/.grok/plugins', '~/.grok/installed-plugins', '~/.grok/plugin-data',
|
|
10
|
+
'~/.grok/personas', '~/.grok/memory', '~/.grok/memory-v2', '~/.grok/AGENTS.md',
|
|
11
|
+
'~/.grok/statusline.sh', '~/.grok/lsp.json', '~/.grok/bin', '~/.grok/downloads',
|
|
12
|
+
'~/.grok/bundled', '~/.grok/bundles', '~/.grok/settings.json', '~/.grok/pager.toml',
|
|
13
|
+
'~/.grok/mcp_credentials.json', '~/.grok/worktrees', '~/.grok/workspaces', '~/.grok/daemon',
|
|
14
|
+
]);
|
|
15
|
+
|
|
16
|
+
const digest = bytes => 'sha256:' + crypto.createHash('sha256').update(bytes).digest('hex');
|
|
17
|
+
const scopeError = (message, cause) => Object.assign(Error(message, {cause}), {reasonCode: 'permission_scope_unverified'});
|
|
18
|
+
const sameEntry = (first, second) => first.dev === second.dev && first.ino === second.ino;
|
|
19
|
+
const identityOf = ({dev, ino}) => ({dev, ino});
|
|
20
|
+
const sandboxEventsPath = grokHome => path.join(grokHome, 'sessions', 'sandbox-events.jsonl');
|
|
21
|
+
|
|
22
|
+
export function grokSandboxProfileName(dispatchId) {
|
|
23
|
+
const prefix = typeof dispatchId === 'string' ? dispatchId.slice(0, 8) : '';
|
|
24
|
+
return /^[0-9a-f]{8}$/.test(prefix) ? 'arc-bridge-' + prefix : null;
|
|
25
|
+
}
|
|
26
|
+
|
|
27
|
+
export function renderGrokSandboxProfile(name) {
|
|
28
|
+
if (typeof name !== 'string' || !/^arc-bridge-[0-9a-f]{8}$/.test(name)) throw Error('Invalid Grok profile name');
|
|
29
|
+
const deny = GROK_SANDBOX_DENY.map(entry => JSON.stringify(entry)).join(', ');
|
|
30
|
+
return Buffer.from(`[profiles.${name}]\nextends = "workspace"\ndeny = [${deny}]\n`);
|
|
31
|
+
}
|
|
32
|
+
|
|
33
|
+
export function grokProfileCovered(allowedPaths) {
|
|
34
|
+
return allowedPaths.some(entry => (entry.endsWith('/') ? GROK_SANDBOX_RELATIVE.startsWith(entry) : entry === GROK_SANDBOX_RELATIVE)
|
|
35
|
+
|| entry === '.grok' || entry.startsWith('.grok/'));
|
|
36
|
+
}
|
|
37
|
+
|
|
38
|
+
export function inspectGrokProfileSlot(worktree) {
|
|
39
|
+
const file = path.join(worktree, GROK_SANDBOX_RELATIVE), directory = path.dirname(file);
|
|
40
|
+
try {
|
|
41
|
+
const parent = fs.lstatSync(directory, {throwIfNoEntry: false});
|
|
42
|
+
if (parent && !parent.isDirectory()) throw Error('.grok is not a real directory');
|
|
43
|
+
if (fs.lstatSync(file, {throwIfNoEntry: false})) throw Error('Sandbox profile slot is occupied');
|
|
44
|
+
} catch (cause) {
|
|
45
|
+
throw scopeError('Grok sandbox profile slot unavailable', cause);
|
|
46
|
+
}
|
|
47
|
+
}
|
|
48
|
+
|
|
49
|
+
export function checkGrokHome({grokHome, userHome, childEnv}) {
|
|
50
|
+
if (typeof grokHome !== 'string' || childEnv?.GROK_HOME !== grokHome) return false;
|
|
51
|
+
try {
|
|
52
|
+
if (Object.hasOwn(childEnv, 'HOME') && fs.realpathSync(childEnv.HOME) !== fs.realpathSync(userHome)) return false;
|
|
53
|
+
return !fs.lstatSync(grokHome, {throwIfNoEntry: false})?.isSymbolicLink();
|
|
54
|
+
} catch {
|
|
55
|
+
return false;
|
|
56
|
+
}
|
|
57
|
+
}
|
|
58
|
+
|
|
59
|
+
export function createGrokSandboxProfile({worktree, bytes}) {
|
|
60
|
+
const file = path.join(worktree, GROK_SANDBOX_RELATIVE), directory = path.dirname(file);
|
|
61
|
+
const profile = {path: file, sha256: digest(bytes), dirCreated: false};
|
|
62
|
+
let fd;
|
|
63
|
+
try {
|
|
64
|
+
try {
|
|
65
|
+
fs.mkdirSync(directory, 0o700);
|
|
66
|
+
profile.dirCreated = true;
|
|
67
|
+
} catch (error) {
|
|
68
|
+
if (error.code !== 'EEXIST') throw error;
|
|
69
|
+
}
|
|
70
|
+
const parent = fs.lstatSync(directory);
|
|
71
|
+
if (!parent.isDirectory()) throw Error('.grok is not a real directory');
|
|
72
|
+
profile.directoryIdentity = identityOf(parent);
|
|
73
|
+
// During creation, the parent .grok can become a symlink between its identity lstat and open.
|
|
74
|
+
fd = fs.openSync(file, fs.constants.O_WRONLY | fs.constants.O_CREAT | fs.constants.O_EXCL | fs.constants.O_NOFOLLOW, 0o444);
|
|
75
|
+
try {
|
|
76
|
+
const opened = fs.fstatSync(fd);
|
|
77
|
+
if (!opened.isFile()) throw Error('Grok sandbox profile is not a regular file');
|
|
78
|
+
profile.fileIdentity = identityOf(opened);
|
|
79
|
+
checkProfileEntries(profile);
|
|
80
|
+
fs.writeFileSync(fd, bytes);
|
|
81
|
+
fs.fchmodSync(fd, 0o444);
|
|
82
|
+
} finally {
|
|
83
|
+
fs.closeSync(fd);
|
|
84
|
+
}
|
|
85
|
+
checkProfileEntries(profile);
|
|
86
|
+
return profile;
|
|
87
|
+
} catch (cause) {
|
|
88
|
+
const error = scopeError('Grok sandbox profile creation failed', cause);
|
|
89
|
+
if (fd !== undefined) {
|
|
90
|
+
const {removed, dirRemoved, violation} = profile.fileIdentity
|
|
91
|
+
? removeGrokSandboxProfile(profile)
|
|
92
|
+
: {removed: false, dirRemoved: false, violation: true};
|
|
93
|
+
error.cleanup = {path: file, retained: !removed, violation, dirRemoved};
|
|
94
|
+
} else if (profile.dirCreated && profile.directoryIdentity) {
|
|
95
|
+
try {
|
|
96
|
+
checkProfileDirectory(profile);
|
|
97
|
+
fs.rmdirSync(directory);
|
|
98
|
+
} catch { /* retain a concurrently occupied or replaced directory */ }
|
|
99
|
+
}
|
|
100
|
+
throw error;
|
|
101
|
+
}
|
|
102
|
+
}
|
|
103
|
+
|
|
104
|
+
function checkProfileDirectory({path: file, directoryIdentity}) {
|
|
105
|
+
const parent = fs.lstatSync(path.dirname(file));
|
|
106
|
+
if (!parent.isDirectory() || !sameEntry(parent, directoryIdentity)) throw Error('Grok sandbox directory changed');
|
|
107
|
+
}
|
|
108
|
+
|
|
109
|
+
function checkProfileEntries(profile) {
|
|
110
|
+
checkProfileDirectory(profile);
|
|
111
|
+
const stat = fs.lstatSync(profile.path);
|
|
112
|
+
if (!stat.isFile() || !sameEntry(stat, profile.fileIdentity)) throw Error('Grok sandbox profile was replaced');
|
|
113
|
+
}
|
|
114
|
+
|
|
115
|
+
export function verifyGrokSandboxProfile(profile) {
|
|
116
|
+
const {path: file, sha256, fileIdentity} = profile;
|
|
117
|
+
try {
|
|
118
|
+
checkProfileEntries(profile);
|
|
119
|
+
const fd = fs.openSync(file, fs.constants.O_RDONLY | fs.constants.O_NOFOLLOW | fs.constants.O_NONBLOCK);
|
|
120
|
+
try {
|
|
121
|
+
const opened = fs.fstatSync(fd);
|
|
122
|
+
if (!opened.isFile() || !sameEntry(opened, fileIdentity) || digest(fs.readFileSync(fd)) !== sha256) return false;
|
|
123
|
+
} finally {
|
|
124
|
+
fs.closeSync(fd);
|
|
125
|
+
}
|
|
126
|
+
checkProfileEntries(profile);
|
|
127
|
+
return true;
|
|
128
|
+
} catch {
|
|
129
|
+
return false;
|
|
130
|
+
}
|
|
131
|
+
}
|
|
132
|
+
|
|
133
|
+
export function removeGrokSandboxProfile(profile) {
|
|
134
|
+
const {path: file, dirCreated} = profile;
|
|
135
|
+
const result = {removed: false, dirRemoved: false, violation: false};
|
|
136
|
+
if (!verifyGrokSandboxProfile(profile)) return {...result, violation: true};
|
|
137
|
+
try {
|
|
138
|
+
// Node has no unlinkat, so a race remains between the final identity check and unlink.
|
|
139
|
+
fs.unlinkSync(file);
|
|
140
|
+
result.removed = true;
|
|
141
|
+
if (dirCreated) {
|
|
142
|
+
try {
|
|
143
|
+
checkProfileDirectory(profile);
|
|
144
|
+
fs.rmdirSync(path.dirname(file));
|
|
145
|
+
result.dirRemoved = true;
|
|
146
|
+
} catch (error) {
|
|
147
|
+
if (error.code !== 'ENOTEMPTY') throw error;
|
|
148
|
+
}
|
|
149
|
+
}
|
|
150
|
+
} catch {
|
|
151
|
+
result.violation = true;
|
|
152
|
+
}
|
|
153
|
+
return result;
|
|
154
|
+
}
|
|
155
|
+
|
|
156
|
+
export function grokEventsBaseline(grokHome) {
|
|
157
|
+
const stat = fs.lstatSync(sandboxEventsPath(grokHome), {throwIfNoEntry: false});
|
|
158
|
+
if (!stat) return {exists: false, size: 0};
|
|
159
|
+
if (!stat.isFile()) throw Error('Grok sandbox events are not a regular file');
|
|
160
|
+
return {exists: true, dev: stat.dev, ino: stat.ino, size: stat.size};
|
|
161
|
+
}
|
|
162
|
+
|
|
163
|
+
const unapplied = (reason, candidates = 0) => ({ok: false, reason, candidates, applied: null});
|
|
164
|
+
|
|
165
|
+
function eventsFileIssue(baseline, current, maxBytes) {
|
|
166
|
+
if (!current.exists) return baseline.exists ? 'rotated' : 'no_candidate';
|
|
167
|
+
if (!current.regular) return 'not_regular';
|
|
168
|
+
if (baseline.exists && !sameEntry(baseline, current)) return 'rotated';
|
|
169
|
+
if (current.size < baseline.size) return 'truncated';
|
|
170
|
+
if (current.size - baseline.size > maxBytes) return 'too_large';
|
|
171
|
+
return null;
|
|
172
|
+
}
|
|
173
|
+
|
|
174
|
+
export function evaluateGrokProfileApplied({text, baseline, current, spawnAtMs, name, worktreeRealpath, maxBytes = EVENTS_MAX_BYTES}) {
|
|
175
|
+
const issue = eventsFileIssue(baseline, current, maxBytes);
|
|
176
|
+
if (issue) return unapplied(issue);
|
|
177
|
+
|
|
178
|
+
const lines = text.split('\n');
|
|
179
|
+
lines.pop(); // The last entry is empty or an unfinished append.
|
|
180
|
+
let candidate = null, candidates = 0, invalidTimestamp = false;
|
|
181
|
+
for (const line of lines) {
|
|
182
|
+
let event;
|
|
183
|
+
try { event = JSON.parse(line); } catch { continue; }
|
|
184
|
+
if (event?.event_type !== 'ProfileApplied' || event.profile !== name || event.workspace !== worktreeRealpath) continue;
|
|
185
|
+
const timestamp = typeof event.timestamp === 'string' ? Date.parse(event.timestamp) : NaN;
|
|
186
|
+
if (Number.isNaN(timestamp)) {
|
|
187
|
+
invalidTimestamp = true;
|
|
188
|
+
candidates++;
|
|
189
|
+
} else if (timestamp >= spawnAtMs) {
|
|
190
|
+
candidate = event;
|
|
191
|
+
candidates++;
|
|
192
|
+
}
|
|
193
|
+
}
|
|
194
|
+
if (invalidTimestamp) return unapplied('timestamp_invalid', candidates);
|
|
195
|
+
if (!candidates) return unapplied('no_candidate');
|
|
196
|
+
if (candidates > 1) return unapplied('multiple_candidates', candidates);
|
|
197
|
+
if (candidate.enforced !== true) return unapplied('not_enforced', candidates);
|
|
198
|
+
if (candidate.inherited === true) return unapplied('inherited', candidates);
|
|
199
|
+
const expectedDeny = path.join(worktreeRealpath, GROK_SANDBOX_RELATIVE);
|
|
200
|
+
if (!Array.isArray(candidate.deny_paths) || !candidate.deny_paths.includes(expectedDeny)) return unapplied('deny_missing', candidates);
|
|
201
|
+
const applied = {timestamp: candidate.timestamp, enforced: true, inherited: false, denyOk: true};
|
|
202
|
+
return {ok: true, reason: null, candidates, applied};
|
|
203
|
+
}
|
|
204
|
+
|
|
205
|
+
export function readGrokProfileApplied({grokHome, baseline, spawnAtMs, name, worktreeRealpath}) {
|
|
206
|
+
const file = sandboxEventsPath(grokHome);
|
|
207
|
+
try {
|
|
208
|
+
const stat = fs.lstatSync(file, {throwIfNoEntry: false});
|
|
209
|
+
const current = stat ? {exists: true, regular: stat.isFile(), dev: stat.dev, ino: stat.ino, size: stat.size} : {exists: false};
|
|
210
|
+
const issue = eventsFileIssue(baseline, current, EVENTS_MAX_BYTES);
|
|
211
|
+
if (issue) return unapplied(issue);
|
|
212
|
+
|
|
213
|
+
const fd = fs.openSync(file, fs.constants.O_RDONLY | fs.constants.O_NOFOLLOW | fs.constants.O_NONBLOCK);
|
|
214
|
+
try {
|
|
215
|
+
const opened = fs.fstatSync(fd);
|
|
216
|
+
if (!sameEntry(opened, stat)) return unapplied('rotated');
|
|
217
|
+
if (!opened.isFile()) return unapplied('not_regular');
|
|
218
|
+
if (opened.size < stat.size) return unapplied('truncated');
|
|
219
|
+
|
|
220
|
+
const bytes = Buffer.alloc(stat.size - baseline.size);
|
|
221
|
+
let offset = 0;
|
|
222
|
+
while (offset < bytes.length) {
|
|
223
|
+
const read = fs.readSync(fd, bytes, offset, bytes.length - offset, baseline.size + offset);
|
|
224
|
+
if (read === 0) return unapplied('truncated');
|
|
225
|
+
offset += read;
|
|
226
|
+
}
|
|
227
|
+
return evaluateGrokProfileApplied({text: bytes.toString('utf8'), baseline, current, spawnAtMs, name, worktreeRealpath});
|
|
228
|
+
} finally {
|
|
229
|
+
fs.closeSync(fd);
|
|
230
|
+
}
|
|
231
|
+
} catch (error) {
|
|
232
|
+
return unapplied(error.code === 'ENOENT' || error.code === 'ELOOP' ? 'rotated' : 'not_regular');
|
|
233
|
+
}
|
|
234
|
+
}
|