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

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 (104) 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/backend-client-token.js +2 -1
  13. package/dist/calibrate.d.ts +2 -2
  14. package/dist/calibrate.js +5 -0
  15. package/dist/cli-backend-errors.d.ts +7 -0
  16. package/dist/cli-backend-errors.js +65 -0
  17. package/dist/cli-commands-authoring.js +57 -51
  18. package/dist/cli-commands-backend.js +49 -42
  19. package/dist/cli-commands-docpack.d.ts +5 -0
  20. package/dist/cli-commands-docpack.js +106 -66
  21. package/dist/cli-commands-pack.d.ts +2 -0
  22. package/dist/cli-commands-pack.js +65 -0
  23. package/dist/cli-commands-session.js +120 -125
  24. package/dist/cli-messages.d.ts +17 -0
  25. package/dist/cli-messages.js +80 -0
  26. package/dist/cli-retired.d.ts +6 -0
  27. package/dist/cli-retired.js +12 -0
  28. package/dist/cli-run-summary.d.ts +15 -0
  29. package/dist/cli-run-summary.js +33 -0
  30. package/dist/cli-usage.d.ts +1 -1
  31. package/dist/cli-usage.js +78 -5
  32. package/dist/cli-verify.d.ts +14 -0
  33. package/dist/cli-verify.js +54 -0
  34. package/dist/cli.js +15 -2
  35. package/dist/deprecation.d.ts +19 -0
  36. package/dist/deprecation.js +32 -0
  37. package/dist/diagnose.d.ts +25 -0
  38. package/dist/diagnose.js +69 -3
  39. package/dist/diff-compute.js +1 -0
  40. package/dist/doc-pack-io.d.ts +14 -0
  41. package/dist/doc-pack-io.js +121 -14
  42. package/dist/doc-pack.d.ts +2282 -387
  43. package/dist/doc-pack.js +135 -43
  44. package/dist/doctor-checks-plugins.js +4 -3
  45. package/dist/doctor-checks.d.ts +1 -1
  46. package/dist/doctor-checks.js +31 -6
  47. package/dist/doctor.d.ts +2 -0
  48. package/dist/doctor.js +27 -3
  49. package/dist/driver-budget.d.ts +6 -0
  50. package/dist/driver-budget.js +15 -0
  51. package/dist/egress-guard.d.ts +58 -0
  52. package/dist/egress-guard.js +136 -0
  53. package/dist/environment-spec.d.ts +67 -0
  54. package/dist/environment-spec.js +38 -0
  55. package/dist/export/playwright-test.js +42 -10
  56. package/dist/flow-file.d.ts +9 -3
  57. package/dist/flow-file.js +21 -1
  58. package/dist/flow-halt.d.ts +16 -0
  59. package/dist/flow-halt.js +76 -0
  60. package/dist/flow-hidden.d.ts +9 -0
  61. package/dist/flow-hidden.js +20 -0
  62. package/dist/flow-lint.js +91 -1
  63. package/dist/flow-matrix-lint.d.ts +10 -0
  64. package/dist/flow-matrix-lint.js +40 -0
  65. package/dist/flow-matrix.d.ts +44 -0
  66. package/dist/flow-matrix.js +238 -0
  67. package/dist/flow-name-rules.d.ts +15 -0
  68. package/dist/flow-name-rules.js +39 -0
  69. package/dist/flow-runtime.d.ts +52 -22
  70. package/dist/flow-runtime.js +63 -117
  71. package/dist/flow-success.d.ts +3 -0
  72. package/dist/flow-success.js +37 -0
  73. package/dist/flow-tree.d.ts +2 -0
  74. package/dist/flow-tree.js +17 -5
  75. package/dist/flow-wait.d.ts +3 -0
  76. package/dist/flow-wait.js +22 -0
  77. package/dist/index.d.ts +5 -0
  78. package/dist/index.js +5 -0
  79. package/dist/matrix-spec.d.ts +145 -0
  80. package/dist/matrix-spec.js +120 -0
  81. package/dist/page-hide.d.ts +10 -0
  82. package/dist/page-hide.js +45 -0
  83. package/dist/page-settle.d.ts +39 -0
  84. package/dist/page-settle.js +142 -0
  85. package/dist/playwright-driver.d.ts +28 -8
  86. package/dist/playwright-driver.js +73 -28
  87. package/dist/plugins/manifest.d.ts +9 -9
  88. package/dist/run-flows.d.ts +40 -0
  89. package/dist/run-flows.js +129 -0
  90. package/dist/style.d.ts +2 -2
  91. package/dist/upload-path.d.ts +15 -0
  92. package/dist/upload-path.js +63 -0
  93. package/dist/verify-compare.d.ts +43 -0
  94. package/dist/verify-compare.js +237 -0
  95. package/dist/verify-determinism.d.ts +16 -0
  96. package/dist/verify-determinism.js +88 -0
  97. package/dist/verify-report.d.ts +53 -0
  98. package/dist/verify-report.js +141 -0
  99. package/dist/verify-tree.d.ts +27 -0
  100. package/dist/verify-tree.js +95 -0
  101. package/dist/viewer-bin.d.ts +6 -0
  102. package/dist/viewer-bin.js +24 -0
  103. package/dist/zip.d.ts +2 -2
  104. package/package.json +3 -2
@@ -10,14 +10,18 @@ import { promises as fs } from "node:fs";
10
10
  import * as path from "node:path";
11
11
  import { LocalStorageStateCache, makeStrategy, parseAuthStrategyFile, resolveCredsEnv, resolveStateCache, } from "./auth.js";
12
12
  import { calibrate } from "./calibrate.js";
13
- import { FlowFileError, parseFlowFile, resolveFlowExtends } from "./flow-file.js";
13
+ import { expandFlowVariants, FlowFileError, parseFlowFile, resolveFlowExtends, } from "./flow-file.js";
14
+ import { assertNoCaseCollision } from "./flow-name-rules.js";
14
15
  import { recordRunHistory } from "./backend-client.js";
15
- import { runFlow } from "./flow-runtime.js";
16
- import { launchPlaywrightSession } from "./playwright-driver.js";
16
+ import { runFlowsInSessions } from "./run-flows.js";
17
17
  import { PlaywrightInstrumentedBrowser } from "./playwright-instrumented-browser.js";
18
- import { initWorkspace, loadWorkspaceConfig, resolveWorkspacePath, resolveWorkspacePathReal, } from "./workspace.js";
18
+ import { initWorkspace, loadWorkspaceConfig, resolveWorkspacePath } from "./workspace.js";
19
19
  import { listFlowFiles, parseFlags } from "./cli-shared.js";
20
- import { USAGE } from "./cli-usage.js";
20
+ import { emitVerifyReport, parseVerifyArgs } from "./cli-verify.js";
21
+ import { verifyDeterminism } from "./verify-determinism.js";
22
+ import { VerifyTreeError } from "./verify-tree.js";
23
+ import { shellQuote, usageError, withNext } from "./cli-messages.js";
24
+ import { reportRun } from "./cli-run-summary.js";
21
25
  async function loadAuthStorageState(projectDir) {
22
26
  const descriptorPath = resolveWorkspacePath(projectDir, "auth", "strategy.yaml");
23
27
  let text;
@@ -32,28 +36,28 @@ async function loadAuthStorageState(projectDir) {
32
36
  const cache = await resolveStateCache(descriptor.roles[role], projectDir);
33
37
  const state = await cache.load(role);
34
38
  if (!state) {
35
- throw new Error(`auth/strategy.yaml configures role "${role}" but no valid cached session was found at ${path.join(projectDir, ".auth", role + ".json")}.\n` +
36
- `Capture one first (calibration's auth step, e.g. the manual-capture flow).`);
39
+ throw new Error(withNext(`auth/strategy.yaml configures role "${role}" but there is no valid cached session at ${path.join(projectDir, ".auth", role + ".json")} (missing or expired)`, `docsxai capture-auth ${shellQuote(projectDir)}`));
37
40
  }
38
41
  return state;
39
42
  }
40
43
  export async function cmdRun(args) {
41
44
  const { positionals, flags } = parseFlags(args);
42
- if (!positionals[0]) {
43
- process.stderr.write("run: missing <project-dir>\n\n" + USAGE + "\n");
44
- return 2;
45
- }
45
+ if (!positionals[0])
46
+ return usageError("run", "missing <workspace-dir>");
46
47
  const projectDir = positionals[0];
47
48
  const onlyFlow = typeof flags.get("flow") === "string" ? flags.get("flow") : undefined;
48
49
  const stopAfter = typeof flags.get("stop-after") === "string" ? flags.get("stop-after") : undefined;
49
50
  const startFrom = typeof flags.get("start-from") === "string" ? flags.get("start-from") : undefined;
50
51
  const cdpEndpoint = typeof flags.get("cdp") === "string" ? flags.get("cdp") : undefined;
52
+ const onlyVariant = typeof flags.get("variant") === "string" ? flags.get("variant") : undefined;
51
53
  const pause = flags.get("pause") === true;
52
54
  const headed = flags.get("headed") === true || pause; // --pause implies --headed
53
55
  if (startFrom && !onlyFlow) {
54
- process.stderr.write(`run: --start-from requires --flow <name> (single-flow calibration aid)\n`);
55
- return 2;
56
+ return usageError("run", "--start-from requires --flow <name> (single-flow calibration aid)");
56
57
  }
58
+ const verify = parseVerifyArgs(flags);
59
+ if (typeof verify === "string")
60
+ return usageError("run", verify);
57
61
  const wsCfg = await loadWorkspaceConfig(projectDir);
58
62
  const baseURL = (typeof flags.get("base-url") === "string" ? flags.get("base-url") : undefined) ??
59
63
  wsCfg?.app_url;
@@ -77,29 +81,71 @@ export async function cmdRun(args) {
77
81
  }
78
82
  return parseFlowFile(text, fp);
79
83
  };
84
+ // `flows` goes to the run loop, which expands each matrix flow itself; `units` is the same
85
+ // expansion here, for the checks and messages that need the variant ids before anything launches.
80
86
  const flows = [];
87
+ const units = [];
88
+ const matrixFlows = new Set();
89
+ const knownFlows = [];
90
+ let flowCount = 0;
81
91
  for (const fp of flowPaths) {
82
92
  let flow;
93
+ let variants;
83
94
  try {
84
95
  const parsed = parseFlowFile(await fs.readFile(fp, "utf8"), fp);
85
96
  flow = parsed.extends ? await resolveFlowExtends(parsed, loadFlowFile) : parsed;
97
+ variants = expandFlowVariants(flow, fp);
86
98
  }
87
99
  catch (e) {
88
100
  if (e instanceof FlowFileError) {
89
- process.stderr.write(`run: ${e.message}\n`);
101
+ process.stderr.write(`run: ${withNext(e.message, `docsxai lint ${shellQuote(projectDir)}`)}\n`);
90
102
  return 1;
91
103
  }
92
104
  throw e;
93
105
  }
94
- if (!onlyFlow || flow.name === onlyFlow)
95
- flows.push(flow);
96
- }
97
- if (flows.length === 0) {
106
+ knownFlows.push(flow.name);
107
+ if (onlyFlow && flow.name !== onlyFlow)
108
+ continue;
109
+ flowCount++;
110
+ flows.push(flow);
111
+ if (flow.matrix)
112
+ matrixFlows.add(flow.name);
113
+ units.push(...variants);
114
+ }
115
+ if (flowCount === 0) {
98
116
  process.stderr.write(onlyFlow
99
- ? `run: no flow named "${onlyFlow}"\n`
100
- : `run: no flow-files in ${projectDir}/flows\n`);
117
+ ? `run: no flow named "${onlyFlow}" (flows: ${knownFlows.join(", ") || "none"})\n`
118
+ : `run: ${withNext(`no flow-files in ${projectDir}/flows`, `docsxai calibrate ${shellQuote(projectDir)} --from <flow.yaml>`)}\n`);
119
+ return 1;
120
+ }
121
+ try {
122
+ assertNoCaseCollision(flows.map((f) => f.name), "flow names");
123
+ }
124
+ catch (e) {
125
+ process.stderr.write(`run: ${e.message}\n`);
126
+ return 1;
127
+ }
128
+ if (cdpEndpoint && matrixFlows.size > 0) {
129
+ process.stderr.write(`run: --cdp attaches to a browser that owns its viewport, color scheme and locale, so it cannot run the matrix of ${[...matrixFlows].join(", ")}\n`);
101
130
  return 1;
102
131
  }
132
+ if (onlyVariant) {
133
+ const wanted = units.filter((u) => u.id === onlyVariant);
134
+ if (wanted.length === 0) {
135
+ process.stderr.write(`run: no variant "${onlyVariant}" (variants: ${units
136
+ .map((u) => u.id)
137
+ .filter(Boolean)
138
+ .join(", ") || "none, no flow has a matrix"})\n`);
139
+ return 1;
140
+ }
141
+ units.splice(0, units.length, ...wanted);
142
+ }
143
+ for (const name of matrixFlows) {
144
+ const stale = resolveWorkspacePath(projectDir, "docs", name, "annotations.json");
145
+ if (await fs.access(stale).then(() => true, () => false)) {
146
+ process.stderr.write(`run: warning — docs/${name}/annotations.json is from before ${name} had a matrix; its variants write to docs/${name}/<variant>/, so remove the old docs/${name}/ outputs\n`);
147
+ }
148
+ }
103
149
  let storageState;
104
150
  try {
105
151
  storageState = await loadAuthStorageState(projectDir);
@@ -118,101 +164,56 @@ export async function cmdRun(args) {
118
164
  if (forceSingle && requestedConcurrency > 1) {
119
165
  process.stderr.write(`run: --pause / --stop-after / --start-from / --cdp force --concurrency 1 (ignoring --concurrency ${requestedConcurrency})\n`);
120
166
  }
121
- const tag = concurrency > 1 ? (name) => `run [${name}]: ` : () => "run: ";
122
- async function runOne(flow) {
123
- const name = flow.name;
124
- let session;
125
- try {
126
- // When attaching to an existing Chrome via --cdp, the operator owns its auth state — don't
127
- // load cached `storageState` over it (would replace cookies). When launching fresh, do.
128
- session = await launchPlaywrightSession({
129
- baseURL,
130
- headed,
131
- ignoreHTTPSErrors,
132
- ...(cdpEndpoint ? { connectOverCdp: cdpEndpoint } : { storageState }),
133
- ...(flow.environment ? { environment: flow.environment } : {}),
134
- docPackRoot: projectDir,
135
- });
136
- }
137
- catch (e) {
138
- const msg = e.message;
139
- if (/Executable doesn't exist|browserType\.launch|playwright install/i.test(msg)) {
140
- process.stderr.write(`${tag(name)}no Chromium binary found. Install one: npx playwright-core install chromium (source checkout: pnpm -C packages/engine exec playwright-core install chromium)\n`);
141
- }
142
- else {
143
- process.stderr.write(`${tag(name)}failed to launch browser: ${msg}\n`);
144
- }
145
- return false;
146
- }
167
+ const noun = matrixFlows.size > 0 ? "flow variants" : "flows";
168
+ const runOptions = {
169
+ projectDir,
170
+ flows,
171
+ variant: onlyVariant,
172
+ storageState,
173
+ baseURL,
174
+ headed,
175
+ ignoreHTTPSErrors,
176
+ cdpEndpoint,
177
+ stopAfter,
178
+ startFrom,
179
+ obstacles: wsCfg?.annotations?.obstacles === true,
180
+ concurrency,
181
+ };
182
+ // Verification runs the same loop N times into isolated roots and prints the report on stdout, so
183
+ // its progress lines go to stderr.
184
+ if (verify) {
147
185
  try {
148
- const result = await runFlow(flow, session.driver, {
149
- resolveLocator: (n) => flow.locators[n],
150
- ...(stopAfter ? { stopAfter } : {}),
151
- ...(startFrom ? { startFrom } : {}),
152
- ...(wsCfg?.annotations?.obstacles === true ? { obstacles: true } : {}),
186
+ const report = await verifyDeterminism({
187
+ ...runOptions,
188
+ runs: verify.runs,
189
+ progress: (line) => process.stderr.write(line),
153
190
  });
154
- await fs.mkdir(resolveWorkspacePath(projectDir, "docs", flow.name), { recursive: true });
155
- // Flow names come from the flow-files — resolve the write target symlink-aware.
156
- const annotationsPath = await resolveWorkspacePathReal(projectDir, "docs", flow.name, "annotations.json");
157
- // With `startFrom`, only the post-startFrom steps emit annotations — merge them into the
158
- // existing file (if any) by step id so the prior steps' annotations stay in place. Same
159
- // story for screenshots (they live as separate PNGs and are simply not re-captured).
160
- let toWrite = result.annotations;
161
- if (startFrom) {
162
- try {
163
- const existingText = await fs.readFile(annotationsPath, "utf8");
164
- const existing = JSON.parse(existingText);
165
- const newStepIds = new Set(result.annotations.annotations.map((a) => a.step));
166
- const merged = [
167
- ...existing.annotations.filter((a) => !newStepIds.has(a.step)),
168
- ...result.annotations.annotations,
169
- ];
170
- toWrite = { ...result.annotations, annotations: merged };
171
- }
172
- catch {
173
- // No existing file (or unreadable) — just write what we have.
174
- }
175
- }
176
- await fs.writeFile(annotationsPath, JSON.stringify(toWrite, null, 2) + "\n", "utf8");
177
- process.stdout.write(`${tag(name)}${name} — ${result.steps.length} step(s) executed, ${result.annotations.annotations.length} annotation(s) ${startFrom ? "merged" : "written"}\n`);
178
- return true;
191
+ return emitVerifyReport(report, verify.format);
179
192
  }
180
193
  catch (e) {
181
- process.stderr.write(`${tag(name)}${e.message}\n`);
182
- return false;
183
- }
184
- finally {
185
- if (pause) {
186
- process.stdout.write("run: --pause — browser is open at the last step run; close it to exit.\n");
187
- await new Promise((resolve) => session.browser.on("disconnected", () => resolve()));
194
+ if (e instanceof VerifyTreeError) {
195
+ process.stderr.write(`run: --verify-determinism: ${e.message}\n`);
196
+ return 1;
188
197
  }
189
- await session.close();
198
+ throw e;
190
199
  }
191
200
  }
192
- let idx = 0;
193
- let anyFailed = false;
194
- let okCount = 0;
195
201
  const startedAt = Date.now();
196
- async function worker() {
197
- while (idx < flows.length) {
198
- const flow = flows[idx++];
199
- if (await runOne(flow))
200
- okCount++;
201
- else
202
- anyFailed = true;
203
- }
204
- }
205
- const workers = Math.min(concurrency, flows.length);
206
- if (workers > 1)
207
- process.stdout.write(`run: running ${flows.length} flows with ${workers} parallel worker(s)…\n`);
208
- await Promise.all(Array.from({ length: workers }, () => worker()));
202
+ const { okCount, failures } = await runFlowsInSessions({
203
+ ...runOptions,
204
+ outputRoot: projectDir,
205
+ pause,
206
+ progress: (line) => process.stdout.write(line),
207
+ });
208
+ const anyFailed = failures.length > 0;
209
+ reportRun({ projectDir, noun, total: units.length, okCount, failures });
209
210
  // Backend-bound workspaces get a run record appended; offline-tolerant (warn, never fail the run).
210
211
  const history = await recordRunHistory({
211
212
  workspaceDir: projectDir,
212
213
  config: wsCfg ?? {},
213
214
  ok: !anyFailed,
214
215
  durationMs: Date.now() - startedAt,
215
- summary: `${okCount}/${flows.length} flows ok`,
216
+ summary: `${okCount}/${units.length} ${noun} ok`,
216
217
  });
217
218
  if (history.warning)
218
219
  process.stderr.write(`run: warning — ${history.warning}\n`);
@@ -221,16 +222,13 @@ export async function cmdRun(args) {
221
222
  export async function cmdCaptureAuth(args) {
222
223
  const { positionals, flags } = parseFlags(args);
223
224
  const projectDir = positionals[0];
224
- if (!projectDir) {
225
- process.stderr.write("capture-auth: missing <project-dir>\n\n" + USAGE + "\n");
226
- return 2;
227
- }
225
+ if (!projectDir)
226
+ return usageError("capture-auth", "missing <workspace-dir>");
228
227
  const wsCfg = await loadWorkspaceConfig(projectDir);
229
228
  const baseURL = (typeof flags.get("base-url") === "string" ? flags.get("base-url") : undefined) ??
230
229
  wsCfg?.app_url;
231
230
  if (!baseURL) {
232
- process.stderr.write("capture-auth: --base-url <url> is required (or set app_url in the workspace's .docsxai.json)\n");
233
- return 2;
231
+ return usageError("capture-auth", "--base-url <url> is required (or set app_url in the workspace's .docsxai.json)");
234
232
  }
235
233
  const headless = flags.get("headless") === true;
236
234
  const ignoreHTTPSErrors = flags.get("ignore-https-errors") === true || !!wsCfg?.ignore_https_errors;
@@ -245,7 +243,7 @@ export async function cmdCaptureAuth(args) {
245
243
  descriptorText = await fs.readFile(descriptorPath, "utf8");
246
244
  }
247
245
  catch {
248
- process.stderr.write(`capture-auth: no auth descriptor at ${descriptorPath}\n`);
246
+ process.stderr.write(`capture-auth: ${withNext(`no auth descriptor at ${descriptorPath}`, "write auth/strategy.yaml (`docsxai init <new-dir>` scaffolds an example to copy)")}\n`);
249
247
  return 1;
250
248
  }
251
249
  let role;
@@ -258,7 +256,8 @@ export async function cmdCaptureAuth(args) {
258
256
  : descriptor.default_role;
259
257
  const ra = descriptor.roles[role];
260
258
  if (!ra) {
261
- process.stderr.write(`capture-auth: role "${role}" not in ${descriptorPath}\n`);
259
+ const roles = Object.keys(descriptor.roles).join(", ");
260
+ process.stderr.write(`capture-auth: role "${role}" not in ${descriptorPath} (roles: ${roles}); pass --role <name>\n`);
262
261
  return 1;
263
262
  }
264
263
  roleAuth = ra;
@@ -317,10 +316,8 @@ export async function cmdInit(args) {
317
316
  const { positionals, flags } = parseFlags(args);
318
317
  const persistTmp = flags.get("persist") === "tmp";
319
318
  const dir = positionals[0];
320
- if (!persistTmp && !dir) {
321
- process.stderr.write("init: missing <workspace-dir> (or use --persist tmp)\n\n" + USAGE + "\n");
322
- return 2;
323
- }
319
+ if (!persistTmp && !dir)
320
+ return usageError("init", "missing <workspace-dir> (or use --persist tmp)");
324
321
  const str = (k) => typeof flags.get(k) === "string" ? flags.get(k) : undefined;
325
322
  const auth = str("auth");
326
323
  if (auth !== undefined && auth !== "manual-capture" && auth !== "none") {
@@ -350,33 +347,31 @@ export async function cmdInit(args) {
350
347
  force: flags.get("force") === true,
351
348
  });
352
349
  process.stdout.write(`init: workspace ${r.ephemeral ? "(ephemeral) " : ""}at ${r.dir}\n created: ${r.created.join(", ")}\n`);
353
- process.stdout.write(` next: ${appUrl ? "" : "(set app_url in .docsxai.json, then) "}docsxai capture-auth ${r.dir} → …calibrate… → docsxai run ${r.dir} → docsxai render ${r.dir}\n`);
350
+ process.stdout.write(` next: ${appUrl ? "" : "(set app_url in .docsxai.json, then) "}docsxai capture-auth ${shellQuote(r.dir)} → …calibrate… → docsxai run ${shellQuote(r.dir)} → docsxai render ${shellQuote(r.dir)}\n`);
354
351
  return 0;
355
352
  }
356
353
  catch (e) {
357
- process.stderr.write(`init: ${e.message}\n`);
354
+ process.stderr.write(`init: ${e.message.replace(/^init: /, "")}\n`);
358
355
  return 1;
359
356
  }
360
357
  }
361
358
  export async function cmdCalibrate(args) {
362
359
  const { positionals, flags } = parseFlags(args);
363
360
  const workspaceDir = positionals[0];
364
- if (!workspaceDir) {
365
- process.stderr.write("calibrate: missing <workspace-dir>\n\n" + USAGE + "\n");
366
- return 2;
367
- }
361
+ if (!workspaceDir)
362
+ return usageError("calibrate", "missing <workspace-dir>");
368
363
  const from = typeof flags.get("from") === "string" ? flags.get("from") : undefined;
369
364
  if (!from) {
370
- process.stderr.write("calibrate: --from <flow.md|.yaml> is required (the structured flow-guide)\n");
371
- return 2;
365
+ return usageError("calibrate", "--from <flow.md|.yaml> is required (the structured flow-guide)");
372
366
  }
373
367
  const flowName = typeof flags.get("name") === "string" ? flags.get("name") : undefined;
374
368
  let text;
375
369
  try {
376
370
  text = await fs.readFile(from, "utf8");
377
371
  }
378
- catch {
379
- process.stderr.write(`calibrate: cannot read ${from}\n`);
372
+ catch (e) {
373
+ const code = e.code ?? "unreadable";
374
+ process.stderr.write(`calibrate: cannot read ${from} (${code}); check the path\n`);
380
375
  return 1;
381
376
  }
382
377
  try {
@@ -389,11 +384,11 @@ export async function cmdCalibrate(args) {
389
384
  process.stdout.write(`calibrate: wrote ${r.flowFilePath} (${r.flow.steps.length} steps)\n`);
390
385
  if (r.wroteStyle)
391
386
  process.stdout.write(`calibrate: wrote default ${r.stylePath}\n`);
392
- process.stdout.write(` next: docsxai run ${workspaceDir} (then: docsxai render ${workspaceDir})\n`);
387
+ process.stdout.write(` next: docsxai run ${shellQuote(workspaceDir)} (then: docsxai render ${shellQuote(workspaceDir)})\n`);
393
388
  return 0;
394
389
  }
395
390
  catch (e) {
396
- process.stderr.write(`calibrate: ${e.message}\n`);
391
+ process.stderr.write(`calibrate: ${withNext(e.message, `fix ${shellQuote(from)}, then docsxai calibrate ${shellQuote(workspaceDir)} --from ${shellQuote(from)}`)}\n`);
397
392
  return 1;
398
393
  }
399
394
  }
@@ -0,0 +1,17 @@
1
+ /** The usage lines of the command named by the first word of `label` (`pack --check` gives both `pack` lines). */
2
+ export declare function commandUsage(label: string): string[];
3
+ /** Print `<label>: <message>`, the command's usage line and a pointer to `--help` on stderr. Returns exit code 2. */
4
+ export declare function usageError(label: string, message: string): number;
5
+ /**
6
+ * `text` with every C0 control character, DEL and C1 control character removed, so text that came
7
+ * from a backend or a flow file cannot move the cursor, recolour the terminal or set its title. A
8
+ * newline, carriage return or tab becomes a space, so the text stays on its own line. With
9
+ * `multiline`, newlines and tabs are kept (the carriage return is still dropped).
10
+ */
11
+ export declare function sanitizeForTerminal(text: string, multiline?: boolean): string;
12
+ /** `value` as one shell word: left bare when it is made of safe characters, else single-quoted. */
13
+ export declare function shellQuote(value: string): string;
14
+ /** `message` followed by the indented line naming the command to run next. */
15
+ export declare function withNext(message: string, next: string): string;
16
+ /** `raw` without user:password, query or fragment, for printing a URL the operator typed. */
17
+ export declare function redactUrl(raw: string): string;
@@ -0,0 +1,80 @@
1
+ // Shared wording for CLI errors. A failing command says what failed, why, and the next command to
2
+ // run, in that order, on `<command>: ` lines with an indented `next:` line. Usage errors show the
3
+ // failing command's own usage line instead of the whole help text. Leaf: imports only the help text.
4
+ import { USAGE } from "./cli-usage.js";
5
+ /** The `Usage:` entries of `docsxai --help`, one whitespace-normalised line per entry. */
6
+ function usageEntries() {
7
+ const start = USAGE.indexOf("Usage:\n");
8
+ const end = USAGE.indexOf("\n\nNotes:");
9
+ if (start < 0 || end < 0)
10
+ return [];
11
+ const entries = [];
12
+ for (const line of USAGE.slice(start + "Usage:\n".length, end).split("\n")) {
13
+ if (/^ {2}docsxai /.test(line))
14
+ entries.push(line.trim());
15
+ else if (entries.length > 0)
16
+ entries[entries.length - 1] += ` ${line.trim()}`;
17
+ }
18
+ return entries.map((e) => e.replace(/\s+/g, " "));
19
+ }
20
+ /** The usage lines of the command named by the first word of `label` (`pack --check` gives both `pack` lines). */
21
+ export function commandUsage(label) {
22
+ const name = label.split(" ")[0];
23
+ return usageEntries().filter((e) => e.split(" ")[1] === name);
24
+ }
25
+ /** Print `<label>: <message>`, the command's usage line and a pointer to `--help` on stderr. Returns exit code 2. */
26
+ export function usageError(label, message) {
27
+ const lines = commandUsage(label).map((l, i) => `${i === 0 ? "usage: " : " "}${l}\n`);
28
+ process.stderr.write(`${label}: ${message}\n${lines.join("")}run \`docsxai --help\` for every flag and an example\n`);
29
+ return 2;
30
+ }
31
+ function isControl(code) {
32
+ return code < 0x20 || (code >= 0x7f && code <= 0x9f);
33
+ }
34
+ /**
35
+ * `text` with every C0 control character, DEL and C1 control character removed, so text that came
36
+ * from a backend or a flow file cannot move the cursor, recolour the terminal or set its title. A
37
+ * newline, carriage return or tab becomes a space, so the text stays on its own line. With
38
+ * `multiline`, newlines and tabs are kept (the carriage return is still dropped).
39
+ */
40
+ export function sanitizeForTerminal(text, multiline = false) {
41
+ let out = "";
42
+ for (const ch of text) {
43
+ const code = ch.codePointAt(0);
44
+ if (code === 0x0a || code === 0x09)
45
+ out += multiline ? ch : " ";
46
+ else if (code === 0x0d)
47
+ out += multiline ? "" : " ";
48
+ else if (!isControl(code))
49
+ out += ch;
50
+ }
51
+ return out;
52
+ }
53
+ /** `value` as one shell word: left bare when it is made of safe characters, else single-quoted. */
54
+ export function shellQuote(value) {
55
+ const v = sanitizeForTerminal(value);
56
+ return /^[\w./@:+-]+$/.test(v) ? v : `'${v.replace(/'/g, "'\\''")}'`;
57
+ }
58
+ /** `message` followed by the indented line naming the command to run next. */
59
+ export function withNext(message, next) {
60
+ return `${sanitizeForTerminal(message, true)}\n next: ${sanitizeForTerminal(next)}`;
61
+ }
62
+ /** `raw` without user:password, query or fragment, for printing a URL the operator typed. */
63
+ export function redactUrl(raw) {
64
+ const invalid = "<invalid url>";
65
+ try {
66
+ const u = new URL(raw);
67
+ // An `@` in the path means the operator's userinfo held a `/` (or `\`): the URL parser read
68
+ // everything after it as a path, so the secret sits in the pathname.
69
+ if (u.pathname.includes("@"))
70
+ return invalid;
71
+ u.username = "";
72
+ u.password = "";
73
+ u.search = "";
74
+ u.hash = "";
75
+ return sanitizeForTerminal(u.toString().replace(/\/$/, ""));
76
+ }
77
+ catch {
78
+ return invalid;
79
+ }
80
+ }
@@ -0,0 +1,6 @@
1
+ import { type RetiredEntry } from "./deprecation.js";
2
+ export interface RetiredCommand extends RetiredEntry {
3
+ /** The argv of the replacement command, from the arguments the retired one was given. */
4
+ rewrite(args: string[]): string[];
5
+ }
6
+ export declare const RETIRED_COMMANDS: Readonly<Record<string, RetiredCommand>>;
@@ -0,0 +1,12 @@
1
+ // CLI commands that were valid and are retired. `main` looks a command up here before it
2
+ // dispatches: a retired command prints one deprecation warning and runs its replacement, so a
3
+ // script that still calls it keeps working for the deprecation window. Retired commands are not
4
+ // listed in `--help`.
5
+ export const RETIRED_COMMANDS = {
6
+ drift: {
7
+ since: "0.3.0",
8
+ replacement: "`docsxai pack --check`",
9
+ note: "same flags, `--check` added",
10
+ rewrite: (args) => ["pack", ...args, "--check"],
11
+ },
12
+ };
@@ -0,0 +1,15 @@
1
+ import { type FlowFailure } from "./run-flows.js";
2
+ export interface RunSummaryInput {
3
+ projectDir: string;
4
+ /** `flows` or `flow variants`. */
5
+ noun: string;
6
+ /** How many units were attempted. */
7
+ total: number;
8
+ okCount: number;
9
+ failures: FlowFailure[];
10
+ }
11
+ /** The command to run for a failure: `diagnose` for a halted step, `doctor` when the browser never started. */
12
+ export declare function nextForFailure(projectDir: string, f: FlowFailure): string;
13
+ export declare function formatRunSummary(input: RunSummaryInput): string;
14
+ /** Write the summary on the stream that fits the outcome. */
15
+ export declare function reportRun(input: RunSummaryInput): void;
@@ -0,0 +1,33 @@
1
+ // The closing line of a plain `docsxai run`: how many flows (or flow variants) finished, where the
2
+ // outputs went, and for each failure the command that digs into it. Success goes to stdout with the
3
+ // progress lines; a failure goes to stderr with the halt messages it summarises.
4
+ import * as path from "node:path";
5
+ import { sanitizeForTerminal, shellQuote } from "./cli-messages.js";
6
+ /** The command to run for a failure: `diagnose` for a halted step, `doctor` when the browser never started. */
7
+ export function nextForFailure(projectDir, f) {
8
+ const dir = shellQuote(projectDir);
9
+ if (f.step === null)
10
+ return `docsxai doctor ${dir}`;
11
+ const slash = f.flow.indexOf("/");
12
+ const flow = slash === -1 ? f.flow : f.flow.slice(0, slash);
13
+ const variant = slash === -1 ? "" : ` --variant ${shellQuote(f.flow.slice(slash + 1))}`;
14
+ return `docsxai diagnose ${dir} --flow ${shellQuote(flow)} --step ${shellQuote(f.step)}${variant}`;
15
+ }
16
+ export function formatRunSummary(input) {
17
+ const { projectDir, noun, total, okCount, failures } = input;
18
+ const where = path.join(projectDir, "docs");
19
+ const unit = total === 1 ? noun.replace(/s$/, "") : noun;
20
+ if (failures.length === 0)
21
+ return `run: ${okCount} of ${total} ${unit} ok, outputs in ${where}\n`;
22
+ const lines = [
23
+ `run: ${failures.length} of ${total} ${unit} failed, ${okCount} ok; outputs in ${where}`,
24
+ ];
25
+ for (const f of failures)
26
+ lines.push(` ${sanitizeForTerminal(f.flow)}: next: ${nextForFailure(projectDir, f)}`);
27
+ return lines.join("\n") + "\n";
28
+ }
29
+ /** Write the summary on the stream that fits the outcome. */
30
+ export function reportRun(input) {
31
+ const text = formatRunSummary(input);
32
+ (input.failures.length === 0 ? process.stdout : process.stderr).write(text);
33
+ }
@@ -1 +1 @@
1
- export declare const USAGE = "docsxai \u2014 deterministic execution CLI\n\nUsage:\n docsxai init <workspace-dir> [--app-url <url>] [--auth manual-capture|none] [--role <name>] [--ttl <dur>]\n [--capture-trigger console|button] [--auth-cookie <name>] [--ignore-https-errors]\n [--persist tmp] [--force]\n docsxai calibrate <workspace-dir> --from <flow.md|.yaml> [--name <flow>]\n docsxai inspect <workspace-dir> [--url <url>] [--selector <css>] [--cdp <endpoint>] [--wait <ms>] [--wait-for <css>] [--headed] [--role <role>]\n docsxai run <workspace-dir> [--flow <name>] [--base-url <url>] [--headed] [--ignore-https-errors] [--stop-after <step-id>] [--start-from <step-id>] [--cdp <endpoint>] [--pause] [--concurrency <N>]\n docsxai lint <workspace-dir> [--flow <name>] [--format text|json]\n docsxai flow-tree <workspace-dir> [--format text|json]\n docsxai diagnose <workspace-dir> --flow <name> --step <step-id> [--cdp <endpoint>] [--format text|json]\n docsxai doctor [<workspace-dir>]\n docsxai style <workspace-dir> [--check] [--format text|json]\n docsxai zip <workspace-dir> [--out <output.zip>] [--include-viewer]\n docsxai baseline <workspace-dir> [--out <dir>]\n docsxai diff <workspace-dir> [--against <dir>] [--format json|md|text] [--fail-on warn|fail]\n docsxai export adf <workspace-dir> [--flow <name>] [--mode single|page-tree] [--title <text>] [--out <dir>]\n docsxai export playwright <workspace-dir> [--flow <name>] [--out <dir>]\n docsxai plugins <list|info|sync> <workspace-dir> [<namespace>] [--format text|json]\n docsxai login --backend-url <url>\n docsxai push <workspace-dir> [--kind calibrate|run|edit] [--author <name>]\n docsxai pull <workspace-dir> [--rev <id>]\n docsxai render <workspace-dir>\n docsxai capture-auth <workspace-dir> [--base-url <url>] [--role <role>] [--auth-cookie <name>] [--cdp <endpoint>] [--fresh] [--headless] [--ignore-https-errors]\n docsxai --help\n\nNotes:\n \u2022 A *workspace* (created by `init`) holds flows/<flow>.flow.yaml, docs/, auth/strategy.yaml, .auth/, .viewer/,\n and a .docsxai.json config. Put it OUTSIDE the app's source repo \u2014 docsxai documents a running app from\n outside and never writes into the app repo.\n \u2022 run / capture-auth read app_url + ignore_https_errors from .docsxai.json if you don't pass the flags.\n \u2022 run launches Chromium; if no browser binary is present, install one: npx playwright-core install chromium\n (source checkout: pnpm -C packages/engine exec playwright-core install chromium)\n \u2022 --ignore-https-errors accepts self-signed/invalid TLS (e.g. an app's local HTTPS dev cert)\n \u2022 run --stop-after <step-id> runs only a prefix of the flow (up to & incl. that step); --pause keeps the\n (headed) browser open at the last step run \u2014 so you can inspect the live state mid-flow when calibrating\n (pair with --flow <name>). For waiting on a slow backend op, give a step a wait_for of the form\n { selector: $x, timeout_ms: 180000 } \u2014 a per-step override of the default ~30s selector-wait timeout.\n \u2022 run --concurrency <N> runs up to N flows in parallel (each its own Chromium session, isolated; default 1).\n Useful when several flows share a long preamble \u2014 total wall time = max(per-flow), not sum. Force-clamped\n to 1 when --pause / --stop-after / --start-from / --cdp is set. The target app must tolerate multiple sessions from one user.\n \u2022 run --start-from <step-id> --flow <name> SKIPS every step before <step-id> and starts execution there \u2014\n the inverse of --stop-after. Pair with --cdp to attach to a Chrome that's already in the post-prior-steps\n state (e.g. left over from a paused previous run) and iterate on the new tail step in seconds rather\n than re-walking the whole extends chain. New annotations MERGE into the existing annotations.json by\n step id; the prior steps' annotations and screenshots are preserved.\n \u2022 run --cdp <endpoint> attaches to a running Chrome (start it with --remote-debugging-port=N) instead of\n launching one. docsxai won't close that Chrome. When --cdp is set, the cached storageState is NOT\n loaded into the context \u2014 the operator's Chrome owns its auth state. Useful with --start-from for the\n sub-3-sec iteration loop on long-async flows.\n \u2022 capture-auth runs the role's auth strategy (MVP: manual-capture \u2014 a headed, instrumented browser the\n engineer logs into; window.__docsxai.capture() or an injected button snapshots the session) and caches\n it to <workspace-dir>/.auth/<role>.json for subsequent `run`s. It prints the captured cookie jar so you\n can identify the app's real auth/session cookie.\n \u2022 capture-auth keeps a persistent Chrome profile at <workspace>/.auth/chrome-profile/ (gitignored) \u2014 re-running\n it reuses the login (just trigger capture again). Use --fresh for a clean profile (forces a fresh login).\n \u2022 --cdp <endpoint> makes capture-auth *attach to an already-running Chrome* (start it with\n --remote-debugging-port=N --disable-web-security --user-data-dir=<dir>) instead of launching a fresh one \u2014\n use this to capture from the same Chrome the engineer is already logged into (and that Claude in Chrome is\n driving for discovery), so they don't log in twice. docsxai won't close that Chrome. (--cdp ignores --fresh.)\n \u2022 auth_cookie (set via `init --auth-cookie`, `capture-auth --auth-cookie`, or hand-edited into\n auth/strategy.yaml) names that cookie; when set, the cached session's expiry tracks *that* cookie's\n expiry rather than the `ttl` guess (an interactive SSO login leaves ephemeral IdP scratch cookies, so\n `min(cookie.expires)` \u2248 now \u2014 don't rely on it). If unset/unfound, `ttl` (or a 1h default) is used.\n \u2022 inspect opens the app in a headless (or --headed) browser *with the cached session loaded* and prints the\n page's [data-testid] elements (or, with --selector, matching elements' HTML) \u2014 for pinning locators when\n hand-authoring a flow-file (the captured session can't be replayed in a browser the agent's MCP controls\n because the auth cookie is usually httpOnly; inspect does the storageState\u2192Playwright bridge for you). On a\n slow SPA, settle before the snapshot with --wait <ms> (default 800) or --wait-for '<css>'. --cdp <endpoint>\n attaches to an already-running Chrome (e.g. the one from capture-auth --cdp) instead of launching one.\n \u2022 calibrate takes a *structured flow-guide* (a flow-file in YAML, or a .md with a yaml fenced block) and\n writes flows/<name>.flow.yaml + a default docs/style.yaml. Loose-prose descriptions / live element-picking\n need the host agent \u2014 that's the /docsxai:calibrate *skill* (see the plugin), which then refines/produces\n the flow-file; this CLI command covers only the deterministic structured-input case.\n \u2022 lint runs pure-static checks across the workspace's flow-files \u2014 no Playwright, no live page. Rules:\n R001 (deep extends chain), R002 (annotation anchored to a likely-unmounting click/navigate target \u2014\n suggest annotation.target override), R003 (wait_for with no timeout_ms on a long-async-looking step),\n R004 (bare [data-*=\u2026] selector \u2014 may have hidden duplicates; suggest :visible / :has-text qualifier).\n Exit 1 if any warning/error; 0 otherwise. --format json emits machine-readable output for tooling.\n \u2022 flow-tree prints the workspace's extends graph (root flows + their descendants), plus any orphans\n (flows whose extends parent isn't in the workspace) and resolution issues (cycles / step-id collisions\n across the merge). Pure-static, ~no I/O beyond reading the flow files. Exit 1 if any issues.\n \u2022 diagnose gathers halt context for a specific step (the step's selector/wait_for/success, the halt\n screenshot if one exists, and \u2014 with --cdp \u2014 a live actionable() probe of the target on the running\n page) and prints recommendations (selector / wait_for / success / annotation_target / split_step /\n investigate). The engine never patches the flow-file itself \u2014 that's the agent's explicit opt-in\n action. --format json emits machine-readable output for an agent to act on. Pair with\n --start-from <step-id> --cdp on a follow-up run to validate the fix in seconds.\n \u2022 doctor health-checks the environment + workspace: Node >= 26, Chromium presence, .docsxai.json\n found + parseable (cwd or the arg), flow-file parses, auth descriptor + cached-session freshness,\n backend reachability (when backend_url is set), the plugin declarations (same inspection as\n `plugins list` \u2014 no plugin code is executed), viewer-bin resolution (which of the three layers\n hit), and DOCSX_* env sanity. \u2713/\u2717 rows with a one-line fix per failure; \u2212 rows are informational\n and never fail. Exit 1 if any \u2717.\n \u2022 style initialises docs/style.yaml + derived docs/style.json if absent (otherwise validates the\n existing YAML against the schema and rederives the JSON). --check additionally scans every\n docs/<flow>/<step>.md user-facing write-up for jargon leaks against the style's pruning_rules\n (e.g. VERIFY / WAIT / data-testid leaking into user-facing prose). The engine never re-shapes\n prose itself (LLM-agnostic) \u2014 the agent does that at calibration time; this command is the\n enforcement layer for the semantic-reshape exit criterion. --format json emits machine-readable\n output for tooling.\n \u2022 zip packages the workspace's doc pack into a single archive for hand-off. Includes flows/, docs/,\n .docsxai.json, auth/strategy.yaml (env-var names only, no creds), README.md. Excludes .auth/\n (operator-local session state), **/halts/ (debug screenshots), .viewer/ by default (re-renderable\n from the doc pack; pass --include-viewer to bundle it). Defaults output to <workspace-name>.zip\n in the current dir; override with --out <path>. Zips in-process (no system 'zip' binary needed)\n and deterministically \u2014 sorted entries, fixed mtime, fixed compression \u2014 so the same doc pack\n always produces a byte-identical archive.\n \u2022 baseline snapshots the doc pack \u2014 flows/, docs/<flow>/*.md, annotations.json, screenshots/, and\n docs/locators.yaml \u2014 into <ws>/.baseline/ (or --out <dir>). Commit the baseline: it's the \"before\"\n that diff compares against in CI.\n \u2022 diff compares the workspace against a baseline (default <ws>/.baseline/, or --against <dir>) and\n emits a deterministic drift report: per flow, step field deltas (id-keyed), annotation moves,\n screenshot pixel diffs (changed-pixel count / % / changed-region bbox; dimension changes flagged\n distinctly), prose line-change counts, and locator changes. --format md is PR-comment-ready.\n --fail-on warn|fail exits 1 when the report severity is at/above the threshold (screenshot\n severity: \u22651% changed pixels = warn, \u22655% = fail; structural changes = warn).\n \u2022 export playwright emits one self-contained Playwright .spec.ts per flow (extends resolved) into\n <ws>/.export/tests/ (or --out <dir>) \u2014 locators as consts, steps as page actions, success criteria\n as expect() assertions, environment as test.use(); optional steps are try/catch-wrapped. Generated\n files say so in a header: regenerate, don't hand-edit.\n \u2022 render builds the static viewer by spawning the docsxai-viewer bin, resolved in order: the\n DOCSX_VIEWER_BIN env var (path to the viewer's bin script), the @docsxai/viewer\n package installed next to the engine, then `docsxai-viewer` on PATH.\n \u2022 login validates a bearer token against a backend URL \u2014 hits /v1/health, /v1/workspaces. Reads\n the token from DOCSX_TOKEN env var. Prints what the backend sees if the call succeeds,\n or a clear error if not. Stateless: doesn't store anything; configure the env var in your shell.\n \u2022 push serialises the workspace's doc pack (flows + annotations + screenshots + style + locators)\n and POSTs it as a new revision against the backend named in .docsxai.json (backend_url +\n optionally backend_workspace_id / backend_project_id; created on first push if absent and\n persisted to the config). --kind defaults to \"calibrate\"; --author defaults to the OS user.\n \u2022 pull fetches a revision's artifacts back into the workspace files (default: HEAD). Useful for\n syncing with a different operator's edits or rolling back to a named revision.";
1
+ export declare const USAGE = "docsxai \u2014 deterministic execution CLI\n\nUsage:\n docsxai init <workspace-dir> [--app-url <url>] [--auth manual-capture|none] [--role <name>] [--ttl <dur>]\n [--capture-trigger console|button] [--auth-cookie <name>] [--ignore-https-errors]\n [--persist tmp] [--force]\n docsxai calibrate <workspace-dir> --from <flow.md|.yaml> [--name <flow>]\n docsxai inspect <workspace-dir> [--url <url>] [--selector <css>] [--cdp <endpoint>] [--wait <ms>] [--wait-for <css>] [--headed] [--ignore-https-errors] [--role <role>]\n docsxai run <workspace-dir> [--flow <name>] [--base-url <url>] [--headed] [--ignore-https-errors] [--stop-after <step-id>] [--start-from <step-id>] [--variant <id>] [--cdp <endpoint>] [--pause] [--concurrency <N>]\n docsxai run <workspace-dir> --verify-determinism [--runs <2-5>] [--format json|md|text] [--flow <name>] [--base-url <url>] [--concurrency <N>]\n docsxai lint <workspace-dir> [--flow <name>] [--format text|json]\n docsxai flow-tree <workspace-dir> [--format text|json]\n docsxai diagnose <workspace-dir> --flow <name> --step <step-id> [--variant <id>] [--cdp <endpoint>] [--format text|json]\n docsxai doctor [<workspace-dir>]\n docsxai style <workspace-dir> [--check] [--format text|json]\n docsxai zip <workspace-dir> [--out <output.zip>] [--include-viewer]\n docsxai baseline <workspace-dir> [--out <dir>]\n docsxai diff <workspace-dir> [--against <dir>] [--format json|md|text] [--fail-on warn|fail]\n docsxai export adf <workspace-dir> [--flow <name>] [--mode single|page-tree] [--title <text>] [--out <dir>]\n docsxai export playwright <workspace-dir> [--flow <name>] [--out <dir>]\n docsxai plugins <list|info|sync> <workspace-dir> [<namespace>] [--format text|json]\n docsxai login --backend-url <url> [--oauth <workspace-dir>]\n docsxai push <workspace-dir> [--kind calibrate|run|edit] [--author <name>]\n docsxai pull <workspace-dir> [--rev <id>]\n docsxai render <workspace-dir>\n docsxai burn <workspace-dir> [--flow <name>] [--out <dir>] [--report <file>] [--no-connector-outline]\n docsxai pack <workspace-or-raw-dir> [--from-raw] [--out <dir>] [--public-prefix <path>] [--no-optimise] [--generated-for <text>]\n docsxai pack <workspace-or-raw-dir> --check --against <pack-dir> [--from-raw] [--threshold <pct>]\n docsxai capture-auth <workspace-dir> [--base-url <url>] [--role <role>] [--auth-cookie <name>] [--cdp <endpoint>] [--fresh] [--headless] [--ignore-https-errors]\n docsxai --help\n\nNotes:\n \u2022 A *workspace* (created by `init`) holds flows/<flow>.flow.yaml, docs/, auth/strategy.yaml, .auth/, .viewer/,\n and a .docsxai.json config. Put it OUTSIDE the app's source repo \u2014 docsxai documents a running app from\n outside and never writes into the app repo.\n \u2022 run / capture-auth read app_url + ignore_https_errors from .docsxai.json if you don't pass the flags.\n \u2022 run launches Chromium; if no browser binary is present, install one: npx playwright-core install chromium\n (source checkout: pnpm -C packages/engine exec playwright-core install chromium)\n \u2022 --ignore-https-errors accepts self-signed/invalid TLS (e.g. an app's local HTTPS dev cert)\n \u2022 run --stop-after <step-id> runs only a prefix of the flow (up to & incl. that step); --pause keeps the\n (headed) browser open at the last step run \u2014 so you can inspect the live state mid-flow when calibrating\n (pair with --flow <name>). For waiting on a slow backend op, give a step a wait_for of the form\n { selector: $x, timeout_ms: 180000 } \u2014 a per-step override of the default ~30s selector-wait timeout.\n For a page that settles late (web fonts swapping, images arriving), use wait_for: settled: it waits for\n fonts, the images in view and the layout of what's on screen to stop changing, within the step's\n timeout_ms (default 10s), and halts with the cause if the page never settles.\n \u2022 run --concurrency <N> runs up to N flows in parallel (each its own Chromium session, isolated; default 1).\n Useful when several flows share a long preamble \u2014 total wall time = max(per-flow), not sum. Force-clamped\n to 1 when --pause / --stop-after / --start-from / --cdp is set. The target app must tolerate multiple sessions from one user.\n \u2022 run --start-from <step-id> --flow <name> SKIPS every step before <step-id> and starts execution there \u2014\n the inverse of --stop-after. Pair with --cdp to attach to a Chrome that's already in the post-prior-steps\n state (e.g. left over from a paused previous run) and iterate on the new tail step in seconds rather\n than re-walking the whole extends chain. New annotations MERGE into the existing annotations.json by\n step id; the prior steps' annotations and screenshots are preserved.\n \u2022 A flow with a top-level `matrix:` (locales, color_schemes, viewports) expands into one variant per\n combination. run gives each variant its own Chromium session and writes docs/<flow>/<variant>/\n {screenshots/, annotations.json, halts/} (variant id: <locale>.<scheme>.<viewport>, axes the matrix\n leaves out are dropped). run --variant <id> runs one variant. lint lists the variants (R015), flow-tree\n prints them, diagnose --variant <id> picks one. --cdp cannot run a matrix flow.\n \u2022 run --cdp <endpoint> attaches to a running Chrome (start it with --remote-debugging-port=N) instead of\n launching one. docsxai won't close that Chrome. When --cdp is set, the cached storageState is NOT\n loaded into the context \u2014 the operator's Chrome owns its auth state. Useful with --start-from for the\n sub-3-sec iteration loop on long-async flows.\n \u2022 run --verify-determinism runs the selected flows N times (--runs, 2 to 5, default 2), each into its own\n root under <ws>/.docsxai-verify/run-<k>/, then byte-compares every artefact: annotations.json, screenshots,\n step markdown, locators, halt context. The workspace output is written only when every run agrees (run 1's\n files are copied in, the bytes a plain run writes); on any difference or halt it is left untouched. The run\n roots are removed at the end. The report goes to stdout (--format text|md|json, default text; progress goes to\n stderr) and names the first differing artefact by path with a cause: the JSON key path, the changed-pixel\n region of a PNG, the first differing line of text, or the sizes. Exit 0 identical, 1 differing or a flow\n halted, 2 bad flags. Not combinable with --pause / --stop-after / --start-from / --cdp.\n \u2022 capture-auth runs the role's auth strategy (MVP: manual-capture \u2014 a headed, instrumented browser the\n engineer logs into; window.__docsxai.capture() or an injected button snapshots the session) and caches\n it to <workspace-dir>/.auth/<role>.json for subsequent `run`s. It prints the captured cookie jar so you\n can identify the app's real auth/session cookie.\n \u2022 capture-auth keeps a persistent Chrome profile at <workspace>/.auth/chrome-profile/ (gitignored) \u2014 re-running\n it reuses the login (just trigger capture again). Use --fresh for a clean profile (forces a fresh login).\n \u2022 --cdp <endpoint> makes capture-auth *attach to an already-running Chrome* (start it with\n --remote-debugging-port=N --disable-web-security --user-data-dir=<dir>) instead of launching a fresh one \u2014\n use this to capture from the same Chrome the engineer is already logged into (and that Claude in Chrome is\n driving for discovery), so they don't log in twice. docsxai won't close that Chrome. (--cdp ignores --fresh.)\n \u2022 auth_cookie (set via `init --auth-cookie`, `capture-auth --auth-cookie`, or hand-edited into\n auth/strategy.yaml) names that cookie; when set, the cached session's expiry tracks *that* cookie's\n expiry rather than the `ttl` guess (an interactive SSO login leaves ephemeral IdP scratch cookies, so\n `min(cookie.expires)` \u2248 now \u2014 don't rely on it). If unset/unfound, `ttl` (or a 1h default) is used.\n \u2022 inspect opens the app in a headless (or --headed) browser *with the cached session loaded* and prints the\n page's [data-testid] elements (or, with --selector, matching elements' HTML) \u2014 for pinning locators when\n hand-authoring a flow-file (the captured session can't be replayed in a browser the agent's MCP controls\n because the auth cookie is usually httpOnly; inspect does the storageState\u2192Playwright bridge for you). On a\n slow SPA, settle before the snapshot with --wait <ms> (default 800) or --wait-for '<css>'. --cdp <endpoint>\n attaches to an already-running Chrome (e.g. the one from capture-auth --cdp) instead of launching one.\n --ignore-https-errors accepts a self-signed/invalid TLS certificate (also read from ignore_https_errors in .docsxai.json).\n \u2022 calibrate takes a *structured flow-guide* (a flow-file in YAML, or a .md with a yaml fenced block) and\n writes flows/<name>.flow.yaml + a default docs/style.yaml. Loose-prose descriptions / live element-picking\n need the host agent \u2014 that's the /docsxai:calibrate *skill* (see the plugin), which then refines/produces\n the flow-file; this CLI command covers only the deterministic structured-input case.\n \u2022 lint runs pure-static checks across the workspace's flow-files \u2014 no Playwright, no live page. Rules:\n R001 (deep extends chain), R002 (annotation anchored to a likely-unmounting click/navigate target \u2014\n suggest annotation.target override), R003 (wait_for with no timeout_ms on a long-async-looking step),\n R004 (bare [data-*=\u2026] selector \u2014 may have hidden duplicates; suggest :visible / :has-text qualifier).\n Exit 1 if any warning/error; 0 otherwise. --format json emits machine-readable output for tooling.\n \u2022 flow-tree prints the workspace's extends graph (root flows + their descendants), plus any orphans\n (flows whose extends parent isn't in the workspace) and resolution issues (cycles / step-id collisions\n across the merge). Pure-static, ~no I/O beyond reading the flow files. Exit 1 if any issues.\n \u2022 diagnose gathers halt context for a specific step (the step's selector/wait_for/success, the halt\n screenshot if one exists, and \u2014 with --cdp \u2014 a live actionable() probe of the target on the running\n page) and prints recommendations (selector / wait_for / success / annotation_target / split_step /\n investigate). The engine never patches the flow-file itself \u2014 that's the agent's explicit opt-in\n action. --format json emits machine-readable output for an agent to act on. Pair with\n --start-from <step-id> --cdp on a follow-up run to validate the fix in seconds.\n \u2022 doctor health-checks the environment + workspace: Node >= 26, Chromium presence, .docsxai.json\n found + parseable (cwd or the arg), flow-file parses, auth descriptor + cached-session freshness,\n backend reachability (when backend_url is set), the plugin declarations (same inspection as\n `plugins list` \u2014 no plugin code is executed), viewer-bin resolution (which of the three layers\n hit), and DOCSX_* env sanity. \u2713/\u2717 rows with a one-line fix per failure; \u2212 rows are informational\n and never fail. Exit 1 if any \u2717.\n \u2022 style initialises docs/style.yaml + derived docs/style.json if absent (otherwise validates the\n existing YAML against the schema and rederives the JSON). --check additionally scans every\n docs/<flow>/<step>.md user-facing write-up for jargon leaks against the style's pruning_rules\n (e.g. VERIFY / WAIT / data-testid leaking into user-facing prose). The engine never re-shapes\n prose itself (LLM-agnostic) \u2014 the agent does that at calibration time; this command is the\n enforcement layer for the semantic-reshape exit criterion. --format json emits machine-readable\n output for tooling.\n \u2022 zip packages the workspace's doc pack into a single archive for hand-off. Includes flows/, docs/,\n .docsxai.json, auth/strategy.yaml (env-var names only, no creds), README.md. Excludes .auth/\n (operator-local session state), **/halts/ (debug screenshots), .viewer/ by default (re-renderable\n from the doc pack; pass --include-viewer to bundle it). Defaults output to <workspace-name>.zip\n in the current dir; override with --out <path>. Zips in-process (no system 'zip' binary needed)\n and deterministically \u2014 sorted entries, fixed mtime, fixed compression \u2014 so the same doc pack\n always produces a byte-identical archive.\n \u2022 baseline snapshots the doc pack \u2014 flows/, docs/<flow>/*.md, annotations.json, screenshots/, and\n docs/locators.yaml \u2014 into <ws>/.baseline/ (or --out <dir>). Commit the baseline: it's the \"before\"\n that diff compares against in CI.\n \u2022 diff compares the workspace against a baseline (default <ws>/.baseline/, or --against <dir>) and\n emits a deterministic drift report: per flow, step field deltas (id-keyed), annotation moves,\n screenshot pixel diffs (changed-pixel count / % / changed-region bbox; dimension changes flagged\n distinctly), prose line-change counts, and locator changes. --format md is PR-comment-ready.\n --fail-on warn|fail exits 1 when the report severity is at/above the threshold (screenshot\n severity: \u22651% changed pixels = warn, \u22655% = fail; structural changes = warn).\n \u2022 export playwright emits one self-contained Playwright .spec.ts per flow (extends resolved) into\n <ws>/.export/tests/ (or --out <dir>) \u2014 locators as consts, steps as page actions, success criteria\n as expect() assertions, environment as test.use(); optional steps are try/catch-wrapped. Generated\n files say so in a header: regenerate, don't hand-edit.\n \u2022 render builds the static viewer by spawning the docsxai-viewer bin, resolved in order: the\n DOCSX_VIEWER_BIN env var (path to the viewer's bin script), the @docsxai/viewer\n package installed next to the engine, then `docsxai-viewer` on PATH.\n \u2022 burn bakes each flow's annotations (halo, badge, callout) into copies of its clean screenshots, for\n surfaces that can't run the interactive viewer, via the same viewer bin as render. Reads\n <ws>/docs/<flow>/annotations.json and writes docs/<flow>/burned/<step>.png (or <out>/<flow>/<step>.png\n with --out). --flow limits it to named flows (repeatable); the default is every flow with annotations.\n --report <file> writes a JSON placement report (callout and badge boxes, overlaps, callouts flagged\n unplaceable), resolved under the workspace when relative. --no-connector-outline keeps every arrow and\n stem plain ink; by default one over a dark part of the screenshot gets a white outline.\n \u2022 pack builds the screenshot pack a docs site or README ships: it burns each step's annotations into its\n clean screenshot, optimises the PNG losslessly with the external `oxipng` binary (on PATH, or\n $DOCSX_OXIPNG_BIN; `brew install oxipng`; --no-optimise skips it), names it\n <flow>/<step>.<hash8>.png from the final bytes, and writes manifest.json (docsxai/screens-pack@2: flows,\n steps, localised alt, variants keyed <locale>.<theme>.<viewport> with src, size and callouts). <dir> is a\n workspace (docs/ plus a pack.json naming which capture flow feeds which variant, and the alt text) or,\n with --from-raw or no docs/, a raw capture directory (<flow>/<step>/<locale>.<theme>.<viewport>.png with a\n .json sidecar, step.json and flow.json). --out defaults to <workspace>/.screens and is required for a raw\n directory. Files the previous manifest listed and the new one does not are deleted by exact path; nothing\n else in --out is touched. Loopback and private-network addresses, emails, non-Bearer Authorization headers,\n URL-query tokens and obvious secrets in alt, caption, title or callout text stop the build. Runs the\n viewer's `pack` through the same bin resolution as render.\n \u2022 pack --check rebuilds the pack in memory (no oxipng, nothing written) and compares it with the committed pack\n in --against (required): equal hash is unchanged, otherwise a pixel diff gives changed %, the changed region and\n a pass or fail against --threshold (default 0.5). A resized, new or missing variant, or a committed file\n that does not match its name, always fails. Exit 1 on any failure, 2 on a bad argument. The report has no\n timestamps. The old `docsxai drift` still works for now: it prints a deprecation warning and runs pack --check.\n \u2022 login validates a bearer token against a backend URL \u2014 hits /v1/health, /v1/workspaces. Reads\n the token from DOCSX_TOKEN env var. Prints what the backend sees if the call succeeds,\n or a clear error if not. Stateless: doesn't store anything; configure the env var in your shell.\n login --oauth <workspace-dir> instead signs in as a person: OAuth 2.1 authorization code + PKCE against\n the backend. It prints a URL to open in a browser and stores the tokens at\n <workspace-dir>/.auth/backend-token.json (mode 0600); push, pull and run read them from there.\n \u2022 push serialises the workspace's doc pack (flows + annotations + screenshots + style + locators)\n and POSTs it as a new revision against the backend named in .docsxai.json (backend_url +\n optionally backend_workspace_id / backend_project_id; created on first push if absent and\n persisted to the config). --kind defaults to \"calibrate\"; --author defaults to the OS user.\n \u2022 pull fetches a revision's artifacts back into the workspace files (default: HEAD). Useful for\n syncing with a different operator's edits or rolling back to a named revision.\n \u2022 A command that works on a workspace takes its directory as the first argument. Reports and data go to\n stdout; progress lines and warnings go to stderr where a command already splits them. Output has no\n colour. An error prints `<command>: what failed`, then `next: <command to run>` when there is one.\n Exit 0 success, 1 runtime failure, 2 usage error.\n \u2022 --format json (lint, flow-tree, diagnose, style, diff, plugins, run --verify-determinism) is the\n machine-readable output; the text formats are for people and may change.\n \u2022 run, calibrate, burn, pack, zip, baseline, push, pull and doctor end with one line,\n `<command>: <result> \u2026`, naming the counts and where the output went (run --verify-determinism\n ends with its report).\n\nExamples:\n docsxai init ~/docsxai/my-app --app-url https://app.example.com\n docsxai capture-auth ~/docsxai/my-app\n docsxai calibrate ~/docsxai/my-app --from login.flow.yaml\n docsxai run ~/docsxai/my-app --flow login\n docsxai run ~/docsxai/my-app --verify-determinism --runs 3 --format md\n docsxai lint ~/docsxai/my-app --format json\n docsxai render ~/docsxai/my-app\n docsxai burn ~/docsxai/my-app --flow login --out ~/docsxai/my-app/burned\n docsxai pack ~/docsxai/my-app --out ~/docsxai/my-app/.screens\n docsxai pack ~/docsxai/my-app --check --against ./public/screens\n docsxai baseline ~/docsxai/my-app\n docsxai diff ~/docsxai/my-app --fail-on warn\n docsxai doctor ~/docsxai/my-app\n docsxai push ~/docsxai/my-app --kind run";