@docsxai/engine 0.2.0 → 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 (89) hide show
  1. package/README.md +26 -6
  2. package/dist/address-class.d.ts +14 -0
  3. package/dist/address-class.js +151 -0
  4. package/dist/auth/api-login.js +6 -2
  5. package/dist/backend-client-contracts.d.ts +2 -0
  6. package/dist/calibrate.js +5 -0
  7. package/dist/cli-commands-authoring.js +23 -4
  8. package/dist/cli-commands-backend.js +2 -2
  9. package/dist/cli-commands-docpack.d.ts +5 -0
  10. package/dist/cli-commands-docpack.js +70 -24
  11. package/dist/cli-commands-pack.d.ts +2 -0
  12. package/dist/cli-commands-pack.js +69 -0
  13. package/dist/cli-commands-session.js +92 -88
  14. package/dist/cli-retired.d.ts +6 -0
  15. package/dist/cli-retired.js +12 -0
  16. package/dist/cli-usage.d.ts +1 -1
  17. package/dist/cli-usage.js +53 -5
  18. package/dist/cli-verify.d.ts +14 -0
  19. package/dist/cli-verify.js +54 -0
  20. package/dist/cli.js +14 -1
  21. package/dist/deprecation.d.ts +19 -0
  22. package/dist/deprecation.js +32 -0
  23. package/dist/diagnose.d.ts +25 -0
  24. package/dist/diagnose.js +69 -3
  25. package/dist/diff-compute.js +1 -0
  26. package/dist/doc-pack-io.d.ts +14 -0
  27. package/dist/doc-pack-io.js +121 -14
  28. package/dist/doc-pack.d.ts +2165 -181
  29. package/dist/doc-pack.js +152 -42
  30. package/dist/doctor-checks.d.ts +1 -1
  31. package/dist/doctor-checks.js +29 -5
  32. package/dist/driver-budget.d.ts +6 -0
  33. package/dist/driver-budget.js +15 -0
  34. package/dist/egress-guard.d.ts +58 -0
  35. package/dist/egress-guard.js +136 -0
  36. package/dist/environment-spec.d.ts +67 -0
  37. package/dist/environment-spec.js +38 -0
  38. package/dist/export/playwright-test.js +42 -10
  39. package/dist/flow-file.d.ts +7 -1
  40. package/dist/flow-file.js +21 -1
  41. package/dist/flow-halt.d.ts +16 -0
  42. package/dist/flow-halt.js +76 -0
  43. package/dist/flow-hidden.d.ts +9 -0
  44. package/dist/flow-hidden.js +20 -0
  45. package/dist/flow-lint.js +91 -1
  46. package/dist/flow-matrix-lint.d.ts +10 -0
  47. package/dist/flow-matrix-lint.js +40 -0
  48. package/dist/flow-matrix.d.ts +44 -0
  49. package/dist/flow-matrix.js +238 -0
  50. package/dist/flow-name-rules.d.ts +15 -0
  51. package/dist/flow-name-rules.js +39 -0
  52. package/dist/flow-runtime.d.ts +67 -21
  53. package/dist/flow-runtime.js +72 -110
  54. package/dist/flow-success.d.ts +3 -0
  55. package/dist/flow-success.js +37 -0
  56. package/dist/flow-tree.d.ts +2 -0
  57. package/dist/flow-tree.js +17 -5
  58. package/dist/flow-wait.d.ts +3 -0
  59. package/dist/flow-wait.js +22 -0
  60. package/dist/index.d.ts +6 -0
  61. package/dist/index.js +6 -0
  62. package/dist/matrix-spec.d.ts +145 -0
  63. package/dist/matrix-spec.js +120 -0
  64. package/dist/obstacles.d.ts +33 -0
  65. package/dist/obstacles.js +72 -0
  66. package/dist/page-hide.d.ts +10 -0
  67. package/dist/page-hide.js +45 -0
  68. package/dist/page-nearby-boxes.d.ts +9 -0
  69. package/dist/page-nearby-boxes.js +92 -0
  70. package/dist/page-settle.d.ts +39 -0
  71. package/dist/page-settle.js +142 -0
  72. package/dist/playwright-driver.d.ts +30 -8
  73. package/dist/playwright-driver.js +88 -18
  74. package/dist/run-flows.d.ts +40 -0
  75. package/dist/run-flows.js +129 -0
  76. package/dist/upload-path.d.ts +15 -0
  77. package/dist/upload-path.js +63 -0
  78. package/dist/verify-compare.d.ts +43 -0
  79. package/dist/verify-compare.js +237 -0
  80. package/dist/verify-determinism.d.ts +16 -0
  81. package/dist/verify-determinism.js +88 -0
  82. package/dist/verify-report.d.ts +53 -0
  83. package/dist/verify-report.js +141 -0
  84. package/dist/verify-tree.d.ts +27 -0
  85. package/dist/verify-tree.js +95 -0
  86. package/dist/viewer-bin.d.ts +6 -0
  87. package/dist/viewer-bin.js +24 -0
  88. package/dist/workspace.d.ts +8 -0
  89. package/package.json +7 -6
@@ -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
+ }
@@ -0,0 +1,53 @@
1
+ import type { ArtefactDifference } from "./verify-compare.js";
2
+ export type VerifyStatus = "identical" | "differing" | "halted";
3
+ /**
4
+ * What a halt message becomes in the report: its first line, with every absolute path (POSIX,
5
+ * Windows drive, UNC, `file://`) replaced by `<path>`. A path under `/tmp`, `/Users`, `/home` or one
6
+ * of `roots` (the workspace root, the home and temp directories of the machine) is scrubbed to the
7
+ * end of its token run first. A run on one machine and a run on another then print the same
8
+ * report, and a CI log does not carry a home directory.
9
+ */
10
+ export declare function scrubHaltMessage(message: string, roots?: readonly string[]): string;
11
+ /** A flow that did not finish in one of the runs. */
12
+ export interface VerifyHalt {
13
+ run: number;
14
+ flow: string;
15
+ /** The step the runtime halted on; null when the flow never started (browser launch failure). */
16
+ step: string | null;
17
+ message: string;
18
+ }
19
+ export interface VerifyReport {
20
+ schema: "docsxai/verify-determinism@1";
21
+ runs: number;
22
+ /** Names of the flows that ran, sorted. */
23
+ flows: string[];
24
+ /**
25
+ * `identical`: every run wrote the same bytes and finished. `differing`: at least one artefact
26
+ * differs between runs. `halted`: a flow halted in some run, so there is nothing to verify as a doc pack.
27
+ */
28
+ status: VerifyStatus;
29
+ /** Artefacts in run 1. */
30
+ artefacts_compared: number;
31
+ /** The first differing artefact by path, run order breaking ties. */
32
+ first: ArtefactDifference | null;
33
+ /** Every differing artefact, ordered by path then run. */
34
+ differences: ArtefactDifference[];
35
+ halts: VerifyHalt[];
36
+ /** True when run 1's output replaced the workspace output (only when status is `identical`). */
37
+ promoted: boolean;
38
+ }
39
+ /** Exit code for a finished verification: 0 identical, 1 differing or halted. Usage errors (2) never reach a report. */
40
+ export declare function verifyExitCode(report: VerifyReport): 0 | 1;
41
+ export declare function buildVerifyReport(input: {
42
+ runs: number;
43
+ flows: string[];
44
+ artefactsCompared: number;
45
+ differences: ArtefactDifference[];
46
+ halts: VerifyHalt[];
47
+ promoted: boolean;
48
+ /** Directories whose paths are scrubbed from halt messages: the workspace root, home, temp. */
49
+ scrubRoots?: readonly string[];
50
+ }): VerifyReport;
51
+ export declare function formatVerifyReportText(r: VerifyReport): string;
52
+ export declare function formatVerifyReportMarkdown(r: VerifyReport): string;
53
+ export declare function formatVerifyReportJson(r: VerifyReport): string;
@@ -0,0 +1,141 @@
1
+ // The `run --verify-determinism` report: the shape, its three renderings (json, md, text) and the
2
+ // exit code it maps to. No timestamps, no absolute paths, no durations: the same runs always
3
+ // render the same bytes, so the report can be diffed, cached and attached to a pipeline. Halt
4
+ // messages are cut to their first line and scrubbed of absolute paths (`scrubHaltMessage`); every
5
+ // other path in the report is relative to a run root.
6
+ // Each pattern finds one kind of absolute path. A POSIX path needs two segments and must not follow a
7
+ // word character, `:`, `/` or `.`, so URLs (`http://host/a/b`), `a/b` and a lone `/done` stay.
8
+ const ABSOLUTE_PATH_PATTERNS = [
9
+ /file:\/\/[^\s"'`<>()[\]{}]*/g,
10
+ /(?<![\w:/.~-])(?:\/[^\s"'`<>()[\]{}/]+){2,}/g,
11
+ /(?<!\w)[A-Za-z]:[\\/][^\s"'`<>()[\]{}]*/g,
12
+ /\\\\[^\s\\"'`<>]+\\[^\s"'`<>()[\]{}]*/g,
13
+ ];
14
+ // Roots that identify a machine or a user. A path under one is scrubbed whole, even a single
15
+ // segment (`/tmp`) and even one with a space in a directory name.
16
+ const FIXED_ROOTS = ["/tmp", "/var/tmp", "/private/tmp", "/Users", "/home"];
17
+ const PATH_CHAR = "[^\\s\"'`<>()[\\]{}]";
18
+ const TRAIL_PUNCTUATION = /[.,;:!?]+$/;
19
+ function escapeRegExp(text) {
20
+ return text.replace(/[.*+?^${}()|[\]\\/]/g, "\\$&");
21
+ }
22
+ /**
23
+ * One pattern for a path under any of `roots`. Inside quotes or brackets the run goes to the
24
+ * closing delimiter, spaces included. Outside them it goes to the next space, and across a space
25
+ * when the next word holds a separator (`/Users/me/My Projects/app`) or starts with a capital or
26
+ * digit and does not follow sentence punctuation (`/Users/me/My Projects`, where nothing after the
27
+ * space tells the directory name from prose). A lowercase last word is left.
28
+ */
29
+ function rootedPathPattern(roots) {
30
+ const alt = roots
31
+ .map(escapeRegExp)
32
+ .sort((a, b) => b.length - a.length || (a < b ? -1 : 1))
33
+ .join("|");
34
+ const inside = `(?<=["'\`(\\[<])(?:${alt})(?:[\\\\/][^"'\`<>()\\[\\]{}\\n]*|(?![\\w-]))`;
35
+ const outside = `(?<![\\w:/.~-])(?:${alt})(?:[\\\\/]${PATH_CHAR}*(?: +(?:(?=${PATH_CHAR}*[\\\\/])|(?<![.,;:!?] )(?=[A-Z0-9]))${PATH_CHAR}+)*|(?![\\w-]))`;
36
+ return new RegExp(`${inside}|${outside}`, "g");
37
+ }
38
+ function replacePath(match) {
39
+ return `<path>${TRAIL_PUNCTUATION.exec(match)?.[0] ?? ""}`;
40
+ }
41
+ /**
42
+ * What a halt message becomes in the report: its first line, with every absolute path (POSIX,
43
+ * Windows drive, UNC, `file://`) replaced by `<path>`. A path under `/tmp`, `/Users`, `/home` or one
44
+ * of `roots` (the workspace root, the home and temp directories of the machine) is scrubbed to the
45
+ * end of its token run first. A run on one machine and a run on another then print the same
46
+ * report, and a CI log does not carry a home directory.
47
+ */
48
+ export function scrubHaltMessage(message, roots = []) {
49
+ const known = new Set(FIXED_ROOTS);
50
+ for (const root of roots) {
51
+ const trimmed = root.replace(/[\\/]+$/, "");
52
+ if (trimmed.length > 1)
53
+ known.add(trimmed);
54
+ }
55
+ let line = (message.split("\n")[0] ?? "").replace(rootedPathPattern([...known]), replacePath);
56
+ for (const pattern of ABSOLUTE_PATH_PATTERNS)
57
+ line = line.replace(pattern, replacePath);
58
+ return line;
59
+ }
60
+ /** Exit code for a finished verification: 0 identical, 1 differing or halted. Usage errors (2) never reach a report. */
61
+ export function verifyExitCode(report) {
62
+ return report.status === "identical" ? 0 : 1;
63
+ }
64
+ export function buildVerifyReport(input) {
65
+ const status = input.halts.length > 0 ? "halted" : input.differences.length > 0 ? "differing" : "identical";
66
+ return {
67
+ schema: "docsxai/verify-determinism@1",
68
+ runs: input.runs,
69
+ flows: [...input.flows].sort((a, b) => (a < b ? -1 : a > b ? 1 : 0)),
70
+ status,
71
+ artefacts_compared: input.artefactsCompared,
72
+ first: input.differences[0] ?? null,
73
+ differences: input.differences,
74
+ halts: input.halts.map((h) => ({
75
+ ...h,
76
+ message: scrubHaltMessage(h.message, input.scrubRoots),
77
+ })),
78
+ promoted: input.promoted,
79
+ };
80
+ }
81
+ function headline(r) {
82
+ const n = r.flows.length;
83
+ return `${r.runs} runs of ${n} flow${n === 1 ? "" : "s"} (${r.flows.join(", ")}), ${r.artefacts_compared} artefact${r.artefacts_compared === 1 ? "" : "s"} per run`;
84
+ }
85
+ function outcome(r) {
86
+ if (r.status === "identical") {
87
+ return "All runs wrote identical bytes; run 1's output is now the workspace output";
88
+ }
89
+ return "The workspace output was not touched";
90
+ }
91
+ function plural(n, word) {
92
+ return `${n} ${word}${n === 1 ? "" : "s"}`;
93
+ }
94
+ export function formatVerifyReportText(r) {
95
+ const lines = [`verify-determinism: ${headline(r)}`, `result: ${r.status.toUpperCase()}`];
96
+ if (r.first) {
97
+ lines.push(`first differing artefact: ${r.first.path} (run ${r.first.run} vs run 1)`, ` cause: ${r.first.hint}`);
98
+ const rest = r.differences.filter((d) => d !== r.first);
99
+ if (rest.length > 0)
100
+ lines.push(`also differing (${rest.length}):`);
101
+ for (const d of rest)
102
+ lines.push(` ${d.path} (run ${d.run}): ${d.hint}`);
103
+ }
104
+ if (r.halts.length > 0)
105
+ lines.push(`halted flows (${r.halts.length}):`);
106
+ for (const h of r.halts) {
107
+ lines.push(` run ${h.run}, ${h.flow}${h.step ? `, step ${h.step}` : ""}: ${h.message.split("\n")[0]}`);
108
+ }
109
+ lines.push(outcome(r));
110
+ return lines.join("\n") + "\n";
111
+ }
112
+ export function formatVerifyReportMarkdown(r) {
113
+ const lines = [
114
+ "## docsxai determinism check",
115
+ "",
116
+ `**${r.status.toUpperCase()}**: ${headline(r)}.`,
117
+ "",
118
+ ];
119
+ if (r.first) {
120
+ lines.push(`First differing artefact: \`${r.first.path}\` (run ${r.first.run} vs run 1).`, "", `- Cause: ${r.first.hint}`, "");
121
+ if (r.differences.length > 1) {
122
+ lines.push(`All ${plural(r.differences.length, "difference")}:`, "", "| Artefact | Run | Cause |", "| --- | --- | --- |");
123
+ for (const d of r.differences) {
124
+ lines.push(`| \`${d.path}\` | ${d.run} | ${d.hint.replace(/\|/g, "\\|")} |`);
125
+ }
126
+ lines.push("");
127
+ }
128
+ }
129
+ if (r.halts.length > 0) {
130
+ lines.push(`Halted flows (${r.halts.length}):`, "");
131
+ for (const h of r.halts) {
132
+ lines.push(`- run ${h.run}, \`${h.flow}\`${h.step ? `, step \`${h.step}\`` : ""}: ${h.message.split("\n")[0]}`);
133
+ }
134
+ lines.push("");
135
+ }
136
+ lines.push(`${outcome(r)}.`, "");
137
+ return lines.join("\n");
138
+ }
139
+ export function formatVerifyReportJson(r) {
140
+ return JSON.stringify(r, null, 2) + "\n";
141
+ }
@@ -0,0 +1,27 @@
1
+ /** Ordinal string order: the same on every machine, unlike `localeCompare`. */
2
+ export declare function byOrdinal(a: string, b: string): number;
3
+ export interface TreeListing {
4
+ /** Regular files, root-relative, `/`-separated, sorted ordinally. */
5
+ files: string[];
6
+ /** Directories, root-relative, `/`-separated, sorted ordinally (parents before children). */
7
+ dirs: string[];
8
+ }
9
+ /** List every file and directory under `root`. A symlink counts as a file and is never followed. */
10
+ export declare function listTree(root: string): Promise<TreeListing>;
11
+ /** A run root holds something the verifier will not copy into the workspace. */
12
+ export declare class VerifyTreeError extends Error {
13
+ constructor(message: string);
14
+ }
15
+ /** {@link assertRegularFiles} over everything listed under `root`. */
16
+ export declare function assertRegularTree(root: string): Promise<void>;
17
+ /**
18
+ * Copy every file of `fromRoot` to the same relative path under `toRoot`. Returns the paths copied.
19
+ * Every entry is checked with `lstat` first, so a symlink in the root stops the copy before any file moves.
20
+ */
21
+ export declare function copyTree(fromRoot: string, toRoot: string): Promise<string[]>;
22
+ /**
23
+ * Remove `root` and everything in it by listing it: each file is unlinked, then each directory is
24
+ * removed deepest first, then `root` itself. A directory that is not empty after its listed
25
+ * contents went (something else wrote there) is left in place.
26
+ */
27
+ export declare function removeListedTree(root: string): Promise<void>;
@@ -0,0 +1,95 @@
1
+ // File-tree helpers for `run --verify-determinism`: list the artefacts of a run root, copy a verified
2
+ // root into the workspace, and remove a run root by the exact paths listed. No recursive delete
3
+ // anywhere: every file and directory the verifier created is named and removed one by one, so a
4
+ // path it did not list is never touched.
5
+ import { promises as fs } from "node:fs";
6
+ import * as path from "node:path";
7
+ import { resolveWorkspacePath, resolveWorkspacePathReal } from "./workspace.js";
8
+ /** Ordinal string order: the same on every machine, unlike `localeCompare`. */
9
+ export function byOrdinal(a, b) {
10
+ return a < b ? -1 : a > b ? 1 : 0;
11
+ }
12
+ /** List every file and directory under `root`. A symlink counts as a file and is never followed. */
13
+ export async function listTree(root) {
14
+ const files = [];
15
+ const dirs = [];
16
+ async function walk(rel) {
17
+ const entries = await fs
18
+ .readdir(resolveWorkspacePath(root, ...rel), { withFileTypes: true })
19
+ .catch((e) => {
20
+ if (e.code === "ENOENT" || e.code === "ENOTDIR")
21
+ return [];
22
+ throw e;
23
+ });
24
+ for (const entry of entries) {
25
+ const next = [...rel, entry.name];
26
+ if (entry.isDirectory()) {
27
+ dirs.push(next.join("/"));
28
+ await walk(next);
29
+ }
30
+ else {
31
+ files.push(next.join("/"));
32
+ }
33
+ }
34
+ }
35
+ await walk([]);
36
+ return { files: files.sort(byOrdinal), dirs: dirs.sort(byOrdinal) };
37
+ }
38
+ /** A run root holds something the verifier will not copy into the workspace. */
39
+ export class VerifyTreeError extends Error {
40
+ constructor(message) {
41
+ super(message);
42
+ this.name = "VerifyTreeError";
43
+ }
44
+ }
45
+ /** Throws {@link VerifyTreeError} naming the first listed entry that is not a regular file (a symlink, say). */
46
+ async function assertRegularFiles(root, files) {
47
+ for (const rel of files) {
48
+ const stat = await fs.lstat(resolveWorkspacePath(root, ...rel.split("/")));
49
+ if (!stat.isFile()) {
50
+ throw new VerifyTreeError(`refusing to copy ${rel}: it is ${stat.isSymbolicLink() ? "a symlink" : "not a regular file"}, and a run only writes regular files. Nothing was copied into the workspace.`);
51
+ }
52
+ }
53
+ }
54
+ /** {@link assertRegularFiles} over everything listed under `root`. */
55
+ export async function assertRegularTree(root) {
56
+ await assertRegularFiles(root, (await listTree(root)).files);
57
+ }
58
+ /**
59
+ * Copy every file of `fromRoot` to the same relative path under `toRoot`. Returns the paths copied.
60
+ * Every entry is checked with `lstat` first, so a symlink in the root stops the copy before any file moves.
61
+ */
62
+ export async function copyTree(fromRoot, toRoot) {
63
+ const { files } = await listTree(fromRoot);
64
+ await assertRegularFiles(fromRoot, files);
65
+ for (const rel of files) {
66
+ const segments = rel.split("/");
67
+ const dest = await resolveWorkspacePathReal(toRoot, ...segments);
68
+ await fs.mkdir(path.dirname(dest), { recursive: true });
69
+ await fs.copyFile(resolveWorkspacePath(fromRoot, ...segments), dest);
70
+ }
71
+ return files;
72
+ }
73
+ /**
74
+ * Remove `root` and everything in it by listing it: each file is unlinked, then each directory is
75
+ * removed deepest first, then `root` itself. A directory that is not empty after its listed
76
+ * contents went (something else wrote there) is left in place.
77
+ */
78
+ export async function removeListedTree(root) {
79
+ const { files, dirs } = await listTree(root);
80
+ for (const rel of files) {
81
+ await fs.unlink(resolveWorkspacePath(root, ...rel.split("/"))).catch(ignoreMissing);
82
+ }
83
+ for (const rel of [...dirs].reverse()) {
84
+ await fs.rmdir(resolveWorkspacePath(root, ...rel.split("/"))).catch(ignoreBusy);
85
+ }
86
+ await fs.rmdir(path.resolve(root)).catch(ignoreBusy);
87
+ }
88
+ function ignoreMissing(e) {
89
+ if (e.code !== "ENOENT")
90
+ throw e;
91
+ }
92
+ function ignoreBusy(e) {
93
+ if (e.code !== "ENOENT" && e.code !== "ENOTEMPTY" && e.code !== "EEXIST")
94
+ throw e;
95
+ }
@@ -18,3 +18,9 @@ export interface ResolveViewerBinOptions {
18
18
  export declare function resolveViewerBin(opts?: ResolveViewerBinOptions): Promise<ViewerBinResolution>;
19
19
  /** Failure message for when the resolved command could not be launched (spawn ENOENT). */
20
20
  export declare function formatViewerBinFailure(resolution: ViewerBinResolution): string;
21
+ /**
22
+ * Run the viewer's CLI with `args` and resolve to its exit code. The viewer is its own package/bin;
23
+ * spawning it keeps the engine from depending on it at build time. `label` prefixes the failure
24
+ * line when the bin can't be launched.
25
+ */
26
+ export declare function runViewerBin(label: string, args: string[]): Promise<number>;