@yunhozz/arc 0.4.5 → 0.4.7
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 +78 -73
- package/README.md +35 -51
- package/claude/agents/arc-implementer.md +2 -2
- package/claude/agents/arc-planner.md +1 -1
- package/claude/agents/arc-qa.md +1 -1
- package/claude/agents/arc-reviewer.md +1 -1
- package/claude/agents/arc-scouter.md +1 -1
- package/claude/skill/references/coordination.md +4 -2
- package/claude/skill/references/handoff-prep.md +5 -0
- package/claude/skill/references/handoff.md +2 -2
- package/claude/skill/references/planning.md +2 -2
- package/claude/skill/references/verification.md +16 -3
- package/claude/skill/references/worktree-creation.md +2 -2
- package/codex/agents/arc-implementer.toml +1 -1
- package/codex/agents/arc-planner.toml +1 -1
- package/codex/agents/arc-qa.toml +1 -1
- package/codex/agents/arc-reviewer.toml +1 -1
- package/codex/agents/arc-scouter.toml +1 -1
- package/codex/skill/references/coordination.md +4 -2
- package/codex/skill/references/handoff-prep.md +5 -0
- package/codex/skill/references/handoff.md +2 -2
- package/codex/skill/references/planning.md +2 -2
- package/codex/skill/references/verification.md +15 -2
- package/gemini/agents/arc-implementer.md +2 -2
- package/gemini/agents/arc-planner.md +1 -1
- package/gemini/agents/arc-qa.md +1 -1
- package/gemini/agents/arc-reviewer.md +1 -1
- package/gemini/agents/arc-scouter.md +1 -1
- package/gemini/skill/references/coordination.md +5 -3
- package/gemini/skill/references/handoff-prep.md +5 -0
- package/gemini/skill/references/handoff.md +2 -2
- package/gemini/skill/references/planning.md +2 -2
- package/gemini/skill/references/verification.md +16 -3
- package/gemini/skill/references/worktree-creation.md +2 -2
- package/grok/agents/arc-implementer.md +2 -2
- package/grok/agents/arc-planner.md +1 -1
- package/grok/agents/arc-qa.md +1 -1
- package/grok/agents/arc-reviewer.md +1 -1
- package/grok/agents/arc-scouter.md +1 -1
- package/grok/skill/references/coordination.md +4 -2
- package/grok/skill/references/handoff-prep.md +5 -0
- package/grok/skill/references/handoff.md +2 -2
- package/grok/skill/references/planning.md +2 -2
- package/grok/skill/references/verification.md +16 -3
- package/grok/skill/references/worktree-creation.md +2 -2
- package/lib/cli/root.mjs +1 -1
- package/lib/management/reapply.mjs +117 -0
- package/lib/management/update.mjs +59 -5
- package/lib/npm/upgrade.mjs +6 -2
- package/lib/policy/role-policy.json +1 -1
- package/lib/prompts/agent-fragments.json +5 -5
- package/lib/runtime/grok-sandbox.mjs +74 -0
- package/lib/runtime/role-bridge.mjs +10 -1
- package/lib/runtime/role-dispatch-policy.mjs +7 -1
- package/lib/runtime/role-observe.mjs +401 -13
- package/lib/runtime/role-routing.mjs +6 -0
- package/lib/runtime/role-supervisor.mjs +285 -33
- package/lib/tui/app.mjs +3 -39
- package/lib/tui/interface.mjs +40 -0
- package/lib/tui/setup.mjs +27 -16
- package/lib/watch/args.mjs +12 -27
- package/lib/watch/dispatch.mjs +2 -2
- package/lib/watch/index.mjs +38 -26
- package/lib/watch/markdown.mjs +232 -0
- package/lib/watch/menu.mjs +43 -0
- package/lib/watch/model.mjs +7 -3
- package/lib/watch/render.mjs +28 -67
- package/lib/watch/scope.mjs +1 -5
- package/lib/watch/status-line.mjs +2 -4
- package/lib/watch/text-width.mjs +43 -0
- package/lib/watch/watcher.mjs +17 -36
- package/package.json +1 -1
- package/shared/skill/runtime/grok-sandbox.mjs +74 -0
- package/shared/skill/runtime/role-bridge.mjs +10 -1
- package/shared/skill/runtime/role-dispatch-policy.mjs +7 -1
- package/shared/skill/runtime/role-observe.mjs +401 -13
- package/shared/skill/runtime/role-policy.json +1 -1
- package/shared/skill/runtime/role-routing.mjs +6 -0
- package/shared/skill/runtime/role-supervisor.mjs +285 -33
|
@@ -4,23 +4,24 @@ import fs from 'node:fs';
|
|
|
4
4
|
import fsp from 'node:fs/promises';
|
|
5
5
|
import path from 'node:path';
|
|
6
6
|
import crypto from 'node:crypto';
|
|
7
|
-
import {spawn, spawnSync} from 'node:child_process';
|
|
7
|
+
import {execFile, spawn, spawnSync} from 'node:child_process';
|
|
8
8
|
import {fileURLToPath} from 'node:url';
|
|
9
|
+
import {promisify} from 'node:util';
|
|
9
10
|
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';
|
|
11
|
+
import {GROK_SANDBOX_RELATIVE, grokSandboxProfileName, renderGrokSandboxProfile, grokProfileCovered, inspectGrokProfileSlot, checkGrokHome, createGrokSandboxProfile, verifyGrokSandboxProfile, removeGrokSandboxProfile, grokEventsBaseline, readGrokProfileApplied, grokConfigSecurityProjection} from './grok-sandbox.mjs';
|
|
11
12
|
import {GEMINI_CONTRACT, normalizeGeminiStreamEvent, evaluateGeminiObservation} from './gemini-stream.mjs';
|
|
12
|
-
import {DEFAULT_POLICY, reason, bridgeGateReasons} from './role-dispatch-policy.mjs';
|
|
13
|
+
import {DEFAULT_POLICY, DESCENDANT_LIMIT, DESCENDANT_SAMPLE_MS, reason, bridgeGateReasons} from './role-dispatch-policy.mjs';
|
|
13
14
|
import {readLease, writeLease, writeHeartbeat, cancelRequested, TERMINAL_STATES} from './role-dispatch-store.mjs';
|
|
14
15
|
import {withRoutingLock, readActivation, resolveRuntimeHomes} from './role-routing.mjs';
|
|
15
|
-
import {observeCooperativeTarget} from './scope.mjs';
|
|
16
16
|
import {resolveLocalCli, localCliEnvironment} from './local-cli.mjs';
|
|
17
17
|
import {parseCompositeProfile, buildBridgeArgs, argsDigest, ROLE_BRIDGE_PERMISSIONS} from './role-bridge-args.mjs';
|
|
18
|
-
import {createLineParser, normalizeClaudeStreamEvent, normalizeCodexStreamEvent, eventRecord, evaluateClaudeInit, evaluateCodexContext, readClaudeTranscriptEffort, readCodexTurnContext, classifyFailure, snapshotWorktree, detectViolations} from './role-observe.mjs';
|
|
18
|
+
import {createLineParser, normalizeClaudeStreamEvent, normalizeCodexStreamEvent, eventRecord, evaluateClaudeInit, evaluateCodexContext, readClaudeTranscriptEffort, readCodexTurnContext, classifyFailure, snapshotWorktree, snapshotControlFiles, observeHeadAdvance, detectViolations, toleratedRecord, allowedPathsCoverControl, claudeProjectSettingsWidenScope, resolveWorktree} from './role-observe.mjs';
|
|
19
19
|
import {getPlatform, routingProfileFile} from './platform-registry.mjs';
|
|
20
20
|
|
|
21
21
|
const sleep = ms => new Promise(resolve => setTimeout(resolve, ms));
|
|
22
22
|
const sha256 = bytes => 'sha256:' + crypto.createHash('sha256').update(bytes).digest('hex');
|
|
23
23
|
const STDERR_LIMIT = 65536;
|
|
24
|
+
const execFileAsync = promisify(execFile);
|
|
24
25
|
|
|
25
26
|
export const SUPERVISOR_IMPLEMENTATIONS = new Map([
|
|
26
27
|
['claude', {
|
|
@@ -78,25 +79,195 @@ export const SUPERVISOR_IMPLEMENTATIONS = new Map([
|
|
|
78
79
|
]);
|
|
79
80
|
export const SUPERVISOR_PLATFORM_IDS = Object.freeze([...SUPERVISOR_IMPLEMENTATIONS.keys()]);
|
|
80
81
|
|
|
82
|
+
const normalizePsWhitespace = value => value.trim().replace(/\s+/g, ' ');
|
|
83
|
+
|
|
81
84
|
/** `ps -o lstart=` start time; used with the pid to tell a live process from a reused pid. Null when ps is unavailable or the pid is gone. */
|
|
82
85
|
export function processStartTime(pid) {
|
|
83
86
|
if (!Number.isInteger(pid) || pid <= 0) return null;
|
|
84
87
|
const result = spawnSync('ps', ['-o', 'lstart=', '-p', String(pid)], {encoding: 'utf8', env: {PATH: process.env.PATH ?? '/usr/bin:/bin', LC_ALL: 'C'}, timeout: 5000});
|
|
85
88
|
if (result.error || result.status !== 0) return null;
|
|
86
|
-
return result.stdout
|
|
89
|
+
return normalizePsWhitespace(result.stdout) || null;
|
|
87
90
|
}
|
|
88
91
|
export function processAlive({pid, startTime} = {}) {
|
|
89
92
|
const current = processStartTime(pid);
|
|
90
93
|
return current !== null && current === startTime;
|
|
91
94
|
}
|
|
92
95
|
|
|
93
|
-
|
|
94
|
-
|
|
95
|
-
|
|
96
|
-
|
|
97
|
-
|
|
98
|
-
|
|
96
|
+
const LSTART = /[A-Z][a-z]{2} [A-Z][a-z]{2} [1-9]\d? \d{2}:\d{2}:\d{2} \d{4}/;
|
|
97
|
+
const PROCESS_ROW = new RegExp(`^(\\d+) (\\d+) (\\d+) (${LSTART.source})(?: (\\d+) ([A-Za-z]\\S*))?$`);
|
|
98
|
+
const validPid = pid => Number.isInteger(pid) && pid > 0 && pid <= 0x7fffffff;
|
|
99
|
+
const sameStart = (row, entry) => row?.startTime === entry.startTime;
|
|
100
|
+
const processEntry = ({pid, ppid, pgid, startTime}) => ({pid, ppid, pgid, startTime});
|
|
101
|
+
|
|
102
|
+
export function parseProcessTable(stdout) {
|
|
103
|
+
const entries = [];
|
|
104
|
+
for (const line of stdout.split('\n')) {
|
|
105
|
+
const match = PROCESS_ROW.exec(normalizePsWhitespace(line));
|
|
106
|
+
if (!match) continue;
|
|
107
|
+
const [, pid, ppid, pgid, startTime, uid, stat] = match;
|
|
108
|
+
const entry = {pid: Number(pid), ppid: Number(ppid), pgid: Number(pgid), startTime};
|
|
109
|
+
if (!validPid(entry.pid) || (entry.ppid !== 0 && !validPid(entry.ppid)) || !validPid(entry.pgid)) continue;
|
|
110
|
+
if (stat?.startsWith('Z')) continue;
|
|
111
|
+
entries.push(uid === undefined ? entry : {...entry, uid: Number(uid)});
|
|
112
|
+
}
|
|
113
|
+
return entries;
|
|
114
|
+
}
|
|
115
|
+
|
|
116
|
+
export async function sampleProcessTable({timeoutMs = 5000} = {}) {
|
|
117
|
+
try {
|
|
118
|
+
const {stdout} = await execFileAsync('ps', ['-A', '-o', 'pid=,ppid=,pgid=,lstart=,uid=,stat='], {
|
|
119
|
+
encoding: 'utf8', env: {PATH: process.env.PATH ?? '/usr/bin:/bin', LC_ALL: 'C'}, timeout: timeoutMs,
|
|
120
|
+
});
|
|
121
|
+
return parseProcessTable(stdout);
|
|
122
|
+
} catch { return null; }
|
|
123
|
+
}
|
|
124
|
+
|
|
125
|
+
function supervisorLineage(byPid, selfPid) {
|
|
126
|
+
const excluded = new Set([selfPid]);
|
|
127
|
+
let parent = byPid.get(selfPid)?.ppid ?? (selfPid === process.pid ? process.ppid : 0);
|
|
128
|
+
while (validPid(parent) && !excluded.has(parent)) {
|
|
129
|
+
excluded.add(parent);
|
|
130
|
+
parent = byPid.get(parent)?.ppid;
|
|
131
|
+
}
|
|
132
|
+
return excluded;
|
|
133
|
+
}
|
|
134
|
+
|
|
135
|
+
export function createDescendantTracker({rootPid, rootPgid, selfPid, limit = DESCENDANT_LIMIT}) {
|
|
136
|
+
const tracked = new Map();
|
|
137
|
+
let root, truncated = false;
|
|
138
|
+
const entries = () => [...tracked.values()];
|
|
139
|
+
return {
|
|
140
|
+
get rootStartTime() { return root?.startTime; },
|
|
141
|
+
get truncated() { return truncated; },
|
|
142
|
+
entries,
|
|
143
|
+
escaped: () => entries().filter(entry => entry.pgid !== rootPgid),
|
|
144
|
+
update(table) {
|
|
145
|
+
const byPid = new Map(table.map(entry => [entry.pid, entry]));
|
|
146
|
+
const excluded = supervisorLineage(byPid, selfPid);
|
|
147
|
+
const currentRoot = byPid.get(rootPid);
|
|
148
|
+
const rootInPlace = currentRoot?.ppid === selfPid && currentRoot.pgid === rootPgid;
|
|
149
|
+
if (!root && rootInPlace) root = processEntry(currentRoot);
|
|
150
|
+
const children = new Map();
|
|
151
|
+
for (const entry of table) {
|
|
152
|
+
if (excluded.has(entry.pid) || entry.pid === rootPid) continue;
|
|
153
|
+
if (!children.has(entry.ppid)) children.set(entry.ppid, []);
|
|
154
|
+
children.get(entry.ppid).push(entry);
|
|
155
|
+
}
|
|
156
|
+
// Seed the walk only with identities still present in this sample.
|
|
157
|
+
const parents = [];
|
|
158
|
+
if (root && rootInPlace && sameStart(currentRoot, root)) parents.push(rootPid);
|
|
159
|
+
for (const entry of tracked.values()) {
|
|
160
|
+
const current = byPid.get(entry.pid);
|
|
161
|
+
if (excluded.has(entry.pid) || !sameStart(current, entry)) {
|
|
162
|
+
tracked.delete(entry.pid);
|
|
163
|
+
continue;
|
|
164
|
+
}
|
|
165
|
+
tracked.set(entry.pid, processEntry(current));
|
|
166
|
+
parents.push(entry.pid);
|
|
167
|
+
}
|
|
168
|
+
for (const parent of parents) {
|
|
169
|
+
for (const entry of children.get(parent) ?? []) {
|
|
170
|
+
if (tracked.has(entry.pid)) continue;
|
|
171
|
+
if (tracked.size >= limit) { truncated = true; continue; }
|
|
172
|
+
tracked.set(entry.pid, processEntry(entry));
|
|
173
|
+
parents.push(entry.pid);
|
|
174
|
+
}
|
|
175
|
+
}
|
|
176
|
+
},
|
|
177
|
+
};
|
|
178
|
+
}
|
|
179
|
+
|
|
180
|
+
export async function reapDescendants(entries, {sample = sampleProcessTable, kill = process.kill, graceMs = DEFAULT_POLICY.cancelGraceMs, timeoutMs = 500, truncated = false} = {}) {
|
|
181
|
+
const observed = entries.length, denied = new Set();
|
|
182
|
+
const uid = process.geteuid?.();
|
|
183
|
+
const readSample = async () => {
|
|
184
|
+
try {
|
|
185
|
+
const table = await sample();
|
|
186
|
+
return Array.isArray(table) ? new Map(table.map(entry => [entry.pid, entry])) : null;
|
|
187
|
+
} catch { return null; }
|
|
188
|
+
};
|
|
189
|
+
const signal = (targets, table, name) => {
|
|
190
|
+
const excluded = supervisorLineage(table, process.pid);
|
|
191
|
+
const eligible = [];
|
|
192
|
+
const send = target => {
|
|
193
|
+
try { kill(target, name); }
|
|
194
|
+
catch (error) {
|
|
195
|
+
// A group error does not identify which members are still alive.
|
|
196
|
+
if (target > 0 && error.code === 'EPERM') denied.add(target);
|
|
197
|
+
}
|
|
198
|
+
};
|
|
199
|
+
for (const entry of targets) {
|
|
200
|
+
const {pid} = entry, current = table.get(pid);
|
|
201
|
+
if (!sameStart(current, entry) || denied.has(pid)) continue;
|
|
202
|
+
if (pid <= 1 || excluded.has(pid) || (current.uid !== undefined && current.uid !== uid)) {
|
|
203
|
+
denied.add(pid);
|
|
204
|
+
continue;
|
|
205
|
+
}
|
|
206
|
+
eligible.push(entry);
|
|
207
|
+
send(pid);
|
|
208
|
+
}
|
|
209
|
+
const eligiblePids = new Set(eligible.map(entry => entry.pid));
|
|
210
|
+
const blockedGroups = new Set();
|
|
211
|
+
for (const member of table.values()) {
|
|
212
|
+
if (!eligiblePids.has(member.pid) || denied.has(member.pid)) blockedGroups.add(member.pgid);
|
|
213
|
+
}
|
|
214
|
+
for (const {pid, pgid} of eligible) {
|
|
215
|
+
if (pgid === pid && table.get(pid).pgid === pid && !blockedGroups.has(pid)) send(-pid);
|
|
216
|
+
}
|
|
217
|
+
};
|
|
218
|
+
const summary = survived => ({observed, reaped: observed - survived, survived, truncated});
|
|
219
|
+
if (!observed) return summary(0);
|
|
220
|
+
let table = await readSample();
|
|
221
|
+
if (!table) return summary(observed);
|
|
222
|
+
let remaining = entries.filter(entry => sameStart(table.get(entry.pid), entry));
|
|
223
|
+
signal(remaining, table, 'SIGTERM');
|
|
224
|
+
if (!remaining.some(entry => !denied.has(entry.pid))) return summary(denied.size);
|
|
225
|
+
if (graceMs > 0) await sleep(graceMs);
|
|
226
|
+
table = await readSample();
|
|
227
|
+
if (!table) return summary(remaining.length);
|
|
228
|
+
remaining = remaining.filter(entry => denied.has(entry.pid) || sameStart(table.get(entry.pid), entry));
|
|
229
|
+
signal(remaining, table, 'SIGKILL');
|
|
230
|
+
const deadline = Date.now() + timeoutMs;
|
|
231
|
+
while (remaining.some(entry => !denied.has(entry.pid))) {
|
|
232
|
+
table = await readSample();
|
|
233
|
+
if (!table) break;
|
|
234
|
+
remaining = remaining.filter(entry => denied.has(entry.pid) || sameStart(table.get(entry.pid), entry));
|
|
235
|
+
const wait = deadline - Date.now();
|
|
236
|
+
if (wait <= 0 || !remaining.some(entry => !denied.has(entry.pid))) break;
|
|
237
|
+
await sleep(Math.min(25, wait));
|
|
238
|
+
}
|
|
239
|
+
return summary(remaining.length);
|
|
240
|
+
}
|
|
241
|
+
|
|
242
|
+
const DESCENDANTS_FILE = 'descendants.json';
|
|
243
|
+
const DESCENDANT_START = new RegExp(`^${LSTART.source}$`);
|
|
244
|
+
export const descendantRecord = stats => stats && (stats.observed > 0 || stats.truncated) ? {escapedDescendants: stats} : {};
|
|
245
|
+
|
|
246
|
+
export async function reapRecordedDescendants(artifactDir, lease, options) {
|
|
247
|
+
let file;
|
|
248
|
+
try {
|
|
249
|
+
file = await fsp.open(path.join(artifactDir, DESCENDANTS_FILE), fs.constants.O_RDONLY | fs.constants.O_NOFOLLOW | fs.constants.O_NONBLOCK);
|
|
250
|
+
const stat = await file.stat();
|
|
251
|
+
if (!stat.isFile() || stat.uid !== process.geteuid?.() || stat.size > 65536) return {};
|
|
252
|
+
const snapshot = JSON.parse(await file.readFile('utf8'));
|
|
253
|
+
const {version, dispatchId, segment, rootPid, rootPgid, rootStartTime, truncated, entries} = snapshot;
|
|
254
|
+
// Bind the snapshot to its lease. Tampering by a user with the same UID is outside this boundary.
|
|
255
|
+
if (Object.keys(snapshot).length !== 8 || version !== 1 || dispatchId !== lease.dispatchId || segment !== (lease.segment ?? 0) || !validPid(rootPid) || rootPid !== lease.child?.pid || rootPgid !== rootPid) return {};
|
|
256
|
+
const recordedStart = typeof rootStartTime === 'string' ? normalizePsWhitespace(rootStartTime) : '';
|
|
257
|
+
const leaseStart = lease.child?.startTime;
|
|
258
|
+
if (!DESCENDANT_START.test(recordedStart) || typeof leaseStart !== 'string' || recordedStart !== normalizePsWhitespace(leaseStart)) return {};
|
|
259
|
+
if (typeof truncated !== 'boolean' || !Array.isArray(entries) || entries.length > DESCENDANT_LIMIT) return {};
|
|
260
|
+
const seen = new Set([rootPid]);
|
|
261
|
+
for (const entry of entries) {
|
|
262
|
+
if (!entry || Object.keys(entry).length !== 4 || !validPid(entry.pid) || entry.pid <= 1 || seen.has(entry.pid) || !validPid(entry.ppid) || !validPid(entry.pgid) || typeof entry.startTime !== 'string' || !DESCENDANT_START.test(entry.startTime)) return {};
|
|
263
|
+
seen.add(entry.pid);
|
|
264
|
+
}
|
|
265
|
+
return descendantRecord(await reapDescendants(entries.filter(entry => entry.pgid !== rootPgid), {...options, truncated}));
|
|
266
|
+
} catch { return {}; }
|
|
267
|
+
finally { await file?.close().catch(() => {}); }
|
|
99
268
|
}
|
|
269
|
+
|
|
270
|
+
export {resolveWorktree};
|
|
100
271
|
export const artifactDirectory = (target, workflowId, dispatchId) => path.join(target.gitCommonDir, 'arc', 'workflows', workflowId, 'dispatches', dispatchId);
|
|
101
272
|
/** Segment 0 (the first run) keeps its files in the dispatch directory; resumed segments use segments/<n>/. */
|
|
102
273
|
export const segmentDirectory = (target, workflowId, dispatchId, segment) => segment > 0 ? path.join(artifactDirectory(target, workflowId, dispatchId), 'segments', String(segment)) : artifactDirectory(target, workflowId, dispatchId);
|
|
@@ -119,6 +290,11 @@ export async function buildBridgeInvocation({lease, config, homes, worktree, res
|
|
|
119
290
|
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');
|
|
120
291
|
if (!implementation) throw fail('permission_scope_unverified', 'Invalid composite profile: unknown platform');
|
|
121
292
|
const permissions = ROLE_BRIDGE_PERMISSIONS[platform][lease.role];
|
|
293
|
+
if (Array.isArray(lease.allowedPaths) && allowedPathsCoverControl(lease.allowedPaths)) throw fail('permission_scope_unverified', 'allowedPaths cover a control file');
|
|
294
|
+
if (platform === 'claude' && permissions.sandbox) {
|
|
295
|
+
const scopeReason = await claudeProjectSettingsWidenScope(worktree);
|
|
296
|
+
if (scopeReason) throw fail('permission_scope_unverified', scopeReason);
|
|
297
|
+
}
|
|
122
298
|
let grokSandbox;
|
|
123
299
|
if (platform === 'grok' && permissions.sandbox === 'custom') {
|
|
124
300
|
const name = grokSandboxProfileName(lease.dispatchId);
|
|
@@ -155,6 +331,10 @@ export async function startSupervisor({codexHome, dispatchId, cwd, userHome, env
|
|
|
155
331
|
export async function runSupervisor(options) {
|
|
156
332
|
const {codexHome, dispatchId, cwd, userHome, env = process.env, policy = DEFAULT_POLICY} = options;
|
|
157
333
|
const heartbeatMs = options.heartbeatMs ?? policy.heartbeatMs, graceMs = options.graceMs ?? policy.cancelGraceMs;
|
|
334
|
+
const descendantSampleMs = options.descendantSampleMs ?? policy.descendantSampleMs ?? DESCENDANT_SAMPLE_MS;
|
|
335
|
+
const descendantLimit = Math.min(options.descendantLimit ?? policy.descendantLimit ?? DESCENDANT_LIMIT, DESCENDANT_LIMIT);
|
|
336
|
+
const sampleProcesses = options.sampleProcesses ?? sampleProcessTable;
|
|
337
|
+
const stopSignal = options.stopSignal;
|
|
158
338
|
const eventsMax = options.eventsMaxBytes ?? policy.eventsMaxBytes, codexWaitMs = options.codexWaitMs ?? 10000;
|
|
159
339
|
const lockRetryMs = options.lockRetryMs ?? policy.lockRetryMs, lockDeadlineMs = options.lockDeadlineMs ?? 30000;
|
|
160
340
|
const startedAt = new Date().toISOString();
|
|
@@ -227,13 +407,55 @@ export async function runSupervisor(options) {
|
|
|
227
407
|
await writeRecord({state: 'failed', reasons: codes, spawned: spawned !== null, ...(spawned !== null ? {childPid: spawned} : {}), ...extra}).catch(() => {});
|
|
228
408
|
await commit('failed', codes, claims);
|
|
229
409
|
};
|
|
230
|
-
const failWithProfileCleanup = (code, spawned = null) => {
|
|
410
|
+
const failWithProfileCleanup = (code, spawned = null, extra = {}) => {
|
|
231
411
|
cleanGrokProfile();
|
|
232
|
-
return earlyFailure(code, spawned, grokProfileRecord());
|
|
412
|
+
return earlyFailure(code, spawned, {...grokProfileRecord(), ...extra});
|
|
233
413
|
};
|
|
234
414
|
|
|
235
415
|
let child = null, eventsFd = null, killTimers = [], terminating = null, termAt = 0;
|
|
236
|
-
|
|
416
|
+
let executionTimer, originalGroupGone;
|
|
417
|
+
const stopGroupSignals = gone => {
|
|
418
|
+
originalGroupGone = gone;
|
|
419
|
+
for (const timer of killTimers) clearTimeout(timer);
|
|
420
|
+
killTimers = [];
|
|
421
|
+
};
|
|
422
|
+
let tracker, descendantTimer, pendingSample, savedSnapshot, descendantCleanup, onStop;
|
|
423
|
+
const sampleDescendants = async () => {
|
|
424
|
+
const table = await sampleProcesses();
|
|
425
|
+
if (!Array.isArray(table)) return;
|
|
426
|
+
tracker.update(table);
|
|
427
|
+
const entries = tracker.entries();
|
|
428
|
+
if (!entries.length && !tracker.truncated && !savedSnapshot) return;
|
|
429
|
+
const snapshot = JSON.stringify({
|
|
430
|
+
version: 1, dispatchId, segment: lease.segment ?? 0, rootPid: child.pid, rootPgid: child.pid,
|
|
431
|
+
rootStartTime: tracker.rootStartTime, truncated: tracker.truncated, entries,
|
|
432
|
+
}) + '\n';
|
|
433
|
+
if (snapshot === savedSnapshot) return;
|
|
434
|
+
const file = path.join(artifactDir, DESCENDANTS_FILE);
|
|
435
|
+
const temporary = `${file}.${crypto.randomUUID()}.tmp`;
|
|
436
|
+
try {
|
|
437
|
+
await fsp.writeFile(temporary, snapshot, {mode: 0o600, flag: 'wx'});
|
|
438
|
+
await fsp.rename(temporary, file);
|
|
439
|
+
savedSnapshot = snapshot;
|
|
440
|
+
} finally { await fsp.unlink(temporary).catch(() => {}); }
|
|
441
|
+
};
|
|
442
|
+
const queueDescendantSample = () => {
|
|
443
|
+
if (!pendingSample) pendingSample = sampleDescendants().catch(() => {}).finally(() => { pendingSample = null; });
|
|
444
|
+
};
|
|
445
|
+
const finishDescendants = () => {
|
|
446
|
+
if (!tracker) return {};
|
|
447
|
+
if (!descendantCleanup) descendantCleanup = (async () => {
|
|
448
|
+
clearInterval(descendantTimer);
|
|
449
|
+
timers.delete(descendantTimer);
|
|
450
|
+
await pendingSample;
|
|
451
|
+
await sampleDescendants().catch(() => {});
|
|
452
|
+
return descendantRecord(await reapDescendants(tracker.escaped(), {
|
|
453
|
+
sample: sampleProcesses, kill: options.killProcess, graceMs, truncated: tracker.truncated,
|
|
454
|
+
}));
|
|
455
|
+
})().catch(() => ({}));
|
|
456
|
+
return descendantCleanup;
|
|
457
|
+
};
|
|
458
|
+
const killGroup = signal => { if (originalGroupGone === undefined && child?.pid) { try { (options.signalGroup ?? process.kill)(-child.pid, signal); } catch { /* group already gone */ } } };
|
|
237
459
|
const groupAlive = () => { try { process.kill(-child.pid, 0); return true; } catch (error) { return error.code === 'EPERM'; } };
|
|
238
460
|
// Terminal states are recorded only after the whole process group is observed gone: SIGKILL goes to the group after the grace period even when the leader already exited.
|
|
239
461
|
const reapGroup = async () => {
|
|
@@ -273,8 +495,16 @@ export async function runSupervisor(options) {
|
|
|
273
495
|
const {path, sha256, dirCreated} = createdGrokProfile;
|
|
274
496
|
grokSandboxProfile = {name: invocation.grokSandbox.name, path, sha256, dirCreated, created: true, removed: null, dirRemoved: false, eventsBaseline: null, applied: null};
|
|
275
497
|
}
|
|
498
|
+
const extra = invocation.grokSandbox ? [
|
|
499
|
+
{label: 'grok-home:config.toml', path: path.join(homes.grok, 'config.toml'), project: grokConfigSecurityProjection},
|
|
500
|
+
{label: 'grok-home:sandbox.toml', path: path.join(homes.grok, 'sandbox.toml')},
|
|
501
|
+
] : [];
|
|
502
|
+
const snapshot = async () => ({
|
|
503
|
+
...await snapshotWorktree(target.realpath),
|
|
504
|
+
control: await snapshotControlFiles({gitCommonDir: target.gitCommonDir, gitDir: target.gitDir, worktree: target.realpath, extra}),
|
|
505
|
+
});
|
|
276
506
|
let before;
|
|
277
|
-
try { before = await
|
|
507
|
+
try { before = await snapshot(); } catch { return await failWithProfileCleanup('execution_failed'); }
|
|
278
508
|
|
|
279
509
|
if (invocation.promptFile) {
|
|
280
510
|
let promptFd;
|
|
@@ -297,10 +527,16 @@ export async function runSupervisor(options) {
|
|
|
297
527
|
}
|
|
298
528
|
// The child is a process-group leader so one signal reaches its descendants. The prompt uses the platform-specific input channel.
|
|
299
529
|
child = spawn(cli.executable, invocation.args, {cwd: target.realpath, env: {...childEnv, ARC_BRIDGE_CHILD: dispatchId}, detached: true, stdio: ['pipe', 'pipe', 'pipe'], shell: false});
|
|
530
|
+
if (child.pid) tracker = createDescendantTracker({rootPid: child.pid, rootPgid: child.pid, selfPid: process.pid, limit: descendantLimit});
|
|
300
531
|
let exitResolve, exited = false;
|
|
301
532
|
const exitPromise = new Promise(resolve => { exitResolve = resolve; });
|
|
302
|
-
|
|
303
|
-
|
|
533
|
+
const observeExit = exit => {
|
|
534
|
+
exited = true;
|
|
535
|
+
clearTimeout(executionTimer);
|
|
536
|
+
exitResolve(exit);
|
|
537
|
+
};
|
|
538
|
+
child.on('exit', (code, signal) => observeExit({code, signal}));
|
|
539
|
+
child.on('error', () => observeExit({code: null, signal: null, spawnError: true}));
|
|
304
540
|
child.stdin.on('error', () => {});
|
|
305
541
|
if (options.afterSpawn) await options.afterSpawn(child); // test injection point for post-spawn failures
|
|
306
542
|
if (platform === 'grok') child.stdin.end();
|
|
@@ -311,15 +547,18 @@ export async function runSupervisor(options) {
|
|
|
311
547
|
let eventsBytes = 0, eventsTruncated = false, stderrLength = 0, contextTask = null;
|
|
312
548
|
const stderrParts = [];
|
|
313
549
|
const terminate = why => {
|
|
314
|
-
if (terminating) return;
|
|
550
|
+
if (terminating || originalGroupGone !== undefined) return;
|
|
315
551
|
terminating = why; termAt = Date.now(); killGroup('SIGTERM');
|
|
316
552
|
killTimers.push(setTimeout(() => {
|
|
317
553
|
killGroup('SIGKILL');
|
|
318
554
|
killTimers.push(setTimeout(() => exitResolve({code: null, signal: null, unobserved: true}), graceMs));
|
|
319
555
|
}, graceMs));
|
|
320
556
|
};
|
|
557
|
+
onStop = () => terminate('supervisor_signal');
|
|
558
|
+
if (stopSignal?.aborted) onStop();
|
|
559
|
+
else stopSignal?.addEventListener('abort', onStop, {once: true});
|
|
321
560
|
const deadline = options.timeoutMs ?? lease.timeoutMinutes * 60000;
|
|
322
|
-
|
|
561
|
+
if (!exited) executionTimer = setTimeout(() => terminate('timeout'), deadline);
|
|
323
562
|
let cancelBusy = false;
|
|
324
563
|
timers.add(setInterval(async () => {
|
|
325
564
|
if (cancelBusy || terminating || exited) return;
|
|
@@ -414,9 +653,11 @@ export async function runSupervisor(options) {
|
|
|
414
653
|
if (!mine(current)) throw Error('Lease changed before the child was recorded');
|
|
415
654
|
await writeLease(codexHome, {...current, state: 'running', child: {pid: child.pid, startTime}}, {runtimePlatforms});
|
|
416
655
|
});
|
|
656
|
+
queueDescendantSample();
|
|
657
|
+
descendantTimer = setInterval(queueDescendantSample, descendantSampleMs);
|
|
658
|
+
timers.add(descendantTimer);
|
|
417
659
|
} catch { state.internal = 'execution_failed'; terminate('internal'); }
|
|
418
660
|
|
|
419
|
-
|
|
420
661
|
let exit = await exitPromise;
|
|
421
662
|
// A cancel request whose own SIGTERM stopped the child before the marker poll ran still counts as a cancel, and the group is reaped the same way.
|
|
422
663
|
if (!terminating && !exit.unobserved && (exit.signal || !state.terminal) && await cancelRequested(codexHome, dispatchId)) { terminating = 'cancel'; termAt = Date.now(); }
|
|
@@ -424,18 +665,19 @@ export async function runSupervisor(options) {
|
|
|
424
665
|
let orphanGroupReaped = false;
|
|
425
666
|
if (!termAt && !exit.unobserved && child?.pid && groupAlive()) { orphanGroupReaped = true; termAt = Date.now(); killGroup('SIGTERM'); }
|
|
426
667
|
if (termAt && !exit.unobserved && !await reapGroup()) exit = {code: null, signal: null, unobserved: true};
|
|
668
|
+
stopGroupSignals(!exit.unobserved);
|
|
669
|
+
const escapes = await finishDescendants();
|
|
427
670
|
await Promise.race([stdoutClosed, sleep(1000)]);
|
|
428
671
|
parser.end();
|
|
429
672
|
if (contextTask) await contextTask;
|
|
430
673
|
for (const timer of timers) { clearInterval(timer); clearTimeout(timer); }
|
|
431
|
-
|
|
432
|
-
timers.clear(); killTimers = [];
|
|
674
|
+
timers.clear();
|
|
433
675
|
fs.closeSync(eventsFd); eventsFd = null;
|
|
434
676
|
|
|
435
677
|
if (exit.unobserved) {
|
|
436
678
|
// The child was signalled but its exit was never observed: the slot stays occupied.
|
|
437
679
|
const claims = {...lease.claims, terminal: {level: 'unverified', source: 'none'}};
|
|
438
|
-
await writeRecord({state: 'unknown', reasons: [...(terminating === 'timeout' ? ['timeout'] : []), 'terminal_state_unverified'], terminatedBy: terminating, eventsTruncated, ignoredLines: parser.ignored, lineOverflow: parser.overflow, ...retainGrokProfile()}).catch(() => {});
|
|
680
|
+
await writeRecord({state: 'unknown', reasons: [...(terminating === 'timeout' ? ['timeout'] : []), 'terminal_state_unverified'], terminatedBy: terminating, eventsTruncated, ignoredLines: parser.ignored, lineOverflow: parser.overflow, ...retainGrokProfile(), ...escapes}).catch(() => {});
|
|
439
681
|
await locked(async () => {
|
|
440
682
|
const current = await readLease(codexHome, dispatchId, {runtimePlatforms});
|
|
441
683
|
if (current && !TERMINAL_STATES.includes(current.state)) await writeLease(codexHome, {...current, state: 'unknown', claims, reasons: [...(terminating === 'timeout' ? ['timeout'] : []), 'terminal_state_unverified'].map(reason)}, {runtimePlatforms});
|
|
@@ -444,8 +686,9 @@ export async function runSupervisor(options) {
|
|
|
444
686
|
}
|
|
445
687
|
|
|
446
688
|
let after = null;
|
|
447
|
-
try { after = await
|
|
448
|
-
const
|
|
689
|
+
try { after = await snapshot(); } catch { after = null; }
|
|
690
|
+
const headAdvance = after ? await observeHeadAdvance(target.realpath, before, after, lease.role, lease.allowedPaths) : null;
|
|
691
|
+
const violations = after ? detectViolations({role: lease.role, allowedPaths: lease.allowedPaths, before, after, headAdvance}) : {reason: null, changedPaths: [], headChanged: false, refsChanged: false, controlChanged: [], toleratedRefs: [], toleratedControl: [], toleratedCommitPaths: []};
|
|
449
692
|
const codes = [];
|
|
450
693
|
if (state.mismatch) codes.push(state.mismatch);
|
|
451
694
|
if (state.internal) codes.push(state.internal);
|
|
@@ -495,25 +738,32 @@ export async function runSupervisor(options) {
|
|
|
495
738
|
}
|
|
496
739
|
if (exit.spawnError && !codes.length) { codes.push('execution_failed'); finalState = 'failed'; }
|
|
497
740
|
if ((finalState === 'completed' || finalState === 'cancelled') && codes.includes('permission_scope_mismatch')) finalState = 'failed';
|
|
498
|
-
|
|
741
|
+
const controlFiles = violations.controlChanged.length ? {controlFiles: {changed: violations.controlChanged}} : {};
|
|
742
|
+
const tolerated = toleratedRecord(violations);
|
|
743
|
+
await writeRecord({state: finalState, reasons: [...new Set(codes)], exit: {code: exit.code, signal: exit.signal}, terminatedBy: terminating, eventsTruncated, ignoredLines: parser.ignored, lineOverflow: parser.overflow, violations: {changedPaths: violations.changedPaths, headChanged: violations.headChanged, refsChanged: violations.refsChanged}, ...controlFiles, ...(tolerated ? {tolerated} : {}), ...(orphanGroupReaped ? {orphanGroupReaped: true} : {}), argsDigest: invocation.argsDigest, resultPath, ...grokProfileRecord(), ...(platform === 'gemini' ? {unverifiedContracts: {delegation: GEMINI_CONTRACT.delegation}} : platform === 'grok' ? {unverifiedContracts: {delegation: GROK_CONTRACT.delegation}} : {}), ...escapes});
|
|
499
744
|
await commit(finalState, codes, claims, {sessionId, resultPath});
|
|
500
745
|
} catch {
|
|
501
746
|
// Unexpected failure after the child started: stop it, then record a failed state if the child is gone.
|
|
502
747
|
const spawnedPid = child?.pid ?? null;
|
|
503
|
-
|
|
504
|
-
|
|
748
|
+
clearTimeout(executionTimer);
|
|
749
|
+
let stopped = originalGroupGone ?? true;
|
|
750
|
+
if (spawnedPid && originalGroupGone === undefined) { if (!termAt) { termAt = Date.now(); killGroup('SIGTERM'); } stopped = await reapGroup().catch(() => false); }
|
|
751
|
+
stopGroupSignals(stopped);
|
|
752
|
+
const escapes = await finishDescendants();
|
|
753
|
+
const details = {...escapes, ...(terminating === 'supervisor_signal' ? {terminatedBy: terminating} : {})};
|
|
505
754
|
for (const timer of timers) { clearInterval(timer); clearTimeout(timer); }
|
|
506
|
-
|
|
507
|
-
if (stopped) await failWithProfileCleanup('execution_failed', spawnedPid).catch(() => {});
|
|
755
|
+
if (stopped) await failWithProfileCleanup('execution_failed', spawnedPid, details).catch(() => {});
|
|
508
756
|
else {
|
|
509
757
|
const codes = ['execution_failed', 'terminal_state_unverified'];
|
|
510
|
-
await writeRecord({state: 'unknown', reasons: codes, spawned: true, childPid: spawnedPid, ...retainGrokProfile()}).catch(() => {});
|
|
758
|
+
await writeRecord({state: 'unknown', reasons: codes, spawned: true, childPid: spawnedPid, ...retainGrokProfile(), ...details}).catch(() => {});
|
|
511
759
|
await locked(async () => {
|
|
512
760
|
const current = await readLease(codexHome, dispatchId, {runtimePlatforms});
|
|
513
761
|
if (current && !TERMINAL_STATES.includes(current.state)) await writeLease(codexHome, {...current, state: 'unknown', reasons: codes.map(reason)}, {runtimePlatforms});
|
|
514
762
|
}).catch(() => {});
|
|
515
763
|
}
|
|
516
764
|
} finally {
|
|
765
|
+
if (onStop) stopSignal?.removeEventListener('abort', onStop);
|
|
766
|
+
clearTimeout(executionTimer);
|
|
517
767
|
for (const timer of timers) { clearInterval(timer); clearTimeout(timer); }
|
|
518
768
|
if (eventsFd !== null) { try { fs.closeSync(eventsFd); } catch { /* closed */ } }
|
|
519
769
|
}
|
|
@@ -522,5 +772,7 @@ export async function runSupervisor(options) {
|
|
|
522
772
|
const isMain = () => { try { return Boolean(process.argv[1]) && fs.realpathSync(process.argv[1]) === fileURLToPath(import.meta.url); } catch { return false; } };
|
|
523
773
|
if (isMain()) {
|
|
524
774
|
const [, , codexHome, dispatchId, cwd, userHome] = process.argv;
|
|
525
|
-
|
|
775
|
+
const controller = new AbortController();
|
|
776
|
+
for (const signal of ['SIGTERM', 'SIGINT', 'SIGHUP']) process.once(signal, () => controller.abort());
|
|
777
|
+
runSupervisor({codexHome, dispatchId, cwd, userHome, env: process.env, stopSignal: controller.signal}).then(() => process.exit(0), () => process.exit(1));
|
|
526
778
|
}
|