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

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.
package/README.md CHANGED
@@ -8,7 +8,7 @@ The engine **never** calls a model API. Calibration-time inference is supplied b
8
8
 
9
9
  - **Flow-file** — declarative YAML at `<workspace>/flows/<name>.flow.yaml`: `prerequisites` + `locators` + `steps[]` (`action`, `target`, `wait_for`, `success`, `annotation` / `annotations`, per-step `redactions`, `timeout_ms`). Actions: `navigate`, `click`, `fill`, `upload`, `press`, `hover`, `select`, `check`, `uncheck`, `wait`, `hide`, `show`. Hand-editable; schema-validated. `extends:` composition for shared preambles (with `environment` merged per-key, child wins; `redactions` concatenated).
10
10
  - **Execution environment** — optional `environment` block (`EnvironmentSpec`): frozen `clock` (Playwright clock API), `locale`, `timezone`, `viewport` (`VIEWPORT_PRESETS`: desktop / tablet / mobile, or explicit size), `color_scheme`, `reduced_motion`. Applied at context creation by `launchPlaywrightSession({ environment })`; on CDP-attached sessions only the clock applies (one stderr warning lists skipped fields). `contextOptions` passes `httpCredentials` / `clientCertificates` / `extraHTTPHeaders` through to `browser.newContext`.
11
- - **Request guard (opt-in)** — `DOCSX_EGRESS_GUARD=1` (or `launchPlaywrightSession({ egressGuard })`) routes every request of the browser context through `egress-guard.ts`: a host that is, or resolves (`dns.lookup`, all addresses) to, a link-local or cloud-metadata address is aborted, redirect hops and WebSocket connections included, and a failed lookup aborts too (the printed reason is generic: `address not allowed`); `DOCSX_EGRESS_DENY_PRIVATE=1` adds loopback and private ranges. Both take `1`, `true` or `yes`. Off by default for a local `run`; the backend runner turns it on for webhook runs. It does not stop DNS rebinding (`SECURITY.md`). An `upload` step reads only regular files under the workspace (`upload-path.ts`). The address rules in `address-class.ts` are a byte-identical copy of the backend's.
11
+ - **Request guard (opt-in)** — `DOCSX_EGRESS_GUARD=1` (or `launchPlaywrightSession({ egressGuard })`) routes every request of the browser context through `egress-guard.ts`: a host that is, or resolves (`dns.lookup`, all addresses) to, a link-local or cloud-metadata address is aborted, redirect hops and WebSocket connections included, and a failed lookup aborts too (the printed reason is generic: `address not allowed`); `DOCSX_EGRESS_DENY_PRIVATE=1` adds loopback and private ranges. Both take `1`, `true` or `yes`. Off by default for a local `run`; the backend runner turns it on for webhook runs, and so does the MCP HTTP transport for the browser `run_flows` starts. It does not stop DNS rebinding (`SECURITY.md`). An `upload` step reads only regular files under the workspace (`upload-path.ts`). The address rules in `address-class.ts` are a byte-identical copy of the backend's.
12
12
  - **Hiding + step timeouts** — `hide` sets `visibility: hidden !important` on every element its `target` matches until a `show` (no target lifts all, a target lifts the `hide` that used the same selector). `PlaywrightDriver` marks the elements with a data attribute and adopts a fixed stylesheet keyed on it (`page-hide.ts`, in-page and engine-owned; the selector is data, never CSS or script). The rule lives on each element's own root, so it reaches shadow trees, and constructable stylesheets are not blocked by a page's CSP. Visibility keeps the box, so nothing reflows; there is deliberately no `display: none` option and no general CSS-injection step. The driver keeps the selectors and re-marks before every screenshot (halt shots included), so the hiding survives navigations and re-renders. `hide` waits for the element to exist (`attached`) and throws when none does, so `optional: true` covers dev-only UI such as `nextjs-portal`. A step's `timeout_ms` (100–30000) is passed to the driver call (`click(selector, timeoutMs?)`, `hideElements(selector, timeoutMs?)`, …); unset, nothing is passed and Playwright's 30 s default applies, so existing flows and non-optional steps are unchanged. `optional` does not shorten the wait by itself, so a missing optional target costs 30 s unless `timeout_ms` is set; `lint` R011 says so. `BrowserDriver` gains `hideElements` / `showElements` (required). The pure `hiddenAtEachStep` (`flow-hidden.ts`) tells `lint` (R013) and `diagnose` which selectors an earlier `hide` hid.
13
13
  - **Redactions** — flow-level + per-step `RedactionSpec[]` (`{ selector }` or `{ region }`, style `box` | `pixelate`) masked deterministically before any screenshot (halt shots included) hits disk. The pure pixel transform is `applyRedactions` in `redact.ts`.
14
14
  - **`BrowserDriver`** interface — what the runtime needs from a browser. The `PlaywrightDriver` implementation includes the `actionable()` predicate (see [`docs/actionability-contract.md`](../../docs/actionability-contract.md)) that browser-bridge consumers can mirror, plus a real `element_stable` wait (bounding-box polling, 10 s best-effort budget). `waitForSettled?`, `hideElements?`, `showElements?` and `nearbyBoxes?` are **optional** methods (behind `wait_for: settled`, the `hide` and `show` actions and `annotations.obstacles`), so a driver written before they existed still compiles; the runtime halts a step that needs a missing method with a message naming it (`obstacles` only when the workspace turned it on), and never calls a method the flow does not use. `PlaywrightDriver` runs the fixed in-page poll in `page-settle.ts` (fonts loaded, visible images complete, viewport box geometry unchanged for two consecutive polls, every 50 ms, bounded by the step's `timeout_ms`, default 10 s) and rejects with `settled: page did not settle within N ms ...` naming what kept moving; `inferHaltCause` turns that into the `[page never settled: ...]` prefix.
@@ -53,7 +53,7 @@ A flow with a top-level `matrix:` (`locales`, `color_schemes`, `viewports`; at m
53
53
 
54
54
  `baseline` + `diff` are the drift-detection pair. `baseline` snapshots `flows/` + `docs/` (step `.md`s, `annotations.json`, `screenshots/`, `locators.yaml`) into `<workspace>/.baseline/` (or `--out <dir>`); `diff` compares the live workspace against it (`diffDocPacks` on the library surface) and emits a deterministic `docsxai/drift@1` report — per flow: id-keyed step field deltas, annotation moves beyond a pixel tolerance, screenshot pixel diffs via pngjs (changed-pixel count / pct / changed-region bbox; dimension changes flagged distinctly; `ignore_regions` excluded), prose line-change counts, and locator changes. `--format md` (`formatDriftReportMarkdown`) is PR-comment-ready; `--fail-on warn|fail` exits 1 at/above the threshold (defaults: ≥1% changed pixels = warn, ≥5% = fail, structural change = warn). The engine detects and reports; proposing flow-file patches stays with the host agent (`diagnose`).
55
55
 
56
- `run --verify-determinism [--runs <2-5>] [--format json|md|text]` runs the selected flows N times (default 2) through the same flow loop as a plain `run` (`runFlowsInSessions`), each into its own output root under `<workspace>/.docsxai-verify/run-<k>/` (`PlaywrightSessionOptions.outputRoot` redirects the screenshots; `upload` sources still resolve against the workspace), then byte-compares every file under the roots (`compareRuns` in `verify-compare.ts`, exported). The first differing artefact is named by path with a cause: JSON key path, PNG changed-pixel count and region (the `diffPngBuffers` of `diff`), first differing text line, or sizes. A halt is recorded as `docs/<flow>/halts/halt-context.json` in the run root, so halt context is compared like any artefact; a halted flow makes the verdict `halted` (exit 1). Run 1's tree is copied into the workspace only when every run agrees and none halted; otherwise the workspace is untouched. The roots are removed by their listing (unlink each file, rmdir each directory deepest first; `verify-tree.ts`), never recursively. The `docsxai/verify-determinism@1` report has no timestamps or paths and is ordered by ordinal path then run: exit 0 identical, 1 differing or halted, 2 usage. Nightly recipes for GitHub Actions, GitLab CI and Woodpecker are in `docs/ci-recipes.md` and `examples/ci/`.
56
+ `run --verify-determinism [--runs <2-5>] [--format text|md|json]` runs the selected flows N times (default 2) through the same flow loop as a plain `run` (`runFlowsInSessions`), each into its own output root under `<workspace>/.docsxai-verify/run-<k>/` (`PlaywrightSessionOptions.outputRoot` redirects the screenshots; `upload` sources still resolve against the workspace), then byte-compares every file under the roots (`compareRuns` in `verify-compare.ts`, exported). The first differing artefact is named by path with a cause: JSON key path, PNG changed-pixel count and region (the `diffPngBuffers` of `diff`), first differing text line, or sizes. A halt is recorded as `docs/<flow>/halts/halt-context.json` in the run root, so halt context is compared like any artefact; a halted flow makes the verdict `halted` (exit 1). Run 1's tree is copied into the workspace only when every run agrees and none halted; otherwise the workspace is untouched. The roots are removed by their listing (unlink each file, rmdir each directory deepest first; `verify-tree.ts`), never recursively. The `docsxai/verify-determinism@1` report has no timestamps or paths and is ordered by ordinal path then run: exit 0 identical, 1 differing or halted, 2 usage. Nightly recipes for GitHub Actions, GitLab CI and Woodpecker are in `docs/ci-recipes.md` and `examples/ci/`.
57
57
 
58
58
  `export playwright` renders each flow (with `extends` resolved) as a self-contained Playwright `.spec.ts` (`exportFlowAsPlaywrightTest`) into `<workspace>/.export/tests/`: locator consts, steps as page actions, `wait_for` as waits, `success` as `expect()` assertions, `environment` as `test.use()` + `page.clock.setFixedTime`, `optional` steps in try/catch. Deterministic; generated files carry a "regenerate, don't hand-edit" header.
59
59
 
@@ -2,6 +2,7 @@
2
2
  // the resolution precedence (explicit → `DOCSX_TOKEN` → stored, with refresh-rotation), and the
3
3
  // load/save helpers. Re-exported from `./backend-client.js`.
4
4
  import { promises as fs } from "node:fs";
5
+ import { redactUrl, redactUrlsIn, shellQuote } from "./cli-messages.js";
5
6
  import { resolveWorkspacePath, resolveWorkspacePathReal } from "./workspace.js";
6
7
  import { BackendClientError } from "./backend-client-contracts.js";
7
8
  const BACKEND_TOKEN_FILE = "backend-token.json";
@@ -53,7 +54,7 @@ export async function resolveBackendToken(opts) {
53
54
  return opts.token;
54
55
  if (process.env.DOCSX_TOKEN)
55
56
  return process.env.DOCSX_TOKEN;
56
- const reloginHint = `set DOCSX_TOKEN or run \`docsxai login --backend-url ${opts.baseUrl} --oauth <workspace-dir>\``;
57
+ const reloginHint = `set DOCSX_TOKEN or run \`docsxai login --backend-url ${shellQuote(redactUrl(opts.baseUrl))} --oauth <workspace-dir>\``;
57
58
  if (!opts.workspaceDir) {
58
59
  throw new BackendClientError(`no bearer token — ${reloginHint}`);
59
60
  }
@@ -82,7 +83,7 @@ export async function resolveBackendToken(opts) {
82
83
  refreshed = (await res.json());
83
84
  }
84
85
  catch (e) {
85
- throw new BackendClientError(`stored backend token expired and the refresh failed (${e.message}) — ${reloginHint}`);
86
+ throw new BackendClientError(`stored backend token expired and the refresh failed (${redactUrlsIn(e.message)}) — ${reloginHint}`);
86
87
  }
87
88
  const tokens = {
88
89
  access_token: refreshed.access_token,
@@ -0,0 +1,7 @@
1
+ /**
2
+ * The message for a backend failure, or `undefined` when `e` is not one (the caller rethrows it).
3
+ * `login` is the command that signs in, so its own failures point at itself.
4
+ */
5
+ export declare function explainBackendFailure(e: unknown, backendUrl: string, workspaceDir?: string): string | undefined;
6
+ /** Why `.docsxai.json` did not load as a workspace config, as a phrase for parentheses. */
7
+ export declare function configProblem(workspaceDir: string): Promise<string>;
@@ -0,0 +1,66 @@
1
+ // Wording for backend failures in `login`, `push` and `pull`: what failed, why, and the next
2
+ // command. A refused connection reaches the CLI as a bare `TypeError: fetch failed` and a stack
3
+ // trace; this turns it into a line that names the backend and what to check. Backend URLs are
4
+ // printed without user:password, query or fragment, and text that came from the backend is stripped
5
+ // of terminal control characters.
6
+ import { promises as fs } from "node:fs";
7
+ import { BackendClientError } from "./backend-client.js";
8
+ import { redactUrl, redactUrlsIn, sanitizeForTerminal, shellQuote, withNext, } from "./cli-messages.js";
9
+ import { resolveWorkspacePath, WORKSPACE_CONFIG_FILE } from "./workspace.js";
10
+ /** The error code Node's fetch buries in `cause` (ECONNREFUSED, ENOTFOUND, ...), or the message when there is none. */
11
+ function networkReason(e) {
12
+ if (!(e instanceof Error))
13
+ return undefined;
14
+ const cause = e.cause;
15
+ const code = cause && typeof cause === "object" ? cause.code : undefined;
16
+ if (typeof code === "string")
17
+ return sanitizeForTerminal(code);
18
+ return e instanceof TypeError && /fetch failed/i.test(e.message) ? e.message : undefined;
19
+ }
20
+ /**
21
+ * The message for a backend failure, or `undefined` when `e` is not one (the caller rethrows it).
22
+ * `login` is the command that signs in, so its own failures point at itself.
23
+ */
24
+ export function explainBackendFailure(e, backendUrl, workspaceDir) {
25
+ const url = redactUrl(backendUrl);
26
+ const login = `docsxai login --backend-url ${shellQuote(url)}`;
27
+ const reason = networkReason(e);
28
+ if (reason !== undefined) {
29
+ return withNext(`cannot reach ${url} (${reason})`, `check backend_url in ${WORKSPACE_CONFIG_FILE} and that the backend is running, then ${login}`);
30
+ }
31
+ if (!(e instanceof BackendClientError))
32
+ return undefined;
33
+ // The message carries the start of the response body, which the backend controls, and can
34
+ // quote a URL with its credentials or query.
35
+ const message = sanitizeForTerminal(redactUrlsIn(e.message));
36
+ if (e.status === 401 || e.status === 403) {
37
+ const oauth = workspaceDir
38
+ ? ` (or add --oauth ${shellQuote(workspaceDir)} to sign in as a person)`
39
+ : "";
40
+ return withNext(`${message}\n why: ${url} rejected the token`, `${login}${oauth}`);
41
+ }
42
+ if (e.status === 404) {
43
+ return withNext(message, `check backend_workspace_id and backend_project_id in ${WORKSPACE_CONFIG_FILE}, or remove them and push again`);
44
+ }
45
+ if (e.status !== undefined && e.status >= 500) {
46
+ return withNext(`${message}\n why: ${url} failed on its side`, "check the backend's logs, then retry");
47
+ }
48
+ return message;
49
+ }
50
+ /** Why `.docsxai.json` did not load as a workspace config, as a phrase for parentheses. */
51
+ export async function configProblem(workspaceDir) {
52
+ let text;
53
+ try {
54
+ text = await fs.readFile(resolveWorkspacePath(workspaceDir, WORKSPACE_CONFIG_FILE), "utf8");
55
+ }
56
+ catch {
57
+ return "the file does not exist";
58
+ }
59
+ try {
60
+ JSON.parse(text);
61
+ }
62
+ catch (e) {
63
+ return `it is not valid JSON: ${e.message}`;
64
+ }
65
+ return 'its "schema" must be "docsxai/workspace@1"';
66
+ }
@@ -19,21 +19,18 @@ import { resolvePlugins } from "./plugins/runtime.js";
19
19
  import { launchPlaywrightSession } from "./playwright-driver.js";
20
20
  import { loadWorkspaceConfig, resolveWorkspacePath } from "./workspace.js";
21
21
  import { listFlowFiles, parseFlags } from "./cli-shared.js";
22
- import { USAGE } from "./cli-usage.js";
22
+ import { shellQuote, usageError, withNext } from "./cli-messages.js";
23
23
  export async function cmdInspect(args) {
24
24
  const { positionals, flags } = parseFlags(args);
25
25
  const workspaceDir = positionals[0];
26
- if (!workspaceDir) {
27
- process.stderr.write("inspect: missing <workspace-dir>\n\n" + USAGE + "\n");
28
- return 2;
29
- }
26
+ if (!workspaceDir)
27
+ return usageError("inspect", "missing <workspace-dir>");
30
28
  const wsCfg = await loadWorkspaceConfig(workspaceDir);
31
29
  const cdp = typeof flags.get("cdp") === "string" ? flags.get("cdp") : undefined;
32
30
  const explicitUrl = typeof flags.get("url") === "string" ? flags.get("url") : undefined;
33
31
  const url = explicitUrl ?? wsCfg?.app_url;
34
32
  if (!cdp && !url) {
35
- process.stderr.write("inspect: no URL — pass --url <url>, set app_url in .docsxai.json, or use --cdp <endpoint>\n");
36
- return 2;
33
+ return usageError("inspect", "no URL — pass --url <url>, set app_url in .docsxai.json, or use --cdp <endpoint>");
37
34
  }
38
35
  const selector = typeof flags.get("selector") === "string" ? flags.get("selector") : undefined;
39
36
  const headed = flags.get("headed") === true;
@@ -84,7 +81,10 @@ export async function cmdInspect(args) {
84
81
  try {
85
82
  // In CDP-attach mode without an explicit --url, inspect whatever the attached browser already has open.
86
83
  if (url && (!cdp || explicitUrl))
87
- await session.page.goto(url, { waitUntil: "domcontentloaded" }).catch(() => undefined);
84
+ await session.page.goto(url, { waitUntil: "domcontentloaded" }).catch((e) => {
85
+ const why = e.message.split("\n")[0];
86
+ process.stderr.write(`inspect: warning — could not load ${url}: ${why}; is the app running?\n`);
87
+ });
88
88
  if (waitForSel)
89
89
  await session.page.waitForSelector(waitForSel, { timeout: 30_000 }).catch(() => undefined);
90
90
  else if (waitMs > 0)
@@ -135,16 +135,13 @@ export async function cmdInspect(args) {
135
135
  }
136
136
  export async function cmdLint(args) {
137
137
  const { positionals, flags } = parseFlags(args);
138
- if (!positionals[0]) {
139
- process.stderr.write(`lint: missing <workspace-dir>\n`);
140
- return 2;
141
- }
138
+ if (!positionals[0])
139
+ return usageError("lint", "missing <workspace-dir>");
142
140
  const projectDir = positionals[0];
143
141
  const flowFilter = typeof flags.get("flow") === "string" ? flags.get("flow") : undefined;
144
142
  const format = typeof flags.get("format") === "string" ? flags.get("format") : "text";
145
143
  if (format !== "text" && format !== "json") {
146
- process.stderr.write(`lint: --format must be "text" or "json"\n`);
147
- return 2;
144
+ return usageError("lint", '--format must be "text" or "json"');
148
145
  }
149
146
  let flowPaths;
150
147
  try {
@@ -163,7 +160,7 @@ export async function cmdLint(args) {
163
160
  }
164
161
  catch (e) {
165
162
  const msg = e instanceof FlowFileError ? e.message : e.message;
166
- process.stderr.write(`lint: parse error in ${p}: ${msg}\n`);
163
+ process.stderr.write(`lint: ${withNext(`parse error in ${p}: ${msg}`, `fix the flow-file, then docsxai lint ${shellQuote(projectDir)}`)}\n`);
167
164
  return 1;
168
165
  }
169
166
  }
@@ -173,8 +170,8 @@ export async function cmdLint(args) {
173
170
  : []
174
171
  : Array.from(flowsByName.values());
175
172
  if (flowFilter && targets.length === 0) {
176
- process.stderr.write(`lint: flow not found: ${flowFilter}\n`);
177
- return 2;
173
+ const known = [...flowsByName.keys()].join(", ") || "none";
174
+ return usageError("lint", `flow not found: ${flowFilter} (flows: ${known})`);
178
175
  }
179
176
  const loadFlow = (name) => {
180
177
  const f = flowsByName.get(name);
@@ -217,15 +214,12 @@ export async function cmdLint(args) {
217
214
  }
218
215
  export async function cmdFlowTree(args) {
219
216
  const { positionals, flags } = parseFlags(args);
220
- if (!positionals[0]) {
221
- process.stderr.write(`flow-tree: missing <workspace-dir>\n`);
222
- return 2;
223
- }
217
+ if (!positionals[0])
218
+ return usageError("flow-tree", "missing <workspace-dir>");
224
219
  const projectDir = positionals[0];
225
220
  const format = typeof flags.get("format") === "string" ? flags.get("format") : "text";
226
221
  if (format !== "text" && format !== "json") {
227
- process.stderr.write(`flow-tree: --format must be "text" or "json"\n`);
228
- return 2;
222
+ return usageError("flow-tree", '--format must be "text" or "json"');
229
223
  }
230
224
  let flowPaths;
231
225
  try {
@@ -244,7 +238,7 @@ export async function cmdFlowTree(args) {
244
238
  }
245
239
  catch (e) {
246
240
  const msg = e instanceof FlowFileError ? e.message : e.message;
247
- process.stderr.write(`flow-tree: parse error in ${p}: ${msg}\n`);
241
+ process.stderr.write(`flow-tree: ${withNext(`parse error in ${p}: ${msg}`, `fix the flow-file, then docsxai flow-tree ${shellQuote(projectDir)}`)}\n`);
248
242
  return 1;
249
243
  }
250
244
  }
@@ -259,27 +253,20 @@ export async function cmdFlowTree(args) {
259
253
  }
260
254
  export async function cmdDiagnose(args) {
261
255
  const { positionals, flags } = parseFlags(args);
262
- if (!positionals[0]) {
263
- process.stderr.write(`diagnose: missing <workspace-dir>\n`);
264
- return 2;
265
- }
256
+ if (!positionals[0])
257
+ return usageError("diagnose", "missing <workspace-dir>");
266
258
  const projectDir = positionals[0];
267
259
  const flowName = typeof flags.get("flow") === "string" ? flags.get("flow") : undefined;
268
260
  const stepId = typeof flags.get("step") === "string" ? flags.get("step") : undefined;
269
261
  const cdpEndpoint = typeof flags.get("cdp") === "string" ? flags.get("cdp") : undefined;
270
262
  const variantFlag = typeof flags.get("variant") === "string" ? flags.get("variant") : undefined;
271
263
  const format = typeof flags.get("format") === "string" ? flags.get("format") : "text";
272
- if (!flowName) {
273
- process.stderr.write(`diagnose: --flow <name> required\n`);
274
- return 2;
275
- }
276
- if (!stepId) {
277
- process.stderr.write(`diagnose: --step <step-id> required\n`);
278
- return 2;
279
- }
264
+ if (!flowName)
265
+ return usageError("diagnose", "--flow <name> required");
266
+ if (!stepId)
267
+ return usageError("diagnose", "--step <step-id> required");
280
268
  if (format !== "text" && format !== "json") {
281
- process.stderr.write(`diagnose: --format must be "text" or "json"\n`);
282
- return 2;
269
+ return usageError("diagnose", '--format must be "text" or "json"');
283
270
  }
284
271
  // Load the flow (resolving `extends` so step lookup works against the merged step list).
285
272
  const loadFlowFile = async (name) => {
@@ -289,7 +276,7 @@ export async function cmdDiagnose(args) {
289
276
  text = await fs.readFile(fp, "utf8");
290
277
  }
291
278
  catch {
292
- throw new FlowFileError(`no flow named "${name}" at ${fp}`);
279
+ throw new FlowFileError(withNext(`no flow named "${name}" at ${fp}`, `docsxai flow-tree ${shellQuote(projectDir)} (lists the flows)`));
293
280
  }
294
281
  return parseFlowFile(text, fp);
295
282
  };
@@ -355,7 +342,10 @@ export async function cmdDiagnose(args) {
355
342
  });
356
343
  }
357
344
  catch (e) {
358
- process.stderr.write(`diagnose: live probe failed: ${e.message}\n`);
345
+ const hint = cdpEndpoint
346
+ ? withNext("", `check Chrome is running with --remote-debugging-port and --cdp ${shellQuote(cdpEndpoint)} points at it, or drop --cdp`)
347
+ : "";
348
+ process.stderr.write(`diagnose: live probe failed: ${e.message}${hint}\n`);
359
349
  return 1;
360
350
  }
361
351
  finally {
@@ -372,16 +362,13 @@ export async function cmdDiagnose(args) {
372
362
  }
373
363
  export async function cmdStyle(args) {
374
364
  const { positionals, flags } = parseFlags(args);
375
- if (!positionals[0]) {
376
- process.stderr.write(`style: missing <workspace-dir>\n`);
377
- return 2;
378
- }
365
+ if (!positionals[0])
366
+ return usageError("style", "missing <workspace-dir>");
379
367
  const projectDir = positionals[0];
380
368
  const check = flags.get("check") === true;
381
369
  const format = typeof flags.get("format") === "string" ? flags.get("format") : "text";
382
370
  if (format !== "text" && format !== "json") {
383
- process.stderr.write(`style: --format must be "text" or "json"\n`);
384
- return 2;
371
+ return usageError("style", '--format must be "text" or "json"');
385
372
  }
386
373
  // init-if-absent (idempotent); then load + validate; then rederive JSON; then optional jargon check.
387
374
  const { created } = await initStyleIfAbsent(projectDir);
@@ -391,7 +378,7 @@ export async function cmdStyle(args) {
391
378
  }
392
379
  catch (e) {
393
380
  if (e instanceof StyleError) {
394
- process.stderr.write(`style: ${e.message}\n`);
381
+ process.stderr.write(`style: ${withNext(e.message, `fix docs/style.yaml, then docsxai style ${shellQuote(projectDir)}`)}\n`);
395
382
  return 1;
396
383
  }
397
384
  throw e;
@@ -6,17 +6,18 @@
6
6
  // plugins — forwards to plugins-cli (list | info | sync over the plugin runtime; no plugin code runs)
7
7
  import { promises as fs } from "node:fs";
8
8
  import * as path from "node:path";
9
- import { BackendClient, BackendClientError, createBackendClient, oauthLogin, saveBackendTokenFile, } from "./backend-client.js";
9
+ import { BackendClient, createBackendClient, oauthLogin, saveBackendTokenFile, } from "./backend-client.js";
10
10
  import { fetchScreenshotBlobs, readDocPack, UnsafePackNameError, uploadScreenshotBlobs, writeDocPack, } from "./doc-pack-io.js";
11
11
  import { pluginsCli } from "./plugins-cli.js";
12
12
  import { loadWorkspaceConfig, resolveWorkspacePath } from "./workspace.js";
13
13
  import { parseFlags } from "./cli-shared.js";
14
+ import { configProblem, explainBackendFailure } from "./cli-backend-errors.js";
15
+ import { redactUrl, sanitizeForTerminal, shellQuote, usageError, withNext, } from "./cli-messages.js";
14
16
  export async function cmdLogin(args) {
15
17
  const { positionals, flags } = parseFlags(args);
16
18
  const backendUrl = typeof flags.get("backend-url") === "string" ? flags.get("backend-url") : undefined;
17
19
  if (!backendUrl) {
18
- process.stderr.write(`login: --backend-url <url> required\n`);
19
- return 2;
20
+ return usageError("login", "--backend-url <url> required");
20
21
  }
21
22
  const oauthFlag = flags.get("oauth");
22
23
  if (oauthFlag !== undefined) {
@@ -26,8 +27,7 @@ export async function cmdLogin(args) {
26
27
  // from the positional.
27
28
  const workspaceDir = typeof oauthFlag === "string" ? oauthFlag : positionals[0];
28
29
  if (!workspaceDir) {
29
- process.stderr.write(`login: --oauth requires a <workspace-dir> (tokens are stored at <workspace>/.auth/backend-token.json)\n`);
30
- return 2;
30
+ return usageError("login", "--oauth requires a <workspace-dir> (tokens are stored at <workspace>/.auth/backend-token.json)");
31
31
  }
32
32
  try {
33
33
  const tokens = await oauthLogin({
@@ -41,12 +41,14 @@ export async function cmdLogin(args) {
41
41
  return 0;
42
42
  }
43
43
  catch (e) {
44
- process.stderr.write(`login: ${e.message}\n`);
44
+ const text = explainBackendFailure(e, backendUrl) ?? sanitizeForTerminal(e.message);
45
+ process.stderr.write(`login: ${text}\n`);
45
46
  return 1;
46
47
  }
47
48
  }
48
49
  if (!process.env.DOCSX_TOKEN) {
49
- process.stderr.write(`login: DOCSX_TOKEN env var not set. Export it before running: DOCSX_TOKEN=<token> docsxai login --backend-url ${backendUrl}\n`);
50
+ const next = `DOCSX_TOKEN=<token> docsxai login --backend-url ${shellQuote(redactUrl(backendUrl))} (or add --oauth <workspace-dir> to sign in as a person)`;
51
+ process.stderr.write(`login: ${withNext("DOCSX_TOKEN env var not set", next)}\n`);
50
52
  return 2;
51
53
  }
52
54
  let client;
@@ -54,25 +56,26 @@ export async function cmdLogin(args) {
54
56
  client = new BackendClient({ baseUrl: backendUrl });
55
57
  }
56
58
  catch (e) {
57
- process.stderr.write(`login: ${e.message}\n`);
59
+ process.stderr.write(`login: ${sanitizeForTerminal(e.message)}\n`);
58
60
  return 1;
59
61
  }
60
62
  try {
61
63
  const h = await client.health();
62
64
  if (!h.ok) {
63
- process.stderr.write(`login: backend health-check returned ok=false\n`);
65
+ const note = withNext(`backend health-check at ${redactUrl(backendUrl)} returned ok=false`, "check the backend's logs, then retry");
66
+ process.stderr.write(`login: ${note}\n`);
64
67
  return 1;
65
68
  }
66
69
  const wss = await client.listWorkspaces();
67
- process.stdout.write(`login: ok. ${wss.length} workspace${wss.length !== 1 ? "s" : ""} visible at ${backendUrl}\n`);
70
+ process.stdout.write(`login: ok. ${wss.length} workspace${wss.length !== 1 ? "s" : ""} visible at ${redactUrl(backendUrl)}\n`);
68
71
  return 0;
69
72
  }
70
73
  catch (e) {
71
- if (e instanceof BackendClientError) {
72
- process.stderr.write(`login: ${e.message}\n`);
73
- return 1;
74
- }
75
- throw e;
74
+ const text = explainBackendFailure(e, backendUrl);
75
+ if (text === undefined)
76
+ throw e;
77
+ process.stderr.write(`login: ${text}\n`);
78
+ return 1;
76
79
  }
77
80
  }
78
81
  /** Ensure the workspace has a backend workspace + project to push to; create them on first push. */
@@ -94,20 +97,20 @@ async function ensureBackendBinding(client, projectDir, cfg, workspaceName) {
94
97
  }
95
98
  export async function cmdPush(args) {
96
99
  const { positionals, flags } = parseFlags(args);
97
- if (!positionals[0]) {
98
- process.stderr.write(`push: missing <workspace-dir>\n`);
99
- return 2;
100
- }
100
+ if (!positionals[0])
101
+ return usageError("push", "missing <workspace-dir>");
101
102
  const projectDir = positionals[0];
102
103
  const wsCfg = await loadWorkspaceConfig(projectDir);
103
104
  if (!wsCfg?.backend_url) {
104
- process.stderr.write(`push: no backend_url in ${path.join(projectDir, ".docsxai.json")}. Set it before pushing.\n`);
105
+ const file = path.join(projectDir, ".docsxai.json");
106
+ const why = wsCfg ? "" : ` (${await configProblem(projectDir)})`;
107
+ const next = 'add "backend_url": "<url>" to it, then docsxai login --backend-url <url>';
108
+ process.stderr.write(`push: ${withNext(`no backend_url in ${file}${why}`, next)}\n`);
105
109
  return 2;
106
110
  }
107
111
  const kindArg = typeof flags.get("kind") === "string" ? flags.get("kind") : "calibrate";
108
112
  if (kindArg !== "calibrate" && kindArg !== "run" && kindArg !== "edit") {
109
- process.stderr.write(`push: --kind must be calibrate | run | edit (got "${kindArg}")\n`);
110
- return 2;
113
+ return usageError("push", `--kind must be calibrate | run | edit (got "${kindArg}")`);
111
114
  }
112
115
  const author = (typeof flags.get("author") === "string" ? flags.get("author") : null) ??
113
116
  process.env.USER ??
@@ -117,7 +120,7 @@ export async function cmdPush(args) {
117
120
  client = await createBackendClient({ baseUrl: wsCfg.backend_url, workspaceDir: projectDir });
118
121
  }
119
122
  catch (e) {
120
- process.stderr.write(`push: ${e.message}\n`);
123
+ process.stderr.write(`push: ${sanitizeForTerminal(e.message)}\n`);
121
124
  return 1;
122
125
  }
123
126
  try {
@@ -150,27 +153,29 @@ export async function cmdPush(args) {
150
153
  pushed++;
151
154
  }
152
155
  await client.finalizeRevision(binding.wsId, binding.projectId, rev.id);
153
- process.stdout.write(`push: revision ${rev.id} (${kindArg}, ${author}) — ${pushed} artifact slot${pushed !== 1 ? "s" : ""} uploaded, finalized\n`);
156
+ process.stdout.write(`push: revision ${sanitizeForTerminal(rev.id)} (${kindArg}, ${sanitizeForTerminal(author)}) on ${redactUrl(wsCfg.backend_url)} — ${pushed} artifact slot${pushed !== 1 ? "s" : ""} uploaded, finalized\n`);
154
157
  return 0;
155
158
  }
156
159
  catch (e) {
157
- if (e instanceof BackendClientError) {
158
- process.stderr.write(`push: ${e.message}\n`);
159
- return 1;
160
- }
161
- throw e;
160
+ const text = explainBackendFailure(e, wsCfg.backend_url, projectDir);
161
+ if (text === undefined)
162
+ throw e;
163
+ process.stderr.write(`push: ${text}\n`);
164
+ return 1;
162
165
  }
163
166
  }
164
167
  export async function cmdPull(args) {
165
168
  const { positionals, flags } = parseFlags(args);
166
- if (!positionals[0]) {
167
- process.stderr.write(`pull: missing <workspace-dir>\n`);
168
- return 2;
169
- }
169
+ if (!positionals[0])
170
+ return usageError("pull", "missing <workspace-dir>");
170
171
  const projectDir = positionals[0];
171
172
  const wsCfg = await loadWorkspaceConfig(projectDir);
172
173
  if (!wsCfg?.backend_url || !wsCfg.backend_workspace_id || !wsCfg.backend_project_id) {
173
- process.stderr.write(`pull: workspace isn't bound to a backend yet. Run \`push\` first (or hand-edit .docsxai.json's backend_workspace_id / backend_project_id).\n`);
174
+ const gap = wsCfg
175
+ ? "backend_url, backend_workspace_id and backend_project_id are all needed"
176
+ : await configProblem(projectDir);
177
+ const next = `docsxai push ${shellQuote(projectDir)} (binds it on the first push), or set the three keys in .docsxai.json`;
178
+ process.stderr.write(`pull: ${withNext(`workspace isn't bound to a backend yet (${gap})`, next)}\n`);
174
179
  return 2;
175
180
  }
176
181
  const revArg = typeof flags.get("rev") === "string" ? flags.get("rev") : "head";
@@ -179,7 +184,7 @@ export async function cmdPull(args) {
179
184
  client = await createBackendClient({ baseUrl: wsCfg.backend_url, workspaceDir: projectDir });
180
185
  }
181
186
  catch (e) {
182
- process.stderr.write(`pull: ${e.message}\n`);
187
+ process.stderr.write(`pull: ${sanitizeForTerminal(e.message)}\n`);
183
188
  return 1;
184
189
  }
185
190
  try {
@@ -194,15 +199,17 @@ export async function cmdPull(args) {
194
199
  ? await fetchScreenshotBlobs(payloads.screenshots, client)
195
200
  : undefined;
196
201
  const r = await writeDocPack(projectDir, payloads, screenshotBytes ? { screenshotBytes } : {});
197
- process.stdout.write(`pull: revision ${rev.id} (${rev.kind}, ${rev.author}) — wrote ${r.filesWritten} file(s)\n`);
202
+ process.stdout.write(`pull: revision ${sanitizeForTerminal(rev.id)} (${sanitizeForTerminal(rev.kind)}, ${sanitizeForTerminal(rev.author)}) — wrote ${r.filesWritten} file(s) to ${sanitizeForTerminal(projectDir)}\n`);
198
203
  return 0;
199
204
  }
200
205
  catch (e) {
201
- if (e instanceof BackendClientError || e instanceof UnsafePackNameError) {
202
- process.stderr.write(`pull: ${e.message}\n`);
203
- return 1;
204
- }
205
- throw e;
206
+ const text = e instanceof UnsafePackNameError
207
+ ? withNext(`${sanitizeForTerminal(e.message)}\n why: the revision names a file a workspace would not produce; nothing was written`, `docsxai pull ${shellQuote(projectDir)} --rev <older-revision-id>`)
208
+ : explainBackendFailure(e, wsCfg.backend_url, projectDir);
209
+ if (text === undefined)
210
+ throw e;
211
+ process.stderr.write(`pull: ${text}\n`);
212
+ return 1;
206
213
  }
207
214
  }
208
215
  /** `docsxai plugins …` — forwards to the plugin-runtime CLI verbatim. */