@dsh-triage/probe 0.0.0-stage → 0.1.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.
@@ -0,0 +1,142 @@
1
+ /**
2
+ * Copying a real profile into a sandbox, and checking the copy is actually usable (T-304).
3
+ *
4
+ * WHY A COPY AND NOT A MOUNT: the whole point of the probe is to answer "would this run
5
+ * alongside *my* bundles?" without touching the user's `~/.dsh`. R20 measured that copying
6
+ * four declaration files is enough to boot the same composition (F38), so the sandbox gets a
7
+ * *copy* — the real profile is only ever read.
8
+ *
9
+ * WHAT IS DELIBERATELY NOT COPIED:
10
+ * - `node_modules/`: rebuilt by the package manager inside the sandbox (F39);
11
+ * - `.plugin-manager/`: logs and install scratch, never declarations;
12
+ * - `.npmrc`: it can carry a registry token, and 铁律 4 forbids moving credentials;
13
+ * - anything else the profile happens to contain. A copy that silently drags the user's
14
+ * secrets or megabytes of cache into a probe artifact is exactly the failure this list
15
+ * prevents.
16
+ *
17
+ * F40, the reason {@link danglingLocalDependencies} exists: `{"x":"link:./not-here"}` makes
18
+ * `dsh plugin install` exit **0** while creating a link to nothing. Without a stat, that
19
+ * "successful" install would become evidence for a composition that cannot work.
20
+ */
21
+ import { copyFileSync, existsSync, mkdirSync, readFileSync, statSync, writeFileSync } from 'node:fs';
22
+ import { isAbsolute, join, resolve } from 'node:path';
23
+ /**
24
+ * Copy `files` from `sourceDir` into `targetDir`, creating the target.
25
+ *
26
+ * Only the names passed in are considered, and only as plain files: this function is given
27
+ * the whitelist by its caller, so an unexpected entry in a profile manifest cannot widen it.
28
+ */
29
+ export function copyProfileDeclarations(input) {
30
+ mkdirSync(input.targetDir, { recursive: true });
31
+ const copied = [];
32
+ const missing = [];
33
+ for (const file of input.files) {
34
+ const source = join(input.sourceDir, file);
35
+ if (!isFile(source)) {
36
+ missing.push(file);
37
+ continue;
38
+ }
39
+ copyFileSync(source, join(input.targetDir, file));
40
+ copied.push(file);
41
+ }
42
+ return { copied, missing };
43
+ }
44
+ /** The manifest's dependency fields that a package manager actually installs. */
45
+ const DEPENDENCY_FIELDS = ['dependencies', 'devDependencies', 'optionalDependencies'];
46
+ /**
47
+ * Local (non-registry) dependency targets declared by a profile manifest.
48
+ *
49
+ * `workspace:` and `npm:` are not local paths and are skipped: the first is resolved by the
50
+ * workspace file, the second aliases a registry package. Only `link:` and `file:` name a
51
+ * path this machine has to have.
52
+ */
53
+ export function localDependencyTargets(manifest, profileDir) {
54
+ if (manifest === null || typeof manifest !== 'object' || Array.isArray(manifest))
55
+ return [];
56
+ const record = manifest;
57
+ const found = [];
58
+ for (const field of DEPENDENCY_FIELDS) {
59
+ const block = record[field];
60
+ if (block === null || typeof block !== 'object' || Array.isArray(block))
61
+ continue;
62
+ for (const [name, value] of Object.entries(block)) {
63
+ if (typeof value !== 'string')
64
+ continue;
65
+ const spec = value.trim();
66
+ const prefix = spec.startsWith('link:') ? 'link:' : spec.startsWith('file:') ? 'file:' : null;
67
+ if (prefix === null)
68
+ continue;
69
+ const raw = spec.slice(prefix.length).trim();
70
+ if (raw === '')
71
+ continue;
72
+ found.push({ name, spec, field, target: isAbsolute(raw) ? resolve(raw) : resolve(profileDir, raw) });
73
+ }
74
+ }
75
+ return found;
76
+ }
77
+ /** The subset of {@link LocalDependencyTarget} that points at something which is not there. */
78
+ export function danglingLocalDependencies(targets) {
79
+ return targets.filter((target) => !targetExists(target.target));
80
+ }
81
+ /** Read a profile manifest; `null` when it is absent or unparseable (the caller reports it). */
82
+ export function readProfileManifest(profileDir) {
83
+ const path = join(profileDir, 'package.json');
84
+ if (!isFile(path))
85
+ return null;
86
+ try {
87
+ return JSON.parse(readFileSync(path, 'utf8').replace(/^\uFEFF/, ''));
88
+ }
89
+ catch {
90
+ return null;
91
+ }
92
+ }
93
+ function isFile(path) {
94
+ try {
95
+ return statSync(path).isFile();
96
+ }
97
+ catch {
98
+ return false;
99
+ }
100
+ }
101
+ /** A broken symlink must count as missing, so `statSync` (which follows links) decides. */
102
+ function targetExists(path) {
103
+ try {
104
+ statSync(path);
105
+ return true;
106
+ }
107
+ catch {
108
+ return false;
109
+ }
110
+ }
111
+ /** Was the copy actually written? Used by the executor as a second proof after `copyFileSync`. */
112
+ export function copiedFilesPresent(input) {
113
+ return input.files.filter((file) => existsSync(join(input.targetDir, file)));
114
+ }
115
+ /**
116
+ * The file name whose content decides whether pnpm treats unapproved builds as fatal.
117
+ *
118
+ * `pnpm-workspace.yaml` is pnpm 10+/11+'s project settings file, and it is also one of the four
119
+ * declaration files a profile is made of (F38), so it is the right place — and the only place
120
+ * that does not overwrite something the user wrote.
121
+ */
122
+ const WORKSPACE_FILE = 'pnpm-workspace.yaml';
123
+ /**
124
+ * Stop the package manager from FAILING over unapproved build scripts, without approving any.
125
+ *
126
+ * WHY THIS IS NOT A GATE BEING LOWERED (measured R21): with a copied real profile,
127
+ * `dsh plugin install` exits 1 with `ERR_PNPM_IGNORED_BUILDS` even though every package
128
+ * installed — and the launcher then skips registering bundles, so the candidate never joins
129
+ * the composition and the probe can only say "no row". Setting `strictDepBuilds: false` makes
130
+ * the same run exit **0**, register the bundle, and still run **no** third-party build script
131
+ * (measured: `onlyBuiltDependencies` stays empty; `Ignored build scripts: …` is still printed).
132
+ *
133
+ * It is applied only when the source profile brought no workspace file of its own: a user's file
134
+ * is never overwritten, and if theirs refuses builds the probe reports `unknown` honestly.
135
+ */
136
+ export function applySandboxBuildPolicy(input) {
137
+ if (input.copiedFiles.includes(WORKSPACE_FILE))
138
+ return 'source';
139
+ writeFileSync(join(input.targetDir, WORKSPACE_FILE), ['# written by dsh-triage probe (T-304): do not fail the install over unapproved builds.', '# No build script is approved or executed: onlyBuiltDependencies stays empty.', 'strictDepBuilds: false', ''].join('\n'), 'utf8');
140
+ return 'sandbox';
141
+ }
142
+ //# sourceMappingURL=profile-copy.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"profile-copy.js","sourceRoot":"","sources":["../src/profile-copy.ts"],"names":[],"mappings":"AAAA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,CAAC,WAAW,CAAC,QAAQ,CAAC,cAAc,CAAC;QAAE,OAAO,QAAQ,CAAA;IAC/D,aAAa,CACX,IAAI,CAAC,KAAK,CAAC,SAAS,EAAE,cAAc,CAAC,EACrC,CAAC,wFAAwF,EAAE,+EAA+E,EAAE,wBAAwB,EAAE,EAAE,CAAC,CAAC,IAAI,CAAC,IAAI,CAAC,EACpN,MAAM,CACP,CAAA;IACD,OAAO,SAAS,CAAA;AAClB,CAAC"}
@@ -0,0 +1,108 @@
1
+ /**
2
+ * Client-render check (M3 / T-302): "HTTP answered" is not "a screen appeared" (BS-03).
3
+ *
4
+ * WHY THIS FILE EXISTS: R14 shipped the probe with `client-rendered: unmeasured` because
5
+ * the executor had no way to look at the page. R15 measured the fact that a headless
6
+ * Chromium can read a real Host's DOM over CDP (see `docs/specs/M3-probe.md` F13–F16), so
7
+ * the assertion becomes measurable instead of staying decorative.
8
+ *
9
+ * WHAT IS JUDGED: whether the page mounted something visible. NOT whether the plugin
10
+ * works, not whether the content is correct, and never whether the code is safe.
11
+ *
12
+ * The browser is optional on purpose: `findBrowser` returns `null` on a machine without
13
+ * one, and the caller must report `unmeasured` rather than pretending a page rendered.
14
+ */
15
+ import { spawn } from 'node:child_process';
16
+ export interface HostUrl {
17
+ /** Full URL including the local session token; never publish this. */
18
+ readonly url: string;
19
+ readonly port: number;
20
+ }
21
+ /**
22
+ * The launcher prints exactly one line like
23
+ * `dsh web: http://127.0.0.1:53997/?token=…` (measured, M3-probe F10/F16).
24
+ *
25
+ * The LAST match wins: a Host that restarted prints twice, and the live one is the newer.
26
+ * The token class is deliberately broad (`[^\s"'<>]+`): a URL-safe Base64 token can carry
27
+ * `.`, `=`, `%` or `+`, and a narrower class silently drops a real URL (R15 review finding).
28
+ */
29
+ export declare function extractHostUrl(stdout: string): HostUrl | null;
30
+ export interface RenderSignals {
31
+ readonly title: string;
32
+ readonly readyState: string;
33
+ readonly bodyChildren: number;
34
+ readonly rootId: string | null;
35
+ readonly rootChildren: number;
36
+ /** Visible text length after whitespace collapsing. */
37
+ readonly textLength: number;
38
+ readonly htmlBytes: number;
39
+ }
40
+ /**
41
+ * 20 characters is deliberately low: a loading spinner with a label already exceeds it,
42
+ * so the threshold separates "mount produced something" from "empty shell", not "good UI".
43
+ */
44
+ export declare const MIN_VISIBLE_TEXT = 20;
45
+ export type RenderState = 'rendered' | 'blank' | 'inconclusive';
46
+ export interface RenderJudgement {
47
+ readonly state: RenderState;
48
+ /** Short machine-ish reason, safe to publish (no URL, no token, no page content). */
49
+ readonly detail: string;
50
+ }
51
+ /**
52
+ * Pure judgement over one DOM observation.
53
+ *
54
+ * `inconclusive` is not a soft pass: it means the observation cannot answer the question
55
+ * (nothing read, the document was still loading, no known mount point, or a mounted root
56
+ * with no text at all such as a canvas-only panel).
57
+ *
58
+ * WHY A MOUNT POINT IS REQUIRED: R15 review measured that Chrome's own error page
59
+ * (`ERR_CONNECTION_REFUSED`) and a 404 page both have body children and visible text —
60
+ * judging `bodyChildren` alone scored the *browser's* page as `rendered`, which would
61
+ * hand a `go` to any plugin whose Host failed to serve. A DSH web app mounts into
62
+ * `#root` (measured), so "no #root/#app" is an observation we cannot interpret, not a pass.
63
+ */
64
+ export declare function judgeRender(signals: RenderSignals | null): RenderJudgement;
65
+ export interface BrowserLookup {
66
+ /** Explicit path (CLI `--browser`); used verbatim when it exists. */
67
+ readonly explicit?: string | null;
68
+ readonly env?: NodeJS.ProcessEnv;
69
+ readonly platform?: NodeJS.Platform;
70
+ /** Injected for tests; defaults to `fs.existsSync`. */
71
+ readonly exists?: (path: string) => boolean;
72
+ }
73
+ /**
74
+ * Find a Chromium-family browser, or `null`.
75
+ *
76
+ * A `null` result is a first-class answer: the artifact then says `unmeasured` with the
77
+ * reason, instead of accusing a plugin because the probe machine has no browser.
78
+ */
79
+ export declare function findBrowser(input?: BrowserLookup): string | null;
80
+ export interface RenderCheck {
81
+ readonly state: RenderState;
82
+ readonly detail: string;
83
+ readonly ms: number;
84
+ readonly signals: RenderSignals | null;
85
+ }
86
+ export interface RenderUrlInput {
87
+ readonly browser: string;
88
+ readonly url: string;
89
+ /** Directory to keep the throwaway browser profile in. */
90
+ readonly scratchRoot: string;
91
+ readonly timeoutMs?: number;
92
+ readonly pollMs?: number;
93
+ /** Injected for tests: replaces the spawn call. */
94
+ readonly spawnImpl?: typeof spawn;
95
+ }
96
+ /**
97
+ * Launch the browser headless, navigate to `url`, and poll the DOM until it answers.
98
+ *
99
+ * WHY CDP AND NOT `--dump-dom`: measured in R15 — Edge 146 and Chrome 154 on this machine
100
+ * return an empty stdout and hang for the full 60s with `--dump-dom` (and `--screenshot`
101
+ * fails too), while the same binaries answer `Runtime.evaluate` over CDP in ~1s.
102
+ */
103
+ export declare function renderUrl(input: RenderUrlInput): Promise<RenderCheck>;
104
+ /** Kill the browser tree: on Windows the launcher keeps helper processes alive. */
105
+ export declare function killBrowser(child: ReturnType<typeof spawn>): void;
106
+ /** Default scratch root for render profiles (never the repo, never the user's home). */
107
+ export declare function renderScratchRoot(): string;
108
+ //# sourceMappingURL=render.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"render.d.ts","sourceRoot":"","sources":["../src/render.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;GAaG;AAEH,OAAO,EAAE,KAAK,EAAa,MAAM,oBAAoB,CAAA;AAOrD,MAAM,WAAW,OAAO;IACtB,sEAAsE;IACtE,QAAQ,CAAC,GAAG,EAAE,MAAM,CAAA;IACpB,QAAQ,CAAC,IAAI,EAAE,MAAM,CAAA;CACtB;AAED;;;;;;;GAOG;AACH,wBAAgB,cAAc,CAAC,MAAM,EAAE,MAAM,GAAG,OAAO,GAAG,IAAI,CAS7D;AAID,MAAM,WAAW,aAAa;IAC5B,QAAQ,CAAC,KAAK,EAAE,MAAM,CAAA;IACtB,QAAQ,CAAC,UAAU,EAAE,MAAM,CAAA;IAC3B,QAAQ,CAAC,YAAY,EAAE,MAAM,CAAA;IAC7B,QAAQ,CAAC,MAAM,E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M,CAAA;IACxB,QAAQ,CAAC,GAAG,EAAE,MAAM,CAAA;IACpB,0DAA0D;IAC1D,QAAQ,CAAC,WAAW,EAAE,MAAM,CAAA;IAC5B,QAAQ,CAAC,SAAS,CAAC,EAAE,MAAM,CAAA;IAC3B,QAAQ,CAAC,MAAM,CAAC,EAAE,MAAM,CAAA;IACxB,mDAAmD;IACnD,QAAQ,CAAC,SAAS,CAAC,EAAE,OAAO,KAAK,CAAA;CAClC;AAYD;;;;;;GAMG;AACH,wBAAsB,SAAS,CAAC,KAAK,EAAE,cAAc,GAAG,OAAO,CAAC,WAAW,CAAC,CAsI3E;AAED,mFAAmF;AACnF,wBAAgB,WAAW,CAAC,KAAK,EAAE,UAAU,CAAC,OAAO,KAAK,CAAC,GAAG,IAAI,CASjE;AAyGD,wFAAwF;AACxF,wBAAgB,iBAAiB,IAAI,MAAM,CAE1C"}
package/dist/render.js ADDED
@@ -0,0 +1,382 @@
1
+ /**
2
+ * Client-render check (M3 / T-302): "HTTP answered" is not "a screen appeared" (BS-03).
3
+ *
4
+ * WHY THIS FILE EXISTS: R14 shipped the probe with `client-rendered: unmeasured` because
5
+ * the executor had no way to look at the page. R15 measured the fact that a headless
6
+ * Chromium can read a real Host's DOM over CDP (see `docs/specs/M3-probe.md` F13–F16), so
7
+ * the assertion becomes measurable instead of staying decorative.
8
+ *
9
+ * WHAT IS JUDGED: whether the page mounted something visible. NOT whether the plugin
10
+ * works, not whether the content is correct, and never whether the code is safe.
11
+ *
12
+ * The browser is optional on purpose: `findBrowser` returns `null` on a machine without
13
+ * one, and the caller must report `unmeasured` rather than pretending a page rendered.
14
+ */
15
+ import { spawn, spawnSync } from 'node:child_process';
16
+ import { existsSync, mkdirSync, mkdtempSync, readFileSync, rmSync } from 'node:fs';
17
+ import { homedir, tmpdir } from 'node:os';
18
+ import { join } from 'node:path';
19
+ /**
20
+ * The launcher prints exactly one line like
21
+ * `dsh web: http://127.0.0.1:53997/?token=…` (measured, M3-probe F10/F16).
22
+ *
23
+ * The LAST match wins: a Host that restarted prints twice, and the live one is the newer.
24
+ * The token class is deliberately broad (`[^\s"'<>]+`): a URL-safe Base64 token can carry
25
+ * `.`, `=`, `%` or `+`, and a narrower class silently drops a real URL (R15 review finding).
26
+ */
27
+ export function extractHostUrl(stdout) {
28
+ const pattern = /https?:\/\/(?:127\.0\.0\.1|localhost):(\d+)\/\?token=[^\s"'<>]+/g;
29
+ let match = null;
30
+ let last = null;
31
+ while ((match = pattern.exec(stdout)) !== null)
32
+ last = match;
33
+ if (last === null)
34
+ return null;
35
+ const port = Number(last[1]);
36
+ if (!Number.isInteger(port) || port <= 0)
37
+ return null;
38
+ return { url: last[0], port };
39
+ }
40
+ /**
41
+ * 20 characters is deliberately low: a loading spinner with a label already exceeds it,
42
+ * so the threshold separates "mount produced something" from "empty shell", not "good UI".
43
+ */
44
+ export const MIN_VISIBLE_TEXT = 20;
45
+ /**
46
+ * How long to keep looking before accepting whatever the page shows. A mounted-but-still-
47
+ * hydrating app keeps growing; a white screen stays white. Both stop mattering at these
48
+ * limits, which are wall-clock caps, not conclusions.
49
+ */
50
+ const BLANK_SETTLE_MS = 3_000;
51
+ const RENDER_SETTLE_MS = 6_000;
52
+ /**
53
+ * Pure judgement over one DOM observation.
54
+ *
55
+ * `inconclusive` is not a soft pass: it means the observation cannot answer the question
56
+ * (nothing read, the document was still loading, no known mount point, or a mounted root
57
+ * with no text at all such as a canvas-only panel).
58
+ *
59
+ * WHY A MOUNT POINT IS REQUIRED: R15 review measured that Chrome's own error page
60
+ * (`ERR_CONNECTION_REFUSED`) and a 404 page both have body children and visible text —
61
+ * judging `bodyChildren` alone scored the *browser's* page as `rendered`, which would
62
+ * hand a `go` to any plugin whose Host failed to serve. A DSH web app mounts into
63
+ * `#root` (measured), so "no #root/#app" is an observation we cannot interpret, not a pass.
64
+ */
65
+ export function judgeRender(signals) {
66
+ if (signals === null)
67
+ return { state: 'inconclusive', detail: 'no DOM observation' };
68
+ if (signals.htmlBytes <= 0)
69
+ return { state: 'inconclusive', detail: 'the browser read an empty document' };
70
+ if (signals.readyState === 'loading')
71
+ return { state: 'inconclusive', detail: 'document still loading' };
72
+ if (signals.rootId === null) {
73
+ // Browser error pages and non-mounting documents land here. Saying "blank" would blame
74
+ // the plugin for something the probe never saw it do.
75
+ return { state: 'inconclusive', detail: 'no #root or #app mount point in the document' };
76
+ }
77
+ if (signals.rootChildren < 1)
78
+ return { state: 'blank', detail: `mount point "${signals.rootId}" has no children` };
79
+ if (signals.textLength === 0) {
80
+ // An icon-only or canvas-only panel is a real UI with no text. We cannot tell it apart
81
+ // from a root that mounted and then threw, so we refuse to call it either way.
82
+ return { state: 'inconclusive', detail: `mount point "${signals.rootId}" has ${signals.rootChildren} child(ren) but no visible text` };
83
+ }
84
+ const settled = signals.readyState === 'complete' ? '' : `, readyState=${signals.readyState}`;
85
+ if (signals.textLength >= MIN_VISIBLE_TEXT) {
86
+ return { state: 'rendered', detail: `mount root with ${signals.rootChildren} child(ren), ${signals.textLength} visible chars${settled}` };
87
+ }
88
+ return { state: 'blank', detail: `mount point "${signals.rootId}" shows only ${signals.textLength} visible chars` };
89
+ }
90
+ /**
91
+ * Find a Chromium-family browser, or `null`.
92
+ *
93
+ * A `null` result is a first-class answer: the artifact then says `unmeasured` with the
94
+ * reason, instead of accusing a plugin because the probe machine has no browser.
95
+ */
96
+ export function findBrowser(input = {}) {
97
+ const exists = input.exists ?? existsSync;
98
+ const explicit = (input.explicit ?? '').trim();
99
+ if (explicit !== '')
100
+ return exists(explicit) ? explicit : null;
101
+ const env = input.env ?? process.env;
102
+ const fromEnv = (env['DSH_TRIAGE_BROWSER'] ?? '').trim();
103
+ if (fromEnv !== '')
104
+ return exists(fromEnv) ? fromEnv : null;
105
+ const platform = input.platform ?? process.platform;
106
+ const candidates = platform === 'win32'
107
+ ? [
108
+ join(env['PROGRAMFILES(X86)'] ?? 'C:/Program Files (x86)', 'Microsoft/Edge/Application/msedge.exe'),
109
+ join(env['PROGRAMFILES'] ?? 'C:/Program Files', 'Microsoft/Edge/Application/msedge.exe'),
110
+ join(env['PROGRAMFILES'] ?? 'C:/Program Files', 'Google/Chrome/Application/chrome.exe'),
111
+ join(env['LOCALAPPDATA'] ?? join(homedir(), 'AppData/Local'), 'Google/Chrome/Application/chrome.exe'),
112
+ ]
113
+ : platform === 'darwin'
114
+ ? [
115
+ '/Applications/Google Chrome.app/Contents/MacOS/Google Chrome',
116
+ '/Applications/Microsoft Edge.app/Contents/MacOS/Microsoft Edge',
117
+ '/Applications/Chromium.app/Contents/MacOS/Chromium',
118
+ ]
119
+ : ['/usr/bin/google-chrome', '/usr/bin/google-chrome-stable', '/opt/google/chrome/chrome', '/usr/bin/chromium', '/usr/bin/chromium-browser', '/usr/bin/microsoft-edge'];
120
+ for (const candidate of candidates) {
121
+ if (exists(candidate))
122
+ return candidate;
123
+ }
124
+ return null;
125
+ }
126
+ const EMPTY_SIGNALS_EXPRESSION = `JSON.stringify({
127
+ title: document.title || '',
128
+ readyState: document.readyState || '',
129
+ bodyChildren: document.body ? document.body.children.length : 0,
130
+ rootId: (() => { const el = document.querySelector('#root, #app'); return el ? el.id : null })(),
131
+ rootChildren: (() => { const el = document.querySelector('#root, #app'); return el ? el.children.length : 0 })(),
132
+ textLength: (document.body && document.body.innerText ? document.body.innerText : '').replace(/\\s+/g, ' ').trim().length,
133
+ htmlBytes: document.documentElement ? document.documentElement.outerHTML.length : 0
134
+ })`;
135
+ /**
136
+ * Launch the browser headless, navigate to `url`, and poll the DOM until it answers.
137
+ *
138
+ * WHY CDP AND NOT `--dump-dom`: measured in R15 — Edge 146 and Chrome 154 on this machine
139
+ * return an empty stdout and hang for the full 60s with `--dump-dom` (and `--screenshot`
140
+ * fails too), while the same binaries answer `Runtime.evaluate` over CDP in ~1s.
141
+ */
142
+ export async function renderUrl(input) {
143
+ const timeoutMs = input.timeoutMs ?? 15_000;
144
+ const pollMs = input.pollMs ?? 300;
145
+ const spawnImpl = input.spawnImpl ?? spawn;
146
+ // Per CDP command ceiling. Without it a renderer whose main thread is blocked (the very
147
+ // shape that produces a white screen: `while(true)`, a render loop) never answers
148
+ // `Runtime.evaluate`, and the await never returns — measured 30s+ past a 4s budget, with
149
+ // the Host and the browser still alive because `host.ts` waits for this before killing.
150
+ const commandTimeoutMs = Math.min(1_500, Math.max(400, Math.floor(timeoutMs / 4)));
151
+ const started = Date.now();
152
+ let child = null;
153
+ let socket = null;
154
+ let profileDir = null;
155
+ try {
156
+ mkdirSync(input.scratchRoot, { recursive: true });
157
+ profileDir = mkdtempSync(join(input.scratchRoot, 'triage-render-'));
158
+ child = spawnImpl(input.browser, [
159
+ '--headless=new',
160
+ '--disable-gpu',
161
+ '--no-first-run',
162
+ '--no-default-browser-check',
163
+ '--disable-extensions',
164
+ '--mute-audio',
165
+ '--remote-debugging-port=0',
166
+ `--user-data-dir=${profileDir}`,
167
+ 'about:blank',
168
+ ], { stdio: ['ignore', 'ignore', 'ignore'] });
169
+ const cdpPort = await waitForDevToolsPort(profileDir, Math.min(timeoutMs, 20_000));
170
+ if (cdpPort === null)
171
+ return { state: 'inconclusive', detail: 'the browser never opened a debugging port', ms: Date.now() - started, signals: null };
172
+ const page = await firstPageTarget(cdpPort);
173
+ if (page === null)
174
+ return { state: 'inconclusive', detail: 'the browser exposed no page target', ms: Date.now() - started, signals: null };
175
+ socket = await connect(page.webSocketDebuggerUrl);
176
+ let id = 0;
177
+ const pending = new Map();
178
+ socket.onMessage((text) => {
179
+ const message = safeParse(text);
180
+ if (message === null)
181
+ return;
182
+ const messageId = typeof message['id'] === 'number' ? message['id'] : null;
183
+ if (messageId !== null) {
184
+ const resolve = pending.get(messageId);
185
+ if (resolve !== undefined) {
186
+ pending.delete(messageId);
187
+ resolve(message);
188
+ }
189
+ }
190
+ });
191
+ const send = (method, params = {}, ceiling = commandTimeoutMs) => new Promise((resolve) => {
192
+ const messageId = ++id;
193
+ // Every command is bounded: a blocked renderer answers nothing, and an unbounded
194
+ // await would keep the whole probe (and the Host) hostage.
195
+ const timer = setTimeout(() => {
196
+ pending.delete(messageId);
197
+ resolve({});
198
+ }, Math.max(250, ceiling));
199
+ pending.set(messageId, (message) => {
200
+ clearTimeout(timer);
201
+ resolve(message);
202
+ });
203
+ try {
204
+ socket?.send(JSON.stringify({ id: messageId, method, params }));
205
+ }
206
+ catch {
207
+ clearTimeout(timer);
208
+ pending.delete(messageId);
209
+ resolve({});
210
+ }
211
+ });
212
+ // The acks are not what we judge; the DOM poll is. Keep them short so a blocked
213
+ // renderer cannot spend the whole budget here.
214
+ await send('Page.enable', {}, 400);
215
+ await send('Page.navigate', { url: input.url }, 1_000);
216
+ let signals = null;
217
+ let judgement = { state: 'inconclusive', detail: 'no observation yet' };
218
+ let lastTextLength = -1;
219
+ // Poll until the document has settled. Stopping at the first non-empty paint would
220
+ // report a loading skeleton as "rendered": the first real measurement read 24 chars at
221
+ // readyState=interactive, while the loaded app shows ~320 chars (R15 spike F14). A page
222
+ // that reaches `complete` with 24 chars keeps growing, so we also require the visible
223
+ // text to stop changing between two polls.
224
+ while (Date.now() - started < timeoutMs) {
225
+ await delay(pollMs);
226
+ const remaining = timeoutMs - (Date.now() - started);
227
+ if (remaining <= 0)
228
+ break;
229
+ const evaluated = await send('Runtime.evaluate', { expression: EMPTY_SIGNALS_EXPRESSION, returnByValue: true }, remaining);
230
+ const value = readString(evaluated.result, 'result', 'value');
231
+ if (value === null)
232
+ continue;
233
+ signals = parseSignals(value);
234
+ judgement = judgeRender(signals);
235
+ const elapsed = Date.now() - started;
236
+ const parsed = signals;
237
+ if (judgement.state === 'rendered' && parsed !== null && parsed.readyState === 'complete') {
238
+ if (parsed.textLength === lastTextLength)
239
+ break;
240
+ lastTextLength = parsed.textLength;
241
+ }
242
+ if (judgement.state === 'blank' && elapsed >= BLANK_SETTLE_MS)
243
+ break;
244
+ if (elapsed >= RENDER_SETTLE_MS)
245
+ break;
246
+ }
247
+ if (signals === null) {
248
+ // No DOM query was ever answered: the renderer's main thread is blocked, so this is
249
+ // an honest "cannot tell", not a blank page.
250
+ judgement = { state: 'inconclusive', detail: `the page never answered a DOM query within ${timeoutMs}ms` };
251
+ }
252
+ return { state: judgement.state, detail: judgement.detail, ms: Date.now() - started, signals };
253
+ }
254
+ catch (error) {
255
+ return {
256
+ state: 'inconclusive',
257
+ detail: error instanceof Error ? `${error.name}: ${error.message}` : String(error),
258
+ ms: Date.now() - started,
259
+ signals: null,
260
+ };
261
+ }
262
+ finally {
263
+ try {
264
+ socket?.close();
265
+ }
266
+ catch {
267
+ // Already closed.
268
+ }
269
+ if (child !== null)
270
+ killBrowser(child);
271
+ if (profileDir !== null) {
272
+ try {
273
+ // A browser helper can still hold a file for a moment; a failed cleanup must not
274
+ // turn "the page rendered" into "the probe threw" (R15 review finding).
275
+ rmSync(profileDir, { recursive: true, force: true });
276
+ }
277
+ catch {
278
+ // Left for the OS temp reaper; the artifact already says what was measured.
279
+ }
280
+ }
281
+ }
282
+ }
283
+ /** Kill the browser tree: on Windows the launcher keeps helper processes alive. */
284
+ export function killBrowser(child) {
285
+ try {
286
+ child.kill();
287
+ }
288
+ catch {
289
+ // Already gone.
290
+ }
291
+ if (process.platform === 'win32' && child.pid !== undefined) {
292
+ spawnSync('taskkill', ['/pid', String(child.pid), '/T', '/F'], { encoding: 'utf8' });
293
+ }
294
+ }
295
+ /**
296
+ * Node 22 ships a global `WebSocket`; the cast keeps this package free of DOM/undici type
297
+ * dependencies (the same reason the gates avoid third-party modules).
298
+ */
299
+ async function connect(url) {
300
+ const Ctor = globalThis.WebSocket;
301
+ if (Ctor === undefined)
302
+ throw new Error('this Node runtime has no global WebSocket');
303
+ const socket = new Ctor(url);
304
+ await new Promise((resolve, reject) => {
305
+ socket.addEventListener('open', () => resolve(), { once: true });
306
+ socket.addEventListener('error', () => reject(new Error('the CDP socket failed to open')), { once: true });
307
+ });
308
+ return {
309
+ send: (data) => socket.send(data),
310
+ close: () => socket.close(),
311
+ onMessage: (listener) => socket.addEventListener('message', (event) => listener(String(event.data ?? ''))),
312
+ };
313
+ }
314
+ async function waitForDevToolsPort(profileDir, timeoutMs) {
315
+ const portFile = join(profileDir, 'DevToolsActivePort');
316
+ const started = Date.now();
317
+ while (Date.now() - started < timeoutMs) {
318
+ if (existsSync(portFile)) {
319
+ try {
320
+ const port = Number(readFileSync(portFile, 'utf8').split(/\r?\n/)[0]);
321
+ if (Number.isInteger(port) && port > 0)
322
+ return port;
323
+ }
324
+ catch {
325
+ // The file can be observed while it is being written; retry.
326
+ }
327
+ }
328
+ await delay(100);
329
+ }
330
+ return null;
331
+ }
332
+ async function firstPageTarget(port) {
333
+ try {
334
+ const list = (await (await fetch(`http://127.0.0.1:${port}/json/list`)).json());
335
+ const page = list.find((target) => target.type === 'page' && typeof target.webSocketDebuggerUrl === 'string');
336
+ return page === undefined ? null : { webSocketDebuggerUrl: String(page.webSocketDebuggerUrl) };
337
+ }
338
+ catch {
339
+ return null;
340
+ }
341
+ }
342
+ function parseSignals(value) {
343
+ const parsed = safeParse(value);
344
+ if (parsed === null)
345
+ return null;
346
+ const text = typeof parsed['textLength'] === 'number' ? parsed['textLength'] : 0;
347
+ return {
348
+ title: typeof parsed['title'] === 'string' ? parsed['title'] : '',
349
+ readyState: typeof parsed['readyState'] === 'string' ? parsed['readyState'] : '',
350
+ bodyChildren: typeof parsed['bodyChildren'] === 'number' ? parsed['bodyChildren'] : 0,
351
+ rootId: typeof parsed['rootId'] === 'string' ? parsed['rootId'] : null,
352
+ rootChildren: typeof parsed['rootChildren'] === 'number' ? parsed['rootChildren'] : 0,
353
+ textLength: text,
354
+ htmlBytes: typeof parsed['htmlBytes'] === 'number' ? parsed['htmlBytes'] : 0,
355
+ };
356
+ }
357
+ function readString(root, ...path) {
358
+ let cursor = root;
359
+ for (const key of path) {
360
+ if (typeof cursor !== 'object' || cursor === null)
361
+ return null;
362
+ cursor = cursor[key];
363
+ }
364
+ return typeof cursor === 'string' ? cursor : null;
365
+ }
366
+ function safeParse(text) {
367
+ try {
368
+ const parsed = JSON.parse(text);
369
+ return typeof parsed === 'object' && parsed !== null ? parsed : null;
370
+ }
371
+ catch {
372
+ return null;
373
+ }
374
+ }
375
+ function delay(ms) {
376
+ return new Promise((resolve) => setTimeout(resolve, ms));
377
+ }
378
+ /** Default scratch root for render profiles (never the repo, never the user's home). */
379
+ export function renderScratchRoot() {
380
+ return join(tmpdir(), 'dsh-triage-render');
381
+ }
382
+ //# sourceMappingURL=render.js.map