@docsxai/engine 0.3.0-rc.3 → 0.3.0-rc.5

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 (181) hide show
  1. package/README.md +44 -34
  2. package/dist/atomic-write.d.ts +19 -0
  3. package/dist/atomic-write.js +127 -0
  4. package/dist/auth/api-login.d.ts +9 -51
  5. package/dist/auth/api-login.js +3 -3
  6. package/dist/auth/browser-session.js +1 -1
  7. package/dist/auth/cookie-jar.d.ts +4 -4
  8. package/dist/auth/cookie-jar.js +4 -4
  9. package/dist/auth/email-otp.d.ts +11 -147
  10. package/dist/auth/email-otp.js +4 -4
  11. package/dist/auth/http-basic.js +1 -1
  12. package/dist/auth/index.js +3 -3
  13. package/dist/auth/jwt-injection.d.ts +7 -131
  14. package/dist/auth/jwt-injection.js +5 -5
  15. package/dist/auth/manual-capture.d.ts +3 -3
  16. package/dist/auth/manual-capture.js +2 -2
  17. package/dist/auth/mtls.d.ts +1 -6
  18. package/dist/auth/mtls.js +1 -1
  19. package/dist/auth/pat-header.d.ts +1 -9
  20. package/dist/auth/pat-header.js +1 -1
  21. package/dist/auth/storage-state-cache.d.ts +16 -6
  22. package/dist/auth/storage-state-cache.js +65 -15
  23. package/dist/auth/test-backdoor.d.ts +2 -13
  24. package/dist/auth/test-backdoor.js +3 -3
  25. package/dist/auth/totp.d.ts +1 -1
  26. package/dist/auth/totp.js +4 -4
  27. package/dist/auth/types.d.ts +3 -3
  28. package/dist/auth/types.js +4 -4
  29. package/dist/auth/ui-form.d.ts +24 -153
  30. package/dist/auth/ui-form.js +3 -3
  31. package/dist/auth/webauthn.d.ts +7 -67
  32. package/dist/auth/webauthn.js +3 -3
  33. package/dist/auth.js +1 -1
  34. package/dist/backend-client-contracts.d.ts +1 -1
  35. package/dist/backend-client-contracts.js +2 -2
  36. package/dist/backend-client-oauth-login.js +1 -1
  37. package/dist/backend-client-state-cache.d.ts +2 -2
  38. package/dist/backend-client-state-cache.js +8 -8
  39. package/dist/backend-client-token.js +4 -4
  40. package/dist/backend-client-transport.d.ts +2 -2
  41. package/dist/backend-client-transport.js +3 -3
  42. package/dist/backend-client.js +6 -6
  43. package/dist/browser-build.d.ts +6 -0
  44. package/dist/browser-build.js +12 -0
  45. package/dist/browser-launch-error.d.ts +18 -0
  46. package/dist/browser-launch-error.js +63 -0
  47. package/dist/browser-wait.d.ts +7 -0
  48. package/dist/browser-wait.js +12 -0
  49. package/dist/calibrate.d.ts +6 -2
  50. package/dist/calibrate.js +20 -13
  51. package/dist/cli-backend-errors.d.ts +5 -0
  52. package/dist/cli-backend-errors.js +24 -3
  53. package/dist/cli-commands-auth.d.ts +1 -0
  54. package/dist/cli-commands-auth.js +114 -0
  55. package/dist/cli-commands-authoring.d.ts +0 -1
  56. package/dist/cli-commands-authoring.js +124 -101
  57. package/dist/cli-commands-backend.d.ts +1 -1
  58. package/dist/cli-commands-backend.js +76 -21
  59. package/dist/cli-commands-docpack.d.ts +3 -1
  60. package/dist/cli-commands-docpack.js +145 -39
  61. package/dist/cli-commands-init.d.ts +1 -0
  62. package/dist/cli-commands-init.js +100 -0
  63. package/dist/cli-commands-pack.d.ts +1 -1
  64. package/dist/cli-commands-pack.js +6 -4
  65. package/dist/cli-commands-session.d.ts +1 -3
  66. package/dist/cli-commands-session.js +109 -180
  67. package/dist/cli-commands-site.d.ts +2 -0
  68. package/dist/cli-commands-site.js +77 -0
  69. package/dist/cli-commands-style.d.ts +1 -0
  70. package/dist/cli-commands-style.js +85 -0
  71. package/dist/cli-flags.d.ts +18 -0
  72. package/dist/cli-flags.js +77 -0
  73. package/dist/cli-help.d.ts +30 -0
  74. package/dist/cli-help.js +174 -0
  75. package/dist/cli-messages.d.ts +30 -0
  76. package/dist/cli-messages.js +97 -0
  77. package/dist/cli-node-guard.d.ts +1 -0
  78. package/dist/cli-node-guard.js +8 -0
  79. package/dist/cli-retired.js +6 -0
  80. package/dist/cli-run-stale.d.ts +2 -0
  81. package/dist/cli-run-stale.js +13 -0
  82. package/dist/cli-run-summary.js +7 -3
  83. package/dist/cli-shared.d.ts +30 -1
  84. package/dist/cli-shared.js +112 -12
  85. package/dist/cli-unexpected.d.ts +12 -2
  86. package/dist/cli-unexpected.js +50 -4
  87. package/dist/cli-usage.d.ts +1 -1
  88. package/dist/cli-usage.js +115 -66
  89. package/dist/cli-value-flags.d.ts +8 -0
  90. package/dist/cli-value-flags.js +34 -0
  91. package/dist/cli-version.d.ts +6 -0
  92. package/dist/cli-version.js +25 -0
  93. package/dist/cli.d.ts +1 -0
  94. package/dist/cli.js +42 -19
  95. package/dist/deprecation.d.ts +2 -0
  96. package/dist/deprecation.js +2 -0
  97. package/dist/device-scale-factor.d.ts +14 -0
  98. package/dist/device-scale-factor.js +38 -0
  99. package/dist/diagnose.js +14 -13
  100. package/dist/diff-compute.js +22 -8
  101. package/dist/diff-report.js +3 -3
  102. package/dist/diff-types.js +1 -1
  103. package/dist/diff.js +3 -3
  104. package/dist/doc-pack-io.js +62 -47
  105. package/dist/doc-pack.d.ts +567 -3487
  106. package/dist/doc-pack.js +47 -33
  107. package/dist/doctor-checks-config.d.ts +12 -0
  108. package/dist/doctor-checks-config.js +229 -0
  109. package/dist/doctor-checks-plugins.js +2 -2
  110. package/dist/doctor-checks-site.d.ts +3 -0
  111. package/dist/doctor-checks-site.js +21 -0
  112. package/dist/doctor-checks.d.ts +13 -2
  113. package/dist/doctor-checks.js +94 -79
  114. package/dist/doctor-next.d.ts +5 -0
  115. package/dist/doctor-next.js +52 -0
  116. package/dist/doctor.d.ts +36 -2
  117. package/dist/doctor.js +88 -29
  118. package/dist/environment-spec.d.ts +36 -44
  119. package/dist/environment-spec.js +31 -3
  120. package/dist/export/adf.d.ts +1 -1
  121. package/dist/export/adf.js +16 -27
  122. package/dist/export/playwright-test.d.ts +1 -1
  123. package/dist/export/playwright-test.js +13 -15
  124. package/dist/flow-file.d.ts +1 -1
  125. package/dist/flow-file.js +22 -4
  126. package/dist/flow-halt.d.ts +1 -1
  127. package/dist/flow-halt.js +15 -3
  128. package/dist/flow-lint.d.ts +3 -1
  129. package/dist/flow-lint.js +39 -26
  130. package/dist/flow-matrix-lint.js +2 -2
  131. package/dist/flow-runtime.d.ts +17 -6
  132. package/dist/flow-runtime.js +48 -17
  133. package/dist/flow-success.js +4 -4
  134. package/dist/flow-tree.js +2 -2
  135. package/dist/index.d.ts +2 -0
  136. package/dist/index.js +2 -0
  137. package/dist/main-module.d.ts +1 -0
  138. package/dist/main-module.js +17 -0
  139. package/dist/matrix-spec.d.ts +33 -106
  140. package/dist/matrix-spec.js +12 -3
  141. package/dist/node-floor.d.ts +4 -0
  142. package/dist/node-floor.js +14 -0
  143. package/dist/obstacles.js +1 -1
  144. package/dist/open-in-browser.d.ts +22 -0
  145. package/dist/open-in-browser.js +37 -0
  146. package/dist/playwright-driver.d.ts +8 -12
  147. package/dist/playwright-driver.js +75 -70
  148. package/dist/playwright-instrumented-browser.d.ts +10 -7
  149. package/dist/playwright-instrumented-browser.js +35 -12
  150. package/dist/plugins/load.d.ts +1 -1
  151. package/dist/plugins/load.js +4 -4
  152. package/dist/plugins/lock.js +11 -8
  153. package/dist/plugins/manifest.d.ts +16 -35
  154. package/dist/plugins/manifest.js +5 -5
  155. package/dist/plugins/plan.d.ts +3 -3
  156. package/dist/plugins/plan.js +14 -14
  157. package/dist/plugins/registry.d.ts +1 -1
  158. package/dist/plugins/registry.js +1 -1
  159. package/dist/plugins/runtime.js +3 -3
  160. package/dist/plugins/types.d.ts +1 -1
  161. package/dist/plugins-cli.js +36 -28
  162. package/dist/posix-path.d.ts +2 -0
  163. package/dist/posix-path.js +7 -0
  164. package/dist/redact.js +2 -2
  165. package/dist/run-flows.d.ts +7 -0
  166. package/dist/run-flows.js +75 -27
  167. package/dist/style.d.ts +2 -2
  168. package/dist/style.js +13 -11
  169. package/dist/verify-determinism.js +2 -1
  170. package/dist/verify-next-step.d.ts +2 -0
  171. package/dist/verify-next-step.js +24 -0
  172. package/dist/verify-report.js +3 -2
  173. package/dist/viewer-bin.d.ts +9 -3
  174. package/dist/viewer-bin.js +35 -12
  175. package/dist/workspace-templates.d.ts +15 -0
  176. package/dist/workspace-templates.js +88 -0
  177. package/dist/workspace.d.ts +78 -5
  178. package/dist/workspace.js +47 -28
  179. package/dist/zip.d.ts +1 -1
  180. package/dist/zip.js +23 -6
  181. package/package.json +6 -6
@@ -1,15 +1,16 @@
1
- // `docsxai plugins <list|info|sync>` — the operator surface over the plugin runtime.
1
+ // `docsxai plugins <list|info|sync>`: the operator surface over the plugin runtime.
2
2
  //
3
- // list — resolve + load the workspace's plugins; print the full status table.
4
- // info — manifest + registered artifact names for one plugin (by namespace).
5
- // sync — (re)write plugins-lock.json from the resolved manifests. Never executes plugin code.
3
+ // list: resolve + load the workspace's plugins; print the full status table.
4
+ // info: manifest + registered artifact names for one plugin (by namespace).
5
+ // sync: (re)write plugins-lock.json from the resolved manifests. Never executes plugin code.
6
6
  //
7
7
  // All three honour `--format json` for tooling.
8
8
  import { promises as fs } from "node:fs";
9
9
  import { PLUGINS_LOCK_FILE, PLUGINS_LOCK_SCHEMA, PluginsConfigError, PluginsLockError, readPluginsLock, readWorkspacePluginsConfig, sha256Hex, writePluginsLock, } from "./plugins/lock.js";
10
- import { parseFlags } from "./cli-shared.js";
10
+ import { sanitizeForTerminal, usageError } from "./cli-messages.js";
11
+ import { parseCommandFlags } from "./cli-flags.js";
11
12
  import { resolvePlugins, resolvePluginSources } from "./plugins/runtime.js";
12
- const PLUGINS_USAGE = `docsxai plugins — workspace plugin runtime
13
+ const PLUGINS_USAGE = `docsxai plugins: workspace plugin runtime
13
14
 
14
15
  Usage:
15
16
  docsxai plugins list <workspace-dir> [--format text|json]
@@ -23,7 +24,7 @@ Notes:
23
24
  • list resolves and loads the declared set, then prints every plugin's status (loaded, or the
24
25
  disabled/error reason). Exit 1 if any declared plugin is not loaded.
25
26
  • sync pins each plugin's register-module sha256 into ${PLUGINS_LOCK_FILE} next to the config.
26
- When the lock exists, every resolve verifies the bytes before importing — a changed module
27
+ When the lock exists, every resolve verifies the bytes before importing, a changed module
27
28
  fails closed until you re-run sync. sync itself never executes plugin code.
28
29
  `;
29
30
  function parseFormat(flags) {
@@ -97,20 +98,25 @@ async function cmdSync(workspaceDir, format) {
97
98
  const resolutions = await resolvePluginSources(workspaceDir, cfg.sources);
98
99
  const failures = [];
99
100
  const lock = { schema: PLUGINS_LOCK_SCHEMA, plugins: {} };
101
+ const claimed = new Map();
100
102
  for (const r of resolutions) {
101
103
  if (!r.ok) {
102
104
  failures.push({ source: r.record.source, reason: r.record.statusReason ?? "unresolvable" });
103
105
  continue;
104
106
  }
105
107
  const ns = r.candidate.manifest.namespace;
106
- if (lock.plugins[ns]) {
107
- failures.push({
108
- source: r.candidate.source,
109
- reason: `namespace "${ns}" is claimed by more than one configured plugin — cannot lock`,
110
- });
111
- delete lock.plugins[ns];
108
+ const reason = `namespace "${ns}" is claimed by more than one configured plugin, so it cannot be locked`;
109
+ const firstSource = claimed.get(ns);
110
+ if (firstSource !== undefined) {
111
+ // The first claimant was locked before this one showed up: take it back out, once.
112
+ if (lock.plugins[ns]) {
113
+ delete lock.plugins[ns];
114
+ failures.push({ source: firstSource, reason });
115
+ }
116
+ failures.push({ source: r.candidate.source, reason });
112
117
  continue;
113
118
  }
119
+ claimed.set(ns, r.candidate.source);
114
120
  let bytes;
115
121
  try {
116
122
  bytes = await fs.readFile(r.candidate.registerPath);
@@ -139,31 +145,35 @@ async function cmdSync(workspaceDir, format) {
139
145
  process.stdout.write(` ${ns} v${entry.version} ${entry.sha256.slice(0, 12)}… ${entry.source}\n`);
140
146
  }
141
147
  for (const f of failures) {
142
- process.stderr.write(`plugins sync: NOT locked ${f.source} — ${f.reason}\n`);
148
+ process.stderr.write(`plugins sync: NOT locked ${f.source}: ${f.reason}\n`);
143
149
  }
144
150
  }
145
151
  return failures.length > 0 ? 1 : 0;
146
152
  }
147
153
  export async function pluginsCli(args) {
148
154
  const [sub, ...rest] = args;
149
- if (sub === undefined || sub === "--help" || sub === "-h" || sub === "help") {
155
+ if (sub === "--help" || sub === "-h" || sub === "help") {
150
156
  process.stdout.write(PLUGINS_USAGE);
151
- return sub === undefined ? 2 : 0;
157
+ return 0;
152
158
  }
159
+ if (sub === undefined)
160
+ return usageError("plugins", "missing subcommand (list, info or sync)");
153
161
  if (sub !== "list" && sub !== "info" && sub !== "sync") {
154
- process.stderr.write(`plugins: unknown subcommand "${sub}"\n\n${PLUGINS_USAGE}`);
155
- return 2;
162
+ return usageError("plugins", `unknown subcommand "${sanitizeForTerminal(sub)}"`);
156
163
  }
157
- const { positionals, flags } = parseFlags(rest);
164
+ const parsed = parseCommandFlags(`plugins ${sub}`, rest, "plugins");
165
+ if (typeof parsed === "number")
166
+ return parsed;
167
+ const { positionals, flags } = parsed;
158
168
  const workspaceDir = positionals[0];
159
- if (!workspaceDir) {
160
- process.stderr.write(`plugins ${sub}: missing <workspace-dir>\n\n${PLUGINS_USAGE}`);
161
- return 2;
169
+ if (!workspaceDir)
170
+ return usageError(`plugins ${sub}`, "missing <workspace-dir>");
171
+ if (flags.get("format") === true) {
172
+ return usageError(`plugins ${sub}`, '--format needs a value ("text" or "json")');
162
173
  }
163
174
  const format = parseFormat(flags);
164
175
  if (!format) {
165
- process.stderr.write(`plugins ${sub}: --format must be "text" or "json"\n`);
166
- return 2;
176
+ return usageError(`plugins ${sub}`, `--format must be "text" or "json" (got "${sanitizeForTerminal(String(flags.get("format")))}")`);
167
177
  }
168
178
  try {
169
179
  switch (sub) {
@@ -171,10 +181,8 @@ export async function pluginsCli(args) {
171
181
  return await cmdList(workspaceDir, format);
172
182
  case "info": {
173
183
  const namespace = positionals[1];
174
- if (!namespace) {
175
- process.stderr.write(`plugins info: missing <namespace>\n\n${PLUGINS_USAGE}`);
176
- return 2;
177
- }
184
+ if (!namespace)
185
+ return usageError("plugins info", "missing <namespace>");
178
186
  return await cmdInfo(workspaceDir, namespace, format);
179
187
  }
180
188
  case "sync":
@@ -0,0 +1,2 @@
1
+ /** `p` with `sep` (the platform separator by default) replaced by `/`. */
2
+ export declare function toPosix(p: string, sep?: string): string;
@@ -0,0 +1,7 @@
1
+ // Workspace-relative paths in reports, halt hints and jargon hits are written with `/` on every
2
+ // platform; `path.relative` joins with a backslash on Windows.
3
+ import * as path from "node:path";
4
+ /** `p` with `sep` (the platform separator by default) replaced by `/`. */
5
+ export function toPosix(p, sep = path.sep) {
6
+ return sep === "/" ? p : p.split(sep).join("/");
7
+ }
package/dist/redact.js CHANGED
@@ -1,6 +1,6 @@
1
- // Deterministic screenshot redaction — pure pixel transforms over decoded PNGs.
1
+ // Deterministic screenshot redaction, pure pixel transforms over decoded PNGs.
2
2
  //
3
- // Boxes arrive in the screenshot's own pixel space (device pixels — selector bounding boxes are
3
+ // Boxes arrive in the screenshot's own pixel space (device pixels, selector bounding boxes are
4
4
  // already devicePixelRatio-scaled by the driver; fixed regions are scaled the same way at capture
5
5
  // time). Same PNG + same boxes → byte-identical output, which is what keeps redacted doc packs
6
6
  // reproducible run-over-run.
@@ -21,6 +21,11 @@ export interface RunFlowsOptions {
21
21
  /** `annotations.obstacles` from the workspace config. */
22
22
  obstacles: boolean;
23
23
  concurrency: number;
24
+ /**
25
+ * Device pixels per CSS pixel (1 to 4). Absent: the browser default of 1 and an annotations.json
26
+ * with no `device_scale_factor`. Ignored with `cdpEndpoint`.
27
+ */
28
+ deviceScaleFactor?: number | undefined;
24
29
  /** Progress lines (`run: …`). stdout for `run`; stderr in verify mode so stdout stays the report. */
25
30
  progress: (line: string) => void;
26
31
  }
@@ -31,6 +36,8 @@ export interface FlowFailure {
31
36
  flow: string;
32
37
  step: string | null;
33
38
  message: string;
39
+ /** The command that fixes the failure, when the runtime knows it (a browser that would not start). */
40
+ next?: string;
34
41
  }
35
42
  export interface RunFlowsResult {
36
43
  okCount: number;
package/dist/run-flows.js CHANGED
@@ -4,11 +4,16 @@
4
4
  // Split out of the CLI handler so `run --verify-determinism` drives the identical code path against
5
5
  // an isolated output root instead of the workspace.
6
6
  import { promises as fs } from "node:fs";
7
+ import { writeFileAtomic } from "./atomic-write.js";
8
+ import { waitForBrowserClose } from "./browser-wait.js";
9
+ import { browserBuildOf } from "./browser-build.js";
7
10
  import { FlowExecutionError } from "./flow-halt.js";
8
11
  import { expandFlows } from "./flow-matrix.js";
9
12
  import { runFlow } from "./flow-runtime.js";
10
13
  import { launchPlaywrightSession } from "./playwright-driver.js";
11
14
  import { resolveWorkspacePath, resolveWorkspacePathReal } from "./workspace.js";
15
+ import { describeBrowserLaunch } from "./browser-launch-error.js";
16
+ import { fsErrorCode } from "./cli-messages.js";
12
17
  /** `<flow>` for a flow without a matrix, `<flow>/<variant>` for a variant (the name `render` and `burn` use). */
13
18
  export function unitLabel(unit) {
14
19
  return unit.id ? `${unit.flow.name}/${unit.id}` : unit.flow.name;
@@ -18,21 +23,39 @@ function selectUnits(opts) {
18
23
  const units = expandFlows(opts.flows);
19
24
  return opts.variant ? units.filter((u) => u.id === opts.variant) : units;
20
25
  }
21
- /** Merge a `--start-from` partial run into the annotations file already on disk, by step id. */
22
- async function mergeAnnotations(annotationsPath, fresh) {
26
+ /**
27
+ * Merge a `--start-from` partial run into the annotations file already on disk, by step id. An
28
+ * existing file that cannot be read or is not an annotations file is replaced by the fresh
29
+ * annotations alone, and `warn` says so.
30
+ */
31
+ async function mergeAnnotations(annotationsPath, fresh, warn) {
32
+ let existing;
23
33
  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 };
34
+ existing = JSON.parse(await fs.readFile(annotationsPath, "utf8"));
31
35
  }
32
- catch {
33
- // No existing file (or unreadable) — just write what we have.
36
+ catch (e) {
37
+ // No existing file: nothing to merge.
38
+ if (e.code !== "ENOENT") {
39
+ warn(`${annotationsPath} cannot be read (${e.message}), the earlier steps are dropped`);
40
+ }
41
+ return fresh;
42
+ }
43
+ if (!Array.isArray(existing?.annotations)) {
44
+ warn(`${annotationsPath} is not an annotations file, the earlier steps are dropped`);
45
+ return fresh;
46
+ }
47
+ // Boxes are in screenshot pixels: earlier steps captured at another scale would be mislabelled.
48
+ const scaleOf = (f) => f.device_scale_factor ?? 1;
49
+ if (scaleOf(existing) !== scaleOf(fresh)) {
50
+ warn(`${annotationsPath} was captured at device scale ${scaleOf(existing)}, this run at ${scaleOf(fresh)}, the earlier steps are dropped`);
34
51
  return fresh;
35
52
  }
53
+ const newStepIds = new Set(fresh.annotations.map((a) => a.step));
54
+ const merged = [
55
+ ...existing.annotations.filter((a) => !newStepIds.has(a.step)),
56
+ ...fresh.annotations,
57
+ ];
58
+ return { ...fresh, annotations: merged };
36
59
  }
37
60
  /** Execute `opts.flows`, up to `opts.concurrency` at a time, each in its own browser session. */
38
61
  export async function runFlowsInSessions(opts) {
@@ -43,9 +66,11 @@ export async function runFlowsInSessions(opts) {
43
66
  async function runOne(unit) {
44
67
  const { flow } = unit;
45
68
  const name = unitLabel(unit);
69
+ // A flow takes seconds to minutes; this line shows a log reader which one is in flight.
70
+ say(`${tag(name)}${name}, starting\n`);
46
71
  let session;
47
72
  try {
48
- // When attaching to an existing Chrome via --cdp, the operator owns its auth state — don't
73
+ // When attaching to an existing Chrome via --cdp, the operator owns its auth state, don't
49
74
  // load cached `storageState` over it (would replace cookies). When launching fresh, do.
50
75
  session = await launchPlaywrightSession({
51
76
  baseURL: opts.baseURL,
@@ -55,43 +80,57 @@ export async function runFlowsInSessions(opts) {
55
80
  ? { connectOverCdp: opts.cdpEndpoint }
56
81
  : { storageState: opts.storageState }),
57
82
  ...(flow.environment ? { environment: flow.environment } : {}),
83
+ ...(opts.deviceScaleFactor !== undefined
84
+ ? { deviceScaleFactor: opts.deviceScaleFactor }
85
+ : {}),
58
86
  docPackRoot: projectDir,
59
87
  outputRoot,
60
88
  });
61
89
  }
62
90
  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}`;
91
+ const problem = describeBrowserLaunch(e.message, opts.cdpEndpoint);
92
+ const reason = problem.reason;
67
93
  process.stderr.write(`${tag(name)}${reason}\n`);
68
- failures.push({ flow: name, step: null, message: reason });
94
+ failures.push({
95
+ flow: name,
96
+ step: null,
97
+ message: reason,
98
+ ...(problem.next ? { next: problem.next } : {}),
99
+ });
69
100
  return false;
70
101
  }
71
102
  try {
103
+ const browserBuild = browserBuildOf(session);
72
104
  const result = await runFlow(flow, session.driver, {
73
105
  resolveLocator: (n) => flow.locators[n],
74
106
  ...(unit.info ? { variant: unit.info } : {}),
75
107
  ...(stopAfter ? { stopAfter } : {}),
76
108
  ...(startFrom ? { startFrom } : {}),
77
109
  ...(opts.obstacles ? { obstacles: true } : {}),
110
+ ...(opts.deviceScaleFactor !== undefined
111
+ ? { deviceScaleFactor: opts.deviceScaleFactor }
112
+ : {}),
113
+ ...(browserBuild ? { browserBuild } : {}),
78
114
  });
79
115
  const docSegments = ["docs", flow.name, ...(unit.id ? [unit.id] : [])];
80
116
  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.
117
+ // Flow names and variant ids come from the flow-files, resolve the write target symlink-aware.
82
118
  const annotationsPath = await resolveWorkspacePathReal(outputRoot, ...docSegments, "annotations.json");
83
- // With `startFrom`, only the post-startFrom steps emit annotations — merge them into the
119
+ // With `startFrom`, only the post-startFrom steps emit annotations, merge them into the
84
120
  // existing file (if any) by step id so the prior steps' annotations stay in place. Same
85
121
  // story for screenshots (they live as separate PNGs and are simply not re-captured).
86
122
  const toWrite = startFrom
87
- ? await mergeAnnotations(annotationsPath, result.annotations)
123
+ ? await mergeAnnotations(annotationsPath, result.annotations, (m) => say(`${tag(name)}warning: ${m}\n`))
88
124
  : 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`);
125
+ await writeFileAtomic(annotationsPath, JSON.stringify(toWrite, null, 2) + "\n", "utf8");
126
+ say(`${tag(name)}${name}, ${result.steps.length} step(s) executed, ${result.annotations.annotations.length} annotation(s) ${startFrom ? "merged" : "written"}\n`);
91
127
  return true;
92
128
  }
93
129
  catch (e) {
94
- const message = e.message;
130
+ const code = fsErrorCode(e);
131
+ const message = code
132
+ ? `cannot write the outputs under ${outputRoot} (${code}): ${e.message}`
133
+ : e.message;
95
134
  process.stderr.write(`${tag(name)}${message}\n`);
96
135
  failures.push({
97
136
  flow: name,
@@ -101,11 +140,14 @@ export async function runFlowsInSessions(opts) {
101
140
  return false;
102
141
  }
103
142
  finally {
143
+ // Cleanup failures never replace the flow's own result or stop the other workers.
104
144
  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()));
145
+ say("run: --pause, browser is open at the last step run; close it to exit.\n");
146
+ await waitForBrowserClose(session.browser).catch(() => undefined);
107
147
  }
108
- await session.close();
148
+ await session.close().catch((e) => {
149
+ process.stderr.write(`${tag(name)}warning: closing the browser failed: ${e.message}\n`);
150
+ });
109
151
  }
110
152
  }
111
153
  const units = selectUnits(opts);
@@ -114,7 +156,13 @@ export async function runFlowsInSessions(opts) {
114
156
  async function worker() {
115
157
  while (idx < units.length) {
116
158
  const unit = units[idx++];
117
- if (await runOne(unit))
159
+ // A throw that escapes runOne would reject the whole pool and leave the other workers running
160
+ // unobserved, so it counts as this unit's failure instead.
161
+ const ok = await runOne(unit).catch((e) => {
162
+ failures.push({ flow: unitLabel(unit), step: null, message: e.message });
163
+ return false;
164
+ });
165
+ if (ok)
118
166
  okCount++;
119
167
  }
120
168
  }
package/dist/style.d.ts CHANGED
@@ -3,14 +3,14 @@ export declare class StyleError extends Error {
3
3
  readonly cause?: unknown | undefined;
4
4
  constructor(message: string, cause?: unknown | undefined);
5
5
  }
6
- /** The seed style every workspace starts with — overwritable by the agent during calibration. */
6
+ /** The seed style every workspace starts with, overwritable by the agent during calibration. */
7
7
  export declare const DEFAULT_STYLE: StyleArtifact;
8
8
  /**
9
9
  * Regex patterns keyed by the pruning-rule category string. The style artifact's `pruning_rules`
10
10
  * names categories from this catalogue; the lint reports any match.
11
11
  *
12
12
  * Each pattern is multiline-friendly. Add new categories here and reference them by string in
13
- * `style.yaml`'s `pruning_rules:` — the engine reads the array, picks the matching patterns,
13
+ * `style.yaml`'s `pruning_rules:`, the engine reads the array, picks the matching patterns,
14
14
  * and scans `docs/**\/*.md` for leaks.
15
15
  */
16
16
  export declare const JARGON_PATTERNS: Record<string, RegExp>;
package/dist/style.js CHANGED
@@ -1,12 +1,14 @@
1
- // Style artifact — load/write/derive `docs/style.yaml` + derived `docs/style.json`, plus the
1
+ // Style artifact, load/write/derive `docs/style.yaml` + derived `docs/style.json`, plus the
2
2
  // jargon-leak scanner that backs the semantic-reshape exit criterion (testing-jargon absent
3
- // from user-facing step write-ups). The engine never re-shapes prose itself (LLM-agnostic) —
3
+ // from user-facing step write-ups). The engine never re-shapes prose itself (LLM-agnostic),
4
4
  // the agent does that during calibration. This module is the engine's contribution: validate
5
5
  // the schema, persist the artifact, and report when jargon leaks through.
6
6
  import { promises as fs } from "node:fs";
7
7
  import * as path from "node:path";
8
8
  import { parse as parseYaml, stringify as stringifyYaml } from "yaml";
9
+ import { writeFileAtomic } from "./atomic-write.js";
9
10
  import { StyleArtifact } from "./doc-pack.js";
11
+ import { toPosix } from "./posix-path.js";
10
12
  import { resolveWorkspacePath } from "./workspace.js";
11
13
  export class StyleError extends Error {
12
14
  cause;
@@ -16,7 +18,7 @@ export class StyleError extends Error {
16
18
  this.name = "StyleError";
17
19
  }
18
20
  }
19
- /** The seed style every workspace starts with — overwritable by the agent during calibration. */
21
+ /** The seed style every workspace starts with, overwritable by the agent during calibration. */
20
22
  export const DEFAULT_STYLE = {
21
23
  schema: "docsxai/style@1",
22
24
  voice: {
@@ -37,7 +39,7 @@ export const DEFAULT_STYLE = {
37
39
  * names categories from this catalogue; the lint reports any match.
38
40
  *
39
41
  * Each pattern is multiline-friendly. Add new categories here and reference them by string in
40
- * `style.yaml`'s `pruning_rules:` — the engine reads the array, picks the matching patterns,
42
+ * `style.yaml`'s `pruning_rules:`, the engine reads the array, picks the matching patterns,
41
43
  * and scans `docs/**\/*.md` for leaks.
42
44
  */
43
45
  export const JARGON_PATTERNS = {
@@ -68,11 +70,11 @@ export async function loadStyle(workspace) {
68
70
  raw = parseYaml(text);
69
71
  }
70
72
  catch (e) {
71
- throw new StyleError(`${yamlPath}: invalid YAML — ${e.message}`, e);
73
+ throw new StyleError(`${yamlPath}: invalid YAML: ${e.message}`, e);
72
74
  }
73
75
  const parsed = StyleArtifact.safeParse(raw);
74
76
  if (!parsed.success) {
75
- throw new StyleError(`${yamlPath}: schema validation failed — ${parsed.error.issues.map((i) => `${i.path.join(".") || "(root)"}: ${i.message}`).join("; ")}`);
77
+ throw new StyleError(`${yamlPath}: schema validation failed: ${parsed.error.issues.map((i) => `${i.path.join(".") || "(root)"}: ${i.message}`).join("; ")}`);
76
78
  }
77
79
  return parsed.data;
78
80
  }
@@ -80,8 +82,8 @@ export async function loadStyle(workspace) {
80
82
  export async function writeStyle(workspace, style) {
81
83
  const paths = stylePathsFor(workspace);
82
84
  await fs.mkdir(path.dirname(paths.yamlPath), { recursive: true });
83
- await fs.writeFile(paths.yamlPath, stringifyYaml(style, { lineWidth: 100 }), "utf8");
84
- await fs.writeFile(paths.jsonPath, JSON.stringify(style, null, 2) + "\n", "utf8");
85
+ await writeFileAtomic(paths.yamlPath, stringifyYaml(style, { lineWidth: 100 }), "utf8");
86
+ await writeFileAtomic(paths.jsonPath, JSON.stringify(style, null, 2) + "\n", "utf8");
85
87
  return paths;
86
88
  }
87
89
  /** Init the style artifact with `DEFAULT_STYLE` if it doesn't already exist. */
@@ -119,7 +121,7 @@ export function scanTextForJargon(text, file, categories) {
119
121
  /** Scan every `<workspace>/docs/<flow>/<step>.md` user-facing write-up for jargon leakage. */
120
122
  export async function scanWorkspaceForJargon(workspace, style) {
121
123
  const docsRoot = resolveWorkspacePath(workspace, "docs");
122
- const flows = await fs.readdir(docsRoot, { withFileTypes: true }).catch(() => []);
124
+ const flows = [...(await fs.readdir(docsRoot, { withFileTypes: true }).catch(() => []))].sort((a, b) => (a.name < b.name ? -1 : a.name > b.name ? 1 : 0));
123
125
  const categories = style.pruning_rules ?? [];
124
126
  if (categories.length === 0)
125
127
  return [];
@@ -129,11 +131,11 @@ export async function scanWorkspaceForJargon(workspace, style) {
129
131
  continue;
130
132
  const flowDir = resolveWorkspacePath(workspace, "docs", ent.name);
131
133
  const files = await fs.readdir(flowDir).catch(() => []);
132
- for (const f of files) {
134
+ for (const f of [...files].sort()) {
133
135
  if (!f.endsWith(".md"))
134
136
  continue;
135
137
  const abs = resolveWorkspacePath(workspace, "docs", ent.name, f);
136
- const rel = path.relative(path.resolve(workspace), abs);
138
+ const rel = toPosix(path.relative(path.resolve(workspace), abs));
137
139
  const text = await fs.readFile(abs, "utf8").catch(() => "");
138
140
  hits.push(...scanTextForJargon(text, rel, categories));
139
141
  }
@@ -8,6 +8,7 @@
8
8
  import { promises as fs } from "node:fs";
9
9
  import * as os from "node:os";
10
10
  import * as path from "node:path";
11
+ import { writeFileAtomic } from "./atomic-write.js";
11
12
  import { runFlowsInSessions } from "./run-flows.js";
12
13
  import { compareRuns } from "./verify-compare.js";
13
14
  import { buildVerifyReport } from "./verify-report.js";
@@ -35,7 +36,7 @@ async function writeHaltContext(root, failure) {
35
36
  step: failure.step,
36
37
  message: failure.message,
37
38
  };
38
- await fs.writeFile(abs, JSON.stringify(body, null, 2) + "\n", "utf8");
39
+ await writeFileAtomic(abs, JSON.stringify(body, null, 2) + "\n", "utf8");
39
40
  }
40
41
  async function cleanUp(projectDir, runs) {
41
42
  for (let k = 1; k <= runs; k++)
@@ -0,0 +1,2 @@
1
+ import type { ArtefactDifference } from "./verify-compare.js";
2
+ export declare function nextStepFor(d: ArtefactDifference): string;
@@ -0,0 +1,24 @@
1
+ // The one-line next step the `run --verify-determinism` report prints under the first difference.
2
+ // The cause line says where two runs part ways; this line says what to pin. Text and markdown
3
+ // renderings only: the JSON report keeps its shape.
4
+ // A JSON key path that names a time, a date, a duration or an id.
5
+ const TIME_OR_ID_PATH = /time|date|(?:^|[._\]])at$|duration|elapsed|(?:^|[._\]])id$|uuid/i;
6
+ export function nextStepFor(d) {
7
+ switch (d.kind) {
8
+ case "missing":
9
+ case "extra":
10
+ return "A file exists in one run only. Look for a step that branches on timing or live data, then pin it.";
11
+ case "png":
12
+ return d.dimension_change
13
+ ? "The image size changed. Pin the viewport and wait for web fonts to load before the step."
14
+ : "Pixels changed in a region. Look for an animation, a caret, a relative date or a clock there, then freeze it with environment.clock or wait_for: settled, or cover it with hide.";
15
+ case "json":
16
+ return d.json_path !== undefined && TIME_OR_ID_PATH.test(d.json_path)
17
+ ? "A time or id value differs. Pin environment.clock in the flow and check that no id comes from random or server state."
18
+ : "A value differs between runs. Look for a locator or label that follows live data and point it at stable text.";
19
+ case "text":
20
+ return "A text artefact differs. Look for dates, counters or generated ids written into it.";
21
+ case "bytes":
22
+ return "Binary content differs with no structure to compare. Look for an embedded timestamp or random seed.";
23
+ }
24
+ }
@@ -3,6 +3,7 @@
3
3
  // render the same bytes, so the report can be diffed, cached and attached to a pipeline. Halt
4
4
  // messages are cut to their first line and scrubbed of absolute paths (`scrubHaltMessage`); every
5
5
  // other path in the report is relative to a run root.
6
+ import { nextStepFor } from "./verify-next-step.js";
6
7
  // Each pattern finds one kind of absolute path. A POSIX path needs two segments and must not follow a
7
8
  // word character, `:`, `/` or `.`, so URLs (`http://host/a/b`), `a/b` and a lone `/done` stay.
8
9
  const ABSOLUTE_PATH_PATTERNS = [
@@ -94,7 +95,7 @@ function plural(n, word) {
94
95
  export function formatVerifyReportText(r) {
95
96
  const lines = [`verify-determinism: ${headline(r)}`, `result: ${r.status.toUpperCase()}`];
96
97
  if (r.first) {
97
- lines.push(`first differing artefact: ${r.first.path} (run ${r.first.run} vs run 1)`, ` cause: ${r.first.hint}`);
98
+ lines.push(`first differing artefact: ${r.first.path} (run ${r.first.run} vs run 1)`, ` cause: ${r.first.hint}`, ` try: ${nextStepFor(r.first)}`);
98
99
  const rest = r.differences.filter((d) => d !== r.first);
99
100
  if (rest.length > 0)
100
101
  lines.push(`also differing (${rest.length}):`);
@@ -117,7 +118,7 @@ export function formatVerifyReportMarkdown(r) {
117
118
  "",
118
119
  ];
119
120
  if (r.first) {
120
- lines.push(`First differing artefact: \`${r.first.path}\` (run ${r.first.run} vs run 1).`, "", `- Cause: ${r.first.hint}`, "");
121
+ lines.push(`First differing artefact: \`${r.first.path}\` (run ${r.first.run} vs run 1).`, "", `- Cause: ${r.first.hint}`, `- Try: ${nextStepFor(r.first)}`, "");
121
122
  if (r.differences.length > 1) {
122
123
  lines.push(`All ${plural(r.differences.length, "difference")}:`, "", "| Artefact | Run | Cause |", "| --- | --- | --- |");
123
124
  for (const d of r.differences) {
@@ -19,8 +19,14 @@ export declare function resolveViewerBin(opts?: ResolveViewerBinOptions): Promis
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
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.
22
+ * Send `signal` to every viewer child that is running. Returns false when none is, so the caller
23
+ * can end the process itself; true means a child got the signal and {@link runViewerBin} resolves
24
+ * once it has exited.
25
+ */
26
+ export declare function forwardSignalToViewer(signal: NodeJS.Signals): boolean;
27
+ /**
28
+ * Run the viewer's CLI with `args` and resolve to its exit code, or 128 plus the signal number
29
+ * when a signal ended it. The viewer is its own package/bin; spawning it keeps the engine from
30
+ * depending on it at build time. `label` prefixes the failure line when the bin can't be launched.
25
31
  */
26
32
  export declare function runViewerBin(label: string, args: string[]): Promise<number>;