@tnunamak/dalan 0.8.1 → 0.8.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 (124) hide show
  1. package/CHANGELOG.md +61 -2
  2. package/CONTRIBUTING.md +2 -0
  3. package/README.md +8 -12
  4. package/bin/dalan.mjs +25 -4
  5. package/bin/dot-acp-agent.mjs +572 -76
  6. package/bin/dot-alert.mjs +9 -3
  7. package/bin/dot-deadman.mjs +3 -1
  8. package/bin/dot-heartbeat.mjs +14 -7
  9. package/bin/dot-pr-reviewer.mjs +3 -31
  10. package/bin/dot-worker.mjs +121 -34
  11. package/contracts/adapter-qualification.schema.json +94 -7
  12. package/docs/chatgpt-worker-onboarding.md +1 -1
  13. package/docs/codex-to-muse.md +2 -2
  14. package/docs/connect-chatgpt.md +1 -1
  15. package/docs/connection-longevity.md +2 -2
  16. package/docs/dalan-upgrade.md +8 -5
  17. package/docs/deadman.md +4 -0
  18. package/docs/design/authority-matrix.md +18 -0
  19. package/docs/design/failure-table.md +87 -0
  20. package/docs/design/identities.md +22 -0
  21. package/docs/design/pnpm-prepared-dependencies.md +64 -0
  22. package/docs/design/reuse-ledger.md +75 -0
  23. package/docs/design/target-architecture-v2.md +434 -0
  24. package/docs/local-agent-mcp.md +14 -0
  25. package/docs/local-agent-requester.md +2 -1
  26. package/docs/manual-setup.md +1 -1
  27. package/docs/operations.md +77 -14
  28. package/docs/pull-workers.md +11 -1
  29. package/docs/service-setup.md +10 -10
  30. package/docs/t3-integration.md +4 -2
  31. package/docs/t3-reverse-control.md +5 -5
  32. package/docs/test-suite-isolation.md +7 -6
  33. package/docs/trials/chatgpt-agent.md +47 -0
  34. package/docs/trials/claude-code-requester.md +68 -0
  35. package/docs/trials/muse.md +46 -0
  36. package/docs/usage.md +21 -7
  37. package/docs/worker-clients.md +1 -1
  38. package/integrations/t3/acp-kit/src/errors.mjs +6 -2
  39. package/integrations/t3/acp-kit/src/lock.mjs +46 -17
  40. package/integrations/t3/acp-kit/src/session-store.mjs +15 -3
  41. package/integrations/t3/acp-kit/src/t3-envelope.mjs +10 -2
  42. package/package.json +4 -3
  43. package/packages/job-core/protocol/canonical.mjs +45 -7
  44. package/packages/job-core/transitions.mjs +4 -2
  45. package/scripts/upgrade-drain.mjs +96 -8
  46. package/scripts/worker-bridge-setup.mjs +215 -120
  47. package/src/ack-ledger.mjs +7 -1
  48. package/src/acp-bridge.mjs +256 -28
  49. package/src/admin-socket.mjs +32 -3
  50. package/src/alerts.mjs +17 -8
  51. package/src/answer-journal-retention.mjs +82 -0
  52. package/src/answer-journal.mjs +6 -4
  53. package/src/as-store.mjs +51 -6
  54. package/src/as.mjs +27 -5
  55. package/src/catalog-switch-inventory.mjs +70 -0
  56. package/src/check-response.mjs +4 -1
  57. package/src/cli-help.mjs +14 -3
  58. package/src/cli-name.mjs +13 -1
  59. package/src/connect-cli.mjs +159 -4
  60. package/src/deadman.mjs +8 -5
  61. package/src/delivery.mjs +2 -19
  62. package/src/destinations/index.mjs +75 -14
  63. package/src/drain-runner.mjs +5 -1
  64. package/src/follow-current.mjs +3 -1
  65. package/src/get-summary.mjs +11 -2
  66. package/src/git-env.mjs +1 -1
  67. package/src/gozar-routes.mjs +313 -94
  68. package/src/host-budget-storage.py +56 -6
  69. package/src/host-budget.mjs +98 -15
  70. package/src/host-execution-policy.mjs +17 -6
  71. package/src/legacy-names.mjs +0 -2
  72. package/src/lifecycle.mjs +44 -9
  73. package/src/loopback-probe.mjs +46 -0
  74. package/src/mcp-outcome.mjs +3 -1
  75. package/src/mcp-sse.mjs +2 -1
  76. package/src/mcp-stdio.mjs +192 -30
  77. package/src/patch-apply.mjs +212 -7
  78. package/src/phase-trace.mjs +73 -0
  79. package/src/prepared-go-modules.mjs +127 -0
  80. package/src/prepared-node-modules.mjs +225 -38
  81. package/src/prepared-pnpm.mjs +276 -0
  82. package/src/prepared-store-prune.mjs +52 -0
  83. package/src/projects.mjs +59 -7
  84. package/src/protocol-artifact-commands.mjs +28 -0
  85. package/src/protocol-finish.mjs +3 -2
  86. package/src/publication-authority.mjs +22 -0
  87. package/src/publish-plan.mjs +2 -2
  88. package/src/pull-queue.mjs +55 -20
  89. package/src/read-api.mjs +127 -0
  90. package/src/redaction.mjs +173 -0
  91. package/src/rejections.mjs +19 -3
  92. package/src/route-custody.mjs +90 -0
  93. package/src/route-publication.mjs +50 -0
  94. package/src/route-setup.mjs +184 -0
  95. package/src/schema-subset.mjs +5 -3
  96. package/src/server.mjs +503 -98
  97. package/src/service-launchd.mjs +5 -1
  98. package/src/service-update-lock.mjs +7 -4
  99. package/src/service-update-runtime.mjs +136 -21
  100. package/src/service-update.mjs +207 -51
  101. package/src/service.mjs +276 -77
  102. package/src/setup.mjs +48 -25
  103. package/src/signal.mjs +1 -1
  104. package/src/status-evidence.mjs +18 -5
  105. package/src/store.mjs +876 -120
  106. package/src/submission-policy.mjs +257 -56
  107. package/src/t3-control.mjs +1 -1
  108. package/src/t3.mjs +14 -8
  109. package/src/terminal-safe.mjs +9 -7
  110. package/src/tool-registry.mjs +134 -41
  111. package/src/try-exposure.mjs +53 -86
  112. package/src/try-hosted.mjs +257 -70
  113. package/src/try.mjs +48 -22
  114. package/src/work-order.mjs +11 -6
  115. package/src/worker-instructions.mjs +26 -4
  116. package/src/worker-runs.mjs +35 -0
  117. package/src/workers.mjs +34 -7
  118. package/src/workspace.mjs +354 -54
  119. package/systemd/dot-deadman.service +3 -1
  120. package/docs/dot-pr-reviewer.config.example.json +0 -9
  121. package/docs/pr-head-reviewer.md +0 -70
  122. package/src/pr-head-reviewer.mjs +0 -596
  123. package/systemd/dot-pr-reviewer.service +0 -11
  124. package/systemd/dot-pr-reviewer.timer +0 -10
@@ -0,0 +1,73 @@
1
+ // Where the time between "queued" and "claimed" goes, one log line per step (no schema, no behavior change):
2
+ // wake_delivery each wake webhook: queued-to-attempt time and how long the receiver took to answer
3
+ // claim_phase each new claim: the timestamps and gaps from submit to wake, wake to first listing, listing to claim
4
+ // claim_first_action the holder's first call on a fresh claim after the claim itself
5
+ // claim_silence the holder's next call after at least SILENCE_MS without one, and (final:true) its finish, whatever the gap
6
+ // Fresh claims and finish handoffs are told apart by `handoff`: a handoff claim has no wake and no listing of its own.
7
+ // Remembered state is in memory and bounded; a restart forgets it, and the lines then carry nulls, never wrong numbers.
8
+ export const SILENCE_MS=120000;
9
+ const iso=ms=>new Date(ms).toISOString();
10
+ const gap=(from,to)=>from==null||to==null?null:Math.round(to-from);
11
+ export function createPhaseTrace({log:write,now=Date.now,max=5000}) {
12
+ // Telemetry only: a failing log write (full disk, missing directory) must never change a tool result or a wake delivery.
13
+ const log=entry=>{try{write(entry);}catch{}};
14
+ const listed=new Map(),woke=new Map(),fresh=new Map(),active=new Map();
15
+ const remember=(map,key,value)=>{map.set(key,value);while(map.size>max)map.delete(map.keys().next().value);};
16
+ // Measurement only: how long a claim goes quiet between the holder's calls. A claim that ends by cancel or lease expiry
17
+ // makes no call, so its last silence is read offline from the last mcp_outcome line against claim_phase.
18
+ const silence=({requestId,tool,subject})=>{
19
+ const claim=active.get(requestId);
20
+ if(!claim||claim.subject!==subject) return;
21
+ const at=now(),silent=at-claim.last,final=tool==='finish';
22
+ if(silent>=SILENCE_MS||final) log({kind:'claim_silence',request_id:requestId,claim_id:claim.claimId,tool,silence_ms:Math.round(silent),
23
+ since:claim.calls?'previous_call':'claim',final,calls_before:claim.calls,claim_age_ms:Math.round(at-claim.claimedAt)});
24
+ if(final) active.delete(requestId);
25
+ else { claim.last=at;claim.calls++; }
26
+ };
27
+ return {
28
+ // A list_pending call showed these rows: keep the first time each one was seen.
29
+ listed(requestIds) {
30
+ const at=now();
31
+ for(const id of requestIds) if(!listed.has(id)) remember(listed,id,at);
32
+ },
33
+ // One wake webhook attempt. `attemptAt` is when the send began; `ackMs` is how long the receiver took to answer (null on a transport error).
34
+ wake({item,worker,attemptAt,ackMs,status,state}) {
35
+ const created=Date.parse(item.created_at);
36
+ log({kind:'wake_delivery',event_id:item.id,request_id:item.request_id??null,worker,wake_kind:item.wake_kind??null,state,http_status:status??null,
37
+ enqueued_at:item.created_at,attempt_at:iso(attemptAt),queued_to_attempt_ms:gap(created,attemptAt),ack_ms:ackMs==null?null:Math.round(ackMs)});
38
+ if(item.request_id&&state==='delivered'&&!woke.has(item.request_id)) remember(woke,item.request_id,{attemptAt,ackAt:ackMs==null?null:attemptAt+ackMs});
39
+ },
40
+ // A new claim was granted. `createdAt` is the assignment's submit time.
41
+ claimed({requestId,worker,subject,claimId,handoff,createdAt}) {
42
+ // A handoff claim has no wake and no listing of its own: whatever an earlier failed or lapsed attempt left behind is not its timing.
43
+ const at=now(),seen=handoff?null:listed.get(requestId)??null,wake=handoff?null:woke.get(requestId)??null,created=Date.parse(createdAt);
44
+ listed.delete(requestId);woke.delete(requestId);
45
+ // Send, answer and listing are separate stamps. A row listed before the answer came back (or before the send) has no known order: null, never a negative gap.
46
+ const wakeToListed=wake&&wake.ackAt!=null&&seen!=null&&seen>=wake.ackAt?gap(wake.ackAt,seen):null;
47
+ remember(fresh,requestId,{claimId,subject,at,handoff});
48
+ remember(active,requestId,{claimId,subject,claimedAt:at,last:at,calls:0});
49
+ log({kind:'claim_phase',request_id:requestId,worker,claim_id:claimId,handoff,created_at:createdAt,
50
+ wake_attempt_at:wake?iso(wake.attemptAt):null,first_listed_at:seen==null?null:iso(seen),claimed_at:iso(at),
51
+ submit_to_wake_ms:gap(created,wake?.attemptAt),wake_ack_ms:wake&&wake.ackAt!=null?Math.round(wake.ackAt-wake.attemptAt):null,
52
+ wake_to_listed_ms:wakeToListed,listed_to_claim_ms:gap(seen,at),submit_to_claim_ms:gap(created,at)});
53
+ },
54
+ // The server provides a snapshot taken before the successful progress write.
55
+ progress({requestId,claimId,claimedAt,first,note}) {
56
+ if(!first) return;
57
+ const stamp=/^dispatched_at=(\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}Z)(?=\s|$)/.exec(note)?.[1];
58
+ const sent=Date.parse(stamp), claimed=Date.parse(claimedAt);
59
+ if(!Number.isFinite(sent)||iso(sent)!==stamp.replace('Z','.000Z')) return;
60
+ const known=Number.isFinite(claimed);
61
+ log({kind:'claim_dispatch',source:'worker_note',request_id:requestId,claim_id:claimId,dispatched_at:stamp,
62
+ claimed_at:known?claimedAt:null,gap_ms:known&&claimed>=sent?gap(sent,claimed):null});
63
+ },
64
+ // Any worker call that names a request. The first one by the claimant after a fresh claim is the first action.
65
+ action({requestId,tool,subject}) {
66
+ silence({requestId,tool,subject});
67
+ const claim=fresh.get(requestId);
68
+ if(!claim||claim.subject!==subject) return;
69
+ fresh.delete(requestId);
70
+ log({kind:'claim_first_action',request_id:requestId,claim_id:claim.claimId,tool,handoff:claim.handoff,after_claim_ms:gap(claim.at,now())});
71
+ },
72
+ };
73
+ }
@@ -0,0 +1,127 @@
1
+ import { defaultPath } from './paths.mjs';
2
+ import fs from 'node:fs';
3
+ import os from 'node:os';
4
+ import path from 'node:path';
5
+ import { randomUUID } from 'node:crypto';
6
+ import { spawnSync } from 'node:child_process';
7
+ import { pruneNodeStore } from './prepared-store-prune.mjs';
8
+ import { hash, failure, markUsed, readRegular, checkDirectory, checkParents, validateTree, freezeTree, thawTree, shellQuote, prepareInChild } from './prepared-node-modules.mjs';
9
+
10
+ // A Go repository's dependencies and its pinned toolchain live in one module cache, prepared on the host (with network)
11
+ // from go.mod and go.sum alone, then mounted read-only at the sandbox's GOMODCACHE. The sandbox has no network, so the cache
12
+ // is the only way a check can get the Go toolchain a go.mod asks for (`go 1.26.0` switches to golang.org/toolchain in this cache)
13
+ // and the modules it imports. Same trust rule as prepared node_modules: the key is the file hashes, never the worker's edits.
14
+ const GO = '/usr/bin/go';
15
+ const store = options => path.resolve(options.cacheDir ?? defaultPath(os.homedir(), '.dot-bridge/prepared-go-modules'));
16
+ const recovery = source => `dalan prepare-deps ${shellQuote(path.resolve(source))} --go`;
17
+ let hostGo;
18
+ const hostGoVersion = () => {
19
+ if (hostGo !== undefined) return hostGo;
20
+ const run = spawnSync(GO, ['env', 'GOVERSION'], { env: { PATH: '/usr/bin:/bin', HOME: os.tmpdir(), GOTOOLCHAIN: 'local', GOFLAGS: '' }, encoding: 'utf8', timeout: 20000 });
21
+ hostGo = run.status === 0 ? run.stdout.trim() : null;
22
+ return hostGo;
23
+ };
24
+
25
+ // Why the host cannot prepare this go.mod (null when it can). A local `replace` or a go.work file points outside go.mod and go.sum.
26
+ export function unsupportedGoModules(goMod) {
27
+ for (const match of String(goMod).matchAll(/=>\s*(\S+)/g)) if (/^(\.|\/)/.test(match[1])) return 'a local replace directive is unsupported';
28
+ return null;
29
+ }
30
+ function inputs(source) {
31
+ const root = path.resolve(source);
32
+ if (fs.realpathSync(root) !== root || !fs.lstatSync(root).isDirectory()) throw failure('dependencies_invalid', 'source directory must be canonical');
33
+ const mod = readRegular(path.join(root, 'go.mod'), true);
34
+ if (!mod) return null;
35
+ if (fs.existsSync(path.join(root, 'go.work'))) throw failure('dependencies_unsupported', 'go.work is unsupported');
36
+ const unsupported = unsupportedGoModules(mod.toString('utf8'));
37
+ if (unsupported) throw failure('dependencies_unsupported', unsupported);
38
+ const sum = readRegular(path.join(root, 'go.sum'), true) ?? Buffer.alloc(0);
39
+ const version = hostGoVersion();
40
+ if (!version) throw failure('dependencies_unsupported', `${GO} is unavailable on this host`);
41
+ const runtime = { go: version, platform: process.platform, arch: process.arch };
42
+ const identity = { go_mod_sha256: hash(mod), go_sum_sha256: hash(sum), runtime };
43
+ return { root, mod, sum, identity, name: hash(`${identity.go_mod_sha256}:${identity.go_sum_sha256}`), key: hash(JSON.stringify(runtime)) };
44
+ }
45
+ const entryPath = (base, input) => path.join(base, input.name, input.key);
46
+ function lookup(input, base) {
47
+ const entry = entryPath(base, input);
48
+ try {
49
+ checkParents(base); checkDirectory(base, true); checkDirectory(path.dirname(entry), true); checkDirectory(entry, true);
50
+ const metaPath = path.join(entry, 'metadata.json'), st = fs.lstatSync(metaPath);
51
+ if (!st.isFile() || st.uid !== process.getuid() || (st.mode & 0o222)) throw new Error('bad metadata');
52
+ const metadata = JSON.parse(readRegular(metaPath));
53
+ if (JSON.stringify(metadata.identity) !== JSON.stringify(input.identity)) throw new Error('identity mismatch');
54
+ const treePath = path.join(entry, 'modcache'); validateTree(treePath);
55
+ markUsed(entry);
56
+ return { treePath, ...input.identity };
57
+ } catch {
58
+ throw failure('dependencies_unprepared', `missing or invalid preparation; owner recovery: ${recovery(input.root)}`);
59
+ }
60
+ }
61
+ // Keep the newest N entries by last use; the rules (a day's grace, rename then delete an hour later) are those of the node_modules store.
62
+ export const pruneGoStore = (options = {}) => pruneNodeStore({ ...options, base: store(options) });
63
+ export function resolvePreparedGoModules(sourceDir, options = {}) {
64
+ const input = inputs(sourceDir);
65
+ return input ? lookup(input, store(options)) : null;
66
+ }
67
+ // For the offer filter: the reason from go.mod and the presence of go.work, null when there is no go.mod.
68
+ export function goModulesUnsupported(goMod, goWork) { return goMod ? (goWork ? 'go.work is unsupported' : unsupportedGoModules(goMod.toString('utf8'))) : null; }
69
+
70
+ export function prepareGoModules(sourceDir, options = {}) {
71
+ const input = inputs(sourceDir);
72
+ if (!input) throw failure('dependencies_invalid', 'root go.mod required');
73
+ const base = store(options);
74
+ fs.mkdirSync(base, { recursive: true, mode: 0o700 });
75
+ checkParents(base); checkDirectory(base, true);
76
+ fs.mkdirSync(path.join(base, input.name), { mode: 0o700, recursive: true }); checkDirectory(path.join(base, input.name), true);
77
+ const destination = entryPath(base, input);
78
+ if (fs.existsSync(destination)) {
79
+ try { return lookup(input, base); }
80
+ catch (error) { if (!options.replaceInvalid) throw error; }
81
+ }
82
+ const stage = fs.mkdtempSync(path.join(base, `.stage-${process.pid}-`));
83
+ try {
84
+ const work = path.join(stage, 'work'), cache = path.join(stage, 'modcache');
85
+ for (const dir of [work, cache, path.join(stage, 'home'), path.join(stage, 'gopath')]) fs.mkdirSync(dir, { mode: 0o700 });
86
+ // The go command records telemetry counters (and may start a helper) under HOME at exit; "off" keeps the stage quiet so removing it cannot race.
87
+ fs.mkdirSync(path.join(stage, 'home', '.config', 'go', 'telemetry'), { recursive: true, mode: 0o700 });
88
+ fs.writeFileSync(path.join(stage, 'home', '.config', 'go', 'telemetry', 'mode'), 'off\n', { mode: 0o600 });
89
+ fs.writeFileSync(path.join(work, 'go.mod'), input.mod, { mode: 0o600 });
90
+ fs.writeFileSync(path.join(work, 'go.sum'), input.sum, { mode: 0o600 });
91
+ const env = options.env ?? process.env;
92
+ const proxyEnv = Object.fromEntries(Object.entries(env).filter(([name]) => /^(LANG|NODE_EXTRA_CA_CERTS|SSL_CERT_FILE|GOPROXY|GOSUMDB|(https?|no)_proxy)$/i.test(name)));
93
+ // GOTOOLCHAIN=auto lets `go mod download` fetch the toolchain go.mod asks for into the same cache; -modcacherw lets us delete
94
+ // a failed stage. Nothing here runs repository code: download only fetches and verifies archives against go.sum.
95
+ const run = spawnSync(GO, ['mod', 'download'], { cwd: work, stdio: 'ignore', timeout: options.timeoutMs ?? 600000, env: { ...proxyEnv, PATH: '/usr/bin:/bin', HOME: path.join(stage, 'home'), GOPATH: path.join(stage, 'gopath'), GOMODCACHE: cache, GOFLAGS: '-modcacherw', GOWORK: 'off', GOTOOLCHAIN: 'auto' } });
96
+ if (run.error || run.status !== 0) {
97
+ const exit = run.error ? `error: ${run.error.message}` : run.signal ? `signal ${run.signal}` : `exit status ${run.status}`;
98
+ throw failure('dependencies_install_failed', `go mod download failed (${exit}); no preparation published`);
99
+ }
100
+ // A go.sum that download had to extend is incomplete: the sandbox build would fail on it, so publish nothing.
101
+ if (!fs.readFileSync(path.join(work, 'go.sum')).equals(input.sum)) throw failure('dependencies_install_failed', 'go.sum is incomplete for go.mod; no preparation published');
102
+ freezeTree(cache); validateTree(cache);
103
+ fs.writeFileSync(path.join(stage, 'metadata.json'), JSON.stringify({ identity: input.identity }) + '\n', { mode: 0o400 });
104
+ for (const name of ['work', 'home', 'gopath']) fs.rmSync(path.join(stage, name), { recursive: true, force: true });
105
+ if (fs.existsSync(destination)) {
106
+ try { return lookup(input, base); }
107
+ catch (error) { if (!options.replaceInvalid) throw error; }
108
+ // Keep the old inodes for any running read-only mount; the new bytes go to a new path.
109
+ fs.renameSync(destination, path.join(base, '.replaced-' + randomUUID()));
110
+ }
111
+ try { fs.renameSync(stage, destination); }
112
+ catch (error) { // another publisher won the race: reuse its entry when it is valid, otherwise report the original failure
113
+ try { return lookup(input, base); } catch { throw error; }
114
+ }
115
+ return lookup(input, base);
116
+ } finally {
117
+ if (fs.existsSync(stage)) { thawTree(stage); fs.rmSync(stage, { recursive: true, force: true, maxRetries: 5, retryDelay: 50 }); }
118
+ }
119
+ }
120
+
121
+ // Same detached child the node preparation uses, so a minutes-long download does not stop the bridge's event loop.
122
+ export function prepareGoModulesInChild(sourceDir, { timeoutMs = 600000, env = process.env } = {}) {
123
+ const root = fs.realpathSync(sourceDir);
124
+ const input = inputs(root);
125
+ if (!input) return Promise.resolve(null);
126
+ return prepareInChild({ root, key: `go:${input.name}:${input.key}`, base: store({}), flags: ['--go'], timeoutMs, env });
127
+ }
@@ -3,15 +3,16 @@ import fs from 'node:fs';
3
3
  import os from 'node:os';
4
4
  import path from 'node:path';
5
5
  import { createHash, randomUUID } from 'node:crypto';
6
- import { spawnSync } from 'node:child_process';
6
+ import { spawnSync, spawn } from 'node:child_process';
7
+ import { fileURLToPath } from 'node:url';
7
8
 
8
- const hash = bytes => createHash('sha256').update(bytes).digest('hex');
9
+ export const hash = bytes => createHash('sha256').update(bytes).digest('hex');
9
10
  const runtime = () => ({ node: process.version, abi: process.versions.modules, platform: process.platform, arch: process.arch });
10
- const store = options => path.resolve(options.cacheDir ?? defaultPath(os.homedir(),'.dot-bridge/prepared-node-modules'));
11
- const failure = (code, message) => Object.assign(new Error(`${code}: ${message}`), { code });
11
+ export const preparedNodeStore = options => path.resolve(options.cacheDir ?? defaultPath(os.homedir(),'.dot-bridge/prepared-node-modules'));
12
+ export const failure = (code, message) => Object.assign(new Error(`${code}: ${message}`), { code });
12
13
  const recovery = source => `dalan prepare-deps ${shellQuote(path.resolve(source))}`;
13
14
 
14
- function readRegular(file, optional = false) {
15
+ export function readRegular(file, optional = false) {
15
16
  let fd;
16
17
  try {
17
18
  fd = fs.openSync(file, fs.constants.O_RDONLY | fs.constants.O_NOFOLLOW | fs.constants.O_NONBLOCK);
@@ -23,6 +24,43 @@ function readRegular(file, optional = false) {
23
24
  throw failure('dependencies_invalid', 'cannot read regular manifest or lock');
24
25
  } finally { if (fd !== undefined) fs.closeSync(fd); }
25
26
  }
27
+ // Workspaces and local tarballs are the only local inputs the host can prepare: every one is a file the owner pins by hash.
28
+ // A workspace is a lock key outside node_modules (npm's own `ci` checks that the lock matches the manifests); a local tarball is a
29
+ // `file:` dependency on a .tgz. Directory links, `link:` and `workspace:` specs stay unsupported.
30
+ const SAFE_SEGMENT = /^[A-Za-z0-9_@.+-]+$/;
31
+ const safeRelative = value => typeof value === 'string' && value.split('/').every(part => SAFE_SEGMENT.test(part) && part !== '.' && part !== '..' && part !== 'node_modules' && part !== '.git');
32
+ const LOCAL_TARBALL = /^file:(?:\.\/)?(.+\.(?:tgz|tar\.gz))$/i;
33
+ const tarballPath = spec => { const match = LOCAL_TARBALL.exec(String(spec)); return match && safeRelative(match[1]) ? match[1] : null; };
34
+ // A dependency spec names its tarball relative to the package that declares it (`file:../../vendor/x.tgz`); only the lock's `resolved` path, relative to the root, decides which file is read.
35
+ const tarballSpec = spec => LOCAL_TARBALL.test(String(spec)) && !String(spec).slice(5).startsWith('/') && !/(^|\/)node_modules(\/|$)/.test(String(spec));
36
+ const workspaceKeys = data => Object.keys(data.packages).filter(name => name && !name.startsWith('node_modules/') && !name.includes('/node_modules/'));
37
+ function unsupportedReason(pkg, data) {
38
+ if (![2, 3].includes(data.lockfileVersion) || !data.packages || typeof data.packages !== 'object') return 'only npm lockfiles of version 2 or 3 are supported';
39
+ const workspaces = new Set(workspaceKeys(data));
40
+ if (workspaces.size && !pkg.workspaces) return 'the lock lists workspaces the manifest does not declare';
41
+ if (pkg.workspaces && !workspaces.size) return 'only root npm lockfiles with their workspaces are supported';
42
+ for (const name of workspaces) if (!safeRelative(name)) return 'a workspace path is unsupported';
43
+ const local = 'local or link dependencies are unsupported';
44
+ for (const [name, entry] of Object.entries(data.packages)) {
45
+ if (name) {
46
+ if (name.includes('/node_modules/') && !name.startsWith('node_modules/') && !workspaces.has(name.split('/node_modules/')[0])) return local;
47
+ if (entry?.link) { if (!name.startsWith('node_modules/') || !workspaces.has(entry.resolved)) return local; continue; }
48
+ if (/^(file:|link:|workspace:)/i.test(entry?.resolved ?? '') && !tarballPath(entry.resolved)) return local;
49
+ }
50
+ for (const group of ['dependencies','devDependencies','optionalDependencies']) for (const value of Object.values(entry?.[group] ?? {})) if (typeof value === 'string' && /^(file:|link:|workspace:)/i.test(value) && !tarballSpec(value)) return local;
51
+ }
52
+ return null;
53
+ }
54
+ // The repository-relative files that must match the owner's pinned base for a lock to be prepared from it: each workspace's package.json and each local tarball.
55
+ export function localInputFiles(lock) {
56
+ const data = JSON.parse(lock);
57
+ const tarballs = Object.values(data.packages ?? {}).map(entry => tarballPath(entry?.resolved)).filter(Boolean);
58
+ return [...new Set([...workspaceKeys(data).map(name => `${name}/package.json`), ...tarballs])].sort();
59
+ }
60
+ export function unsupportedDependencies(manifest, lock) {
61
+ if (!lock) return null;
62
+ try { return unsupportedReason(JSON.parse(manifest), JSON.parse(lock)); } catch { return null; }
63
+ }
26
64
  function inputs(source) {
27
65
  const root = path.resolve(source);
28
66
  if (fs.realpathSync(root) !== root || !fs.lstatSync(root).isDirectory()) throw failure('dependencies_invalid', 'source directory must be canonical');
@@ -31,30 +69,58 @@ function inputs(source) {
31
69
  const manifest = readRegular(path.join(root, 'package.json'));
32
70
  let pkg, data;
33
71
  try { pkg = JSON.parse(manifest); data = JSON.parse(lock); } catch { throw failure('dependencies_invalid', 'invalid manifest or lock JSON'); }
34
- if (pkg.workspaces || ![2, 3].includes(data.lockfileVersion) || !data.packages || typeof data.packages !== 'object') throw failure('dependencies_unsupported', 'only root npm lockfiles without workspaces are supported');
35
- for (const [name, entry] of Object.entries(data.packages)) {
36
- if (entry?.link || (name && !name.startsWith('node_modules/')) || /^(file:|link:|workspace:)/i.test(entry?.resolved ?? '')) throw failure('dependencies_unsupported', 'local or workspace dependencies are unsupported');
37
- for (const group of ['dependencies','devDependencies','optionalDependencies']) for (const value of Object.values(entry?.[group] ?? {})) if (typeof value === 'string' && /^(file:|link:|workspace:)/i.test(value)) throw failure('dependencies_unsupported', 'local or workspace dependencies are unsupported');
38
- }
72
+ const unsupported = unsupportedReason(pkg, data);
73
+ if (unsupported) throw failure('dependencies_unsupported', unsupported);
39
74
  const identity = { lock_sha256: hash(lock), manifest_sha256: hash(manifest), runtime: runtime() };
40
- return { root, lock, manifest, identity, key: hash(JSON.stringify(identity.runtime)) };
75
+ // Workspace manifests and local tarballs are read without following symlinks, and their hashes join the identity.
76
+ const files = new Map(), workspaces = workspaceKeys(data).sort();
77
+ for (const name of localInputFiles(lock)) {
78
+ const dir = path.dirname(path.join(root, name));
79
+ if (fs.realpathSync(dir) !== dir) throw failure('dependencies_invalid', 'workspace or tarball path must not contain links');
80
+ files.set(name, readRegular(path.join(root, name)));
81
+ }
82
+ if (workspaces.length) identity.workspaces = Object.fromEntries(workspaces.map(name => [name, hash(files.get(`${name}/package.json`))]));
83
+ const manifests = new Set(workspaces.map(name => `${name}/package.json`));
84
+ const tarballs = [...files.keys()].filter(name => !manifests.has(name));
85
+ if (tarballs.length) identity.local_files = Object.fromEntries(tarballs.map(name => [name, hash(files.get(name))]));
86
+ // Each full dependency identity has its own slot under the lock, so checkouts sharing one lock can keep different
87
+ // manifests and local files without fighting over an entry. Legacy runtime-only slots are prepared again once.
88
+ const key = hash(JSON.stringify({ runtime: identity.runtime, manifest_sha256: identity.manifest_sha256, workspaces: identity.workspaces ?? {}, local_files: identity.local_files ?? {} }));
89
+ return { root, lock, manifest, files, workspaces, identity, key };
41
90
  }
42
- function checkDirectory(dir, privateMode = false) {
91
+ // Remove every write bit under a prepared tree so the sandbox's read-only mount and the owner agree on what the bytes are.
92
+ export function freezeTree(dir) { const s = fs.lstatSync(dir); if (s.isSymbolicLink()) return; if (s.isDirectory()) for (const name of fs.readdirSync(dir)) freezeTree(path.join(dir, name)); else if (!s.isFile()) throw failure('dependencies_invalid', 'special file in dependency tree'); fs.chmodSync(dir, s.mode & 0o555); }
93
+ // Make a staging tree removable again after freezeTree.
94
+ export function thawTree(dir) { const st=fs.lstatSync(dir); if (!st.isDirectory() || st.isSymbolicLink()) return; fs.chmodSync(dir, 0o700); for (const name of fs.readdirSync(dir)) thawTree(path.join(dir,name)); }
95
+ export function checkDirectory(dir, privateMode = false) {
43
96
  const s = fs.lstatSync(dir);
44
97
  if (!s.isDirectory() || s.uid !== process.getuid() || (s.mode & (privateMode ? 0o077 : 0o022))) throw failure('dependencies_invalid', 'unsafe cache directory ownership or mode');
45
98
  }
46
- function checkParents(dir) {
99
+ export function checkParents(dir) {
47
100
  for (let p = dir; ; p = path.dirname(p)) {
48
101
  const s = fs.lstatSync(p);
49
102
  if (!s.isDirectory() || (s.uid !== process.getuid() && s.uid !== 0) || (s.mode & 0o022)) throw failure('dependencies_invalid', 'unsafe cache parent');
50
103
  if (p === '/') break;
51
104
  }
52
105
  }
53
- function validateTree(root) {
106
+ // `place` says where this tree sits in the repository layout (dir: its node_modules' parent, relative to the repository root) and which
107
+ // workspace paths a link may point at: npm links each workspace into node_modules, and that target is the source checkout, not this tree.
108
+ export function validateTree(root, place = null) {
54
109
  const walk = dir => {
55
110
  const st = fs.lstatSync(dir);
56
111
  if (st.uid !== process.getuid() || (!st.isSymbolicLink() && (st.mode & 0o222))) throw failure('dependencies_invalid', 'dependency tree ownership or mode invalid');
57
112
  if (st.isSymbolicLink()) {
113
+ const text = fs.readlinkSync(dir);
114
+ // The lexical rules below read the link text as plain path arithmetic. That is sound only when `..` comes first: a `..` after a name
115
+ // climbs from where a directory link points, not from where the name sits, so such a text is left to the realpath check.
116
+ const parts = text.split('/'), leading = parts.findIndex(part => part !== '..');
117
+ if (place && !path.isAbsolute(text) && !parts.slice(leading < 0 ? parts.length : leading).includes('..')) {
118
+ const inRepo = path.posix.join(place.dir, 'node_modules', path.relative(root, path.dirname(dir)).split(path.sep).join('/'));
119
+ const target = path.posix.normalize(path.posix.join(inRepo, text));
120
+ if (place.workspaces.includes(target)) return;
121
+ // pnpm: a relative link may also point into the root tree or another allowed importer's tree (place.treeDirs); only lexical targets count.
122
+ if (place.treeDirs?.some(tree => target === tree || target.startsWith(tree + '/'))) return;
123
+ }
58
124
  const target = fs.realpathSync(dir);
59
125
  if (!target.startsWith(root + path.sep)) throw failure('dependencies_invalid', 'dependency link escapes tree');
60
126
  } else if (st.isDirectory()) for (const name of fs.readdirSync(dir)) walk(path.join(dir, name));
@@ -63,29 +129,84 @@ function validateTree(root) {
63
129
  walk(root);
64
130
  }
65
131
  function entryPath(base, input) { return path.join(base, input.identity.lock_sha256, input.key); }
66
- const shellQuote = value => "'" + value.replaceAll("'", "'\\''") + "'";
132
+ // Record that a check resolved this entry: the prune ranks entries by the mtime of metadata.json. Touching at most hourly keeps the
133
+ // metadata write rare; an owner-only 0400 file can still have its times set by its owner, and a failure here never fails a lookup.
134
+ export function markUsed(entry, now = Date.now()) {
135
+ const meta = path.join(entry, 'metadata.json');
136
+ try { if (now - fs.lstatSync(meta).mtimeMs >= 3600e3) fs.utimesSync(meta, now / 1000, now / 1000); } catch { /* best effort */ }
137
+ }
138
+ // Tools write caches and temp files under node_modules: vite bundles its config into node_modules/.vite-temp (and fails the whole run when it
139
+ // cannot), vitest and vite keep results in .vite, babel, eslint and prettier in .cache. The sandbox mounts the tree read-only, so each of these
140
+ // names is a real empty directory in every published tree, and the sandbox mounts a small tmpfs over it (host-budget-storage.py names the same
141
+ // directories). The store stays read-only and untouched; the writes vanish with the sandbox. A mount point can only exist if the tree has it.
142
+ export const SCRATCH_DIRS = ['.cache', '.vite', '.vite-temp', '.vitest', '.vitest-cache'];
143
+ export function addScratchMountpoints(tree) {
144
+ const st = fs.lstatSync(tree);
145
+ if (!st.isDirectory() || st.isSymbolicLink()) return;
146
+ const missing = SCRATCH_DIRS.filter(name => { try { fs.lstatSync(path.join(tree, name)); return false; } catch { return true; } });
147
+ if (!missing.length) return;
148
+ fs.chmodSync(tree, st.mode | 0o200);
149
+ try { for (const name of missing) fs.mkdirSync(path.join(tree, name), { mode: 0o555 }); }
150
+ finally { fs.chmodSync(tree, st.mode & 0o7555); } // never restore a write bit: a concurrent repair may have read the mode inside this one's writable window
151
+ }
152
+ // An entry published before this existed gets its mount points the next time any lookup validates it (the owner's process owns the store).
153
+ // Best effort: without them the check still runs, vite just cannot bundle its config.
154
+ export function repairScratchMountpoints(trees) { for (const tree of trees) { try { addScratchMountpoints(tree); } catch { /* see above */ } } }
155
+ export const shellQuote = value => "'" + value.replaceAll("'", "'\\''") + "'";
67
156
  function lookup(input, base) {
68
157
  const entry = entryPath(base, input);
158
+ let cause = 'unsafe store directory';
69
159
  try {
70
160
  checkParents(base); checkDirectory(base, true); checkDirectory(path.dirname(entry), true); checkDirectory(entry, true);
161
+ cause = 'bad metadata';
71
162
  const metaPath = path.join(entry, 'metadata.json'), st = fs.lstatSync(metaPath);
72
- if (!st.isFile() || st.uid !== process.getuid() || (st.mode & 0o222)) throw new Error('bad metadata');
163
+ if (!st.isFile() || st.uid !== process.getuid() || (st.mode & 0o222)) throw new Error();
73
164
  const metadata = JSON.parse(readRegular(metaPath));
74
- if (JSON.stringify(metadata.identity) !== JSON.stringify(input.identity)) throw new Error('identity mismatch');
75
- const treePath = path.join(entry, 'node_modules'); validateTree(treePath);
76
- return { treePath, ...input.identity };
77
- } catch (e) {
78
- throw failure('dependencies_unprepared', `missing or invalid preparation; owner recovery: ${recovery(input.root)} --replace-invalid`);
165
+ if (!metadata?.identity || typeof metadata.identity !== 'object' || Array.isArray(metadata.identity) ||
166
+ (metadata.trees != null && (!Array.isArray(metadata.trees) || metadata.trees.some(name => typeof name !== 'string')))) throw new Error();
167
+ if (JSON.stringify(metadata.identity) !== JSON.stringify(input.identity)) {
168
+ cause = 'identity mismatch';
169
+ throw new Error();
170
+ }
171
+ const places = [{ dir: '', treePath: path.join(entry, 'node_modules') }, ...(metadata.trees ?? []).map(name => ({ dir: name, treePath: path.join(entry, 'workspaces', name, 'node_modules') }))];
172
+ // Only workspaces the identity names may have a tree; a recorded tree for any other path is refused.
173
+ if (places.slice(1).some(place => !input.workspaces.includes(place.dir))) {
174
+ cause = 'unexpected workspace tree';
175
+ throw new Error();
176
+ }
177
+ const workspaces = input.workspaces.map(name => path.posix.normalize(name));
178
+ cause = 'invalid dependency tree';
179
+ for (const place of places) validateTree(place.treePath, { dir: place.dir, workspaces });
180
+ repairScratchMountpoints(places.map(place => place.treePath));
181
+ markUsed(entry);
182
+ return { treePath: places[0].treePath, workspaceTrees: places.slice(1).map(({ dir, treePath }) => ({ path: dir, treePath })), ...input.identity };
183
+ } catch (error) {
184
+ if (error?.code === 'ENOENT' && (cause === 'unsafe store directory' || cause === 'bad metadata')) cause = 'missing';
185
+ throw failure('dependencies_unprepared', `invalid preparation (${cause}); owner recovery: ${recovery(input.root)} --replace-invalid`);
79
186
  }
80
187
  }
188
+ // The `npm` file beside Node is not always JavaScript: mise installs a Bash wrapper there, and
189
+ // running that wrapper under Node fails before npm starts. Find npm's own JavaScript entry point:
190
+ // the running npm (`npm_execpath`), then the layouts Node installers use, then the sibling file.
191
+ export function npmCliPath({ execPath = process.execPath, env = process.env } = {}) {
192
+ const binDir = path.dirname(execPath);
193
+ const real = file => { try { return fs.realpathSync(file); } catch { return null; } };
194
+ const entry = file => { const resolved = real(file); return resolved && fs.statSync(resolved).isFile() ? resolved : null; };
195
+ const fromEnv = env.npm_execpath && path.basename(env.npm_execpath) === 'npm-cli.js' ? entry(env.npm_execpath) : null;
196
+ const sibling = path.join(binDir, 'npm');
197
+ return fromEnv
198
+ ?? entry(path.join(binDir, '..', 'lib', 'node_modules', 'npm', 'bin', 'npm-cli.js'))
199
+ ?? entry(path.join(binDir, 'node_modules', 'npm', 'bin', 'npm-cli.js'))
200
+ ?? (path.basename(real(sibling) ?? '') === 'npm-cli.js' ? real(sibling) : sibling);
201
+ }
81
202
  export function resolvePreparedNodeModules(sourceDir, options = {}) {
82
203
  const input = inputs(sourceDir);
83
- return input ? lookup(input, store(options)) : null;
204
+ return input ? lookup(input, preparedNodeStore(options)) : null;
84
205
  }
85
206
  export function prepareNodeModules(sourceDir, options = {}) {
86
207
  const input = inputs(sourceDir);
87
208
  if (!input) throw failure('dependencies_invalid', 'root package-lock.json required');
88
- const base = store(options);
209
+ const base = preparedNodeStore(options);
89
210
  fs.mkdirSync(base, { recursive: true, mode: 0o700 });
90
211
  checkParents(base); checkDirectory(base, true);
91
212
  const lockDir = path.join(base, input.identity.lock_sha256);
@@ -95,35 +216,101 @@ export function prepareNodeModules(sourceDir, options = {}) {
95
216
  try { return lookup(input, base); }
96
217
  catch(error) { if(!options.replaceInvalid)throw error; }
97
218
  }
98
- const stage = fs.mkdtempSync(path.join(base, '.stage-'));
219
+ const stage = fs.mkdtempSync(path.join(base, `.stage-${process.pid}-`));
99
220
  try {
100
- fs.writeFileSync(path.join(stage, 'package.json'), input.manifest, { mode: 0o600 });
101
- fs.writeFileSync(path.join(stage, 'package-lock.json'), input.lock, { mode: 0o600 });
102
- const npm = path.join(path.dirname(process.execPath), 'npm');
103
- const run = spawnSync(process.execPath, [npm, 'ci', '--ignore-scripts', '--no-audit', '--no-fund'], { cwd: stage, env: { ...process.env, npm_config_ignore_scripts: 'true' }, stdio: 'ignore' });
221
+ // npm runs in work/ with the lock, the root manifest, every workspace manifest and every local tarball; only the node_modules trees are published.
222
+ const work = path.join(stage, 'work');
223
+ fs.mkdirSync(work, { mode: 0o700 });
224
+ fs.writeFileSync(path.join(work, 'package.json'), input.manifest, { mode: 0o600 });
225
+ fs.writeFileSync(path.join(work, 'package-lock.json'), input.lock, { mode: 0o600 });
226
+ for (const [name, bytes] of input.files) { fs.mkdirSync(path.dirname(path.join(work, name)), { recursive: true, mode: 0o700 }); fs.writeFileSync(path.join(work, name), bytes, { mode: 0o600 }); }
227
+ const env = options.env ?? process.env, execPath = options.execPath ?? process.execPath;
228
+ const npm = npmCliPath({ execPath, env });
229
+ const run = spawnSync(execPath, [npm, 'ci', '--ignore-scripts', '--no-audit', '--no-fund'], { cwd: work, env: { ...env, npm_config_ignore_scripts: 'true' }, stdio: 'ignore' });
104
230
  if (run.error || run.status !== 0) {
105
231
  const exit = run.error ? `error: ${run.error.message}` : run.signal ? `signal ${run.signal}` : `exit status ${run.status}`;
106
232
  throw failure('dependencies_install_failed', `npm ci failed (ran ${npm}; ${exit}); no preparation published`);
107
233
  }
108
- const tree = path.join(stage, 'node_modules');
109
- if (!fs.existsSync(tree)) fs.mkdirSync(tree, { mode: 0o700 });
110
- const freeze = dir => { const s = fs.lstatSync(dir); if (s.isSymbolicLink()) return; if (s.isDirectory()) for (const name of fs.readdirSync(dir)) freeze(path.join(dir, name)); else if (!s.isFile()) throw failure('dependencies_invalid', 'special file in dependency tree'); fs.chmodSync(dir, s.mode & 0o555); };
111
- freeze(tree); validateTree(tree);
112
- fs.rmSync(path.join(stage, 'package.json')); fs.rmSync(path.join(stage, 'package-lock.json'));
113
- fs.writeFileSync(path.join(stage, 'metadata.json'), JSON.stringify({ identity: input.identity }) + '\n', { mode: 0o400 });
234
+ const workspaces = input.workspaces.map(name => path.posix.normalize(name));
235
+ const trees = [];
236
+ fs.mkdirSync(path.join(work, 'node_modules'), { recursive: true, mode: 0o700 });
237
+ fs.renameSync(path.join(work, 'node_modules'), path.join(stage, 'node_modules'));
238
+ for (const name of input.workspaces) {
239
+ const tree = path.join(work, name, 'node_modules');
240
+ if (!fs.existsSync(tree)) continue;
241
+ fs.mkdirSync(path.join(stage, 'workspaces', name), { recursive: true, mode: 0o700 });
242
+ fs.renameSync(tree, path.join(stage, 'workspaces', name, 'node_modules')); trees.push(name);
243
+ }
244
+ fs.rmSync(work, { recursive: true, force: true });
245
+ for (const [dir, tree] of [['', path.join(stage, 'node_modules')], ...trees.map(name => [name, path.join(stage, 'workspaces', name, 'node_modules')])]) { addScratchMountpoints(tree); freezeTree(tree); validateTree(tree, { dir, workspaces }); }
246
+ fs.writeFileSync(path.join(stage, 'metadata.json'), JSON.stringify({ identity: input.identity, trees }) + '\n', { mode: 0o400 });
114
247
  if(fs.existsSync(destination)) {
115
248
  // Recheck after npm: a concurrent owner preparation may have finished.
116
- try { return lookup(input,base); }
249
+ try { return lookup(input, base); }
117
250
  catch(error) { if(!options.replaceInvalid)throw error; }
118
251
  // Preserve old inodes for any active read-only mount. An explicit owner
119
252
  // repair publishes new bytes without modifying a running check's input.
120
253
  fs.renameSync(destination,path.join(base,'.replaced-'+randomUUID()));
121
254
  }
122
255
  // The private publication directory remains owner-writable for explicit recovery.
123
- fs.renameSync(stage, destination);
256
+ try { fs.renameSync(stage, destination); }
257
+ catch(error) {
258
+ if(error?.code!=='EEXIST'&&error?.code!=='ENOTEMPTY') throw error;
259
+ // Another publisher won after the last probe. Use only a fully verified entry.
260
+ return lookup(input, base);
261
+ }
124
262
  return lookup(input, base);
125
263
  } finally { if (fs.existsSync(stage)) {
126
- const thaw = dir => { const st=fs.lstatSync(dir); if (!st.isDirectory() || st.isSymbolicLink()) return; fs.chmodSync(dir, 0o700); for (const name of fs.readdirSync(dir)) thaw(path.join(dir,name)); };
127
- thaw(stage); fs.rmSync(stage, { recursive: true, force: true });
264
+ thawTree(stage); fs.rmSync(stage, { recursive: true, force: true });
128
265
  } }
129
266
  }
267
+
268
+ // Prepare in a child process so a minutes-long `npm ci` does not stop the bridge's event loop. The child is the same
269
+ // `dalan prepare-deps` the owner runs by hand, so it publishes to the same private store and under the same checks.
270
+ // Callers must only pass a source whose manifest and lock the owner already trusts (a pinned base commit).
271
+ const inFlight = new Map();
272
+ // A stage directory names the process that owns it, so a killed child's parent removes exactly that child's stages.
273
+ const listStages = (base, pid) => { try { return fs.readdirSync(base).filter(name => name.startsWith(`.stage-${pid}-`)); } catch { return []; } };
274
+ export function prepareNodeModulesInChild(sourceDir, { timeoutMs = 600000, env = process.env } = {}) {
275
+ const root = fs.realpathSync(sourceDir);
276
+ const input = inputs(root);
277
+ if (!input) return Promise.resolve(null);
278
+ return prepareInChild({ root, key: `${input.identity.lock_sha256}:${input.key}`, base: preparedNodeStore({}), flags: [], timeoutMs, env });
279
+ }
280
+ // Preserve deadline settlement even when a child never reports close; normally reap its staging first.
281
+ const STOP_CLEANUP_GRACE_MS = 100;
282
+ // Shared by every kind of preparation: one pending attempt per key, own process group, and stage cleanup after close.
283
+ export function prepareInChild({ root, key, base, flags, timeoutMs = 600000, env = process.env }) {
284
+ const running = inFlight.get(key);
285
+ if (running) return running;
286
+ const cli = fileURLToPath(new URL('../bin/dot-worker.mjs', import.meta.url));
287
+ const childEnv = Object.fromEntries(Object.entries(env).filter(([name]) => /^(PATH|HOME|LANG|TMPDIR|NODE_EXTRA_CA_CERTS|SSL_CERT_FILE|(npm|pnpm)_config_.*|GOPROXY|GOSUMDB|(https?|no)_proxy)$/i.test(name)));
288
+ const done = new Promise((resolve, reject) => {
289
+ // Own process group: npm runs under the CLI's synchronous spawn, so killing the CLI alone would leave npm installing.
290
+ const child = spawn(process.execPath, [cli, 'prepare-deps', root, '--json', ...flags], { env: childEnv, detached: true, stdio: ['ignore', 'pipe', 'pipe'] });
291
+ let out = '', err = '', timedOut = false, closed = false, cleanupDeadline;
292
+ const timeoutFailure = () => failure('dependencies_install_failed', `automatic preparation failed (timed out after ${Math.round(timeoutMs / 1000)} s)`);
293
+ child.stdout.on('data', chunk => { if (out.length < 1 << 20) out += chunk; });
294
+ child.stderr.on('data', chunk => { if (err.length < 1 << 16) err += chunk; });
295
+ const timer = setTimeout(() => {
296
+ timedOut = true;
297
+ try { process.kill(-child.pid, 'SIGKILL'); } catch {}
298
+ if (!closed) cleanupDeadline = setTimeout(() => reject(timeoutFailure()), STOP_CLEANUP_GRACE_MS);
299
+ }, timeoutMs);
300
+ child.on('error', error => { if (timedOut) return; clearTimeout(timer); reject(failure('dependencies_install_failed', `automatic preparation could not start: ${error.message}`)); });
301
+ child.on('close', code => {
302
+ closed = true;
303
+ clearTimeout(timer);
304
+ clearTimeout(cleanupDeadline);
305
+ // A stopped child cannot still use these paths; never delete another preparation's stage.
306
+ if (Number.isInteger(child.pid)) for (const name of listStages(base, child.pid)) {
307
+ try { thawTree(path.join(base, name)); fs.rmSync(path.join(base, name), { recursive: true, force: true, maxRetries: 5, retryDelay: 50 }); } catch {}
308
+ }
309
+ if (timedOut) return reject(timeoutFailure());
310
+ if (code !== 0) return reject(failure('dependencies_install_failed', `automatic preparation failed (exit ${code}): ${err.trim().split('\n').slice(-3).join(' ').slice(0, 300)}`));
311
+ try { resolve(JSON.parse(out)); } catch { reject(failure('dependencies_install_failed', 'automatic preparation printed no result')); }
312
+ });
313
+ }).finally(() => inFlight.delete(key));
314
+ inFlight.set(key, done);
315
+ return done;
316
+ }