@yunhozz/arc 0.4.3 → 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.
Files changed (87) hide show
  1. package/MANIFEST.sha256 +86 -84
  2. package/README.md +3 -2
  3. package/claude/agents/arc-implementer.md +1 -0
  4. package/claude/agents/arc-planner.md +1 -0
  5. package/claude/agents/arc-qa.md +1 -0
  6. package/claude/agents/arc-reviewer.md +1 -0
  7. package/claude/agents/arc-scouter.md +1 -0
  8. package/claude/skill/SKILL.md +7 -4
  9. package/claude/skill/references/commit.md +6 -4
  10. package/claude/skill/references/coordination.md +84 -9
  11. package/claude/skill/references/handoff-prep.md +4 -4
  12. package/claude/skill/references/handoff.md +1 -1
  13. package/claude/skill/references/planning.md +41 -4
  14. package/claude/skill/references/verification.md +4 -4
  15. package/codex/agents/arc-implementer.toml +1 -0
  16. package/codex/agents/arc-planner.toml +1 -0
  17. package/codex/agents/arc-qa.toml +1 -0
  18. package/codex/agents/arc-reviewer.toml +1 -0
  19. package/codex/agents/arc-scouter.toml +1 -0
  20. package/codex/skill/SKILL.md +7 -4
  21. package/codex/skill/references/commit.md +6 -4
  22. package/codex/skill/references/coordination.md +84 -9
  23. package/codex/skill/references/handoff-prep.md +4 -4
  24. package/codex/skill/references/handoff.md +1 -1
  25. package/codex/skill/references/planning.md +41 -4
  26. package/codex/skill/references/verification.md +4 -4
  27. package/gemini/agents/arc-implementer.md +1 -0
  28. package/gemini/agents/arc-planner.md +1 -0
  29. package/gemini/agents/arc-qa.md +1 -0
  30. package/gemini/agents/arc-reviewer.md +1 -0
  31. package/gemini/agents/arc-scouter.md +1 -0
  32. package/gemini/skill/SKILL.md +7 -4
  33. package/gemini/skill/references/commit.md +6 -4
  34. package/gemini/skill/references/coordination.md +85 -10
  35. package/gemini/skill/references/handoff-prep.md +4 -4
  36. package/gemini/skill/references/handoff.md +1 -1
  37. package/gemini/skill/references/planning.md +41 -4
  38. package/gemini/skill/references/verification.md +4 -4
  39. package/grok/agents/arc-implementer.md +1 -0
  40. package/grok/agents/arc-planner.md +1 -0
  41. package/grok/agents/arc-qa.md +1 -0
  42. package/grok/agents/arc-reviewer.md +1 -0
  43. package/grok/agents/arc-scouter.md +1 -0
  44. package/grok/skill/SKILL.md +7 -4
  45. package/grok/skill/references/commit.md +6 -4
  46. package/grok/skill/references/coordination.md +88 -13
  47. package/grok/skill/references/handoff-prep.md +4 -4
  48. package/grok/skill/references/handoff.md +1 -1
  49. package/grok/skill/references/planning.md +41 -4
  50. package/grok/skill/references/verification.md +4 -4
  51. package/lib/installer/global-config.mjs +8 -3
  52. package/lib/installer/language.mjs +54 -6
  53. package/lib/installer/plan.mjs +13 -11
  54. package/lib/installer/role-routing.mjs +2 -2
  55. package/lib/installer/runtime-assets.mjs +1 -0
  56. package/lib/installer/upgrade-state.mjs +10 -3
  57. package/lib/installer/upgrade.mjs +3 -3
  58. package/lib/management/operations.mjs +9 -6
  59. package/lib/management/status.mjs +22 -3
  60. package/lib/platforms/claude.mjs +1 -0
  61. package/lib/platforms/codex.mjs +1 -0
  62. package/lib/platforms/index.mjs +7 -0
  63. package/lib/policy/placement.mjs +2 -2
  64. package/lib/policy/render.mjs +1 -1
  65. package/lib/policy/role-policy.json +28 -2
  66. package/lib/prompts/agent-fragments.json +1 -1
  67. package/lib/prompts/render.mjs +1 -1
  68. package/lib/runtime/bootstrap.mjs +1 -1
  69. package/lib/runtime/grok-sandbox.mjs +234 -0
  70. package/lib/runtime/platform-registry.mjs +2 -2
  71. package/lib/runtime/role-bridge-args.mjs +6 -4
  72. package/lib/runtime/role-bridge.mjs +14 -6
  73. package/lib/runtime/role-dispatch-policy.mjs +30 -5
  74. package/lib/runtime/role-routing.mjs +31 -4
  75. package/lib/runtime/role-supervisor.mjs +77 -16
  76. package/lib/tui/mode.mjs +15 -3
  77. package/lib/tui/setup.mjs +51 -34
  78. package/package.json +1 -1
  79. package/shared/skill/runtime/bootstrap.mjs +1 -1
  80. package/shared/skill/runtime/grok-sandbox.mjs +234 -0
  81. package/shared/skill/runtime/platform-registry.mjs +2 -2
  82. package/shared/skill/runtime/role-bridge-args.mjs +6 -4
  83. package/shared/skill/runtime/role-bridge.mjs +14 -6
  84. package/shared/skill/runtime/role-dispatch-policy.mjs +30 -5
  85. package/shared/skill/runtime/role-policy.json +28 -2
  86. package/shared/skill/runtime/role-routing.mjs +31 -4
  87. package/shared/skill/runtime/role-supervisor.mjs +77 -16
@@ -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
- const earlyFailure = async (code, spawned = null) => {
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
- await writeRecord({state: 'failed', reasons: [code], spawned: spawned !== null, ...(spawned !== null ? {childPid: spawned} : {})}).catch(() => {});
203
- await commit('failed', [code], claims);
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 earlyFailure('execution_failed'); }
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 earlyFailure('execution_failed'); }
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: {...localCliEnvironment(cli), ...invocation.childEnv, ARC_BRIDGE_CHILD: dispatchId}, detached: true, stdio: ['pipe', 'pipe', 'pipe'], shell: false});
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 (violations.reason) codes.push(violations.reason);
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
- else if (violations.reason) claims.permissions = {...claims.permissions, level: 'unverified', details: 'permission violation observed'};
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
- 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, ...(platform === 'gemini' ? {unverifiedContracts: {delegation: GEMINI_CONTRACT.delegation}} : platform === 'grok' ? {unverifiedContracts: {delegation: GROK_CONTRACT.delegation}} : {})});
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 (eventsFd !== null) { try { fs.closeSync(eventsFd); } catch { /* closed */ } }
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/lib/tui/mode.mjs CHANGED
@@ -49,11 +49,23 @@ export function statusInfo(installState, statuses, registry = installerRegistryO
49
49
  const status = statuses.find(status => status.platform === runtime.id);
50
50
  return status ? [{runtime, status, state: stateLabel(status, runtime)}] : [];
51
51
  });
52
+ const settings = statuses.filter(status => status.state === 'installed' && status.settings).map(status => status.settings);
53
+ const settingsRows = settings.length ? [
54
+ ['Run mode', ({runMode}) => runMode === 'full-auto' ? 'Full Auto' : 'Supervised'],
55
+ ['Language', ({language}) => language === 'ko' ? 'Korean' : 'English'],
56
+ ['Total subagents', ({limits}) => String(limits.max_total_subagents)],
57
+ ['Concurrent subagents', ({limits}) => String(limits.max_concurrent_subagents)]
58
+ ].map(([label, displayValue]) => {
59
+ const values = settings.map(displayValue);
60
+ return [label, values.every(value => value === values[0]) ? values[0] : 'mixed'];
61
+ }) : [];
52
62
  const width = text => [...escapeTerminalText(text)].reduce((sum, character) => sum + cellWidth(character), 0);
53
- const labelWidth = Math.max(width('Mode'), ...(version ? [width('Version')] : []), ...platforms.map(({runtime}) => width(runtime.label)));
63
+ const labelWidth = Math.max(width('Installed on'), ...settingsRows.map(([label]) => width(label)),
64
+ ...(version ? [width('Version')] : []), ...platforms.map(({runtime}) => width(runtime.label)));
54
65
  const row = (label, value) => label + ' '.repeat(labelWidth - width(label) + 3) + value;
55
- const info = [row('Mode', homeModeLine(installState, statuses, registry)), ''];
56
- const infoTones = [undefined, undefined], notes = new Map();
66
+ const info = [row('Installed on', homeModeLine(installState, statuses, registry)),
67
+ ...settingsRows.map(([label, value]) => row(label, value)), ''];
68
+ const infoTones = info.map(() => undefined), notes = new Map();
57
69
  const humanize = value => value.replace(/\b[a-z]+(?:_[a-z0-9]+)+\b/g, token => REASON_TEXT[token] ?? token.replaceAll('_', ' '));
58
70
  const diagnosticText = value => {
59
71
  const code = value.trim();
package/lib/tui/setup.mjs CHANGED
@@ -12,7 +12,9 @@ import {deriveInstallPlan} from './derive-install-plan.mjs';
12
12
  import {diagramRows} from './diagram.mjs';
13
13
  import {editRole} from './custom-preset.mjs';
14
14
  import {arrowValue,cellWidth,wrapDetailRows} from './render.mjs';
15
- const languageLabel = value => value === 'ko' ? 'KR' : 'EN';
15
+ const runModeName = value => value === 'full-auto' ? 'Full Auto' : 'Supervised';
16
+ const languageName = value => value === 'ko' ? 'Korean' : 'English';
17
+ const fullAutoNotice='Full Auto: ARC auto-approves specs, plans, choices; push/merge/holds ask you.';
16
18
  export function loadRoleDefaults({context,statuses,target,readText=filename=>readFileSync(filename,'utf8')}) {
17
19
  if(!installerRegistryOf(context).isPlatformId(target))throw new ModelValidationError('Unsupported role target');
18
20
  const installed=statuses.find(status=>status.platform===target)?.settings?.modelConfig;
@@ -20,16 +22,20 @@ export function loadRoleDefaults({context,statuses,target,readText=filename=>rea
20
22
  const resolved=resolveModelSettings(config,context);if(resolved.platform!==target)throw new ModelValidationError('Model configuration platform does not match target');
21
23
  return resolved.roles;
22
24
  }
23
- const installSettingKeys=['language','maxTotalSubagents','maxConcurrentSubagents'];
25
+ const installSettingKeys=['runMode','language','maxTotalSubagents','maxConcurrentSubagents'];
24
26
  const installRoleNames=['Scouter','Planner','Implementer','QA','Reviewer'];
25
27
  export function roleDisplayName(role){return installRoleNames[ROLES.indexOf(role)]??role;}
26
28
 
27
29
  export function installSettingsDraft(statuses,platforms){
28
- const values=platforms.map(platform=>{
29
- const settings=statuses.find(status=>status.platform===platform&&status.state==='installed')?.settings;
30
- return {language:settings?.language??'en',maxTotalSubagents:settings?.limits?.max_total_subagents??100,maxConcurrentSubagents:settings?.limits?.max_concurrent_subagents??5};
31
- });
32
- const first=values[0]??{language:'en',maxTotalSubagents:100,maxConcurrentSubagents:5};
30
+ const participatingStatuses=platforms.map(platform=>statuses.find(status=>status.platform===platform))
31
+ .filter(status=>status&&status.state!=='absent');
32
+ const values=participatingStatuses.map(({settings})=>({
33
+ runMode:settings?.runMode??'supervised',
34
+ language:settings?.language??'en',
35
+ maxTotalSubagents:settings?.limits?.max_total_subagents??100,
36
+ maxConcurrentSubagents:settings?.limits?.max_concurrent_subagents??5,
37
+ }));
38
+ const first=values[0]??{runMode:'supervised',language:'en',maxTotalSubagents:100,maxConcurrentSubagents:5};
33
39
  return {...first,mixed:new Set(installSettingKeys.filter(key=>values.some(value=>value[key]!==first[key]))),touched:new Set()};
34
40
  }
35
41
 
@@ -48,26 +54,6 @@ export function installPrepareOptions(plan,draft,catalog){
48
54
  return {kind:'install',target:'composite',platforms:plan.platforms,config,settings};
49
55
  }
50
56
 
51
- export async function editInstallSettings({ui,settings}){
52
- let selected=0;
53
- const display=(key,state)=>settings.mixed.has(key)&&!settings.touched.has(key)?'(mixed)':key==='language'?arrowValue(languageLabel(settings[key]),state.frame,state.selected===0):String(settings[key]);
54
- const rows=(state={})=>['Language '+display('language',state),'Total subagents '+display('maxTotalSubagents',state),'Concurrent subagents '+display('maxConcurrentSubagents',state),'Back'];
55
- const cycleLanguage=()=>{settings.language=settings.language==='ko'?'en':'ko';settings.touched.add('language');};
56
- while(true){
57
- const choice=await ui.menu('Settings',rows(),{selected,onHorizontal:({selected})=>{if(selected===0)cycleLanguage();},renderBody:state=>({rows:rows(state),rowKinds:[undefined,undefined,undefined,'cancel'],selected:state.selected,position:null})});
58
- if(choice===null||choice===3)return;
59
- selected=choice;
60
- if(choice===0){cycleLanguage();continue;}
61
- const key=installSettingKeys[choice];if(!key)continue;
62
- let raw=settings.mixed.has(key)&&!settings.touched.has(key)?'':String(settings[key]);
63
- while(true){
64
- raw=await ui.text(choice===1?'Total subagents':'Concurrent subagents',raw);if(raw===null)break;
65
- let value;try{value=parsePositiveLimit(raw);}catch{await ui.page('Invalid limit',['Enter a positive whole number.']);continue;}
66
- settings[key]=value;settings.touched.add(key);break;
67
- }
68
- }
69
- }
70
-
71
57
  export async function editHosts({ui,hosts,rolePlatforms,availabilityOf,registry=DEFAULT_INSTALLER_REGISTRY}){
72
58
  const ids=registry.byDisplayOrder().map(descriptor=>descriptor.runtime.id),locked=new Set(rolePlatforms),checked=new Set([...hosts,...rolePlatforms]);
73
59
  const labels=ids.map(id=>platformLabel(id,registry)),labelWidths=labels.map(label=>[...label].reduce((width,character)=>width+cellWidth(character),0)),suffixColumn=Math.max(0,...labelWidths)+2;
@@ -149,17 +135,38 @@ export async function runInstallFlow({ui,statuses,draft,installState,currentConf
149
135
  const reason=firstId?`! ${firstRole===undefined?'Hosts':installRoleNames[firstRole]}: ${platformLabel(firstId,registry)} - Unavailable (${REASON_TEXT[gates.get(firstId).reason]})`:null;
150
136
  const warningId=plan.platforms.find(id=>gates.get(id).warning==='auth_unverified');
151
137
  const info=[...(installState.legacyAnchor&&plan.anchorMove?['Mixed routing files will move to the Claude home.']:[]),...(reason?[reason]:warningId?[`${platformLabel(warningId,registry)}: auth unverified`]:[])];
152
- const controls=['Hosts: '+sortByDisplay(draft.hosts,registry).map(id=>platformLabel(id,registry)).join(', '),'Settings',`Apply - ${plan.modeLabel}`,'Back'];
153
- const choice=await ui.menu('Configure',[...installRoleNames,...controls.slice(0,-1)],{
138
+ const hostsRow='Hosts: '+sortByDisplay(draft.hosts,registry).map(id=>platformLabel(id,registry)).join(', ');
139
+ const isMixed=key=>settings.mixed.has(key)&&!settings.touched.has(key);
140
+ const display=(key,name=String,state,index)=>{
141
+ if(isMixed(key))return '(mixed)';
142
+ const label=name(settings[key]);
143
+ return state?arrowValue(label,state.frame,state.selected===index):label;
144
+ };
145
+ const controlsFor=state=>[
146
+ hostsRow,
147
+ 'Run mode '+display('runMode',runModeName,state,6),
148
+ 'Language '+display('language',languageName,state,7),
149
+ 'Total subagents '+display('maxTotalSubagents'),
150
+ 'Concurrent subagents '+display('maxConcurrentSubagents'),
151
+ `Apply - ${plan.modeLabel}`,'Back',
152
+ ];
153
+ const cycleRunMode=()=>{settings.runMode=settings.runMode==='full-auto'?'supervised':'full-auto';settings.touched.add('runMode');};
154
+ const cycleLanguage=()=>{settings.language=settings.language==='ko'?'en':'ko';settings.touched.add('language');};
155
+ const choice=await ui.menu('Configure',[...installRoleNames,...controlsFor().slice(0,-1)],{
154
156
  selected,backRow:true,refreshMs:600,notice:info,
157
+ onHorizontal:({selected})=>{if(selected===6)cycleRunMode();else if(selected===7)cycleLanguage();},
155
158
  renderBody:state=>{
156
- const diagram=diagramRows(roleRows,{...state,selectedRole:state.selected<ROLES.length?state.selected:undefined,blocked,footerRows:wrapDetailRows(info,state.columns).length+controls.length,registry});
159
+ const controls=controlsFor(state);
160
+ const notices=settings.runMode==='full-auto'&&!isMixed('runMode')?[...info,fullAutoNotice]:info;
161
+ const noticeRows=wrapDetailRows(notices,state.columns).length;
162
+ const diagram=diagramRows(roleRows,{...state,selectedRole:state.selected<ROLES.length?state.selected:undefined,blocked,footerRows:noticeRows+controls.length,registry});
157
163
  if(diagram.mode==='guard')return {rows:diagram.rows,notices:[],selected:undefined,position:null};
158
164
  const diagramBody=diagram.mode==='compact'?diagram.rows.slice(0,ROLES.length):diagram.rows;
159
165
  const rows=[...diagramBody,...controls];
160
166
  const selected=state.selected<ROLES.length?(diagram.mode==='compact'?state.selected:state.selected<3?0:8):diagramBody.length+state.selected-ROLES.length;
161
- const capacity=Math.max(1,state.rows-wrapDetailRows(info,state.columns).length-5),offset=Math.max(0,Math.min(selected-capacity+1,rows.length-capacity));
162
- return {rows:rows.slice(offset,offset+capacity),rowKinds:[...diagramBody.map(()=>undefined),undefined,undefined,'confirm','cancel'].slice(offset,offset+capacity),selected:selected-offset,notices:info,showSelection:diagram.mode==='compact'||state.selected>=ROLES.length,position:rows.length>capacity?`${offset+1}-${Math.min(rows.length,offset+capacity)}/${rows.length}`:null};
167
+ const capacity=Math.max(1,state.rows-noticeRows-5),offset=Math.max(0,Math.min(selected-capacity+1,rows.length-capacity));
168
+ const rowKinds=[...diagramBody.map(()=>undefined),...controls.map((_,i)=>i===controls.length-2?'confirm':i===controls.length-1?'cancel':undefined)];
169
+ return {rows:rows.slice(offset,offset+capacity),rowKinds:rowKinds.slice(offset,offset+capacity),selected:selected-offset,notices,showSelection:diagram.mode==='compact'||state.selected>=ROLES.length,position:rows.length>capacity?`${offset+1}-${Math.min(rows.length,offset+capacity)}/${rows.length}`:null};
163
170
  },
164
171
  });
165
172
  if(choice===null)return null;
@@ -173,8 +180,18 @@ export async function runInstallFlow({ui,statuses,draft,installState,currentConf
173
180
  }else if(choice===5){
174
181
  const hosts=await editHosts({ui,hosts:draft.hosts,rolePlatforms:ROLES.map(role=>draft.roles[role].platform),availabilityOf:id=>availabilityOf(id,'host'),registry});
175
182
  if(hosts!==null)draft.hosts=hosts;
176
- }else if(choice===6)await editInstallSettings({ui,settings:draft.settings});
177
- else if(choice===7){
183
+ }else if(choice===6)cycleRunMode();
184
+ else if(choice===7)cycleLanguage();
185
+ else if(choice===8||choice===9){
186
+ const key=choice===8?'maxTotalSubagents':'maxConcurrentSubagents';
187
+ const title=choice===8?'Total subagents':'Concurrent subagents';
188
+ let raw=isMixed(key)?'':String(settings[key]);
189
+ while(true){
190
+ raw=await ui.text(title,raw);if(raw===null)break;
191
+ let value;try{value=parsePositiveLimit(raw);}catch{await ui.page('Invalid limit',['Enter a positive whole number.']);continue;}
192
+ settings[key]=value;settings.touched.add(key);break;
193
+ }
194
+ }else if(choice===10){
178
195
  if(reason)continue;
179
196
  if(plan.rule==='D1-f'){
180
197
  await ui.page('Operation unavailable',[installState.reason??'Mixed routing configuration cannot be verified.',...(installState.residualPaths??[]).map(value=>'Residual path: '+value),'No changes were applied.']);continue;
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@yunhozz/arc",
3
- "version": "0.4.3",
3
+ "version": "0.4.5",
4
4
  "publishConfig": {
5
5
  "access": "public",
6
6
  "registry": "https://registry.npmjs.org/"
@@ -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
+ }
@@ -137,8 +137,8 @@ export const DEFAULT_PLATFORM_REGISTRY = createPlatformRegistry([
137
137
  },
138
138
  executionEnvironments: ['grok-cli'],
139
139
  routing: {validatePair: (model, effort) => validText(model) && /^[A-Za-z0-9][A-Za-z0-9._:/@+\-]*$/.test(model) && effort === 'default'},
140
- capabilities: {install: {state: 'verified'}, nativeProfile: {state: 'verified'}, catalog: {state: 'verified'}, standalone: {state: 'verified'}, bridge: {state: 'verified'}, compositeRole: {state: 'verified'}, ...Object.fromEntries(Object.entries({
141
- compositeHost: 'composite host not verified', authProbe: 'no official auth status command',
140
+ capabilities: {install: {state: 'verified'}, nativeProfile: {state: 'verified'}, catalog: {state: 'verified'}, standalone: {state: 'verified'}, bridge: {state: 'verified'}, compositeRole: {state: 'verified'}, compositeHost: {state: 'verified'}, ...Object.fromEntries(Object.entries({
141
+ authProbe: 'no official auth status command',
142
142
  watch: 'watch support out of scope',
143
143
  }).map(([key, reason]) => [key, {state: 'off', reason}]))},
144
144
  },