@docsxai/engine 0.2.1-rc.1 → 0.3.0-rc.1

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.
Files changed (94) hide show
  1. package/README.md +18 -5
  2. package/dist/address-class.d.ts +14 -0
  3. package/dist/address-class.js +151 -0
  4. package/dist/auth/api-login.d.ts +3 -3
  5. package/dist/auth/email-otp.d.ts +60 -60
  6. package/dist/auth/jwt-injection.d.ts +45 -45
  7. package/dist/auth/pat-header.d.ts +2 -2
  8. package/dist/auth/types.d.ts +2 -2
  9. package/dist/auth/ui-form.d.ts +54 -54
  10. package/dist/auth/webauthn.d.ts +22 -22
  11. package/dist/backend-client-contracts.d.ts +4 -2
  12. package/dist/calibrate.d.ts +2 -2
  13. package/dist/calibrate.js +5 -0
  14. package/dist/cli-commands-authoring.js +23 -4
  15. package/dist/cli-commands-backend.js +2 -2
  16. package/dist/cli-commands-docpack.d.ts +5 -0
  17. package/dist/cli-commands-docpack.js +70 -24
  18. package/dist/cli-commands-pack.d.ts +2 -0
  19. package/dist/cli-commands-pack.js +69 -0
  20. package/dist/cli-commands-session.js +92 -89
  21. package/dist/cli-retired.d.ts +6 -0
  22. package/dist/cli-retired.js +12 -0
  23. package/dist/cli-usage.d.ts +1 -1
  24. package/dist/cli-usage.js +52 -4
  25. package/dist/cli-verify.d.ts +14 -0
  26. package/dist/cli-verify.js +54 -0
  27. package/dist/cli.js +14 -1
  28. package/dist/deprecation.d.ts +19 -0
  29. package/dist/deprecation.js +32 -0
  30. package/dist/diagnose.d.ts +25 -0
  31. package/dist/diagnose.js +69 -3
  32. package/dist/diff-compute.js +1 -0
  33. package/dist/doc-pack-io.d.ts +14 -0
  34. package/dist/doc-pack-io.js +121 -14
  35. package/dist/doc-pack.d.ts +2282 -387
  36. package/dist/doc-pack.js +135 -43
  37. package/dist/doctor-checks.d.ts +1 -1
  38. package/dist/doctor-checks.js +25 -1
  39. package/dist/driver-budget.d.ts +6 -0
  40. package/dist/driver-budget.js +15 -0
  41. package/dist/egress-guard.d.ts +58 -0
  42. package/dist/egress-guard.js +136 -0
  43. package/dist/environment-spec.d.ts +67 -0
  44. package/dist/environment-spec.js +38 -0
  45. package/dist/export/playwright-test.js +42 -10
  46. package/dist/flow-file.d.ts +9 -3
  47. package/dist/flow-file.js +21 -1
  48. package/dist/flow-halt.d.ts +16 -0
  49. package/dist/flow-halt.js +76 -0
  50. package/dist/flow-hidden.d.ts +9 -0
  51. package/dist/flow-hidden.js +20 -0
  52. package/dist/flow-lint.js +91 -1
  53. package/dist/flow-matrix-lint.d.ts +10 -0
  54. package/dist/flow-matrix-lint.js +40 -0
  55. package/dist/flow-matrix.d.ts +44 -0
  56. package/dist/flow-matrix.js +238 -0
  57. package/dist/flow-name-rules.d.ts +15 -0
  58. package/dist/flow-name-rules.js +39 -0
  59. package/dist/flow-runtime.d.ts +52 -22
  60. package/dist/flow-runtime.js +63 -117
  61. package/dist/flow-success.d.ts +3 -0
  62. package/dist/flow-success.js +37 -0
  63. package/dist/flow-tree.d.ts +2 -0
  64. package/dist/flow-tree.js +17 -5
  65. package/dist/flow-wait.d.ts +3 -0
  66. package/dist/flow-wait.js +22 -0
  67. package/dist/index.d.ts +5 -0
  68. package/dist/index.js +5 -0
  69. package/dist/matrix-spec.d.ts +145 -0
  70. package/dist/matrix-spec.js +120 -0
  71. package/dist/page-hide.d.ts +10 -0
  72. package/dist/page-hide.js +45 -0
  73. package/dist/page-settle.d.ts +39 -0
  74. package/dist/page-settle.js +142 -0
  75. package/dist/playwright-driver.d.ts +28 -8
  76. package/dist/playwright-driver.js +73 -28
  77. package/dist/plugins/manifest.d.ts +9 -9
  78. package/dist/run-flows.d.ts +40 -0
  79. package/dist/run-flows.js +129 -0
  80. package/dist/style.d.ts +2 -2
  81. package/dist/upload-path.d.ts +15 -0
  82. package/dist/upload-path.js +63 -0
  83. package/dist/verify-compare.d.ts +43 -0
  84. package/dist/verify-compare.js +237 -0
  85. package/dist/verify-determinism.d.ts +16 -0
  86. package/dist/verify-determinism.js +88 -0
  87. package/dist/verify-report.d.ts +53 -0
  88. package/dist/verify-report.js +141 -0
  89. package/dist/verify-tree.d.ts +27 -0
  90. package/dist/verify-tree.js +95 -0
  91. package/dist/viewer-bin.d.ts +6 -0
  92. package/dist/viewer-bin.js +24 -0
  93. package/dist/zip.d.ts +2 -2
  94. package/package.json +3 -2
@@ -0,0 +1,40 @@
1
+ import { type StorageState } from "./auth.js";
2
+ import { type FlowFile } from "./doc-pack.js";
3
+ import { type FlowVariant } from "./flow-matrix.js";
4
+ export interface RunFlowsOptions {
5
+ /** The workspace: flows, auth and `upload` sources resolve against it. */
6
+ projectDir: string;
7
+ /** Where `docs/<flow>/…` is written. The workspace itself for a plain `run`. */
8
+ outputRoot: string;
9
+ /** Flows to run. A flow with a `matrix` runs once per variant (see `expandFlow`). */
10
+ flows: FlowFile[];
11
+ /** Run only the matrix variant with this id; other variants and flows without a matrix are skipped. */
12
+ variant?: string | undefined;
13
+ storageState?: StorageState | undefined;
14
+ baseURL?: string | undefined;
15
+ headed: boolean;
16
+ ignoreHTTPSErrors: boolean;
17
+ cdpEndpoint?: string | undefined;
18
+ stopAfter?: string | undefined;
19
+ startFrom?: string | undefined;
20
+ pause: boolean;
21
+ /** `annotations.obstacles` from the workspace config. */
22
+ obstacles: boolean;
23
+ concurrency: number;
24
+ /** Progress lines (`run: …`). stdout for `run`; stderr in verify mode so stdout stays the report. */
25
+ progress: (line: string) => void;
26
+ }
27
+ /** `<flow>` for a flow without a matrix, `<flow>/<variant>` for a variant (the name `render` and `burn` use). */
28
+ export declare function unitLabel(unit: FlowVariant): string;
29
+ /** A unit that did not finish. `flow` is the unit label; `step` is set when the runtime halted on a step. */
30
+ export interface FlowFailure {
31
+ flow: string;
32
+ step: string | null;
33
+ message: string;
34
+ }
35
+ export interface RunFlowsResult {
36
+ okCount: number;
37
+ failures: FlowFailure[];
38
+ }
39
+ /** Execute `opts.flows`, up to `opts.concurrency` at a time, each in its own browser session. */
40
+ export declare function runFlowsInSessions(opts: RunFlowsOptions): Promise<RunFlowsResult>;
@@ -0,0 +1,129 @@
1
+ // The flow-execution loop behind `docsxai run`: one Playwright session per unit (a flow, or one
2
+ // matrix variant of a flow), a worker pool for `--concurrency`, and the write of each unit's
3
+ // annotations.json under an output root (`docs/<flow>/`, or `docs/<flow>/<variant>/` for a matrix).
4
+ // Split out of the CLI handler so `run --verify-determinism` drives the identical code path against
5
+ // an isolated output root instead of the workspace.
6
+ import { promises as fs } from "node:fs";
7
+ import { FlowExecutionError } from "./flow-halt.js";
8
+ import { expandFlows } from "./flow-matrix.js";
9
+ import { runFlow } from "./flow-runtime.js";
10
+ import { launchPlaywrightSession } from "./playwright-driver.js";
11
+ import { resolveWorkspacePath, resolveWorkspacePathReal } from "./workspace.js";
12
+ /** `<flow>` for a flow without a matrix, `<flow>/<variant>` for a variant (the name `render` and `burn` use). */
13
+ export function unitLabel(unit) {
14
+ return unit.id ? `${unit.flow.name}/${unit.id}` : unit.flow.name;
15
+ }
16
+ /** The units `opts` selects: every flow expanded, narrowed to `opts.variant` when it is set. */
17
+ function selectUnits(opts) {
18
+ const units = expandFlows(opts.flows);
19
+ return opts.variant ? units.filter((u) => u.id === opts.variant) : units;
20
+ }
21
+ /** Merge a `--start-from` partial run into the annotations file already on disk, by step id. */
22
+ async function mergeAnnotations(annotationsPath, fresh) {
23
+ try {
24
+ const existing = JSON.parse(await fs.readFile(annotationsPath, "utf8"));
25
+ const newStepIds = new Set(fresh.annotations.map((a) => a.step));
26
+ const merged = [
27
+ ...existing.annotations.filter((a) => !newStepIds.has(a.step)),
28
+ ...fresh.annotations,
29
+ ];
30
+ return { ...fresh, annotations: merged };
31
+ }
32
+ catch {
33
+ // No existing file (or unreadable) — just write what we have.
34
+ return fresh;
35
+ }
36
+ }
37
+ /** Execute `opts.flows`, up to `opts.concurrency` at a time, each in its own browser session. */
38
+ export async function runFlowsInSessions(opts) {
39
+ const { projectDir, outputRoot, startFrom, stopAfter, pause } = opts;
40
+ const tag = opts.concurrency > 1 ? (name) => `run [${name}]: ` : () => "run: ";
41
+ const say = (line) => opts.progress(line);
42
+ const failures = [];
43
+ async function runOne(unit) {
44
+ const { flow } = unit;
45
+ const name = unitLabel(unit);
46
+ let session;
47
+ try {
48
+ // When attaching to an existing Chrome via --cdp, the operator owns its auth state — don't
49
+ // load cached `storageState` over it (would replace cookies). When launching fresh, do.
50
+ session = await launchPlaywrightSession({
51
+ baseURL: opts.baseURL,
52
+ headed: opts.headed,
53
+ ignoreHTTPSErrors: opts.ignoreHTTPSErrors,
54
+ ...(opts.cdpEndpoint
55
+ ? { connectOverCdp: opts.cdpEndpoint }
56
+ : { storageState: opts.storageState }),
57
+ ...(flow.environment ? { environment: flow.environment } : {}),
58
+ docPackRoot: projectDir,
59
+ outputRoot,
60
+ });
61
+ }
62
+ catch (e) {
63
+ const msg = e.message;
64
+ const reason = /Executable doesn't exist|browserType\.launch|playwright install/i.test(msg)
65
+ ? "no Chromium binary found. Install one: npx playwright-core install chromium (source checkout: pnpm -C packages/engine exec playwright-core install chromium)"
66
+ : `failed to launch browser: ${msg}`;
67
+ process.stderr.write(`${tag(name)}${reason}\n`);
68
+ failures.push({ flow: name, step: null, message: reason });
69
+ return false;
70
+ }
71
+ try {
72
+ const result = await runFlow(flow, session.driver, {
73
+ resolveLocator: (n) => flow.locators[n],
74
+ ...(unit.info ? { variant: unit.info } : {}),
75
+ ...(stopAfter ? { stopAfter } : {}),
76
+ ...(startFrom ? { startFrom } : {}),
77
+ ...(opts.obstacles ? { obstacles: true } : {}),
78
+ });
79
+ const docSegments = ["docs", flow.name, ...(unit.id ? [unit.id] : [])];
80
+ await fs.mkdir(resolveWorkspacePath(outputRoot, ...docSegments), { recursive: true });
81
+ // Flow names and variant ids come from the flow-files — resolve the write target symlink-aware.
82
+ const annotationsPath = await resolveWorkspacePathReal(outputRoot, ...docSegments, "annotations.json");
83
+ // With `startFrom`, only the post-startFrom steps emit annotations — merge them into the
84
+ // existing file (if any) by step id so the prior steps' annotations stay in place. Same
85
+ // story for screenshots (they live as separate PNGs and are simply not re-captured).
86
+ const toWrite = startFrom
87
+ ? await mergeAnnotations(annotationsPath, result.annotations)
88
+ : result.annotations;
89
+ await fs.writeFile(annotationsPath, JSON.stringify(toWrite, null, 2) + "\n", "utf8");
90
+ say(`${tag(name)}${name} — ${result.steps.length} step(s) executed, ${result.annotations.annotations.length} annotation(s) ${startFrom ? "merged" : "written"}\n`);
91
+ return true;
92
+ }
93
+ catch (e) {
94
+ const message = e.message;
95
+ process.stderr.write(`${tag(name)}${message}\n`);
96
+ failures.push({
97
+ flow: name,
98
+ step: e instanceof FlowExecutionError ? e.stepId : null,
99
+ message,
100
+ });
101
+ return false;
102
+ }
103
+ finally {
104
+ if (pause) {
105
+ say("run: --pause — browser is open at the last step run; close it to exit.\n");
106
+ await new Promise((resolve) => session.browser.on("disconnected", () => resolve()));
107
+ }
108
+ await session.close();
109
+ }
110
+ }
111
+ const units = selectUnits(opts);
112
+ let idx = 0;
113
+ let okCount = 0;
114
+ async function worker() {
115
+ while (idx < units.length) {
116
+ const unit = units[idx++];
117
+ if (await runOne(unit))
118
+ okCount++;
119
+ }
120
+ }
121
+ const workers = Math.min(opts.concurrency, units.length);
122
+ const noun = units.some((u) => u.id) ? "flow variants" : "flows";
123
+ if (workers > 1)
124
+ say(`run: running ${units.length} ${noun} with ${workers} parallel worker(s)…\n`);
125
+ await Promise.all(Array.from({ length: workers }, () => worker()));
126
+ // Workers finish in completion order; sort so the failure list is stable across runs.
127
+ failures.sort((a, b) => (a.flow < b.flow ? -1 : a.flow > b.flow ? 1 : 0));
128
+ return { okCount, failures };
129
+ }
package/dist/style.d.ts CHANGED
@@ -1,7 +1,7 @@
1
1
  import { StyleArtifact } from "./doc-pack.js";
2
2
  export declare class StyleError extends Error {
3
- readonly cause?: unknown;
4
- constructor(message: string, cause?: unknown);
3
+ readonly cause?: unknown | undefined;
4
+ constructor(message: string, cause?: unknown | undefined);
5
5
  }
6
6
  /** The seed style every workspace starts with — overwritable by the agent during calibration. */
7
7
  export declare const DEFAULT_STYLE: StyleArtifact;
@@ -0,0 +1,15 @@
1
+ /** An `upload` value that reaches outside the workspace or does not name a regular file. */
2
+ export declare class UploadPathError extends Error {
3
+ constructor(value: string, reason: string);
4
+ }
5
+ /**
6
+ * Why `value` cannot be an upload path on its spelling alone, or null: empty, with a NUL byte,
7
+ * absolute (a leading slash or backslash, or a drive letter), with a `..` segment, with a segment
8
+ * that starts with a dot (`.auth/` holds captured sessions, `.docsxai.json` the workspace config) or
9
+ * naming `webhook-job.json`. The backend
10
+ * keeps a copy of this rule for flow files it stores, and a test in `packages/docsxai` holds the
11
+ * two to the same answers.
12
+ */
13
+ export declare function uploadPathProblem(value: string): string | null;
14
+ /** The real path of the file `value` names under `root`; throws {@link UploadPathError} otherwise. */
15
+ export declare function resolveUploadPath(root: string, value: string): Promise<string>;
@@ -0,0 +1,63 @@
1
+ // Where an `upload` step may read from. The step hands a file to the page it is driving, so a
2
+ // value that reaches outside the workspace (`/proc/self/environ`, a key under the home directory)
3
+ // would put that file in front of the app's own script. The value must be a path relative to the
4
+ // workspace root, with no `..` segment, that names a regular file whose real path (symlinks
5
+ // followed) is still under the root.
6
+ import { promises as fs } from "node:fs";
7
+ import * as path from "node:path";
8
+ import { resolveWorkspacePathReal, WorkspacePathEscapeError } from "./workspace.js";
9
+ /** An `upload` value that reaches outside the workspace or does not name a regular file. */
10
+ export class UploadPathError extends Error {
11
+ constructor(value, reason) {
12
+ super(`upload path ${JSON.stringify(value)} ${reason}`);
13
+ this.name = "UploadPathError";
14
+ }
15
+ }
16
+ /**
17
+ * Why `value` cannot be an upload path on its spelling alone, or null: empty, with a NUL byte,
18
+ * absolute (a leading slash or backslash, or a drive letter), with a `..` segment, with a segment
19
+ * that starts with a dot (`.auth/` holds captured sessions, `.docsxai.json` the workspace config) or
20
+ * naming `webhook-job.json`. The backend
21
+ * keeps a copy of this rule for flow files it stores, and a test in `packages/docsxai` holds the
22
+ * two to the same answers.
23
+ */
24
+ export function uploadPathProblem(value) {
25
+ if (value === "")
26
+ return "is empty";
27
+ if (value.includes("\0"))
28
+ return "contains a NUL byte";
29
+ if (/^(?:[\\/]|[A-Za-z]:)/.test(value))
30
+ return "is an absolute path";
31
+ const segments = value.split(/[\\/]+/);
32
+ if (segments.includes(".."))
33
+ return "has a .. segment";
34
+ if (segments.some((s) => s.startsWith(".") && s !== "."))
35
+ return "has a hidden segment";
36
+ if (segments.some((s) => s.toLowerCase() === "webhook-job.json"))
37
+ return "is a reserved file";
38
+ return null;
39
+ }
40
+ /** The real path of the file `value` names under `root`; throws {@link UploadPathError} otherwise. */
41
+ export async function resolveUploadPath(root, value) {
42
+ const spelling = uploadPathProblem(value);
43
+ if (spelling)
44
+ throw new UploadPathError(value, spelling);
45
+ let real;
46
+ try {
47
+ real = await fs.realpath(await resolveWorkspacePathReal(root, value));
48
+ }
49
+ catch (e) {
50
+ if (e instanceof WorkspacePathEscapeError) {
51
+ throw new UploadPathError(value, "is outside the workspace");
52
+ }
53
+ throw new UploadPathError(value, "does not name a readable file under the workspace");
54
+ }
55
+ // A symlink under an innocent name must not lead to a hidden or reserved file either.
56
+ const target = path.relative(await fs.realpath(root), real);
57
+ const reserved = uploadPathProblem(target);
58
+ if (reserved)
59
+ throw new UploadPathError(value, `leads to a path that ${reserved}`);
60
+ if (!(await fs.stat(real)).isFile())
61
+ throw new UploadPathError(value, "is not a regular file");
62
+ return real;
63
+ }
@@ -0,0 +1,43 @@
1
+ import { type DimensionChange, type DriftRegion } from "./diff.js";
2
+ export type DifferenceKind = "missing" | "extra" | "json" | "png" | "text" | "bytes";
3
+ export interface ArtefactDifference {
4
+ /** Root-relative, `/`-separated. */
5
+ path: string;
6
+ /** The run that disagreed with run 1 (2 and up). */
7
+ run: number;
8
+ kind: DifferenceKind;
9
+ /** One line a person can act on. */
10
+ hint: string;
11
+ size?: {
12
+ a: number;
13
+ b: number;
14
+ };
15
+ /** `json`: where the two documents first differ, e.g. `annotations[0].bounding_box.x`. */
16
+ json_path?: string;
17
+ /** `png`: bounding box of the changed pixels. */
18
+ region?: DriftRegion;
19
+ changed_pixel_count?: number;
20
+ dimension_change?: DimensionChange;
21
+ /** `text`: 1-based line of the first difference. */
22
+ line?: number;
23
+ }
24
+ export type ContentDifference = Omit<ArtefactDifference, "path" | "run">;
25
+ /** First difference between two parsed JSON values, in a stable order: array indices ascending, object keys ordinal. */
26
+ export declare function firstJsonDifference(a: unknown, b: unknown, at?: string): {
27
+ path: string;
28
+ a: unknown;
29
+ b: unknown;
30
+ } | null;
31
+ /** Compare one artefact's two byte strings. `null` when they are identical. */
32
+ export declare function compareArtefactBytes(artefactPath: string, a: Buffer, b: Buffer): ContentDifference | null;
33
+ /** Artefacts above this size are compared as raw bytes in chunks and never decoded or held whole. */
34
+ export declare const MAX_COMPARE_BYTES: number;
35
+ export interface TreeComparison {
36
+ /** Artefacts in run 1, the side every other run is compared against. */
37
+ compared: number;
38
+ differences: ArtefactDifference[];
39
+ }
40
+ /** Compare run root `a` (run 1) with run root `b` (run `run`). Differences come out in ordinal path order. */
41
+ export declare function compareRunRoots(aRoot: string, bRoot: string, run: number, maxBytes?: number): Promise<TreeComparison>;
42
+ /** Compare run 1 against every other run. Differences are ordered by path, then by run. */
43
+ export declare function compareRuns(roots: string[]): Promise<TreeComparison>;
@@ -0,0 +1,237 @@
1
+ // Byte comparison of two run roots for `run --verify-determinism`. Every file under the roots is an
2
+ // artefact (annotations.json, screenshots, step markdown, locators, halt context). Equal bytes pass;
3
+ // otherwise the comparator says where the two files first part ways, in terms an author can act on:
4
+ // a JSON key path, the bounding box of the changed pixels of a PNG, the first differing line of a
5
+ // text file, or the sizes. Pure over the file contents and ordered by ordinal path, so the same two
6
+ // roots always produce the same differences in the same order.
7
+ import { promises as fs } from "node:fs";
8
+ import { diffPngBuffers } from "./diff.js";
9
+ import { byOrdinal, listTree } from "./verify-tree.js";
10
+ import { resolveWorkspacePath } from "./workspace.js";
11
+ const MAX_SHOWN = 60;
12
+ function show(v) {
13
+ const s = v === undefined ? "(absent)" : JSON.stringify(v);
14
+ return s.length > MAX_SHOWN ? `${s.slice(0, MAX_SHOWN - 1)}…` : s;
15
+ }
16
+ function isRecord(v) {
17
+ return typeof v === "object" && v !== null && !Array.isArray(v);
18
+ }
19
+ /** First difference between two parsed JSON values, in a stable order: array indices ascending, object keys ordinal. */
20
+ export function firstJsonDifference(a, b, at = "") {
21
+ if (Array.isArray(a) && Array.isArray(b)) {
22
+ const n = Math.max(a.length, b.length);
23
+ for (let i = 0; i < n; i++) {
24
+ const d = firstJsonDifference(a[i], b[i], `${at}[${i}]`);
25
+ if (d)
26
+ return d;
27
+ }
28
+ return null;
29
+ }
30
+ if (isRecord(a) && isRecord(b)) {
31
+ const keys = [...new Set([...Object.keys(a), ...Object.keys(b)])].sort(byOrdinal);
32
+ for (const k of keys) {
33
+ const d = firstJsonDifference(a[k], b[k], at === "" ? k : `${at}.${k}`);
34
+ if (d)
35
+ return d;
36
+ }
37
+ return null;
38
+ }
39
+ return Object.is(a, b) ? null : { path: at === "" ? "(root)" : at, a, b };
40
+ }
41
+ function sizeHint(a, b) {
42
+ if (a.length !== b.length)
43
+ return `size differs (${a.length} vs ${b.length} bytes)`;
44
+ let i = 0;
45
+ while (a[i] === b[i])
46
+ i++;
47
+ return `same size (${a.length} bytes), first differing byte at offset ${i}`;
48
+ }
49
+ function compareJson(a, b) {
50
+ let pa;
51
+ let pb;
52
+ try {
53
+ pa = JSON.parse(a.toString("utf8"));
54
+ pb = JSON.parse(b.toString("utf8"));
55
+ }
56
+ catch {
57
+ return null;
58
+ }
59
+ const d = firstJsonDifference(pa, pb);
60
+ if (!d) {
61
+ return {
62
+ kind: "json",
63
+ hint: `same JSON data, bytes differ (key order or formatting): ${sizeHint(a, b)}`,
64
+ size: { a: a.length, b: b.length },
65
+ };
66
+ }
67
+ return {
68
+ kind: "json",
69
+ hint: `key ${d.path} differs: ${show(d.a)} vs ${show(d.b)}`,
70
+ json_path: d.path,
71
+ size: { a: a.length, b: b.length },
72
+ };
73
+ }
74
+ function comparePng(a, b) {
75
+ let result;
76
+ try {
77
+ result = diffPngBuffers(a, b);
78
+ }
79
+ catch {
80
+ return null;
81
+ }
82
+ const size = { a: a.length, b: b.length };
83
+ if (result.kind === "dimension-change") {
84
+ const { a: da, b: db } = result;
85
+ return {
86
+ kind: "png",
87
+ hint: `image size differs (${da.width}x${da.height} vs ${db.width}x${db.height} px)`,
88
+ dimension_change: { a: da, b: db },
89
+ size,
90
+ };
91
+ }
92
+ if (result.changed_pixel_count === 0) {
93
+ return {
94
+ kind: "png",
95
+ hint: `pixels identical, file bytes differ (encoder output or metadata): ${sizeHint(a, b)}`,
96
+ size,
97
+ };
98
+ }
99
+ const r = result.region;
100
+ return {
101
+ kind: "png",
102
+ hint: `${result.changed_pixel_count} pixels differ (${result.pct}%) inside x=${r.x} y=${r.y} ${r.width}x${r.height}`,
103
+ changed_pixel_count: result.changed_pixel_count,
104
+ region: r,
105
+ size,
106
+ };
107
+ }
108
+ function compareText(a, b) {
109
+ const la = a.toString("utf8").split("\n");
110
+ const lb = b.toString("utf8").split("\n");
111
+ let i = 0;
112
+ while (i < la.length && i < lb.length && la[i] === lb[i])
113
+ i++;
114
+ if (i === la.length && i === lb.length)
115
+ return bytesDifference(a, b); // differs only in invalid UTF-8
116
+ return {
117
+ kind: "text",
118
+ hint: `line ${i + 1} differs: ${show(la[i])} vs ${show(lb[i])}`,
119
+ line: i + 1,
120
+ size: { a: a.length, b: b.length },
121
+ };
122
+ }
123
+ function bytesDifference(a, b) {
124
+ return { kind: "bytes", hint: sizeHint(a, b), size: { a: a.length, b: b.length } };
125
+ }
126
+ /** Compare one artefact's two byte strings. `null` when they are identical. */
127
+ export function compareArtefactBytes(artefactPath, a, b) {
128
+ if (a.equals(b))
129
+ return null;
130
+ const ext = artefactPath.slice(artefactPath.lastIndexOf(".")).toLowerCase();
131
+ if (ext === ".png")
132
+ return comparePng(a, b) ?? bytesDifference(a, b);
133
+ if (ext === ".json")
134
+ return compareJson(a, b) ?? bytesDifference(a, b);
135
+ if ([".md", ".yaml", ".yml", ".txt"].includes(ext))
136
+ return compareText(a, b);
137
+ return bytesDifference(a, b);
138
+ }
139
+ /** Artefacts above this size are compared as raw bytes in chunks and never decoded or held whole. */
140
+ export const MAX_COMPARE_BYTES = 64 * 1024 * 1024;
141
+ const CHUNK_BYTES = 1024 * 1024;
142
+ function limitLabel(maxBytes) {
143
+ return maxBytes >= 1024 * 1024 ? `${maxBytes / (1024 * 1024)} MiB` : `${maxBytes} bytes`;
144
+ }
145
+ async function sameBytesChunked(aPath, bPath) {
146
+ const [fa, fb] = [await fs.open(aPath, "r"), await fs.open(bPath, "r")];
147
+ try {
148
+ const [ba, bb] = [Buffer.allocUnsafe(CHUNK_BYTES), Buffer.allocUnsafe(CHUNK_BYTES)];
149
+ for (;;) {
150
+ const [ra, rb] = await Promise.all([
151
+ fa.read(ba, 0, CHUNK_BYTES, null),
152
+ fb.read(bb, 0, CHUNK_BYTES, null),
153
+ ]);
154
+ if (ra.bytesRead !== rb.bytesRead)
155
+ return false;
156
+ if (ra.bytesRead === 0)
157
+ return true;
158
+ if (!ba.subarray(0, ra.bytesRead).equals(bb.subarray(0, rb.bytesRead)))
159
+ return false;
160
+ }
161
+ }
162
+ finally {
163
+ await Promise.all([fa.close(), fb.close()]);
164
+ }
165
+ }
166
+ /**
167
+ * Compare two artefacts too large to decode: sizes first, then the bytes in 1 MiB chunks. The
168
+ * difference is always `bytes`-level: a PNG is not decoded and a JSON file is not parsed.
169
+ */
170
+ async function compareLarge(aPath, bPath, size, maxBytes) {
171
+ const over = `larger than ${limitLabel(maxBytes)}, compared as raw bytes`;
172
+ if (size.a !== size.b) {
173
+ return { kind: "bytes", hint: `${over}: ${size.a} vs ${size.b} bytes`, size };
174
+ }
175
+ if (await sameBytesChunked(aPath, bPath))
176
+ return null;
177
+ return { kind: "bytes", hint: `${over}: same size (${size.a} bytes), content differs`, size };
178
+ }
179
+ /** Compare run root `a` (run 1) with run root `b` (run `run`). Differences come out in ordinal path order. */
180
+ export async function compareRunRoots(aRoot, bRoot, run, maxBytes = MAX_COMPARE_BYTES) {
181
+ const [la, lb] = await Promise.all([listTree(aRoot), listTree(bRoot)]);
182
+ const inA = new Set(la.files);
183
+ const inB = new Set(lb.files);
184
+ const all = [...new Set([...la.files, ...lb.files])].sort(byOrdinal);
185
+ const differences = [];
186
+ for (const rel of all) {
187
+ if (!inB.has(rel)) {
188
+ differences.push({
189
+ path: rel,
190
+ run,
191
+ kind: "missing",
192
+ hint: `present in run 1, absent in run ${run}`,
193
+ });
194
+ continue;
195
+ }
196
+ if (!inA.has(rel)) {
197
+ differences.push({
198
+ path: rel,
199
+ run,
200
+ kind: "extra",
201
+ hint: `absent in run 1, present in run ${run}`,
202
+ });
203
+ continue;
204
+ }
205
+ const segments = rel.split("/");
206
+ const aPath = resolveWorkspacePath(aRoot, ...segments);
207
+ const bPath = resolveWorkspacePath(bRoot, ...segments);
208
+ // Size first: a huge artefact is never read whole.
209
+ const [sa, sb] = await Promise.all([fs.stat(aPath), fs.stat(bPath)]);
210
+ if (sa.size > maxBytes || sb.size > maxBytes) {
211
+ const large = await compareLarge(aPath, bPath, { a: sa.size, b: sb.size }, maxBytes);
212
+ if (large)
213
+ differences.push({ path: rel, run, ...large });
214
+ continue;
215
+ }
216
+ const [a, b] = await Promise.all([fs.readFile(aPath), fs.readFile(bPath)]);
217
+ const d = compareArtefactBytes(rel, a, b);
218
+ if (d)
219
+ differences.push({ path: rel, run, ...d });
220
+ }
221
+ return { compared: la.files.length, differences };
222
+ }
223
+ /** Compare run 1 against every other run. Differences are ordered by path, then by run. */
224
+ export async function compareRuns(roots) {
225
+ const [first, ...rest] = roots;
226
+ if (first === undefined)
227
+ return { compared: 0, differences: [] };
228
+ let compared = 0;
229
+ const differences = [];
230
+ for (const [i, root] of rest.entries()) {
231
+ const c = await compareRunRoots(first, root, i + 2);
232
+ compared = Math.max(compared, c.compared);
233
+ differences.push(...c.differences);
234
+ }
235
+ differences.sort((x, y) => byOrdinal(x.path, y.path) || x.run - y.run);
236
+ return { compared, differences };
237
+ }
@@ -0,0 +1,16 @@
1
+ import { type RunFlowsOptions } from "./run-flows.js";
2
+ import { type VerifyReport } from "./verify-report.js";
3
+ export declare const VERIFY_DIR = ".docsxai-verify";
4
+ export declare const MIN_RUNS = 2;
5
+ export declare const MAX_RUNS = 5;
6
+ export declare const DEFAULT_RUNS = 2;
7
+ export type VerifyRunOptions = Omit<RunFlowsOptions, "outputRoot" | "progress" | "pause"> & {
8
+ runs: number;
9
+ progress: (line: string) => void;
10
+ };
11
+ /** Root of run `k` (1-based) under the workspace. */
12
+ export declare function runRoot(projectDir: string, k: number): string;
13
+ /** Workspace-relative path of a flow's halt context inside a run root. */
14
+ export declare function haltContextRelPath(flow: string): string;
15
+ /** Run the flows `opts.runs` times into isolated roots, compare, and promote run 1 when all agree. */
16
+ export declare function verifyDeterminism(opts: VerifyRunOptions): Promise<VerifyReport>;
@@ -0,0 +1,88 @@
1
+ // `docsxai run --verify-determinism`: run the selected flows N times, each into its own output root
2
+ // under `<workspace>/.docsxai-verify/run-<k>/`, then byte-compare every artefact.
3
+ //
4
+ // The workspace output (docs/<flow>/…) is only written when every run agrees: run 1's tree is copied
5
+ // in then, and it is the same bytes a plain `run` would have written. When the runs differ or a flow
6
+ // halts, the workspace is left exactly as it was. The run roots are removed at the end by the paths
7
+ // listed in them (see verify-tree.ts); there is no recursive delete.
8
+ import { promises as fs } from "node:fs";
9
+ import * as os from "node:os";
10
+ import * as path from "node:path";
11
+ import { runFlowsInSessions } from "./run-flows.js";
12
+ import { compareRuns } from "./verify-compare.js";
13
+ import { buildVerifyReport } from "./verify-report.js";
14
+ import { assertRegularTree, copyTree, removeListedTree } from "./verify-tree.js";
15
+ import { resolveWorkspacePath, resolveWorkspacePathReal } from "./workspace.js";
16
+ export const VERIFY_DIR = ".docsxai-verify";
17
+ export const MIN_RUNS = 2;
18
+ export const MAX_RUNS = 5;
19
+ export const DEFAULT_RUNS = 2;
20
+ /** Root of run `k` (1-based) under the workspace. */
21
+ export function runRoot(projectDir, k) {
22
+ return resolveWorkspacePath(projectDir, VERIFY_DIR, `run-${k}`);
23
+ }
24
+ /** Workspace-relative path of a flow's halt context inside a run root. */
25
+ export function haltContextRelPath(flow) {
26
+ return path.posix.join("docs", flow, "halts", "halt-context.json");
27
+ }
28
+ async function writeHaltContext(root, failure) {
29
+ const rel = haltContextRelPath(failure.flow);
30
+ const abs = await resolveWorkspacePathReal(root, ...rel.split("/"));
31
+ await fs.mkdir(path.dirname(abs), { recursive: true });
32
+ const body = {
33
+ schema: "docsxai/halt-context@1",
34
+ flow: failure.flow,
35
+ step: failure.step,
36
+ message: failure.message,
37
+ };
38
+ await fs.writeFile(abs, JSON.stringify(body, null, 2) + "\n", "utf8");
39
+ }
40
+ async function cleanUp(projectDir, runs) {
41
+ for (let k = 1; k <= runs; k++)
42
+ await removeListedTree(runRoot(projectDir, k));
43
+ // The parent only goes when it is empty; anything else in it stays.
44
+ await fs.rmdir(resolveWorkspacePath(projectDir, VERIFY_DIR)).catch((e) => {
45
+ if (e.code !== "ENOENT" && e.code !== "ENOTEMPTY" && e.code !== "EEXIST")
46
+ throw e;
47
+ });
48
+ }
49
+ /** Run the flows `opts.runs` times into isolated roots, compare, and promote run 1 when all agree. */
50
+ export async function verifyDeterminism(opts) {
51
+ const { runs, projectDir } = opts;
52
+ const halts = [];
53
+ try {
54
+ // A crashed earlier verification may have left run roots behind; they are ours by name.
55
+ await cleanUp(projectDir, MAX_RUNS);
56
+ const roots = [];
57
+ for (let k = 1; k <= runs; k++) {
58
+ const outputRoot = runRoot(projectDir, k);
59
+ await fs.mkdir(outputRoot, { recursive: true });
60
+ opts.progress(`verify-determinism: run ${k} of ${runs}\n`);
61
+ const result = await runFlowsInSessions({ ...opts, pause: false, outputRoot });
62
+ for (const failure of result.failures) {
63
+ await writeHaltContext(outputRoot, failure);
64
+ halts.push({ run: k, ...failure });
65
+ }
66
+ roots.push(outputRoot);
67
+ }
68
+ // A symlink in a run root would be read through by the comparison and refused by the copy.
69
+ for (const root of roots)
70
+ await assertRegularTree(root);
71
+ const compared = await compareRuns(roots);
72
+ const identical = compared.differences.length === 0 && halts.length === 0;
73
+ if (identical)
74
+ await copyTree(roots[0], path.resolve(projectDir));
75
+ return buildVerifyReport({
76
+ runs,
77
+ flows: opts.flows.map((f) => f.name),
78
+ artefactsCompared: compared.compared,
79
+ differences: compared.differences,
80
+ halts,
81
+ promoted: identical,
82
+ scrubRoots: [path.resolve(projectDir), os.homedir(), os.tmpdir()],
83
+ });
84
+ }
85
+ finally {
86
+ await cleanUp(projectDir, MAX_RUNS);
87
+ }
88
+ }