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

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (94) hide show
  1. package/README.md +18 -5
  2. package/dist/address-class.d.ts +14 -0
  3. package/dist/address-class.js +151 -0
  4. package/dist/auth/api-login.d.ts +3 -3
  5. package/dist/auth/email-otp.d.ts +60 -60
  6. package/dist/auth/jwt-injection.d.ts +45 -45
  7. package/dist/auth/pat-header.d.ts +2 -2
  8. package/dist/auth/types.d.ts +2 -2
  9. package/dist/auth/ui-form.d.ts +54 -54
  10. package/dist/auth/webauthn.d.ts +22 -22
  11. package/dist/backend-client-contracts.d.ts +4 -2
  12. package/dist/calibrate.d.ts +2 -2
  13. package/dist/calibrate.js +5 -0
  14. package/dist/cli-commands-authoring.js +23 -4
  15. package/dist/cli-commands-backend.js +2 -2
  16. package/dist/cli-commands-docpack.d.ts +5 -0
  17. package/dist/cli-commands-docpack.js +70 -24
  18. package/dist/cli-commands-pack.d.ts +2 -0
  19. package/dist/cli-commands-pack.js +69 -0
  20. package/dist/cli-commands-session.js +92 -89
  21. package/dist/cli-retired.d.ts +6 -0
  22. package/dist/cli-retired.js +12 -0
  23. package/dist/cli-usage.d.ts +1 -1
  24. package/dist/cli-usage.js +52 -4
  25. package/dist/cli-verify.d.ts +14 -0
  26. package/dist/cli-verify.js +54 -0
  27. package/dist/cli.js +14 -1
  28. package/dist/deprecation.d.ts +19 -0
  29. package/dist/deprecation.js +32 -0
  30. package/dist/diagnose.d.ts +25 -0
  31. package/dist/diagnose.js +69 -3
  32. package/dist/diff-compute.js +1 -0
  33. package/dist/doc-pack-io.d.ts +14 -0
  34. package/dist/doc-pack-io.js +121 -14
  35. package/dist/doc-pack.d.ts +2282 -387
  36. package/dist/doc-pack.js +135 -43
  37. package/dist/doctor-checks.d.ts +1 -1
  38. package/dist/doctor-checks.js +25 -1
  39. package/dist/driver-budget.d.ts +6 -0
  40. package/dist/driver-budget.js +15 -0
  41. package/dist/egress-guard.d.ts +58 -0
  42. package/dist/egress-guard.js +136 -0
  43. package/dist/environment-spec.d.ts +67 -0
  44. package/dist/environment-spec.js +38 -0
  45. package/dist/export/playwright-test.js +42 -10
  46. package/dist/flow-file.d.ts +9 -3
  47. package/dist/flow-file.js +21 -1
  48. package/dist/flow-halt.d.ts +16 -0
  49. package/dist/flow-halt.js +76 -0
  50. package/dist/flow-hidden.d.ts +9 -0
  51. package/dist/flow-hidden.js +20 -0
  52. package/dist/flow-lint.js +91 -1
  53. package/dist/flow-matrix-lint.d.ts +10 -0
  54. package/dist/flow-matrix-lint.js +40 -0
  55. package/dist/flow-matrix.d.ts +44 -0
  56. package/dist/flow-matrix.js +238 -0
  57. package/dist/flow-name-rules.d.ts +15 -0
  58. package/dist/flow-name-rules.js +39 -0
  59. package/dist/flow-runtime.d.ts +52 -22
  60. package/dist/flow-runtime.js +63 -117
  61. package/dist/flow-success.d.ts +3 -0
  62. package/dist/flow-success.js +37 -0
  63. package/dist/flow-tree.d.ts +2 -0
  64. package/dist/flow-tree.js +17 -5
  65. package/dist/flow-wait.d.ts +3 -0
  66. package/dist/flow-wait.js +22 -0
  67. package/dist/index.d.ts +5 -0
  68. package/dist/index.js +5 -0
  69. package/dist/matrix-spec.d.ts +145 -0
  70. package/dist/matrix-spec.js +120 -0
  71. package/dist/page-hide.d.ts +10 -0
  72. package/dist/page-hide.js +45 -0
  73. package/dist/page-settle.d.ts +39 -0
  74. package/dist/page-settle.js +142 -0
  75. package/dist/playwright-driver.d.ts +28 -8
  76. package/dist/playwright-driver.js +73 -28
  77. package/dist/plugins/manifest.d.ts +9 -9
  78. package/dist/run-flows.d.ts +40 -0
  79. package/dist/run-flows.js +129 -0
  80. package/dist/style.d.ts +2 -2
  81. package/dist/upload-path.d.ts +15 -0
  82. package/dist/upload-path.js +63 -0
  83. package/dist/verify-compare.d.ts +43 -0
  84. package/dist/verify-compare.js +237 -0
  85. package/dist/verify-determinism.d.ts +16 -0
  86. package/dist/verify-determinism.js +88 -0
  87. package/dist/verify-report.d.ts +53 -0
  88. package/dist/verify-report.js +141 -0
  89. package/dist/verify-tree.d.ts +27 -0
  90. package/dist/verify-tree.js +95 -0
  91. package/dist/viewer-bin.d.ts +6 -0
  92. package/dist/viewer-bin.js +24 -0
  93. package/dist/zip.d.ts +2 -2
  94. package/package.json +3 -2
@@ -1,4 +1,5 @@
1
1
  import type { BoundingBox, FlowFile, Step } from "./doc-pack.js";
2
+ import { type FlowVariant } from "./flow-matrix.js";
2
3
  import type { ActionableState, BrowserDriver } from "./flow-runtime.js";
3
4
  export type DiagnoseRecommendationKind = "selector" | "wait_for" | "success" | "annotation_target" | "split_step" | "investigate";
4
5
  export interface DiagnoseRecommendation {
@@ -15,6 +16,10 @@ export interface DiagnoseLiveProbe {
15
16
  export interface DiagnoseReport {
16
17
  workspace: string;
17
18
  flow: string;
19
+ /** The matrix variant diagnosed. Absent for a flow without a `matrix`. */
20
+ variant?: string;
21
+ /** Every variant id the flow's `matrix` expands to (present with `variant`). */
22
+ variants?: string[];
18
23
  step: {
19
24
  id: string;
20
25
  action: Step["action"];
@@ -36,6 +41,21 @@ export declare function recommendFromActionable(state: ActionableState): Diagnos
36
41
  export declare function recommendStatic(step: Step, halt: {
37
42
  screenshotRelPath?: string;
38
43
  }): DiagnoseRecommendation[];
44
+ /** The step reaches an element an earlier `hide` step hid: a hidden element is never visible, so waits on it run out. */
45
+ export declare function recommendHiddenTarget(flow: FlowFile, step: Step): DiagnoseRecommendation[];
46
+ /** Pick the matrix variant to diagnose: the requested one, else the only one with a halt shot for the step. */
47
+ export declare function pickDiagnoseVariant(opts: {
48
+ workspace: string;
49
+ flow: string;
50
+ stepId: string;
51
+ variants: FlowVariant[];
52
+ requested: string | undefined;
53
+ }): Promise<{
54
+ variant: FlowVariant;
55
+ ids: string[];
56
+ } | {
57
+ error: string;
58
+ }>;
39
59
  /** Build the full report. `liveProbe` is invoked lazily (only if a driver is supplied). */
40
60
  export declare function buildDiagnoseReport(opts: {
41
61
  workspace: string;
@@ -44,6 +64,11 @@ export declare function buildDiagnoseReport(opts: {
44
64
  resolvedSelector?: string;
45
65
  haltScreenshotAbsPath?: string;
46
66
  liveProbe?: () => Promise<DiagnoseLiveProbe>;
67
+ /** The matrix variant `flow` was expanded for, and every variant of the matrix. */
68
+ variant?: {
69
+ id: string;
70
+ all: string[];
71
+ };
47
72
  }): Promise<DiagnoseReport>;
48
73
  /** Live-probe helper that uses any driver implementing the runtime's `BrowserDriver` interface. */
49
74
  export declare function probeLive(driver: BrowserDriver, selector: string, cdpEndpoint: string): Promise<DiagnoseLiveProbe>;
package/dist/diagnose.js CHANGED
@@ -5,6 +5,10 @@
5
5
  // <step-id> --cdp <endpoint>` then validates the edit in seconds.
6
6
  import { promises as fs } from "node:fs";
7
7
  import * as path from "node:path";
8
+ import { hiddenAtEachStep } from "./flow-hidden.js";
9
+ import { locatorRefName } from "./flow-file.js";
10
+ import { variantDocDir } from "./flow-matrix.js";
11
+ import { resolveWorkspacePath } from "./workspace.js";
8
12
  /** Map an `ActionableState` to concrete recommendations for the agent. */
9
13
  export function recommendFromActionable(state) {
10
14
  switch (state) {
@@ -13,7 +17,7 @@ export function recommendFromActionable(state) {
13
17
  {
14
18
  kind: "investigate",
15
19
  rationale: "The current target is actionable on the live page right now.",
16
- suggestion: "Drift may be intermittent (race condition) or in the `success` criterion. Consider adding `wait_for: network_idle` or `element_stable`; re-check the `success` clause against the live target state.",
20
+ suggestion: "Drift may be intermittent (race condition) or in the `success` criterion. Consider adding `wait_for: network_idle`, `settled` (fonts, images and layout) or `element_stable`; re-check the `success` clause against the live target state.",
17
21
  },
18
22
  ];
19
23
  case "not-found":
@@ -21,7 +25,7 @@ export function recommendFromActionable(state) {
21
25
  {
22
26
  kind: "selector",
23
27
  rationale: "Selector matches 0 elements on the live page — the element was renamed, moved, or removed.",
24
- 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).",
28
+ 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.",
25
29
  },
26
30
  ];
27
31
  case "multiple-matches":
@@ -84,6 +88,13 @@ export function recommendStatic(step, halt) {
84
88
  suggestion: "Open the screenshot; compare the visual state to what the step expects.",
85
89
  });
86
90
  }
91
+ if (step.action === "hide") {
92
+ recs.push({
93
+ kind: "selector",
94
+ rationale: "A `hide` step waits for its target to exist (not to be visible); it halts when no element matched within the step's budget.",
95
+ suggestion: "Check the locator against the live page. If the element is conditionally present (a dev-only overlay, a banner), set `optional: true` with a short `timeout_ms` (e.g. 1500) so a miss is skipped quickly.",
96
+ });
97
+ }
87
98
  const success = step.success;
88
99
  if (success && typeof success === "object" && success !== null && "text_contains" in success) {
89
100
  recs.push({
@@ -94,6 +105,56 @@ export function recommendStatic(step, halt) {
94
105
  }
95
106
  return recs;
96
107
  }
108
+ /** The step reaches an element an earlier `hide` step hid: a hidden element is never visible, so waits on it run out. */
109
+ export function recommendHiddenTarget(flow, step) {
110
+ const index = flow.steps.findIndex((s) => s.id === step.id);
111
+ if (index < 0 || !step.target || step.action === "hide" || step.action === "show")
112
+ return [];
113
+ const resolve = (v) => {
114
+ const name = locatorRefName(v);
115
+ return name ? (flow.locators[name] ?? v) : v;
116
+ };
117
+ if (!hiddenAtEachStep(flow, resolve)[index].before.has(resolve(step.target)))
118
+ return [];
119
+ return [
120
+ {
121
+ kind: "split_step",
122
+ rationale: "An earlier `hide` step hides this step's target (`visibility: hidden`), so it is never visible or actionable here.",
123
+ suggestion: "Insert a `show` step with this target (or none, to show everything) before this step, or move the `hide` step after it.",
124
+ },
125
+ ];
126
+ }
127
+ /** Pick the matrix variant to diagnose: the requested one, else the only one with a halt shot for the step. */
128
+ export async function pickDiagnoseVariant(opts) {
129
+ const ids = opts.variants.flatMap((v) => (v.id ? [v.id] : []));
130
+ if (ids.length === 0) {
131
+ return opts.requested
132
+ ? { error: `--variant "${opts.requested}": flow "${opts.flow}" has no matrix` }
133
+ : { variant: opts.variants[0], ids };
134
+ }
135
+ if (opts.requested) {
136
+ const hit = opts.variants.find((v) => v.id === opts.requested);
137
+ return hit
138
+ ? { variant: hit, ids }
139
+ : {
140
+ error: `no variant "${opts.requested}" in flow "${opts.flow}" (variants: ${ids.join(", ")})`,
141
+ };
142
+ }
143
+ const halted = [];
144
+ for (const v of opts.variants) {
145
+ const shot = resolveWorkspacePath(opts.workspace, variantDocDir(opts.flow, v.id), "halts", `${opts.stepId}.png`);
146
+ if (await fs.access(shot).then(() => true, () => false))
147
+ halted.push(v);
148
+ }
149
+ if (halted.length === 1)
150
+ return { variant: halted[0], ids };
151
+ return {
152
+ error: `flow "${opts.flow}" has a matrix: pass --variant <id> (variants: ${ids.join(", ")}; ` +
153
+ (halted.length > 0
154
+ ? `halt screenshots for step "${opts.stepId}" in: ${halted.map((v) => v.id).join(", ")})`
155
+ : `no halt screenshot found for step "${opts.stepId}")`),
156
+ };
157
+ }
97
158
  /** Build the full report. `liveProbe` is invoked lazily (only if a driver is supplied). */
98
159
  export async function buildDiagnoseReport(opts) {
99
160
  const haltExists = opts.haltScreenshotAbsPath
@@ -108,11 +169,13 @@ export async function buildDiagnoseReport(opts) {
108
169
  const live = opts.liveProbe ? await opts.liveProbe() : undefined;
109
170
  const recommendations = [
110
171
  ...recommendStatic(opts.step, { screenshotRelPath: haltRel }),
172
+ ...recommendHiddenTarget(opts.flow, opts.step),
111
173
  ...(live ? recommendFromActionable(live.actionable) : []),
112
174
  ];
113
175
  return {
114
176
  workspace: opts.workspace,
115
177
  flow: opts.flow.name,
178
+ ...(opts.variant ? { variant: opts.variant.id, variants: opts.variant.all } : {}),
116
179
  step: {
117
180
  id: opts.step.id,
118
181
  action: opts.step.action,
@@ -137,7 +200,10 @@ export async function probeLive(driver, selector, cdpEndpoint) {
137
200
  return { cdpEndpoint, url, actionable, bbox };
138
201
  }
139
202
  export function formatReportText(r) {
140
- let out = `diagnose: flow=${r.flow} step=${r.step.id}\n\n`;
203
+ let out = `diagnose: flow=${r.flow}${r.variant ? ` variant=${r.variant}` : ""} step=${r.step.id}\n`;
204
+ if (r.variants)
205
+ out += `variants: ${r.variants.join(", ")}\n`;
206
+ out += "\n";
141
207
  out += `Current step:\n`;
142
208
  out += ` action: ${r.step.action}\n`;
143
209
  if (r.step.target)
@@ -135,6 +135,7 @@ async function loadAnnotations(dir, flow) {
135
135
  const STEP_FIELDS = [
136
136
  "action",
137
137
  "optional",
138
+ "timeout_ms",
138
139
  "target",
139
140
  "value",
140
141
  "wait_for",
@@ -22,6 +22,20 @@ export declare function uploadScreenshotBlobs(workspace: string, manifest: Scree
22
22
  }>;
23
23
  /** Fetch the bytes behind a screenshots manifest, verifying each blob against its sha256. */
24
24
  export declare function fetchScreenshotBlobs(manifest: ScreenshotsPayload, blobs: BlobFetcher): Promise<Record<string, Uint8Array>>;
25
+ /** A pulled payload named a file the workspace would not have produced; nothing was written. */
26
+ export declare class UnsafePackNameError extends Error {
27
+ constructor(message: string);
28
+ }
29
+ /**
30
+ * Throws {@link UnsafePackNameError} on the first file name in `payloads` that is not one a
31
+ * workspace produces: a flow file that is not `<flow name>.flow.yaml`, an annotations file that is
32
+ * not `<flow>[/<variant>]/annotations.json`, a screenshot that is not under a `screenshots/`
33
+ * directory of such a path, a variant segment or screenshot stem that is a Windows device name or
34
+ * ends in a dot, or two flow files, annotation paths, screenshot paths or output directories that
35
+ * differ only by case. The backend is not trusted
36
+ * with names, and a name like `../.docsxai.json` would otherwise land on workspace config.
37
+ */
38
+ export declare function assertSafePackNames(payloads: Partial<DocPackPayloads>): void;
25
39
  export declare function writeDocPack(workspace: string, payloads: Partial<DocPackPayloads>, extras?: {
26
40
  /** Screenshot bytes keyed by manifest path (from {@link fetchScreenshotBlobs}). */
27
41
  screenshotBytes?: Record<string, Uint8Array>;
@@ -7,6 +7,8 @@
7
7
  import { createHash } from "node:crypto";
8
8
  import { promises as fs } from "node:fs";
9
9
  import * as path from "node:path";
10
+ import { FlowName } from "./doc-pack.js";
11
+ import { findCaseCollision, hasTrailingDot, isWindowsDeviceName } from "./flow-name-rules.js";
10
12
  import { resolveWorkspacePath, resolveWorkspacePathReal } from "./workspace.js";
11
13
  /** Read the workspace's doc pack from disk into the per-artifact payload shape the backend accepts. */
12
14
  export async function readDocPack(workspace) {
@@ -32,19 +34,36 @@ async function readFlows(workspace) {
32
34
  }
33
35
  return { schema: "docsxai/flows@1", files };
34
36
  }
35
- async function readAnnotations(workspace) {
37
+ /**
38
+ * Directories under `docs/` that can hold a flow's outputs, relative to it: `<flow>`, then each
39
+ * `<flow>/<variant>` (a flow with a `matrix` writes there). A directory without outputs is harmless.
40
+ */
41
+ async function outputDirs(workspace) {
36
42
  const docsDir = resolveWorkspacePath(workspace, "docs");
37
43
  const flows = await fs.readdir(docsDir, { withFileTypes: true }).catch(() => []);
38
- const files = {};
44
+ const dirs = [];
39
45
  for (const ent of flows) {
40
46
  if (!ent.isDirectory())
41
47
  continue;
42
- const annPath = resolveWorkspacePath(workspace, "docs", ent.name, "annotations.json");
48
+ dirs.push(ent.name);
49
+ const subs = await fs
50
+ .readdir(resolveWorkspacePath(workspace, "docs", ent.name), { withFileTypes: true })
51
+ .catch(() => []);
52
+ for (const sub of subs)
53
+ if (sub.isDirectory())
54
+ dirs.push(`${ent.name}/${sub.name}`);
55
+ }
56
+ return dirs;
57
+ }
58
+ async function readAnnotations(workspace) {
59
+ const files = {};
60
+ for (const dir of await outputDirs(workspace)) {
61
+ const annPath = resolveWorkspacePath(workspace, "docs", dir, "annotations.json");
43
62
  const text = await fs.readFile(annPath, "utf8").catch(() => null);
44
63
  if (text === null)
45
64
  continue;
46
65
  try {
47
- files[`${ent.name}/annotations.json`] = JSON.parse(text);
66
+ files[`${dir}/annotations.json`] = JSON.parse(text);
48
67
  }
49
68
  catch {
50
69
  // skip unparseable files (push surfaces them in lint output, not here)
@@ -55,21 +74,17 @@ async function readAnnotations(workspace) {
55
74
  return { schema: "docsxai/annotations-bundle@1", files };
56
75
  }
57
76
  async function readScreenshots(workspace) {
58
- const docsDir = resolveWorkspacePath(workspace, "docs");
59
- const flows = await fs.readdir(docsDir, { withFileTypes: true }).catch(() => []);
60
77
  const files = {};
61
- for (const ent of flows) {
62
- if (!ent.isDirectory())
63
- continue;
64
- const screenDir = resolveWorkspacePath(workspace, "docs", ent.name, "screenshots");
78
+ for (const dir of await outputDirs(workspace)) {
79
+ const screenDir = resolveWorkspacePath(workspace, "docs", dir, "screenshots");
65
80
  const shots = await fs.readdir(screenDir).catch(() => null);
66
81
  if (!shots)
67
82
  continue;
68
83
  for (const f of shots) {
69
84
  if (!/\.(png|jpg|jpeg|webp)$/i.test(f))
70
85
  continue;
71
- const buf = await fs.readFile(resolveWorkspacePath(workspace, "docs", ent.name, "screenshots", f));
72
- files[`${ent.name}/screenshots/${f}`] = {
86
+ const buf = await fs.readFile(resolveWorkspacePath(workspace, "docs", dir, "screenshots", f));
87
+ files[`${dir}/screenshots/${f}`] = {
73
88
  sha256: createHash("sha256").update(buf).digest("hex"),
74
89
  bytes: buf.byteLength,
75
90
  };
@@ -128,10 +143,102 @@ async function readLocators(workspace) {
128
143
  return { schema: "docsxai/locators@1", yaml };
129
144
  }
130
145
  // --- write back (pull) ------------------------------------------------------
146
+ /** A pulled payload named a file the workspace would not have produced; nothing was written. */
147
+ export class UnsafePackNameError extends Error {
148
+ constructor(message) {
149
+ super(message);
150
+ this.name = "UnsafePackNameError";
151
+ }
152
+ }
153
+ const FLOW_FILE_SUFFIX = ".flow.yaml";
154
+ const SAFE_SEGMENT = /^[A-Za-z0-9][A-Za-z0-9._-]*$/;
155
+ const SCREENSHOT_FILE = /^[A-Za-z0-9][A-Za-z0-9._-]*\.(?:png|jpe?g|webp)$/i;
156
+ const isFlowName = (name) => FlowName.safeParse(name).success;
157
+ /** Names a variant directory cannot take: they are what the flow directory holds already. */
158
+ const RESERVED_SEGMENTS = new Set(["annotations.json", "screenshots"]);
159
+ /**
160
+ * A path segment or file name a workspace can hold on every disk: safe characters, no `..`, no
161
+ * trailing dot and not a Windows device name (`con`, `nul`, `com1`, ..., with or without an extension).
162
+ */
163
+ const isSafeSegment = (seg) => seg.length <= 128 &&
164
+ !RESERVED_SEGMENTS.has(seg.toLowerCase()) &&
165
+ SAFE_SEGMENT.test(seg) &&
166
+ !seg.includes("..") &&
167
+ !hasTrailingDot(seg) &&
168
+ !isWindowsDeviceName(seg);
169
+ /** `<stem>.png|jpg|jpeg|webp` with the stem held to the same rules as a segment. */
170
+ const isScreenshotFile = (file) => SCREENSHOT_FILE.test(file) && isSafeSegment(file) && isSafeSegment(file.replace(/\.[^.]+$/, ""));
171
+ /** `<flow>[/<variant>]`, every segment safe, the flow segment a valid flow name. */
172
+ function isOutputDir(segments) {
173
+ const [flow, ...variants] = segments;
174
+ return (flow !== undefined && isFlowName(flow) && variants.length <= 1 && variants.every(isSafeSegment));
175
+ }
176
+ /** `flows/<name>.flow.yaml`: the file name is `<valid flow name>.flow.yaml`. */
177
+ function isFlowFileName(file) {
178
+ return file.endsWith(FLOW_FILE_SUFFIX) && isFlowName(file.slice(0, -FLOW_FILE_SUFFIX.length));
179
+ }
180
+ /** `docs/<flow>[/<variant>]/annotations.json`, relative to `docs/`. */
181
+ function isAnnotationsPath(rel) {
182
+ const segments = rel.split("/");
183
+ return segments.pop() === "annotations.json" && isOutputDir(segments);
184
+ }
185
+ /** `docs/<flow>[/<variant>]/screenshots/<file>`, relative to `docs/`. */
186
+ function isScreenshotPath(rel) {
187
+ const segments = rel.split("/");
188
+ const file = segments.pop() ?? "";
189
+ return isScreenshotFile(file) && segments.pop() === "screenshots" && isOutputDir(segments);
190
+ }
191
+ function describeName(name) {
192
+ const shown = name.length > 80 ? `${name.slice(0, 80)}...` : name;
193
+ return JSON.stringify(shown);
194
+ }
195
+ /**
196
+ * Throws {@link UnsafePackNameError} on the first file name in `payloads` that is not one a
197
+ * workspace produces: a flow file that is not `<flow name>.flow.yaml`, an annotations file that is
198
+ * not `<flow>[/<variant>]/annotations.json`, a screenshot that is not under a `screenshots/`
199
+ * directory of such a path, a variant segment or screenshot stem that is a Windows device name or
200
+ * ends in a dot, or two flow files, annotation paths, screenshot paths or output directories that
201
+ * differ only by case. The backend is not trusted
202
+ * with names, and a name like `../.docsxai.json` would otherwise land on workspace config.
203
+ */
204
+ export function assertSafePackNames(payloads) {
205
+ const checks = [
206
+ ["flows", Object.keys(payloads.flows?.files ?? {}), isFlowFileName],
207
+ ["annotations", Object.keys(payloads.annotations?.files ?? {}), isAnnotationsPath],
208
+ ["screenshots", Object.keys(payloads.screenshots?.files ?? {}), isScreenshotPath],
209
+ ];
210
+ for (const [artifact, names, ok] of checks) {
211
+ const bad = names.find((n) => !ok(n));
212
+ if (bad !== undefined) {
213
+ throw new UnsafePackNameError(`refusing the pulled doc pack, nothing written: ${artifact} file name ${describeName(bad)} is not a valid ${artifact} path`);
214
+ }
215
+ }
216
+ const annotationNames = Object.keys(payloads.annotations?.files ?? {});
217
+ const screenshotNames = Object.keys(payloads.screenshots?.files ?? {});
218
+ // Directories are compared across annotations and screenshots: `Tour/` and `tour/` are one
219
+ // directory on a case-insensitive disk, whichever artifact names them.
220
+ const outputDirs = [
221
+ ...annotationNames.map((n) => n.split("/").slice(0, -1).join("/")),
222
+ ...screenshotNames.map((n) => n.split("/").slice(0, -2).join("/")),
223
+ ];
224
+ const collisions = [
225
+ ["flows", Object.keys(payloads.flows?.files ?? {})],
226
+ ["annotations", annotationNames],
227
+ ["screenshots", screenshotNames],
228
+ ["output directories", outputDirs],
229
+ ];
230
+ for (const [artifact, names] of collisions) {
231
+ const clash = findCaseCollision(names);
232
+ if (clash) {
233
+ throw new UnsafePackNameError(`refusing the pulled doc pack, nothing written: ${artifact} ${describeName(clash[0])} and ${describeName(clash[1])} differ only by case`);
234
+ }
235
+ }
236
+ }
131
237
  export async function writeDocPack(workspace, payloads, extras = {}) {
132
238
  let n = 0;
133
- // Pulled payload file names come from the backend — treat as untrusted and resolve with the
134
- // symlink-aware variant before writing.
239
+ // Pulled payload file names come from the backend: check every one before the first write, then
240
+ // resolve with the symlink-aware variant.
241
+ assertSafePackNames(payloads);
135
242
  if (payloads.flows) {
136
243
  await fs.mkdir(resolveWorkspacePath(workspace, "flows"), { recursive: true });
137
244
  for (const [f, text] of Object.entries(payloads.flows.files)) {