Skip to content
Merged
Prev Previous commit
Next Next commit
feat(environment): time browser scenario records so their state learn…
…s a write clock

Scenario records take startedDateTime from when each request was observed and
time from the browser's duration, as HAR entries are timed. A timed scenario
of the book session learns the same clock and serves the same writes as its
HAR; an untimed one keeps record order and learns no clock, as before.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
  • Loading branch information
earakely-scale and claude committed Oct 24, 2026
commit 0ed402e86806b5f94aa4fe96bbedebae719be149
124 changes: 124 additions & 0 deletions src/domain/analysisView/environmentStateScenarioTiming.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,124 @@
import { expect, it } from "vitest";

import { timedCaptureEvidence } from "../../../tests/fixtures/analysisView.js";
import {
scenarioCaptureEvidence,
scenarioCaptureFixture,
type ScenarioExchange,
} from "../../../tests/fixtures/browserScenarioCapture.js";
import {
BOOK_ROWS,
BOOK_WRITE_CLOCK,
environmentStateViewOf,
} from "../../../tests/fixtures/environmentStateWrites.js";
import type { BrowserScenarioCapture } from "../browserScenarioCapture.js";
import { scenarioCaptureRecords } from "./scenarioCaptureRecords.js";

const START = Date.parse("2026-10-17T18:00:00.000Z");

/** The book session the HAR fixture times one second apart, as browser scenario exchanges. */
const EXCHANGES: readonly ScenarioExchange[] = BOOK_ROWS.map(
([method, path, body = null, status = 200, sent]) => ({
method,
url: path,
status,
mediaType: "application/json",
body: typeof body === "string" ? body : JSON.stringify(body),
...(sent === undefined
? {}
: {
requestMediaType: "application/json",
requestBody: JSON.stringify(sent),
}),
}),
);

/** The same capture with each request observed when the HAR fixture starts it, finishing 5 ms later. */
const timed = (capture: BrowserScenarioCapture): BrowserScenarioCapture => {
let transaction = 0;
const items = capture.events.items.map((event) =>
event.kind === "request"
? {
...event,
observed_at: new Date(START + transaction++ * 1000).toISOString(),
}
: event,
);
let sequence = Math.max(...items.map((event) => event.sequence));
const finished = items.flatMap((event) =>
event.kind === "request"
? [
{
...event,
observed_at: undefined,
sequence: ++sequence,
kind: "request-finished" as const,
elapsed_ms: 5,
},
]
: [],
);
return {
...capture,
events: {
...capture.events,
retained: items.length + finished.length,
items: [
...items,
...finished.map(({ observed_at: _unset, ...event }) => event),
],
},
};
};

const verdicts = (state: ReturnType<typeof environmentStateViewOf>) =>
Object.fromEntries(
state.writes.map((plan) => [
plan.tool,
plan.served
? plan.rules.map(({ field, rule }) => `${field}:${rule}`)
: plan.reason,
]),
);

it("times scenario records from when each request was observed and how long the browser took", () => {
const records = scenarioCaptureRecords(
timed(scenarioCaptureFixture(EXCHANGES)),
"manifest",
);
expect(records.records[1]?.reported).toMatchObject({
startedDateTime: "2026-10-17T18:00:01.000Z",
time: 5,
});
expect(records.limitations).toContainEqual(
expect.stringContaining("observed each request"),
);
const untimed = scenarioCaptureRecords(
scenarioCaptureFixture(EXCHANGES),
"manifest",
);
expect(untimed.records[1]?.reported).not.toHaveProperty("startedDateTime");
expect(untimed.limitations.join(" ")).not.toContain("observed each request");
});

it("learns the clock from a timed scenario as from the same session's HAR, and none without times", () => {
const har = environmentStateViewOf(timedCaptureEvidence(BOOK_ROWS));
const scenario = environmentStateViewOf(
scenarioCaptureEvidence(timed(scenarioCaptureFixture(EXCHANGES))),
);
expect(scenario.timeline).toBe("recorded-start-time");
expect(scenario.write_clock).toBe(BOOK_WRITE_CLOCK);
expect(verdicts(scenario)).toEqual(verdicts(har));
expect(Object.values(verdicts(scenario)).flat()).toContain(
"updated_at:clock",
);

const untimed = environmentStateViewOf(
scenarioCaptureEvidence(scenarioCaptureFixture(EXCHANGES)),
);
expect(untimed.timeline).toBe("record-order");
expect(untimed.write_clock).toBeNull();
expect(Object.values(verdicts(untimed)).flat()).not.toContain(
"updated_at:clock",
);
});
48 changes: 47 additions & 1 deletion src/domain/analysisView/scenarioCaptureRecords.ts
Original file line number Diff line number Diff line change
Expand Up @@ -103,11 +103,41 @@ const reportedRequest = (
};
};

/** Each transaction's browser-timed duration, from its single finished or failed event. */
const elapsedByTransaction = (
events: RetainedBrowserScenarioCapture["events"]["items"],
): ReadonlyMap<string, number | undefined> => {
const elapsed = new Map<string, number | undefined>();
for (const event of events) {
if (event.kind !== "request-finished" && event.kind !== "request-failed")
continue;
// A transaction ending twice has no single duration.
elapsed.set(
event.transaction_id,
elapsed.has(event.transaction_id) ? undefined : event.elapsed_ms,
);
}
return elapsed;
};

/** HAR timing for a record: when the request was observed and how long it took (0 when the browser reported no duration). */
const recordTiming = (
request: RequestEvent,
elapsed: ReadonlyMap<string, number | undefined>,
): { readonly startedDateTime: string; readonly time: number } | undefined =>
request.observed_at === undefined
? undefined
: {
startedDateTime: request.observed_at,
time: elapsed.get(request.transaction_id) ?? 0,
};

const record = (
ordinal: number,
observed: { readonly event: RequestEvent; readonly item: number },
index: BrowserScenarioTransactionIndex,
purpose: "manifest" | "replay",
timing: ReturnType<typeof recordTiming>,
): {
readonly record: WebNetworkCaptureRecord;
readonly responseBody: ScenarioResponseBodyRetention;
Expand Down Expand Up @@ -147,6 +177,7 @@ const record = (
ordinal,
location,
reported: {
...timing,
request: reportedRequest(request, requestContent, purpose),
...(response === undefined
? {}
Expand Down Expand Up @@ -186,11 +217,21 @@ export const scenarioCaptureRecords = (
purpose: "manifest" | "replay",
): ScenarioCaptureRecords => {
const index = indexBrowserScenarioTransactions(capture.events.items);
const elapsed = elapsedByTransaction(capture.events.items);
const records: WebNetworkCaptureRecord[] = [];
const responseBodies = new Map<number, ScenarioResponseBodyRetention>();
let timed = false;
for (const [item, event] of capture.events.items.entries()) {
if (event.kind !== "request") continue;
const projected = record(records.length, { event, item }, index, purpose);
const timing = recordTiming(event, elapsed);
timed ||= timing !== undefined;
const projected = record(
records.length,
{ event, item },
index,
purpose,
timing,
);
records.push(projected.record);
if (purpose === "manifest")
responseBodies.set(projected.record.ordinal, projected.responseBody);
Expand All @@ -201,6 +242,11 @@ export const scenarioCaptureRecords = (
responseBodies,
limitations: [
"Scenario records are the capture's network transactions in request order; each record ordinal is the transaction's zero-based position.",
...(timed
? [
"Scenario record start times are when the provider observed each request, shortly after the browser started it; durations are the browser's own timing.",
]
: []),
...(capture.events.dropped > 0
? [
`The scenario capture omitted ${String(capture.events.dropped)} events; the manifest covers only retained transactions.`,
Expand Down