@tnunamak/dalan 0.8.0 → 0.8.2

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 (130) hide show
  1. package/CHANGELOG.md +70 -1
  2. package/CONTRIBUTING.md +2 -0
  3. package/PROTOCOL.md +6 -0
  4. package/README.md +8 -12
  5. package/bin/dalan.mjs +25 -4
  6. package/bin/dot-acp-agent.mjs +572 -76
  7. package/bin/dot-alert.mjs +9 -3
  8. package/bin/dot-deadman.mjs +3 -1
  9. package/bin/dot-heartbeat.mjs +14 -7
  10. package/bin/dot-pr-reviewer.mjs +3 -31
  11. package/bin/dot-worker.mjs +215 -40
  12. package/contracts/adapter-qualification.schema.json +94 -7
  13. package/docs/chatgpt-worker-onboarding.md +1 -1
  14. package/docs/codex-to-muse.md +2 -2
  15. package/docs/connect-chatgpt.md +1 -1
  16. package/docs/connection-longevity.md +2 -2
  17. package/docs/dalan-upgrade.md +8 -5
  18. package/docs/deadman.md +4 -0
  19. package/docs/design/authority-matrix.md +18 -0
  20. package/docs/design/failure-table.md +87 -0
  21. package/docs/design/identities.md +22 -0
  22. package/docs/design/pnpm-prepared-dependencies.md +64 -0
  23. package/docs/design/reuse-ledger.md +75 -0
  24. package/docs/design/target-architecture-v2.md +434 -0
  25. package/docs/local-agent-mcp.md +14 -0
  26. package/docs/local-agent-requester.md +3 -2
  27. package/docs/manual-setup.md +1 -1
  28. package/docs/operations.md +78 -14
  29. package/docs/pull-workers.md +11 -0
  30. package/docs/relationships.md +13 -0
  31. package/docs/service-setup.md +10 -10
  32. package/docs/t3-integration.md +6 -2
  33. package/docs/t3-reverse-control.md +5 -5
  34. package/docs/t3-wake-fence-r4.md +1 -1
  35. package/docs/test-suite-isolation.md +8 -6
  36. package/docs/trials/chatgpt-agent.md +47 -0
  37. package/docs/trials/claude-code-requester.md +68 -0
  38. package/docs/trials/muse.md +46 -0
  39. package/docs/usage.md +35 -9
  40. package/docs/worker-clients.md +1 -1
  41. package/integrations/t3/acp-kit/src/errors.mjs +6 -2
  42. package/integrations/t3/acp-kit/src/lock.mjs +46 -17
  43. package/integrations/t3/acp-kit/src/session-store.mjs +15 -3
  44. package/integrations/t3/acp-kit/src/t3-envelope.mjs +10 -2
  45. package/package.json +4 -3
  46. package/packages/job-core/protocol/canonical.mjs +45 -7
  47. package/packages/job-core/transitions.mjs +4 -2
  48. package/scripts/upgrade-drain.mjs +96 -8
  49. package/scripts/worker-bridge-setup.mjs +215 -120
  50. package/src/ack-ledger.mjs +7 -1
  51. package/src/acp-bridge.mjs +256 -28
  52. package/src/admin-socket.mjs +32 -3
  53. package/src/alerts.mjs +17 -8
  54. package/src/answer-journal-retention.mjs +82 -0
  55. package/src/answer-journal.mjs +6 -4
  56. package/src/as-store.mjs +51 -6
  57. package/src/as.mjs +27 -5
  58. package/src/catalog-switch-inventory.mjs +70 -0
  59. package/src/check-response.mjs +4 -1
  60. package/src/claim-command-ledger.mjs +3 -2
  61. package/src/cli-help.mjs +29 -10
  62. package/src/cli-name.mjs +13 -1
  63. package/src/connect-cli.mjs +159 -4
  64. package/src/deadman.mjs +8 -5
  65. package/src/delivery.mjs +2 -19
  66. package/src/destinations/index.mjs +75 -14
  67. package/src/drain-runner.mjs +5 -1
  68. package/src/follow-current.mjs +3 -1
  69. package/src/get-summary.mjs +11 -2
  70. package/src/git-env.mjs +1 -1
  71. package/src/gozar-routes.mjs +313 -94
  72. package/src/host-budget-storage.py +56 -6
  73. package/src/host-budget.mjs +98 -15
  74. package/src/host-execution-policy.mjs +17 -6
  75. package/src/inbox.mjs +13 -3
  76. package/src/legacy-names.mjs +0 -2
  77. package/src/lifecycle.mjs +104 -11
  78. package/src/loopback-probe.mjs +46 -0
  79. package/src/mcp-outcome.mjs +3 -1
  80. package/src/mcp-sse.mjs +2 -1
  81. package/src/mcp-stdio.mjs +192 -30
  82. package/src/patch-apply.mjs +285 -19
  83. package/src/phase-trace.mjs +73 -0
  84. package/src/prepared-go-modules.mjs +127 -0
  85. package/src/prepared-node-modules.mjs +225 -38
  86. package/src/prepared-pnpm.mjs +276 -0
  87. package/src/prepared-store-prune.mjs +52 -0
  88. package/src/projects.mjs +59 -7
  89. package/src/protocol-artifact-commands.mjs +28 -0
  90. package/src/protocol-finish.mjs +3 -2
  91. package/src/publication-authority.mjs +22 -0
  92. package/src/publish-plan.mjs +2 -2
  93. package/src/pull-queue.mjs +55 -20
  94. package/src/read-api.mjs +127 -0
  95. package/src/redaction.mjs +173 -0
  96. package/src/rejections.mjs +19 -3
  97. package/src/route-custody.mjs +90 -0
  98. package/src/route-publication.mjs +50 -0
  99. package/src/route-setup.mjs +184 -0
  100. package/src/schema-subset.mjs +5 -3
  101. package/src/server.mjs +619 -88
  102. package/src/service-launchd.mjs +5 -1
  103. package/src/service-update-lock.mjs +7 -4
  104. package/src/service-update-runtime.mjs +64 -19
  105. package/src/service-update.mjs +193 -48
  106. package/src/service.mjs +276 -77
  107. package/src/setup.mjs +48 -25
  108. package/src/signal.mjs +1 -1
  109. package/src/status-evidence.mjs +18 -5
  110. package/src/status-summary.mjs +3 -0
  111. package/src/store.mjs +1086 -127
  112. package/src/submission-policy.mjs +257 -56
  113. package/src/t3-control.mjs +1 -1
  114. package/src/t3.mjs +14 -8
  115. package/src/terminal-safe.mjs +9 -7
  116. package/src/tool-registry.mjs +134 -41
  117. package/src/try-exposure.mjs +53 -86
  118. package/src/try-hosted.mjs +257 -70
  119. package/src/try.mjs +48 -22
  120. package/src/work-order.mjs +11 -6
  121. package/src/worker-instructions.mjs +26 -4
  122. package/src/worker-runs.mjs +35 -0
  123. package/src/workers.mjs +49 -4
  124. package/src/workspace.mjs +354 -54
  125. package/systemd/dot-deadman.service +3 -1
  126. package/docs/dot-pr-reviewer.config.example.json +0 -9
  127. package/docs/pr-head-reviewer.md +0 -70
  128. package/src/pr-head-reviewer.mjs +0 -596
  129. package/systemd/dot-pr-reviewer.service +0 -11
  130. package/systemd/dot-pr-reviewer.timer +0 -10
@@ -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
+ }