@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
package/dist/diagnose.js CHANGED
@@ -1,4 +1,4 @@
1
- // Halt diagnosis — gather the context a calibration agent needs to propose a recalibration diff.
1
+ // Halt diagnosis, gather the context a calibration agent needs to propose a recalibration diff.
2
2
  // Pure data + recommendations; the engine never patches the flow-file itself (that's an explicit
3
3
  // opt-in action by the agent / human, never ambient). The agent reads the report, walks the live
4
4
  // page (typically via browxai), picks a fix, and edits the flow-file. `docsxai run --start-from
@@ -7,6 +7,7 @@ import { promises as fs } from "node:fs";
7
7
  import * as path from "node:path";
8
8
  import { hiddenAtEachStep } from "./flow-hidden.js";
9
9
  import { locatorRefName } from "./flow-file.js";
10
+ import { toPosix } from "./posix-path.js";
10
11
  import { variantDocDir } from "./flow-matrix.js";
11
12
  import { resolveWorkspacePath } from "./workspace.js";
12
13
  /** Map an `ActionableState` to concrete recommendations for the agent. */
@@ -24,7 +25,7 @@ export function recommendFromActionable(state) {
24
25
  return [
25
26
  {
26
27
  kind: "selector",
27
- rationale: "Selector matches 0 elements on the live page — the element was renamed, moved, or removed.",
28
+ rationale: "Selector matches 0 elements on the live page, the element was renamed, moved, or removed.",
28
29
  suggestion: "Re-discover the element via the calibration loop (browxai's `find()`, or `docsxai inspect`). Pick a new canonical locator and commit it as the step's `target` (or update the named entry in the flow's `locators:` block). If the element is only sometimes there, declare that instead: `optional: true` with a short `timeout_ms` (e.g. 1500) skips a miss in seconds, not after the full 30 s default.",
29
30
  },
30
31
  ];
@@ -32,8 +33,8 @@ export function recommendFromActionable(state) {
32
33
  return [
33
34
  {
34
35
  kind: "selector",
35
- rationale: "Selector matches multiple DOM nodes — strict-mode violation territory; one of them is likely a hidden duplicate.",
36
- suggestion: "Scope the selector: append `:visible`, use `:nth-match(<sel>, 1)`, or add a stable qualifier (parent class, `:has-text(...)`). Avoid silently picking one — the duplicate signal usually means the locator isn't specific enough.",
36
+ rationale: "Selector matches multiple DOM nodes, strict-mode violation territory; one of them is likely a hidden duplicate.",
37
+ suggestion: "Scope the selector: append `:visible`, use `:nth-match(<sel>, 1)`, or add a stable qualifier (parent class, `:has-text(...)`). Avoid silently picking one, the duplicate signal usually means the locator isn't specific enough.",
37
38
  },
38
39
  ];
39
40
  case "disabled":
@@ -41,14 +42,14 @@ export function recommendFromActionable(state) {
41
42
  {
42
43
  kind: "investigate",
43
44
  rationale: "Selector resolves to a single visible element that is `disabled`.",
44
- suggestion: "Check whether the action is appropriate for the target state — sometimes a UI element is intentionally disabled (clip-driven inputs, gated controls). The doc may need to describe the disabled-state behaviour rather than trying to act on the element. If unexpected, the disabled state itself is a product-side question.",
45
+ suggestion: "Check whether the action is appropriate for the target state, sometimes a UI element is intentionally disabled (clip-driven inputs, gated controls). The doc may need to describe the disabled-state behaviour and not try to act on the element. If unexpected, the disabled state itself is a product-side question.",
45
46
  },
46
47
  ];
47
48
  case "detached":
48
49
  return [
49
50
  {
50
51
  kind: "annotation_target",
51
- rationale: "Selector resolved but the element isn't attached to the DOM any more — usually unmounted by the action itself (the step's action transitions the UI, and the original target is gone in the post-action state).",
52
+ rationale: "Selector resolved but the element isn't attached to the DOM any more, usually unmounted by the action itself (the step's action transitions the UI, and the original target is gone in the post-action state).",
52
53
  suggestion: "Set the annotation's `target` to a different element that survives the transition (an element in the resulting state). The action's `target` stays the same; only the annotation anchor moves.",
53
54
  },
54
55
  ];
@@ -57,7 +58,7 @@ export function recommendFromActionable(state) {
57
58
  {
58
59
  kind: "wait_for",
59
60
  rationale: "Selector resolves to a single element but it's hidden (`display: none` / `visibility: hidden` / zero-size).",
60
- suggestion: "Add (or strengthen) `wait_for: { selector: <sel>, timeout_ms: <ms> }` to give the element time to become visible. If it's permanently hidden, the locator probably moved — re-discover.",
61
+ suggestion: "Add (or strengthen) `wait_for: { selector: <sel>, timeout_ms: <ms> }` to give the element time to become visible. If it's permanently hidden, the locator probably moved, re-discover.",
61
62
  },
62
63
  ];
63
64
  case "off-screen":
@@ -65,14 +66,14 @@ export function recommendFromActionable(state) {
65
66
  {
66
67
  kind: "split_step",
67
68
  rationale: "Selector resolves to a CSS-visible element but it's outside the viewport, and Playwright's auto-scroll didn't reach it.",
68
- suggestion: "Insert a scroll-into-view step before the action (or pick a parent element that's in the viewport). Off-screen elements inside `overflow: auto` containers are usually fine — this state means the page scroll is the issue, not a scroller.",
69
+ suggestion: "Insert a scroll-into-view step before the action (or pick a parent element that's in the viewport). Off-screen elements inside `overflow: auto` containers are usually fine, this state means the page scroll is the issue, not a scroller.",
69
70
  },
70
71
  ];
71
72
  case "covered":
72
73
  return [
73
74
  {
74
75
  kind: "split_step",
75
- rationale: "Another element receives clicks at this element's center — likely a modal, overlay, or tooltip covering the target.",
76
+ rationale: "Another element receives clicks at this element's center, likely a modal, overlay, or tooltip covering the target.",
76
77
  suggestion: "Insert a step to dismiss the covering element (close button, click outside, ESC key), then act on the original target.",
77
78
  },
78
79
  ];
@@ -84,7 +85,7 @@ export function recommendStatic(step, halt) {
84
85
  if (halt.screenshotRelPath) {
85
86
  recs.push({
86
87
  kind: "investigate",
87
- rationale: `A halt screenshot exists at \`${halt.screenshotRelPath}\` — read it first; on most halts the visual state shows the issue immediately.`,
88
+ rationale: `A halt screenshot exists at \`${halt.screenshotRelPath}\`, read it first; on most halts the visual state shows the issue immediately.`,
88
89
  suggestion: "Open the screenshot; compare the visual state to what the step expects.",
89
90
  });
90
91
  }
@@ -99,7 +100,7 @@ export function recommendStatic(step, halt) {
99
100
  if (success && typeof success === "object" && success !== null && "text_contains" in success) {
100
101
  recs.push({
101
102
  kind: "success",
102
- rationale: "Success criterion uses `text_contains` — fragile against UI copy changes / localisation drift.",
103
+ rationale: "Success criterion uses `text_contains`, fragile against UI copy changes / localisation drift.",
103
104
  suggestion: "Verify the expected text still appears in the post-action state. If the text changed, update it; if the text shifted to a different element, change the success selector. Where stable, a structural criterion (visible/hidden element, url_matches) is more drift-resistant.",
104
105
  });
105
106
  }
@@ -164,7 +165,7 @@ export async function buildDiagnoseReport(opts) {
164
165
  .catch(() => false)
165
166
  : false;
166
167
  const haltRel = haltExists
167
- ? path.relative(opts.workspace, opts.haltScreenshotAbsPath)
168
+ ? toPosix(path.relative(opts.workspace, opts.haltScreenshotAbsPath))
168
169
  : undefined;
169
170
  const live = opts.liveProbe ? await opts.liveProbe() : undefined;
170
171
  const recommendations = [
@@ -217,7 +218,7 @@ export function formatReportText(r) {
217
218
  out += `Halt artifacts:\n screenshot: ${r.halt.screenshotRelPath}\n\n`;
218
219
  }
219
220
  else {
220
- out += `Halt artifacts:\n (no halt screenshot found at the expected path — run hasn't halted on this step recently, or screenshots are disabled)\n\n`;
221
+ out += `Halt artifacts:\n (no halt screenshot found at the expected path, run hasn't halted on this step recently, or screenshots are disabled)\n\n`;
221
222
  }
222
223
  if (r.live) {
223
224
  out += `Live probe (via ${r.live.cdpEndpoint}):\n`;
@@ -1,8 +1,8 @@
1
- // Doc-pack drift detection — the deterministic computation half.
1
+ // Doc-pack drift detection, the deterministic computation half.
2
2
  //
3
3
  // The engine DETECTS drift and reports it; proposing flow-file patches is the host agent's
4
4
  // calibration-time job (`diagnose` feeds that loop). `docsxai baseline` snapshots a doc pack;
5
- // `docsxai diff` compares the live workspace against it and emits this module's DriftReport —
5
+ // `docsxai diff` compares the live workspace against it and emits this module's DriftReport,
6
6
  // per flow: step deltas (id-keyed field changes), annotation moves (bounding-box delta beyond a
7
7
  // pixel tolerance), screenshot pixel diffs (pngjs, exact RGBA compare, ignore-region aware),
8
8
  // prose line-change counts, and locator changes. Reports carry no timestamps: same two doc packs
@@ -63,7 +63,7 @@ export function diffPngBuffers(aPng, bPng, ignoreRegions = []) {
63
63
  return { kind: "pixels", changed_pixel_count: count, pct, region };
64
64
  }
65
65
  // ---------------------------------------------------------------------------
66
- // Prose line diff (LCS — step write-ups are small)
66
+ // Prose line diff (LCS, step write-ups are small)
67
67
  // ---------------------------------------------------------------------------
68
68
  function lineDiffCounts(aText, bText) {
69
69
  const a = aText.split("\n");
@@ -121,11 +121,15 @@ async function loadAnnotations(dir, flow) {
121
121
  parsed = JSON.parse(raw.toString("utf8"));
122
122
  }
123
123
  catch (e) {
124
- throw new DriftError(`docs/${flow}/annotations.json: not valid JSON — ${e.message}`);
124
+ throw new DriftError(`docs/${flow}/annotations.json: not valid JSON: ${e.message}`);
125
125
  }
126
126
  const result = AnnotationsFile.safeParse(parsed);
127
127
  if (!result.success) {
128
- throw new DriftError(`docs/${flow}/annotations.json: invalid annotations file`);
128
+ const issues = result.error.issues
129
+ .slice(0, 3)
130
+ .map((i) => `${i.path.join(".") || "(root)"}: ${i.message}`);
131
+ const more = result.error.issues.length - issues.length;
132
+ throw new DriftError(`docs/${flow}/annotations.json: invalid annotations file (${issues.join("; ")}${more > 0 ? `; and ${more} more` : ""})`);
129
133
  }
130
134
  return result.data.annotations;
131
135
  }
@@ -222,7 +226,13 @@ async function diffScreenshots(aDir, bDir, flow, policy, ignoreRegions) {
222
226
  const regions = ignoreRegions
223
227
  .filter((r) => r.flow === flow && r.step === step)
224
228
  .map((r) => r.region);
225
- const diff = diffPngBuffers(aPng, bPng, regions);
229
+ let diff;
230
+ try {
231
+ diff = diffPngBuffers(aPng, bPng, regions);
232
+ }
233
+ catch (e) {
234
+ throw new DriftError(`docs/${flow}/screenshots/${name}: not a readable PNG (${e.message})`);
235
+ }
226
236
  if (diff.kind === "dimension-change") {
227
237
  out.push({
228
238
  step,
@@ -234,9 +244,13 @@ async function diffScreenshots(aDir, bDir, flow, policy, ignoreRegions) {
234
244
  }
235
245
  if (diff.changed_pixel_count === 0)
236
246
  continue;
237
- const severity = diff.pct >= policy.screenshot_pct_fail
247
+ // `pct` is rounded to 4 decimals for the report; the thresholds compare the exact ratio, so
248
+ // 0.99996% does not count as 1%. Width and height are the first two IHDR fields, 16 bytes in.
249
+ const area = aPng.readUInt32BE(16) * aPng.readUInt32BE(20);
250
+ const reaches = (threshold) => diff.changed_pixel_count * 100 >= threshold * area;
251
+ const severity = reaches(policy.screenshot_pct_fail)
238
252
  ? "fail"
239
- : diff.pct >= policy.screenshot_pct_warn
253
+ : reaches(policy.screenshot_pct_warn)
240
254
  ? "warn"
241
255
  : "info";
242
256
  out.push({
@@ -1,8 +1,8 @@
1
- // Doc-pack drift detection — severity ranking and the report formatters.
1
+ // Doc-pack drift detection, severity ranking and the report formatters.
2
2
  //
3
3
  // These render the deterministic DriftReport produced by `diffDocPacks` into the surfaces the host
4
4
  // surfaces it on: markdown for PR comments, plain text for the CLI. Like the report itself, the
5
- // formatters carry no timestamps — same report → byte-identical output — so the renderings stay
5
+ // formatters carry no timestamps, same report → byte-identical output, so the renderings stay
6
6
  // PR-comment- and CI-gate-safe.
7
7
  import { SEVERITY_RANK, } from "./diff-types.js";
8
8
  /** True when `severity` is at or above `threshold` (the `--fail-on` gate). */
@@ -80,7 +80,7 @@ export function formatDriftReportMarkdown(report) {
80
80
  lines.push("| Flow | Severity | Steps Δ | Annotations | Screenshots Δ | Locators Δ | Prose Δ |", "| --- | --- | --- | --- | --- | --- | --- |");
81
81
  for (const f of report.flows) {
82
82
  if (f.status !== "changed") {
83
- lines.push(`| \`${f.flow}\` | ${MARKER[f.severity]} | flow ${f.status} | — | — | — | — |`);
83
+ lines.push(`| \`${f.flow}\` | ${MARKER[f.severity]} | flow ${f.status} | - | - | - | - |`);
84
84
  continue;
85
85
  }
86
86
  const locatorCount = f.locators_added.length + f.locators_removed.length + f.locators_changed.length;
@@ -1,4 +1,4 @@
1
- // Doc-pack drift report shapes — the result interfaces, severity enum, and the severity-rank
1
+ // Doc-pack drift report shapes, the result interfaces, severity enum, and the severity-rank
2
2
  // leaf both the computation and the formatters lean on.
3
3
  //
4
4
  // Reports carry no timestamps: same two doc packs → byte-identical report, which is what makes
package/dist/diff.js CHANGED
@@ -1,8 +1,8 @@
1
- // Doc-pack drift detection — deterministic diff between two doc-pack directories.
1
+ // Doc-pack drift detection, deterministic diff between two doc-pack directories.
2
2
  //
3
3
  // The engine DETECTS drift and reports it; proposing flow-file patches is the host agent's
4
4
  // calibration-time job (`diagnose` feeds that loop). `docsxai baseline` snapshots a doc pack;
5
- // `docsxai diff` compares the live workspace against it and emits this module's DriftReport —
5
+ // `docsxai diff` compares the live workspace against it and emits this module's DriftReport,
6
6
  // per flow: step deltas (id-keyed field changes), annotation moves (bounding-box delta beyond a
7
7
  // pixel tolerance), screenshot pixel diffs (pngjs, exact RGBA compare, ignore-region aware),
8
8
  // prose line-change counts, and locator changes. Reports carry no timestamps: same two doc packs
@@ -10,7 +10,7 @@
10
10
  //
11
11
  // This module is a barrel: the report shapes live in `diff-types.ts`, the deterministic
12
12
  // computation in `diff-compute.ts`, the severity gate + formatters in `diff-report.ts`. Importers
13
- // keep using `./diff.js` — the public surface is re-exported here verbatim.
13
+ // keep using `./diff.js`, the public surface is re-exported here verbatim.
14
14
  export { DriftError, } from "./diff-types.js";
15
15
  export { diffDocPacks, diffPngBuffers } from "./diff-compute.js";
16
16
  export { formatDriftReportMarkdown, formatDriftReportText, severityAtLeast, } from "./diff-report.js";
@@ -2,14 +2,14 @@
2
2
  // and (for `pull`) deserialise the payloads back into workspace files.
3
3
  //
4
4
  // The backend treats payloads as opaque; the schemas here are the engine's own contract.
5
- // Screenshot bytes travel as content-addressed blobs — the screenshots artifact carries only a
5
+ // Screenshot bytes travel as content-addressed blobs, the screenshots artifact carries only a
6
6
  // sha256 manifest; `uploadScreenshotBlobs` / `fetchScreenshotBlobs` move the bytes.
7
7
  import { createHash } from "node:crypto";
8
8
  import { promises as fs } from "node:fs";
9
- import * as path from "node:path";
9
+ import { writeFilesTransactional } from "./atomic-write.js";
10
10
  import { FlowName } from "./doc-pack.js";
11
11
  import { findCaseCollision, hasTrailingDot, isWindowsDeviceName } from "./flow-name-rules.js";
12
- import { resolveWorkspacePath, resolveWorkspacePathReal } from "./workspace.js";
12
+ import { readFileInside, resolveWorkspacePath, resolveWorkspacePathReal, WorkspacePathEscapeError, } from "./workspace.js";
13
13
  /** Read the workspace's doc pack from disk into the per-artifact payload shape the backend accepts. */
14
14
  export async function readDocPack(workspace) {
15
15
  return {
@@ -20,18 +20,23 @@ export async function readDocPack(workspace) {
20
20
  locators: await readLocators(workspace),
21
21
  };
22
22
  }
23
+ const readInsideText = async (workspace, ...segments) => (await readFileInside(workspace, ...segments))?.toString("utf8") ?? null;
23
24
  async function readFlows(workspace) {
24
25
  const dir = resolveWorkspacePath(workspace, "flows");
25
26
  const entries = await fs.readdir(dir).catch(() => null);
26
27
  if (!entries)
27
28
  return null;
28
- const yamls = entries.filter((e) => e.endsWith(".flow.yaml"));
29
+ const yamls = entries.filter((e) => e.endsWith(".flow.yaml")).sort();
29
30
  if (yamls.length === 0)
30
31
  return null;
31
32
  const files = {};
32
33
  for (const f of yamls) {
33
- files[f] = await fs.readFile(resolveWorkspacePath(workspace, "flows", f), "utf8");
34
+ const text = await readInsideText(workspace, "flows", f);
35
+ if (text !== null)
36
+ files[f] = text;
34
37
  }
38
+ if (Object.keys(files).length === 0)
39
+ return null;
35
40
  return { schema: "docsxai/flows@1", files };
36
41
  }
37
42
  /**
@@ -53,13 +58,12 @@ async function outputDirs(workspace) {
53
58
  if (sub.isDirectory())
54
59
  dirs.push(`${ent.name}/${sub.name}`);
55
60
  }
56
- return dirs;
61
+ return dirs.sort();
57
62
  }
58
63
  async function readAnnotations(workspace) {
59
64
  const files = {};
60
65
  for (const dir of await outputDirs(workspace)) {
61
- const annPath = resolveWorkspacePath(workspace, "docs", dir, "annotations.json");
62
- const text = await fs.readFile(annPath, "utf8").catch(() => null);
66
+ const text = await readInsideText(workspace, "docs", dir, "annotations.json");
63
67
  if (text === null)
64
68
  continue;
65
69
  try {
@@ -80,10 +84,12 @@ async function readScreenshots(workspace) {
80
84
  const shots = await fs.readdir(screenDir).catch(() => null);
81
85
  if (!shots)
82
86
  continue;
83
- for (const f of shots) {
87
+ for (const f of shots.sort()) {
84
88
  if (!/\.(png|jpg|jpeg|webp)$/i.test(f))
85
89
  continue;
86
- const buf = await fs.readFile(resolveWorkspacePath(workspace, "docs", dir, "screenshots", f));
90
+ const buf = await readFileInside(workspace, "docs", dir, "screenshots", f);
91
+ if (buf === null)
92
+ continue;
87
93
  files[`${dir}/screenshots/${f}`] = {
88
94
  sha256: createHash("sha256").update(buf).digest("hex"),
89
95
  bytes: buf.byteLength,
@@ -126,18 +132,24 @@ export async function fetchScreenshotBlobs(manifest, blobs) {
126
132
  return out;
127
133
  }
128
134
  async function readStyle(workspace) {
129
- const yamlPath = resolveWorkspacePath(workspace, "docs", "style.yaml");
130
135
  const jsonPath = resolveWorkspacePath(workspace, "docs", "style.json");
131
- const yaml = await fs.readFile(yamlPath, "utf8").catch(() => null);
132
- const jsonText = await fs.readFile(jsonPath, "utf8").catch(() => null);
136
+ const yaml = await readInsideText(workspace, "docs", "style.yaml");
137
+ const jsonText = await readInsideText(workspace, "docs", "style.json");
133
138
  if (yaml === null && jsonText === null)
134
139
  return null;
135
- const json = jsonText ? JSON.parse(jsonText) : null;
140
+ let json = null;
141
+ if (jsonText) {
142
+ try {
143
+ json = JSON.parse(jsonText);
144
+ }
145
+ catch (e) {
146
+ throw new Error(`${jsonPath}: invalid JSON, ${e.message}`, { cause: e });
147
+ }
148
+ }
136
149
  return { schema: "docsxai/style-bundle@1", yaml, json };
137
150
  }
138
151
  async function readLocators(workspace) {
139
- const yamlPath = resolveWorkspacePath(workspace, "docs", "locators.yaml");
140
- const yaml = await fs.readFile(yamlPath, "utf8").catch(() => null);
152
+ const yaml = await readInsideText(workspace, "docs", "locators.yaml");
141
153
  if (yaml === null)
142
154
  return null;
143
155
  return { schema: "docsxai/locators@1", yaml };
@@ -234,24 +246,33 @@ export function assertSafePackNames(payloads) {
234
246
  }
235
247
  }
236
248
  }
249
+ /** `docs/<name>` for a pulled file, refused when a symlink on the way leads outside the workspace. */
250
+ async function docsTargetInside(workspace, name) {
251
+ try {
252
+ return await resolveWorkspacePathReal(workspace, "docs", name);
253
+ }
254
+ catch (e) {
255
+ if (!(e instanceof WorkspacePathEscapeError))
256
+ throw e;
257
+ throw new Error(`refusing to write docs/${name}: a symlink leads it outside the workspace`);
258
+ }
259
+ }
237
260
  export async function writeDocPack(workspace, payloads, extras = {}) {
238
- let n = 0;
239
261
  // Pulled payload file names come from the backend: check every one before the first write, then
240
- // resolve with the symlink-aware variant.
262
+ // resolve with the symlink-aware variant. The files go to disk in one transaction, so a pull that
263
+ // fails partway leaves the workspace as it was.
241
264
  assertSafePackNames(payloads);
265
+ const files = [];
242
266
  if (payloads.flows) {
243
- await fs.mkdir(resolveWorkspacePath(workspace, "flows"), { recursive: true });
244
267
  for (const [f, text] of Object.entries(payloads.flows.files)) {
245
- await fs.writeFile(await resolveWorkspacePathReal(workspace, "flows", f), text, "utf8");
246
- n++;
268
+ const target = await resolveWorkspacePathReal(workspace, "flows", f);
269
+ files.push({ target, data: text, encoding: "utf8" });
247
270
  }
248
271
  }
249
272
  if (payloads.annotations) {
250
273
  for (const [rel, json] of Object.entries(payloads.annotations.files)) {
251
- const abs = await resolveWorkspacePathReal(workspace, "docs", rel);
252
- await fs.mkdir(path.dirname(abs), { recursive: true });
253
- await fs.writeFile(abs, JSON.stringify(json, null, 2) + "\n", "utf8");
254
- n++;
274
+ const target = await resolveWorkspacePathReal(workspace, "docs", rel);
275
+ files.push({ target, data: JSON.stringify(json, null, 2) + "\n", encoding: "utf8" });
255
276
  }
256
277
  }
257
278
  if (payloads.screenshots && extras.screenshotBytes) {
@@ -259,31 +280,25 @@ export async function writeDocPack(workspace, payloads, extras = {}) {
259
280
  const data = extras.screenshotBytes[rel];
260
281
  if (!data)
261
282
  continue;
262
- const abs = await resolveWorkspacePathReal(workspace, "docs", rel);
263
- await fs.mkdir(path.dirname(abs), { recursive: true });
264
- await fs.writeFile(abs, data);
265
- n++;
283
+ files.push({ target: await resolveWorkspacePathReal(workspace, "docs", rel), data });
266
284
  }
267
285
  }
268
- if (payloads.style) {
269
- if (payloads.style.yaml !== null) {
270
- const p = resolveWorkspacePath(workspace, "docs", "style.yaml");
271
- await fs.mkdir(path.dirname(p), { recursive: true });
272
- await fs.writeFile(p, payloads.style.yaml, "utf8");
273
- n++;
274
- }
275
- if (payloads.style.json !== null) {
276
- const p = resolveWorkspacePath(workspace, "docs", "style.json");
277
- await fs.mkdir(path.dirname(p), { recursive: true });
278
- await fs.writeFile(p, JSON.stringify(payloads.style.json, null, 2) + "\n", "utf8");
279
- n++;
280
- }
286
+ if (payloads.style?.yaml != null) {
287
+ const target = await docsTargetInside(workspace, "style.yaml");
288
+ files.push({ target, data: payloads.style.yaml, encoding: "utf8" });
289
+ }
290
+ if (payloads.style?.json != null) {
291
+ const target = await docsTargetInside(workspace, "style.json");
292
+ files.push({
293
+ target,
294
+ data: JSON.stringify(payloads.style.json, null, 2) + "\n",
295
+ encoding: "utf8",
296
+ });
281
297
  }
282
298
  if (payloads.locators?.yaml) {
283
- const p = resolveWorkspacePath(workspace, "docs", "locators.yaml");
284
- await fs.mkdir(path.dirname(p), { recursive: true });
285
- await fs.writeFile(p, payloads.locators.yaml, "utf8");
286
- n++;
299
+ const target = await docsTargetInside(workspace, "locators.yaml");
300
+ files.push({ target, data: payloads.locators.yaml, encoding: "utf8" });
287
301
  }
288
- return { filesWritten: n };
302
+ await writeFilesTransactional(files);
303
+ return { filesWritten: files.length };
289
304
  }