recovery-probe 0.3.0-preview.11 → 0.3.0-preview.13

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/CHANGELOG.md CHANGED
@@ -4,13 +4,26 @@ All notable changes to Recovery Probe are documented here. The project follows [
4
4
 
5
5
  Version 0.2.0 is the first npm release. Earlier 0.1.x revisions were repository-only prototypes.
6
6
 
7
- ## 0.3.0-preview.11 (release candidate; npm publication separate)
7
+ ## 0.3.0-preview.13 (2026-10-14)
8
+
9
+ - Add observation report provenance: package/CLI runtime, available browser version and allowlisted IPC hook version/runtime/capabilities. Older observation-capable hooks remain supported with unknown metadata.
10
+ - Measure completed-sample duration and actual start-to-start cadence independently of the configured post-sample delay, including unchanged samples. Report first-content sample bounds and explain no-read versus pending-read findings without changing their codes or verdict semantics.
11
+ - Add a runnable synthetic CI recovery example with a saved scenario, explicit content assertion, bounded 503 injection, nonzero failure exits, JSON/Markdown reports and Playwright traces. Verify broken and fixed controls in CI; setup failures cannot satisfy the expected broken result.
12
+
13
+ ## 0.3.0-preview.12 (2026-10-14)
14
+
15
+ - Add `observe --config FILE` for fault-free HTTP/IPC read observation in an existing renderer without reloads, navigation, focus changes or UI cleanup resets. Operator interval markers preserve cumulative read history.
16
+ - Record read starts/completions and sampled content evidence, including `CONTENT_BEFORE_READ` observations. Pre-capture history remains unknown; no identity, ownership or security verdict is inferred.
17
+ - Add bounded, owned IPC observation leases, timestamped snapshots and the documented `recovery-probe/ipc-inspector` subpath. Old hooks fail capability checks before mutation.
18
+ - Validate cache reuse and stale content with synthetic browser/Electron fixtures, alongside a per-identity cache control. Document the session-isolation boundary of reload-based checks.
19
+
20
+ ## 0.3.0-preview.11 (2026-10-14)
8
21
 
9
22
  - Extend bounded end-state calibration to HTTP and IPC initial-load discovery: observe three full healthy windows and require matching stable end states before trusting a baseline or injecting faults.
10
23
  - Accept genuinely empty selected regions after successful target/dependency reads. Retain calibration evidence and report `readiness.calibrationComplete`; failed calibration cannot claim verified final UI restoration.
11
24
  - Use the configured `settleMs` consistently instead of deriving extra stability time from the duration of full calibration windows. Later controls and cleanup may finish early only after matching a trusted baseline.
12
25
  - Add browser and real Electron regression cases for delayed image cards, empty regions and inconsistent end states.
13
- - Align installation guides on the exact preview version, document an unpublished-source fallback, and default preview publishing to npm's `next` tag. This candidate also includes the previously unpublished preview.3–preview.10 changes below.
26
+ - Align installation guides on the exact preview version, document an unpublished-source fallback, and default preview publishing to npm's `next` tag. This npm release also includes the previously unpublished preview.3–preview.10 changes below.
14
27
 
15
28
  ## 0.3.0-preview.10 (GitHub preview; npm publication separate)
16
29
 
package/README.md CHANGED
@@ -21,12 +21,12 @@ Desktop support currently means Electron, not arbitrary native applications. IPC
21
21
 
22
22
  ## Install the current preview
23
23
 
24
- This checkout targets **0.3.0-preview.11**. Preview releases use npm's `next` tag; `latest` is the stable channel. Confirm that the exact version is published before installing it:
24
+ This checkout targets **0.3.0-preview.13**. Preview releases use npm's `next` tag; `latest` is the stable channel. Confirm that the exact version is published before installing it:
25
25
 
26
26
  ```bash
27
27
  mkdir recovery-probe-tools && cd recovery-probe-tools
28
- npm view recovery-probe@0.3.0-preview.11 version
29
- npm install --save-dev --save-exact recovery-probe@0.3.0-preview.11 playwright@1.62.1
28
+ npm view recovery-probe@0.3.0-preview.13 version
29
+ npm install --save-dev --save-exact recovery-probe@0.3.0-preview.13 playwright@1.62.1
30
30
  npx recovery-probe --version
31
31
  ```
32
32
 
@@ -34,12 +34,16 @@ If the version check reports that the version is unavailable, npm publication is
34
34
 
35
35
  ## Choose a workflow
36
36
 
37
+ **New in preview.12:** [fault-free observation](docs/observe.md) records selected reads and content while you navigate, without reloading or clearing caches. See the guide for updating the development IPC hook before capturing cached state.
38
+
37
39
  | Goal | Entry point | Guide |
38
40
  | --- | --- | --- |
39
41
  | Set up a first request-recovery check interactively | `recovery-probe start web URL` or `start desktop` | [Guided start](docs/start.md) |
40
42
  | Discover and test renderer reads in an existing browser or Electron window | `recovery-probe desktop --cdp URL` | [Attachment and HTTP discovery](docs/desktop.md) |
41
43
  | Compare an Electron screen under IPC faults | `recovery-probe ipc --discover --config FILE` | [IPC setup and discovery](docs/ipc.md) |
42
44
  | Test a refresh after content has already loaded | `recovery-probe refresh --config FILE --json` | [Refresh experiments](docs/refresh.md) |
45
+ | Observe cached content without a reload | `recovery-probe observe --config FILE` | [Observation](docs/observe.md) |
46
+ | Run a repeatable synthetic recovery check in CI | `npm run test:ci-example` (source checkout) | [CI example](docs/ci.md) |
43
47
  | Add an explicit recovery assertion to a test | `withFault` or `createFaultFetch` | Examples below |
44
48
  | Propose and verify a source change | Opt-in repair workflow | [Repair setup and limits](docs/repair.md) |
45
49
 
@@ -49,6 +53,8 @@ Guided setup asks you to choose a request and loaded content that proves success
49
53
 
50
54
  HTTP and IPC structural discovery calibrate three healthy reloads for the full `baselineTimeoutMs` window before injecting faults (45 seconds with the default 15-second window). All three stable end states must agree. This avoids treating a briefly stable loading shell as the healthy screen, accepts legitimate empty regions, and keeps an unsuccessful calibration inconclusive. Later controls may finish early once they match the calibrated baseline. Content arriving after the window remains outside the evidence.
51
55
 
56
+ **Session-isolation boundary:** recovery/discovery/refresh workflows reload the renderer to establish controls. That clears in-memory caches and can hide state carried between sessions. Those modes cannot prove account isolation; content preservation within one session is not an ownership check. The new observation workflow collects evidence without resetting that state, but does not infer identities or data ownership.
57
+
52
58
  ## Refresh experiments
53
59
 
54
60
  The preview.9 refresh mode tests an **already populated screen** using an explicitly configured synthetic window event, such as `online`. It first checks the event without a fault, then injects the next selected read failure and observes the screen without reloading. An optional second event tests whether another refresh repairs the screen.
@@ -0,0 +1,101 @@
1
+ import { readFile, mkdir, writeFile, mkdtemp } from 'node:fs/promises';
2
+ import { resolve, join } from 'node:path';
3
+ import { randomUUID } from 'node:crypto';
4
+ import { createInterface } from 'node:readline';
5
+ import { connectDesktop, selectDesktopPage, desktopPages } from '../src/desktop.mjs';
6
+ import { connectIpcInspector } from '../src/ipc-inspector.mjs';
7
+ import { observationConfig, runObservation, httpObservationAdapter, ipcObservationAdapter } from '../src/observe.mjs';
8
+ import { observationMetadata, samplingMetrics, observationSummary, renderObservationReport } from '../src/observation-report.mjs';
9
+
10
+ export async function observeMain(args) {
11
+ if (!args.length || args.includes('--help')) {
12
+ console.log(`recovery-probe observe --config FILE [--out NEW_DIRECTORY] [--json] [--interactive]
13
+
14
+ Fault-free observation of an existing browser or Electron renderer.
15
+ No reload, navigation, focus change, fault injection or final UI reset.
16
+ Choose transport: http or ipc and explicit regionSelector/contentSelector CSS markers.
17
+ Navigate manually during the bounded capture. Enter marks a new interval in an
18
+ interactive terminal; --interactive also enables newline markers on piped input.
19
+ Ctrl+C saves partial evidence. CONTENT_BEFORE_READ is an observation, not a defect.
20
+ IPC requires the observation-capable development hook. See docs/observe.md.`);
21
+ return;
22
+ }
23
+ const options = {};
24
+ for (let i = 0; i < args.length; i++) {
25
+ if (['--json', '--interactive'].includes(args[i])) options[args[i].slice(2)] = true;
26
+ else if (['--config', '--out'].includes(args[i]) && args[i + 1] && !args[i + 1].startsWith('--')) options[args[i].slice(2)] = args[++i];
27
+ else throw Error('Use observe --config FILE [--out NEW_DIRECTORY] [--json] [--interactive]');
28
+ }
29
+ if (!options.config) throw Error('--config is required');
30
+ const config = observationConfig(JSON.parse(await readFile(options.config, 'utf8')));
31
+ let directory;
32
+ if (options.out) { directory = resolve(options.out); await mkdir(directory, { mode: 0o700 }); }
33
+ else { const parent = resolve('.recovery-probe'); await mkdir(parent, { recursive: true, mode: 0o700 }); directory = await mkdtemp(join(parent, 'observe-')); }
34
+ await writeFile(join(directory, '.gitignore'), '*\n', { mode: 0o600 });
35
+ const abort = new AbortController();
36
+ const stop = () => abort.abort();
37
+ process.on('SIGINT', stop); process.on('SIGTERM', stop);
38
+ let browser, control, input, report, pendingMarkers = 0, browserVersion = null;
39
+ try {
40
+ browser = await connectDesktop(config.cdp);
41
+ try { browserVersion = await browser.version(); } catch { /* Metadata may be unavailable on an attached runtime. */ }
42
+ let page, adapter;
43
+ if (config.transport === 'ipc') {
44
+ control = await connectIpcInspector(config.inspector);
45
+ const identity = await control.call('identify');
46
+ if (!identity.registered.includes(config.channel)) throw Error('Configured read channel was not registered through the development hook');
47
+ const pages = desktopPages(browser).filter(p => p.url() === identity.pageUrl);
48
+ if (pages.length !== 1) throw Error('Keep exactly one matching IPC target window open');
49
+ page = pages[0];
50
+ const nonce = randomUUID();
51
+ await page.evaluate(value => {
52
+ if (Object.hasOwn(globalThis, '__recoveryProbeWindowNonce')) throw Error('Existing window challenge');
53
+ Object.defineProperty(globalThis, '__recoveryProbeWindowNonce', { value, configurable: true });
54
+ }, nonce);
55
+ try { await control.call('identify', nonce); }
56
+ finally { await page.evaluate(value => { if (globalThis.__recoveryProbeWindowNonce === value) delete globalThis.__recoveryProbeWindowNonce; }, nonce); }
57
+ adapter = ipcObservationAdapter(control, config, identity.senderId);
58
+ } else {
59
+ page = selectDesktopPage(browser, config);
60
+ adapter = httpObservationAdapter(page, config);
61
+ }
62
+ report = await runObservation(page, config, adapter, {
63
+ signal: abort.signal,
64
+ onReady() {
65
+ if (process.stdin.isTTY || options.interactive) {
66
+ input = createInterface({ input: process.stdin, terminal: false });
67
+ input.on('line', () => { pendingMarkers = Math.min(50, pendingMarkers + 1); });
68
+ input.on('SIGINT', stop);
69
+ }
70
+ console.error(`Observing for ${config.observationMs} ms without reloading. Navigate in the app now.${input ? ' Press Enter before each action to mark a new interval.' : ''} Ctrl+C saves partial evidence.`);
71
+ },
72
+ takeMarker() {
73
+ if (!pendingMarkers) return false;
74
+ pendingMarkers--;
75
+ return true;
76
+ },
77
+ onInterval() { console.error('New observation interval.'); },
78
+ });
79
+ } catch (error) {
80
+ report ??= { schemaVersion: 1, metadata: observationMetadata(), sampling: samplingMetrics(config.sampleMs).snapshot(), mode: 'fault-free observation', status: 'incomplete', captureComplete: false, intervals: [], findings: [], reloads: 0, injected: 0 };
81
+ report.error = error.message;
82
+ } finally {
83
+ if (input) { input.close(); process.stdin.pause(); }
84
+ control?.close();
85
+ try { await browser?.close(); } catch (error) { report.status = 'incomplete'; report.captureComplete = false; report.disconnectError = error.message; }
86
+ process.off('SIGINT', stop); process.off('SIGTERM', stop);
87
+ }
88
+ report.metadata.browserVersion = browserVersion;
89
+ await writeFile(join(directory, 'scenario.json'), JSON.stringify(config, null, 2), { mode: 0o600 });
90
+ await writeFile(join(directory, 'report.json'), JSON.stringify(report, null, 2), { mode: 0o600 });
91
+ await writeFile(join(directory, 'report.html'), renderObservationReport(report), { mode: 0o600 });
92
+ if (options.json) console.log(JSON.stringify({ ...report, reportPath: join(directory, 'report.json') }));
93
+ else {
94
+ for (const i of report.intervals) console.log(`Interval ${i.index}: ${i.reads?.calls ?? '?'} reads, ${i.reads?.successes ?? '?'} successes, ${i.reads?.errors ?? '?'} errors${i.findings.length ? '; ' + i.findings.join(', ') : ''}`);
95
+ for (const finding of report.findings) console.log(`Interval ${finding.interval}: ${observationSummary(finding)}`);
96
+ console.log(`Sampling: requested delay ${config.sampleMs} ms; measured mean cadence ${report.sampling.startToStart.meanMs ?? 'unavailable'} ms.`);
97
+ if (report.error) console.error(report.error);
98
+ console.log(`Capture: ${report.status} (not a health verdict)\nReport: ${join(directory, 'report.html')}`);
99
+ }
100
+ process.exitCode = report.captureComplete ? 0 : report.status === 'interrupted' ? 130 : 2;
101
+ }
@@ -15,6 +15,7 @@ Usage:
15
15
  recovery-probe start web http://localhost:3000
16
16
  recovery-probe start desktop
17
17
  recovery-probe refresh --help
18
+ recovery-probe observe --help
18
19
  recovery-probe ipc --help
19
20
  recovery-probe desktop --help
20
21
  recovery-probe web --help
@@ -58,6 +59,10 @@ function printSummary(report) {
58
59
 
59
60
  async function main() {
60
61
  const args = process.argv.slice(2);
62
+ if (args[0] === 'observe') {
63
+ const { observeMain } = await import('./observe.mjs');
64
+ return observeMain(args.slice(1));
65
+ }
61
66
  if (args[0] === 'refresh') {
62
67
  const { refreshMain } = await import('./refresh.mjs');
63
68
  return refreshMain(args.slice(1));
package/docs/ci.md ADDED
@@ -0,0 +1,65 @@
1
+ # A repeatable recovery check in CI
2
+
3
+ This synthetic example shows how to turn a specified recovery expectation into a CI result. It is not automatic discovery or a conversion of an arbitrary happy-path suite. Run it from a Recovery Probe source checkout with Node 22+:
4
+
5
+ ```bash
6
+ npm ci
7
+ npx playwright install --with-deps chromium
8
+ npm run test:ci-example
9
+ ```
10
+
11
+ The verifier runs the same saved `examples/ci/scenario.json` against broken and fixed versions of the bundled app. Both must pass the healthy baseline. It injects exactly one HTTP 503, clicks the explicit Retry button, then requires visible profile content with the exact expected text. The broken app leaves its loading guard set and cannot retry; the fixed app resets the guard and recovers.
12
+
13
+ The verifier only passes when the broken command exits 1 with `RECOVERY_ASSERTION_FAILED`, exactly one applied fault and verified cleanup, and the fixed command exits 0 with the same verified injection. A browser startup error, missed route or failed baseline does not count as detecting the defect. Each child has a 45-second timeout. Individual navigation and selector waits are bounded to 3 seconds. There are no test-runner retries that could hide the broken result.
14
+
15
+ To run a single variant as a normal gate:
16
+
17
+ ```bash
18
+ node examples/ci/run.mjs fixed artifacts/my-recovery-run
19
+ ```
20
+
21
+ Use a new output directory each time. Replace `fixed` with `broken` to observe exit 1. Exit 2 means an inconclusive/setup/cleanup failure. This command only starts the bundled synthetic application; adapting it to a real application requires explicit setup, actions and assertions.
22
+
23
+ Each variant saves `scenario.json`, `report.json`, `summary.md`, and baseline/fault Playwright trace ZIPs when tracing starts successfully. Open a trace locally:
24
+
25
+ ```bash
26
+ npx playwright show-trace artifacts/my-recovery-run/fault-trace.zip
27
+ ```
28
+
29
+ The scenario's selectors and expected text are synthetic. Traces record DOM snapshots, screenshots and sources; real-app traces may contain private data. Select artifact access and retention accordingly.
30
+
31
+ ## GitHub Actions
32
+
33
+ The repository's Browser integration job runs the verifier and uploads artifacts even if a step fails. This standalone example assumes a checkout of this repository:
34
+
35
+ ```yaml
36
+ name: Recovery example
37
+ on: [push, pull_request]
38
+ permissions:
39
+ contents: read
40
+ jobs:
41
+ recovery:
42
+ runs-on: ubuntu-latest
43
+ timeout-minutes: 5
44
+ steps:
45
+ - uses: actions/checkout@v7
46
+ - uses: actions/setup-node@v7
47
+ with:
48
+ node-version: '24'
49
+ cache: npm
50
+ - run: npm ci
51
+ - run: npx playwright install --with-deps chromium
52
+ - run: npm run test:ci-example
53
+ - uses: actions/upload-artifact@v6
54
+ if: always()
55
+ with:
56
+ name: recovery-example
57
+ path: artifacts/ci-example-*/
58
+ retention-days: 7
59
+ ```
60
+
61
+ ## Adapt it to an application
62
+
63
+ Install `recovery-probe@0.3.0-preview.13` and your compatible Playwright runtime. Copy the example's orchestration pattern into your test suite, replace the synthetic server startup with your authorized test application, choose one read-only request and specify the expected recovery action and result. Keep the healthy control, bounded fault count, cleanup, inconclusive outcomes and process exit checks. Run the normal gate against the current app; the deliberately broken variant belongs only in a synthetic verification fixture.
64
+
65
+ This example provides local/CI execution and artifacts. It does not post PR comments, upload to a hosted Recovery Probe service or infer what your product ought to display.
package/docs/desktop.md CHANGED
@@ -38,8 +38,8 @@ Install the exact preview in a separate tester folder:
38
38
  mkdir recovery-probe-desktop-test
39
39
  cd recovery-probe-desktop-test
40
40
  npm init -y
41
- npm view recovery-probe@0.3.0-preview.11 version
42
- npm install --save-dev --save-exact recovery-probe@0.3.0-preview.11 playwright@1.62.1
41
+ npm view recovery-probe@0.3.0-preview.13 version
42
+ npm install --save-dev --save-exact recovery-probe@0.3.0-preview.13 playwright@1.62.1
43
43
  npx recovery-probe desktop --list
44
44
  ```
45
45
 
package/docs/ipc.md CHANGED
@@ -1,5 +1,7 @@
1
1
  # IPC renderer recovery preview
2
2
 
3
+ For cache/navigation evidence that must survive without a reload, see the [fault-free observation workflow](observe.md). The recovery checks below reload the renderer and cannot establish session or account isolation.
4
+
3
5
  This adapter tests renderer recovery after bounded **rejected IPC invocations** or **successful null results**. It supports initial-load discovery and opt-in [refresh experiments](refresh.md). It does not simulate HTTP status codes, Rust transport failures, token refresh, connection banners or native retry behavior. Use only read-only channels in a development build with known fixture data.
4
6
 
5
7
  Unlike renderer HTTP routing, this boundary requires a small main-process hook. The local agent can perform the setup below; no interactive picker is required. Do not edit generated client files or access Electron's private handler map.
@@ -10,8 +12,8 @@ Node 22+ is required for the CLI. Electron 29's bundled Node can load the small
10
12
 
11
13
  ```bash
12
14
  mkdir -p recovery-probe-tools && cd recovery-probe-tools
13
- npm view recovery-probe@0.3.0-preview.11 version
14
- npm install --save-dev --save-exact recovery-probe@0.3.0-preview.11 playwright@1.62.1
15
+ npm view recovery-probe@0.3.0-preview.13 version
16
+ npm install --save-dev --save-exact recovery-probe@0.3.0-preview.13 playwright@1.62.1
15
17
  node -p "require.resolve('recovery-probe/ipc')"
16
18
  ```
17
19
 
@@ -0,0 +1,118 @@
1
+ # Observe reads without resetting the app
2
+
3
+ Available in **0.3.0-preview.12**. Install the exact preview and verify the CLI:
4
+
5
+ ```bash
6
+ npm install --save-dev --save-exact recovery-probe@0.3.0-preview.13 playwright@1.62.1
7
+ npx recovery-probe --version
8
+ ```
9
+
10
+ Use observation when reloading would erase the state you are investigating: cached rows, content carried between screens, or content surviving a session change. The command attaches to an existing development browser/Electron renderer. It never reloads, navigates, clicks, changes focus, clears caches, injects faults, or resets the UI at the end. You operate the app yourself.
11
+
12
+ This is evidence collection, not an identity-isolation test. A cache hit can be correct. Content overlap can be legitimate shared data. No finding establishes whose data is visible or whether a server authorized it correctly.
13
+
14
+ ## Configuration
15
+
16
+ Save a local JSON file, for example `observe.json`:
17
+
18
+ ```json
19
+ {
20
+ "transport": "ipc",
21
+ "cdp": "http://127.0.0.1:9222",
22
+ "inspector": "http://127.0.0.1:9229",
23
+ "channel": "fixture:read-items",
24
+ "regionSelector": "#items-panel",
25
+ "contentSelector": "tbody tr[data-item]",
26
+ "observationMs": 90000,
27
+ "sampleMs": 100
28
+ }
29
+ ```
30
+
31
+ IPC requires the [explicit development hook](ipc.md), loaded **from the same installed package version** before handler registration. It must advertise `observation` and `readTimestamps` capabilities. An old running hook is rejected before starting a plan; reinstalling the CLI alone does not update a hook already loaded in the app. Resolve the updated hook with `node -p "require.resolve('recovery-probe/ipc')"`, update the app's development hook path if needed, and restart the development app **before reproducing the cached state**. The selected window is verified against that hook without reloading it.
32
+
33
+ For renderer HTTP reads, use:
34
+
35
+ ```json
36
+ {
37
+ "transport": "http",
38
+ "cdp": "http://127.0.0.1:9222",
39
+ "page": 0,
40
+ "endpoint": "http://localhost:3000/api/items",
41
+ "regionSelector": "#items-panel",
42
+ "contentSelector": "tbody tr[data-item]",
43
+ "observationMs": 90000,
44
+ "sampleMs": 100
45
+ }
46
+ ```
47
+
48
+ Select an existing page using `desktop --list`. HTTP observes main-frame GET fetch/XHR requests grouped by origin/path. Query values, headers and bodies are not recorded. Native SDK traffic, IPC, service-worker-only traffic, iframes, and other endpoints are outside this HTTP observation. It does not install route interception, so it does not disable the browser's HTTP cache.
49
+
50
+ `regionSelector` must identify at most one region. The region may disappear or become hidden during navigation. `contentSelector` is a CSS selector **inside that region**, chosen to identify actual data rows/cards rather than headings, placeholders or loading skeletons. This explicit marker is the only basis for saying data-dependent content is present. Nothing infers a framework mount, a user id, or ownership from the DOM.
51
+
52
+ The duration is bounded to 500–120000 ms; sampling is bounded to 50–1000 ms. Default duration is 30000 ms and sampling is 100 ms. Setup, protocol operations and cleanup add overhead. An unresponsive UI sample times out after 5 seconds and produces incomplete evidence; Ctrl+C interrupts a pending UI sample. Only one target is counted per capture. Existing fault/discovery configs must be adapted: unrelated options are rejected to avoid silently performing a different experiment.
53
+
54
+ ## Capture a return visit
55
+
56
+ ```bash
57
+ npx recovery-probe observe --config observe.json
58
+ ```
59
+
60
+ 1. Start on a neutral screen and wait for the terminal's `Observing` message.
61
+ 2. Open the data screen and let its read finish. Return to the neutral screen.
62
+ 3. Press Enter in the terminal and wait for `New observation interval`. Open the data screen again.
63
+ 4. Let capture finish, or press Ctrl+C to save partial evidence.
64
+
65
+ Enter starts an interval at the next sample boundary; it does not navigate or reset counters. Thus the second interval can show **zero new reads** while retaining the last observed read/completion time from the first interval. Up to 50 intervals are allowed. Terminal input is not saved as a label; do not type credentials. `--interactive` enables newline markers on piped stdin; without it, noninteractive runs have a single interval. `--json` writes the report to stdout and keeps progress on stderr.
66
+
67
+ To observe a particular cached state that already exists, start on a neutral screen immediately before returning to it. Reads before capture are unknown. Start earlier if you need a measured age of the last read.
68
+
69
+ ## Report provenance and sampling
70
+
71
+ Since preview.13, `metadata` records the installed Recovery Probe version, CLI Node version, browser version when available, and the IPC hook's reported version, runtime and observation capabilities. Older observation-capable hooks remain compatible; unavailable metadata is null. Restart with the new hook if its version/runtime metadata is needed. No environment variables, account information, full user agent or registered-channel inventory is included.
72
+
73
+ `sampleMs` is the requested delay **after each completed sample**, not a guaranteed sampling resolution. `sampling.sampleDuration` summarizes the UI-read-to-counter-snapshot duration; `sampling.startToStart` measures actual cadence, including protocol work, delays and operator callbacks. Both contain count, meanMs, minMs and maxMs. All completed samples contribute, including unchanged samples omitted from the timeline. With no samples the duration statistics are null; with fewer than two samples cadence statistics are null. A timed-out/incomplete sample is not included. `captureComplete` retains its existing meaning and does not guarantee that brief UI flashes were captured.
74
+
75
+ JSON findings retain their codes/bases and add a plain-language `summary`. HTML shows first-content sample bounds relative to each interval rather than an exact paint time.
76
+
77
+ ## Interpretation
78
+
79
+ Local `report.json` and `report.html` contain interval read counts, starts/completions, first-content sample bounds, and a change-only sampled timeline. `scenario.json` records the selected scope. No screenshots, response bodies or raw UI values are saved. Region text and repeated values are hashed; hashes are **not anonymization**, particularly for predictable text. Treat reports and selectors as private evidence.
80
+
81
+ `CONTENT_BEFORE_READ` means the configured content marker was sampled as visible with **no observed completion during that interval**. Its basis distinguishes zero observed starts from an outstanding read. This is an observation requiring interpretation, not a defect verdict. It may include content already present at the interval's first sample; that is recorded explicitly. A read begun in a previous interval is represented by `pendingAtStart`.
82
+
83
+ The observer brackets each UI sample with read snapshots. If a completion arrives during that sample, it does not claim content preceded that completion. Timestamps are epoch milliseconds from the observer/hook clock; ages are measured within the same clock. Pre-capture history and pre-capture pending work remain unknown. An HTTP success means a completed 2xx response, not JSON validation or application success. IPC completion means handler settlement, not renderer consumption.
84
+
85
+ This release has no automatic login steps, operator identity assertions, identity callback, ownership oracle, or `CROSS_IDENTITY_CONTENT` verdict. A separate account-switch experiment needs evidence about identity and expected data sharing. Reload-based recovery and refresh checks still reset renderer state and cannot establish session isolation.
86
+
87
+ Capture ends without touching UI state. HTTP listeners are detached; the owned IPC observation lease is ended with its run id. Faults cannot be included in an observation plan, and an active foreign plan is never replaced. An observation lease also expires if the client disappears. Calls already started may finish normally after capture.
88
+
89
+ A document reload/navigation ends capture as incomplete because the renderer state may have been reset; SPA navigation is allowed. Hidden-document samples and truncated regions are coverage gaps. Very short flashes between samples may be missed. If the content marker is never observed, `CONTENT_MARKER_NOT_OBSERVED` records the missing evidence; it may reflect an empty screen, an unvisited route, or a wrong selector. Exit `0` means the bounded capture completed without recorded coverage gaps; `2` means incomplete coverage or a setup/cleanup error; `130` means operator interruption. None means a recovery or security pass.
90
+
91
+ ## Supported inspector API
92
+
93
+ Advanced scripts can use `recovery-probe/ipc-inspector` after installing preview.12, without importing private `src/` paths:
94
+
95
+ ```js
96
+ import { randomUUID } from 'node:crypto';
97
+ import { connectIpcInspector } from 'recovery-probe/ipc-inspector';
98
+
99
+ const control = await connectIpcInspector('http://127.0.0.1:9229');
100
+ const id = randomUUID();
101
+ try {
102
+ // Explicitly bounded, fault-free, and protected against replacing active plans.
103
+ await control.call('begin', {
104
+ id, channel: 'fixture:read-items', observation: true, ttlMs: 30000
105
+ });
106
+ // Operate the application in your own harness, then collect evidence.
107
+ const snapshot = await control.call('snapshot');
108
+ if (snapshot?.id !== id || !snapshot.observingUntil) throw Error('Observation coverage lost');
109
+ console.log(snapshot.channels['fixture:read-items']);
110
+ } finally {
111
+ try { await control.call('reset', id); }
112
+ finally { control.close(); }
113
+ }
114
+ ```
115
+
116
+ `callIpcInspector(send, method, argument)` is also exported for custom Node inspector transports. It accepts only the existing probe control method allowlist. The CLI additionally performs window matching and cleanup readback; advanced callers must implement those checks themselves. Never retry `begin` after an uncertain reply. Use the same id for cleanup; never use an unscoped reset against shared tooling.
117
+
118
+ Each channel snapshot adds `firstReadAt`, `lastReadAt`, `firstCompletedAt`, `lastCompletedAt`, and `lastSuccessAt` (null until observed). `startedAt` and `capturedAt` belong to the plan/snapshot. `observation: true` opts into the bounded fault-free lease; ordinary fault-free `begin` calls retain their existing recovery-control semantics.
package/docs/start.md CHANGED
@@ -10,8 +10,8 @@ Install the exact npm preview after confirming availability:
10
10
 
11
11
  ```bash
12
12
  mkdir recovery-probe-tools && cd recovery-probe-tools
13
- npm view recovery-probe@0.3.0-preview.11 version
14
- npm install --save-dev --save-exact recovery-probe@0.3.0-preview.11 playwright@1.62.1
13
+ npm view recovery-probe@0.3.0-preview.13 version
14
+ npm install --save-dev --save-exact recovery-probe@0.3.0-preview.13 playwright@1.62.1
15
15
  npx recovery-probe start web http://localhost:3000
16
16
  ```
17
17
 
@@ -0,0 +1,70 @@
1
+ // Runnable synthetic CI example. Adapt the fixture, actions and assertions to your app.
2
+ import assert from 'node:assert/strict';
3
+ import { readFile, mkdir, writeFile } from 'node:fs/promises';
4
+ import { resolve, join } from 'node:path';
5
+ import { chromium } from 'playwright';
6
+ import { withFault } from 'recovery-probe';
7
+ import { startDemoServer } from '../demo-server.mjs';
8
+
9
+ const variant = process.argv[2];
10
+ const output = process.argv[3];
11
+ if (!['broken', 'fixed'].includes(variant) || !output || process.argv.length !== 4) {
12
+ console.error('Usage: node examples/ci/run.mjs broken|fixed NEW_OUTPUT_DIRECTORY');
13
+ process.exitCode = 2;
14
+ } else {
15
+ const directory = resolve(output);
16
+ await mkdir(directory, { mode: 0o700 }); // Never overwrite a previous experiment.
17
+ const scenario = JSON.parse(await readFile(new URL('./scenario.json', import.meta.url), 'utf8'));
18
+ const report = { variant, status: 'inconclusive', code: 'SETUP_FAILED', baseline: false, fault: null, cleanup: 'not-started' };
19
+ let server, browser;
20
+ try {
21
+ server = await startDemoServer();
22
+ browser = await chromium.launch();
23
+ async function inPage(name, exercise) {
24
+ const context = await browser.newContext({ serviceWorkers: 'block' });
25
+ try {
26
+ await context.tracing.start({ screenshots: true, snapshots: true, sources: true });
27
+ const page = await context.newPage();
28
+ page.setDefaultTimeout(scenario.timeoutMs);
29
+ page.setDefaultNavigationTimeout(scenario.timeoutMs);
30
+ await exercise(page);
31
+ } finally {
32
+ try { await context.tracing.stop({ path: join(directory, `${name}-trace.zip`) }); }
33
+ finally { await context.close(); }
34
+ }
35
+ }
36
+ const ready = async page => {
37
+ await page.locator(scenario.readySelector).waitFor({ state: 'visible' });
38
+ assert.equal(await page.locator(scenario.readySelector).textContent(), scenario.expectedText);
39
+ };
40
+ await inPage('baseline', async page => {
41
+ await page.goto(`${server.url}/${variant}`, { waitUntil: 'domcontentloaded' });
42
+ await ready(page);
43
+ });
44
+ report.baseline = true;
45
+ await inPage('fault', async page => {
46
+ report.fault = await withFault(page, { ...scenario.fault, match: `${server.url}${scenario.requestPath}`, method: 'GET' }, async () => {
47
+ await page.goto(`${server.url}/${variant}`, { waitUntil: 'domcontentloaded' });
48
+ await page.locator(scenario.retrySelector).waitFor({ state: 'visible' });
49
+ await page.locator(scenario.retrySelector).click();
50
+ await ready(page);
51
+ });
52
+ });
53
+ assert.equal(report.fault.applied, 1);
54
+ report.status = 'pass'; report.code = 'OK';
55
+ } catch (error) {
56
+ report.status = error.code === 'RECOVERY_ASSERTION_FAILED' ? 'fail' : 'inconclusive';
57
+ report.code = error.code ?? 'RUNNER_ERROR';
58
+ report.fault = error.stats ?? report.fault;
59
+ } finally {
60
+ const cleanup = await Promise.allSettled([browser?.close(), server?.close()]);
61
+ report.cleanup = cleanup.every(r => r.status === 'fulfilled') ? 'complete' : 'unverified';
62
+ if (report.cleanup !== 'complete') { report.status = 'inconclusive'; report.code = 'CLEANUP_FAILED'; }
63
+ }
64
+ await writeFile(join(directory, 'scenario.json'), JSON.stringify(scenario, null, 2), { mode: 0o600 });
65
+ await writeFile(join(directory, 'report.json'), JSON.stringify(report, null, 2), { mode: 0o600 });
66
+ const summary = `| Variant | Baseline | Faults applied | Result | Code |\n| --- | --- | --- | --- | --- |\n| ${variant} | ${report.baseline ? 'passed' : 'not established'} | ${report.fault?.applied ?? 0} | ${report.status} | ${report.code} |\n`;
67
+ await writeFile(join(directory, 'summary.md'), summary, { mode: 0o600 });
68
+ console.log(summary);
69
+ process.exitCode = report.status === 'pass' ? 0 : report.status === 'fail' ? 1 : 2;
70
+ }
@@ -0,0 +1,8 @@
1
+ {
2
+ "requestPath": "/api/profile",
3
+ "readySelector": "#profile",
4
+ "expectedText": "Synthetic Example",
5
+ "retrySelector": "#retry",
6
+ "timeoutMs": 3000,
7
+ "fault": { "kind": "http-error", "status": 503, "count": 1 }
8
+ }
@@ -0,0 +1,26 @@
1
+ // Verify both the CLI exit status and evidence: an unrelated crash is never the expected failure.
2
+ import assert from 'node:assert/strict';
3
+ import { spawn } from 'node:child_process';
4
+ import { mkdir, mkdtemp, readFile, appendFile } from 'node:fs/promises';
5
+ import { fileURLToPath } from 'node:url';
6
+ import { resolve, join } from 'node:path';
7
+ await mkdir('artifacts', { recursive: true });
8
+ const directory = await mkdtemp(resolve('artifacts/ci-example-'));
9
+ for (const variant of ['broken', 'fixed']) {
10
+ const output = join(directory, variant);
11
+ const code = await new Promise((done, reject) => {
12
+ const child = spawn(process.execPath, [fileURLToPath(new URL('./run.mjs', import.meta.url)), variant, output], { stdio: 'inherit', timeout: 45000 });
13
+ child.once('error', reject);
14
+ child.once('exit', (status, signal) => signal ? reject(Error(`Example stopped: ${signal}`)) : done(status));
15
+ });
16
+ if (process.env.GITHUB_STEP_SUMMARY) await appendFile(process.env.GITHUB_STEP_SUMMARY, await readFile(join(output, 'summary.md'), 'utf8'));
17
+ const report = JSON.parse(await readFile(join(output, 'report.json'), 'utf8'));
18
+ assert.equal(report.baseline, true);
19
+ assert.equal(report.fault.applied, 1);
20
+ assert.equal(report.fault.injectionErrors, 0);
21
+ assert.equal(report.cleanup, 'complete');
22
+ assert.equal(code, variant === 'broken' ? 1 : 0);
23
+ assert.equal(report.status, variant === 'broken' ? 'fail' : 'pass');
24
+ assert.equal(report.code, variant === 'broken' ? 'RECOVERY_ASSERTION_FAILED' : 'OK');
25
+ }
26
+ console.log(`Broken/fixed CI example verified. Artifacts: ${directory}`);
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "recovery-probe",
3
- "version": "0.3.0-preview.11",
3
+ "version": "0.3.0-preview.13",
4
4
  "type": "module",
5
5
  "description": "Test recovery from failed reads in web and Electron desktop apps, during loading and refresh.",
6
6
  "license": "MIT",
@@ -29,6 +29,10 @@
29
29
  "import": "./src/web.mjs",
30
30
  "default": "./src/web.mjs"
31
31
  },
32
+ "./ipc-inspector": {
33
+ "types": "./src/ipc-inspector.d.mts",
34
+ "import": "./src/ipc-inspector.mjs"
35
+ },
32
36
  "./ipc": {
33
37
  "types": "./src/ipc-probe.d.cts",
34
38
  "import": "./src/ipc-probe.cjs",
@@ -52,7 +56,9 @@
52
56
  "docs/repair.md",
53
57
  "docs/start.md",
54
58
  "docs/ipc.md",
55
- "docs/refresh.md"
59
+ "docs/refresh.md",
60
+ "docs/observe.md",
61
+ "docs/ci.md"
56
62
  ],
57
63
  "sideEffects": false,
58
64
  "engines": {
@@ -98,9 +104,9 @@
98
104
  "scripts": {
99
105
  "test": "npm run test:core",
100
106
  "test:core": "node --test test/fetch-core.test.mjs",
101
- "test:browser": "node --test test/recovery.integration.test.mjs test/discovery.integration.test.mjs test/discovery-calibration.integration.test.mjs test/attach.integration.test.mjs test/refresh.integration.test.mjs",
107
+ "test:browser": "node --test test/recovery.integration.test.mjs test/discovery.integration.test.mjs test/discovery-calibration.integration.test.mjs test/attach.integration.test.mjs test/refresh.integration.test.mjs test/observe.integration.test.mjs",
102
108
  "test:package": "node --test test/package.integration.test.mjs",
103
- "test:all": "npm run test:core && npm run test:package && npm run test:browser && npm run test:desktop && npm run test:repair && npm run test:guided && npm run test:ipc",
109
+ "test:all": "npm run test:core && npm run test:package && npm run test:browser && npm run test:desktop && npm run test:repair && npm run test:guided && npm run test:ipc && npm run test:ci-example",
104
110
  "demo": "node bin/core-demo.mjs",
105
111
  "demo:browser": "node bin/recovery-probe.mjs --demo --out artifacts/browser-demo.json",
106
112
  "prepublishOnly": "npm run test:core && npm run test:package && npm run test:ipc",
@@ -109,7 +115,8 @@
109
115
  "test:repair": "node --test test/repair.test.mjs test/repair.integration.test.mjs test/web.integration.test.mjs",
110
116
  "test:repair:electron": "node --test test/repair.electron.test.mjs",
111
117
  "test:guided": "node --test test/guided-start.test.mjs test/guided-start.integration.test.mjs",
112
- "test:ipc": "node --test test/ipc-probe.test.mjs test/ipc-control.test.mjs test/ipc-observation.test.mjs test/visibility.test.mjs test/refresh.test.mjs",
113
- "test:ipc:electron": "node --test test/ipc.electron.test.mjs"
118
+ "test:ipc": "node --test test/ipc-probe.test.mjs test/ipc-control.test.mjs test/ipc-observation.test.mjs test/visibility.test.mjs test/refresh.test.mjs test/observe.test.mjs test/observation-report.test.mjs",
119
+ "test:ipc:electron": "node --test --test-concurrency=1 test/ipc.electron.test.mjs test/observe.electron.test.mjs",
120
+ "test:ci-example": "node examples/ci/verify.mjs"
114
121
  }
115
122
  }
@@ -1,7 +1,8 @@
1
1
  import { performance } from 'node:perf_hooks';
2
2
  import { pageIdentity } from './desktop.mjs';
3
3
  export async function observeHttp(page, { endpoint, requiredEndpoints = [], fault, times = 1 }) {
4
- const channels = Object.fromEntries([endpoint, ...requiredEndpoints].map(e => [e, { calls: 0, realCalls: 0, successes: 0, errors: 0, pending: 0, maxDurationMs: 0 }]));
4
+ const channels = Object.fromEntries([endpoint, ...requiredEndpoints].map(e => [e, { calls: 0, realCalls: 0, successes: 0, errors: 0, pending: 0, maxDurationMs: 0, firstReadAt: null, lastReadAt: null, firstCompletedAt: null, lastCompletedAt: null, lastSuccessAt: null }]));
5
+ const startedAt = Date.now();
5
6
  const requests = new Map(), coverage = new Map(), operations = new Set();
6
7
  let reserved = 0, applied = 0, injectedAt = null, successfulAfterFault = 0, active = true, injectionError = false;
7
8
  let routed = Boolean(fault);
@@ -13,6 +14,7 @@ export async function observeHttp(page, { endpoint, requiredEndpoints = [], faul
13
14
  const row = r.method() === 'GET' && channels[url];
14
15
  if (!row) return;
15
16
  row.calls++; row.realCalls++; row.pending++;
17
+ row.firstReadAt ??= Date.now(); row.lastReadAt = Date.now();
16
18
  requests.set(r, { row, start: performance.now(), injected: false, afterFault: reserved === times && injectedAt !== null, target: url === endpoint });
17
19
  };
18
20
  const finish = async (r, failed) => {
@@ -21,8 +23,10 @@ export async function observeHttp(page, { endpoint, requiredEndpoints = [], faul
21
23
  const response = failed ? null : await r.response().catch(() => null);
22
24
  meta.row.pending--;
23
25
  if (meta.injected) return;
26
+ const completed = Date.now();
27
+ meta.row.firstCompletedAt ??= completed; meta.row.lastCompletedAt = completed;
24
28
  meta.row.maxDurationMs = Math.max(meta.row.maxDurationMs, Math.round(performance.now() - meta.start));
25
- if (response?.ok()) { meta.row.successes++; if (meta.target && meta.afterFault) successfulAfterFault++; }
29
+ if (response?.ok()) { meta.row.successes++; meta.row.lastSuccessAt = completed; if (meta.target && meta.afterFault) successfulAfterFault++; }
26
30
  else meta.row.errors++;
27
31
  };
28
32
  const finished = r => { const p = finish(r, false); operations.add(p); p.finally(() => operations.delete(p)); };
@@ -47,7 +51,7 @@ export async function observeHttp(page, { endpoint, requiredEndpoints = [], faul
47
51
  try { if (fault) await page.route(match, handler); }
48
52
  catch (error) { page.off('request', request); page.off('requestfinished', finished); page.off('requestfailed', failed); throw error; }
49
53
  return {
50
- snapshot: () => ({ injected: applied, injectedAt, successfulAfterFault, injectionError, armed: fault && active && reserved < times ? { remaining: times - reserved } : null, channels: structuredClone(channels) }),
54
+ snapshot: () => ({ startedAt, capturedAt: Date.now(), injected: applied, injectedAt, successfulAfterFault, injectionError, armed: fault && active && reserved < times ? { remaining: times - reserved } : null, channels: structuredClone(channels) }),
51
55
  coverage: () => [...coverage.values()],
52
56
  async disarm() {
53
57
  active = false;
@@ -0,0 +1,13 @@
1
+ import type { IpcProbe, IpcSnapshot } from './ipc-probe.cjs';
2
+ export interface IpcInspector {
3
+ call(method: 'identify', challenge?: string): Promise<ReturnType<IpcProbe['identify']> extends Promise<infer T> ? T : never>;
4
+ call(method: 'begin', options: Parameters<IpcProbe['begin']>[0]): Promise<IpcSnapshot>;
5
+ call(method: 'snapshot'): Promise<IpcSnapshot | null>;
6
+ call(method: 'reset', id?: string): Promise<IpcSnapshot | null>;
7
+ call(method: 'windowState'): Promise<{ minimized: boolean }>;
8
+ call(method: 'setWindowMinimized', minimized: boolean): Promise<{ minimized: boolean }>;
9
+ close(): void;
10
+ }
11
+ export function connectIpcInspector(endpoint?: string): Promise<IpcInspector>;
12
+ /** Advanced protocol transport; only the documented probe control methods are allowed. */
13
+ export function callIpcInspector(send: (method: string, params: Record<string, unknown>) => Promise<any>, method: 'identify' | 'begin' | 'snapshot' | 'reset' | 'windowState' | 'setWindowMinimized', argument?: unknown): Promise<any>;
@@ -3,10 +3,17 @@ const hash = value => createHash('sha256').update(value).digest('hex');
3
3
 
4
4
  // Runs in the page. Neither raw text nor attribute values are persisted.
5
5
  export function readRegion(selector) {
6
+ const observation = typeof selector === 'object' && selector !== null ? selector : null;
7
+ if (observation) {
8
+ selector = observation.regionSelector;
9
+ document.querySelector(observation.contentSelector); // Validate even when the region is absent.
10
+ }
6
11
  const roots = selector ? document.querySelectorAll(selector) : null;
12
+ if (observation && roots?.length === 0) return { presence: 'absent', contentCount: 0, visible: document.visibilityState === 'visible', online: navigator.onLine };
7
13
  if (roots && roots.length !== 1) throw new Error('regionSelector must identify one region');
8
14
  const root = roots?.[0] ?? document.querySelector('main, [role="main"]') ?? document.body;
9
15
  const visible = e => !!(e.getClientRects().length && getComputedStyle(e).visibility !== 'hidden' && getComputedStyle(e).display !== 'none');
16
+ if (observation && !visible(root)) return { presence: 'hidden', contentCount: 0, visible: document.visibilityState === 'visible', online: navigator.onLine };
10
17
  const nodes = [...root.querySelectorAll('*')].filter(visible).slice(0, 5000);
11
18
  const count = s => [...root.querySelectorAll(s)].filter(visible).length;
12
19
  const text = (root.innerText ?? '').replace(/\s+/g, ' ').trim();
@@ -49,6 +56,7 @@ export function readRegion(selector) {
49
56
  }
50
57
  }
51
58
  return { text, structure, groups, distributions,
59
+ ...(observation ? { presence: 'visible', contentCount: [...root.querySelectorAll(observation.contentSelector)].filter(visible).length } : {}),
52
60
  region: selector ? 'selected' : root === document.body ? 'body' : 'main',
53
61
  truncated: root.querySelectorAll('*').length > 5000,
54
62
  visible: document.visibilityState === 'visible', online: navigator.onLine,
package/src/ipc-probe.cjs CHANGED
@@ -1,4 +1,5 @@
1
1
  'use strict';
2
+ const { version } = require('../package.json');
2
3
 
3
4
  const installed = new WeakSet();
4
5
 
@@ -18,7 +19,7 @@ exports.installIpcProbe = function installIpcProbe(ipcMain, { channels, sender,
18
19
  const identify = challenge => {
19
20
  const contents = sender();
20
21
  if (!contents || contents.isDestroyed()) throw new Error('Target WebContents is not available');
21
- const identity = { senderId: contents.id, pageUrl: contents.getURL(), registered: [...registered], capabilities: { maxFaultCount: 10 } };
22
+ const identity = { version, runtime: { node: process.versions.node, electron: process.versions.electron ?? null, chrome: process.versions.chrome ?? null }, senderId: contents.id, pageUrl: contents.getURL(), registered: [...registered], capabilities: { maxFaultCount: 10, observation: true, readTimestamps: true } };
22
23
  if (challenge === undefined) return identity;
23
24
  if (typeof challenge !== 'string' || !/^[a-f0-9-]{36}$/.test(challenge)) throw new Error('Invalid window challenge');
24
25
  return contents.executeJavaScript(`globalThis.__recoveryProbeWindowNonce === ${JSON.stringify(challenge)}`).then(matches => {
@@ -30,12 +31,12 @@ exports.installIpcProbe = function installIpcProbe(ipcMain, { channels, sender,
30
31
  const contents = sender();
31
32
  return contents && !contents.isDestroyed() && event?.sender === contents && contents.mainFrame && event.senderFrame === contents.mainFrame;
32
33
  };
33
- const disarm = () => { clearTimeout(timer); if (state) state.armed = null; };
34
+ const disarm = () => { clearTimeout(timer); if (state) { state.armed = null; state.observingUntil = null; } };
34
35
  const snapshot = () => {
35
- if (state?.armed && Date.now() >= state.armed.expiresAt) disarm();
36
- return state ? JSON.parse(JSON.stringify(state)) : null;
36
+ if ((state?.armed && Date.now() >= state.armed.expiresAt) || (state?.observingUntil && Date.now() >= state.observingUntil)) disarm();
37
+ return state ? JSON.parse(JSON.stringify({ ...state, capturedAt: Date.now() })) : null;
37
38
  };
38
- const begin = ({ id, channel, requiredChannels = [], fault, times = 1, ttlMs = 30000 } = {}) => {
39
+ const begin = ({ id, channel, requiredChannels = [], fault, observation = false, times = 1, ttlMs = 30000 } = {}) => {
39
40
  if (!active) throw new Error('IPC probe is disposed');
40
41
  if (typeof id !== 'string' || !id || id.length > 100 || seenIds.has(id)) throw new Error('Use a new non-empty run ID');
41
42
  if (seenIds.size >= 10000) throw new Error('Restart the dev app after 10000 probe runs');
@@ -43,24 +44,29 @@ exports.installIpcProbe = function installIpcProbe(ipcMain, { channels, sender,
43
44
  const watched = [...new Set([channel, ...requiredChannels])];
44
45
  if (watched.some(c => !allowed.has(c) || !registered.has(c))) throw new Error('All watched channels must be allowed and registered after installing the probe');
45
46
  if (fault !== undefined && !['rejection', 'null-result'].includes(fault)) throw new Error('Supported IPC faults: rejection, null-result');
47
+ if (typeof observation !== 'boolean' || (observation && fault !== undefined)) throw new Error('Observation must be fault-free');
46
48
  if (!Number.isInteger(times) || times < 1 || times > 10) throw new Error('times must be 1–10');
47
- if (!Number.isInteger(ttlMs) || ttlMs < 100 || ttlMs > 60000) throw new Error('ttlMs must be 100–60000');
49
+ if (!Number.isInteger(ttlMs) || ttlMs < 100 || ttlMs > (observation ? 125000 : 60000)) throw new Error('ttlMs exceeds the supported bounds');
50
+ snapshot(); // Expire a previous lease before the atomic ownership check.
51
+ if (state?.observingUntil || (observation && state?.armed)) throw new Error('IPC_PLAN_ALREADY_ACTIVE');
48
52
  if (state && Object.values(state.channels).some(c => c.pending)) throw new Error('Previous real calls are still pending; wait before beginning another run');
49
53
  const identity = identify();
50
54
  disarm(); seenIds.add(id);
51
- state = { id, channel, senderId: identity.senderId, injected: 0, injectedAt: null, successfulAfterFault: 0, armed: fault ? { fault, remaining: times, expiresAt: Date.now() + ttlMs } : null, channels: Object.create(null) };
52
- for (const name of watched) state.channels[name] = { calls: 0, realCalls: 0, successes: 0, errors: 0, pending: 0, maxDurationMs: 0 };
53
- if (fault) { timer = setTimeout(disarm, ttlMs); timer.unref?.(); }
55
+ state = { id, channel, senderId: identity.senderId, startedAt: Date.now(), observation, observingUntil: observation ? Date.now() + ttlMs : null, injected: 0, injectedAt: null, successfulAfterFault: 0, armed: fault ? { fault, remaining: times, expiresAt: Date.now() + ttlMs } : null, channels: Object.create(null) };
56
+ for (const name of watched) state.channels[name] = { calls: 0, realCalls: 0, successes: 0, errors: 0, pending: 0, maxDurationMs: 0, firstReadAt: null, lastReadAt: null, firstCompletedAt: null, lastCompletedAt: null, lastSuccessAt: null };
57
+ if (fault || observation) { timer = setTimeout(disarm, ttlMs); timer.unref?.(); }
54
58
  return snapshot();
55
59
  };
56
60
  function handle(channel, real) {
57
61
  if (!allowed.has(channel)) return Reflect.apply(original, this, [channel, real]);
58
62
  if (typeof real !== 'function') return Reflect.apply(original, this, [channel, real]);
59
63
  function dispatch(event, ...args) {
64
+ if (state?.observingUntil && Date.now() >= state.observingUntil) disarm();
60
65
  const current = state;
61
- const row = active && current && matches(event) && event.sender.id === current.senderId ? current.channels[channel] : null;
66
+ const row = active && current && (!current.observation || current.observingUntil) && matches(event) && event.sender.id === current.senderId ? current.channels[channel] : null;
62
67
  if (!row) return Reflect.apply(real, this, [event, ...args]);
63
68
  row.calls++;
69
+ row.firstReadAt ??= Date.now(); row.lastReadAt = Date.now();
64
70
  if (current.armed && Date.now() >= current.armed.expiresAt) disarm();
65
71
  if (channel === current.channel && current.armed) {
66
72
  const fault = current.armed.fault;
@@ -72,6 +78,9 @@ exports.installIpcProbe = function installIpcProbe(ipcMain, { channels, sender,
72
78
  const started = Date.now();
73
79
  const afterFault = current.injected > 0;
74
80
  const finish = success => {
81
+ const completed = Date.now();
82
+ row.firstCompletedAt ??= completed; row.lastCompletedAt = completed;
83
+ if (success) row.lastSuccessAt = completed;
75
84
  row.pending--; row.maxDurationMs = Math.max(row.maxDurationMs, Date.now() - started);
76
85
  if (success) { row.successes++; if (afterFault && channel === current.channel) current.successfulAfterFault++; }
77
86
  else row.errors++;
@@ -3,14 +3,15 @@ export interface ProbeWebContents {
3
3
  }
4
4
  export interface IpcSnapshot {
5
5
  id: string; channel: string; senderId: number; injected: number;
6
+ startedAt: number; capturedAt: number; observation: boolean; observingUntil: number | null;
6
7
  injectedAt: number | null; successfulAfterFault: number;
7
8
  armed: { fault: 'rejection' | 'null-result'; remaining: number; expiresAt: number } | null;
8
- channels: Record<string, { calls: number; realCalls: number; successes: number; errors: number; pending: number; maxDurationMs: number }>;
9
+ channels: Record<string, { calls: number; realCalls: number; successes: number; errors: number; pending: number; maxDurationMs: number; firstReadAt: number | null; lastReadAt: number | null; firstCompletedAt: number | null; lastCompletedAt: number | null; lastSuccessAt: number | null }>;
9
10
  }
10
11
  export interface IpcProbe {
11
- identify(): { senderId: number; pageUrl: string; registered: string[]; capabilities: { maxFaultCount: number } };
12
- identify(challenge: string): Promise<{ senderId: number; pageUrl: string; registered: string[]; capabilities: { maxFaultCount: number } }>;
13
- begin(options: { id: string; channel: string; requiredChannels?: string[]; fault?: 'rejection' | 'null-result'; times?: number; ttlMs?: number }): IpcSnapshot;
12
+ identify(): { version: string; runtime: { node: string; electron: string | null; chrome: string | null }; senderId: number; pageUrl: string; registered: string[]; capabilities: { maxFaultCount: number; observation: true; readTimestamps: true } };
13
+ identify(challenge: string): Promise<{ version: string; runtime: { node: string; electron: string | null; chrome: string | null }; senderId: number; pageUrl: string; registered: string[]; capabilities: { maxFaultCount: number; observation: true; readTimestamps: true } }>;
14
+ begin(options: { id: string; channel: string; requiredChannels?: string[]; times?: number; ttlMs?: number } & ({ observation: true; fault?: never } | { observation?: false; fault?: 'rejection' | 'null-result' })): IpcSnapshot;
14
15
  snapshot(): IpcSnapshot | null;
15
16
  windowState(): { minimized: boolean };
16
17
  setWindowMinimized(minimized: boolean): { minimized: boolean };
@@ -0,0 +1,42 @@
1
+ import { createRequire } from 'node:module';
2
+ const { version } = createRequire(import.meta.url)('../package.json');
3
+
4
+ export function observationMetadata() {
5
+ return { recoveryProbeVersion: version, runtime: { node: process.versions.node }, browserVersion: null, ipcHook: null };
6
+ }
7
+
8
+ // Aggregate every completed sample, including samples omitted from the change-only timeline.
9
+ export function samplingMetrics(requestedDelayMs) {
10
+ let previous, count = 0, sum = 0, min = Infinity, max = 0;
11
+ let gaps = 0, gapSum = 0, gapMin = Infinity, gapMax = 0;
12
+ return {
13
+ add(fromMs, toMs) {
14
+ const duration = toMs - fromMs;
15
+ count++; sum += duration; min = Math.min(min, duration); max = Math.max(max, duration);
16
+ if (previous !== undefined) {
17
+ const gap = fromMs - previous;
18
+ gaps++; gapSum += gap; gapMin = Math.min(gapMin, gap); gapMax = Math.max(gapMax, gap);
19
+ }
20
+ previous = fromMs;
21
+ },
22
+ snapshot() {
23
+ const stats = (n, total, low, high) => ({ count: n, meanMs: n ? Math.round(total / n * 100) / 100 : null, minMs: n ? low : null, maxMs: n ? high : null });
24
+ return { requestedDelayMs, completedSamples: count,
25
+ sampleDuration: stats(count, sum, min, max), startToStart: stats(gaps, gapSum, gapMin, gapMax),
26
+ note: 'The configured delay follows each completed sample. Sample duration brackets the UI read and following counter snapshot; cadence also includes other protocol work. These are completed-sample measurements, not guaranteed temporal coverage.' };
27
+ },
28
+ };
29
+ }
30
+
31
+ export function observationSummary(finding) {
32
+ if (finding.basis === 'NO_READ_OBSERVED_IN_INTERVAL') return 'Content was visible without a new selected read in this interval.';
33
+ if (finding.basis === 'NO_COMPLETION_OBSERVED_IN_INTERVAL') return 'Content was visible before any selected read completed in this interval (a read was pending or had started).';
34
+ return 'Content/read ordering was observed; inspect the evidence.';
35
+ }
36
+
37
+ const escape = value => String(value).replace(/[&<>"']/g, c => ({ '&': '&amp;', '<': '&lt;', '>': '&gt;', '"': '&quot;', "'": '&#39;' }[c]));
38
+ export function renderObservationReport(report) {
39
+ const rows = report.intervals.map(i => `<tr><td>${i.index}</td><td>${i.reads?.calls ?? 'unknown'}</td><td>${i.reads?.successes ?? 'unknown'}</td><td>${i.reads?.errors ?? 'unknown'}</td><td>${i.firstContent ? `${i.firstContent.fromMs - i.startMs}–${i.firstContent.toMs - i.startMs} ms` : 'not sampled'}</td></tr>`).join('');
40
+ const sampling = report.sampling;
41
+ return `<!doctype html><meta charset="utf-8"><title>Recovery Probe observation</title><style>body{font:16px system-ui;max-width:1000px;margin:40px auto;padding:20px}td,th{text-align:left;padding:8px}pre{white-space:pre-wrap;overflow-wrap:anywhere}</style><h1>Fault-free observation</h1><p>Capture: ${escape(report.status)}. This is not a recovery or account-isolation verdict.</p><p>Recovery Probe ${escape(report.metadata?.recoveryProbeVersion ?? 'unknown')} · Node ${escape(report.metadata?.runtime?.node ?? 'unknown')} · Browser ${escape(report.metadata?.browserVersion ?? 'unknown')} · IPC hook ${escape(report.metadata?.ipcHook?.version ?? 'unknown / not applicable')}</p>${sampling ? `<p>Configured delay: ${sampling.requestedDelayMs} ms. Completed samples: ${sampling.completedSamples}. Mean sample duration: ${sampling.sampleDuration.meanMs ?? 'unavailable'} ms. Mean start-to-start cadence: ${sampling.startToStart.meanMs ?? 'unavailable'} ms (maximum ${sampling.startToStart.maxMs ?? 'unavailable'} ms).</p><p>${escape(sampling.note)}</p>` : ''}<p>${escape(report.limitation ?? report.error)}</p><table><thead><tr><th>Interval</th><th>Reads started</th><th>Successes</th><th>Errors</th><th>First content sample bounds</th></tr></thead><tbody>${rows}</tbody></table>${report.findings.map(f => `<p>Interval ${f.interval}: ${escape(observationSummary(f))} <strong>${escape(f.code)}</strong> — ${escape(f.basis)}</p>`).join('')}<details><summary>Evidence and coverage</summary><pre>${escape(JSON.stringify(report, null, 2))}</pre></details>`;
42
+ }
@@ -0,0 +1,202 @@
1
+ import { observationMetadata, samplingMetrics, observationSummary } from './observation-report.mjs';
2
+ import { performance } from 'node:perf_hooks';
3
+ import { randomUUID } from 'node:crypto';
4
+ import { readRegion, summarizeRegion } from './ipc-observation.mjs';
5
+ import { observeHttp } from './http-observer.mjs';
6
+
7
+ export function observationConfig(input) {
8
+ if (!input || typeof input !== 'object' || Array.isArray(input)) throw Error('Observation config must be an object');
9
+ const c = { transport: undefined, cdp: 'http://127.0.0.1:9222', inspector: 'http://127.0.0.1:9229', page: undefined, pageUrl: undefined,
10
+ channel: undefined, endpoint: undefined, regionSelector: undefined, contentSelector: undefined, observationMs: 30000, sampleMs: 100 };
11
+ for (const key of Object.keys(input)) {
12
+ if (!Object.hasOwn(c, key)) throw Error(`Unsupported observation option: ${key}`);
13
+ c[key] = input[key];
14
+ }
15
+ if (!['http', 'ipc'].includes(c.transport)) throw Error('transport must be http or ipc');
16
+ for (const key of ['regionSelector', 'contentSelector']) if (typeof c[key] !== 'string' || !c[key].trim()) throw Error(`${key} must be an explicit CSS selector`);
17
+ for (const [key, low, high] of [['observationMs', 500, 120000], ['sampleMs', 50, 1000]]) {
18
+ if (!Number.isInteger(c[key]) || c[key] < low || c[key] > high) throw Error(`${key} must be ${low}–${high}`);
19
+ }
20
+ if (c.page !== undefined && (!Number.isInteger(c.page) || c.page < 0)) throw Error('page must be a non-negative integer');
21
+ for (const key of ['cdp', 'inspector']) {
22
+ const url = new URL(c[key]);
23
+ if (!['http:', 'ws:'].includes(url.protocol) || !['localhost', '127.0.0.1', '[::1]'].includes(url.hostname) || url.username || url.password) throw Error(`${key} must be a loopback HTTP or WebSocket address without credentials`);
24
+ }
25
+ if (c.transport === 'http') {
26
+ const url = new URL(c.endpoint);
27
+ if (!['http:', 'https:'].includes(url.protocol) || url.username || url.password || url.search || url.hash) throw Error('endpoint must be HTTP(S) origin/path without credentials, query or fragment');
28
+ c.endpoint = url.href;
29
+ if (c.channel !== undefined) throw Error('channel is only supported with IPC');
30
+ } else {
31
+ if (typeof c.channel !== 'string' || !c.channel.trim()) throw Error('channel is required');
32
+ if (c.endpoint !== undefined || c.page !== undefined || c.pageUrl !== undefined) throw Error('IPC selects the window owned by its development hook');
33
+ }
34
+ return c;
35
+ }
36
+
37
+ export function ipcObservationAdapter(control, config, senderId) {
38
+ let id, metadata = null;
39
+ return {
40
+ metadata: () => metadata,
41
+ async start() {
42
+ const identity = await control.call('identify');
43
+ if (!identity.capabilities?.observation || !identity.capabilities?.readTimestamps) throw Error('IPC_OBSERVATION_UNSUPPORTED: restart the development app with the new observation-capable hook');
44
+ metadata = { version: identity.version ?? null, runtime: { node: identity.runtime?.node ?? null, electron: identity.runtime?.electron ?? null, chrome: identity.runtime?.chrome ?? null }, capabilities: { observation: identity.capabilities.observation, readTimestamps: identity.capabilities.readTimestamps, maxFaultCount: identity.capabilities.maxFaultCount ?? null } };
45
+ if (identity.senderId !== senderId) throw Error('IPC_TARGET_CHANGED');
46
+ const previous = await control.call('snapshot');
47
+ if (previous?.armed || previous?.observingUntil) throw Error('IPC_PLAN_ALREADY_ACTIVE');
48
+ id = randomUUID(); // A lost begin reply still requires scoped cleanup.
49
+ await control.call('begin', { id, channel: config.channel, observation: true, ttlMs: config.observationMs + 5000 });
50
+ },
51
+ async snapshot() {
52
+ const s = await control.call('snapshot');
53
+ if (!s || s.id !== id || s.senderId !== senderId || !s.observation || !s.observingUntil || s.armed || s.injected) throw Error('IPC_OBSERVATION_COVERAGE_LOST');
54
+ return s;
55
+ },
56
+ async stop() {
57
+ if (!id) return;
58
+ // reset(id) cannot clear another client's plan, even after an uncertain reply.
59
+ let resetError;
60
+ try { await control.call('reset', id); } catch (error) { resetError = error; }
61
+ const s = await control.call('snapshot');
62
+ if (!s || s.id !== id || s.observingUntil || s.armed) throw Error(`IPC_OBSERVATION_CLEANUP_UNVERIFIED${resetError ? ': ' + resetError.message : ''}`);
63
+ },
64
+ };
65
+ }
66
+
67
+ export function httpObservationAdapter(page, config) {
68
+ let observer;
69
+ return {
70
+ async start() { observer = await observeHttp(page, { endpoint: config.endpoint }); },
71
+ snapshot() { return observer.snapshot(); },
72
+ async stop() { await observer?.stop(); },
73
+ };
74
+ }
75
+
76
+ const counts = row => ({ calls: row.calls, successes: row.successes, errors: row.errors, pending: row.pending });
77
+ const delta = (row, base) => ({ calls: row.calls - base.calls, successes: row.successes - base.successes, errors: row.errors - base.errors, pending: row.pending, pendingAtStart: base.pending });
78
+ const age = (snapshot, at) => at === null ? null : Math.max(0, snapshot.capturedAt - at);
79
+
80
+ async function boundedUiRead(action, signal) {
81
+ let timer, cancel;
82
+ try {
83
+ return await Promise.race([
84
+ Promise.resolve().then(() => {
85
+ if (signal?.aborted) throw Error('CAPTURE_INTERRUPTED');
86
+ return action();
87
+ }),
88
+ new Promise((_, reject) => {
89
+ timer = setTimeout(() => reject(Error('UI_SAMPLE_TIMEOUT: renderer did not respond within 5000 ms')), 5000);
90
+ cancel = () => reject(Error('CAPTURE_INTERRUPTED'));
91
+ signal?.addEventListener('abort', cancel, { once: true });
92
+ }),
93
+ ]);
94
+ } finally { clearTimeout(timer); signal?.removeEventListener('abort', cancel); }
95
+ }
96
+
97
+ /** Observe only. No reload, navigation, routing, focus changes or final UI reset. */
98
+ export async function runObservation(page, input, adapter, { signal, takeMarker = () => false, onReady = () => {}, onInterval = () => {}, onSample = () => {} } = {}) {
99
+ const c = observationConfig(input);
100
+ const target = c.transport === 'ipc' ? c.channel : c.endpoint;
101
+ const metrics = samplingMetrics(c.sampleMs);
102
+ const report = { schemaVersion: 1, metadata: observationMetadata(), mode: 'fault-free observation', transport: c.transport, target, generatedAt: new Date().toISOString(),
103
+ status: 'incomplete', captureComplete: false, observationMs: c.observationMs, sampleMs: c.sampleMs, intervals: [], findings: [], timeline: [],
104
+ injected: 0, reloads: 0, cleanup: 'not-started',
105
+ coverage: { historyBeforeCapture: 'unknown', pendingBeforeCapture: 'unknown', scope: 'One selected renderer and read target; only calls starting during capture are counted.', gaps: [] },
106
+ limitation: 'Observations are not recovery passes or account-isolation verdicts. Cache reuse may be legitimate. Intervals start at capture or an operator marker, not at a proven mount or identity change. HTTP success means a completed 2xx response, not valid JSON or UI correctness. UI changes between samples can be missed. Only hashes, structural counts and read metadata are stored; hashes are not anonymization.' };
107
+ let lastSnapshot, interval, started, previousSignature, samples = 0;
108
+ let attempted = false, pageErrors = 0, newDocument = false;
109
+ const errors = () => { pageErrors++; };
110
+ // A document load destroys the state being investigated. SPA route changes are allowed.
111
+ const documentLoaded = () => { newDocument = true; };
112
+ const elapsed = () => Math.round(performance.now() - started);
113
+ const openInterval = s => {
114
+ const row = s.channels[target];
115
+ interval = { index: report.intervals.length + 1, startMs: elapsed(), startCounts: counts(row), firstContent: null, samples: 0, findings: [] };
116
+ report.intervals.push(interval);
117
+ previousSignature = undefined;
118
+ };
119
+ const closeInterval = () => {
120
+ if (!interval || !lastSnapshot) return;
121
+ interval.endMs = elapsed();
122
+ interval.reads = delta(lastSnapshot.channels[target], interval.startCounts);
123
+ };
124
+ const gap = code => { if (!report.coverage.gaps.includes(code)) report.coverage.gaps.push(code); };
125
+ try {
126
+ // Validate CSS without requiring the region to be mounted yet.
127
+ await boundedUiRead(() => page.evaluate(({ regionSelector, contentSelector }) => { document.querySelector(regionSelector); document.querySelector(contentSelector); }, c), signal);
128
+ page.on('pageerror', errors); page.on('domcontentloaded', documentLoaded);
129
+ attempted = true;
130
+ await adapter.start();
131
+ report.metadata.ipcHook = adapter.metadata?.() ?? null;
132
+ started = performance.now();
133
+ lastSnapshot = await adapter.snapshot();
134
+ report.startedAt = lastSnapshot.startedAt;
135
+ openInterval(lastSnapshot);
136
+ await onReady();
137
+ while (true) {
138
+ if (signal?.aborted) { report.status = 'interrupted'; break; }
139
+ if (newDocument) throw Error('DOCUMENT_REPLACED: capture stopped; the in-memory state may have been reset');
140
+ if (takeMarker()) {
141
+ if (report.intervals.length >= 50) throw Error('INTERVAL_LIMIT_REACHED');
142
+ // Use a fresh boundary snapshot; do not attribute between-sample reads to the next interval.
143
+ lastSnapshot = await adapter.snapshot(); closeInterval(); openInterval(lastSnapshot);
144
+ await onInterval(interval.index);
145
+ }
146
+ const before = await adapter.snapshot();
147
+ const sampleStart = elapsed();
148
+ const raw = await boundedUiRead(() => page.evaluate(readRegion, { regionSelector: c.regionSelector, contentSelector: c.contentSelector }), signal);
149
+ const ui = raw.presence === 'visible' ? summarizeRegion(raw) : raw;
150
+ const after = await adapter.snapshot();
151
+ if (newDocument) throw Error('DOCUMENT_REPLACED: capture stopped; the in-memory state may have been reset');
152
+ lastSnapshot = after;
153
+ const row = after.channels[target];
154
+ if (!row || !Object.hasOwn(row, 'lastCompletedAt')) throw Error('READ_TIMESTAMPS_UNAVAILABLE');
155
+ if (!ui.visible) gap('HIDDEN_DOCUMENT');
156
+ if (ui.truncated) gap('TRUNCATED_REGION');
157
+ const readCounts = delta(row, interval.startCounts);
158
+ const event = { interval: interval.index, fromMs: sampleStart, toMs: elapsed(), ui,
159
+ reads: readCounts, before: counts(before.channels[target]), after: counts(row),
160
+ lastReadAgeMs: age(after, row.lastReadAt), lastCompletionAgeMs: age(after, row.lastCompletedAt), pageErrors };
161
+ if (ui.visible && ui.contentCount > 0 && !interval.firstContent) {
162
+ interval.firstContent = { fromMs: sampleStart, toMs: event.toMs, alreadyPresentAtFirstSample: interval.samples === 0,
163
+ reads: readCounts, lastReadAgeMs: event.lastReadAgeMs, lastCompletionAgeMs: event.lastCompletionAgeMs };
164
+ }
165
+ if (ui.visible && ui.contentCount > 0 && readCounts.successes + readCounts.errors === 0 && !interval.findings.includes('CONTENT_BEFORE_READ')) {
166
+ const finding = { code: 'CONTENT_BEFORE_READ', kind: 'observation', interval: interval.index, fromMs: sampleStart, toMs: event.toMs,
167
+ basis: readCounts.calls === 0 && readCounts.pendingAtStart === 0 ? 'NO_READ_OBSERVED_IN_INTERVAL' : 'NO_COMPLETION_OBSERVED_IN_INTERVAL',
168
+ reads: readCounts, lastReadAgeMs: event.lastReadAgeMs, lastCompletionAgeMs: event.lastCompletionAgeMs,
169
+ note: 'The configured content marker is visible. This does not establish cache origin, ownership, a mount boundary, or a defect; earlier and unobserved reads are possible.' };
170
+ finding.summary = observationSummary(finding);
171
+ interval.findings.push(finding.code); report.findings.push(finding);
172
+ }
173
+ const signature = JSON.stringify([interval.index, ui, readCounts, pageErrors]);
174
+ if (signature !== previousSignature) {
175
+ if (report.timeline.length < 1000) report.timeline.push(event); else gap('TIMELINE_LIMIT_REACHED');
176
+ previousSignature = signature;
177
+ }
178
+ metrics.add(event.fromMs, event.toMs);
179
+ interval.samples++; samples++;
180
+ await onSample(event);
181
+ if (performance.now() - started >= c.observationMs) { report.status = 'complete'; break; }
182
+ await new Promise(resolve => setTimeout(resolve, Math.min(c.sampleMs, Math.max(0, c.observationMs - (performance.now() - started)))));
183
+ }
184
+ } catch (error) {
185
+ report.status = signal?.aborted ? 'interrupted' : 'incomplete';
186
+ if (!signal?.aborted) report.error = error.message;
187
+ } finally {
188
+ if (interval) closeInterval();
189
+ report.elapsedMs = started === undefined ? 0 : elapsed();
190
+ report.samples = samples;
191
+ report.sampling = metrics.snapshot();
192
+ report.snapshot = lastSnapshot;
193
+ page.off('pageerror', errors); page.off('domcontentloaded', documentLoaded);
194
+ if (attempted) {
195
+ try { await adapter.stop(); report.cleanup = 'complete'; }
196
+ catch (error) { report.cleanup = 'unverified'; report.cleanupError = error.message; report.status = 'incomplete'; }
197
+ }
198
+ if (samples > 0 && !report.intervals.some(i => i.firstContent)) gap('CONTENT_MARKER_NOT_OBSERVED');
199
+ report.captureComplete = report.status === 'complete' && report.coverage.gaps.length === 0;
200
+ }
201
+ return report;
202
+ }