Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
61 changes: 60 additions & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -251,7 +251,6 @@ node scripts/record-demo.mjs # re-record demo/traces/*.jsonl through the
## Roadmap

- `streamscope serve` — record + replay in one process (a session list panel).
- Diff two traces frame by frame (`streamscope diff a.jsonl b.jsonl`).
- Custom header/body redaction rules for traces that get committed (the built-in credential mask ships in 0.1.1).

## License
Expand Down Expand Up @@ -285,3 +284,63 @@ Validation: `npm run verify && npm run test:e2e && npm run test:browser`. Runner
Use Node.js 22.18.0 (`.nvmrc`) for development and CI. Vitest 5.1.1 requires Node 22.12+ on its supported release lines; Node 20.19 is outside its declared development support range. It may execute there, but CI does not treat that as supported test-runner usage. This development requirement does not change the package engine declaration. Runtime compatibility must be checked using the built package, separately from the test runner. TypeScript 7.0.2 is the development compiler baseline.

Development minimum exception: tsup9 requires Node22.x from22.18.0. This does not change consumer runtime engines.

## Trace diff and regression gates

```sh
streamscope diff before.jsonl after.jsonl
streamscope diff before.jsonl after.jsonl --fail-on 'added,removed,payload,latency>200ms,count'
streamscope diff before.jsonl after.jsonl --json --html reports/diff.html
streamscope diff after.jsonl --baseline before.jsonl
```

With one trace and no explicit baseline, `.streams/baseline.json` is read:

```json
{"path":"main/events.jsonl","sha256":"<64-character SHA-256 of the trace file bytes>"}
```

The path is relative to the manifest directory. `sha` is accepted as an alias
for `sha256`. The hash is verified before comparing; no baseline is created or
updated implicitly. Get a hash with `sha256sum .streams/main/events.jsonl`.

Matching uses event type + event ID (including normalized tool-call IDs), or
native toolCallId/inputIndex/input_index/index when present, plus an occurrence
counter for repeated deltas. Without an identity, absolute frame ordinal is
used. Inserting an anonymous event can therefore appear as several payload
changes; this is positional alignment, not semantic inference. Reorder compares
the relative rank of matched events, so inserting an identified event alone
is not a reorder. Added and removed events report their own indices.

Payload changes compare normalized event objects recursively, including native
`data`, with JSON Pointer key paths. JSON object key order is ignored. Wire
whitespace and frame `seq` are not payload changes. Elapsed `t_ms` deltas are
reported per matched frame: these are cumulative stream times, not processing
durations. A latency gate fails only for a positive delta strictly greater
than its threshold. Equal or faster frames do not fail. Count compares total
frame counts, so one addition and one removal does not trigger count alone.

Different adapter/protocol/framing metadata, invalid frame metadata or truncated
JSONL is rejected. Identical traces print `no differences`. Exit codes are 0
for successful comparison with no gate violations (even if differences exist),
1 for gate violations or I/O errors, and 2 for invalid input/options. JSON
includes `violations`; HTML embeds sandboxed before/after timeline viewers.
The HTML contains trace payloads, so handle it like the source recordings.

See [`examples/ci/trace-diff.yml`](examples/ci/trace-diff.yml) for a two-job PR
workflow that downloads a base-commit recording artifact and fails on removed
frames. It uses the committed demo trace as a runnable placeholder; replace
both copy steps with the same deterministic application recording command.
Comment thread
developjik marked this conversation as resolved.
Resolved
It does not use elevated pull_request_target permissions or release packages.

Use stable seeded tool/message/run IDs in both recordings. If providers generate
new IDs on each run, normalize them consistently (including references inside
native data) before hashing/comparing; otherwise ID changes are additions and
removals by design. Provider fragment indices are scoped by step/message ID.
Completed valid JSON argument strings are compared structurally; partial argument
fragments stay byte-sensitive. HTML output may not overwrite either input trace
or the baseline manifest (symlink and hardlink aliases are also rejected).

Argument JSON numeric normalization is conservative: fractional, exponent-form and unsafe
integer values keep the original argument string, so rounding cannot hide a
payload change. Those strings may still flag whitespace/key-order changes.
160 changes: 151 additions & 9 deletions bin/cli.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,14 +7,16 @@
* streamscope inject .streams/<session> --with "dup(4)" -o checkout.broken.jsonl
* streamscope inspect .streams/<session> --html viewer.html
*/
import { existsSync, readFileSync, realpathSync } from 'node:fs';
import { createHash } from 'node:crypto';
import { diffTraces, diffViolations, formatTraceDiff, parseDiffGates, renderDiffHtml } from '../src/diff.js';
import { existsSync, readFileSync, realpathSync, statSync } from 'node:fs';
import { mkdir, writeFile } from 'node:fs/promises';
import path from 'node:path';
import { fileURLToPath } from 'node:url';
import { applyFaults, FaultSyntaxError, defaultEncoder, formatScenario, parseScenario } from '../src/faults.js';
import { startRecordingProxy } from '../src/proxy.js';
import { startReplayServer } from '../src/replay.js';
import { formatSummary, readTrace, resolveTracePath, summarize, traceToJsonl } from '../src/trace.js';
import { formatSummary, parseTrace, readTrace, resolveTracePath, summarize, traceToJsonl } from '../src/trace.js';
import { renderPanelHtml } from '../src/ui/panel.js';
import type { Trace } from '../src/types.js';

Expand All @@ -30,7 +32,18 @@ const DEFAULT_IO: CliIO = {
cwd: process.cwd(),
};

const BOOLEAN_FLAGS = new Set(['help', 'version', 'json', 'open', 'no-ui', 'print', 'quiet', 'force', 'frames', 'no-redact']);
const BOOLEAN_FLAGS = new Set([
'help',
'version',
'json',
'open',
'no-ui',
'print',
'quiet',
'force',
'frames',
'no-redact',
]);
const VALUE_FLAGS = new Set([
'target',
'port',
Expand All @@ -43,8 +56,10 @@ const VALUE_FLAGS = new Set([
'speed',
'html',
'url',
'baseline',
'fail-on',
]);
const COMMANDS = ['record', 'replay', 'inject', 'inspect', 'help', 'version'] as const;
const COMMANDS = ['record', 'replay', 'inject', 'inspect', 'diff', 'help', 'version'] as const;
type Command = (typeof COMMANDS)[number];

interface Parsed {
Expand Down Expand Up @@ -78,7 +93,9 @@ export function readVersion(root = packageRoot()): string {
try {
const file = path.join(root, 'package.json');
if (existsSync(file)) {
const pkg = JSON.parse(readFileSync(file, 'utf8')) as { version?: unknown };
const pkg = JSON.parse(readFileSync(file, 'utf8')) as {
version?: unknown;
};
if (typeof pkg.version === 'string') return pkg.version;
}
} catch {
Expand Down Expand Up @@ -184,6 +201,10 @@ Replay
Inject
streamscope inject <trace> --with "truncate_tool_args(12),error(429)" -o out.jsonl

Diff
streamscope diff <before> <after> [--fail-on 'removed,payload,latency>200ms'] [--json] [--html diff.html]
streamscope diff <after> --baseline <trace>

Inspect
streamscope inspect <trace> [--json] [--html viewer.html]

Expand Down Expand Up @@ -234,6 +255,8 @@ is written to <out>/<session>/events.jsonl.`;
streamscope inject <trace> --with "<dsl>" [-o <out.jsonl>] [--print]

Without -o the result is written next to the input as <session>.injected.jsonl.`;
case 'diff':
return `streamscope diff <before> <after> [--fail-on 'added,removed,payload,count,latency>200ms'] [--json] [--html diff.html]\nWith one trace, use --baseline <trace> or .streams/baseline.json containing {path,sha256}. Paths in the manifest are relative to the manifest directory.\nIdentity-less events match by ordinal; latency is elapsed frame time.`;
case 'inspect':
return `streamscope inspect — summarize a trace

Expand Down Expand Up @@ -279,6 +302,8 @@ export async function run(argv: string[], io: CliIO = DEFAULT_IO): Promise<numbe

try {
switch (parsed.command as Command) {
case 'diff':
return await runDiff(parsed, io);
case 'inspect':
return await runInspect(parsed, io);
case 'inject':
Expand Down Expand Up @@ -321,7 +346,9 @@ async function runInspect(parsed: Parsed, io: CliIO): Promise<number> {
if (bool(parsed, 'frames')) {
io.stdout('\n');
for (const frame of trace.frames) {
io.stdout(`#${frame.seq}\t${frame.t_ms}ms\t${frame.event.type}\t${JSON.stringify(frame.event.delta ?? frame.event.argsDelta ?? frame.event.message ?? '')}\n`);
io.stdout(
`#${frame.seq}\t${frame.t_ms}ms\t${frame.event.type}\t${JSON.stringify(frame.event.delta ?? frame.event.argsDelta ?? frame.event.message ?? '')}\n`,
);
}
}
}
Expand All @@ -346,10 +373,17 @@ async function runInject(parsed: Parsed, io: CliIO): Promise<number> {
});
const meta = {
...trace.meta,
notes: { ...(trace.meta.notes ?? {}), inject: formatScenario(faults), outcome: result.outcome },
notes: {
...(trace.meta.notes ?? {}),
inject: formatScenario(faults),
outcome: result.outcome,
},
};
const injected: Trace = { meta, frames: result.frames, path: trace.path };
const defaultOut = path.join(path.dirname(resolveTracePath(path.resolve(io.cwd, parsed.positionals[0] as string))), `${trace.meta.session}.injected.jsonl`);
const defaultOut = path.join(
path.dirname(resolveTracePath(path.resolve(io.cwd, parsed.positionals[0] as string))),
`${trace.meta.session}.injected.jsonl`,
);
const out = path.resolve(io.cwd, flag(parsed, 'out') ?? defaultOut);
await writeFile(out, traceToJsonl(injected), 'utf8');
io.stdout(`wrote ${out}\n`);
Expand Down Expand Up @@ -380,7 +414,9 @@ async function runRecord(parsed: Parsed, io: CliIO): Promise<number> {
onSession: () => undefined,
});
if (bool(parsed, 'no-redact')) {
io.stderr('streamscope: warning: recording without header redaction — Authorization, Cookie, Set-Cookie, X-API-Key and Proxy-Authorization are stored verbatim\n');
io.stderr(
'streamscope: warning: recording without header redaction — Authorization, Cookie, Set-Cookie, X-API-Key and Proxy-Authorization are stored verbatim\n',
);
}
io.stdout(`streamscope proxy: ${proxy.url} -> ${target}\n`);
io.stdout(`traces: ${out}/<session>/events.jsonl (Ctrl-C to stop)\n`);
Expand Down Expand Up @@ -448,3 +484,109 @@ if (isMain) {
process.exitCode = 1;
});
}

async function runDiff(parsed: Parsed, io: CliIO): Promise<number> {
if (parsed.positionals.length < 1 || parsed.positionals.length > 2)
throw new UsageError('diff needs <before> <after>, or <after> with a baseline');
let base: string | undefined, head: string | undefined, expected: string | undefined;
const explicit = flag(parsed, 'baseline');
if (parsed.positionals.length === 2) {
if (explicit) throw new UsageError('--baseline cannot be combined with two traces');
[base, head] = parsed.positionals;
} else {
head = parsed.positionals[0];
if (explicit) base = explicit;
else {
const manifest = path.resolve(io.cwd, '.streams/baseline.json');
const record = JSON.parse(readFileSync(manifest, 'utf8')) as {
path?: unknown;
sha256?: unknown;
sha?: unknown;
};
const hash = record.sha256 ?? record.sha;
if (typeof record.path !== 'string' || typeof hash !== 'string' || !/^[a-f0-9]{64}$/i.test(hash))
throw new UsageError('baseline manifest needs path and 64-character sha256 (sha alias accepted)');
base = path.resolve(path.dirname(manifest), record.path);
expected = hash.toLowerCase();
}
}
const before = await loadDiffTrace(base, io, expected),
after = await loadDiffTrace(head, io);
const html = flag(parsed, 'html');
if (html) {
const output = path.resolve(io.cwd, html);
for (const input of [before.path!, after.path!, path.resolve(io.cwd, '.streams/baseline.json')]) {
if (
output === input ||
(existsSync(output) &&
existsSync(input) &&
(realpathSync(output) === realpathSync(input) ||
(statSync(output).dev === statSync(input).dev && statSync(output).ino === statSync(input).ino)))
)
throw new UsageError('--html must not overwrite an input trace or baseline manifest');
}
}
const result = diffTraces(before, after),
raw = flag(parsed, 'fail-on');
const violations = diffViolations(result, raw === undefined ? [] : parseDiffGates(raw));
const output = { ...result, violations };
io.stdout(
(bool(parsed, 'json')
? JSON.stringify(output, null, 2)
: formatTraceDiff(result) + (violations.length ? `\nfailed gates: ${violations.join(', ')}` : '')) + '\n',
);
if (html) {
const out = path.resolve(io.cwd, html);
await mkdir(path.dirname(out), { recursive: true });
await writeFile(out, renderDiffHtml(result, before, after, violations), 'utf8');
io.stderr(`diff report: ${out}\n`);
}
return violations.length ? 1 : 0;
}

async function loadDiffTrace(input: string | undefined, io: CliIO, expected?: string): Promise<Trace> {
if (!input) throw new UsageError('missing diff trace');
const file = path.resolve(io.cwd, resolveTracePath(input));
const bytes = readFileSync(file);
if (expected && createHash('sha256').update(bytes).digest('hex') !== expected)
throw new UsageError('baseline SHA-256 mismatch');
const text = bytes.toString('utf8');
const lines = text.split(/\r?\n/).filter((line) => line.trim());
if (!lines.length) throw new UsageError(`empty diff trace: ${file}`);
const records = lines.map((line, i) => {
try {
return JSON.parse(line) as Record<string, unknown>;
} catch {
throw new UsageError(`invalid JSON at ${file}:${i + 1}`);
}
});
const meta = records[0];
if (
!meta ||
meta.kind !== 'meta' ||
meta.v !== 1 ||
typeof meta.adapter !== 'string' ||
!meta.adapter ||
typeof meta.protocol !== 'string' ||
typeof meta.framing !== 'string'
)
throw new UsageError(`invalid trace metadata: ${file}`);
const seq = new Set<number>();
for (const [i, frame] of records.slice(1).entries()) {
const event = frame?.event as Record<string, unknown> | undefined;
if (
!frame ||
!Number.isInteger(frame.seq) ||
seq.has(frame.seq as number) ||
typeof frame.t_ms !== 'number' ||
!Number.isFinite(frame.t_ms) ||
frame.t_ms < 0 ||
typeof frame.raw !== 'string' ||
!event ||
typeof event.type !== 'string'
)
throw new UsageError(`invalid diff frame at ${file}:${i + 2}`);
seq.add(frame.seq as number);
}
return parseTrace(text, file);
}
25 changes: 25 additions & 0 deletions e2e/run-e2e.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,7 @@ import { fileURLToPath } from 'node:url';
const root = path.resolve(path.dirname(fileURLToPath(import.meta.url)), '..');
const { chromium } = await import('playwright-core');
const { replayStream } = await import(path.join(root, 'dist', 'playwright.js'));
const { diffTraces, renderDiffHtml, parseTrace } = await import(path.join(root, 'dist', 'index.js'));
const { startReplayServer } = await import(path.join(root, 'dist', 'index.js'));

const DEMO_PORT = 8795;
Expand Down Expand Up @@ -115,6 +116,30 @@ try {
check('panel: injected error is flagged as the break point', breakCard);
await page.screenshot({ path: path.join(artifacts, 'panel.png'), fullPage: false });
await panelServer.close();

// Diff report: gates, both reused viewers and narrow-screen controls.
const original = parseTrace(await fs.readFile(path.join(root, 'demo', 'traces', 'chat-ai-sdk.jsonl'), 'utf8'));
const changed = structuredClone(original);
changed.frames.forEach(frame => { frame.t_ms += 200; });
changed.frames.push({seq:100,t_ms:600,raw:'data: {}',event:{type:'tool-call-delta',id:'added-tool',argsDelta:'{}'}});
const diff = diffTraces(original, changed);
await page.setContent(renderDiffHtml(diff, original, changed, ['added', 'latency>199ms']));
const report = page.locator('body');
check('diff: change summary and failed gates visible', (await report.innerText()).includes('Gate failed: added, latency>199ms'));
await page.setViewportSize({width:390,height:844});
check('diff: no outer horizontal overflow', await page.evaluate(() => document.documentElement.scrollWidth <= innerWidth));
for (const title of ['Before trace','After trace']) {
const iframe = page.frameLocator(`iframe[title="${title}"]`);
await iframe.locator('#scrub').waitFor();
await iframe.locator('#next').click();
check(`diff: ${title} next control works`, (await iframe.locator('#frame-title').innerText()).startsWith('#1 '));
const fits = await iframe.locator('body').evaluate(() => document.documentElement.scrollWidth <= innerWidth && document.querySelector('#scrub').getBoundingClientRect().right <= innerWidth);
check(`diff: ${title} controls fit narrow viewport`, fits);
await iframe.locator('.counts').evaluate(el => { el.scrollLeft = el.scrollWidth; });
check(`diff: ${title} counts can scroll`, await iframe.locator('.counts').evaluate(el => el.scrollWidth <= el.clientWidth || el.scrollLeft > 0));
}
await page.screenshot({path:path.join(artifacts,'diff-mobile.png'),fullPage:true});

} finally {
if (browser) await browser.close();
demo.kill('SIGTERM');
Expand Down
Loading