@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/dist/exec.js ADDED
@@ -0,0 +1,1281 @@
1
+ /**
2
+ * Probe executor (M3 / T-301): run a plan, then judge what actually happened.
3
+ *
4
+ * WHY THE EXECUTOR IS SPLIT FROM THE JUDGE: the runner is I/O (install, boot, http,
5
+ * cleanup) and the judge is a pure function over the observed facts. Everything a
6
+ * reviewer would want to argue about — "is a `null` phase a pass?", "does an HTTP 200
7
+ * mean the UI works?" — lives in {@link judgeProbe}, which the tests can drive with
8
+ * hand-written facts and no sandbox at all.
9
+ *
10
+ * CONTRACT (docs/specs/M3-probe.md):
11
+ * - `cleanup` always runs, even when an earlier step threw;
12
+ * - the candidate row must be identified by module name and must be unique — 0 rows and
13
+ * ≥2 rows are different verdicts, and neither is rounded to "fine";
14
+ * - assertions this layer cannot measure (`namespace-diff`) are reported as `unmeasured`,
15
+ * never omitted and never `passed`; `client-rendered` is measured since R15, and stays
16
+ * `unmeasured` only when the machine has no browser (T-302);
17
+ * - `go` means "installed + booted + served + row active (+ page mounted)". It does NOT
18
+ * mean "works", and it is never a security statement.
19
+ */
20
+ import { parseInventorySnapshot } from '@dsh-triage/core';
21
+ /**
22
+ * Install gets its own budget: a registry install is network-bound and cannot be held to
23
+ * the 20s boot budget. `docs/specs/M3-probe.md` §4 keeps the two numbers apart on purpose.
24
+ */
25
+ export const DEFAULT_PROBE_TIMEOUTS = {
26
+ installMs: 180_000,
27
+ bootMs: 120_000,
28
+ httpMs: 5_000,
29
+ cleanupMs: 10_000,
30
+ };
31
+ export async function executeProbe(input, deps) {
32
+ const timeouts = { ...DEFAULT_PROBE_TIMEOUTS, ...(input.timeouts ?? {}) };
33
+ const run = {
34
+ candidate: { spec: input.plan.candidate, package: input.candidatePackage },
35
+ dshMain: input.dshMain,
36
+ sandboxHome: input.plan.sandboxHome,
37
+ profileOrigin: input.plan.profileOrigin,
38
+ profileSourceDir: input.plan.profileSource === null ? null : input.plan.profileSource.dir,
39
+ port: input.plan.port,
40
+ runtimeVersion: null,
41
+ steps: [],
42
+ timings: { installMs: null, bootToSampleMs: null, bootToFinalSampleMs: null, httpMs: null, renderMs: null, cleanupMs: null, bootSegments: null },
43
+ sample: null,
44
+ sampleReplacement: null,
45
+ http: null,
46
+ readiness: null,
47
+ render: null,
48
+ renderSkipped: null,
49
+ urlPrinted: false,
50
+ firstLine: null,
51
+ errorTail: null,
52
+ startupFailed: false,
53
+ bindFailedPorts: [],
54
+ bootSetupError: null,
55
+ bootScratchCleanupError: null,
56
+ installDiagnosis: null,
57
+ installAuthUsed: null,
58
+ installIgnoredPackages: [],
59
+ installBuildRefusedProfileOnly: false,
60
+ nodeLayout: null,
61
+ candidateRegistered: null,
62
+ profileCopy: null,
63
+ cleanup: { removed: false, portClosed: false, detail: 'cleanup did not run' },
64
+ abortedAt: null,
65
+ };
66
+ try {
67
+ // The sequence is a separate function on purpose: a `return` inside this `try` would
68
+ // be evaluated *before* `finally` ran, and the returned record would carry the
69
+ // pre-cleanup state (a bug the first draft had).
70
+ await runSequence(run, deps, input, timeouts);
71
+ }
72
+ finally {
73
+ const started = deps.now();
74
+ try {
75
+ run.cleanup = await deps.cleanup({
76
+ dshHome: input.plan.sandboxHome,
77
+ port: input.plan.port,
78
+ ...(run.readiness === null || run.readiness.port === input.plan.port ? {} : { extraPorts: [run.readiness.port] }),
79
+ timeoutMs: timeouts.cleanupMs,
80
+ });
81
+ }
82
+ catch (error) {
83
+ run.cleanup = { removed: false, portClosed: false, detail: error instanceof Error ? error.message : String(error) };
84
+ }
85
+ run.timings.cleanupMs = deps.now() - started;
86
+ run.steps.push({
87
+ id: 'cleanup',
88
+ status: run.cleanup.removed && run.cleanup.portClosed ? 'passed' : 'failed',
89
+ ms: run.timings.cleanupMs,
90
+ detail: run.cleanup.detail,
91
+ exitCode: null,
92
+ });
93
+ }
94
+ return freeze(run);
95
+ }
96
+ /** Steps in contract order; stops at the first step that makes the rest meaningless. */
97
+ async function runSequence(run, deps, input, timeouts) {
98
+ await runStep(run, deps, 'runtime', async () => {
99
+ const read = await deps.readRuntimeVersion({ dshMain: input.dshMain, timeoutMs: timeouts.httpMs });
100
+ run.runtimeVersion = read.version;
101
+ return read.version === null
102
+ ? { status: 'failed', detail: read.detail, exitCode: null }
103
+ : { status: 'passed', detail: `runtime ${read.version}`, exitCode: null };
104
+ });
105
+ if (run.abortedAt !== null)
106
+ return;
107
+ if (input.plan.profileSource !== null) {
108
+ await runStep(run, deps, 'profile', async () => {
109
+ const prepare = deps.prepareProfile;
110
+ if (prepare === undefined) {
111
+ return { status: 'failed', detail: 'the plan copies a profile but no copier was supplied', exitCode: null };
112
+ }
113
+ const outcome = await prepare({ plan: input.plan, dshMain: input.dshMain, timeoutMs: timeouts.installMs });
114
+ // A build-script refusal is not a failed install: pnpm printed `+ pkg@ver`, it just did not
115
+ // run the scripts (R19 F35, remeasured for profile copies in R21). It is recorded as its
116
+ // own fact because it makes every later failure unattributable — see `judgeProbe`.
117
+ const buildRefused = outcome.install?.code === 'ERR_PNPM_IGNORED_BUILDS';
118
+ run.profileCopy = { origin: input.plan.profileOrigin, ...outcome, buildRefused };
119
+ // A dangling `link:`/`file:` target is checked BEFORE the exit code, because F40 measured
120
+ // that `plugin install` exits 0 in exactly that shape.
121
+ if (outcome.danglingLinks.length > 0) {
122
+ return {
123
+ status: 'failed',
124
+ detail: `dangling local dependencies: ${outcome.danglingLinks.map((link) => `${link.name} (${link.spec})`).join(', ')}`,
125
+ exitCode: outcome.install?.exitCode ?? null,
126
+ };
127
+ }
128
+ if (outcome.install !== null && outcome.install.exitCode !== 0 && !buildRefused) {
129
+ return {
130
+ status: 'failed',
131
+ detail: `the copied profile's dependencies did not install: ${outcome.install.detail}`,
132
+ exitCode: outcome.install.exitCode,
133
+ };
134
+ }
135
+ return {
136
+ status: 'passed',
137
+ detail: `copied ${outcome.copied.join(', ') || 'no declarations'}${outcome.missing.length === 0 ? '' : ` (absent: ${outcome.missing.join(', ')})`}${buildRefused ? ' · dependencies installed, build scripts refused by the package manager' : ' · dependencies installed'}`,
138
+ exitCode: outcome.install?.exitCode ?? null,
139
+ };
140
+ });
141
+ if (run.abortedAt !== null)
142
+ return;
143
+ }
144
+ if (input.skipInstall !== true) {
145
+ await runStep(run, deps, 'install', async () => {
146
+ const result = await deps.install({
147
+ dshMain: input.dshMain,
148
+ dshHome: input.plan.sandboxHome,
149
+ profile: input.plan.profile,
150
+ candidate: input.plan.candidate,
151
+ timeoutMs: timeouts.installMs,
152
+ });
153
+ // Recorded before the status branch: a *passing* install can still have printed a
154
+ // warning, and a failed one is exactly what the judge needs (T-310).
155
+ run.installDiagnosis = result.diagnosis ?? null;
156
+ run.installAuthUsed = result.authUsed ?? null;
157
+ run.installIgnoredPackages = [...(result.ignoredPackages ?? [])];
158
+ /**
159
+ * A copy plan re-reports the PROFILE's unbuilt dependencies every time a candidate is
160
+ * added, and pnpm exits 1 for it (R21 measured: the ignored list was
161
+ * `@deepseek-ai/dsh-subprocess-local, @google/genai, koffi, node-pty, protobufjs` — the
162
+ * candidate was not one of them).
163
+ *
164
+ * WHY THE EXCEPTION IS NARROW: it needs a copied profile (so a template probe keeps R19's
165
+ * strict behaviour) AND a readable ignored list that does not name the candidate. With
166
+ * an unreadable list we stay conservative and block.
167
+ */
168
+ const refused = result.diagnosis?.code === 'ERR_PNPM_IGNORED_BUILDS';
169
+ const ignored = result.ignoredPackages ?? [];
170
+ /**
171
+ * With the sandbox build policy in place (T-304) the same refusal exits 0 and pnpm still
172
+ * prints which packages it did not build, so the exit code alone cannot distinguish
173
+ * "nothing was skipped" from "five native modules were skipped".
174
+ */
175
+ const profileOnly = input.plan.profileSource !== null &&
176
+ ignored.length > 0 &&
177
+ !ignored.includes(input.candidatePackage) &&
178
+ (refused || result.exitCode === 0);
179
+ run.installBuildRefusedProfileOnly = profileOnly;
180
+ if (profileOnly) {
181
+ // The refusal is the profile's, but the command still exited 1 — and R21 measured that
182
+ // the launcher registers the bundle only after a clean run. So do not assume: read the
183
+ // composition back and let the registration decide whether this is measurable.
184
+ const bundles = deps.profileBundles?.({ profileDir: input.plan.sandboxProfileDir }) ?? null;
185
+ const registered = bundles === null ? null : bundles.includes(input.candidatePackage);
186
+ run.candidateRegistered = registered;
187
+ const why = `${result.detail} · the refusal is about the copied profile's own dependencies (${ignored.join(', ')}), not the candidate`;
188
+ if (result.exitCode === 0) {
189
+ // The launcher's own run succeeded, so it registered the bundle; nothing to read back.
190
+ return { status: 'passed', detail: `${why} · the launcher reported success`, exitCode: 0 };
191
+ }
192
+ if (registered === true) {
193
+ return { status: 'passed', detail: `${why} · the candidate is registered in the composition`, exitCode: result.exitCode };
194
+ }
195
+ return {
196
+ status: 'failed',
197
+ detail: `${why} · the candidate was NOT registered in ${registered === null ? 'a composition that could not be read' : 'dsh.profile.bundles'}`,
198
+ exitCode: result.exitCode,
199
+ };
200
+ }
201
+ return result.exitCode === 0
202
+ ? { status: 'passed', detail: result.detail, exitCode: result.exitCode }
203
+ : {
204
+ status: 'failed',
205
+ // Naming the endpoint is the difference between "install failed" and "install
206
+ // failed because this profile points at a registry that does not answer".
207
+ detail: result.endpoints === undefined || result.endpoints.length === 0
208
+ ? result.detail
209
+ : `${result.detail} · tried ${result.endpoints.join(', ')}`,
210
+ exitCode: result.exitCode,
211
+ };
212
+ });
213
+ if (run.abortedAt !== null)
214
+ return;
215
+ }
216
+ else {
217
+ run.steps.push({ id: 'install', status: 'skipped', ms: 0, detail: 'skipInstall', exitCode: null });
218
+ }
219
+ /*
220
+ * T-315 residual (R30): record the layout the sandbox ACTUALLY uses, right after install and
221
+ * before boot. Without this the artifact can only say "this hoisted shape was not misjudged";
222
+ * with it, `install.node_layout.linker` answers "did pnpm really switch". Read errors stay
223
+ * `null` (not read), never a guess.
224
+ */
225
+ if (deps.readNodeLayout !== undefined) {
226
+ try {
227
+ run.nodeLayout = deps.readNodeLayout({ dir: input.plan.sandboxProfileDir }) ?? null;
228
+ }
229
+ catch {
230
+ run.nodeLayout = null;
231
+ }
232
+ }
233
+ await runStep(run, deps, 'boot', async () => {
234
+ const boot = await deps.bootAndSample({ plan: input.plan, dshMain: input.dshMain, timeoutMs: timeouts.bootMs });
235
+ // Boot facts must be recorded BEFORE the no-sample early return (R17): "the Host printed
236
+ // its URL but the hook wrote nothing" is the difference between a measurement failure and
237
+ // a blocked boot, and it lives on these fields.
238
+ if (boot.http !== undefined)
239
+ run.http = boot.http;
240
+ if (boot.readiness !== undefined)
241
+ run.readiness = boot.readiness;
242
+ if (boot.render !== undefined)
243
+ run.render = boot.render;
244
+ if (boot.renderSkipped !== undefined)
245
+ run.renderSkipped = boot.renderSkipped;
246
+ if (boot.urlPrinted !== undefined)
247
+ run.urlPrinted = boot.urlPrinted;
248
+ if (boot.firstLine !== undefined)
249
+ run.firstLine = boot.firstLine;
250
+ if (boot.errorTail !== undefined)
251
+ run.errorTail = boot.errorTail;
252
+ if (boot.startupFailed !== undefined)
253
+ run.startupFailed = boot.startupFailed;
254
+ if (boot.bindFailedPorts !== undefined)
255
+ run.bindFailedPorts = [...boot.bindFailedPorts];
256
+ // R37: our own scratch failures are recorded, never judged as candidate behaviour.
257
+ if (boot.setupError !== undefined)
258
+ run.bootSetupError = boot.setupError ?? null;
259
+ if (boot.scratchCleanupError !== undefined)
260
+ run.bootScratchCleanupError = boot.scratchCleanupError ?? null;
261
+ // T-314: record the segmentation even on a no-sample boot — that is exactly the case whose
262
+ // 42.7s wall time nobody could explain.
263
+ if (boot.segments !== undefined)
264
+ run.timings.bootSegments = boot.segments;
265
+ // ADR-0008 E: record the replacement decision even when no sample arrived — "we waited"
266
+ // and "we did not" have to be readable without subtracting two timestamps.
267
+ if (boot.replacement !== undefined)
268
+ run.sampleReplacement = boot.replacement;
269
+ // `seconds` is the recorder's own clock (spawn → sample). `runStep` measures the same
270
+ // interval and overwrites `bootToSampleMs`, so the 20s budget is judged on one number.
271
+ if (boot.sample === null)
272
+ return { status: 'failed', detail: boot.detail, exitCode: null };
273
+ run.sample = readSample(boot.sample, input.candidatePackage, input.plan.sandboxHome);
274
+ // The 20s budget is spawn → sample (`boot.seconds`). The STEP's wall time also covers
275
+ // the settle, the readiness probe and the post-kill wait, so the two numbers differ on
276
+ // purpose and only one of them is judged (docs/specs/M3-probe.md §4).
277
+ run.timings.bootToSampleMs = Math.round(boot.seconds * 1000);
278
+ // T-312: the judged number is the first sample; the final one says when the sample the
279
+ // verdict may rest on arrived.
280
+ run.timings.bootToFinalSampleMs = Math.round((boot.finalSeconds ?? boot.seconds) * 1000);
281
+ return { status: 'passed', detail: `${boot.seconds}s to sample`, exitCode: null };
282
+ });
283
+ if (run.abortedAt !== null)
284
+ return;
285
+ await runStep(run, deps, 'http', async () => {
286
+ if (input.skipHttp === true) {
287
+ return { status: 'skipped', detail: 'no web surface requested (--no-http)', exitCode: null };
288
+ }
289
+ // A captured reading (taken before the kill) wins; otherwise probe live.
290
+ const http = run.http ?? (await deps.probeHttp({ port: input.plan.port, timeoutMs: timeouts.httpMs }));
291
+ run.http = http;
292
+ // 2xx / 3xx / 401 all mean "something is listening and answering". A refused
293
+ // connection or a timeout is the only failure signal we accept.
294
+ return http.status === null
295
+ ? { status: 'failed', detail: http.detail, exitCode: null }
296
+ : { status: 'passed', detail: `HTTP ${http.status}`, exitCode: null };
297
+ });
298
+ await runStep(run, deps, 'render', async () => {
299
+ // Not a pass, not a failure: a machine without a browser simply cannot answer this.
300
+ // The artifact keeps the assertion visible as `unmeasured` with the reason (T-302).
301
+ if (run.render === null) {
302
+ return { status: 'skipped', detail: run.renderSkipped ?? 'render check not requested', exitCode: null };
303
+ }
304
+ const detail = `${run.render.state}: ${run.render.detail} (${run.render.ms}ms)`;
305
+ return {
306
+ status: run.render.state === 'blank' ? 'failed' : run.render.state === 'rendered' ? 'passed' : 'skipped',
307
+ detail,
308
+ exitCode: null,
309
+ };
310
+ });
311
+ await runStep(run, deps, 'inventory', async () => {
312
+ if (run.sample === null)
313
+ return { status: 'failed', detail: 'no sample', exitCode: null };
314
+ if (run.sample.error !== null)
315
+ return { status: 'failed', detail: run.sample.error, exitCode: null };
316
+ const rows = run.sample.candidateRows;
317
+ if (rows.length === 1) {
318
+ return { status: 'passed', detail: `${rows[0]?.entryId} ${rows[0]?.phase ?? 'none'}`, exitCode: null };
319
+ }
320
+ return { status: 'failed', detail: `${rows.length} candidate row(s)`, exitCode: null };
321
+ });
322
+ }
323
+ function freeze(run) {
324
+ return {
325
+ candidate: run.candidate,
326
+ dshMain: run.dshMain,
327
+ sandboxHome: run.sandboxHome,
328
+ profileOrigin: run.profileOrigin,
329
+ profileSourceDir: run.profileSourceDir,
330
+ nodeLayout: run.nodeLayout,
331
+ port: run.port,
332
+ runtimeVersion: run.runtimeVersion,
333
+ steps: run.steps,
334
+ timings: run.timings,
335
+ sample: run.sample,
336
+ sampleReplacement: run.sampleReplacement,
337
+ http: run.http,
338
+ readiness: run.readiness,
339
+ render: run.render,
340
+ renderSkipped: run.renderSkipped,
341
+ urlPrinted: run.urlPrinted,
342
+ firstLine: run.firstLine,
343
+ errorTail: run.errorTail,
344
+ startupFailed: run.startupFailed,
345
+ bindFailedPorts: run.bindFailedPorts,
346
+ bootSetupError: run.bootSetupError,
347
+ bootScratchCleanupError: run.bootScratchCleanupError,
348
+ installDiagnosis: run.installDiagnosis,
349
+ installAuthUsed: run.installAuthUsed,
350
+ installIgnoredPackages: run.installIgnoredPackages,
351
+ installBuildRefusedProfileOnly: run.installBuildRefusedProfileOnly,
352
+ candidateRegistered: run.candidateRegistered,
353
+ profileCopy: run.profileCopy,
354
+ cleanup: run.cleanup,
355
+ abortedAt: run.abortedAt,
356
+ };
357
+ }
358
+ async function runStep(run, deps, id, body) {
359
+ const started = deps.now();
360
+ let outcome;
361
+ try {
362
+ outcome = await body();
363
+ }
364
+ catch (error) {
365
+ const detail = error instanceof Error ? error.message : String(error);
366
+ /*
367
+ * A THROWN BOOT IS A MEASUREMENT FAILURE (R37).
368
+ *
369
+ * Before this, an exception from `bootAndSample` (measured: `rmSync` → EPERM on Windows) only
370
+ * became `steps[boot].detail`; the judge then saw "no sample, no URL, no startup failure" and
371
+ * fell through to `probe.boot-timeout` → `blocked`. Recording the throw as a setup failure is
372
+ * what lets the judge say `unknown` instead of blaming a plugin for our own file lock.
373
+ */
374
+ if (id === 'boot')
375
+ run.bootSetupError = `boot-step-threw: ${detail}`;
376
+ outcome = { status: 'failed', detail, exitCode: null };
377
+ }
378
+ const step = { id, status: outcome.status, ms: deps.now() - started, detail: outcome.detail, exitCode: outcome.exitCode };
379
+ run.steps.push(step);
380
+ if (id === 'install')
381
+ run.timings.installMs = step.ms;
382
+ if (id === 'http')
383
+ run.timings.httpMs = step.ms;
384
+ // The render segment is the observation's own clock (browser spawn → settled DOM), not
385
+ // the wall time of the step that merely reads it back.
386
+ if (id === 'render')
387
+ run.timings.renderMs = run.render?.ms ?? step.ms;
388
+ // `render` is deliberately not an aborting step: a blank page must still be reported
389
+ // together with the row phase, because "row active but nothing rendered" is the exact
390
+ // shape of the 白屏 case this assertion exists for.
391
+ if (outcome.status === 'failed' && id !== 'http' && id !== 'inventory' && id !== 'cleanup' && id !== 'render') {
392
+ run.abortedAt = id;
393
+ }
394
+ }
395
+ /* --------------------------------- sampling -------------------------------- */
396
+ /**
397
+ * Turn the hook's payload into the only thing the judge needs.
398
+ *
399
+ * The hook can legitimately write `{ error }`; that is a failed measurement, not zero
400
+ * rows. Anything unparseable must surface as an error string rather than be skipped.
401
+ */
402
+ export function readSample(payload, candidatePackage, sandboxHome) {
403
+ const record = isRecord(payload) ? payload : null;
404
+ const excluded = Array.isArray(record?.['excluded'])
405
+ ? record['excluded']
406
+ .map((item) => (isRecord(item) && typeof item['entryId'] === 'string' ? String(item['entryId']) : null))
407
+ .filter((item) => item !== null)
408
+ : [];
409
+ const settled = typeof record?.['settled'] === 'boolean' ? Boolean(record['settled']) : null;
410
+ const attempts = attemptsOf(record);
411
+ // T-312: `null` for payloads written before the field existed.
412
+ const provisional = typeof record?.['provisional'] === 'boolean' ? Boolean(record['provisional']) : null;
413
+ const applies = readNumber(record?.['applies']);
414
+ if (record !== null && record['error'] !== undefined && record['error'] !== null) {
415
+ const error = record['error'];
416
+ return {
417
+ transport: null,
418
+ entries: 0,
419
+ waitMs: readNumber(record['wait_ms']),
420
+ error: isRecord(error) ? String(error['message'] ?? 'hook error') : String(error),
421
+ // Machine-readable: the judge must not parse prose to tell "could not measure" from
422
+ // "measured and it is broken".
423
+ errorCode: isRecord(error) && typeof error['code'] === 'string' ? error['code'] : 'other',
424
+ settled,
425
+ attempts,
426
+ applies,
427
+ provisional,
428
+ candidateRows: [],
429
+ excluded,
430
+ };
431
+ }
432
+ const parsed = parseInventorySnapshot(payload, { source: sandboxHome, sampledAt: '' });
433
+ if (!parsed.ok) {
434
+ return {
435
+ transport: null,
436
+ entries: 0,
437
+ waitMs: readNumber(record?.['wait_ms'] ?? null),
438
+ error: parsed.error.detail,
439
+ errorCode: 'unreadable',
440
+ settled,
441
+ attempts,
442
+ applies,
443
+ provisional,
444
+ candidateRows: [],
445
+ excluded,
446
+ };
447
+ }
448
+ const candidateRows = parsed.value.entries
449
+ .filter((entry) => isCandidateModule(entry.moduleName, candidatePackage))
450
+ .map((entry) => ({ entryId: entry.entryId, moduleName: entry.moduleName, phase: entry.fiberPhase }))
451
+ .sort((left, right) => left.entryId.localeCompare(right.entryId));
452
+ return {
453
+ transport: parsed.value.transport,
454
+ entries: parsed.value.entries.length,
455
+ waitMs: readNumber(record?.['wait_ms'] ?? null),
456
+ error: null,
457
+ errorCode: null,
458
+ settled,
459
+ attempts,
460
+ applies,
461
+ provisional,
462
+ candidateRows,
463
+ excluded,
464
+ };
465
+ }
466
+ /**
467
+ * `@scope/pkg/sub/path` and `file:///…/node_modules/pkg/x.js` both have to reduce to the
468
+ * package name, because the inventory reports whatever the loader resolved.
469
+ *
470
+ * A `file:` URL with no `node_modules/` segment (a linked or vendored plugin) has no
471
+ * derivable package name; this returns `''` instead of inventing one, and
472
+ * {@link isCandidateModule} decides the match with the path evidence it does have.
473
+ */
474
+ export function modulePackageName(moduleName) {
475
+ let text = moduleName;
476
+ if (text.startsWith('file://')) {
477
+ try {
478
+ text = decodeURIComponent(text);
479
+ }
480
+ catch {
481
+ // Keep the raw text; the comparison below simply will not match.
482
+ }
483
+ const marker = text.lastIndexOf('node_modules/');
484
+ if (marker === -1)
485
+ return '';
486
+ text = text.slice(marker + 'node_modules/'.length);
487
+ }
488
+ const parts = text.split('/').filter((part) => part !== '');
489
+ if (parts.length === 0)
490
+ return text;
491
+ if (parts[0]?.startsWith('@') === true)
492
+ return parts.length >= 2 ? `${parts[0]}/${parts[1]}` : String(parts[0]);
493
+ return String(parts[0]);
494
+ }
495
+ /**
496
+ * Does this runtime row belong to the candidate?
497
+ *
498
+ * Exact package name first; then the path segment, so a `link:`-installed candidate (the
499
+ * shape our own fixtures use) is still identified. Both matches are recorded as *the*
500
+ * candidate row, and two rows still produce `unknown` — the heuristic widens what can be
501
+ * recognised, never what can be concluded.
502
+ */
503
+ export function isCandidateModule(moduleName, candidatePackage) {
504
+ if (candidatePackage === '')
505
+ return false;
506
+ if (moduleName === candidatePackage)
507
+ return true;
508
+ if (modulePackageName(moduleName) === candidatePackage)
509
+ return true;
510
+ let text = moduleName;
511
+ if (text.startsWith('file://')) {
512
+ try {
513
+ text = decodeURIComponent(text);
514
+ }
515
+ catch {
516
+ // Raw comparison below.
517
+ }
518
+ }
519
+ const normalized = text.replaceAll('\\', '/');
520
+ if (normalized.includes(`/node_modules/${candidatePackage}/`))
521
+ return true;
522
+ // A `link:`ed or vendored candidate resolves to a path inside its own directory, so the
523
+ // directory segment is the only evidence left. Scoped names keep their `@scope/pkg` form.
524
+ if (moduleName.startsWith('file://') && normalized.includes(`/${candidatePackage}/`))
525
+ return true;
526
+ return normalized.endsWith(`/${candidatePackage}`);
527
+ }
528
+ /** Phases that mean "still moving"; a row in one of these is not a row that failed. */
529
+ const TRANSIENT_PHASES = new Set(['pending', 'loading', 'unloading']);
530
+ /**
531
+ * What can this reading support? (R17 / BS-25)
532
+ *
533
+ * `settled: null` (older payloads without the field) is treated as usable: the probe cannot
534
+ * retroactively fail a sample it produced before the field existed, and the hook always
535
+ * writes it now.
536
+ */
537
+ export function measurementState(sample) {
538
+ if (sample === null)
539
+ return 'unreadable';
540
+ if (sample.error !== null)
541
+ return 'unreadable';
542
+ if (sample.settled === false)
543
+ return 'unsettled';
544
+ return 'valid';
545
+ }
546
+ /** Publishable detail for `probe.tree-not-settled`: observations only, no guesses. */
547
+ function measurementDetail(run) {
548
+ const parts = [];
549
+ const sample = run.sample;
550
+ if (sample !== null) {
551
+ parts.push(`settled=${String(sample.settled)}`);
552
+ parts.push(`attempts=${sample.attempts ?? 'unknown'}`);
553
+ if (sample.errorCode !== null)
554
+ parts.push(`code=${sample.errorCode}`);
555
+ if (sample.error !== null)
556
+ parts.push(sample.error.slice(0, 120));
557
+ if (sample.candidateRows.length > 0) {
558
+ parts.push(`rows=${sample.candidateRows.map((row) => `${row.entryId}:${row.phase ?? 'none'}`).join(',')}`);
559
+ }
560
+ }
561
+ // ADR-0008 E: say out loud whether a replacement was even attempted. Without this the
562
+ // reader sees only a shorter wall clock and has to guess why.
563
+ if (sample !== null && sample.provisional !== null)
564
+ parts.push(`provisional=${String(sample.provisional)}`);
565
+ const replacement = run.sampleReplacement;
566
+ if (replacement !== null) {
567
+ if (replacement.waited) {
568
+ parts.push(`replacement=waited(${replacement.waitedMs}ms, samples=${replacement.samples})`);
569
+ }
570
+ else if (replacement.upgraded || replacement.reason === 'upgrade') {
571
+ // T-312 (R29: BS-33): waiting for the final sample after a PROVISIONAL one is not a
572
+ // replacement wait. Naming it separately keeps E's claim checkable in one field.
573
+ parts.push(`replacement=not-waited(ADR-0008 E) · upgrade=waited(${replacement.upgradeWaitedMs}ms)`);
574
+ }
575
+ else {
576
+ parts.push('replacement=not-waited(ADR-0008 E: only an unreadable sample is replaced)');
577
+ }
578
+ }
579
+ if (run.readiness !== null) {
580
+ parts.push(`readiness=${run.readiness.outcome}(${run.readiness.waited_ms}ms/${run.readiness.window_ms}ms)`);
581
+ }
582
+ return parts.join(' · ');
583
+ }
584
+ export function judgeProbe(input) {
585
+ const { run, at } = input;
586
+ const reasons = [];
587
+ const evidence = [];
588
+ const remediation = [];
589
+ const missingEvidence = [];
590
+ // A mutable holder: TypeScript's control-flow analysis cannot see assignments made
591
+ // inside the `block()` closure, and a plain `let` made the later guards look dead.
592
+ const state = { conclusion: 'go', level: 'high' };
593
+ const block = (code, messageId, params) => {
594
+ state.conclusion = 'blocked';
595
+ reasons.push({ code, severity: 'block', messageId, ...(params === undefined ? {} : { params }) });
596
+ };
597
+ evidence.push({
598
+ id: 'probe-runtime',
599
+ tier: 'measured-local',
600
+ source: run.dshMain,
601
+ method: 'dsh --version (sandbox)',
602
+ at,
603
+ ...(run.runtimeVersion === null ? {} : { detail: run.runtimeVersion }),
604
+ });
605
+ const stepOf = (id) => run.steps.find((step) => step.id === id);
606
+ const runtimeStep = stepOf('runtime');
607
+ if (runtimeStep?.status !== 'passed') {
608
+ block('probe-runtime-unavailable', 'probe.runtime-unavailable', { detail: runtimeStep?.detail ?? 'runtime not read' });
609
+ return finishJudgement(run, { conclusion: state.conclusion, level: state.level, reasons, evidence, remediation, missingEvidence });
610
+ }
611
+ /**
612
+ * The copied profile failed to become usable (T-304).
613
+ *
614
+ * WHY THIS RETURNS IMMEDIATELY: the candidate was never given a chance to run. Carrying on
615
+ * would let the generic paths below turn "your own dependencies did not install" into
616
+ * `probe.boot-timeout` or `probe.install-failed` — a `blocked` verdict about the wrong
617
+ * package. The two reasons are separate on purpose: a dangling `link:` is a *silent*
618
+ * success of the package manager (F40) and reads differently from a failed install.
619
+ */
620
+ const profileStep = stepOf('profile');
621
+ if (profileStep !== undefined && profileStep.status === 'failed') {
622
+ const copy = run.profileCopy;
623
+ if (copy !== null) {
624
+ evidence.push({
625
+ id: 'probe-profile-copy',
626
+ tier: 'measured-local',
627
+ source: run.profileSourceDir ?? `copy:${copy.origin}`,
628
+ method: 'profile declaration copy + dependency install (sandbox)',
629
+ at,
630
+ detail: `origin=${copy.origin} copied=${copy.copied.join(',') || 'none'} missing=${copy.missing.join(',') || 'none'} install_exit=${copy.install?.exitCode ?? 'not attempted'}`,
631
+ });
632
+ }
633
+ state.conclusion = 'unknown';
634
+ state.level = 'medium';
635
+ missingEvidence.push('missing.probe');
636
+ const dangling = copy?.danglingLinks ?? [];
637
+ if (dangling.length > 0) {
638
+ reasons.push({
639
+ code: 'probe-profile-link-dangling',
640
+ severity: 'warn',
641
+ messageId: 'probe.profile-link-dangling',
642
+ params: {
643
+ links: dangling.map((link) => `${link.name} → ${link.spec}`).join(', '),
644
+ count: dangling.length,
645
+ },
646
+ });
647
+ }
648
+ else {
649
+ reasons.push({
650
+ code: 'probe-profile-copy-unusable',
651
+ severity: 'warn',
652
+ messageId: 'probe.profile-copy-unusable',
653
+ params: {
654
+ profile: copy?.origin ?? run.profileOrigin,
655
+ detail: (profileStep.detail ?? 'the copied profile could not be installed').slice(0, 240),
656
+ },
657
+ });
658
+ }
659
+ return finishJudgement(run, {
660
+ conclusion: state.conclusion,
661
+ level: state.level,
662
+ reasons,
663
+ evidence,
664
+ remediation,
665
+ missingEvidence,
666
+ });
667
+ }
668
+ if (profileStep !== undefined && profileStep.status === 'passed' && run.profileCopy !== null) {
669
+ evidence.push({
670
+ id: 'probe-profile-copy',
671
+ tier: 'measured-local',
672
+ source: run.profileSourceDir ?? `copy:${run.profileCopy.origin}`,
673
+ method: 'profile declaration copy + dependency install (sandbox)',
674
+ at,
675
+ detail: `origin=${run.profileCopy.origin} copied=${run.profileCopy.copied.join(',') || 'none'} missing=${run.profileCopy.missing.join(',') || 'none'} install_exit=${run.profileCopy.install?.exitCode ?? 'not attempted'}`,
676
+ });
677
+ /**
678
+ * The copy's dependencies installed but their build scripts were refused (R19 F35 shape).
679
+ *
680
+ * WHY IT IS NOT SILENT: native modules that never got built can make a Host fail to start
681
+ * for reasons that have nothing to do with the candidate. The caveat has to be visible in
682
+ * every verdict it could have touched, not only in the artifacts someone reads twice.
683
+ */
684
+ if (run.profileCopy.buildRefused === true) {
685
+ reasons.push({
686
+ code: 'probe-profile-build-refused',
687
+ severity: 'warn',
688
+ messageId: 'probe.profile-build-refused',
689
+ params: { detail: (run.profileCopy.install?.detail ?? 'the package manager refused to run build scripts').slice(0, 200) },
690
+ });
691
+ }
692
+ }
693
+ const installStep = stepOf('install');
694
+ if (installStep !== undefined && installStep.status === 'failed') {
695
+ /**
696
+ * The package-manager refusal was about the COPIED PROFILE, and the composition was not
697
+ * updated (T-304 / R21). Nothing here is evidence about the candidate: the install never
698
+ * completed, so the bundle was never registered and the Host never mounted it. Reporting
699
+ * `blocked` would blame a package for a profile it did not write.
700
+ */
701
+ if (run.installBuildRefusedProfileOnly) {
702
+ state.conclusion = 'unknown';
703
+ state.level = 'medium';
704
+ missingEvidence.push('missing.probe');
705
+ // One refusal, one reason: when the copy's own install already reported the same policy
706
+ // fact, repeating it here would read like two separate findings.
707
+ if (run.profileCopy?.buildRefused !== true) {
708
+ reasons.push({
709
+ code: 'probe-profile-build-refused',
710
+ severity: 'warn',
711
+ messageId: 'probe.profile-build-refused',
712
+ params: {
713
+ detail: `the package manager refused to build the copied profile's own dependencies (${run.installIgnoredPackages.join(', ')}), so the composition was not updated with the candidate`,
714
+ },
715
+ });
716
+ }
717
+ evidence.push({
718
+ id: 'probe-install-refused-by-profile',
719
+ tier: 'measured-local',
720
+ source: run.candidate.spec,
721
+ method: 'dsh plugin add (sandbox) + dsh.profile.bundles read-back',
722
+ at,
723
+ detail: `candidate_registered=${run.candidateRegistered === null ? 'unreadable' : String(run.candidateRegistered)} ignored=${run.installIgnoredPackages.join(',') || 'none'}`,
724
+ });
725
+ return finishJudgement(run, {
726
+ conclusion: state.conclusion,
727
+ level: state.level,
728
+ reasons,
729
+ evidence,
730
+ remediation,
731
+ missingEvidence,
732
+ });
733
+ }
734
+ // T-310: name the package manager's reason, not just its exit code. Three shapes, and
735
+ // the difference matters to the reader: a build-script refusal is a package-manager
736
+ // policy (the plugin is fine, it just never got built), a code is a cause, and the
737
+ // third branch is the honest "it failed and said nothing usable".
738
+ const diagnosis = run.installDiagnosis;
739
+ const code = diagnosis?.code ?? null;
740
+ const keyLine = diagnosis?.key_line ?? null;
741
+ const spoken = keyLine === null ? 'the package manager printed no line that explains this' : keyLine;
742
+ if (diagnosis !== null && diagnosis.source !== 'none') {
743
+ evidence.push({
744
+ id: 'probe-install-diagnosis',
745
+ tier: 'measured-local',
746
+ source: run.candidate.spec,
747
+ method: `package manager output (${diagnosis.source}, sandbox)`,
748
+ at,
749
+ detail: code === null ? spoken : `code=${code} · ${spoken}`,
750
+ });
751
+ }
752
+ if (code === 'ERR_PNPM_IGNORED_BUILDS') {
753
+ block('probe-install-build-refused', 'probe.install-build-refused', { code, detail: spoken });
754
+ remediation.push({
755
+ kind: 'report',
756
+ messageId: 'remediation.install-build-refused',
757
+ note: 'the package manager installed the package but refused to run its build scripts, so nothing was built; allow build scripts for this package or ask the author for a prebuilt release',
758
+ });
759
+ }
760
+ else if (code !== null) {
761
+ block('probe-install-failed-code', 'probe.install-failed-code', {
762
+ exit: installStep.exitCode ?? 'unknown',
763
+ code,
764
+ detail: spoken,
765
+ });
766
+ remediation.push({ kind: 'report', messageId: 'remediation.report', note: 'report the install failure to the plugin author with the probe artifact' });
767
+ }
768
+ else {
769
+ block('probe-install-failed', 'probe.install-failed', {
770
+ step: 'install',
771
+ exit: installStep.exitCode ?? 'unknown',
772
+ });
773
+ remediation.push({ kind: 'report', messageId: 'remediation.report', note: 'report the install failure to the plugin author with the probe artifact' });
774
+ }
775
+ }
776
+ else if (installStep !== undefined && installStep.status === 'passed') {
777
+ evidence.push({
778
+ id: 'probe-install',
779
+ tier: 'measured-local',
780
+ source: run.candidate.spec,
781
+ method: 'dsh plugin --profile <p> add <candidate> (sandbox)',
782
+ at,
783
+ });
784
+ // The install passed but the package manager refused to build something. Name it, and name
785
+ // whose it is: a reader must not have to guess why `go` came with a build warning (T-304).
786
+ if (run.installBuildRefusedProfileOnly && run.profileCopy?.buildRefused !== true) {
787
+ reasons.push({
788
+ code: 'probe-profile-build-refused',
789
+ severity: 'warn',
790
+ messageId: 'probe.profile-build-refused',
791
+ params: {
792
+ detail: `the package manager refused to build the copied profile's own dependencies (${run.installIgnoredPackages.join(', ')}) while adding the candidate; the candidate is registered in the composition`,
793
+ },
794
+ });
795
+ }
796
+ }
797
+ const bootStep = stepOf('boot');
798
+ if (run.sample === null) {
799
+ const ourPortUnbindable = run.bindFailedPorts.includes(run.port);
800
+ if (bootStep?.status === 'failed' && ourPortUnbindable) {
801
+ // The Host could not bind the port WE chose (EACCES/EADDRINUSE on 127.0.0.1:<plan>).
802
+ // That is a probe-environment failure: the candidate was never given a chance (R17 —
803
+ // this machine excludes TCP 53461-53560 and the plan's hash picked 53506).
804
+ state.conclusion = 'unknown';
805
+ state.level = 'medium';
806
+ missingEvidence.push('missing.probe');
807
+ reasons.push({
808
+ code: 'probe-port-unavailable',
809
+ severity: 'warn',
810
+ messageId: 'probe.port-unavailable',
811
+ params: { port: run.port },
812
+ });
813
+ }
814
+ else if (bootStep?.status === 'failed' && run.urlPrinted) {
815
+ // The Host printed its own URL, so it was up: "the hook wrote nothing" is OUR
816
+ // instrument failing, not the candidate. N22: unknown + missing.inventory, never blocked.
817
+ state.conclusion = 'unknown';
818
+ state.level = 'medium';
819
+ missingEvidence.push('missing.inventory');
820
+ reasons.push({
821
+ code: 'probe-instrument-silent',
822
+ severity: 'warn',
823
+ messageId: 'probe.tree-not-settled',
824
+ params: {
825
+ detail: `no inventory sample in ${Math.round((run.timings.bootToSampleMs ?? 0) / 1000)}s while the Host was serving`,
826
+ },
827
+ });
828
+ }
829
+ else if (bootStep?.status === 'failed' && run.bootSetupError !== null) {
830
+ // OUR filesystem failed (R37): the probe could not prepare or remove its own scratch
831
+ // directory, so the candidate was never measured. A `blocked` here would blame a plugin for
832
+ // a Windows file lock — the same class of self-harm as R17's port collision.
833
+ state.conclusion = 'unknown';
834
+ state.level = 'medium';
835
+ missingEvidence.push('missing.probe');
836
+ reasons.push({
837
+ code: 'probe-measurement-unavailable',
838
+ severity: 'warn',
839
+ messageId: 'probe.measurement-unavailable',
840
+ params: { detail: run.bootSetupError.slice(0, 200) },
841
+ });
842
+ }
843
+ else if (state.conclusion !== 'blocked' && run.startupFailed) {
844
+ // The launcher's own verdict, quoted rather than paraphrased: "startup failed: N
845
+ // required plugins did not activate", plus the first line of its diagnosis.
846
+ block('probe-startup-failed', 'probe.startup-failed', {
847
+ detail: (run.firstLine ?? 'the Host refused to start').slice(0, 200),
848
+ });
849
+ remediation.push({
850
+ kind: 'report',
851
+ messageId: 'remediation.report',
852
+ note: 'the sandbox Host refused to start with this candidate installed; attach the probe artifact (it carries the launcher diagnostic)',
853
+ });
854
+ }
855
+ else if (state.conclusion !== 'blocked') {
856
+ block('probe-boot-timeout', 'probe.boot-timeout', {
857
+ // With no sample there is no `bootToSampleMs`; the honest number is how long the boot
858
+ // step actually waited (R17: the first draft said "within 0s", which read as a bug).
859
+ seconds: Math.round((bootStep?.ms ?? 0) / 1000),
860
+ });
861
+ remediation.push({ kind: 'report', messageId: 'remediation.report', note: 'the sandbox Host never produced a sample; attach it to the bug report' });
862
+ }
863
+ }
864
+ else {
865
+ evidence.push({
866
+ id: 'probe-boot',
867
+ tier: 'measured-local',
868
+ source: run.candidate.spec,
869
+ method: `boot + ${run.sample.transport ?? 'unstated transport'} inventory sample`,
870
+ at,
871
+ detail: `entries=${run.sample.entries} wait_ms=${run.sample.waitMs ?? 'unknown'}`,
872
+ });
873
+ }
874
+ /**
875
+ * Can the inventory reading support a `blocked` verdict? (R17 / BS-25)
876
+ *
877
+ * - `valid`: the hook read the tree after it stopped moving;
878
+ * - `unsettled`: rows were still `pending`/`loading` when the budget ran out;
879
+ * - `unreadable`: the hook could not read the tree at all (`{error}`).
880
+ *
881
+ * Only `valid` may attribute a failure to the candidate. The other two are measurement
882
+ * failures and must end as `unknown` + `missing.inventory` -- that is the whole
883
+ * "slow is not broken" separation.
884
+ */
885
+ const measurement = measurementState(run.sample);
886
+ if (measurement !== 'valid' && run.sample !== null) {
887
+ state.conclusion = 'unknown';
888
+ state.level = 'medium';
889
+ missingEvidence.push('missing.inventory');
890
+ const unreadable = measurement === 'unreadable' && run.sample.errorCode !== 'inactive-context';
891
+ reasons.push(unreadable
892
+ ? {
893
+ code: 'probe-sample-unreadable',
894
+ severity: 'warn',
895
+ messageId: 'probe.sample-unreadable',
896
+ params: { detail: run.sample.error ?? 'unreadable sample' },
897
+ }
898
+ : {
899
+ code: 'probe-tree-not-settled',
900
+ severity: 'warn',
901
+ messageId: 'probe.tree-not-settled',
902
+ params: { detail: measurementDetail(run) },
903
+ });
904
+ }
905
+ const httpSkipped = stepOf('http')?.status === 'skipped';
906
+ if (!httpSkipped) {
907
+ if (measurement !== 'valid') {
908
+ // The port check ran, but a silent port cannot be attributed to the candidate while
909
+ // the tree was still composing (or could not be read). The step record keeps what the
910
+ // probe actually observed; the verdict refuses to turn it into "does not serve".
911
+ }
912
+ else if (run.http === null || run.http.status === null) {
913
+ if (state.conclusion !== 'blocked') {
914
+ block('probe-http-unreachable', 'probe.http-unreachable', { port: run.port });
915
+ remediation.push({ kind: 'report', messageId: 'remediation.report', note: 'the Host never answered on the probe port' });
916
+ }
917
+ }
918
+ else {
919
+ evidence.push({
920
+ id: 'probe-http',
921
+ tier: 'measured-local',
922
+ source: `http://127.0.0.1:${run.readiness?.port ?? run.port}`,
923
+ method: 'http readiness (redirect: manual)',
924
+ at,
925
+ detail: `status=${run.http.status}` +
926
+ (run.readiness === null
927
+ ? ''
928
+ : ` waited=${run.readiness.waited_ms}ms window=${run.readiness.window_ms}ms url_seen=${String(run.readiness.url_seen)}`),
929
+ });
930
+ }
931
+ }
932
+ if (run.readiness !== null && run.readiness.source === 'host-url' && run.readiness.port !== run.port) {
933
+ // The Host's own URL wins over the planned port, but the difference is evidence, not
934
+ // noise: it means `--port` was not honoured and any later check must use both ports.
935
+ reasons.push({
936
+ code: 'probe-port-mismatch',
937
+ severity: 'warn',
938
+ messageId: 'probe.port-mismatch',
939
+ params: { host: run.readiness.port, plan: run.port },
940
+ });
941
+ }
942
+ // Client-render (T-302). A blank page blocks on its own: "HTTP answered, row active,
943
+ // nothing on screen" is exactly BS-03, and reporting `go` for it would be the lie this
944
+ // assertion was added to prevent.
945
+ if (run.render !== null) {
946
+ if (run.render.state === 'blank') {
947
+ block('probe-render-blank', 'probe.render-blank', { detail: run.render.detail });
948
+ remediation.push({
949
+ kind: 'report',
950
+ messageId: 'remediation.report',
951
+ note: 'the page mounted nothing (white screen); attach the probe artifact and the browser console log',
952
+ });
953
+ }
954
+ else if (run.render.state === 'inconclusive') {
955
+ if (state.conclusion === 'go') {
956
+ state.conclusion = 'unknown';
957
+ state.level = 'medium';
958
+ }
959
+ missingEvidence.push('missing.render');
960
+ reasons.push({ code: 'probe-render-unmeasured', severity: 'warn', messageId: 'probe.render-unmeasured', params: { detail: run.render.detail } });
961
+ }
962
+ else {
963
+ reasons.push({ code: 'probe-render-ok', severity: 'info', messageId: 'probe.render-ok', params: { ms: run.render.ms } });
964
+ evidence.push({
965
+ id: 'probe-render',
966
+ tier: 'measured-local',
967
+ source: `http://127.0.0.1:${run.readiness?.port ?? run.port}`,
968
+ method: 'headless Chromium + CDP DOM observation',
969
+ at,
970
+ detail: run.render.detail,
971
+ });
972
+ }
973
+ }
974
+ if (state.conclusion !== 'blocked' && measurement === 'valid') {
975
+ const rows = run.sample?.candidateRows ?? [];
976
+ if (rows.length === 0) {
977
+ block('probe-row-missing', 'probe.row-missing');
978
+ remediation.push({
979
+ kind: 'remove-plugin',
980
+ messageId: 'remediation.remove-plugin',
981
+ note: 'the candidate installed but produced no row; remove it or report the silent no-op',
982
+ });
983
+ }
984
+ else if (rows.length > 1) {
985
+ state.conclusion = 'unknown';
986
+ state.level = 'medium';
987
+ reasons.push({
988
+ code: 'probe-row-ambiguous',
989
+ severity: 'warn',
990
+ messageId: 'probe.row-ambiguous',
991
+ params: { count: rows.length, rows: rows.map((row) => row.entryId).join(', ') },
992
+ });
993
+ missingEvidence.push('missing.row-identity');
994
+ }
995
+ else {
996
+ const row = rows[0];
997
+ if (row !== undefined && row.phase !== null && TRANSIENT_PHASES.has(row.phase)) {
998
+ // A row still moving at sample time is NOT a row that failed (N21): the phase is a
999
+ // race, not an outcome. The settle budget is the hook's, and it already reported it.
1000
+ state.conclusion = 'unknown';
1001
+ state.level = 'medium';
1002
+ missingEvidence.push('missing.inventory');
1003
+ reasons.push({
1004
+ code: 'probe-row-unsettled',
1005
+ severity: 'warn',
1006
+ messageId: 'probe.tree-not-settled',
1007
+ params: { detail: `row ${row.entryId} is still ${row.phase}` },
1008
+ });
1009
+ }
1010
+ else if (row !== undefined && row.phase === 'active') {
1011
+ reasons.push({
1012
+ code: 'probe-row-active',
1013
+ severity: 'info',
1014
+ messageId: 'probe.row-active',
1015
+ params: { row: row.entryId },
1016
+ });
1017
+ if (run.http !== null && run.http.status !== null) {
1018
+ reasons.unshift({
1019
+ code: 'probe-served',
1020
+ severity: 'info',
1021
+ messageId: 'probe.served',
1022
+ params: {
1023
+ status: run.http.status,
1024
+ seconds: Math.round((run.timings.bootToSampleMs ?? 0) / 1000),
1025
+ },
1026
+ });
1027
+ }
1028
+ }
1029
+ else if (row !== undefined) {
1030
+ block('probe-row-inactive', 'probe.row-inactive', { row: row.entryId, phase: row.phase ?? 'none' });
1031
+ remediation.push({
1032
+ kind: 'remove-plugin',
1033
+ messageId: 'remediation.remove-plugin',
1034
+ note: 'the candidate row is declared and admitted but never runs; remove it until the author ships a fix',
1035
+ });
1036
+ }
1037
+ }
1038
+ }
1039
+ if (input.declaredRange !== undefined && input.declaredRange !== null && run.runtimeVersion !== null) {
1040
+ // Only a *stated* mismatch downgrades the reading. We never guess a range here: the
1041
+ // declaration was already judged by admission, this is the honesty check that the
1042
+ // measurement transfers to the runtime the user actually runs.
1043
+ if (rangeExcludes(input.declaredRange, run.runtimeVersion)) {
1044
+ if (state.conclusion === 'go')
1045
+ state.conclusion = 'unknown';
1046
+ state.level = state.level === 'high' ? 'medium' : state.level;
1047
+ reasons.push({
1048
+ code: 'probe-runtime-mismatch',
1049
+ severity: 'warn',
1050
+ messageId: 'probe.runtime-mismatch',
1051
+ params: { runtime: run.runtimeVersion, range: input.declaredRange },
1052
+ });
1053
+ missingEvidence.push('missing.probe');
1054
+ }
1055
+ }
1056
+ /**
1057
+ * A copy whose build scripts were refused cannot support a `blocked` verdict.
1058
+ *
1059
+ * WHY ONLY THE BOOT STEP: `abortedAt === 'boot'` covers every shape where the composition
1060
+ * never came up (startup failed / no sample / boot timeout). Those are exactly the failures
1061
+ * an unbuilt native module can cause. A failed candidate install or a dead row is the
1062
+ * candidate's own fact and keeps its `blocked` — the downgrade must not become a blanket
1063
+ * "we are never sure".
1064
+ */
1065
+ if ((run.profileCopy?.buildRefused === true || run.installBuildRefusedProfileOnly) &&
1066
+ state.conclusion === 'blocked' &&
1067
+ run.abortedAt === 'boot') {
1068
+ state.conclusion = 'unknown';
1069
+ state.level = 'medium';
1070
+ missingEvidence.push('missing.probe');
1071
+ reasons.push({
1072
+ code: 'probe-profile-build-unattributable',
1073
+ severity: 'warn',
1074
+ messageId: 'probe.profile-build-refused',
1075
+ params: {
1076
+ detail: `the copy's dependencies installed without their build scripts, so the Host's failure to start cannot be attributed to the candidate (${run.firstLine ?? 'no launcher line'})`.slice(0, 240),
1077
+ },
1078
+ });
1079
+ }
1080
+ if (!run.cleanup.removed || !run.cleanup.portClosed) {
1081
+ if (state.conclusion === 'go')
1082
+ state.conclusion = 'risky';
1083
+ reasons.push({
1084
+ code: 'probe-cleanup-incomplete',
1085
+ severity: 'warn',
1086
+ messageId: 'probe.cleanup-incomplete',
1087
+ params: { removed: String(run.cleanup.removed), portClosed: String(run.cleanup.portClosed) },
1088
+ });
1089
+ }
1090
+ evidence.push({
1091
+ id: 'probe-cleanup',
1092
+ tier: 'measured-local',
1093
+ source: run.cleanup.detail,
1094
+ method: 'directory + port check',
1095
+ at,
1096
+ });
1097
+ return finishJudgement(run, {
1098
+ conclusion: state.conclusion,
1099
+ level: state.level,
1100
+ reasons,
1101
+ evidence,
1102
+ remediation,
1103
+ missingEvidence: state.conclusion === 'unknown' && missingEvidence.length === 0 ? ['missing.probe'] : missingEvidence,
1104
+ });
1105
+ }
1106
+ function finishJudgement(run, input) {
1107
+ return {
1108
+ conclusion: input.conclusion,
1109
+ confidence: { level: input.level, basis: 'measured-local' },
1110
+ reasons: input.reasons,
1111
+ evidence: input.evidence,
1112
+ remediation: input.remediation,
1113
+ missingEvidence: input.conclusion === 'unknown' ? input.missingEvidence : [],
1114
+ assertions: probeAssertions(run),
1115
+ };
1116
+ }
1117
+ /** The six assertions of the contract; the ones we cannot measure stay visible. */
1118
+ export function probeAssertions(run) {
1119
+ const step = (id) => run.steps.find((item) => item.id === id);
1120
+ const httpStep = step('http');
1121
+ const measurement = measurementState(run.sample);
1122
+ const rows = run.sample?.candidateRows ?? [];
1123
+ /**
1124
+ * A copy that never became usable means the candidate was never booted (T-304). Saying
1125
+ * `failed` here would read as "the plugin failed", which is the one thing this run cannot
1126
+ * know: nothing was measured.
1127
+ *
1128
+ * The second shape is the subtler one: the copy worked, but a build-script refusal left the
1129
+ * candidate out of `dsh.profile.bundles` (R22 / F42), so the composition never contained it.
1130
+ */
1131
+ const profileUnusable = step('profile')?.status === 'failed';
1132
+ const compositionNotUpdated = run.installBuildRefusedProfileOnly && step('install')?.status === 'failed';
1133
+ /**
1134
+ * R37: our own scratch directory failed to prepare or clean. Nothing about the candidate was
1135
+ * measured, so every assertion that depends on a boot must read `unmeasured`, and the run must
1136
+ * not look like a plugin that failed to start.
1137
+ */
1138
+ const probeEnvironmentFailed = run.bootSetupError !== null;
1139
+ const notMeasured = probeEnvironmentFailed
1140
+ ? `the probe could not prepare its own scratch files (${run.bootSetupError.slice(0, 160)}), so the candidate was never booted`
1141
+ : profileUnusable
1142
+ ? 'the copied profile could not be made usable, so the candidate was never booted'
1143
+ : compositionNotUpdated
1144
+ ? 'the package manager refused to build the copied profile’s own dependencies, so the composition was not updated and the candidate was never booted'
1145
+ : null;
1146
+ return [
1147
+ {
1148
+ // `failed` is "nothing was written"; `unmeasured` is "something was written but it is
1149
+ // not a reading" (the hook's own context died). They are different facts (R17).
1150
+ id: 'boot-sampled',
1151
+ status: notMeasured !== null
1152
+ ? 'unmeasured'
1153
+ : run.sample === null
1154
+ ? run.urlPrinted
1155
+ ? 'unmeasured'
1156
+ : 'failed'
1157
+ : measurement === 'unreadable'
1158
+ ? 'unmeasured'
1159
+ : 'passed',
1160
+ detail: notMeasured ??
1161
+ (run.sample === null
1162
+ ? run.urlPrinted
1163
+ ? 'the Host was serving but the probe wrote no sample'
1164
+ : 'no sample'
1165
+ : (run.sample.error ??
1166
+ (run.sample.settled === false ? 'sampled while the tree was still moving (settled=false)' : null))),
1167
+ },
1168
+ {
1169
+ // A silent port measured while the tree was still composing is NOT a failure of the
1170
+ // candidate: it is a reading that cannot answer this question (R17 / BS-25).
1171
+ id: 'http-served',
1172
+ status: notMeasured !== null || httpStep?.status === 'skipped' || measurement !== 'valid'
1173
+ ? 'unmeasured'
1174
+ : run.http === null || run.http.status === null
1175
+ ? 'failed'
1176
+ : 'passed',
1177
+ detail: notMeasured ??
1178
+ (httpStep?.status === 'skipped'
1179
+ ? httpStep.detail
1180
+ : measurement !== 'valid'
1181
+ ? `not attributable: the inventory reading was ${measurement}`
1182
+ : (run.http?.detail ?? 'not probed')),
1183
+ },
1184
+ {
1185
+ id: 'inventory-active',
1186
+ status: notMeasured !== null
1187
+ ? 'unmeasured'
1188
+ : measurement !== 'valid'
1189
+ ? 'unmeasured'
1190
+ : rows.length === 1 && rows[0]?.phase === 'active'
1191
+ ? 'passed'
1192
+ : 'failed',
1193
+ detail: notMeasured ??
1194
+ (measurement !== 'valid'
1195
+ ? `no settled reading (${measurement})`
1196
+ : run.sample === null
1197
+ ? 'no sample'
1198
+ : `${rows.length} candidate row(s)`),
1199
+ },
1200
+ {
1201
+ id: 'cleanup-complete',
1202
+ status: run.cleanup.removed && run.cleanup.portClosed ? 'passed' : 'failed',
1203
+ detail: run.cleanup.detail,
1204
+ },
1205
+ // Not "skipped": the artifact must show whether this run answered it. `unmeasured`
1206
+ // means no browser was available (or the check could not complete), never "fine".
1207
+ {
1208
+ id: 'client-rendered',
1209
+ status: run.render === null
1210
+ ? 'unmeasured'
1211
+ : run.render.state === 'rendered'
1212
+ ? 'passed'
1213
+ : run.render.state === 'blank'
1214
+ ? 'failed'
1215
+ : 'unmeasured',
1216
+ detail: run.render === null
1217
+ ? (run.renderSkipped ?? 'render check not requested')
1218
+ : `${run.render.state}: ${run.render.detail}`,
1219
+ },
1220
+ { id: 'namespace-diff', status: 'unmeasured', detail: 'tracked as T-303; tool surface lives in agent scope (BS-21)' },
1221
+ ];
1222
+ }
1223
+ /** Build the contract-shaped verdict around a judgement. */
1224
+ export function probeVerdict(input) {
1225
+ const { run, judgement, env, at } = input;
1226
+ return {
1227
+ schemaVersion: 1,
1228
+ subject: { name: run.candidate.package, version: null, kind: 'plugin' },
1229
+ env,
1230
+ conclusion: judgement.conclusion,
1231
+ confidence: judgement.confidence,
1232
+ reasons: judgement.reasons,
1233
+ evidence: judgement.evidence,
1234
+ remediation: judgement.remediation,
1235
+ missingEvidence: judgement.missingEvidence,
1236
+ generatedAt: at,
1237
+ };
1238
+ }
1239
+ /* --------------------------------- helpers -------------------------------- */
1240
+ function isRecord(value) {
1241
+ return typeof value === 'object' && value !== null && !Array.isArray(value);
1242
+ }
1243
+ function readNumber(value) {
1244
+ return typeof value === 'number' && Number.isFinite(value) ? value : null;
1245
+ }
1246
+ /**
1247
+ * How many reads the hook needed. The payload carries either the attempt trace (array) or
1248
+ * a count; both are facts, and neither is inferred from the failure text.
1249
+ */
1250
+ function attemptsOf(record) {
1251
+ if (record === null)
1252
+ return null;
1253
+ const list = record['attempts'];
1254
+ if (Array.isArray(list))
1255
+ return list.length;
1256
+ if (typeof list === 'number' && Number.isFinite(list))
1257
+ return list;
1258
+ const error = record['error'];
1259
+ if (isRecord(error))
1260
+ return readNumber(error['attempts']);
1261
+ return null;
1262
+ }
1263
+ /**
1264
+ * Deliberately tiny range check: enough to know that the runtime is *outside* a stated
1265
+ * range, so the probe result is not advertised for a runtime it never ran on. Full
1266
+ * admission semantics live in core/admission — this is not a second implementation.
1267
+ */
1268
+ function rangeExcludes(range, runtime) {
1269
+ const text = range.trim();
1270
+ if (text === '' || text === '*' || text.toLowerCase() === 'any')
1271
+ return false;
1272
+ const versions = [runtime, runtime.replace(/^v/, '')];
1273
+ if (versions.some((version) => text.includes(version)))
1274
+ return false;
1275
+ // Only the exact-pin shape can be judged without a semver engine here.
1276
+ const exact = /^=?v?(\d+\.\d+\.\d+(?:-[0-9A-Za-z.-]+)?)$/.exec(text);
1277
+ if (exact !== null)
1278
+ return versions.every((version) => version !== exact[1]);
1279
+ return false;
1280
+ }
1281
+ //# sourceMappingURL=exec.js.map