@clipy/cli 0.16.1 → 0.18.0

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/dist/index.js CHANGED
@@ -13,7 +13,7 @@
13
13
  * override the stored key. Read-only unless the key carries the "ingest" scope.
14
14
  */
15
15
  import { parseArgs } from "node:util";
16
- import { appendFileSync, closeSync, copyFileSync, cpSync, createWriteStream, existsSync, mkdirSync, openSync, readdirSync, readFileSync, readSync, realpathSync, renameSync, rmSync, statSync, writeFileSync, chmodSync } from "node:fs";
16
+ import { appendFileSync, closeSync, copyFileSync, cpSync, createWriteStream, existsSync, mkdirSync, mkdtempSync, openSync, readdirSync, readFileSync, readSync, realpathSync, renameSync, rmSync, statSync, writeFileSync, chmodSync } from "node:fs";
17
17
  import { homedir, tmpdir } from "node:os";
18
18
  import { basename, dirname, extname, isAbsolute, join, relative, resolve } from "node:path";
19
19
  import { createInterface } from "node:readline";
@@ -30,14 +30,17 @@ import { attachCdpDiagnostics } from "./cdpDiagnostics.js";
30
30
  import { SETUP_TARGETS, detectSetupTarget, isSetupTarget, registerMcpServer, renderSetupBox, shortPath, skillPathFor as setupSkillPathFor, } from "./setup.js";
31
31
  import { APP_NAME as CHROME_FOR_CLIPY_APP_NAME, appBundlePath as chromeForClipyAppPath, chromeStatus, DEFAULT_CDP_PORT, installApp as installChromeForClipyApp, startChrome as startChromeForClipy, startChromeForClipyCapture, markExtensionRecording, ownershipProbeStatus as chromeOwnershipProbeStatus, resolveChromeBinary, stopChrome as stopChromeForClipy, TAB_CAPTURE_TITLE_MARKER, } from "./chromeForClipy.js";
32
32
  import { ExtensionRecordingEndedError, abortExtensionRecording, ExtensionAlreadyUploadedError, extensionReadiness, extensionRecordingStatus, extensionStoreUrl, openTabForPerson, sendExtensionMark, startExtensionRecording, stopExtensionRecording, } from "./chromeExtensionCapture.js";
33
- import { browserLogin, shouldUseManualLogin } from "./browserLogin.js";
33
+ import { browserLogin, LOGIN_SCOPES, shouldUseManualLogin } from "./browserLogin.js";
34
34
  import { openUrl } from "./openUrl.js";
35
35
  import { cmdContextImport } from "./context/importCmd.js";
36
36
  import { cmdContextRead } from "./context/readCmd.js";
37
37
  import { errorEnvelope } from "./context/errors.js";
38
38
  import { supportsWebp } from "./context/ffmpeg.js";
39
39
  import { renderProofFrames } from "./proofFrames.js";
40
+ import { cmdAnalytics, cmdComment, cmdComments, cmdDelete, cmdDiagnostics, cmdFolders, cmdInteractions, cmdOrganize, cmdShare, cmdUpdate, failure, } from "./library.js";
40
41
  import { waitForAgentContext } from "./agentReadiness.js";
42
+ import { cmdRecheck } from "./recheckCmd.js";
43
+ import { RECHECK_MAX_STEPS } from "./recheck.js";
41
44
  import { BridgeUnavailableError, bridgeRequest, inspectBridge, listSources, readBridgeInfo, resolveCaptureSource, windowLabel, probeSocketOpenable, probeBridgeHandshake, bridgeInfoFromFile, bridgeAppOutdated, MIN_BRIDGE_APP_VERSION, describeWindow, describeDisplay, resolveFromSources, } from "./macBridge.js";
42
45
  import { defaultDisplay, describeCaps, ffmpegCaps, isWaylandSession, listLinuxSources, orphanedCaptureProcesses, parseDisplaySize, realRunner, startScreenRecorder, startVirtualDisplay, } from "./linuxScreen.js";
43
46
  // Exit quietly when stdout/stderr close early (e.g. `clipy list | head`).
@@ -239,6 +242,75 @@ function normalizeId(input, ctx) {
239
242
  // ---------------------------------------------------------------------------
240
243
  // Output helpers
241
244
  // ---------------------------------------------------------------------------
245
+ /** The helpers library.ts commands need, bound to this invocation. */
246
+ function libraryDeps(ctx, json) {
247
+ return {
248
+ apiUrl: ctx.apiUrl,
249
+ apiKey: ctx.apiKey,
250
+ version: VERSION,
251
+ json,
252
+ normalizeId: (input) => normalizeId(input, ctx),
253
+ die,
254
+ printJson,
255
+ color: c,
256
+ };
257
+ }
258
+ /** `clipy recheck`: the library helpers plus Playwright and the proof upload. */
259
+ function recheckDeps(ctx, json) {
260
+ return {
261
+ ...libraryDeps(ctx, json),
262
+ loadChromium: async () => (await loadChromium()),
263
+ uploadFrames: (frames, meta) => uploadRecheckFrames(ctx, frames, meta),
264
+ };
265
+ }
266
+ /** The same path as `clipy proof --frame`: one held frame per step, the step
267
+ * result as its timed caption. */
268
+ async function uploadRecheckFrames(ctx, frames, meta) {
269
+ requireKey(ctx);
270
+ const holdSeconds = 3;
271
+ // Private (mkdtemp is 0700): the video is made of screenshots of a
272
+ // signed-in app. Removed on success, failure and Ctrl-C alike.
273
+ const tmpDir = mkdtempSync(join(tmpdir(), "clipy-recheck-upload-"));
274
+ const onSignal = (signal) => {
275
+ rmSync(tmpDir, { recursive: true, force: true });
276
+ process.exit(signal === "SIGINT" ? 130 : 143);
277
+ };
278
+ process.once("SIGINT", onSignal);
279
+ process.once("SIGTERM", onSignal);
280
+ try {
281
+ const videoPath = join(tmpDir, "recheck.mp4");
282
+ meta.log(`assembling ${frames.length} step frame${frames.length === 1 ? "" : "s"}…`);
283
+ await renderProofFrames({
284
+ framePaths: frames.map((f) => f.path),
285
+ outputPath: videoPath,
286
+ holdSeconds,
287
+ width: 1280,
288
+ height: 720,
289
+ notify: meta.log,
290
+ });
291
+ const notes = frames.map((f, i) => ({
292
+ startMs: Math.round(i * holdSeconds * 1000),
293
+ endMs: Math.round((i + 1) * holdSeconds * 1000),
294
+ text: f.caption,
295
+ }));
296
+ const uploaded = await uploadVideoToClipy(ctx, {
297
+ videoPath,
298
+ name: meta.name,
299
+ nameIsUserProvided: true,
300
+ description: meta.description,
301
+ narration: { notes },
302
+ // The server maps the cli-proof/ prefix to the CLI source platform.
303
+ sourceVersion: `cli-proof/${VERSION}`,
304
+ log: meta.log,
305
+ });
306
+ return { id: uploaded.publicId, shareUrl: uploaded.shareUrl, contextUrl: uploaded.contextUrl };
307
+ }
308
+ finally {
309
+ process.off("SIGINT", onSignal);
310
+ process.off("SIGTERM", onSignal);
311
+ rmSync(tmpDir, { recursive: true, force: true });
312
+ }
313
+ }
242
314
  function printJson(data) {
243
315
  process.stdout.write(`${JSON.stringify(data, null, 2)}\n`);
244
316
  }
@@ -303,6 +375,7 @@ ${c.bold("AUTH")}
303
375
  login --no-browser Copy-code flow for SSH/headless: open the URL anywhere, paste the code back
304
376
  login --key <clipy_sk_live_…> Skip the browser: store a key you pasted
305
377
  login --paste Prompt for a pasted key instead of the browser
378
+ login --allow-delete Also allow \`clipy delete\` (permanent; off by default)
306
379
  logout Delete the stored key
307
380
  whoami Check which key is active and that it works
308
381
 
@@ -345,6 +418,51 @@ ${c.bold("RECORDINGS")}
345
418
  open <id> Open the share page in your browser
346
419
  wait <id> [--for transcript|summary|both] [--timeout <sec>]
347
420
  Block until processing artifacts are ready
421
+ upload <file> [--title <t>] [--type kind] [--access mode] [--note '12: text']…
422
+ Upload an existing WebM, MP4 or MOV file to
423
+ your library (needs "ingest"). --wait, --json
424
+
425
+ ${c.bold("MANAGE")} ${c.dim("(needs recordings:write; comments needs comments:read, comment comments:write, analytics analytics:read)")}
426
+ update <id> [--title <t>] [--description <d> | --clear-description] [--expected <text>]
427
+ Rename a recording or edit its description
428
+ share <id> [public|restricted|private]
429
+ Show or change who can open the share link
430
+ organize <id> [--folder <name|id> | --no-folder] [--tag <t>]… [--untag <t>]…
431
+ File into a folder and add or remove tags
432
+ folders [--create <name>] List folders (with ids), or create one
433
+ comments <id> [--json] The comment thread, with timestamps
434
+ comment <id> "<text>" [--at <sec> | --reply-to <comment-id>]
435
+ Comment at a moment, or reply, as you
436
+ analytics <id> [--range <days>] Lifetime views, unique viewers, completion,
437
+ who watched (detail is Pro); --range sets
438
+ the days in the daily series
439
+ delete <id> --yes Permanently delete a recording. Needs a key
440
+ from \`clipy login --allow-delete\`
441
+
442
+ ${c.bold("BUG EVIDENCE")} ${c.dim("(captured by the Chrome extension's bug capture, or browsers Clipy drives)")}
443
+ diagnostics <id> [--errors] [--console] [--network] [--json]
444
+ Console logs, uncaught errors, network
445
+ requests and the browser/OS/viewport of a
446
+ recording. Alias: logs
447
+ --errors Only what went wrong: console errors, exceptions, failed
448
+ requests (combine with --console or --network to narrow)
449
+ --levels <l,…> Console levels: debug, info, log, warn, error
450
+ --status <s> Network status: 5xx, 4xx, 404, failed
451
+ --method/--host Narrow network requests
452
+ --bodies <b> Request/response bodies: none, errors, all
453
+ --limit/--after Page through long captures (max 500 per page)
454
+ interactions <id> [--types click,dwell,…] [--from-ms N] [--to-ms N]
455
+ Clicks, scrolls, typing and pauses with
456
+ the element labels and frame evidence;
457
+ page with --cursor <nextCursor>
458
+ recheck <id> --url <start-url> [--plan] [--no-upload] [--out <dir>]
459
+ Replay a recorded workflow in Chrome for
460
+ Clipy and report each step: matched,
461
+ control not found, different screen, error
462
+ or could not map. --plan lists the steps only.
463
+ Irreversible-looking controls (delete, pay,
464
+ send) are not clicked without
465
+ --allow-destructive
348
466
 
349
467
  ${c.bold("PROOF")} ${c.dim("(tool-neutral evidence; needs an ingest-scoped API key)")}
350
468
  proof --frame <png|jpg|webp> [--frame <image> ...]
@@ -555,10 +673,10 @@ async function cmdLogin(ctx, opts) {
555
673
  // --no-browser, SSH sessions, and display-less Linux take the copy-code
556
674
  // flow: this machine can't receive the loopback redirect (or can't open a
557
675
  // browser at all), so the approval page shows a code to paste back here.
558
- await loginWithBrowser(ctx, opts.noBrowser || shouldUseManualLogin());
676
+ await loginWithBrowser(ctx, opts.noBrowser || shouldUseManualLogin(), opts.allowDelete ? [...LOGIN_SCOPES, "recordings:delete"] : undefined);
559
677
  }
560
678
  /** Browser-approve flow (the default): open clipy.online, approve, store. */
561
- async function loginWithBrowser(ctx, manual) {
679
+ async function loginWithBrowser(ctx, manual, scopes) {
562
680
  process.stderr.write(`${c.dim(manual ? "approve this device from a browser on any machine…" : "opening your browser to approve this device…")}\n`);
563
681
  let result;
564
682
  try {
@@ -566,6 +684,7 @@ async function loginWithBrowser(ctx, manual) {
566
684
  apiUrl: ctx.apiUrl,
567
685
  log: (m) => process.stderr.write(`${m}\n`),
568
686
  manual,
687
+ scopes,
569
688
  promptCode: manual
570
689
  ? () => promptVisible("Paste the approval code shown in the browser: ")
571
690
  : undefined,
@@ -1630,14 +1749,15 @@ async function ingestPostJson(ctx, path, payload) {
1630
1749
  }
1631
1750
  if (!res.ok) {
1632
1751
  const msg = (typeof body.error === "string" && body.error) || `Clipy API error ${res.status}`;
1752
+ const code = typeof body.code === "string" ? body.code : undefined;
1633
1753
  if (res.status === 401) {
1634
- throw ingestError(`${msg}. Run \`clipy login\` with an ingest-scoped key.`, res.status);
1754
+ throw ingestError(`${msg}. Run \`clipy login\` with an ingest-scoped key.`, res.status, code);
1635
1755
  }
1636
1756
  if (res.status === 403) {
1637
1757
  throw ingestError(`${msg}\nYour API key needs the "ingest" permission. Mint one at ` +
1638
- `${ctx.apiUrl}/settings/api-keys (check "Record & upload").`, res.status);
1758
+ `${ctx.apiUrl}/settings/api-keys (check "Record & upload").`, res.status, code);
1639
1759
  }
1640
- throw ingestError(msg, res.status);
1760
+ throw ingestError(msg, res.status, code);
1641
1761
  }
1642
1762
  return body;
1643
1763
  }
@@ -1645,8 +1765,22 @@ async function ingestPostJson(ctx, path, payload) {
1645
1765
  }
1646
1766
  // Error with the HTTP status attached so callers can branch on it (e.g. the
1647
1767
  // best-effort read receipt treats owner-scope 404 as "not mine", not a failure).
1648
- function ingestError(message, status) {
1649
- return Object.assign(new Error(message), { status });
1768
+ function ingestError(message, status, code) {
1769
+ return Object.assign(new Error(message), { status, ...(code ? { code } : {}) });
1770
+ }
1771
+ /**
1772
+ * Whether a failed /complete may have committed unseen: no HTTP response at
1773
+ * all (network error, timeout), or a 502/504 from the gateway in front of the
1774
+ * app. Every answer the route itself gives (503 access_mode_pending, a 500
1775
+ * that marked the recording failed) is explicit and never a success.
1776
+ */
1777
+ /** /complete answers that mean the recording exists or is being committed. */
1778
+ const PENDING_COMPLETION_CODES = new Set(["access_mode_pending", "queue_pending", "claim_pending"]);
1779
+ function completionWasAmbiguous(error) {
1780
+ const { status, code } = error;
1781
+ if (typeof status !== "number")
1782
+ return true;
1783
+ return !code && (status === 502 || status === 504);
1650
1784
  }
1651
1785
  /** Upload one chunk as multipart/form-data, retrying transient 429/5xx. */
1652
1786
  async function ingestPostChunk(ctx, recordingId, uploadToken, partNumber, bytes, container = "webm") {
@@ -2022,13 +2156,12 @@ async function uploadVideoToClipy(ctx, opts) {
2022
2156
  let publicId = "";
2023
2157
  try {
2024
2158
  // 1) initiate → uploadToken + the video row (createVideoRow so the share
2025
- // link exists immediately). The existing CLI/raw-upload contract uses
2026
- // sourcePlatform "web"; sourceVersion carries `cli-proof/*` provenance
2027
- // until the backend grows provider-specific source metadata.
2159
+ // link exists immediately). Servers that predate "cli" store "web" and
2160
+ // the sourceVersion prefix (`cli/`, `cli-proof/`) still identifies us.
2028
2161
  const init = await ingestPostJson(ctx, "/api/videos/raw-upload/initiate", {
2029
2162
  recordingId,
2030
2163
  createVideoRow: true,
2031
- sourcePlatform: "web",
2164
+ sourcePlatform: "cli",
2032
2165
  sourceVersion,
2033
2166
  });
2034
2167
  uploadToken = String(init.uploadToken ?? "");
@@ -2075,9 +2208,12 @@ async function uploadVideoToClipy(ctx, opts) {
2075
2208
  uploadToken,
2076
2209
  name: opts.name,
2077
2210
  description: opts.description,
2078
- sourcePlatform: "web",
2211
+ sourcePlatform: "cli",
2079
2212
  sourceVersion,
2213
+ ...(opts.accessMode ? { accessMode: opts.accessMode } : {}),
2214
+ ...(opts.nameIsUserProvided && opts.name ? { nameIsUserProvided: true } : {}),
2080
2215
  ...(opts.recordingKind ? { recordingKind: opts.recordingKind } : {}),
2216
+ ...(opts.expectedResult ? { expectedResult: opts.expectedResult } : {}),
2081
2217
  ...(opts.narration && (opts.narration.text || opts.narration.notes?.length)
2082
2218
  ? { narration: opts.narration }
2083
2219
  : {}),
@@ -2104,10 +2240,33 @@ async function uploadVideoToClipy(ctx, opts) {
2104
2240
  catch (e) {
2105
2241
  // Best-effort: release the half-uploaded streaming session so it doesn't
2106
2242
  // sit as an orphan (the server also janitors orphans after 8 days).
2243
+ // A /complete whose responses were all lost may still have committed;
2244
+ // the server then refuses the abort with 409 already_attached, which
2245
+ // proves the recording exists. Reporting failure would invite a duplicate.
2246
+ // An explicit answer from the route (503 access_mode_pending, queue_pending,
2247
+ // claim_pending) is not a success, but the recording exists: the error
2248
+ // names it so the caller never uploads the file again.
2249
+ // A coded pending answer already says the recording exists or is being
2250
+ // committed: name it directly, without depending on an abort that could
2251
+ // itself fail, and without aborting a commit still in flight.
2252
+ const pendingCode = e.code;
2253
+ if (publicId && pendingCode && PENDING_COMPLETION_CODES.has(pendingCode)) {
2254
+ throw Object.assign(e, { publicId });
2255
+ }
2256
+ let attached = false;
2107
2257
  if (uploadToken) {
2108
- await ingestPostJson(ctx, "/api/videos/raw-upload/abort", { recordingId, uploadToken }).catch(() => { });
2258
+ await ingestPostJson(ctx, "/api/videos/raw-upload/abort", { recordingId, uploadToken }).catch((abortError) => {
2259
+ attached = abortError.status === 409;
2260
+ });
2261
+ }
2262
+ if (publicId && attached) {
2263
+ if (!completionWasAmbiguous(e))
2264
+ throw Object.assign(e, { publicId });
2265
+ // otherwise fall through to the success result
2266
+ }
2267
+ else {
2268
+ throw e;
2109
2269
  }
2110
- throw e;
2111
2270
  }
2112
2271
  return {
2113
2272
  publicId,
@@ -2119,6 +2278,104 @@ async function uploadVideoToClipy(ctx, opts) {
2119
2278
  container,
2120
2279
  };
2121
2280
  }
2281
+ // ---------------------------------------------------------------------------
2282
+ // upload: put an existing video file into the library. The same pipeline as
2283
+ // `proof --video`, but titled after the file and meant for ordinary videos
2284
+ // (a screen recording made elsewhere, a demo, a bug repro from a teammate).
2285
+ // ---------------------------------------------------------------------------
2286
+ async function cmdUpload(ctx, file, opts) {
2287
+ const fail = (code, message, remediation, exitCode = 1, partial = null) => failure({ json: opts.json, die }, code, message, remediation, exitCode, partial);
2288
+ if (!ctx.apiKey) {
2289
+ fail("auth_required", "no API key", "Run `clipy login` to approve this device, or set CLIPY_API_KEY.");
2290
+ }
2291
+ const videoPath = resolve(file);
2292
+ if (!existsSync(videoPath)) {
2293
+ fail("source_unreadable", `no such file: ${videoPath}`, "Check the path; nothing was uploaded.");
2294
+ }
2295
+ let accessMode;
2296
+ if (opts.accessMode !== undefined) {
2297
+ if (!["public", "restricted", "private"].includes(opts.accessMode)) {
2298
+ fail("usage_error", "--access must be public, restricted or private", "Fix the arguments.", 2);
2299
+ }
2300
+ accessMode = opts.accessMode;
2301
+ }
2302
+ const log = (message) => {
2303
+ if (!opts.json)
2304
+ process.stderr.write(`${message}\n`);
2305
+ };
2306
+ const title = opts.name ?? basename(videoPath, extname(videoPath));
2307
+ let uploaded;
2308
+ try {
2309
+ const notes = resolveNarrationNotes(opts.notes, [0]).sort((a, b) => a.startMs - b.startMs);
2310
+ uploaded = await uploadVideoToClipy(ctx, {
2311
+ videoPath,
2312
+ name: title,
2313
+ nameIsUserProvided: opts.name !== undefined,
2314
+ description: opts.description,
2315
+ recordingKind: opts.recordingKind,
2316
+ expectedResult: opts.expectedResult,
2317
+ narration: notes.length > 0 ? { notes } : undefined,
2318
+ accessMode,
2319
+ sourceVersion: `cli/${VERSION}`,
2320
+ log,
2321
+ });
2322
+ }
2323
+ catch (error) {
2324
+ const message = error.message;
2325
+ const status = error.status;
2326
+ if (status === undefined && /not valid WebM or MP4|empty file|not a file/i.test(message)) {
2327
+ fail("source_unreadable", message, "Upload a WebM, MP4 or MOV file; nothing was uploaded.");
2328
+ }
2329
+ const stranded = error.publicId;
2330
+ if (stranded) {
2331
+ const partial = { id: stranded, shareUrl: `${ctx.apiUrl}/video/${stranded}` };
2332
+ if (error.code === "access_mode_pending") {
2333
+ fail("sharing_not_applied", `uploaded as ${stranded}, but the ${accessMode ?? "requested"} sharing could not be applied, so it may still be readable at the account's default access`, `Do not upload again. Set the sharing on the existing recording: clipy share ${stranded} ${accessMode ?? "private"}`, 1, partial);
2334
+ }
2335
+ fail("upload_unconfirmed", `uploaded as ${stranded}, but the server did not confirm its completion: ${message}`, `Do not upload again; the recording exists. Check it with: clipy show ${stranded}`, 1, partial);
2336
+ }
2337
+ if (status === 401)
2338
+ fail("auth_required", message, "Run `clipy login` to set a new key, then retry.");
2339
+ if (status === 429 || (status === 403 && /pro|allowance|recordings or|minutes/i.test(message))) {
2340
+ fail("quota_exceeded", message, "Report the limit to the user and stop; retrying only burns it.");
2341
+ }
2342
+ if (status === 403) {
2343
+ fail("wrong_scope", message, 'The key needs "ingest": run `clipy login` again, or create one at /settings/api-keys.');
2344
+ }
2345
+ fail("unknown", message, "Re-run once; if it fails again, report this output as a bug.");
2346
+ }
2347
+ // The recording exists from here on. A failed wait is a warning on a
2348
+ // successful result, never a failure: a caller that saw a failure would
2349
+ // upload the same file again and create a duplicate.
2350
+ const warnings = [];
2351
+ if (opts.wait) {
2352
+ const waitError = await waitForArtifactsSafely(ctx, uploaded.publicId);
2353
+ if (waitError) {
2354
+ warnings.push({
2355
+ code: "wait_incomplete",
2356
+ error: `uploaded, but waiting for processing failed: ${waitError}`,
2357
+ remediation: `Do not upload again. Check progress with: clipy wait ${uploaded.publicId} --for both`,
2358
+ });
2359
+ }
2360
+ }
2361
+ if (opts.json) {
2362
+ printJson({
2363
+ ok: true,
2364
+ id: uploaded.publicId,
2365
+ shareUrl: uploaded.shareUrl,
2366
+ contextUrl: uploaded.contextUrl,
2367
+ sizeBytes: uploaded.sizeBytes,
2368
+ container: uploaded.container,
2369
+ warnings,
2370
+ });
2371
+ return;
2372
+ }
2373
+ process.stdout.write(`${c.green("✓")} uploaded: ${c.bold(uploaded.shareUrl)}\n`);
2374
+ process.stdout.write(`${c.dim("agent context:")} ${uploaded.contextUrl}\n`);
2375
+ for (const warning of warnings) {
2376
+ process.stderr.write(`${c.yellow("warning:")} ${warning.error}\n ${warning.remediation}\n`);
2377
+ }
2378
+ }
2122
2379
  /**
2123
2380
  * Creates a shareable proof recording from screenshots supplied by any agent
2124
2381
  * tool, or uploads a WebM/MP4 that tool already recorded. This path deliberately
@@ -2195,6 +2452,7 @@ async function cmdProof(ctx, opts) {
2195
2452
  description: opts.description,
2196
2453
  narration: narrationNotes.length > 0 ? { notes: narrationNotes } : undefined,
2197
2454
  recordingKind: opts.recordingKind,
2455
+ expectedResult: opts.expectedResult,
2198
2456
  sourceVersion: `cli-proof/${VERSION}`,
2199
2457
  log,
2200
2458
  });
@@ -2804,6 +3062,7 @@ async function cmdRecord(ctx, opts) {
2804
3062
  name: opts.name,
2805
3063
  description: opts.description,
2806
3064
  recordingKind: opts.recordingKind,
3065
+ expectedResult: opts.expectedResult,
2807
3066
  narration: notes.length ? { notes } : undefined,
2808
3067
  log,
2809
3068
  });
@@ -2844,6 +3103,44 @@ async function cmdRecord(ctx, opts) {
2844
3103
  process.stdout.write(`${c.dim("next:")} clipy context ${uploaded.publicId} · clipy transcript ${uploaded.publicId}\n`);
2845
3104
  }
2846
3105
  /** Poll until the transcript reaches a terminal state (or ~5 min elapse). */
3106
+ /**
3107
+ * waitForArtifacts without the exits: returns null once the transcript is
3108
+ * terminal (or the five-minute deadline passes, as waitForArtifacts does) and
3109
+ * an error message instead of calling die(). For callers whose real work has
3110
+ * already succeeded and must not be reported as failed.
3111
+ */
3112
+ async function waitForArtifactsSafely(ctx, publicId) {
3113
+ const key = ctx.apiKey;
3114
+ if (!key)
3115
+ return "no API key";
3116
+ const url = `${ctx.apiUrl}/api/v1/recordings/${encodeURIComponent(publicId)}/transcript`;
3117
+ const deadline = Date.now() + 300_000;
3118
+ const terminal = new Set(["ready", "failed", "none"]);
3119
+ for (;;) {
3120
+ const controller = new AbortController();
3121
+ const timer = setTimeout(() => controller.abort(), FETCH_TIMEOUT_MS);
3122
+ try {
3123
+ const res = await fetch(url, {
3124
+ headers: { Authorization: `Bearer ${key}`, Accept: "application/json", "User-Agent": `clipy-cli/${VERSION}` },
3125
+ signal: controller.signal,
3126
+ });
3127
+ if (!res.ok)
3128
+ return `HTTP ${res.status}`;
3129
+ const body = (await res.json());
3130
+ if (terminal.has(String(body.status)))
3131
+ return null;
3132
+ }
3133
+ catch (e) {
3134
+ return e.name === "AbortError" ? "request timed out" : e.message;
3135
+ }
3136
+ finally {
3137
+ clearTimeout(timer);
3138
+ }
3139
+ if (Date.now() >= deadline)
3140
+ return null;
3141
+ await new Promise((r) => setTimeout(r, 3000));
3142
+ }
3143
+ }
2847
3144
  async function waitForArtifacts(ctx, publicId) {
2848
3145
  const pid = encodeURIComponent(publicId);
2849
3146
  const deadline = Date.now() + 300_000;
@@ -3358,6 +3655,7 @@ async function cmdSessionStartLinux(ctx, opts) {
3358
3655
  name: opts.name,
3359
3656
  description: opts.description,
3360
3657
  recordingKind: opts.recordingKind,
3658
+ expectedResult: opts.expectedResult,
3361
3659
  maxSec,
3362
3660
  width: opts.width,
3363
3661
  height: opts.height,
@@ -3479,6 +3777,7 @@ async function cmdRecordLinux(ctx, opts) {
3479
3777
  name: opts.name,
3480
3778
  description: opts.description,
3481
3779
  recordingKind: opts.recordingKind,
3780
+ expectedResult: opts.expectedResult,
3482
3781
  narration: notes.length ? { notes } : undefined,
3483
3782
  log: (m) => {
3484
3783
  if (!opts.json)
@@ -3687,6 +3986,9 @@ async function cmdRecordMac(opts) {
3687
3986
  if (opts.recordingKind) {
3688
3987
  log(c.yellow(`note: --type is not applied to --source mac-screen recordings yet (needs a Clipy app update)`));
3689
3988
  }
3989
+ if (opts.expectedResult) {
3990
+ log(c.yellow(`note: --expected is not applied to --source mac-screen recordings yet; run clipy update <id> --expected "<text>" afterwards`));
3991
+ }
3690
3992
  // Before the camera turns on, not after — see warnAudioUncontrollable().
3691
3993
  // Deliberately NOT `log`: a "your mic may be live" warning must survive
3692
3994
  // --json, and stderr never corrupts the JSON on stdout.
@@ -3898,6 +4200,9 @@ async function cmdSessionStartExtension(opts) {
3898
4200
  if (opts.recordingKind && !opts.json) {
3899
4201
  process.stderr.write(`${c.yellow("note: --type is not applied to --source chrome-extension recordings yet")}\n`);
3900
4202
  }
4203
+ if (opts.expectedResult && !opts.json) {
4204
+ process.stderr.write(`${c.yellow("note: --expected is not applied to --source chrome-extension recordings yet; after stop, run clipy update <id> --expected \"<text>\"")}\n`);
4205
+ }
3901
4206
  const file = sessionFilePath(process.cwd());
3902
4207
  const existing = readSessionState(file);
3903
4208
  if (existing && sessionIsActive(existing)) {
@@ -4016,6 +4321,9 @@ async function cmdSessionStart(ctx, opts) {
4016
4321
  if (opts.recordingKind && !opts.json) {
4017
4322
  process.stderr.write(`${c.yellow("note: --type is not applied to --source mac-screen recordings yet (needs a Clipy app update)")}\n`);
4018
4323
  }
4324
+ if (opts.expectedResult && !opts.json) {
4325
+ process.stderr.write(`${c.yellow("note: --expected is not applied to --source mac-screen recordings yet; after stop, run clipy update <id> --expected \"<text>\"")}\n`);
4326
+ }
4019
4327
  // Before the camera turns on, not after — see warnAudioUncontrollable().
4020
4328
  const audioUncontrollable = warnAudioUncontrollable(info.protocolVersion, opts.audio, (m) => process.stderr.write(`${m}\n`));
4021
4329
  const windowWarned = warnWindowCaptureUnknown(info.protocolVersion, target, (m) => process.stderr.write(`${m}\n`));
@@ -4117,6 +4425,7 @@ async function cmdSessionStart(ctx, opts) {
4117
4425
  name: opts.name,
4118
4426
  description: opts.description,
4119
4427
  recordingKind: opts.recordingKind,
4428
+ expectedResult: opts.expectedResult,
4120
4429
  maxSec,
4121
4430
  width: opts.width,
4122
4431
  height: opts.height,
@@ -5659,6 +5968,7 @@ async function runSessionDaemon(file) {
5659
5968
  name: state.name,
5660
5969
  description: state.description,
5661
5970
  recordingKind: state.recordingKind,
5971
+ expectedResult: state.expectedResult,
5662
5972
  narration: notes.length ? { notes } : undefined,
5663
5973
  browserDiagnostics: diagnosticsSidecar,
5664
5974
  log: (m) => log(m.replace(/\x1b\[[0-9;]*m/g, "")),
@@ -6105,7 +6415,7 @@ async function cmdAgents(ctx, sub, targetRaw, json) {
6105
6415
  // command's shape without trial-and-error. Bump GUIDE_SCHEMA_VERSION when the
6106
6416
  // contract changes.
6107
6417
  // ---------------------------------------------------------------------------
6108
- const GUIDE_SCHEMA_VERSION = 17;
6418
+ const GUIDE_SCHEMA_VERSION = 19;
6109
6419
  /** The stable machine-readable failure taxonomy carried in `--json` error
6110
6420
  * envelopes. Codes are the contract; messages are not. Published through the
6111
6421
  * guide so an agent discovers the full recovery table without the skill. */
@@ -6119,13 +6429,24 @@ const GUIDE_ERROR_CODES = [
6119
6429
  { code: "ffmpeg_missing", meaning: "ffmpeg/ffprobe is not installed or not on PATH", retryable: true, remediation: "brew install ffmpeg (macOS) / sudo apt install ffmpeg (Linux) / winget install Gyan.FFmpeg, then re-run the same command" },
6120
6430
  { code: "no_video_stream", meaning: "the file carries no decodable video track", retryable: false, remediation: "audio-only source — import transcript-only with --no-frames, or supply the real video file" },
6121
6431
  { code: "auth_required", meaning: "HTTP 401 — no API key, or the key is invalid/revoked", retryable: true, remediation: "run `clipy login` and WAIT for the user to approve the device in the browser it opens (`clipy login --no-browser` on headless hosts); retry only after login returns" },
6122
- { code: "wrong_scope", meaning: "HTTP 403 — the key is valid but lacks a required permission", retryable: false, remediation: "write paths need the 'ingest' scope — mint a key carrying it at /settings/api-keys; re-running with the same key cannot help" },
6432
+ { code: "wrong_scope", meaning: "HTTP 403 — the key is valid but lacks a required permission", retryable: false, remediation: "the error names the missing scope: recording/upload needs 'ingest', update/share/organize need 'recordings:write', comments needs 'comments:read', comment needs 'comments:write', analytics needs 'analytics:read', delete needs 'recordings:delete' (clipy login --allow-delete). Mint a key carrying it at /settings/api-keys; re-running with the same key cannot help" },
6123
6433
  { code: "quota_exceeded", meaning: "HTTP 429 — the account hit a plan or rate limit", retryable: false, remediation: "report the quota to the user and STOP; a retry loop only burns the limit. Any local bundle already produced remains readable" },
6124
6434
  { code: "frames_upload_failed", meaning: "the transcript synced but the frames did not", retryable: true, remediation: "PARTIAL SUCCESS, not a failure — the document exists and is readable. Re-run the SAME import command later to complete it; never re-import from scratch" },
6125
6435
  { code: "server_unreachable", meaning: "the Clipy API could not be reached", retryable: true, remediation: "check `clipy doctor --json`'s api check; a local (non --sync) bundle is still complete and readable with `clipy context read`" },
6126
6436
  { code: "transcript_unreadable", meaning: "the --transcript file could not be parsed", retryable: false, remediation: "confirm it is a real .vtt/.srt/Clipy transcript JSON and not empty or an HTML error page; ask the user for the right file rather than guessing another path" },
6127
6437
  { code: "source_unreadable", meaning: "the local video file could not be opened or probed", retryable: false, remediation: "verify the path exists and is readable (unmounted volume, still downloading, wrong container) — not retryable until the file is" },
6128
6438
  { code: "content_conflict", meaning: "a different video already occupies that document", retryable: false, remediation: "do NOT overwrite — show the user both and let them choose; re-running unchanged conflicts again" },
6439
+ { code: "usage_error", meaning: "the command's arguments are wrong or missing (exit 2)", retryable: false, remediation: "fix the arguments; this manifest lists every command's usage and flags" },
6440
+ { code: "not_found", meaning: "HTTP 404: no recording or folder with that id or name in this account", retryable: false, remediation: "look the id up with `clipy list --json` (or the folder with `clipy folders --json`); ids from another account never resolve" },
6441
+ { code: "invalid_request", meaning: "the API refused the request as sent (HTTP 400, 409 or 422)", retryable: false, remediation: "read `error`, change the request accordingly; re-running unchanged fails the same way" },
6442
+ { code: "confirmation_required", meaning: "a permanent action (clipy delete) was run without --yes (exit 2)", retryable: false, remediation: "only if the user asked for that exact recording to be deleted, re-run with --yes" },
6443
+ { code: "upload_unconfirmed", meaning: "the upload became a recording, but the server never confirmed its completion (still being committed or queued)", retryable: false, remediation: "do NOT upload again (that creates a duplicate); check the recording in partial.id with `clipy show <id>`" },
6444
+ { code: "sharing_not_applied", meaning: "the upload became a recording, but the requested public/restricted/private sharing could not be applied", retryable: false, remediation: "do NOT upload again (that creates a duplicate); run the `clipy share <id> <mode>` in the remediation, using partial.id" },
6445
+ { code: "timeline_not_ready", meaning: "clipy recheck: the recording's interaction timeline is still being prepared", retryable: true, remediation: "wait a minute and re-run the same command" },
6446
+ { code: "no_interactions", meaning: "clipy recheck: the recording has no clicks or page navigations to replay (for example a plain web-recorder take)", retryable: false, remediation: "only Chrome extension, Chrome for Clipy, Mac and Windows app takes can be re-checked; re-running cannot help" },
6447
+ { code: "chrome_unavailable", meaning: "clipy recheck: Chrome for Clipy could not be started or driven", retryable: true, remediation: "run `clipy chrome status --json` and `clipy chrome start`, then re-run once" },
6448
+ { code: "start_url_unreachable", meaning: "clipy recheck: the --url page could not be opened (connection refused, unknown host)", retryable: false, remediation: "check that --url loads (is the server running, is it the right host?), then re-run" },
6449
+ { code: "recheck_upload_failed", meaning: "clipy recheck finished, but its step frames were not uploaded (a warning on an ok:true report, not a failure)", retryable: false, remediation: "the report and frames are saved locally (files.json); do not re-run the whole re-check just for the upload" },
6129
6450
  { code: "unknown", meaning: "an unclassified failure", retryable: true, remediation: "re-run once; if it repeats, hand the user the whole envelope as a bug report rather than improvising a workaround" },
6130
6451
  ];
6131
6452
  function cmdGuide(json) {
@@ -6149,12 +6470,12 @@ function cmdGuide(json) {
6149
6470
  jsonFlag: "--json",
6150
6471
  stdout: "primary results (JSON when --json is set) — THE SOURCE OF TRUTH",
6151
6472
  stderr: "progress, warnings, and install disclosures; narration only, never part of the contract, never JSON. Do not parse it and do not infer success or failure from it.",
6152
- errors: "exit non-zero with a message on stderr prefixed 'error:'. Under --json, `context import` prints exactly ONE object on stdout either way: a failure is {ok:false, code, error, remediation, partial} — branch on `code` (stable, see errorCodes), never on `error` text; `remediation` is the next action, written to be run verbatim where possible; `partial` holds whatever survived (e.g. {bundlePath}) or null.",
6473
+ errors: "exit non-zero with a message on stderr prefixed 'error:'. Under --json, `context import` and the library commands (upload, update, share, organize, folders, comments, comment, analytics, delete, diagnostics, interactions) print exactly ONE object on stdout either way: a failure is {ok:false, code, error, remediation, partial} — branch on `code` (stable, see errorCodes), never on `error` text; `remediation` is the next action, written to be run verbatim where possible; `partial` holds whatever survived (e.g. {bundlePath}) or null.",
6153
6474
  success: "{ok:true, …} always carries a `warnings` array — empty when nothing went wrong. A PARTIAL success (transcript synced, frames missing) is ok:true with entries in `warnings`, each {code, error, remediation}, and exits 0. Read the warnings; do not read them as failure.",
6154
6475
  neverInventSuccess: "If no readable result was printed, the work did not happen. Never report an import, recording, or frame capture as done because the command appeared to run.",
6155
6476
  },
6156
6477
  env: [
6157
- { name: "CLIPY_API_KEY", description: "API key (clipy_sk_live_…) from clipy.online/settings/api-keys; write commands need the 'ingest' scope" },
6478
+ { name: "CLIPY_API_KEY", description: "API key (clipy_sk_live_…) from clipy.online/settings/api-keys; record/upload/proof need 'ingest', update/share/organize need 'recordings:write', comments needs 'comments:read', comment needs 'comments:write', analytics needs 'analytics:read', delete needs 'recordings:delete'" },
6158
6479
  { name: "CLIPY_API_URL", description: "API base URL override (default https://clipy.online)" },
6159
6480
  { name: "CLIPY_DISABLE_CDP", description: "set to 1 to force session --expose-cdp off (a hard kill switch that wins over the flag)" },
6160
6481
  { name: "CLIPY_SESSION_FILE", description: "path to a session state file that mark/chapter/session stop|abort|status resolve FIRST (before the cwd hash). `session run` exports it to the child so a driver can mark from any cwd." },
@@ -6165,6 +6486,7 @@ function cmdGuide(json) {
6165
6486
  { code: 1, meaning: "error" },
6166
6487
  { code: 2, meaning: "usage error" },
6167
6488
  { code: 3, meaning: "artifact not ready yet (transcript/summary/wait)" },
6489
+ { code: 4, meaning: "clipy recheck --fail-on-divergence: the re-check finished but its verdict is not matches" },
6168
6490
  ],
6169
6491
  errorCodes: GUIDE_ERROR_CODES,
6170
6492
  partialSuccess: {
@@ -6174,7 +6496,7 @@ function cmdGuide(json) {
6174
6496
  tellTheUser: "Say plainly: imported and readable, frames pending, and which timestamps are affected (the classifier already names them in the bundle's sufficiency report).",
6175
6497
  },
6176
6498
  commands: [
6177
- cmdDoc("login", "clipy login [--no-browser] [--key <key>] [--paste]", "Approve this device in the browser (default). --no-browser (auto-detected on SSH and display-less Linux) prints the approval URL to open on any device and prompts for the code it shows. --key/--paste store a pasted key (also the automatic path when stdout is not a TTY)", ["--no-browser", "--key <key>", "--paste"]),
6499
+ cmdDoc("login", "clipy login [--no-browser] [--allow-delete] [--key <key>] [--paste]", "Approve this device in the browser (default). The approved key reads, organizes, comments and uploads; --allow-delete adds the permanent-delete permission. --no-browser (auto-detected on SSH and display-less Linux) prints the approval URL to open on any device and prompts for the code it shows. --key/--paste store a pasted key (also the automatic path when stdout is not a TTY)", ["--no-browser", "--key <key>", "--paste"]),
6178
6500
  cmdDoc("logout", "clipy logout", "Delete the stored key"),
6179
6501
  cmdDoc("whoami", "clipy whoami", "Check the active key"),
6180
6502
  cmdDoc("list", "clipy list [-n N] [--page P] [--status s,…] [--json]", "List recordings, newest first"),
@@ -6186,13 +6508,25 @@ function cmdGuide(json) {
6186
6508
  cmdDoc("moments", "clipy moments <id> [--json]", "Key moments: timestamps, captions, click coords"),
6187
6509
  cmdDoc("context", "clipy context <id>", "Full agent-context bundle as markdown"),
6188
6510
  cmdDoc("context import", "clipy context import <youtube-url|loom-url|local-file> [--transcript <f>] [--output <dir>] [--language <code>] [--title <t>] [--tag <t>]… [--folder <name>] [--sync] [--json]", "Compile ANY video into a local Clipy context bundle — a directory holding recording.arec (the canonical agent-facing Markdown document), a byte-identical recording.md compatibility copy, manifest.json (provenance, versions, sufficiency report) and transcript.json. YouTube URLs resolve on YOUR machine via a Clipy-managed yt-dlp (auto-installed into ~/.clipy/bin on first use, with a disclosure); creator captions are preferred over auto-captions and NO media is downloaded. Loom share links (loom.com/share/<32-hex-id>) use Loom's own published transcript over plain HTTPS — no yt-dlp is needed and none is installed, so `clipy doctor`'s yt-dlp check does not gate a Loom import; roughly one Loom in six has no transcript recorded and fails with `no_captions` rather than emitting an empty bundle, and Loom's transcript is machine-generated so it is recorded as auto_captions. Local files need --transcript <.vtt|.srt|Clipy transcript JSON> and are probed with ffprobe. A deterministic classifier scores how well the transcript stands alone and lists the timestamps where it is blind — v1 emits the transcript profile only, so those gaps are the honest statement of what the bundle cannot show. Reruns over the same source are idempotent. --sync additionally uploads the DERIVED bundle (never source media) to your private library.", ["--transcript", "--output", "--language", "--title", "--tag", "--folder", "--sync", "--no-frames", "--json"]),
6189
- cmdDoc("context read", "clipy context read <bundle-path>", "Print a local bundle's recording.arec to stdout — plain, unpaged, uncoloured, for an agent to read directly. It opens with a self-describing header (source, duration, classification, sufficiency, untrusted-content warning) before the [MM:SS] transcript sections, so the first screen tells you what the document is and where it is blind. For a SYNCED document read it over MCP instead: get_context_document for metadata+classification without the transcript, then read_context_document with startMs/endMs for just the span you need."),
6511
+ cmdDoc("context read", "clipy context read <bundle-path>", "Print a local bundle's recording.arec to stdout: plain, unpaged, uncoloured, for an agent to read directly. It opens with a self-describing header (source, duration, classification, sufficiency) before the [MM:SS] transcript sections, so the first screen tells you what the document is and where it is blind. For a SYNCED document read it over MCP instead: get_context_document for metadata+classification without the transcript, then read_context_document with startMs/endMs for just the span you need."),
6512
+ cmdDoc("upload", "clipy upload <file> [--title t] [--description d] [--type kind] [--expected text] [--access public|restricted|private] [--note '12: text']… [--wait] [--json]", "Upload an existing WebM/MP4/MOV file to the library through the same pipeline as recordings (needs 'ingest'; counts toward the recording allowance). JSON: {ok:true, id, shareUrl, contextUrl, sizeBytes, container, warnings}. With --wait, a failed wait is a `wait_incomplete` warning on a successful result: the recording exists, so never upload again. --expected states what should have happened; agents read it as the recording's Expected result", ["--title", "--description", "--type", "--expected", "--access", "--note", "--wait", "--json"]),
6513
+ cmdDoc("update", "clipy update <id> [--title t] [--description d | --clear-description] [--expected text | --clear-expected] [--json]", "Rename a recording, edit its description, or set what should have happened (--expected, shown to agents as Expected result) (recordings:write)", ["--title", "--description", "--clear-description", "--expected", "--clear-expected", "--json"]),
6514
+ cmdDoc("share", "clipy share <id> [public|restricted|private] [--json]", "Without a mode: print who can open the link. With one: change it (recordings:write). It never invites or emails anyone"),
6515
+ cmdDoc("organize", "clipy organize <id> [--folder <name|id> | --no-folder] [--tag t]… [--untag t]… [--json]", "Move into a folder (by exact name or id) and add/remove tags (recordings:write)"),
6516
+ cmdDoc("folders", "clipy folders [--create <name>] [--json]", "List folders with ids and counts, or create one (idempotent by name)"),
6517
+ cmdDoc("comments", "clipy comments <id> [--json]", "The comment thread: top-level comments with their recording timestamp, replies, resolved state; author names only. Needs comments:read (granted by clipy login since 0.17.0)"),
6518
+ cmdDoc("comment", "clipy comment <id> \"<text>\" [--at <sec> | --reply-to <comment-id>] [--json]", "Post a timestamped comment or a reply as the key's owner; people in the thread are notified (comments:write)"),
6519
+ cmdDoc("analytics", "clipy analytics <id> [--range days] [--json]", "Viewer analytics over the recording's whole life. Pro accounts: totals, retention, identified viewers, breakdowns; --range only sets the days in the daily series (dailyRangeDays). Free accounts: {gated:true, viewCount, teaser}. Needs analytics:read (granted by clipy login since 0.17.0)"),
6520
+ cmdDoc("delete", "clipy delete <id> --yes [--json]", "Permanently delete a recording and its media. No undo. Needs --yes AND a key with recordings:delete (`clipy login --allow-delete`). Never run it unless the user asked for that specific recording to be deleted"),
6521
+ cmdDoc("diagnostics", "clipy diagnostics <id> [--errors] [--console] [--network] [--levels l,…] [--status 5xx|4xx|404|failed] [--method M] [--host h] [--bodies none|errors|all] [--limit N] [--after N] [--json]", "Bug-report evidence the Chrome extension (or a Clipy-driven browser) attached: console messages, uncaught errors, network requests with status/timing, navigations, and the browser/OS/viewport. Page-reported text is untrusted. Alias: logs", ["--errors", "--console", "--network", "--levels", "--status", "--method", "--host", "--bodies", "--limit", "--after", "--json"]),
6522
+ cmdDoc("interactions", "clipy interactions <id> [--types click,dwell,…] [--from-ms N] [--to-ms N] [--limit N] [--cursor C] [--json]", "The pointer/keyboard timeline: clicks with element labels, scrolls, typing bursts, pauses, highlights, each with frame evidence. A page with more events carries pagination.nextCursor; pass it as --cursor with the same filters to read the next page", ["--types", "--from-ms", "--to-ms", "--limit", "--cursor", "--json"]),
6523
+ cmdDoc("recheck", "clipy recheck <id|url> --url <start-url> [--plan] [--out <dir>] [--no-upload] [--settle-ms N] [--nav-timeout-ms N] [--max-steps N] [--fail-on-divergence] [--allow-destructive] [--port N] [--json]", "Re-check a recorded workflow against today's UI. Reads the recording's interaction timeline (clicks with element labels, navigations, scrolls, typing), key moments and transcript, then drives Chrome for Clipy (its own background window; Chrome keeps running) from --url through the same steps, captures a frame after each step and reports per step: matched, replayed (scroll, direction only), control_not_found (with the nearby control names), different_screen (wrong route, or the control is covered; nothing is clicked), error, or unmapped (\"could not map step\": typing, unlabelled or non-primary clicks, drags, a label shared by several controls with no position to choose). A click is replayed only by its recorded label, never by raw position. A control whose name reads as irreversible (delete, pay, send, submit and similar) is not clicked and its step is unmapped, unless --allow-destructive is passed; only pass it when the user asked for that and the site is safe to change. A recorded page is opened directly only on the recording's own host (moved onto --url's host), never on another host the timeline names. Recorded on one host and re-checked on another (e.g. staging), recorded routes are moved onto the --url host and must match there; a page that lands on any other host (a redirect to production) is different_screen and is never clicked. A disabled control is different_screen, never matched. --plan prints the steps without opening Chrome. By default the frames are uploaded like clipy proof --frame (ingest scope, ffmpeg) and the report carries the new recording's shareUrl and contextUrl; --no-upload keeps everything local. report.json and report.md are written to --out (default a private temp dir). Ctrl-C closes the re-check's window and exits 130. An unreachable --url fails with start_url_unreachable. An upload whose completion was not confirmed carries the recording plus an upload_unconfirmed warning: do not upload again. --json prints {ok:true, type:'clipy.recheck_report', original:{…, expectedResult}, summary:{verdict: matches|diverged|incomplete, firstDivergence, counts}, steps:[{status, reason, expected, observed}], recording, limitations, warnings, files}. original.expectedResult carries the recording's \"what should have happened\" when it has one; compare it with the last frame yourself. --fail-on-divergence exits 4 unless the verdict is matches. Needs Playwright (as session --source chrome-for-clipy does) and a Chrome for Clipy that is signed in where the workflow needs it.", ["--url <start-url>", "--plan", "--out <dir>", "--no-upload", "--settle-ms", "--nav-timeout-ms", "--max-steps", "--fail-on-divergence", "--allow-destructive", "--port", "--json"]),
6190
6524
  cmdDoc("download", "clipy download <id> [-o path]", "Download the MP4"),
6191
6525
  cmdDoc("open", "clipy open <id>", "Open the share page in a browser"),
6192
6526
  cmdDoc("wait", "clipy wait <id> [--for transcript|summary|both] [--timeout sec]", "Block until artifacts are ready"),
6193
- cmdDoc("proof", "clipy proof (--frame <png|jpg|webp>… | --video <webm|mp4>) [--for <recording>] [--caption <text>…] [--hold sec] [--title t] [--type kind] [--note '3: text']… [--wait] [--json]", "Tool-neutral proof upload. --frame may be repeated to turn screenshots produced by any browser, computer-use, simulator, or test tool into one high-quality silent MP4; --caption must be omitted or repeated exactly once per frame and becomes timestamped agent narration. --hold controls each frame's duration (default 3s, 0.25–30; total cap 300s); --width/--height must be even integers from 320–3840 and default to 1280x720. Frame inputs are bounded to 50 MiB each and 250 MiB total. Screenshot stitching needs ffmpeg but does not need Playwright or a browser integration. --video uploads an already-recorded WebM or MP4 without re-encoding and needs no recording dependency. Exactly one source mode is required. --for <recording id|url> links the uploaded proof back to the recording it verifies (validated before upload; the link appears in the owner-only receipt on that recording's watch page and needs a key with both ingest and recordings:read). --json prints {id, shareUrl, contextUrl, sizeBytes, source, verifies?}; proof-video source reports only the detected container and never discloses the local path. Captions and notes are driver-attested narration, not Clipy-verified assertions.", ["--frame", "--caption", "--video", "--for", "--hold", "--width", "--height", "--title", "--description", "--type", "--note", "--wait", "--json"]),
6194
- cmdDoc("record", "clipy record --url <url> [--for sec] [--viewports list] [--title t] [--type kind] [--note '12: text']… [--storage-state f] [--cookie 'n=v']… [--local-storage 'k=v']… [--init-script f] [--wait] [--json]", "Headless one-shot capture of a web app; notes become the transcript. Notes are absolute ('12: text') or pass-scoped ('pass2: text' / 'pass2@5: text', anchored to a --viewports pass's real start; a malformed pass note is rejected). --type declares the recording kind (bug_report|feature_request|product_demo|walkthrough_tutorial|feedback_review|discussion_talk|other, plus aliases bug/feature/demo/walkthrough/feedback/discussion) so the AI summary reads it correctly. Auth (web capture only, applied before the first navigation so a logged-in SPA's route guard sees it): --storage-state <playwright storageState JSON path>, --cookie 'name=value[; Domain=d; Path=p; Secure; HttpOnly; SameSite=Lax]' (repeatable), --local-storage 'key=value' (repeatable, target origin only), --init-script <js file run before every page load>, --user-data-dir <dir> (launch from a persistent Chromium user-data ROOT with its whole logged-in identity; web only, mutually exclusive with --storage-state; refused if <dir> is a profile subdir — pass the root — or, in direct mode, a live-locked root via SingletonLock/Socket), --profile-directory <name> (with --user-data-dir: pick a NAMED profile like 'Profile 12' from chrome://version; Playwright can't select a profile in place, so Clipy COPIES it into a temp recording root and launches the copy — loudly disclosed, the real profile is never opened or written, and the copy is deleted after upload; no need to quit Chrome, though it warns if Chrome is running since in-use DBs may copy inconsistently). Auth boundary: --storage-state only seeds what the file contains; for cross-origin auth produce it with `npx playwright open --save-storage=auth.json <login-host>`, or use --user-data-dir + --profile-directory to record your real profile, or --source mac-screen --window Chrome. With --source screen (or mac-screen on macOS): records the real screen, via the Clipy Mac app on macOS (--type not yet applied on mac) and with the CLI's own X11 recorder on Linux (silent; needs ffmpeg with x11grab). Auth flags are rejected, since the screen is already logged in; --window '<title|app|id>' records that window by itself (windows on top of it stay out, and it follows the window if it moves, only when --json reports windowCapture \"window\"; \"area\", from a Clipy Mac app older than bridge protocol v3 or on ffmpeg older than 5.1, records whatever is on top, and on Linux covered parts are black without a compositor) and --display <id> records one display (ids from clipy sources). Linux only: --x-display :N picks the X display (default $DISPLAY) and --virtual-display records a private X display sized by --width/--height. --json prints {id, shareUrl, contextUrl, sizeBytes}", ["--for", "--viewports", "--title", "--description", "--type", "--note", "--storage-state", "--cookie", "--local-storage", "--init-script", "--user-data-dir", "--profile-directory", "--width", "--height", "--wait", "--source", "--window", "--display", "--x-display", "--virtual-display", "--json"]),
6195
- cmdDoc("session", "clipy session <start|run|stop|abort|status> [--url <url>] [--max sec] [--type kind] [--source web|screen|chrome-for-clipy|chrome-extension] [--window w] [--display d] [--x-display :N] [--virtual-display] [--expose-cdp] [--diagnostics off|errors|all] [--network-detail] [--storage-state f] [--cookie 'n=v']… [--local-storage 'k=v']… [--init-script f] [--json]", "Background recording session; auto-stops + uploads at --max (default 600s, cap 1800s). --type sets the recording kind (see record). Web and chrome-for-clipy sessions attach browser evidence read from the browser itself (console output, uncaught errors, failed requests including GraphQL errors, WebSocket activity, environment) as the recording's browser diagnostics: --diagnostics errors (default) keeps warnings/errors and failures, all keeps every message and request, off keeps none; --network-detail also keeps request/response headers and text bodies (cookie and authorization headers never leave the machine; the server redacts the rest by field name and value pattern). With --source screen (mac-screen on macOS), --window records that window by itself (windows on top of it stay out only when --json reports windowCapture \"window\"; \"area\", from a Clipy Mac app older than bridge protocol v3 or on ffmpeg older than 5.1, records whatever is on top, and on Linux covered parts are black without a compositor) and --display records one display; on Linux --x-display :N picks the X display and --virtual-display records a private X display whose name is returned as xDisplay (session run exports it to the command as DISPLAY). --source chrome-extension records ONE TAB through the Clipy extension inside Chrome for Clipy (needs a one-time clipy chrome setup): no daemon, the extension records and uploads; start returns cdpHttpUrl and the recorded tab's url (opened in the background, never focused), --name titles the recording, the tab's sound is left out unless --tab-audio (detected speech would replace the marks as the transcript), mark/chapter (plain or --observed/--verdict, not --assert-*) are kept by the CLI and sent at stop as the transcript, stop waits for the upload and returns the link. --source chrome-for-clipy records ONE TAB (tab video + tab audio, no picker or gesture) inside the persistent Chrome for Clipy instance: the instance is started automatically (sign in once via clipy chrome start and the profile stays signed in), the recorded tab opens at --url, its CDP endpoint is always published as cdpUrl/cdpHttpUrl so drivers attach to the very browser being recorded, and stopping the session leaves Chrome for Clipy running; auth-capture flags and --user-data-dir are rejected for this source. --expose-cdp (web sessions) opens a CDP endpoint (cdpUrl/cdpHttpUrl in the state file + session start/status output) so your own tools can drive the page while it records; OFF by default (any local process could attach), and CLIPY_DISABLE_CDP=1 forces it off. `session run [start flags] -- <command…>` starts a session, runs the command with inherited stdio (env CLIPY_SESSION=1, plus CLIPY_CDP_URL when --expose-cdp, plus CLIPY_TARGET_ID/CLIPY_PAGE_WS_URL for the recorded tab with --source chrome-extension), then GUARANTEES cleanup: exit 0 uploads, any non-zero exit or signal discards (session abort) and propagates the child's code. It is the crash-safe wrapper, so a dead driver never records dead air. Accepts the same auth flags as record (--storage-state/--user-data-dir/--profile-directory/--cookie/--local-storage/--init-script; web only, rejected on --source mac-screen). `session run` exports CLIPY_SESSION_FILE to the child so mark/chapter resolve the session from any cwd. --json is supported on start/stop/status (start returns cdpUrl/cdpHttpUrl)", ["run", "--url", "--max", "--type", "--source", "--window", "--display", "--x-display", "--virtual-display", "--tab-audio", "--expose-cdp", "--diagnostics", "--network-detail", "--storage-state", "--user-data-dir", "--profile-directory", "--cookie", "--local-storage", "--init-script", "--json"]),
6527
+ cmdDoc("proof", "clipy proof (--frame <png|jpg|webp>… | --video <webm|mp4>) [--for <recording>] [--caption <text>…] [--hold sec] [--title t] [--type kind] [--expected text] [--note '3: text']… [--wait] [--json]", "Tool-neutral proof upload. --frame may be repeated to turn screenshots produced by any browser, computer-use, simulator, or test tool into one high-quality silent MP4; --caption must be omitted or repeated exactly once per frame and becomes timestamped agent narration. --hold controls each frame's duration (default 3s, 0.25–30; total cap 300s); --width/--height must be even integers from 320–3840 and default to 1280x720. Frame inputs are bounded to 50 MiB each and 250 MiB total. Screenshot stitching needs ffmpeg but does not need Playwright or a browser integration. --video uploads an already-recorded WebM or MP4 without re-encoding and needs no recording dependency. Exactly one source mode is required. --for <recording id|url> links the uploaded proof back to the recording it verifies (validated before upload; the link appears in the owner-only receipt on that recording's watch page and needs a key with both ingest and recordings:read). --json prints {id, shareUrl, contextUrl, sizeBytes, source, verifies?}; proof-video source reports only the detected container and never discloses the local path. Captions and notes are driver-attested narration, not Clipy-verified assertions.", ["--frame", "--caption", "--video", "--for", "--hold", "--width", "--height", "--title", "--description", "--type", "--expected", "--note", "--wait", "--json"]),
6528
+ cmdDoc("record", "clipy record --url <url> [--for sec] [--viewports list] [--title t] [--type kind] [--expected text] [--note '12: text']… [--storage-state f] [--cookie 'n=v']… [--local-storage 'k=v']… [--init-script f] [--wait] [--json]", "Headless one-shot capture of a web app; notes become the transcript. Notes are absolute ('12: text') or pass-scoped ('pass2: text' / 'pass2@5: text', anchored to a --viewports pass's real start; a malformed pass note is rejected). --type declares the recording kind (bug_report|feature_request|product_demo|walkthrough_tutorial|feedback_review|discussion_talk|other, plus aliases bug/feature/demo/walkthrough/feedback/discussion) so the AI summary reads it correctly. --expected states what should have happened (not yet applied on mac; use clipy update afterwards). Auth (web capture only, applied before the first navigation so a logged-in SPA's route guard sees it): --storage-state <playwright storageState JSON path>, --cookie 'name=value[; Domain=d; Path=p; Secure; HttpOnly; SameSite=Lax]' (repeatable), --local-storage 'key=value' (repeatable, target origin only), --init-script <js file run before every page load>, --user-data-dir <dir> (launch from a persistent Chromium user-data ROOT with its whole logged-in identity; web only, mutually exclusive with --storage-state; refused if <dir> is a profile subdir — pass the root — or, in direct mode, a live-locked root via SingletonLock/Socket), --profile-directory <name> (with --user-data-dir: pick a NAMED profile like 'Profile 12' from chrome://version; Playwright can't select a profile in place, so Clipy COPIES it into a temp recording root and launches the copy — loudly disclosed, the real profile is never opened or written, and the copy is deleted after upload; no need to quit Chrome, though it warns if Chrome is running since in-use DBs may copy inconsistently). Auth boundary: --storage-state only seeds what the file contains; for cross-origin auth produce it with `npx playwright open --save-storage=auth.json <login-host>`, or use --user-data-dir + --profile-directory to record your real profile, or --source mac-screen --window Chrome. With --source screen (or mac-screen on macOS): records the real screen, via the Clipy Mac app on macOS (--type not yet applied on mac) and with the CLI's own X11 recorder on Linux (silent; needs ffmpeg with x11grab). Auth flags are rejected, since the screen is already logged in; --window '<title|app|id>' records that window by itself (windows on top of it stay out, and it follows the window if it moves, only when --json reports windowCapture \"window\"; \"area\", from a Clipy Mac app older than bridge protocol v3 or on ffmpeg older than 5.1, records whatever is on top, and on Linux covered parts are black without a compositor) and --display <id> records one display (ids from clipy sources). Linux only: --x-display :N picks the X display (default $DISPLAY) and --virtual-display records a private X display sized by --width/--height. --json prints {id, shareUrl, contextUrl, sizeBytes}", ["--for", "--viewports", "--title", "--description", "--type", "--expected", "--note", "--storage-state", "--cookie", "--local-storage", "--init-script", "--user-data-dir", "--profile-directory", "--width", "--height", "--wait", "--source", "--window", "--display", "--x-display", "--virtual-display", "--json"]),
6529
+ cmdDoc("session", "clipy session <start|run|stop|abort|status> [--url <url>] [--max sec] [--type kind] [--expected text] [--source web|screen|chrome-for-clipy|chrome-extension] [--window w] [--display d] [--x-display :N] [--virtual-display] [--expose-cdp] [--diagnostics off|errors|all] [--network-detail] [--storage-state f] [--cookie 'n=v']… [--local-storage 'k=v']… [--init-script f] [--json]", "Background recording session; auto-stops + uploads at --max (default 600s, cap 1800s). --type sets the recording kind (see record). --expected states what should have happened, shown to agents as the recording's Expected result (web, chrome-for-clipy and Linux screen sessions; for the others run clipy update afterwards). Web and chrome-for-clipy sessions attach browser evidence read from the browser itself (console output, uncaught errors, failed requests including GraphQL errors, WebSocket activity, environment) as the recording's browser diagnostics: --diagnostics errors (default) keeps warnings/errors and failures, all keeps every message and request, off keeps none; --network-detail also keeps request/response headers and text bodies (cookie and authorization headers never leave the machine; the server redacts the rest by field name and value pattern). With --source screen (mac-screen on macOS), --window records that window by itself (windows on top of it stay out only when --json reports windowCapture \"window\"; \"area\", from a Clipy Mac app older than bridge protocol v3 or on ffmpeg older than 5.1, records whatever is on top, and on Linux covered parts are black without a compositor) and --display records one display; on Linux --x-display :N picks the X display and --virtual-display records a private X display whose name is returned as xDisplay (session run exports it to the command as DISPLAY). --source chrome-extension records ONE TAB through the Clipy extension inside Chrome for Clipy (needs a one-time clipy chrome setup): no daemon, the extension records and uploads; start returns cdpHttpUrl and the recorded tab's url (opened in the background, never focused), --name titles the recording, the tab's sound is left out unless --tab-audio (detected speech would replace the marks as the transcript), mark/chapter (plain or --observed/--verdict, not --assert-*) are kept by the CLI and sent at stop as the transcript, stop waits for the upload and returns the link. --source chrome-for-clipy records ONE TAB (tab video + tab audio, no picker or gesture) inside the persistent Chrome for Clipy instance: the instance is started automatically (sign in once via clipy chrome start and the profile stays signed in), the recorded tab opens at --url, its CDP endpoint is always published as cdpUrl/cdpHttpUrl so drivers attach to the very browser being recorded, and stopping the session leaves Chrome for Clipy running; auth-capture flags and --user-data-dir are rejected for this source. --expose-cdp (web sessions) opens a CDP endpoint (cdpUrl/cdpHttpUrl in the state file + session start/status output) so your own tools can drive the page while it records; OFF by default (any local process could attach), and CLIPY_DISABLE_CDP=1 forces it off. `session run [start flags] -- <command…>` starts a session, runs the command with inherited stdio (env CLIPY_SESSION=1, plus CLIPY_CDP_URL when --expose-cdp, plus CLIPY_TARGET_ID/CLIPY_PAGE_WS_URL for the recorded tab with --source chrome-extension), then GUARANTEES cleanup: exit 0 uploads, any non-zero exit or signal discards (session abort) and propagates the child's code. It is the crash-safe wrapper, so a dead driver never records dead air. Accepts the same auth flags as record (--storage-state/--user-data-dir/--profile-directory/--cookie/--local-storage/--init-script; web only, rejected on --source mac-screen). `session run` exports CLIPY_SESSION_FILE to the child so mark/chapter resolve the session from any cwd. --json is supported on start/stop/status (start returns cdpUrl/cdpHttpUrl)", ["run", "--url", "--max", "--type", "--expected", "--source", "--window", "--display", "--x-display", "--virtual-display", "--tab-audio", "--expose-cdp", "--diagnostics", "--network-detail", "--storage-state", "--user-data-dir", "--profile-directory", "--cookie", "--local-storage", "--init-script", "--json"]),
6196
6530
  cmdDoc("mark", "clipy mark \"<text>\" [--observed \"<values>\" --verdict pass|fail] [--assert-selector <css> [--assert-text <substr>]] [--assert-url <glob>] [--fail-mode warn|abort] [--at <sec>|--ago <sec>] [--json]", "Drop a live-timestamped note into the active session. A mark carries at most ONE evidence provenance, and the two are labeled + tallied separately so they can never be pooled. DRIVER-ATTESTED (--observed '<values>' --verdict pass|fail, both required together): you drove the browser and report what YOU observed — renders '<text> [≈ ASSERT driver-attested; observed=<values>]' (pass) / '<text> [≈ FAILED driver-attested; observed=<values>]' (fail) — a HEDGE glyph, never ✓/✗, so a skim distinguishes provenance by shape alone and works in EVERY session type including --source mac-screen. Honesty rule: driver-attested means Clipy vouches the agent SAID it, not that Clipy verified it — put real observed values there. Combining --observed/--verdict with --assert-* is a usage error. CLIPY-VERIFIED assertion marks (Clipy-owned page only) make the note evidence Clipy itself checked: --assert-selector checks a CSS selector matches (its trimmed textContent is recorded as 'observed'); --assert-text requires that element's text to contain a substring (needs --assert-selector); --assert-url matches the page URL against a glob (** = any, * = any non-slash, no * = substring). The daemon evaluates against its live page and annotates the mark: pass ⇒ '<text> [assert ✓ verified-by-clipy; <observed>]', fail ⇒ '<text> [ASSERT ✗ verified-by-clipy; expected …; observed …]' — a false claim cannot read as fact. --fail-mode warn (default) records the ✗; --fail-mode abort DISCARDS the whole session on a failed assertion (no upload) and the CLI exits non-zero. If any assertion was attempted, a leading 0ms [verification] note is prepended, reporting the provenances as SEPARATE segments: '[verification] N clipy-verified: P passed, F failed, K unverified · M driver-attested: P passed, F failed' (a segment is omitted when empty; with only clipy-verified marks the legacy 'N assertion(s): …' rendering is byte-identical). --at <sec> stamps at an absolute recording time; --ago <sec> stamps N seconds before now (mutually exclusive). Assertions/backdating need a web session (rejected on --source mac-screen). Up to 200 marks per recording.", ["--observed", "--verdict", "--assert-selector", "--assert-text", "--assert-url", "--fail-mode", "--at", "--ago", "--json"]),
6197
6531
  cmdDoc("chapter", "clipy chapter \"<label>\" [--json]", "Mark a BEFORE/AFTER section boundary in the active recording (stored as '=== CHAPTER: <label> ==='). The PR-review shape: demo the base branch, run `clipy chapter \"AFTER — fix applied\"`, swap branches + restart the dev server, demo the fix — one video carrying both states. Works on web + --source mac-screen sessions.", ["--json"]),
6198
6532
  cmdDoc("doctor", "clipy doctor [--json]", "One-shot health check: API reachability (GET /api/health, with latency), API key + whoami round-trip, Mac agent bridge (exists/parses/pid/appVersion>=" + MIN_BRIDGE_APP_VERSION + "), Playwright resolvability (and the resolved path/node_modules dir), context/proof prerequisites (yt-dlp presence/path/version, ffmpeg + ffprobe presence/version, and whether that ffmpeg has libwebp), and install mode (npx/global/local) — each a pass/warn/fail with a fix hint; exits non-zero if any check fails. Read-only: it never installs anything, so a missing yt-dlp/ffmpeg reports WARN with the install command rather than silently downloading a binary. Run it first whenever an import, proof, or recording fails.", ["--json"]),
@@ -6329,6 +6663,15 @@ async function main() {
6329
6663
  for: { type: "string" },
6330
6664
  timeout: { type: "string" },
6331
6665
  url: { type: "string" },
6666
+ // recheck
6667
+ out: { type: "string" },
6668
+ plan: { type: "boolean", default: false },
6669
+ "no-upload": { type: "boolean", default: false },
6670
+ "settle-ms": { type: "string" },
6671
+ "nav-timeout-ms": { type: "string" },
6672
+ "max-steps": { type: "string" },
6673
+ "fail-on-divergence": { type: "boolean", default: false },
6674
+ "allow-destructive": { type: "boolean", default: false },
6332
6675
  name: { type: "string" },
6333
6676
  title: { type: "string" },
6334
6677
  description: { type: "string" },
@@ -6374,10 +6717,37 @@ async function main() {
6374
6717
  width: { type: "string" },
6375
6718
  height: { type: "string" },
6376
6719
  wait: { type: "boolean", default: false },
6720
+ // Library management + bug evidence (library.ts).
6721
+ yes: { type: "boolean", default: false },
6722
+ "allow-delete": { type: "boolean", default: false },
6723
+ "clear-description": { type: "boolean", default: false },
6724
+ // What the recorder expected to happen (issue #741). Optional; shown to
6725
+ // agents as "Expected result" in the recording's AREC.
6726
+ expected: { type: "string" },
6727
+ "clear-expected": { type: "boolean", default: false },
6728
+ access: { type: "string" },
6729
+ create: { type: "string" },
6730
+ untag: { type: "string", multiple: true },
6731
+ "no-folder": { type: "boolean", default: false },
6732
+ "reply-to": { type: "string" },
6733
+ range: { type: "string" },
6734
+ console: { type: "boolean", default: false },
6735
+ network: { type: "boolean", default: false },
6736
+ errors: { type: "boolean", default: false },
6737
+ levels: { type: "string" },
6738
+ method: { type: "string" },
6739
+ host: { type: "string" },
6740
+ bodies: { type: "string" },
6741
+ after: { type: "string" },
6742
+ types: { type: "string" },
6743
+ "from-ms": { type: "string" },
6744
+ "to-ms": { type: "string" },
6745
+ cursor: { type: "string" },
6377
6746
  version: { type: "boolean", short: "v", default: false },
6378
6747
  help: { type: "boolean", short: "h", default: false },
6379
6748
  },
6380
6749
  });
6750
+ const expectedResult = values.expected?.trim() || undefined;
6381
6751
  if (values.version) {
6382
6752
  process.stdout.write(`${VERSION}\n`);
6383
6753
  return;
@@ -6461,12 +6831,16 @@ async function main() {
6461
6831
  const webAudioGuard = "--mic/--no-system-audio apply to --source mac-screen only — headless web captures record no audio at all, so there is nothing to turn on or off";
6462
6832
  const linuxAudioGuard = "--mic/--no-system-audio: Linux screen recordings are silent for now (narrate with clipy mark); drop the audio flag";
6463
6833
  const macAuthGuard = "auth state (--storage-state/--user-data-dir/--cookie/--local-storage/--init-script) applies to headless web capture — --source mac-screen records the real, already-logged-in screen";
6834
+ // Usage errors for the library commands honour --json like their API
6835
+ // errors do: one {ok:false, code:"usage_error", …} object on stdout.
6836
+ const usageFail = (message) => failure({ json, die }, "usage_error", message, "Fix the arguments; `clipy guide --json` lists every command's flags.", 2);
6464
6837
  switch (command) {
6465
6838
  case "login":
6466
6839
  await cmdLogin(ctx, {
6467
6840
  key: values.key,
6468
6841
  paste: Boolean(values.paste),
6469
6842
  noBrowser: Boolean(values["no-browser"]),
6843
+ allowDelete: Boolean(values["allow-delete"]),
6470
6844
  });
6471
6845
  return;
6472
6846
  case "logout":
@@ -6586,6 +6960,161 @@ async function main() {
6586
6960
  await cmdContext(ctx, rest[0]);
6587
6961
  return;
6588
6962
  }
6963
+ case "upload": {
6964
+ const file = rest[0] ?? values.video;
6965
+ if (!file)
6966
+ usageFail('usage: clipy upload <file.mp4|webm|mov> [--title "<t>"] [--type kind] [--expected "<text>"] [--access public|restricted|private] [--wait] [--json]', 2);
6967
+ // Validated here, not by requireRecordingKind/parseNoteFlag, whose die()
6968
+ // would print prose and break the one-object --json contract.
6969
+ let uploadKind;
6970
+ if (values.type) {
6971
+ uploadKind = normalizeRecordingKind(String(values.type)) ?? undefined;
6972
+ if (!uploadKind) {
6973
+ usageFail(`--type "${String(values.type)}" is not a recording kind. Accepted: ${RECORDING_KINDS.join(", ")}`);
6974
+ }
6975
+ }
6976
+ const uploadNotes = values.note ?? [];
6977
+ const passNote = uploadNotes.find((note) => /^\s*pass\s*\d/i.test(note));
6978
+ if (passNote !== undefined) {
6979
+ usageFail(`--note "${passNote}": an uploaded file has no passes; use absolute times such as "12: text"`);
6980
+ }
6981
+ await cmdUpload(ctx, file, {
6982
+ name: (values.title ?? values.name)?.trim() || undefined,
6983
+ description: values.description?.trim() || undefined,
6984
+ recordingKind: uploadKind,
6985
+ expectedResult,
6986
+ notes: uploadNotes.map(parseNoteFlag),
6987
+ accessMode: values.access,
6988
+ wait: Boolean(values.wait),
6989
+ json,
6990
+ });
6991
+ return;
6992
+ }
6993
+ case "update":
6994
+ if (!rest[0])
6995
+ usageFail('usage: clipy update <id|url> [--title "<title>"] [--description "<text>" | --clear-description] [--expected "<text>" | --clear-expected]', 2);
6996
+ await cmdUpdate(libraryDeps(ctx, json), rest[0], {
6997
+ title: values.title ?? values.name,
6998
+ description: values.description,
6999
+ clearDescription: Boolean(values["clear-description"]),
7000
+ expected: values.expected,
7001
+ clearExpected: Boolean(values["clear-expected"]),
7002
+ });
7003
+ return;
7004
+ case "share":
7005
+ if (!rest[0])
7006
+ usageFail("usage: clipy share <id|url> [public|restricted|private]", 2);
7007
+ await cmdShare(libraryDeps(ctx, json), rest[0], rest[1] ?? values.access);
7008
+ return;
7009
+ case "organize":
7010
+ if (!rest[0])
7011
+ usageFail("usage: clipy organize <id|url> [--folder <name|id> | --no-folder] [--tag <t>]… [--untag <t>]…", 2);
7012
+ await cmdOrganize(libraryDeps(ctx, json), rest[0], {
7013
+ folder: values.folder,
7014
+ noFolder: Boolean(values["no-folder"]),
7015
+ addTags: values.tag ?? [],
7016
+ removeTags: values.untag ?? [],
7017
+ });
7018
+ return;
7019
+ case "folders":
7020
+ await cmdFolders(libraryDeps(ctx, json), { create: values.create });
7021
+ return;
7022
+ case "delete":
7023
+ if (!rest[0])
7024
+ usageFail("usage: clipy delete <id|url> --yes", 2);
7025
+ await cmdDelete(libraryDeps(ctx, json), rest[0], { yes: Boolean(values.yes) });
7026
+ return;
7027
+ case "comments":
7028
+ if (!rest[0])
7029
+ usageFail("usage: clipy comments <id|url> [--json]", 2);
7030
+ await cmdComments(libraryDeps(ctx, json), rest[0]);
7031
+ return;
7032
+ case "comment": {
7033
+ if (!rest[0])
7034
+ usageFail('usage: clipy comment <id|url> "<text>" [--at <seconds> | --reply-to <comment-id>]', 2);
7035
+ const at = values.at;
7036
+ await cmdComment(libraryDeps(ctx, json), rest[0], rest.slice(1).join(" "), {
7037
+ atSeconds: at === undefined
7038
+ ? undefined
7039
+ : Number.isFinite(Number(at)) && Number(at) >= 0
7040
+ ? Number(at)
7041
+ : usageFail("--at must be a non-negative number of seconds"),
7042
+ replyTo: values["reply-to"],
7043
+ });
7044
+ return;
7045
+ }
7046
+ case "analytics": {
7047
+ if (!rest[0])
7048
+ usageFail("usage: clipy analytics <id|url> [--range <days>] [--json]", 2);
7049
+ const range = values.range === undefined ? undefined : Number(values.range);
7050
+ if (range !== undefined && (!Number.isInteger(range) || range < 1 || range > 365)) {
7051
+ usageFail("--range must be a whole number of days from 1 to 365", 2);
7052
+ }
7053
+ await cmdAnalytics(libraryDeps(ctx, json), rest[0], { range });
7054
+ return;
7055
+ }
7056
+ case "diagnostics":
7057
+ case "logs": {
7058
+ if (!rest[0])
7059
+ usageFail("usage: clipy diagnostics <id|url> [--errors] [--console] [--network] [--levels warn,error] [--status 5xx|4xx|failed|404] [--method M] [--host h] [--json]", 2);
7060
+ const optInt = (v, flag) => {
7061
+ if (v === undefined)
7062
+ return undefined;
7063
+ const n = Number(v);
7064
+ if (!Number.isInteger(n) || n < 0)
7065
+ usageFail(`${flag} must be a whole number`, 2);
7066
+ return n;
7067
+ };
7068
+ await cmdDiagnostics(libraryDeps(ctx, json), rest[0], {
7069
+ console: Boolean(values.console),
7070
+ network: Boolean(values.network),
7071
+ errors: Boolean(values.errors),
7072
+ levels: values.levels,
7073
+ status: values.status,
7074
+ method: values.method,
7075
+ host: values.host,
7076
+ bodies: values.bodies,
7077
+ limit: optInt(values.limit, "--limit"),
7078
+ after: optInt(values.after, "--after"),
7079
+ });
7080
+ return;
7081
+ }
7082
+ case "interactions": {
7083
+ if (!rest[0])
7084
+ usageFail("usage: clipy interactions <id|url> [--types click,dwell,…] [--from-ms N] [--to-ms N] [--limit N] [--cursor C] [--json]", 2);
7085
+ const optMs = (v, flag) => {
7086
+ if (v === undefined)
7087
+ return undefined;
7088
+ const n = Number(v);
7089
+ if (!Number.isInteger(n) || n < 0)
7090
+ usageFail(`${flag} must be a whole number of milliseconds`, 2);
7091
+ return n;
7092
+ };
7093
+ await cmdInteractions(libraryDeps(ctx, json), rest[0], {
7094
+ types: values.types,
7095
+ fromMs: optMs(values["from-ms"], "--from-ms"),
7096
+ toMs: optMs(values["to-ms"], "--to-ms"),
7097
+ limit: optMs(values.limit, "--limit"),
7098
+ cursor: values.cursor || undefined,
7099
+ });
7100
+ return;
7101
+ }
7102
+ case "recheck": {
7103
+ const numFlag = (v, fallback) => (v === undefined ? fallback : Number(v));
7104
+ await cmdRecheck(recheckDeps(ctx, json), rest[0], {
7105
+ startUrl: values.url?.trim() || undefined,
7106
+ outDir: values.out?.trim() || undefined,
7107
+ planOnly: Boolean(values.plan),
7108
+ upload: !values["no-upload"],
7109
+ settleMs: numFlag(values["settle-ms"], 800),
7110
+ navigationTimeoutMs: numFlag(values["nav-timeout-ms"], 5_000),
7111
+ maxSteps: numFlag(values["max-steps"], RECHECK_MAX_STEPS),
7112
+ failOnDivergence: Boolean(values["fail-on-divergence"]),
7113
+ allowDestructive: Boolean(values["allow-destructive"]),
7114
+ port: values.port === undefined ? undefined : Number(values.port),
7115
+ });
7116
+ return;
7117
+ }
6589
7118
  case "download":
6590
7119
  if (!rest[0])
6591
7120
  die("usage: clipy download <id|url> [-o <path>]", 2);
@@ -6685,6 +7214,7 @@ async function main() {
6685
7214
  undefined,
6686
7215
  description: values.description?.trim() || undefined,
6687
7216
  recordingKind: values.type ? requireRecordingKind(String(values.type)) : undefined,
7217
+ expectedResult,
6688
7218
  notes: (values.note ?? []).map(parseNoteFlag),
6689
7219
  wait: Boolean(values.wait),
6690
7220
  json,
@@ -6723,6 +7253,7 @@ async function main() {
6723
7253
  undefined,
6724
7254
  description: values.description?.trim() || undefined,
6725
7255
  recordingKind,
7256
+ expectedResult,
6726
7257
  window: values.window?.trim() || undefined,
6727
7258
  display: values.display?.trim() || undefined,
6728
7259
  xDisplay: values["x-display"]?.trim() || undefined,
@@ -6766,6 +7297,7 @@ async function main() {
6766
7297
  undefined,
6767
7298
  description: values.description?.trim() || undefined,
6768
7299
  recordingKind,
7300
+ expectedResult,
6769
7301
  window: values.window?.trim() || undefined,
6770
7302
  display: values.display?.trim() || undefined,
6771
7303
  notes: noteFlags.map(parseNoteFlag),
@@ -6804,6 +7336,7 @@ async function main() {
6804
7336
  undefined,
6805
7337
  description: values.description?.trim() || undefined,
6806
7338
  recordingKind,
7339
+ expectedResult,
6807
7340
  notes: noteFlags.map(parseNoteFlag),
6808
7341
  viewports: values.viewports ? parseViewports(String(values.viewports)) : null,
6809
7342
  width: num(values.width, 1280),
@@ -6861,6 +7394,7 @@ async function main() {
6861
7394
  undefined,
6862
7395
  description: values.description?.trim() || undefined,
6863
7396
  recordingKind: values.type ? requireRecordingKind(String(values.type)) : undefined,
7397
+ expectedResult,
6864
7398
  maxSec: num(values.max, SESSION_DEFAULT_MAX_SEC),
6865
7399
  width: num(values.width, 1280),
6866
7400
  height: num(values.height, 720),