@dsh-triage/probe 0.0.0-stage → 0.2.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE +21 -0
- package/README.md +28 -2
- package/dist/exec.d.ts +485 -0
- package/dist/exec.d.ts.map +1 -0
- package/dist/exec.js +1281 -0
- package/dist/exec.js.map +1 -0
- package/dist/host.d.ts +544 -0
- package/dist/host.d.ts.map +1 -0
- package/dist/host.js +986 -0
- package/dist/host.js.map +1 -0
- package/dist/index.d.ts +18 -0
- package/dist/index.d.ts.map +1 -0
- package/dist/index.js +13 -0
- package/dist/index.js.map +1 -0
- package/dist/plan.d.ts +109 -0
- package/dist/plan.d.ts.map +1 -0
- package/dist/plan.js +246 -0
- package/dist/plan.js.map +1 -0
- package/dist/profile-copy.d.ts +82 -0
- package/dist/profile-copy.d.ts.map +1 -0
- package/dist/profile-copy.js +142 -0
- package/dist/profile-copy.js.map +1 -0
- package/dist/render.d.ts +108 -0
- package/dist/render.d.ts.map +1 -0
- package/dist/render.js +382 -0
- package/dist/render.js.map +1 -0
- package/package.json +30 -3
package/dist/host.js
ADDED
|
@@ -0,0 +1,986 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Host I/O for the probe: the four side effects, in one place.
|
|
3
|
+
*
|
|
4
|
+
* WHY ONE PLACE: R12/R13 shipped two recorders that each booted the same sandbox Host.
|
|
5
|
+
* They were merged into one helper because two copies of "write overlay → spawn → wait for
|
|
6
|
+
* the sample → kill the tree" drift silently until one of them samples a different moment
|
|
7
|
+
* than the other. The M3 executor would have been the third copy, so the machinery lives
|
|
8
|
+
* here and `scripts/lib/live.mjs` re-exports it.
|
|
9
|
+
*
|
|
10
|
+
* NOTHING HERE JUDGES ANYTHING. Failure is returned as data; `packages/probe/src/exec.ts`
|
|
11
|
+
* decides what it means.
|
|
12
|
+
*/
|
|
13
|
+
import { spawn, spawnSync } from 'node:child_process';
|
|
14
|
+
import { createHash } from 'node:crypto';
|
|
15
|
+
import { copyFileSync, existsSync, lstatSync, mkdirSync, mkdtempSync, readFileSync, readdirSync, readlinkSync, rmSync, statSync, writeFileSync } from 'node:fs';
|
|
16
|
+
import { createServer } from 'node:net';
|
|
17
|
+
import { isAbsolute, join } from 'node:path';
|
|
18
|
+
import { extractHostUrl, renderUrl } from './render.js';
|
|
19
|
+
/** Read {@link NodeLayout} from a profile dir. `null` = could not read (never a guess). */
|
|
20
|
+
export function readNodeLayout(dir) {
|
|
21
|
+
try {
|
|
22
|
+
const nodeModules = join(dir, 'node_modules');
|
|
23
|
+
if (!existsSync(nodeModules)) {
|
|
24
|
+
return { linker: 'absent', declared: null, topLevel: 0, topLevelSymlink: null, virtualStoreLinks: 0, pnpmStore: false };
|
|
25
|
+
}
|
|
26
|
+
const modulesYaml = join(nodeModules, '.modules.yaml');
|
|
27
|
+
let declared = null;
|
|
28
|
+
if (existsSync(modulesYaml)) {
|
|
29
|
+
// pnpm writes this file with quoted keys and trailing commas (` "nodeLinker": "hoisted",`),
|
|
30
|
+
// so a strict YAML line match misses it — R31 read `null` for a file that said exactly this.
|
|
31
|
+
const match = /["']?nodeLinker["']?\s*:\s*["']?([A-Za-z0-9_-]+)/.exec(readFileSync(modulesYaml, 'utf8'));
|
|
32
|
+
if (match !== null)
|
|
33
|
+
declared = match[1] ?? null;
|
|
34
|
+
}
|
|
35
|
+
const entries = readdirSync(nodeModules).filter((entry) => !entry.startsWith('.'));
|
|
36
|
+
const store = join(nodeModules, '.pnpm');
|
|
37
|
+
let topLevelSymlink = null;
|
|
38
|
+
let virtualStoreLinks = 0;
|
|
39
|
+
for (const entry of entries) {
|
|
40
|
+
const full = join(nodeModules, entry);
|
|
41
|
+
let isLink = false;
|
|
42
|
+
try {
|
|
43
|
+
isLink = lstatSync(full).isSymbolicLink();
|
|
44
|
+
}
|
|
45
|
+
catch {
|
|
46
|
+
continue;
|
|
47
|
+
}
|
|
48
|
+
if (topLevelSymlink === null)
|
|
49
|
+
topLevelSymlink = isLink;
|
|
50
|
+
if (isLink) {
|
|
51
|
+
try {
|
|
52
|
+
const target = readlinkSync(full);
|
|
53
|
+
const resolved = isAbsolute(target) ? target : join(nodeModules, target);
|
|
54
|
+
if (resolved.startsWith(store))
|
|
55
|
+
virtualStoreLinks += 1;
|
|
56
|
+
}
|
|
57
|
+
catch {
|
|
58
|
+
// An unreadable link is not evidence either way.
|
|
59
|
+
}
|
|
60
|
+
}
|
|
61
|
+
}
|
|
62
|
+
const linker = declared === 'isolated' || declared === 'hoisted'
|
|
63
|
+
? declared
|
|
64
|
+
: entries.length === 0
|
|
65
|
+
? 'absent'
|
|
66
|
+
: virtualStoreLinks > 0
|
|
67
|
+
? 'isolated'
|
|
68
|
+
: 'hoisted';
|
|
69
|
+
return {
|
|
70
|
+
linker,
|
|
71
|
+
declared,
|
|
72
|
+
topLevel: entries.length,
|
|
73
|
+
topLevelSymlink,
|
|
74
|
+
virtualStoreLinks,
|
|
75
|
+
pnpmStore: existsSync(store),
|
|
76
|
+
};
|
|
77
|
+
}
|
|
78
|
+
catch {
|
|
79
|
+
return null;
|
|
80
|
+
}
|
|
81
|
+
}
|
|
82
|
+
/**
|
|
83
|
+
* Boot the Host with a one-entry launcher overlay that mounts `hookSource`, wait for the
|
|
84
|
+
* hook to write its sample, then kill the whole process tree.
|
|
85
|
+
*/
|
|
86
|
+
export async function bootAndSampleHost(options) {
|
|
87
|
+
const { dshMain, dshHome, profile, profileDir, hookSource, scratchRoot, config = {}, extraPatch = [], timeoutMs = 180_000, env = process.env, appArgs = [], readinessPort, readinessTimeoutMs = 5_000, unsettledReadinessMs = 20_000, sampleReplaceWindowMs = unsettledReadinessMs,
|
|
88
|
+
/**
|
|
89
|
+
* T-312: how long to wait for the final sample after a provisional one. Tied to the shipped
|
|
90
|
+
* hook's own settle budget (15s) — waiting longer than the hook can take would buy nothing.
|
|
91
|
+
*/
|
|
92
|
+
sampleUpgradeWindowMs = 15_000, settleMs = 1_000, } = options;
|
|
93
|
+
/*
|
|
94
|
+
* THE PROBE'S OWN SCRATCH DIR IS NOT PART OF THE MEASUREMENT (R37).
|
|
95
|
+
*
|
|
96
|
+
* Measured failure this prevents: `rmSync(probeDir)` threw EPERM (Windows held a handle), the
|
|
97
|
+
* exception escaped `bootAndSampleHost`, the executor caught it as a failed `boot` step, and the
|
|
98
|
+
* judge fell through to `probe.boot-timeout` — so a candidate was reported `blocked` because OUR
|
|
99
|
+
* scratch directory could not be deleted
|
|
100
|
+
* (`data/results/probe-matrix-2026-10-29T15-30-00.000Z.json`, `real-unlag`).
|
|
101
|
+
*
|
|
102
|
+
* So: preparation failures and scratch-cleanup failures are recorded as facts on the result and
|
|
103
|
+
* never thrown, and a cleanup failure can no longer destroy a sample we already have.
|
|
104
|
+
*/
|
|
105
|
+
let setupError = null;
|
|
106
|
+
let scratchCleanupError = null;
|
|
107
|
+
let probeDir = null;
|
|
108
|
+
try {
|
|
109
|
+
mkdirSync(scratchRoot, { recursive: true });
|
|
110
|
+
probeDir = mkdtempSync(join(scratchRoot, 'triage-live-'));
|
|
111
|
+
}
|
|
112
|
+
catch (error) {
|
|
113
|
+
const detail = `scratch-setup-failed: ${error instanceof Error ? error.message : String(error)}`;
|
|
114
|
+
return unmeasuredBoot(detail, detail);
|
|
115
|
+
}
|
|
116
|
+
const samplePath = join(probeDir, 'sample.json');
|
|
117
|
+
const patchPath = join(probeDir, 'overlay.patch.yml');
|
|
118
|
+
const hookPath = join(probeDir, 'inventory-hook.mjs');
|
|
119
|
+
let child = null;
|
|
120
|
+
try {
|
|
121
|
+
try {
|
|
122
|
+
copyFileSync(hookSource, hookPath);
|
|
123
|
+
/**
|
|
124
|
+
* Merge the caller's hook config over the defaults instead of appending it.
|
|
125
|
+
*
|
|
126
|
+
* WHY (T-316): `resolveFrom` / `profile` used to be emitted before `config`, so a caller
|
|
127
|
+
* could not override them — and an experiment that needs the hook to talk to a different
|
|
128
|
+
* tree (e.g. one with no projection package, to make the hook write a real `{error}`) had
|
|
129
|
+
* no way to say so. Duplicate YAML keys were the alternative and they are a parser trap.
|
|
130
|
+
* `out` is written LAST on purpose: the sample path is the loop's contract, not a knob.
|
|
131
|
+
*/
|
|
132
|
+
const hookConfig = { resolveFrom: profileDir.replaceAll('\\', '/'), profile, ...config };
|
|
133
|
+
const configLines = [
|
|
134
|
+
...Object.entries(hookConfig)
|
|
135
|
+
.filter(([key]) => key !== 'out')
|
|
136
|
+
.map(([key, value]) => ` ${key}: ${JSON.stringify(value)}`),
|
|
137
|
+
` out: '${samplePath.replaceAll('\\', '/')}'`,
|
|
138
|
+
];
|
|
139
|
+
writeFileSync(patchPath, [
|
|
140
|
+
'- insert:',
|
|
141
|
+
' - id: triage-inventory-probe',
|
|
142
|
+
" name: './inventory-hook.mjs'",
|
|
143
|
+
' config:',
|
|
144
|
+
...configLines,
|
|
145
|
+
// Experiment overlays come after the probe so a row the probe targets is already
|
|
146
|
+
// composed when the overlay patches it (the launcher applies them in order).
|
|
147
|
+
...extraPatch.flatMap((entry) => [
|
|
148
|
+
`- id: ${entry.id}`,
|
|
149
|
+
...(entry.name === undefined ? [] : [` name: '${entry.name}'`]),
|
|
150
|
+
...(entry.disabled === undefined ? [] : [` disabled: ${entry.disabled}`]),
|
|
151
|
+
...(entry.config === undefined
|
|
152
|
+
? []
|
|
153
|
+
: [
|
|
154
|
+
' config:',
|
|
155
|
+
...Object.entries(entry.config).map(([key, value]) => ` ${key}: ${JSON.stringify(value)}`),
|
|
156
|
+
]),
|
|
157
|
+
]),
|
|
158
|
+
'',
|
|
159
|
+
].join('\n'), 'utf8');
|
|
160
|
+
}
|
|
161
|
+
catch (error) {
|
|
162
|
+
setupError = `scratch-setup-failed: ${error instanceof Error ? error.message : String(error)}`;
|
|
163
|
+
try {
|
|
164
|
+
rmSync(probeDir, { recursive: true, force: true });
|
|
165
|
+
}
|
|
166
|
+
catch {
|
|
167
|
+
// Leaving the directory behind is reported by the caller; the reason above is what matters.
|
|
168
|
+
}
|
|
169
|
+
return unmeasuredBoot(setupError, setupError);
|
|
170
|
+
}
|
|
171
|
+
const started = Date.now();
|
|
172
|
+
child = spawn(process.execPath, [dshMain, '--profile', profile, '--patch', patchPath, ...appArgs], {
|
|
173
|
+
env: { ...env, DSH_HOME: dshHome },
|
|
174
|
+
stdio: ['ignore', 'pipe', 'pipe'],
|
|
175
|
+
});
|
|
176
|
+
const spawnedAt = Date.now();
|
|
177
|
+
let stdout = '';
|
|
178
|
+
let stderr = '';
|
|
179
|
+
child.stdout?.on('data', (chunk) => {
|
|
180
|
+
stdout += String(chunk);
|
|
181
|
+
});
|
|
182
|
+
child.stderr?.on('data', (chunk) => {
|
|
183
|
+
stderr += String(chunk);
|
|
184
|
+
});
|
|
185
|
+
/**
|
|
186
|
+
* Wait for a sample we can judge from.
|
|
187
|
+
*
|
|
188
|
+
* A file appearing is not enough (R17): the hook can write `{error}` when its context
|
|
189
|
+
* died mid-compose, and Cordis re-applies the plugin once the services are back — the
|
|
190
|
+
* next apply overwrites the same file with a healthy sample. So we keep the best sample
|
|
191
|
+
* we have and wait, bounded, for a better one instead of freezing the first write.
|
|
192
|
+
*
|
|
193
|
+
* ADR-0008 E narrows who is worth waiting for: an unreadable `{error}` sample still opens
|
|
194
|
+
* the window (that is exactly R17's recovery path), but a FINAL `settled: false` sample is
|
|
195
|
+
* the hook's own last word, so it converges here instead of buying another full window.
|
|
196
|
+
*
|
|
197
|
+
* T-312 adds the other half: a `provisional: true` sample is readable but explicitly not
|
|
198
|
+
* the hook's last word, so it opens a bounded upgrade window instead of converging. The
|
|
199
|
+
* judged budget is the FIRST sample; the verdict uses the final one when it arrives.
|
|
200
|
+
*/
|
|
201
|
+
let payload = null;
|
|
202
|
+
let sampleText = null;
|
|
203
|
+
let firstSampleAtMs = null;
|
|
204
|
+
let firstSampleWrittenAtMs = null;
|
|
205
|
+
let sampleWrittenAtMs = null;
|
|
206
|
+
let sampleReads = 0;
|
|
207
|
+
let waitedForReplacement = false;
|
|
208
|
+
/** R29 (`BS-33`): when the run started waiting on an UNREADABLE sample, and how long that lasted. */
|
|
209
|
+
let replacementWaitStartedAtMs = null;
|
|
210
|
+
let replacementWaitedMs = 0;
|
|
211
|
+
let upgradeStartedAtMs = null;
|
|
212
|
+
let upgraded = false;
|
|
213
|
+
let stoppedBy = 'timeout';
|
|
214
|
+
for (;;) {
|
|
215
|
+
const text = readTextOrNull(samplePath);
|
|
216
|
+
if (text !== null && text !== sampleText) {
|
|
217
|
+
sampleText = text;
|
|
218
|
+
sampleReads += 1;
|
|
219
|
+
payload = parseSample(text);
|
|
220
|
+
const writtenAt = mtimeMsOf(samplePath);
|
|
221
|
+
if (firstSampleAtMs === null) {
|
|
222
|
+
firstSampleAtMs = Date.now();
|
|
223
|
+
firstSampleWrittenAtMs = writtenAt;
|
|
224
|
+
}
|
|
225
|
+
sampleWrittenAtMs = writtenAt ?? sampleWrittenAtMs;
|
|
226
|
+
// A final sample that replaces a provisional one is an upgrade, not a new apply.
|
|
227
|
+
if (sampleReads > 1 && isReadableSample(payload) && !isProvisionalSample(payload))
|
|
228
|
+
upgraded = true;
|
|
229
|
+
}
|
|
230
|
+
const readable = isReadableSample(payload);
|
|
231
|
+
const provisional = readable && isProvisionalSample(payload);
|
|
232
|
+
// R29 (`BS-33`): the replacement window ends the moment a readable sample lands, so its
|
|
233
|
+
// duration is measured here rather than inferred from the loop's end (the T-312 upgrade
|
|
234
|
+
// wait can follow it and would otherwise be folded into the same number).
|
|
235
|
+
if (readable && replacementWaitStartedAtMs !== null && replacementWaitedMs === 0) {
|
|
236
|
+
replacementWaitedMs = Date.now() - replacementWaitStartedAtMs;
|
|
237
|
+
}
|
|
238
|
+
// T-312: when the provisional sample tells us its own settle budget, wait exactly that long
|
|
239
|
+
// plus a margin — waiting less loses upgrades at the boundary, waiting more buys nothing.
|
|
240
|
+
// A payload without the field (older hook) falls back to the configured window.
|
|
241
|
+
const settleBudget = provisional ? settleTimeoutOf(payload) : null;
|
|
242
|
+
const upgradeWindowMs = settleBudget === null ? sampleUpgradeWindowMs : settleBudget + 1_000;
|
|
243
|
+
// `dsh: startup failed: …` is the launcher's own verdict: no sample will follow, and
|
|
244
|
+
// waiting the whole boot timeout for one costs two minutes per broken candidate (R17).
|
|
245
|
+
const startupFailed = `${stdout}\n${stderr}`.includes('startup failed');
|
|
246
|
+
// ADR-0008 E: only an UNREADABLE sample is worth replacing, and only for one window.
|
|
247
|
+
const replacedEnough = firstSampleAtMs !== null && !readable && Date.now() - firstSampleAtMs >= sampleReplaceWindowMs;
|
|
248
|
+
// T-312: a provisional sample is readable, so E would converge on it. Instead give the
|
|
249
|
+
// hook one bounded window to publish the settled snapshot (it cannot exceed its own
|
|
250
|
+
// settle budget, which is what the default window is tied to).
|
|
251
|
+
if (provisional && upgradeStartedAtMs === null)
|
|
252
|
+
upgradeStartedAtMs = Date.now();
|
|
253
|
+
const upgradeEnough = provisional && upgradeStartedAtMs !== null && Date.now() - upgradeStartedAtMs >= upgradeWindowMs;
|
|
254
|
+
if (readable && !provisional) {
|
|
255
|
+
stoppedBy = 'readable-sample';
|
|
256
|
+
break;
|
|
257
|
+
}
|
|
258
|
+
if (Date.now() - started >= timeoutMs) {
|
|
259
|
+
stoppedBy = 'timeout';
|
|
260
|
+
break;
|
|
261
|
+
}
|
|
262
|
+
if (replacedEnough) {
|
|
263
|
+
stoppedBy = 'unreadable-window';
|
|
264
|
+
break;
|
|
265
|
+
}
|
|
266
|
+
if (upgradeEnough) {
|
|
267
|
+
stoppedBy = 'upgrade-window';
|
|
268
|
+
break;
|
|
269
|
+
}
|
|
270
|
+
if (startupFailed) {
|
|
271
|
+
stoppedBy = 'startup-failed';
|
|
272
|
+
break;
|
|
273
|
+
}
|
|
274
|
+
// About to sleep while already holding a sample. R29 (`BS-33`): this is a REPLACEMENT
|
|
275
|
+
// wait only when that sample was unreadable — E's decision. T-312 also sleeps here, but
|
|
276
|
+
// on a readable provisional sample, and that wait is reported as `upgradeWaitedMs`.
|
|
277
|
+
if (firstSampleAtMs !== null && !readable) {
|
|
278
|
+
if (replacementWaitStartedAtMs === null)
|
|
279
|
+
replacementWaitStartedAtMs = Date.now();
|
|
280
|
+
waitedForReplacement = true;
|
|
281
|
+
}
|
|
282
|
+
await new Promise((resolveWait) => setTimeout(resolveWait, 250));
|
|
283
|
+
}
|
|
284
|
+
const collected = payload !== null;
|
|
285
|
+
// The judged number is the FIRST sample (T-312); `finalSeconds` says when the sample the
|
|
286
|
+
// verdict rests on arrived.
|
|
287
|
+
const seconds = Math.round((((firstSampleWrittenAtMs ?? sampleWrittenAtMs) ?? Date.now()) - started) / 100) / 10;
|
|
288
|
+
const finalSeconds = Math.round(((sampleWrittenAtMs ?? Date.now()) - started) / 100) / 10;
|
|
289
|
+
// T-314 boundaries, all relative to `started` (the same origin as the judged budget). Each
|
|
290
|
+
// is set to the previous phase's end until that phase actually runs, so a skipped phase
|
|
291
|
+
// contributes 0 rather than a gap.
|
|
292
|
+
const loopEndedAt = Date.now();
|
|
293
|
+
const replacement = {
|
|
294
|
+
policy: 'error-only',
|
|
295
|
+
waited: waitedForReplacement,
|
|
296
|
+
waitedMs: replacementWaitStartedAtMs === null
|
|
297
|
+
? 0
|
|
298
|
+
: replacementWaitedMs > 0
|
|
299
|
+
? replacementWaitedMs
|
|
300
|
+
: loopEndedAt - replacementWaitStartedAtMs,
|
|
301
|
+
reason: waitedForReplacement ? 'unreadable' : upgradeStartedAtMs === null ? null : 'upgrade',
|
|
302
|
+
samples: sampleReads,
|
|
303
|
+
stoppedBy,
|
|
304
|
+
upgraded,
|
|
305
|
+
upgradeWaitedMs: upgradeStartedAtMs === null ? 0 : loopEndedAt - upgradeStartedAtMs,
|
|
306
|
+
};
|
|
307
|
+
let settleEndedAt = loopEndedAt;
|
|
308
|
+
let readinessEndedAt = loopEndedAt;
|
|
309
|
+
let renderEndedAt = loopEndedAt;
|
|
310
|
+
let http = null;
|
|
311
|
+
let readiness = null;
|
|
312
|
+
let render = null;
|
|
313
|
+
let renderSkipped = null;
|
|
314
|
+
let hostUrl = null;
|
|
315
|
+
if (collected) {
|
|
316
|
+
// Probe while the Host is alive. A server that binds a moment after the tree
|
|
317
|
+
// settles is normal, so this retries instead of sampling one instant.
|
|
318
|
+
await new Promise((resolveWait) => setTimeout(resolveWait, settleMs));
|
|
319
|
+
settleEndedAt = Date.now();
|
|
320
|
+
readinessEndedAt = settleEndedAt;
|
|
321
|
+
renderEndedAt = settleEndedAt;
|
|
322
|
+
// One window, two sources (R17): the launcher's own token URL and the planned port
|
|
323
|
+
// are polled together, because waiting for the URL first (the R15 order) missed a URL
|
|
324
|
+
// that appeared a moment later and then judged the fallback port.
|
|
325
|
+
const unsettled = !isUsableSample(payload);
|
|
326
|
+
const windowMs = unsettled ? unsettledReadinessMs : readinessTimeoutMs;
|
|
327
|
+
if (readinessPort !== undefined || options.render !== undefined) {
|
|
328
|
+
const readinessStarted = Date.now();
|
|
329
|
+
for (;;) {
|
|
330
|
+
if (hostUrl === null)
|
|
331
|
+
hostUrl = extractHostUrl(stdout);
|
|
332
|
+
const port = hostUrl?.port ?? readinessPort;
|
|
333
|
+
if (port !== undefined) {
|
|
334
|
+
http = await probeHttp(port, Math.min(2_000, windowMs));
|
|
335
|
+
if (http.status !== null)
|
|
336
|
+
break;
|
|
337
|
+
}
|
|
338
|
+
if (Date.now() - readinessStarted >= windowMs)
|
|
339
|
+
break;
|
|
340
|
+
await new Promise((resolveWait) => setTimeout(resolveWait, 250));
|
|
341
|
+
}
|
|
342
|
+
const port = hostUrl?.port ?? readinessPort;
|
|
343
|
+
if (port !== undefined) {
|
|
344
|
+
readiness = {
|
|
345
|
+
source: hostUrl === null ? 'plan-port' : 'host-url',
|
|
346
|
+
port,
|
|
347
|
+
outcome: http?.status === null || http === null ? 'timeout' : 'served',
|
|
348
|
+
waited_ms: Date.now() - readinessStarted,
|
|
349
|
+
window_ms: windowMs,
|
|
350
|
+
url_seen: hostUrl !== null,
|
|
351
|
+
};
|
|
352
|
+
}
|
|
353
|
+
readinessEndedAt = Date.now();
|
|
354
|
+
renderEndedAt = readinessEndedAt;
|
|
355
|
+
}
|
|
356
|
+
if (options.render !== undefined) {
|
|
357
|
+
if (options.render.browser === null) {
|
|
358
|
+
renderSkipped = 'no Chromium-family browser was found on this machine (pass --browser or DSH_TRIAGE_BROWSER)';
|
|
359
|
+
}
|
|
360
|
+
else if (hostUrl === null) {
|
|
361
|
+
renderSkipped = 'the Host printed no http://127.0.0.1:<port>/?token=… line, so there was nothing to render';
|
|
362
|
+
}
|
|
363
|
+
else {
|
|
364
|
+
// Still inside the Host's lifetime: the page is served by this process.
|
|
365
|
+
render = await renderUrl({
|
|
366
|
+
browser: options.render.browser,
|
|
367
|
+
url: hostUrl.url,
|
|
368
|
+
// Keep the throwaway browser profile inside this run's scratch dir, so a killed
|
|
369
|
+
// probe cannot leave a browser profile behind under the shared temp root.
|
|
370
|
+
scratchRoot: probeDir,
|
|
371
|
+
...(options.render.timeoutMs === undefined ? {} : { timeoutMs: options.render.timeoutMs }),
|
|
372
|
+
});
|
|
373
|
+
}
|
|
374
|
+
renderEndedAt = Date.now();
|
|
375
|
+
}
|
|
376
|
+
}
|
|
377
|
+
// R21 left ~12s of the boot step unexplained. This is where it gets accounted for: the
|
|
378
|
+
// kill (`taskkill /T /F` walks the tree), the fixed post-kill wait, and the scratch
|
|
379
|
+
// removal all happen AFTER the sample, and none of them were measured before.
|
|
380
|
+
const killStarted = Date.now();
|
|
381
|
+
killTree(child);
|
|
382
|
+
const killMs = Date.now() - killStarted;
|
|
383
|
+
const postKillStarted = Date.now();
|
|
384
|
+
await new Promise((resolveWait) => setTimeout(resolveWait, 1200));
|
|
385
|
+
const postKillWaitMs = Date.now() - postKillStarted;
|
|
386
|
+
const stderrLine = stderr.trimEnd().split(/\r?\n/)[0] ?? '';
|
|
387
|
+
const stdoutLine = stdout.trimEnd().split(/\r?\n/)[0] ?? '';
|
|
388
|
+
const host = {
|
|
389
|
+
status: collected ? 'sampled' : 'no-sample',
|
|
390
|
+
seconds,
|
|
391
|
+
log_sha256: sha256Of(`${stdout}\n${stderr}`),
|
|
392
|
+
// Stderr first, stdout as the real fallback: a healthy `dsh web` prints its URL on
|
|
393
|
+
// stdout, so `?? ` on an always-string value would have hidden it (R15 review finding).
|
|
394
|
+
first_line: sanitizeLogLine(stderrLine !== '' ? stderrLine : stdoutLine).slice(0, 240),
|
|
395
|
+
// Kept short and only on failure: a blocked boot must explain itself, but a healthy
|
|
396
|
+
// one should not carry a log into a publishable artifact. BOTH streams: the launcher
|
|
397
|
+
// prints its own startup diagnostic on stdout (R17).
|
|
398
|
+
error_tail: collected ? null : sanitizeLogLine(`${stdout}\n${stderr}`.trimEnd()).slice(-1500),
|
|
399
|
+
url_printed: extractHostUrl(stdout) !== null,
|
|
400
|
+
startup_failed: `${stdout}\n${stderr}`.includes('startup failed'),
|
|
401
|
+
bind_failed_ports: bindFailedPorts(`${stdout}\n${stderr}`),
|
|
402
|
+
};
|
|
403
|
+
// Measured here rather than in `finally`, because a segment nobody can read is not a
|
|
404
|
+
// measurement. `finally` keeps the same call as a backstop if this throws.
|
|
405
|
+
const scratchStarted = Date.now();
|
|
406
|
+
scratchCleanupError = removeScratch(probeDir);
|
|
407
|
+
const scratchCleanupMs = Date.now() - scratchStarted;
|
|
408
|
+
child = null;
|
|
409
|
+
const segments = {
|
|
410
|
+
spawnMs: spawnedAt - started,
|
|
411
|
+
sampleWaitMs: loopEndedAt - started,
|
|
412
|
+
// T-312: the judged number is the FIRST sample; the final one is recorded beside it.
|
|
413
|
+
sampleMtimeMs: firstSampleWrittenAtMs === null ? null : Math.round(firstSampleWrittenAtMs - started),
|
|
414
|
+
finalSampleMtimeMs: sampleWrittenAtMs === null ? null : Math.round(sampleWrittenAtMs - started),
|
|
415
|
+
settleMs: collected ? settleEndedAt - loopEndedAt : 0,
|
|
416
|
+
readinessMs: readinessEndedAt - settleEndedAt,
|
|
417
|
+
renderMs: renderEndedAt - readinessEndedAt,
|
|
418
|
+
killMs,
|
|
419
|
+
postKillWaitMs,
|
|
420
|
+
scratchCleanupMs,
|
|
421
|
+
totalMs: Date.now() - started,
|
|
422
|
+
};
|
|
423
|
+
if (!collected) {
|
|
424
|
+
return { payload: null, host, error: 'the hook wrote nothing within the timeout', seconds, finalSeconds, http, readiness, render, renderSkipped, segments, replacement, setupError, scratchCleanupError };
|
|
425
|
+
}
|
|
426
|
+
return { payload, host, error: null, seconds, finalSeconds, http, readiness, render, renderSkipped, segments, replacement, setupError, scratchCleanupError };
|
|
427
|
+
}
|
|
428
|
+
finally {
|
|
429
|
+
if (child !== null)
|
|
430
|
+
killTree(child);
|
|
431
|
+
// Backstop only: a failure here must not turn a measurement into a throw (R37).
|
|
432
|
+
removeScratch(probeDir);
|
|
433
|
+
}
|
|
434
|
+
}
|
|
435
|
+
/**
|
|
436
|
+
* Remove the probe's own scratch directory, reporting instead of throwing.
|
|
437
|
+
*
|
|
438
|
+
* @returns `null` on success, else the OS message — the caller publishes it, because a leaked
|
|
439
|
+
* directory in %TEMP% is a fact and silence would hide it.
|
|
440
|
+
*/
|
|
441
|
+
function removeScratch(directory) {
|
|
442
|
+
try {
|
|
443
|
+
rmSync(directory, { recursive: true, force: true });
|
|
444
|
+
return existsSync(directory) ? `the scratch directory is still there after rm -r: ${directory}` : null;
|
|
445
|
+
}
|
|
446
|
+
catch (error) {
|
|
447
|
+
return error instanceof Error ? error.message : String(error);
|
|
448
|
+
}
|
|
449
|
+
}
|
|
450
|
+
/**
|
|
451
|
+
* The result of a boot that never happened because OUR side could not prepare its files.
|
|
452
|
+
*
|
|
453
|
+
* Every field says "not measured": no sample, no URL, no readiness, no segments. The reason is
|
|
454
|
+
* carried twice on purpose — `error` for humans, `setupError` for the judge, which must report
|
|
455
|
+
* `unknown` rather than blaming the candidate (R37).
|
|
456
|
+
*/
|
|
457
|
+
function unmeasuredBoot(reason, setupError) {
|
|
458
|
+
return {
|
|
459
|
+
payload: null,
|
|
460
|
+
host: {
|
|
461
|
+
status: 'no-sample',
|
|
462
|
+
seconds: 0,
|
|
463
|
+
log_sha256: sha256Of(''),
|
|
464
|
+
first_line: '',
|
|
465
|
+
error_tail: null,
|
|
466
|
+
url_printed: false,
|
|
467
|
+
startup_failed: false,
|
|
468
|
+
bind_failed_ports: [],
|
|
469
|
+
},
|
|
470
|
+
error: reason,
|
|
471
|
+
seconds: 0,
|
|
472
|
+
finalSeconds: 0,
|
|
473
|
+
http: null,
|
|
474
|
+
readiness: null,
|
|
475
|
+
render: null,
|
|
476
|
+
renderSkipped: null,
|
|
477
|
+
segments: {
|
|
478
|
+
spawnMs: 0,
|
|
479
|
+
sampleWaitMs: 0,
|
|
480
|
+
sampleMtimeMs: null,
|
|
481
|
+
finalSampleMtimeMs: null,
|
|
482
|
+
settleMs: 0,
|
|
483
|
+
readinessMs: 0,
|
|
484
|
+
renderMs: 0,
|
|
485
|
+
killMs: 0,
|
|
486
|
+
postKillWaitMs: 0,
|
|
487
|
+
scratchCleanupMs: 0,
|
|
488
|
+
totalMs: 0,
|
|
489
|
+
},
|
|
490
|
+
replacement: {
|
|
491
|
+
policy: 'error-only',
|
|
492
|
+
waited: false,
|
|
493
|
+
waitedMs: 0,
|
|
494
|
+
reason: null,
|
|
495
|
+
samples: 0,
|
|
496
|
+
stoppedBy: 'timeout',
|
|
497
|
+
upgraded: false,
|
|
498
|
+
upgradeWaitedMs: 0,
|
|
499
|
+
},
|
|
500
|
+
setupError,
|
|
501
|
+
scratchCleanupError: null,
|
|
502
|
+
};
|
|
503
|
+
}
|
|
504
|
+
/** On Windows the Host keeps helper processes alive; kill the tree, not the parent. */
|
|
505
|
+
export function killTree(child) {
|
|
506
|
+
try {
|
|
507
|
+
child.kill();
|
|
508
|
+
}
|
|
509
|
+
catch {
|
|
510
|
+
// Already gone.
|
|
511
|
+
}
|
|
512
|
+
if (process.platform === 'win32' && child.pid !== undefined) {
|
|
513
|
+
spawnSync('taskkill', ['/pid', String(child.pid), '/T', '/F'], { encoding: 'utf8' });
|
|
514
|
+
}
|
|
515
|
+
}
|
|
516
|
+
/** Deterministic digest used in artifacts instead of storing logs. */
|
|
517
|
+
export function sha256Of(text) {
|
|
518
|
+
return createHash('sha256').update(String(text)).digest('hex');
|
|
519
|
+
}
|
|
520
|
+
/** The dsh CLI entry inside an install directory, or '' when it is not there. */
|
|
521
|
+
export function dshMainOf(installDir) {
|
|
522
|
+
return installDir === '' ? '' : join(installDir, 'node_modules', '@deepseek-ai', 'dsh', 'lib', 'bin.js');
|
|
523
|
+
}
|
|
524
|
+
/** `dsh --version`; the version string is the only thing we take from it. */
|
|
525
|
+
export function readRuntimeVersion(input) {
|
|
526
|
+
const run = spawnSync(process.execPath, [input.dshMain, '--version'], {
|
|
527
|
+
env: input.env,
|
|
528
|
+
encoding: 'utf8',
|
|
529
|
+
timeout: input.timeoutMs,
|
|
530
|
+
killSignal: 'SIGKILL',
|
|
531
|
+
});
|
|
532
|
+
const text = `${run.stdout ?? ''}${run.stderr ?? ''}`.trim();
|
|
533
|
+
const match = /\d+\.\d+\.\d+(?:-[0-9A-Za-z.-]+)?/.exec(text);
|
|
534
|
+
if (run.status !== 0 || match === null) {
|
|
535
|
+
return { version: null, detail: text === '' ? `dsh --version exited ${run.status ?? 'null'}` : text.slice(0, 240) };
|
|
536
|
+
}
|
|
537
|
+
return { version: match[0], detail: match[0] };
|
|
538
|
+
}
|
|
539
|
+
/**
|
|
540
|
+
* Environment for a child that may run pnpm, with the operator's npm user config redirected.
|
|
541
|
+
*
|
|
542
|
+
* WHY: `scrubbedEnv` drops secret-looking env vars, but credentials also live in `~/.npmrc`,
|
|
543
|
+
* which pnpm reads on its own. Measured in R20: a failing install printed
|
|
544
|
+
* `An authorization header was used: Bearer npm_[hidden]` until `npm_config_userconfig`
|
|
545
|
+
* pointed at an empty file inside the sandbox. We do not read that file (铁律 4) — we simply
|
|
546
|
+
* stop inheriting it.
|
|
547
|
+
*
|
|
548
|
+
* The PROFILE's own `.npmrc` is untouched, so T-305b (a profile-level registry that must be
|
|
549
|
+
* unreachable) still works: pnpm reads project config separately from user config.
|
|
550
|
+
*/
|
|
551
|
+
export function sandboxNpmEnv(env, dshHome) {
|
|
552
|
+
const userconfig = join(dshHome, 'probe-user-npmrc');
|
|
553
|
+
try {
|
|
554
|
+
if (!existsSync(userconfig))
|
|
555
|
+
writeFileSync(userconfig, '', 'utf8');
|
|
556
|
+
}
|
|
557
|
+
catch {
|
|
558
|
+
// If the sandbox cannot take the file, the env still points at a path that will not
|
|
559
|
+
// resolve — pnpm then behaves as "no user config", which is the safe side of this.
|
|
560
|
+
}
|
|
561
|
+
// Both spellings on purpose: pnpm reads the lower-case one, npm-compatible tools the upper.
|
|
562
|
+
return { ...env, npm_config_userconfig: userconfig, NPM_CONFIG_USERCONFIG: userconfig };
|
|
563
|
+
}
|
|
564
|
+
const ERROR_CODE = /\bERR_[A-Z0-9_]{2,}\b/;
|
|
565
|
+
/** One line of package-manager output, stripped of decoration, URLs' secrets and length. */
|
|
566
|
+
export function sanitizeDiagnosisLine(line) {
|
|
567
|
+
const stripped = line
|
|
568
|
+
// ANSI colour, then the box-drawing/arrow prefixes pnpm puts on `×`/`╰─▶` lines.
|
|
569
|
+
.replace(/\u001b\[[0-9;]*m/g, '')
|
|
570
|
+
.replace(/^[\s>×✖✗╰├│└─▶›—·•]+/u, '')
|
|
571
|
+
.replace(/\s+/g, ' ')
|
|
572
|
+
.trim();
|
|
573
|
+
// A private registry URL can carry credentials in the userinfo part …
|
|
574
|
+
const noUserInfo = stripped.replace(/\b([a-z][a-z0-9+.-]*:\/\/)[^\s/@]+@/gi, '$1');
|
|
575
|
+
// … or a token in the query string. Neither ever belongs in an artifact.
|
|
576
|
+
const noQuery = noUserInfo.replace(/(\b[a-z][a-z0-9+.-]*:\/\/[^\s?#]+)[?#][^\s]*/gi, '$1');
|
|
577
|
+
return sanitizeLogLine(noQuery).slice(0, 240);
|
|
578
|
+
}
|
|
579
|
+
/** Does this line say anything beyond its label? (`Error:` alone does not.) */
|
|
580
|
+
function substantive(text) {
|
|
581
|
+
return text.replace(/[^A-Za-z0-9]/g, '').length >= 8;
|
|
582
|
+
}
|
|
583
|
+
/**
|
|
584
|
+
* Package names whose build scripts the package manager refused to run.
|
|
585
|
+
*
|
|
586
|
+
* WHY THIS IS PARSED FROM THE RAW OUTPUT AND NOT FROM `key_line`: pnpm wraps the list over
|
|
587
|
+
* several lines and `key_line` is one line (`Ignored build scripts: a@1.0.0,` — R21 measured
|
|
588
|
+
* exactly that truncation). Membership in this list is what tells "the candidate was not
|
|
589
|
+
* built" apart from "the profile I copied was not built", and those need opposite verdicts.
|
|
590
|
+
*/
|
|
591
|
+
export function ignoredBuildPackages(text) {
|
|
592
|
+
const marker = text.indexOf('Ignored build scripts');
|
|
593
|
+
if (marker === -1)
|
|
594
|
+
return [];
|
|
595
|
+
// The list ends at the first blank line; 800 characters is ample for any realistic profile.
|
|
596
|
+
const tail = text.slice(marker, marker + 800);
|
|
597
|
+
const stop = tail.search(/\r?\n\s*\r?\n/);
|
|
598
|
+
const block = stop === -1 ? tail : tail.slice(0, stop);
|
|
599
|
+
const names = new Set();
|
|
600
|
+
for (const match of block.matchAll(/(@?[a-zA-Z0-9][a-zA-Z0-9._/-]*)@\d+\.\d+\.\d+/g)) {
|
|
601
|
+
if (match[1] !== undefined)
|
|
602
|
+
names.add(match[1]);
|
|
603
|
+
}
|
|
604
|
+
return [...names];
|
|
605
|
+
}
|
|
606
|
+
/**
|
|
607
|
+
* The line that explains `code`.
|
|
608
|
+
*
|
|
609
|
+
* pnpm splits a failure across lines: `Error: ERR_PNPM_IGNORED_BUILDS` names the code, and
|
|
610
|
+
* the very next lines carry the cause (`Ignored build scripts: …`). Publishing only the code
|
|
611
|
+
* line would leave the reader with the same dead end as an exit code (R19 measured this).
|
|
612
|
+
* So: use the code line when it explains itself, otherwise the first explanatory line below
|
|
613
|
+
* it — never the harness's own `dsh: …` line and never a `help:`/`hint:` line, which are
|
|
614
|
+
* pointers, not causes.
|
|
615
|
+
*/
|
|
616
|
+
function explanationFor(text, code) {
|
|
617
|
+
const lines = text.split(/\r?\n/);
|
|
618
|
+
const index = lines.findIndex((line) => line.includes(code));
|
|
619
|
+
if (index === -1)
|
|
620
|
+
return null;
|
|
621
|
+
const raw = lines[index];
|
|
622
|
+
if (raw === undefined)
|
|
623
|
+
return null;
|
|
624
|
+
const codeLine = sanitizeDiagnosisLine(raw);
|
|
625
|
+
if (substantive(codeLine.replace(code, '')))
|
|
626
|
+
return codeLine;
|
|
627
|
+
for (const line of lines.slice(index + 1, index + 9)) {
|
|
628
|
+
const clean = sanitizeDiagnosisLine(line);
|
|
629
|
+
if (clean === '')
|
|
630
|
+
continue;
|
|
631
|
+
// `dsh: plugin command failed; diagnostics: <path>` is the launcher talking about itself:
|
|
632
|
+
// it names no cause, and taking it would hide the package manager's own sentence (R19:
|
|
633
|
+
// the missing-package run published exactly that line before this filter existed).
|
|
634
|
+
if (/^dsh:/i.test(clean))
|
|
635
|
+
continue;
|
|
636
|
+
if (/^(help|hint|note|usage)\s*:/i.test(clean))
|
|
637
|
+
continue;
|
|
638
|
+
// Either pnpm's `label: detail` shape, or a plain sentence worth reading.
|
|
639
|
+
if (/^[a-z][a-z ]{0,24}:\s*\S/i.test(clean) || clean.replace(/[^A-Za-z0-9]/g, '').length >= 20)
|
|
640
|
+
return clean;
|
|
641
|
+
}
|
|
642
|
+
return codeLine === '' ? null : codeLine;
|
|
643
|
+
}
|
|
644
|
+
/** First line that reads like an error, else the first line that says anything at all. */
|
|
645
|
+
function firstErrorLine(text) {
|
|
646
|
+
const lines = text.split(/\r?\n/).map(sanitizeDiagnosisLine).filter((line) => line !== '');
|
|
647
|
+
const loud = lines.find((line) => /\b(error|failed|cannot|unable|refused|denied|ignored)\b/i.test(line));
|
|
648
|
+
return loud ?? lines[0] ?? null;
|
|
649
|
+
}
|
|
650
|
+
/**
|
|
651
|
+
* Pure core of {@link installDiagnosis}: no filesystem, so every rule is testable.
|
|
652
|
+
*
|
|
653
|
+
* Order matters and is measured, not assumed: the launcher's own output wins, because the
|
|
654
|
+
* diagnostics log is a *summary* that drops the code (R19 fact F34).
|
|
655
|
+
*/
|
|
656
|
+
export function diagnosisFromText(input) {
|
|
657
|
+
const launcher = input.launcher;
|
|
658
|
+
const log = input.log ?? null;
|
|
659
|
+
const launcherCode = ERROR_CODE.exec(launcher)?.[0] ?? null;
|
|
660
|
+
const logCode = log === null ? null : (ERROR_CODE.exec(log)?.[0] ?? null);
|
|
661
|
+
const code = launcherCode ?? logCode;
|
|
662
|
+
if (code !== null) {
|
|
663
|
+
const fromLauncher = launcherCode !== null;
|
|
664
|
+
const text = fromLauncher ? launcher : (log ?? '');
|
|
665
|
+
return {
|
|
666
|
+
code,
|
|
667
|
+
key_line: explanationFor(text, code) ?? firstErrorLine(text),
|
|
668
|
+
source: fromLauncher ? 'launcher' : 'diagnostics-log',
|
|
669
|
+
};
|
|
670
|
+
}
|
|
671
|
+
const keyLine = firstErrorLine(launcher) ?? (log === null ? null : firstErrorLine(log));
|
|
672
|
+
return {
|
|
673
|
+
code: null,
|
|
674
|
+
key_line: keyLine,
|
|
675
|
+
source: keyLine === null ? 'none' : log !== null && firstErrorLine(launcher) === null ? 'diagnostics-log' : 'launcher',
|
|
676
|
+
};
|
|
677
|
+
}
|
|
678
|
+
/**
|
|
679
|
+
* Extract the failure reason from a launcher run, reading its diagnostics log when named.
|
|
680
|
+
*
|
|
681
|
+
* The log is capped at 64KB and read through the same guard as {@link failureEndpoints}: a
|
|
682
|
+
* missing log is normal (the install may fail before one is written).
|
|
683
|
+
*/
|
|
684
|
+
export function installDiagnosis(output) {
|
|
685
|
+
const named = /diagnostics:\s*(.+?\.log)/.exec(output)?.[1];
|
|
686
|
+
let log = null;
|
|
687
|
+
if (named !== undefined) {
|
|
688
|
+
try {
|
|
689
|
+
log = readFileSync(named.trim(), 'utf8').slice(0, 64 * 1024);
|
|
690
|
+
}
|
|
691
|
+
catch {
|
|
692
|
+
log = null;
|
|
693
|
+
}
|
|
694
|
+
}
|
|
695
|
+
return diagnosisFromText({ launcher: output, log });
|
|
696
|
+
}
|
|
697
|
+
/**
|
|
698
|
+
* `dsh plugin --profile <p> add <spec>` forwards to pnpm inside the profile.
|
|
699
|
+
*
|
|
700
|
+
* The candidate is installed into the SANDBOX home only; the caller passes the env, and
|
|
701
|
+
* that env must already be scrubbed (see `scrubbedEnv`).
|
|
702
|
+
*/
|
|
703
|
+
export function runInstall(input) {
|
|
704
|
+
return runPluginCommand({
|
|
705
|
+
argv: pluginArgv({ dshMain: input.dshMain, profile: input.profile, verb: 'add', spec: input.candidate }),
|
|
706
|
+
dshHome: input.dshHome,
|
|
707
|
+
timeoutMs: input.timeoutMs,
|
|
708
|
+
env: input.env,
|
|
709
|
+
});
|
|
710
|
+
}
|
|
711
|
+
/**
|
|
712
|
+
* The argv of `dsh plugin …`, in one place.
|
|
713
|
+
*
|
|
714
|
+
* WHY IT IS EXPORTED: the credential-source audit (T-313) has to run the launcher with an env
|
|
715
|
+
* it builds itself, so that it can prove a source WOULD leak if it were not closed. Copying the
|
|
716
|
+
* argv into the audit would make the audit drift away from what the probe really runs.
|
|
717
|
+
*/
|
|
718
|
+
export function pluginArgv(input) {
|
|
719
|
+
const base = [input.dshMain, 'plugin', '--profile', input.profile, input.verb];
|
|
720
|
+
return input.spec === undefined ? base : [...base, input.spec];
|
|
721
|
+
}
|
|
722
|
+
/**
|
|
723
|
+
* `dsh plugin --profile <p> install` — install the PROFILE's own dependencies.
|
|
724
|
+
*
|
|
725
|
+
* WHY THIS IS A SEPARATE ENTRY POINT (T-304 / R20 fact F39): `dsh` does NOT install profile
|
|
726
|
+
* dependencies while booting (the R12 pitfall), but `dsh plugin <args>` forwards its arguments
|
|
727
|
+
* straight to pnpm, so `plugin install` does. A copied profile therefore has to run this once
|
|
728
|
+
* before it can boot — and if it fails, that failure belongs to the copy, not to the
|
|
729
|
+
* candidate.
|
|
730
|
+
*/
|
|
731
|
+
export function runProfileInstall(input) {
|
|
732
|
+
return runPluginCommand({
|
|
733
|
+
argv: pluginArgv({ dshMain: input.dshMain, profile: input.profile, verb: 'install' }),
|
|
734
|
+
dshHome: input.dshHome,
|
|
735
|
+
timeoutMs: input.timeoutMs,
|
|
736
|
+
env: input.env,
|
|
737
|
+
});
|
|
738
|
+
}
|
|
739
|
+
/** The one place that spawns a `dsh plugin …` child and reads its result. */
|
|
740
|
+
function runPluginCommand(input) {
|
|
741
|
+
const run = spawnSync(process.execPath, [...input.argv], {
|
|
742
|
+
// R20: the operator's `~/.npmrc` must not travel into the sandbox (see `sandboxNpmEnv`).
|
|
743
|
+
env: sandboxNpmEnv(input.env, input.dshHome),
|
|
744
|
+
encoding: 'utf8',
|
|
745
|
+
timeout: input.timeoutMs,
|
|
746
|
+
killSignal: 'SIGKILL',
|
|
747
|
+
});
|
|
748
|
+
const text = `${run.stdout ?? ''}${run.stderr ?? ''}`.trim();
|
|
749
|
+
const lastLine = text.split(/\r?\n/).filter((line) => line.trim() !== '').slice(-1)[0] ?? '';
|
|
750
|
+
return {
|
|
751
|
+
exitCode: run.status,
|
|
752
|
+
detail: lastLine.slice(0, 240),
|
|
753
|
+
endpoints: failureEndpoints(text),
|
|
754
|
+
// T-310: the launcher's last line names no cause; this is the line that does. A passing
|
|
755
|
+
// install has nothing to diagnose — publishing "Already up to date" as a diagnosis would
|
|
756
|
+
// make a healthy run look like a failed one.
|
|
757
|
+
diagnosis: run.status === 0 ? { code: null, key_line: null, source: 'none' } : installDiagnosis(text),
|
|
758
|
+
authUsed: /authorization header was used/i.test(text),
|
|
759
|
+
ignoredPackages: ignoredBuildPackages(text),
|
|
760
|
+
};
|
|
761
|
+
}
|
|
762
|
+
/**
|
|
763
|
+
* Endpoints named by a failed install, taken from the diagnostics log when the launcher
|
|
764
|
+
* points at one. Pure and exported so the sanitising rules are testable without a sandbox.
|
|
765
|
+
*/
|
|
766
|
+
export function failureEndpoints(output) {
|
|
767
|
+
const diagnostics = /diagnostics:\s*(.+?\.log)/.exec(output)?.[1];
|
|
768
|
+
let text = output;
|
|
769
|
+
if (diagnostics !== undefined) {
|
|
770
|
+
try {
|
|
771
|
+
text = `${text}\n${readFileSync(diagnostics.trim(), 'utf8').slice(0, 64 * 1024)}`;
|
|
772
|
+
}
|
|
773
|
+
catch {
|
|
774
|
+
// The log is optional; the output itself may still carry the URL.
|
|
775
|
+
}
|
|
776
|
+
}
|
|
777
|
+
const found = new Set();
|
|
778
|
+
for (const match of text.matchAll(/https?:\/\/[^\s'"<>)\]]+/g)) {
|
|
779
|
+
// pnpm writes `http://host/pkg: error …`; trailing punctuation is not part of the URL.
|
|
780
|
+
const raw = match[0].replace(/[.,;:]+$/, '');
|
|
781
|
+
try {
|
|
782
|
+
const url = new URL(raw);
|
|
783
|
+
// Strip credentials, query and fragment: a private registry URL can carry a token.
|
|
784
|
+
url.username = '';
|
|
785
|
+
url.password = '';
|
|
786
|
+
url.search = '';
|
|
787
|
+
url.hash = '';
|
|
788
|
+
found.add(url.toString());
|
|
789
|
+
}
|
|
790
|
+
catch {
|
|
791
|
+
// Not a URL we can parse; do not publish a half-redacted string.
|
|
792
|
+
}
|
|
793
|
+
if (found.size >= 5)
|
|
794
|
+
break;
|
|
795
|
+
}
|
|
796
|
+
return [...found];
|
|
797
|
+
}
|
|
798
|
+
/**
|
|
799
|
+
* Is something listening?
|
|
800
|
+
*
|
|
801
|
+
* `redirect: 'manual'` is not a detail: with a token the first response is a 303 plus
|
|
802
|
+
* `Set-Cookie`, and `fetch` following it turns a healthy Host into a 401 (R12 pitfall).
|
|
803
|
+
*/
|
|
804
|
+
export async function probeHttp(port, timeoutMs) {
|
|
805
|
+
try {
|
|
806
|
+
const response = await fetch(`http://127.0.0.1:${port}/`, {
|
|
807
|
+
redirect: 'manual',
|
|
808
|
+
signal: AbortSignal.timeout(timeoutMs),
|
|
809
|
+
});
|
|
810
|
+
return { status: response.status, detail: `HTTP ${response.status}` };
|
|
811
|
+
}
|
|
812
|
+
catch (error) {
|
|
813
|
+
const detail = error instanceof Error ? `${error.name}: ${error.message}` : String(error);
|
|
814
|
+
return { status: null, detail: detail.slice(0, 240) };
|
|
815
|
+
}
|
|
816
|
+
}
|
|
817
|
+
/**
|
|
818
|
+
* Strip the launcher's token before any log line can reach an artifact.
|
|
819
|
+
*
|
|
820
|
+
* `dsh web: http://127.0.0.1:53052/?token=…` is the one line we want to keep for diagnosis,
|
|
821
|
+
* and it is also the one line that must never be published. F-2 (R16) taught us that a
|
|
822
|
+
* single unredacted field is enough to leak; this is that field.
|
|
823
|
+
*/
|
|
824
|
+
export function sanitizeLogLine(line) {
|
|
825
|
+
return line.replace(/([?&]token=)[^\s"'&]+/gi, '$1<redacted>');
|
|
826
|
+
}
|
|
827
|
+
/**
|
|
828
|
+
* Ports named by a bind failure in the Host log.
|
|
829
|
+
*
|
|
830
|
+
* WHY: on this machine `netsh int ipv4 show excludedportrange protocol=tcp` lists
|
|
831
|
+
* 53461–53560, and the plan's deterministic port landed on **53506**, so the Host's own
|
|
832
|
+
* `webserver` row died with `listen EACCES`. That failure has nothing to do with the
|
|
833
|
+
* candidate, and the judge needs the port number to say so (R17).
|
|
834
|
+
*/
|
|
835
|
+
export function bindFailedPorts(log) {
|
|
836
|
+
const found = new Set();
|
|
837
|
+
for (const match of log.matchAll(/listen (?:EACCES|EADDRINUSE|EADDRNOTAVAIL|EAFNOSUPPORT)[^\n]*?:(\d{2,5})\b/g)) {
|
|
838
|
+
const port = Number(match[1]);
|
|
839
|
+
if (Number.isInteger(port) && port > 0 && port <= 65_535)
|
|
840
|
+
found.add(port);
|
|
841
|
+
}
|
|
842
|
+
return [...found].sort((left, right) => left - right);
|
|
843
|
+
}
|
|
844
|
+
/**
|
|
845
|
+
* A port the OS is willing to hand out right now.
|
|
846
|
+
*
|
|
847
|
+
* The deterministic `basePort` in the plan is a *preference*: Windows excludes ranges
|
|
848
|
+
* dynamically (Hyper-V/WSL reservations change during a session), so a hash-picked port can
|
|
849
|
+
* be unbindable while a neighbouring one is fine. Binding :0 asks the OS for one it will
|
|
850
|
+
* actually allow. The port is released immediately; a Host that boots a second later can
|
|
851
|
+
* still lose the race, which is why the judge also recognises a bind failure on our port.
|
|
852
|
+
*/
|
|
853
|
+
export function findFreePort() {
|
|
854
|
+
return new Promise((resolvePort) => {
|
|
855
|
+
const server = createServer();
|
|
856
|
+
let settled = false;
|
|
857
|
+
const done = (port) => {
|
|
858
|
+
if (settled)
|
|
859
|
+
return;
|
|
860
|
+
settled = true;
|
|
861
|
+
try {
|
|
862
|
+
server.close();
|
|
863
|
+
}
|
|
864
|
+
catch {
|
|
865
|
+
// Nothing to close.
|
|
866
|
+
}
|
|
867
|
+
resolvePort(port);
|
|
868
|
+
};
|
|
869
|
+
server.once('error', () => done(null));
|
|
870
|
+
server.listen(0, '127.0.0.1', () => {
|
|
871
|
+
const address = server.address();
|
|
872
|
+
done(address !== null && typeof address === 'object' ? address.port : null);
|
|
873
|
+
});
|
|
874
|
+
});
|
|
875
|
+
}
|
|
876
|
+
/** Read the sample file, or `null` when it is not there (yet). BOM stripped: PowerShell writes one. */
|
|
877
|
+
function readTextOrNull(path) {
|
|
878
|
+
try {
|
|
879
|
+
return readFileSync(path, 'utf8').replace(/^\uFEFF/, '');
|
|
880
|
+
}
|
|
881
|
+
catch {
|
|
882
|
+
return null;
|
|
883
|
+
}
|
|
884
|
+
}
|
|
885
|
+
/** Write time of the sample, used as the honest "spawn → sample" instant (not "when we polled"). */
|
|
886
|
+
function mtimeMsOf(path) {
|
|
887
|
+
try {
|
|
888
|
+
return statSync(path).mtimeMs;
|
|
889
|
+
}
|
|
890
|
+
catch {
|
|
891
|
+
return null;
|
|
892
|
+
}
|
|
893
|
+
}
|
|
894
|
+
function parseSample(text) {
|
|
895
|
+
try {
|
|
896
|
+
return JSON.parse(text);
|
|
897
|
+
}
|
|
898
|
+
catch {
|
|
899
|
+
// Unparseable is a measurement failure, not "zero rows": keep it shaped like the hook's
|
|
900
|
+
// own error payload so one code path reports both.
|
|
901
|
+
return { error: { code: 'unparseable', message: 'the sample file is not valid JSON' } };
|
|
902
|
+
}
|
|
903
|
+
}
|
|
904
|
+
/**
|
|
905
|
+
* Can a verdict rest on this sample?
|
|
906
|
+
*
|
|
907
|
+
* `{error}` means the hook could not read the tree (e.g. `inactive context` while the Host
|
|
908
|
+
* was still composing) and `settled: false` means rows were still moving when it gave up.
|
|
909
|
+
* Both are measurement failures: the executor must report `unknown`, never `blocked`.
|
|
910
|
+
*
|
|
911
|
+
* DO NOT REDEFINE THIS (ADR-0008 E): the replacement window narrowed to `{error}`, but
|
|
912
|
+
* "usable" still means "settled and readable". The judge and the assertions decide verdicts
|
|
913
|
+
* from this predicate, so weakening it here would turn a race into a `blocked`.
|
|
914
|
+
*/
|
|
915
|
+
export function isUsableSample(payload) {
|
|
916
|
+
if (payload === null || typeof payload !== 'object' || Array.isArray(payload))
|
|
917
|
+
return false;
|
|
918
|
+
const record = payload;
|
|
919
|
+
if (record['error'] !== undefined && record['error'] !== null)
|
|
920
|
+
return false;
|
|
921
|
+
return record['settled'] !== false;
|
|
922
|
+
}
|
|
923
|
+
/**
|
|
924
|
+
* Did the hook manage to write *something we can interpret*?
|
|
925
|
+
*
|
|
926
|
+
* This is deliberately weaker than {@link isUsableSample}: a `settled: false` sample is a
|
|
927
|
+
* real reading of a tree that was still moving (the hook spent its settle budget and then
|
|
928
|
+
* wrote down what it saw), while an `{error}` payload is the hook saying it could not read at
|
|
929
|
+
* all. Only the second one can be improved by Cordis re-applying the plugin, which is the
|
|
930
|
+
* whole reason the replacement window exists (ADR-0008 E).
|
|
931
|
+
*/
|
|
932
|
+
export function isReadableSample(payload) {
|
|
933
|
+
if (payload === null || typeof payload !== 'object' || Array.isArray(payload))
|
|
934
|
+
return false;
|
|
935
|
+
const record = payload;
|
|
936
|
+
return record['error'] === undefined || record['error'] === null;
|
|
937
|
+
}
|
|
938
|
+
/**
|
|
939
|
+
* Is this the hook's first, not-yet-settled write? (T-312)
|
|
940
|
+
*
|
|
941
|
+
* A provisional sample is readable on purpose (the phase table exists), but it explicitly says
|
|
942
|
+
* `settled: false` and `provisional: true`. The executor may rest an `unknown` on it, and it
|
|
943
|
+
* keeps a bounded window open for the final write. Anything that is not explicitly marked is
|
|
944
|
+
* treated as final, so an older hook (no field) behaves exactly as before.
|
|
945
|
+
*/
|
|
946
|
+
export function isProvisionalSample(payload) {
|
|
947
|
+
if (payload === null || typeof payload !== 'object' || Array.isArray(payload))
|
|
948
|
+
return false;
|
|
949
|
+
return payload['provisional'] === true;
|
|
950
|
+
}
|
|
951
|
+
/** The settle budget the hook published with its provisional sample (T-312), or `null`. */
|
|
952
|
+
function settleTimeoutOf(payload) {
|
|
953
|
+
if (payload === null || typeof payload !== 'object' || Array.isArray(payload))
|
|
954
|
+
return null;
|
|
955
|
+
const value = payload['settle_timeout_ms'];
|
|
956
|
+
return typeof value === 'number' && Number.isFinite(value) && value > 0 ? value : null;
|
|
957
|
+
}
|
|
958
|
+
/** Remove the sandbox home and report whether it is really gone. */
|
|
959
|
+
export function removeSandbox(directory) {
|
|
960
|
+
try {
|
|
961
|
+
rmSync(directory, { recursive: true, force: true });
|
|
962
|
+
}
|
|
963
|
+
catch (error) {
|
|
964
|
+
return { removed: false, detail: error instanceof Error ? error.message : String(error) };
|
|
965
|
+
}
|
|
966
|
+
return { removed: !existsSync(directory), detail: directory };
|
|
967
|
+
}
|
|
968
|
+
/**
|
|
969
|
+
* Environment handed to every sandbox child.
|
|
970
|
+
*
|
|
971
|
+
* Credentials are dropped, not passed through: `PROJECT_RULES.md` 铁律 4 forbids injecting
|
|
972
|
+
* real secrets into a probe sandbox, and a plugin that needs one must be reported as
|
|
973
|
+
* unverified rather than measured with the user's key.
|
|
974
|
+
*/
|
|
975
|
+
export function scrubbedEnv(base, overrides) {
|
|
976
|
+
const out = {};
|
|
977
|
+
for (const [key, value] of Object.entries(base)) {
|
|
978
|
+
if (value === undefined)
|
|
979
|
+
continue;
|
|
980
|
+
if (/(API_?KEY|TOKEN|SECRET|PASSWORD|PASSWD|CREDENTIAL|_AUTH)/i.test(key))
|
|
981
|
+
continue;
|
|
982
|
+
out[key] = value;
|
|
983
|
+
}
|
|
984
|
+
return { ...out, ...overrides };
|
|
985
|
+
}
|
|
986
|
+
//# sourceMappingURL=host.js.map
|