@yunhozz/arc 0.5.2 → 0.5.3

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 (35) hide show
  1. package/MANIFEST.sha256 +34 -30
  2. package/README.md +10 -1
  3. package/claude/skill/SKILL.md +1 -1
  4. package/claude/skill/references/coordination.md +6 -0
  5. package/codex/skill/SKILL.md +1 -1
  6. package/codex/skill/references/coordination.md +6 -0
  7. package/gemini/skill/SKILL.md +1 -1
  8. package/gemini/skill/references/coordination.md +6 -0
  9. package/grok/skill/SKILL.md +1 -1
  10. package/grok/skill/references/coordination.md +6 -0
  11. package/lib/installer/runtime-assets.mjs +2 -0
  12. package/lib/runtime/bootstrap.mjs +1 -1
  13. package/lib/runtime/command.mjs +2 -2
  14. package/lib/runtime/host-service.mjs +155 -0
  15. package/lib/runtime/role-bridge-args.mjs +110 -8
  16. package/lib/runtime/role-bridge.mjs +47 -20
  17. package/lib/runtime/role-dispatch-policy.mjs +9 -1
  18. package/lib/runtime/role-dispatch-store.mjs +6 -2
  19. package/lib/runtime/role-observe.mjs +7 -2
  20. package/lib/runtime/role-routing.mjs +13 -1
  21. package/lib/runtime/role-supervisor.mjs +248 -9
  22. package/lib/runtime/tool-access.mjs +560 -0
  23. package/lib/watch/watcher.mjs +46 -25
  24. package/package.json +1 -1
  25. package/shared/skill/runtime/bootstrap.mjs +1 -1
  26. package/shared/skill/runtime/command.mjs +2 -2
  27. package/shared/skill/runtime/host-service.mjs +155 -0
  28. package/shared/skill/runtime/role-bridge-args.mjs +110 -8
  29. package/shared/skill/runtime/role-bridge.mjs +47 -20
  30. package/shared/skill/runtime/role-dispatch-policy.mjs +9 -1
  31. package/shared/skill/runtime/role-dispatch-store.mjs +6 -2
  32. package/shared/skill/runtime/role-observe.mjs +7 -2
  33. package/shared/skill/runtime/role-routing.mjs +13 -1
  34. package/shared/skill/runtime/role-supervisor.mjs +248 -9
  35. package/shared/skill/runtime/tool-access.mjs +560 -0
@@ -0,0 +1,560 @@
1
+ import path from 'node:path';
2
+ import {constants} from 'node:fs';
3
+ import fsp from 'node:fs/promises';
4
+ import {resolveWorktree} from './role-observe.mjs';
5
+ import {hostDirFor, hostServicePreflight} from './host-service.mjs';
6
+
7
+ function deepFreeze(value) {
8
+ for (const child of Object.values(value)) {
9
+ if (child !== null && typeof child === 'object') deepFreeze(child);
10
+ }
11
+ return Object.freeze(value);
12
+ }
13
+
14
+ export const TOOL_ACCESS_KEYS = Object.freeze(['network', 'domains', 'unixSockets', 'paths', 'services', 'envPresets']);
15
+ export const TOOL_ACCESS_SERVICES = Object.freeze([
16
+ 'browser-cdp', 'browser-playwright-chromium', 'browser-playwright-firefox', 'browser-playwright-webkit',
17
+ ]);
18
+ export const ALWAYS_ENV_PRESETS = Object.freeze(['base', 'caches']);
19
+ export const REQUESTABLE_ENV_PRESETS = Object.freeze(['ci', 'daemon-off', 'polling']);
20
+ export const TOOL_PATHS = Object.freeze({});
21
+ export const TOOL_UNIX_SOCKETS = Object.freeze({});
22
+
23
+ export const TOOL_ENV_PRESETS = deepFreeze({
24
+ base: {
25
+ TMPDIR: '<S>/tmp', XDG_CACHE_HOME: '<S>/cache/xdg', GIT_TERMINAL_PROMPT: '0', DO_NOT_TRACK: '1',
26
+ NEXT_TELEMETRY_DISABLED: '1', NPM_CONFIG_UPDATE_NOTIFIER: 'false', HOMEBREW_NO_AUTO_UPDATE: '1',
27
+ HOMEBREW_NO_ANALYTICS: '1', AGENT_BROWSER_NO_VERSION_CHECK: '1', AGENT_BROWSER_SOCKET_DIR: '<S>/sock',
28
+ ARC_SCRATCH_DIR: '<S>', ARC_EVIDENCE_DIR: '<S>/evidence', ARC_HOST_SERVICES_FILE: '<S>/services.json',
29
+ },
30
+ caches: {
31
+ npm_config_cache: '<S>/cache/npm', PYTHONPYCACHEPREFIX: '<S>/cache/pyc', UV_CACHE_DIR: '<S>/cache/uv',
32
+ YARN_CACHE_FOLDER: '<S>/cache/yarn', PIP_CACHE_DIR: '<S>/cache/pip', POETRY_CACHE_DIR: '<S>/cache/poetry',
33
+ GOCACHE: '<S>/cache/go-build', HOMEBREW_CACHE: '<S>/cache/brew',
34
+ },
35
+ ci: {CI: '1', NO_COLOR: '1', PIP_NO_INPUT: '1'},
36
+ 'daemon-off': {NX_DAEMON: 'false', GRADLE_OPTS: '-Dorg.gradle.daemon=false'},
37
+ polling: {
38
+ CHOKIDAR_USEPOLLING: '1', WATCHPACK_POLLING: 'true',
39
+ TSC_WATCHFILE: 'DynamicPriorityPolling', TSC_WATCHDIRECTORY: 'DynamicPriorityPolling',
40
+ },
41
+ });
42
+
43
+ const dir = path => ({path, kind: 'dir'});
44
+ const file = path => ({path, kind: 'file'});
45
+ const externalReads = [
46
+ dir('~/.ssh'), dir('~/.aws'), dir('~/.config/gh'), dir('~/.config/gcloud'), file('~/.npmrc'),
47
+ file('~/.netrc'), dir('~/.docker'), dir('~/.kube'), dir('~/.gnupg'), file('~/.gitconfig'), dir('<cli-homes>'),
48
+ ];
49
+ export const FORBIDDEN = deepFreeze({
50
+ write: [
51
+ dir('<wt>/.git'), dir('<wt>/.codex'), ...externalReads,
52
+ file('~/.zshrc'), file('~/.zprofile'), file('~/.zshenv'), file('~/.bashrc'), file('~/.bash_profile'), file('~/.profile'),
53
+ dir('~/Library/LaunchAgents'), dir('~/Library/Keychains'),
54
+ ],
55
+ sockets: ['/var/run/docker.sock', '~/.docker', '~/.colima', '$SSH_AUTH_SOCK', '~/.gnupg'],
56
+ readWhenExternal: externalReads,
57
+ envWhenExternal: [
58
+ '*TOKEN*', '*SECRET*', '*PASSWORD*', '*PASSWD*', '*API_KEY*', '*ACCESS_KEY*', '*PRIVATE_KEY*', '*CREDENTIAL*',
59
+ 'AWS_*', 'GH_*', 'GITHUB_*', 'SSH_AUTH_SOCK', 'GPG_AGENT_INFO',
60
+ ],
61
+ });
62
+
63
+ export function resolveForbidden({worktree, userHome, homes, env}) {
64
+ const resolvePath = value => {
65
+ if (value.startsWith('<wt>/')) return path.resolve(worktree, value.slice(5));
66
+ if (value.startsWith('~/')) return path.resolve(userHome, value.slice(2));
67
+ return path.resolve(worktree, value);
68
+ };
69
+ const resolveEntries = entries => entries.flatMap(({path, kind}) =>
70
+ (path === '<cli-homes>' ? Object.values(homes) : [path]).map(value => ({path: resolvePath(value), kind})));
71
+ const sockets = FORBIDDEN.sockets.flatMap(value => value === '$SSH_AUTH_SOCK' ? (env?.SSH_AUTH_SOCK ? [env.SSH_AUTH_SOCK] : []) : [value]);
72
+ return {
73
+ write: resolveEntries(FORBIDDEN.write),
74
+ sockets: sockets.map(resolvePath),
75
+ readWhenExternal: resolveEntries(FORBIDDEN.readWhenExternal),
76
+ envWhenExternal: [...FORBIDDEN.envWhenExternal],
77
+ };
78
+ }
79
+
80
+ const writingGates = {
81
+ // Codex 0.170.0 / Claude 2.1.327, 2026-11-24, T0·T0b SX3, SC0·SC2
82
+ scratch: 'pass',
83
+ // Codex 0.170.0 / Claude 2.1.327, 2026-11-24, T0·T0b SX3, SC2, B4
84
+ 'env.base': 'pass',
85
+ 'env.caches': 'pass',
86
+ // Codex 0.170.0 / Claude 2.1.327, 2026-11-24, T0·T0b SX3, SC2, B9 (mechanism only)
87
+ 'env.ci': 'pass',
88
+ 'env.daemon-off': 'pass',
89
+ 'env.polling': 'pass',
90
+ // Codex 0.170.0 / Claude 2.1.327, 2026-11-24, T0·T0b SX1, SC1, B3
91
+ 'network.loopback': 'pass',
92
+ // Codex 0.170.0 / Claude 2.1.327, 2026-11-24, T0·T0b SX4, SC3, B5
93
+ 'unixSockets.scratch': 'pass',
94
+ 'unixSockets.registered': 'pass',
95
+ // Codex 0.170.0 / Claude 2.1.327, 2026-11-24, T0·T0b B13
96
+ paths: 'pass',
97
+ // Codex 0.170.0 / Claude 2.1.327, 2026-11-24, T0·T0b B2, B6, B7
98
+ 'network.domains': 'conditional',
99
+ // Codex 0.170.0 / Claude 2.1.327, 2026-11-24, T0·T0b SX1
100
+ 'network.full': 'held',
101
+ // Chrome 158.0.8127.37, 2026-11-24, MI-A
102
+ 'service.browser-cdp': 'conditional',
103
+ // Chrome 158.0.8127.37, 2026-11-24, MI-B
104
+ 'service.browser-playwright-chromium': 'held',
105
+ 'service.browser-playwright-firefox': 'held',
106
+ 'service.browser-playwright-webkit': 'held',
107
+ };
108
+ const uniformGates = state => Object.fromEntries(Object.keys(writingGates).map(mechanism => [mechanism, state]));
109
+
110
+ const playwrightCondition = 'no host-global Playwright install; isolation unmeasured (MI-B)';
111
+ const browserConditions = {
112
+ 'service.browser-cdp': 'home and ~/Library reads denied (MI-A); files outside home such as /etc remain readable through file://; concurrent loopback dispatches can connect to the unauthenticated CDP port (R-1)',
113
+ 'service.browser-playwright-chromium': playwrightCondition,
114
+ 'service.browser-playwright-firefox': playwrightCondition,
115
+ 'service.browser-playwright-webkit': playwrightCondition,
116
+ };
117
+
118
+ function configHasEntry(config, section, entry) {
119
+ // The installed runtime has no TOML parser. Match both tokens anywhere outside comments.
120
+ const uncommented = config.replace(/("""(?:\\[\s\S]|[^\\])*?"""|'''[\s\S]*?'''|"(?:[^"\\\r\n]|\\.)*"|'[^'\r\n]*')|#[^\r\n]*/g, (_match, quoted) => {
121
+ if (!quoted) return '';
122
+ if (!quoted.startsWith('"')) return quoted;
123
+ return quoted.replace(/\\(?:u([\da-fA-F]{4})|U([\da-fA-F]{8})|.)/g, (escape, short, long) =>
124
+ short || long ? String.fromCodePoint(Number.parseInt(short ?? long, 16)) : escape);
125
+ });
126
+ return section.test(uncommented) && entry.test(uncommented);
127
+ }
128
+
129
+ async function codexUserProfileConflict({grants, worktree, homes, io}) {
130
+ if (!grants.mechanisms.includes('codexProfile')) return null;
131
+ const hold = 'permission_scope_unverified';
132
+ if (typeof worktree !== 'string') return hold;
133
+ try {
134
+ // Prepare receives the caller's cwd, which can be below the worktree root.
135
+ const {realpath} = await resolveWorktree(worktree);
136
+ const configs = [path.join(homes.codex, 'config.toml'), path.join(realpath, '.codex', 'config.toml')];
137
+ for (const filename of configs) {
138
+ let config;
139
+ try { config = await io.readFile(filename, 'utf8'); }
140
+ catch (error) {
141
+ if (error.code === 'ENOENT') continue;
142
+ return hold;
143
+ }
144
+ if (configHasEntry(config, /(?<![\w-])permissions(?![\w-])/, /(?<![\w-])arc_bridge(?![\w-])/)) return hold;
145
+ if (grants.network === 'domains' && configHasEntry(config,
146
+ /(?<![\w-])shell_environment_policy(?![\w-])/, /(?<![\w-])exclude(?![\w-])/)) return hold;
147
+ }
148
+ } catch { return hold; }
149
+ return null;
150
+ }
151
+
152
+ async function claudeAllowWriteDirsExist({grants, io}, {toolPaths = TOOL_PATHS} = {}) {
153
+ const hold = 'permission_scope_unverified';
154
+ for (const id of grants.paths) {
155
+ if (!Object.hasOwn(toolPaths, id)) return hold;
156
+ try {
157
+ if (!(await io.lstat(toolPaths[id])).isDirectory()) return hold;
158
+ } catch { return hold; }
159
+ }
160
+ return null;
161
+ }
162
+
163
+ const noAdapter = {scratchRoot: null, scratchParent: null, extraMechanisms: () => [], preflight: [], conditions: {}};
164
+ const claudeScratchParent = ({uid}) => `/private/tmp/claude-${uid}`;
165
+ export const TOOL_ACCESS_ADAPTERS = deepFreeze({
166
+ codex: {
167
+ ...noAdapter,
168
+ gates: {
169
+ ...writingGates,
170
+ // Codex 0.170.0, 2026-11-24, MI-1, MI-3
171
+ codexProfile: 'conditional',
172
+ // Codex 0.170.0, 2026-11-24, MI-9
173
+ 'network.domains': 'conditional',
174
+ },
175
+ conditions: {
176
+ ...browserConditions,
177
+ codexProfile: 'profile mode requires worktree .git and .codex read entries (verified by MI-1/MI-3)',
178
+ 'network.domains': 'tools that ignore the network proxy (for example npm) fail (B2); external read denials verified by MI-9',
179
+ },
180
+ scratchRoot: ({id8}) => `/private/tmp/arc-bridge-${id8}`,
181
+ extraMechanisms: grants => (grants.network !== null || grants.paths.length || grants.unixSockets.length) ? ['codexProfile'] : [],
182
+ preflight: [codexUserProfileConflict, checkHostServices],
183
+ },
184
+ claude: {
185
+ ...noAdapter,
186
+ gates: {
187
+ ...writingGates,
188
+ // Claude 2.1.327, 2026-11-24, MI-5
189
+ 'network.loopback': 'pass',
190
+ // Claude 2.1.327, 2026-11-24, MI-6
191
+ // Claude 2.1.327, 2026-11-24, MI-7
192
+ // Claude 2.1.327, 2026-11-24, MI-9
193
+ 'network.domains': 'conditional',
194
+ },
195
+ conditions: {
196
+ ...browserConditions,
197
+ 'network.domains': 'tools that ignore the network proxy (for example npm) fail (B2); Read tool denial verified by MI-7, directory denyRead by MI-9',
198
+ },
199
+ scratchRoot: ({id8, uid}) => `${claudeScratchParent({uid})}/arc-bridge-${id8}`,
200
+ scratchParent: claudeScratchParent,
201
+ preflight: [claudeAllowWriteDirsExist, checkHostServices],
202
+ },
203
+ grok: {...noAdapter, gates: uniformGates('unmeasured')},
204
+ gemini: {...noAdapter, gates: uniformGates('held')},
205
+ });
206
+
207
+ function checkHostServices({grants, io}) {
208
+ return hostServicePreflight({services: grants.services ?? [], io});
209
+ }
210
+
211
+ function mechanismView(field) {
212
+ const view = {};
213
+ for (const [platform, adapter] of Object.entries(TOOL_ACCESS_ADAPTERS)) {
214
+ for (const [mechanism, value] of Object.entries(adapter[field])) {
215
+ (view[mechanism] ??= {})[platform] = value;
216
+ }
217
+ }
218
+ return deepFreeze(view);
219
+ }
220
+
221
+ export const TOOL_ACCESS_GATES = mechanismView('gates');
222
+ export const TOOL_ACCESS_CONDITIONS = mechanismView('conditions');
223
+
224
+ function gateFor(mechanism, platform, overrides) {
225
+ return overrides == null ? TOOL_ACCESS_ADAPTERS[platform]?.gates?.[mechanism] : overrides[mechanism]?.[platform];
226
+ }
227
+
228
+ const domainPattern = /^(?=.{1,253}$)(?:[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?\.)+(?:[a-z]{2,63}|xn--[a-z0-9-]{1,59})$/;
229
+ const internalDomain = /\.(?:localhost|local|internal|home\.arpa)$/;
230
+ export const isValidDomain = name => typeof name === 'string' && domainPattern.test(name) && !internalDomain.test(name);
231
+
232
+ const roleAccess = deepFreeze({
233
+ arc_implementer: {networks: [null, 'loopback'], services: []},
234
+ arc_tester: {networks: [null, 'loopback', 'domains', 'full'], services: TOOL_ACCESS_SERVICES},
235
+ });
236
+ const arrayKeys = TOOL_ACCESS_KEYS.slice(1);
237
+
238
+ export function validateToolAccess(role, value) {
239
+ if (!Object.hasOwn(roleAccess, role) || !value || typeof value !== 'object' || Array.isArray(value)
240
+ || Object.keys(value).length !== TOOL_ACCESS_KEYS.length || !TOOL_ACCESS_KEYS.every(key => Object.hasOwn(value, key))) return null;
241
+ const allowed = roleAccess[role];
242
+ if (!allowed.networks.includes(value.network)) return null;
243
+ const normalized = {network: value.network};
244
+ for (const key of arrayKeys) {
245
+ if (!Array.isArray(value[key])) return null;
246
+ const items = [...value[key]];
247
+ if (items.some(item => typeof item !== 'string') || new Set(items).size !== items.length) return null;
248
+ normalized[key] = items.sort();
249
+ }
250
+ const {network, domains, unixSockets, paths, services, envPresets} = normalized;
251
+ if (network === 'domains' ? domains.length < 1 || domains.length > 16 || !domains.every(isValidDomain) : domains.length !== 0) return null;
252
+ if (!unixSockets.every(id => Object.hasOwn(TOOL_UNIX_SOCKETS, id)) || !paths.every(id => Object.hasOwn(TOOL_PATHS, id))
253
+ || !services.every(id => allowed.services.includes(id)) || !envPresets.every(id => REQUESTABLE_ENV_PRESETS.includes(id))) return null;
254
+ return normalized;
255
+ }
256
+
257
+ const alwaysMechanisms = ['scratch', ...ALWAYS_ENV_PRESETS.map(id => `env.${id}`)];
258
+ const networkMechanisms = {loopback: ['network.loopback'], domains: ['network.loopback', 'network.domains'], full: ['network.full']};
259
+
260
+ export function effectiveGrants(platform, role, toolAccess) {
261
+ if (!Object.hasOwn(roleAccess, role)) return null;
262
+ if (toolAccess === null && !alwaysMechanisms.every(id => gateFor(id, platform) === 'pass')) return null;
263
+ const access = toolAccess ?? {network: null, domains: [], unixSockets: [], paths: [], services: [], envPresets: []};
264
+ const network = access.network ?? (access.services.length ? 'loopback' : null);
265
+ const grants = {...access, network, envPresets: [...ALWAYS_ENV_PRESETS, ...access.envPresets]};
266
+ const mechanisms = [
267
+ ...alwaysMechanisms,
268
+ ...access.envPresets.map(id => `env.${id}`),
269
+ ...(TOOL_ACCESS_ADAPTERS[platform]?.extraMechanisms?.(grants) ?? []),
270
+ ...(networkMechanisms[network] ?? []),
271
+ ];
272
+ if (network !== null) mechanisms.push('unixSockets.scratch');
273
+ if (access.unixSockets.length) mechanisms.push('unixSockets.registered');
274
+ if (access.paths.length) mechanisms.push('paths');
275
+ mechanisms.push(...access.services.map(id => `service.${id}`));
276
+ return {...grants, mechanisms: [...new Set(mechanisms)]};
277
+ }
278
+
279
+ export function toolAccessReasons({platform, role, route, toolAccess, policy}) {
280
+ if (toolAccess === undefined) return {reasons: [], conditions: []};
281
+ const normalized = validateToolAccess(role, toolAccess);
282
+ if (normalized === null) return {reasons: ['invalid_request'], conditions: []};
283
+ if (route === 'native') return {reasons: ['permission_scope_unverified'], conditions: []};
284
+ const {mechanisms} = effectiveGrants(platform, role, normalized);
285
+ const conditions = [];
286
+ for (const mechanism of mechanisms) {
287
+ const gate = gateFor(mechanism, platform, policy?.toolAccessGates);
288
+ if (gate === 'conditional') conditions.push({mechanism, condition: TOOL_ACCESS_ADAPTERS[platform]?.conditions?.[mechanism] ?? ''});
289
+ else if (gate !== 'pass') return {reasons: ['permission_scope_unverified'], conditions: []};
290
+ }
291
+ return {reasons: [], conditions};
292
+ }
293
+
294
+ export async function toolAccessPreflight(context, options) {
295
+ for (const check of TOOL_ACCESS_ADAPTERS[context.platform]?.preflight ?? []) {
296
+ const reason = await check(context, options);
297
+ if (reason !== null) return [reason];
298
+ }
299
+ return [];
300
+ }
301
+
302
+ export const EVIDENCE_LIMITS = Object.freeze({totalBytes: 67108864, fileBytes: 16777216, entries: 256, depth: 8});
303
+
304
+ export function renderEnv(presetIds, scratch) {
305
+ const values = new Map();
306
+ for (const id of presetIds) {
307
+ for (const [key, value] of Object.entries(TOOL_ENV_PRESETS[id])) {
308
+ if (values.has(key)) throw Error(`Duplicate tool environment key: ${key}`);
309
+ values.set(key, value.replaceAll('<S>', () => scratch));
310
+ }
311
+ }
312
+ return [...values.keys()].sort().map(key => [key, values.get(key)]);
313
+ }
314
+
315
+ export function buildToolContext({platform, role, dispatchId, toolAccess, uid, userHome, homes, env, envNames = [], worktree, gitDir, gitCommonDir, policy}) {
316
+ const grants = effectiveGrants(platform, role, toolAccess ?? null);
317
+ if (grants === null) return null;
318
+ const adapter = TOOL_ACCESS_ADAPTERS[platform];
319
+ const scratch = adapter.scratchRoot({id8: dispatchId.replaceAll('-', '').slice(0, 8), uid});
320
+ const forbidden = resolveForbidden({worktree, userHome, homes, env});
321
+ const hostDir = grants.services.length ? hostDirFor(dispatchId) : null;
322
+ if (hostDir && forbidden.write.some(({path: filename}) => containsPath(filename, hostDir) || containsPath(hostDir, filename))) {
323
+ throw Object.assign(Error('Host service directory overlaps a protected path'), {reasonCode: 'permission_scope_unverified'});
324
+ }
325
+ const {conditions} = toolAccessReasons({platform, role, route: 'bridge', toolAccess, policy});
326
+ const secretPatterns = grants.network === 'domains' ? forbidden.envWhenExternal.map(glob => new RegExp(`^${glob.replaceAll('*', '.*')}$`)) : [];
327
+ return {
328
+ scratch, parent: adapter.scratchParent?.({uid}) ?? null, env: renderEnv(grants.envPresets, scratch), grants, forbidden,
329
+ secretEnvNames: envNames.filter(name => secretPatterns.some(pattern => pattern.test(name))).sort(),
330
+ hostDir, worktree, gitDir, gitCommonDir, conditions,
331
+ };
332
+ }
333
+
334
+ function containsPath(parent, child) {
335
+ const relative = path.relative(parent, child);
336
+ return relative !== '..' && !relative.startsWith('..' + path.sep) && !path.isAbsolute(relative);
337
+ }
338
+
339
+ async function lstatIfPresent(filename) {
340
+ try { return await fsp.lstat(filename); } catch (error) {
341
+ if (error.code !== 'ENOENT') throw error;
342
+ return null;
343
+ }
344
+ }
345
+
346
+ export async function createScratch({scratch, parent, uid, artifactDir = path.dirname(scratch), fallbackDir, quarantineKey}) {
347
+ let identity;
348
+ try {
349
+ if (parent) {
350
+ let madeParent = false;
351
+ try { await fsp.mkdir(parent, {mode: 0o700}); madeParent = true; } catch (error) {
352
+ if (error.code !== 'EEXIST') throw error;
353
+ }
354
+ const stat = await fsp.lstat(parent);
355
+ if (!stat.isDirectory() || stat.uid !== uid) {
356
+ throw Object.assign(Error('Scratch parent must be an owned directory'), {reasonCode: 'permission_scope_unverified'});
357
+ }
358
+ if (madeParent) await fsp.chmod(parent, 0o700);
359
+ }
360
+ await fsp.mkdir(scratch, {mode: 0o700});
361
+ const stat = await fsp.lstat(scratch);
362
+ if (!stat.isDirectory() || stat.uid !== uid) throw Error('Scratch directory changed during creation');
363
+ identity = {dev: stat.dev, ino: stat.ino};
364
+ await fsp.chmod(scratch, 0o700);
365
+ for (const name of ['tmp', 'cache', 'sock', 'evidence']) {
366
+ const directory = path.join(scratch, name);
367
+ await fsp.mkdir(directory, {mode: 0o700});
368
+ await fsp.chmod(directory, 0o700);
369
+ }
370
+ return identity;
371
+ } catch (error) {
372
+ if (identity) await removeScratch(scratch, {identity, artifactDir, fallbackDir, quarantineKey});
373
+ throw Object.assign(error, {reasonCode: error.reasonCode ?? 'execution_failed'});
374
+ }
375
+ }
376
+
377
+ function verifyQuarantineRoot(stat) {
378
+ if (!stat?.isDirectory() || stat.uid !== process.geteuid()) throw Error('Unverified quarantine root');
379
+ }
380
+
381
+ async function hasRetainedQuarantine(root, prefix) {
382
+ const stat = await lstatIfPresent(root);
383
+ if (!stat) return false;
384
+ verifyQuarantineRoot(stat);
385
+ return (await fsp.readdir(root)).some(name => name.startsWith(prefix));
386
+ }
387
+
388
+ const quarantinePrefix = (source, key) => key ? `.cleanup-${key}-${path.basename(source)}-` : '.cleanup-';
389
+
390
+ export async function hasRetainedCleanup(source, {artifactDir, fallbackDir, quarantineKey}) {
391
+ const prefix = quarantinePrefix(source, quarantineKey);
392
+ return await hasRetainedQuarantine(artifactDir, prefix)
393
+ || Boolean(fallbackDir && await hasRetainedQuarantine(fallbackDir, prefix));
394
+ }
395
+
396
+ async function quarantineAndRemove(source, identity, root, prefix) {
397
+ if (containsPath(source, root) || !ownedDirectory(await lstatIfPresent(source), identity)) return false;
398
+ verifyQuarantineRoot(await fsp.lstat(root));
399
+ const quarantine = await fsp.mkdtemp(path.join(root, prefix));
400
+ try {
401
+ const moved = path.join(quarantine, 'tree');
402
+ try { await fsp.rename(source, moved); }
403
+ catch (error) {
404
+ if (error.code === 'EXDEV') return 'cross-device';
405
+ throw error;
406
+ }
407
+ if (!ownedDirectory(await fsp.lstat(moved), identity)) return false;
408
+ await fsp.rm(moved, {recursive: true, force: false});
409
+ return true;
410
+ } finally {
411
+ // A moved directory which failed verification stays in the protected quarantine.
412
+ await fsp.rmdir(quarantine).catch(() => {});
413
+ }
414
+ }
415
+
416
+ export async function removeScratch(scratch, options) {
417
+ const {artifactDir = path.dirname(scratch), fallbackDir, quarantineKey, missingOk = false} = options ?? {};
418
+ const prefix = quarantinePrefix(scratch, quarantineKey);
419
+ try {
420
+ const source = await lstatIfPresent(scratch);
421
+ if (missingOk && await hasRetainedCleanup(scratch, {artifactDir, fallbackDir, quarantineKey})) return false;
422
+ if (!source) return missingOk;
423
+ const identity = options ? options.identity : source;
424
+ const removed = await quarantineAndRemove(scratch, identity, artifactDir, prefix);
425
+ if (removed === 'cross-device' && fallbackDir) {
426
+ return await quarantineAndRemove(scratch, identity, fallbackDir, prefix) === true;
427
+ }
428
+ return removed === true;
429
+ } catch {
430
+ return false;
431
+ }
432
+ }
433
+
434
+ const sameEntry = (a, b) => a && a.dev === b.dev && a.ino === b.ino;
435
+ const sameVersion = (a, b) => sameEntry(a, b) && a.size === b.size && a.mtimeMs === b.mtimeMs && a.ctimeMs === b.ctimeMs;
436
+ const ownedDirectory = (stat, identity) => stat?.isDirectory() && stat.uid === process.geteuid() && identity && sameEntry(stat, identity);
437
+
438
+ async function readEvidenceFile(filename, stat, maxBytes, parentIntact) {
439
+ const source = await fsp.open(filename, constants.O_RDONLY | constants.O_NOFOLLOW | constants.O_NONBLOCK);
440
+ try {
441
+ const current = await source.stat();
442
+ if (!current.isFile() || !sameEntry(current, stat) || !await parentIntact()) return {skipped: true};
443
+ if (current.size > maxBytes) return {truncated: true};
444
+ // Read at most one extra byte so a file that grows during collection cannot bypass the limits.
445
+ const buffer = Buffer.alloc(current.size + 1);
446
+ let length = 0;
447
+ while (length < buffer.length) {
448
+ const {bytesRead} = await source.read(buffer, length, buffer.length - length, length);
449
+ if (bytesRead === 0) break;
450
+ length += bytesRead;
451
+ }
452
+ if (length > current.size) return {truncated: true};
453
+ return {bytes: buffer.subarray(0, length)};
454
+ } finally {
455
+ await source.close();
456
+ }
457
+ }
458
+
459
+ export async function collectEvidence({scratch, artifactDir, limits = EVIDENCE_LIMITS, identity, recovery = false}) {
460
+ const result = {copied: 0, skipped: [], truncated: false};
461
+ const skip = (relative, truncated = false) => {
462
+ if (result.skipped.length < EVIDENCE_LIMITS.entries) result.skipped.push(relative);
463
+ if (truncated) result.truncated = true;
464
+ };
465
+ const sourceRoot = path.join(scratch, 'evidence');
466
+ const scratchStat = await lstatIfPresent(scratch);
467
+ if (identity && scratchStat && !ownedDirectory(scratchStat, identity)) throw Error('Scratch directory changed before evidence collection');
468
+ if (!scratchStat?.isDirectory()) return result;
469
+ const sourceStat = await lstatIfPresent(sourceRoot);
470
+ if (!sourceStat) return result;
471
+ if (!sourceStat.isDirectory()) { skip('.'); return result; }
472
+ if (!(await fsp.lstat(artifactDir)).isDirectory()) throw Error('Evidence artifact directory is not a directory');
473
+ let destinationRoot = path.join(artifactDir, 'evidence');
474
+ let verifyExisting = false;
475
+ const unverified = () => Error('Existing recovery evidence could not be verified');
476
+ const verifyDirectory = async filename => {
477
+ const stat = await lstatIfPresent(filename);
478
+ if (!stat?.isDirectory() || stat.uid !== process.geteuid()) throw unverified();
479
+ };
480
+ const makeDirectory = async filename => {
481
+ await fsp.mkdir(filename, {mode: 0o700});
482
+ await fsp.chmod(filename, 0o700);
483
+ };
484
+ if (recovery) {
485
+ const copies = (await fsp.readdir(artifactDir)).filter(name => name.startsWith('evidence-recovery-'));
486
+ if (copies.length > 1) throw unverified();
487
+ if (copies.length === 1) {
488
+ destinationRoot = path.join(artifactDir, copies[0]);
489
+ verifyExisting = true;
490
+ }
491
+ }
492
+ if (!verifyExisting) {
493
+ try { await makeDirectory(destinationRoot); }
494
+ catch (error) {
495
+ if (!recovery || error.code !== 'EEXIST') throw error;
496
+ // An exclusive fixed name also prevents concurrent recovery from creating extra copies.
497
+ destinationRoot = path.join(artifactDir, 'evidence-recovery-1');
498
+ try { await makeDirectory(destinationRoot); }
499
+ catch (error) {
500
+ if (error.code !== 'EEXIST') throw error;
501
+ verifyExisting = true;
502
+ }
503
+ }
504
+ }
505
+ if (verifyExisting) await verifyDirectory(destinationRoot);
506
+ const compareSource = verifyExisting ? sameVersion : sameEntry;
507
+ let visited = 0, totalBytes = 0;
508
+ const walk = async (directory, stat, parentIntact, depth) => {
509
+ const intact = async () => {
510
+ const matches = await parentIntact() && compareSource(await lstatIfPresent(directory), stat);
511
+ if (verifyExisting && !matches) throw unverified();
512
+ return matches;
513
+ };
514
+ if (!await intact()) return;
515
+ const names = (await fsp.readdir(directory)).sort();
516
+ if (!await intact()) return;
517
+ for (const name of names) {
518
+ if (!await intact()) return;
519
+ const source = path.join(directory, name);
520
+ const relative = path.relative(sourceRoot, source);
521
+ const destination = path.join(destinationRoot, relative);
522
+ if (path.relative(destinationRoot, destination).startsWith('..')) { skip(relative); continue; }
523
+ if (visited >= limits.entries) { skip(relative, true); return; }
524
+ visited++;
525
+ if (depth > limits.depth) { skip(relative, true); return; }
526
+ const entry = await lstatIfPresent(source);
527
+ if (entry?.isDirectory()) {
528
+ await (verifyExisting ? verifyDirectory(destination) : makeDirectory(destination));
529
+ await walk(source, entry, intact, depth + 1);
530
+ if (result.truncated) return;
531
+ } else if (entry?.isFile()) {
532
+ const maxBytes = Math.min(limits.fileBytes, limits.totalBytes - totalBytes);
533
+ if (entry.size > maxBytes) { skip(relative, true); return; }
534
+ const {bytes, truncated} = await readEvidenceFile(source, entry, maxBytes, intact);
535
+ if (truncated) { skip(relative, true); return; }
536
+ if (!bytes) { skip(relative); continue; }
537
+ if (verifyExisting) {
538
+ const copy = await lstatIfPresent(destination);
539
+ if (!copy?.isFile() || copy.uid !== process.geteuid() || copy.size !== bytes.length) throw unverified();
540
+ const {bytes: copied} = await readEvidenceFile(destination, copy, bytes.length, intact);
541
+ if (!copied?.equals(bytes) || !sameVersion(await lstatIfPresent(source), entry)) throw unverified();
542
+ } else {
543
+ const output = await fsp.open(destination, 'wx', 0o600);
544
+ try {
545
+ await output.writeFile(bytes);
546
+ await output.chmod(0o600);
547
+ } finally { await output.close(); }
548
+ }
549
+ totalBytes += bytes.length;
550
+ result.copied++;
551
+ } else {
552
+ skip(relative);
553
+ }
554
+ }
555
+ if (verifyExisting) await intact();
556
+ };
557
+ await walk(sourceRoot, sourceStat, async () => sameEntry(await lstatIfPresent(scratch), scratchStat), 1);
558
+ if (verifyExisting && (result.truncated || result.skipped.length)) throw unverified();
559
+ return result;
560
+ }