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

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,6 +4,13 @@ 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.14 (2026-10-14)
8
+
9
+ - Default fault-free observation to lightweight selected-content sampling; retain `detail: "region"` for full diagnostics. Explicit marker/text limits flag partial evidence; unrelated controls do not affect marker comparisons.
10
+ - Compare ordered visible marker text/count across observed read completions and operator intervals. Distinguish unchanged, changed and unavailable evidence, successful/failed settlements, and ambiguous completion during sampling. No freshness or ownership verdict is inferred.
11
+ - Measure renderer, protocol round-trip, summarization and counter-snapshot phases separately. Add a reproducible synthetic benchmark and controlled brief-transition coverage tests; no guaranteed temporal resolution is claimed.
12
+ - Persist separate cleanup readback evidence and label the observation snapshot as pre-cleanup. Extend browser and Electron checks; update the observation guide and CLI/HTML explanations.
13
+
7
14
  ## 0.3.0-preview.13 (2026-10-14)
8
15
 
9
16
  - 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.
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.13**. 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.14**. 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.13 version
29
- npm install --save-dev --save-exact recovery-probe@0.3.0-preview.13 playwright@1.62.1
28
+ npm view recovery-probe@0.3.0-preview.14 version
29
+ npm install --save-dev --save-exact recovery-probe@0.3.0-preview.14 playwright@1.62.1
30
30
  npx recovery-probe --version
31
31
  ```
32
32
 
@@ -34,6 +34,8 @@ 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.14:** [observation](docs/observe.md) now defaults to lightweight content sampling, reports marker text/count comparisons across reads and return intervals, and records sampling phase timings plus separate cleanup evidence. Use `"detail": "region"` for full DOM diagnostics.
38
+
37
39
  **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
40
 
39
41
  | Goal | Entry point | Guide |
package/bin/observe.mjs CHANGED
@@ -14,6 +14,7 @@ export async function observeMain(args) {
14
14
  Fault-free observation of an existing browser or Electron renderer.
15
15
  No reload, navigation, focus change, fault injection or final UI reset.
16
16
  Choose transport: http or ipc and explicit regionSelector/contentSelector CSS markers.
17
+ Sampling defaults to detail: "content"; use "region" for full DOM diagnostics.
17
18
  Navigate manually during the bounded capture. Enter marks a new interval in an
18
19
  interactive terminal; --interactive also enables newline markers on piped input.
19
20
  Ctrl+C saves partial evidence. CONTENT_BEFORE_READ is an observation, not a defect.
@@ -93,7 +94,8 @@ IPC requires the observation-capable development hook. See docs/observe.md.`);
93
94
  else {
94
95
  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
96
  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
+ for (const comparison of report.comparisons ?? []) console.log(`Interval ${comparison.interval}: ${comparison.summary}`);
98
+ console.log(`Sampling: ${config.detail}; requested delay ${config.sampleMs} ms; measured mean cadence ${report.sampling.startToStart.meanMs ?? 'unavailable'} ms.`);
97
99
  if (report.error) console.error(report.error);
98
100
  console.log(`Capture: ${report.status} (not a health verdict)\nReport: ${join(directory, 'report.html')}`);
99
101
  }
package/docs/ci.md CHANGED
@@ -60,6 +60,6 @@ jobs:
60
60
 
61
61
  ## Adapt it to an application
62
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.
63
+ Install `recovery-probe@0.3.0-preview.14` 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
64
 
65
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.13 version
42
- npm install --save-dev --save-exact recovery-probe@0.3.0-preview.13 playwright@1.62.1
41
+ npm view recovery-probe@0.3.0-preview.14 version
42
+ npm install --save-dev --save-exact recovery-probe@0.3.0-preview.14 playwright@1.62.1
43
43
  npx recovery-probe desktop --list
44
44
  ```
45
45
 
package/docs/ipc.md CHANGED
@@ -12,8 +12,8 @@ Node 22+ is required for the CLI. Electron 29's bundled Node can load the small
12
12
 
13
13
  ```bash
14
14
  mkdir -p recovery-probe-tools && cd recovery-probe-tools
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
+ npm view recovery-probe@0.3.0-preview.14 version
16
+ npm install --save-dev --save-exact recovery-probe@0.3.0-preview.14 playwright@1.62.1
17
17
  node -p "require.resolve('recovery-probe/ipc')"
18
18
  ```
19
19
 
package/docs/observe.md CHANGED
@@ -3,7 +3,7 @@
3
3
  Available in **0.3.0-preview.12**. Install the exact preview and verify the CLI:
4
4
 
5
5
  ```bash
6
- npm install --save-dev --save-exact recovery-probe@0.3.0-preview.13 playwright@1.62.1
6
+ npm install --save-dev --save-exact recovery-probe@0.3.0-preview.14 playwright@1.62.1
7
7
  npx recovery-probe --version
8
8
  ```
9
9
 
@@ -49,6 +49,12 @@ Select an existing page using `desktop --list`. HTTP observes main-frame GET fet
49
49
 
50
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
51
 
52
+ Since preview.14, `detail` defaults to `"content"`: each sample reads visible selected markers and their normalized text, without traversing the region's full structure, controls and repeated-value distributions. Existing configs automatically use this lighter path. Set `"detail": "region"` to retain detailed region diagnostics alongside the same marker evidence. Fault-injection/discovery workflows retain their detailed inspections.
53
+
54
+ `ui.contentCount` counts visible matches of your content selector. In region detail, `ui.items` is a separate generic list/row heuristic and is **not** the number of application records. Content fingerprints cover ordered normalized marker text/count, not attributes, image pixels, input values, server data or account identity. Controls inside a selected marker contribute to its text; use a narrower marker when appropriate.
55
+
56
+ Marker inspection is capped at the first 1000 selector matches and 200000 normalized text characters per sample. Exceeding either sets `ui.content.truncated` and a coverage gap; counts may then be partial and comparisons are unavailable. These caps limit collected evidence, not a guarantee about browser execution time. CSS matching and reading a large individual element still cost work.
57
+
52
58
  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
59
 
54
60
  ## Capture a return visit
@@ -74,6 +80,21 @@ Since preview.13, `metadata` records the installed Recovery Probe version, CLI N
74
80
 
75
81
  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
82
 
83
+ Since preview.14, `sampling.phases` also summarizes `beforeSnapshotMs`, `uiRoundTripMs`, `rendererReadMs`, `summarizeMs`, and `afterSnapshotMs`. Renderer time is measured inside the page; the other durations use the CLI's monotonic clock. **Renderer time is included in the UI round trip**, so these fields must not all be added together. They help distinguish renderer work from protocol/serialization and counter costs. Timing values are excluded from the UI signature, so timing noise does not fill the change-only timeline. An observation lease, inspector transport or busy app can still dominate cadence.
84
+
85
+ For a reproducible local diagnostic from a repository checkout, run `npm run benchmark:observe` after installing dependencies and Chromium. It alternates content/region reads of a synthetic 200-row fixture, discards warmup samples, and prints renderer, round-trip, summarization and transfer measurements. This is not a performance pass/fail gate or a guarantee of detecting a particular flash duration. Compare actual cadence in field reports before drawing conclusions about the application under test.
86
+
87
+ ## Content comparisons
88
+
89
+ `comparisons` and the HTML/terminal summaries make two relationships explicit:
90
+
91
+ - `INTERVAL_RETURN`: compare the first visible selected content in a new operator interval with the last visible selected content from an earlier interval. Read counts explain whether new selected calls started in the current interval. An interval is not a verified route, mount or identity transition.
92
+ - `READ_COMPLETION`: compare a sample before observed completion(s) with the first subsequent sample whose before/after counters agree on the number of completions. A completion during a UI read is ambiguous: comparison waits for a later sample. Successful and failed completion counts are reported separately; overlapping completions may be grouped.
93
+
94
+ Results are `unchanged`, `changed`, or `unavailable`. Unavailable means the required visible, untruncated marker summaries are missing. An unchanged result means only that the sampled ordered marker text and count match. It does not prove that content stayed continuously visible, that the data is fresh, or that the renderer has consumed a completed read. A delayed render may change in later timeline entries. There is no comparison when a suitable pre-completion sample was not captured; an unresolved completion at capture end cannot establish a post-completion comparison. Up to 1000 comparisons are retained; exceeding that records a coverage gap.
95
+
96
+ The browser tests include unchanged content after a failed refresh, changed content after a successful refresh, cached interval return, a sampled 250 ms pulse, and a pulse entirely between samples that remains undetected. These controls deliberately distinguish captured evidence from missed transitions.
97
+
77
98
  ## Interpretation
78
99
 
79
100
  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.
@@ -86,6 +107,8 @@ This release has no automatic login steps, operator identity assertions, identit
86
107
 
87
108
  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
109
 
110
+ `snapshot` remains the last observation snapshot, explicitly labelled `snapshotStage: "before-cleanup"`. `cleanupEvidence` separately records HTTP listener detachment or the verified IPC readback (owned run id, capture time, expired/cleared observation lease, no armed fault and zero injections). A pre-cleanup snapshot with an active lease does not contradict successful cleanup. Failed cleanup remains incomplete; setup failures may have no cleanup evidence.
111
+
89
112
  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
113
 
91
114
  ## Supported inspector API
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.13 version
14
- npm install --save-dev --save-exact recovery-probe@0.3.0-preview.13 playwright@1.62.1
13
+ npm view recovery-probe@0.3.0-preview.14 version
14
+ npm install --save-dev --save-exact recovery-probe@0.3.0-preview.14 playwright@1.62.1
15
15
  npx recovery-probe start web http://localhost:3000
16
16
  ```
17
17
 
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "recovery-probe",
3
- "version": "0.3.0-preview.13",
3
+ "version": "0.3.0-preview.14",
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",
@@ -117,6 +117,7 @@
117
117
  "test:guided": "node --test test/guided-start.test.mjs test/guided-start.integration.test.mjs",
118
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
119
  "test:ipc:electron": "node --test --test-concurrency=1 test/ipc.electron.test.mjs test/observe.electron.test.mjs",
120
+ "benchmark:observe": "node scripts/benchmark-observe.mjs",
120
121
  "test:ci-example": "node examples/ci/verify.mjs"
121
122
  }
122
123
  }
@@ -3,17 +3,42 @@ 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 readStarted = performance.now();
6
7
  const observation = typeof selector === 'object' && selector !== null ? selector : null;
8
+ const finish = value => observation ? { ...value, rendererReadMs: performance.now() - readStarted } : value;
7
9
  if (observation) {
8
10
  selector = observation.regionSelector;
9
11
  document.querySelector(observation.contentSelector); // Validate even when the region is absent.
10
12
  }
11
13
  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 };
14
+ if (observation && roots?.length === 0) return finish({ presence: 'absent', contentCount: 0, visible: document.visibilityState === 'visible', online: navigator.onLine });
13
15
  if (roots && roots.length !== 1) throw new Error('regionSelector must identify one region');
14
16
  const root = roots?.[0] ?? document.querySelector('main, [role="main"]') ?? document.body;
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 };
17
+ // Cache only within this synchronous read: no DOM references survive a sample.
18
+ const visibility = new WeakMap();
19
+ const visible = e => {
20
+ if (!visibility.has(e)) {
21
+ const style = getComputedStyle(e);
22
+ visibility.set(e, !!(e.getClientRects().length && style.visibility !== 'hidden' && style.display !== 'none'));
23
+ }
24
+ return visibility.get(e);
25
+ };
26
+ if (observation && !visible(root)) return finish({ presence: 'hidden', contentCount: 0, visible: document.visibilityState === 'visible', online: navigator.onLine });
27
+ let content;
28
+ if (observation) {
29
+ const matches = root.querySelectorAll(observation.contentSelector);
30
+ const texts = [];
31
+ let remaining = 200000, truncated = matches.length > 1000;
32
+ for (const e of [...matches].slice(0, 1000)) {
33
+ if (!visible(e)) continue;
34
+ const text = (e.innerText ?? '').replace(/\s+/g, ' ').trim();
35
+ if (text.length > remaining) truncated = true;
36
+ texts.push(text.slice(0, remaining)); remaining = Math.max(0, remaining - text.length);
37
+ }
38
+ content = { texts, truncated };
39
+ if (observation.detail === 'content') return finish({ presence: 'visible', contentCount: texts.length,
40
+ content, truncated, visible: document.visibilityState === 'visible', online: navigator.onLine });
41
+ }
17
42
  const nodes = [...root.querySelectorAll('*')].filter(visible).slice(0, 5000);
18
43
  const count = s => [...root.querySelectorAll(s)].filter(visible).length;
19
44
  const text = (root.innerText ?? '').replace(/\s+/g, ' ').trim();
@@ -55,10 +80,10 @@ export function readRegion(selector) {
55
80
  distributions[key] = values;
56
81
  }
57
82
  }
58
- return { text, structure, groups, distributions,
59
- ...(observation ? { presence: 'visible', contentCount: [...root.querySelectorAll(observation.contentSelector)].filter(visible).length } : {}),
83
+ return finish({ text, structure, groups, distributions,
84
+ ...(observation ? { presence: 'visible', contentCount: content.texts.length, content } : {}),
60
85
  region: selector ? 'selected' : root === document.body ? 'body' : 'main',
61
- truncated: root.querySelectorAll('*').length > 5000,
86
+ truncated: root.querySelectorAll('*').length > 5000 || Boolean(content?.truncated),
62
87
  visible: document.visibilityState === 'visible', online: navigator.onLine,
63
88
  items: count('tbody tr, [role="row"]:not(:has([role="columnheader"])), [role="listitem"], li'),
64
89
  images: count('img, [role="img"], svg'), links: count('a[href]'), buttons: count('button, [role="button"]'),
@@ -66,10 +91,14 @@ export function readRegion(selector) {
66
91
  empty: /\b(no (files|items|results|data)|nothing (here|found)|empty|keine (dateien|einträge|ergebnisse))\b/i.test(text),
67
92
  error: count('[role="alert"]') > 0 || /\b(error|failed|unable to|something went wrong|fehler|fehlgeschlagen)\b/i.test(text),
68
93
  retry: [...root.querySelectorAll('button, [role="button"]')].some(e => visible(e) && /\b(retry|try again|erneut versuchen|wiederholen)\b/i.test(e.innerText || e.getAttribute('aria-label') || '')),
69
- };
94
+ });
70
95
  }
71
96
  export function summarizeRegion(raw) {
72
- const { text, distributions = {}, ...summary } = raw;
97
+ const { text, distributions = {}, content, rendererReadMs: _timing, ...summary } = raw;
98
+ if (content) summary.content = { basis: 'ordered-visible-marker-text', count: content.texts.length,
99
+ textLength: content.texts.reduce((sum, value) => sum + value.length, 0),
100
+ textFingerprint: hash(JSON.stringify(content.texts)), truncated: content.truncated };
101
+ if (text === undefined) return summary;
73
102
  const values = {};
74
103
  for (const [family, columns] of Object.entries(distributions)) {
75
104
  values[family] = {};
@@ -9,8 +9,9 @@ export function observationMetadata() {
9
9
  export function samplingMetrics(requestedDelayMs) {
10
10
  let previous, count = 0, sum = 0, min = Infinity, max = 0;
11
11
  let gaps = 0, gapSum = 0, gapMin = Infinity, gapMax = 0;
12
+ const phases = {};
12
13
  return {
13
- add(fromMs, toMs) {
14
+ add(fromMs, toMs, timings = {}) {
14
15
  const duration = toMs - fromMs;
15
16
  count++; sum += duration; min = Math.min(min, duration); max = Math.max(max, duration);
16
17
  if (previous !== undefined) {
@@ -18,16 +19,64 @@ export function samplingMetrics(requestedDelayMs) {
18
19
  gaps++; gapSum += gap; gapMin = Math.min(gapMin, gap); gapMax = Math.max(gapMax, gap);
19
20
  }
20
21
  previous = fromMs;
22
+ for (const key of ['beforeSnapshotMs', 'uiRoundTripMs', 'rendererReadMs', 'summarizeMs', 'afterSnapshotMs']) {
23
+ const value = timings[key];
24
+ if (!Number.isFinite(value) || value < 0) continue;
25
+ const p = phases[key] ??= { count: 0, sum: 0, min: Infinity, max: 0 };
26
+ p.count++; p.sum += value; p.min = Math.min(p.min, value); p.max = Math.max(p.max, value);
27
+ }
21
28
  },
22
29
  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 });
30
+ const round = n => Math.round(n * 100) / 100;
31
+ const stats = (n, total, low, high) => ({ count: n, meanMs: n ? round(total / n) : null, minMs: n ? round(low) : null, maxMs: n ? round(high) : null });
24
32
  return { requestedDelayMs, completedSamples: count,
25
33
  sampleDuration: stats(count, sum, min, max), startToStart: stats(gaps, gapSum, gapMin, gapMax),
34
+ phases: Object.fromEntries(Object.entries(phases).map(([key, p]) => [key, stats(p.count, p.sum, p.min, p.max)])),
26
35
  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
36
  },
28
37
  };
29
38
  }
30
39
 
40
+ // Compare samples only; these summaries cannot establish ownership or freshness.
41
+ export function contentComparison(basis, before, after) {
42
+ const evidence = e => ({ interval: e.interval, fromMs: e.fromMs, toMs: e.toMs,
43
+ presence: e.ui.presence, content: e.ui.content ?? null });
44
+ const a = before.ui.content, b = after.ui.content;
45
+ const comparable = before.ui.visible && after.ui.visible && a && b && !a.truncated && !b.truncated;
46
+ const result = !comparable ? 'unavailable' : a.count === b.count && a.textFingerprint === b.textFingerprint ? 'unchanged' : 'changed';
47
+ return { kind: 'observation', basis, interval: after.interval, result, before: evidence(before), after: evidence(after),
48
+ ...(basis === 'READ_COMPLETION' ? { completions: { successes: after.before.successes - before.after.successes,
49
+ errors: after.before.errors - before.after.errors } } : { reads: after.reads }),
50
+ summary: `${basis === 'READ_COMPLETION' ? 'Across observed read completion(s)' : 'On the first sampled content in this interval'}, selected marker text/count comparison: ${result}.`,
51
+ note: 'Ordered normalized visible marker text/count only. Other values, ownership, freshness and changes between samples are unknown. Completion does not imply renderer consumption.' };
52
+ }
53
+
54
+ export function contentComparisons() {
55
+ let interval, anchor, lastContent, returnBaseline, comparedReturn = false;
56
+ const completed = counts => counts.successes + counts.errors;
57
+ return {
58
+ add(event) {
59
+ const results = [];
60
+ if (interval !== event.interval) {
61
+ interval = event.interval; anchor = undefined; returnBaseline = lastContent; comparedReturn = false;
62
+ }
63
+ if (event.ui.visible && event.ui.contentCount > 0) {
64
+ if (returnBaseline && !comparedReturn) results.push(contentComparison('INTERVAL_RETURN', returnBaseline, event));
65
+ comparedReturn = true; lastContent = event;
66
+ }
67
+ if (anchor && completed(event.after) > completed(anchor.after)) {
68
+ // A completion during the UI read is ambiguous. Retain the earlier
69
+ // sample until a later UI read is bracketed by settled counters.
70
+ if (completed(event.before) === completed(event.after)) {
71
+ results.push(contentComparison('READ_COMPLETION', anchor, event));
72
+ anchor = event;
73
+ }
74
+ } else anchor = event;
75
+ return results;
76
+ },
77
+ };
78
+ }
79
+
31
80
  export function observationSummary(finding) {
32
81
  if (finding.basis === 'NO_READ_OBSERVED_IN_INTERVAL') return 'Content was visible without a new selected read in this interval.';
33
82
  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).';
@@ -38,5 +87,7 @@ const escape = value => String(value).replace(/[&<>"']/g, c => ({ '&': '&amp;',
38
87
  export function renderObservationReport(report) {
39
88
  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
89
  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>`;
90
+ const comparisons = (report.comparisons ?? []).map(c => `<p>Interval ${escape(c.interval)}: ${escape(c.summary)} ${c.completions ? `(${c.completions.successes} successful, ${c.completions.errors} failed read completions)` : `(${c.reads.calls} selected reads started in this interval)`}</p>`).join('');
91
+ const phases = Object.entries(sampling?.phases ?? {}).map(([name, s]) => `<tr><td>${escape(name)}</td><td>${s.meanMs}</td><td>${s.maxMs}</td></tr>`).join('');
92
+ 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>Sampling detail: ${escape(report.detail ?? 'region (legacy)')}. Marker counts describe the configured content selector; generic region item counts are heuristics.</p>${phases ? `<table><thead><tr><th>Measured phase</th><th>Mean ms</th><th>Maximum ms</th></tr></thead><tbody>${phases}</tbody></table><p>Renderer read time is included in the UI round trip, not additional to it.</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('')}${comparisons}<p>Comparisons concern sampled marker text and count, not ownership or freshness. A completion does not guarantee the UI has consumed its result.</p><p>Cleanup: ${escape(report.cleanup ?? 'unknown')}. The observation snapshot is from before cleanup; cleanupEvidence records the separate cleanup check when available.</p><details><summary>Evidence and coverage</summary><pre>${escape(JSON.stringify(report, null, 2))}</pre></details>`;
42
93
  }
package/src/observe.mjs CHANGED
@@ -1,4 +1,4 @@
1
- import { observationMetadata, samplingMetrics, observationSummary } from './observation-report.mjs';
1
+ import { observationMetadata, samplingMetrics, observationSummary, contentComparisons } from './observation-report.mjs';
2
2
  import { performance } from 'node:perf_hooks';
3
3
  import { randomUUID } from 'node:crypto';
4
4
  import { readRegion, summarizeRegion } from './ipc-observation.mjs';
@@ -7,12 +7,13 @@ import { observeHttp } from './http-observer.mjs';
7
7
  export function observationConfig(input) {
8
8
  if (!input || typeof input !== 'object' || Array.isArray(input)) throw Error('Observation config must be an object');
9
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 };
10
+ channel: undefined, endpoint: undefined, regionSelector: undefined, contentSelector: undefined, detail: 'content', observationMs: 30000, sampleMs: 100 };
11
11
  for (const key of Object.keys(input)) {
12
12
  if (!Object.hasOwn(c, key)) throw Error(`Unsupported observation option: ${key}`);
13
13
  c[key] = input[key];
14
14
  }
15
15
  if (!['http', 'ipc'].includes(c.transport)) throw Error('transport must be http or ipc');
16
+ if (!['content', 'region'].includes(c.detail)) throw Error('detail must be content or region');
16
17
  for (const key of ['regionSelector', 'contentSelector']) if (typeof c[key] !== 'string' || !c[key].trim()) throw Error(`${key} must be an explicit CSS selector`);
17
18
  for (const [key, low, high] of [['observationMs', 500, 120000], ['sampleMs', 50, 1000]]) {
18
19
  if (!Number.isInteger(c[key]) || c[key] < low || c[key] > high) throw Error(`${key} must be ${low}–${high}`);
@@ -59,7 +60,8 @@ export function ipcObservationAdapter(control, config, senderId) {
59
60
  let resetError;
60
61
  try { await control.call('reset', id); } catch (error) { resetError = error; }
61
62
  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
+ if (!s || s.id !== id || s.observingUntil || s.armed || s.injected !== 0) throw Error(`IPC_OBSERVATION_CLEANUP_UNVERIFIED${resetError ? ': ' + resetError.message : ''}`);
64
+ return { transport: 'ipc', verified: true, runId: s.id, capturedAt: s.capturedAt, observingUntil: s.observingUntil, armed: s.armed, injected: s.injected };
63
65
  },
64
66
  };
65
67
  }
@@ -69,7 +71,7 @@ export function httpObservationAdapter(page, config) {
69
71
  return {
70
72
  async start() { observer = await observeHttp(page, { endpoint: config.endpoint }); },
71
73
  snapshot() { return observer.snapshot(); },
72
- async stop() { await observer?.stop(); },
74
+ async stop() { await observer?.stop(); return { transport: 'http', listenersDetached: true }; },
73
75
  };
74
76
  }
75
77
 
@@ -99,8 +101,9 @@ export async function runObservation(page, input, adapter, { signal, takeMarker
99
101
  const c = observationConfig(input);
100
102
  const target = c.transport === 'ipc' ? c.channel : c.endpoint;
101
103
  const metrics = samplingMetrics(c.sampleMs);
104
+ const comparisons = contentComparisons();
102
105
  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: [],
106
+ status: 'incomplete', captureComplete: false, observationMs: c.observationMs, sampleMs: c.sampleMs, detail: c.detail, intervals: [], findings: [], comparisons: [], timeline: [],
104
107
  injected: 0, reloads: 0, cleanup: 'not-started',
105
108
  coverage: { historyBeforeCapture: 'unknown', pendingBeforeCapture: 'unknown', scope: 'One selected renderer and read target; only calls starting during capture are counted.', gaps: [] },
106
109
  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.' };
@@ -143,11 +146,16 @@ export async function runObservation(page, input, adapter, { signal, takeMarker
143
146
  lastSnapshot = await adapter.snapshot(); closeInterval(); openInterval(lastSnapshot);
144
147
  await onInterval(interval.index);
145
148
  }
149
+ const beforeStart = performance.now();
146
150
  const before = await adapter.snapshot();
151
+ const uiStart = performance.now();
147
152
  const sampleStart = elapsed();
148
- const raw = await boundedUiRead(() => page.evaluate(readRegion, { regionSelector: c.regionSelector, contentSelector: c.contentSelector }), signal);
153
+ const { rendererReadMs, ...raw } = await boundedUiRead(() => page.evaluate(readRegion, { regionSelector: c.regionSelector, contentSelector: c.contentSelector, detail: c.detail }), signal);
154
+ const summarizeStart = performance.now();
149
155
  const ui = raw.presence === 'visible' ? summarizeRegion(raw) : raw;
156
+ const afterStart = performance.now();
150
157
  const after = await adapter.snapshot();
158
+ const afterEnd = performance.now();
151
159
  if (newDocument) throw Error('DOCUMENT_REPLACED: capture stopped; the in-memory state may have been reset');
152
160
  lastSnapshot = after;
153
161
  const row = after.channels[target];
@@ -175,7 +183,11 @@ export async function runObservation(page, input, adapter, { signal, takeMarker
175
183
  if (report.timeline.length < 1000) report.timeline.push(event); else gap('TIMELINE_LIMIT_REACHED');
176
184
  previousSignature = signature;
177
185
  }
178
- metrics.add(event.fromMs, event.toMs);
186
+ for (const comparison of comparisons.add(event)) {
187
+ if (report.comparisons.length < 1000) report.comparisons.push(comparison); else gap('COMPARISON_LIMIT_REACHED');
188
+ }
189
+ metrics.add(event.fromMs, event.toMs, { beforeSnapshotMs: uiStart - beforeStart, uiRoundTripMs: summarizeStart - uiStart,
190
+ rendererReadMs, summarizeMs: afterStart - summarizeStart, afterSnapshotMs: afterEnd - afterStart });
179
191
  interval.samples++; samples++;
180
192
  await onSample(event);
181
193
  if (performance.now() - started >= c.observationMs) { report.status = 'complete'; break; }
@@ -190,9 +202,10 @@ export async function runObservation(page, input, adapter, { signal, takeMarker
190
202
  report.samples = samples;
191
203
  report.sampling = metrics.snapshot();
192
204
  report.snapshot = lastSnapshot;
205
+ report.snapshotStage = 'before-cleanup';
193
206
  page.off('pageerror', errors); page.off('domcontentloaded', documentLoaded);
194
207
  if (attempted) {
195
- try { await adapter.stop(); report.cleanup = 'complete'; }
208
+ try { report.cleanupEvidence = await adapter.stop() ?? null; report.cleanup = 'complete'; }
196
209
  catch (error) { report.cleanup = 'unverified'; report.cleanupError = error.message; report.status = 'incomplete'; }
197
210
  }
198
211
  if (samples > 0 && !report.intervals.some(i => i.firstContent)) gap('CONTENT_MARKER_NOT_OBSERVED');