@clipy/cli 0.4.1 → 0.8.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, createWriteStream, mkdirSync, openSync, readFileSync, readSync, renameSync, rmSync, statSync, writeFileSync, chmodSync } from "node:fs";
16
+ import { appendFileSync, closeSync, createWriteStream, mkdirSync, openSync, readFileSync, readSync, realpathSync, renameSync, rmSync, statSync, writeFileSync, chmodSync } from "node:fs";
17
17
  import { homedir, tmpdir } from "node:os";
18
18
  import { dirname, join, resolve } from "node:path";
19
19
  import { createInterface } from "node:readline";
@@ -22,9 +22,12 @@ import { createHash, randomUUID } from "node:crypto";
22
22
  import { Readable, Transform } from "node:stream";
23
23
  import { pipeline } from "node:stream/promises";
24
24
  import { createRequire } from "node:module";
25
+ import { pathToFileURL } from "node:url";
26
+ import { createServer } from "node:net";
27
+ import { createServer as createHttpServer } from "node:http";
25
28
  import { CLIPY_SKILL_MD } from "./skill.js";
26
29
  import { browserLogin, shouldUseManualLogin } from "./browserLogin.js";
27
- import { BridgeUnavailableError, bridgeRequest, listSources, readBridgeInfo, resolveCaptureSource, windowLabel, } from "./macBridge.js";
30
+ import { BridgeUnavailableError, bridgeRequest, inspectBridge, listSources, readBridgeInfo, resolveCaptureSource, windowLabel, probeSocketOpenable, probeBridgeHandshake, bridgeInfoFromFile, bridgeAppOutdated, MIN_BRIDGE_APP_VERSION, } from "./macBridge.js";
28
31
  // Exit quietly when stdout/stderr close early (e.g. `clipy list | head`).
29
32
  for (const stream of [process.stdout, process.stderr]) {
30
33
  stream.on("error", (e) => {
@@ -295,10 +298,22 @@ ${c.bold("RECORD")} ${c.dim("(needs an API key with the \"ingest\" permission)")
295
298
  --viewports <l> Record several sizes into ONE video, e.g.
296
299
  mobile,tablet,desktop or 390x844,1440x900 (chapters marked)
297
300
  --title/--description Recording metadata
298
- --note "12: text" Timestamped narration note (repeatable) — for silent
299
- captures the notes become the transcript
301
+ --type <kind> What this recording IS, so the AI summary reads it right:
302
+ bug|feature|demo|walkthrough|feedback|discussion|other
303
+ (aliases of bug_report/feature_request/product_demo/…)
304
+ --note "12: text" Timestamped narration note (repeatable). "12: text" is
305
+ absolute; "pass2: text" / "pass2@5: text" anchor to the
306
+ actual start of a --viewports pass. Silent captures → the
307
+ notes become the transcript
300
308
  --width/--height Viewport + video size (default 1280×720)
301
309
  --wait Block until the transcript is ready before printing
310
+ --json Print {id, shareUrl, contextUrl, sizeBytes}
311
+ ${c.dim("auth (headless web capture only) — seed a logged-in session BEFORE the")}
312
+ ${c.dim("first navigation, so an app's route guard sees it (never on --source mac-screen):")}
313
+ --storage-state <f> Playwright storageState JSON (cookies + localStorage)
314
+ --cookie "n=v[; Domain=d; Path=p; Secure; HttpOnly; SameSite=Lax]" (repeatable)
315
+ --local-storage "k=v" Seed a localStorage pair for the target origin (repeatable)
316
+ --init-script <f> Run a JS file before every page load
302
317
 
303
318
  ${c.bold("SESSION")} ${c.dim("(agent works, Clipy records — one active session per directory)")}
304
319
  ${c.dim("--source mac-screen on record/session records the REAL screen via the")}
@@ -307,12 +322,34 @@ ${c.bold("SESSION")} ${c.dim("(agent works, Clipy records — one active session
307
322
  sources List capturable displays + windows (ids for --window/--display)
308
323
  --window "<title|app|id>" Record just that window (e.g. --window Chrome)
309
324
  --display <id> Record a specific display
310
- session start --url <app> [--max <sec>] [--title <t>]
325
+ session start --url <app> [--max <sec>] [--title <t>] [--type <kind>] [--expose-cdp]
311
326
  Start recording in a background daemon and
312
327
  return immediately (auto-stops + uploads at
313
- --max, default ${SESSION_DEFAULT_MAX_SEC}s, cap ${SESSION_HARD_CAP_SEC}s)
314
- mark "<what just happened>" Drop a live timestamped note; marks become
315
- the recording's transcript chapters
328
+ --max, default ${SESSION_DEFAULT_MAX_SEC}s, cap ${SESSION_HARD_CAP_SEC}s). --type sets
329
+ the recording kind (see record). --expose-cdp
330
+ opens a CDP endpoint so your tools can drive the
331
+ page as it records (off by default; any local
332
+ process could attach — CLIPY_DISABLE_CDP=1 forces off).
333
+ Accepts the same auth flags as record
334
+ (--storage-state/--cookie/--local-storage/--init-script)
335
+ and --json (returns cdpUrl/cdpHttpUrl)
336
+ session run [start flags] -- <command …>
337
+ Start a session, run the command (inherited
338
+ stdio), then GUARANTEE cleanup: exit 0 uploads,
339
+ any non-zero exit or signal discards and
340
+ propagates the code. Sets CLIPY_SESSION=1 (+
341
+ CLIPY_CDP_URL with --expose-cdp). Crash-safe
342
+ wrapper for driver scripts — no dead-air uploads.
343
+ mark "<what just happened>" Drop a live timestamped note; marks become the
344
+ recording's transcript. Verify what you claim:
345
+ --assert-selector <css> assert an element exists (observed text recorded)
346
+ --assert-text <substr> require that element's text to contain <substr>
347
+ --assert-url <glob> assert the page URL matches (**/* wildcards)
348
+ --fail-mode warn|abort warn (default) annotates ASSERT ✗; abort
349
+ discards the whole session on a failed assertion
350
+ --at <sec> | --ago <sec> backdate the mark (absolute / N seconds ago)
351
+ chapter "<label>" Split the recording into BEFORE/AFTER sections
352
+ (demo base → chapter "AFTER" → demo the fix)
316
353
  session stop Finish: close browser, upload, print link
317
354
  session abort Discard the session — nothing is uploaded
318
355
  session status Show the active session's state
@@ -322,8 +359,13 @@ ${c.bold("AGENTS")}
322
359
  Install the bundled Clipy skill for a coding
323
360
  agent (teaches it to read + make recordings)
324
361
  agents status | uninstall <t> Show / remove installed skills
362
+ doctor [--json] Health check: API key, Mac agent bridge,
363
+ Playwright, and install mode — with fix hints
325
364
  guide --json Machine-readable manifest: every command,
326
365
  flag, env var, and exit code
366
+ playwright-path [--json] Print the node_modules dir of the Playwright
367
+ this CLI resolves, for your own driver scripts:
368
+ ${c.dim("NODE_PATH=$(clipy playwright-path) node driver.js")}
327
369
  transcript <id> --replace <file> Replace a transcript with agent-authored
328
370
  JSON ({segments} or {plaintext}); regenerates
329
371
  the summary ${c.dim("(needs the \"ingest\" permission)")}
@@ -332,7 +374,9 @@ ${c.bold("AGENTS")}
332
374
  ${c.bold("GLOBAL FLAGS")}
333
375
  --key <key> API key for this invocation (else CLIPY_API_KEY, else stored login)
334
376
  --api-url <url> API base (else CLIPY_API_URL, default https://clipy.online)
335
- --json Machine-readable output (list/search/show/transcript/summary/moments/wait)
377
+ --json Machine-readable output. Supported on: list, search, show,
378
+ transcript, summary, moments, wait, record, session
379
+ start/stop/status, mark, chapter, doctor, playwright-path
336
380
  -v, --version Print version
337
381
 
338
382
  ${c.bold("EXIT CODES")}
@@ -731,6 +775,294 @@ function cmdMcp() {
731
775
  child.on("exit", (code) => process.exit(code ?? 0));
732
776
  child.on("error", (e) => die(`failed to launch @clipy/mcp via npx: ${e.message}`));
733
777
  }
778
+ /** Non-dying key probe for doctor — reuses the whoami round-trip endpoint but
779
+ * returns structured results (die() would exit before other checks run) and
780
+ * distinguishes offline from rejected so we can degrade gracefully. */
781
+ async function probeApiKey(ctx) {
782
+ if (!ctx.apiKey)
783
+ return { ok: false, offline: false, status: 0, message: "no key" };
784
+ const controller = new AbortController();
785
+ const timer = setTimeout(() => controller.abort(), FETCH_TIMEOUT_MS);
786
+ try {
787
+ const res = await fetch(`${ctx.apiUrl}/api/v1/recordings?limit=1`, {
788
+ headers: {
789
+ Authorization: `Bearer ${ctx.apiKey}`,
790
+ Accept: "application/json",
791
+ "User-Agent": `clipy-cli/${VERSION}`,
792
+ },
793
+ signal: controller.signal,
794
+ });
795
+ if (res.ok)
796
+ return { ok: true, offline: false, status: res.status, message: "ok" };
797
+ let message = `HTTP ${res.status}`;
798
+ try {
799
+ const body = (await res.json());
800
+ if (typeof body.error === "string")
801
+ message = body.error;
802
+ }
803
+ catch {
804
+ // keep the HTTP status message
805
+ }
806
+ return { ok: false, offline: false, status: res.status, message };
807
+ }
808
+ catch (e) {
809
+ const message = e.name === "AbortError" ? "request timed out" : e.message;
810
+ return { ok: false, offline: true, status: 0, message };
811
+ }
812
+ finally {
813
+ clearTimeout(timer);
814
+ }
815
+ }
816
+ async function doctorAuthCheck(ctx) {
817
+ if (!ctx.apiKey) {
818
+ return {
819
+ name: "auth",
820
+ status: "fail",
821
+ detail: "no API key configured",
822
+ hint: "run `clipy login` (or set CLIPY_API_KEY)",
823
+ data: { hasKey: false },
824
+ };
825
+ }
826
+ const source = process.env.CLIPY_API_KEY === ctx.apiKey
827
+ ? "env CLIPY_API_KEY"
828
+ : readConfig().apiKey === ctx.apiKey
829
+ ? configPath()
830
+ : "--key flag";
831
+ const masked = `${ctx.apiKey.slice(0, 18)}…`;
832
+ const probe = await probeApiKey(ctx);
833
+ const data = { hasKey: true, keySource: source, apiUrl: ctx.apiUrl };
834
+ if (probe.ok) {
835
+ return { name: "auth", status: "pass", detail: `key ${masked} valid (${source}) against ${ctx.apiUrl}`, data };
836
+ }
837
+ if (probe.offline) {
838
+ return {
839
+ name: "auth",
840
+ status: "warn",
841
+ detail: `key ${masked} present (${source}) but ${ctx.apiUrl} is unreachable: ${probe.message}`,
842
+ hint: "check your connection — the key could not be verified",
843
+ data: { ...data, offline: true },
844
+ };
845
+ }
846
+ const hint = probe.status === 401
847
+ ? "the key is invalid or revoked — run `clipy login`"
848
+ : probe.status === 403
849
+ ? `the key lacks a required scope — mint one at ${ctx.apiUrl}/settings/api-keys`
850
+ : "check the key and --api-url";
851
+ return {
852
+ name: "auth",
853
+ status: "fail",
854
+ detail: `key ${masked} (${source}) rejected by ${ctx.apiUrl}: ${probe.message}`,
855
+ hint,
856
+ data: { ...data, status: probe.status },
857
+ };
858
+ }
859
+ function fmtAge(ms) {
860
+ const sec = Math.max(0, Math.round(ms / 1000));
861
+ if (sec < 90)
862
+ return `${sec}s`;
863
+ if (sec < 5400)
864
+ return `${Math.round(sec / 60)}m`;
865
+ return `${Math.round(sec / 3600)}h`;
866
+ }
867
+ /** The bridge produces several PASS/FAIL lines: the discovery FILE (validity +
868
+ * version), its MTIME freshness, the SOCKET's openability, and a live
869
+ * HANDSHAKE that confirms the running app answers and its version matches the
870
+ * file (catching the "stale artifact from an app that predates the bridge"
871
+ * case a pid check alone misses). */
872
+ async function doctorBridgeChecks() {
873
+ const b = inspectBridge();
874
+ const fileData = {
875
+ path: b.path,
876
+ exists: b.exists,
877
+ appVersion: b.appVersion,
878
+ pid: b.pid,
879
+ pidAlive: b.pidAlive,
880
+ minAppVersion: MIN_BRIDGE_APP_VERSION,
881
+ mtimeMs: b.mtimeMs,
882
+ };
883
+ if (!b.applicable) {
884
+ return [{ name: "bridge", status: "skip", detail: `n/a — ${b.detail}`, data: fileData }];
885
+ }
886
+ if (!b.exists) {
887
+ return [
888
+ {
889
+ name: "bridge",
890
+ status: "warn",
891
+ detail: `${b.detail} (${b.path})`,
892
+ hint: "only needed for --source mac-screen; open the Clipy app, or install/update it at https://clipy.online/download",
893
+ data: fileData,
894
+ },
895
+ ];
896
+ }
897
+ const out = [];
898
+ // 1) discovery file validity + version
899
+ if (b.healthy) {
900
+ out.push({ name: "bridge", status: "pass", detail: `${b.detail} at ${b.path}`, data: fileData });
901
+ }
902
+ else {
903
+ const predate = (b.pidAlive === false && bridgeAppOutdated(b.appVersion)) || b.versionOk === false;
904
+ const hint = predate
905
+ ? `your installed Clipy app likely predates the agent bridge (needs v${MIN_BRIDGE_APP_VERSION}+) — update via https://clipy.online/download`
906
+ : b.pidAlive === false
907
+ ? "open the Clipy app (its previous process quit)"
908
+ : "restart the Clipy app";
909
+ out.push({ name: "bridge", status: "fail", detail: `${b.detail} (${b.path})`, hint, data: fileData });
910
+ }
911
+ // 2) mtime freshness (the app rewrites the file every launch on 0.1.41+)
912
+ if (b.mtimeMs != null) {
913
+ const age = fmtAge(Date.now() - b.mtimeMs);
914
+ const staleShaped = b.pidAlive === false;
915
+ out.push({
916
+ name: "bridge mtime",
917
+ status: staleShaped ? "warn" : "info",
918
+ detail: staleShaped
919
+ ? `discovery file last written ${age} ago but its pid is dead — stale artifact`
920
+ : `discovery file written ${age} ago`,
921
+ ...(staleShaped
922
+ ? { hint: `a fresh Clipy launch should rewrite it; if it doesn't, the app predates the bridge (needs v${MIN_BRIDGE_APP_VERSION}+)` }
923
+ : {}),
924
+ data: { mtimeMs: b.mtimeMs },
925
+ });
926
+ }
927
+ // 3) + 4) socket openability + live handshake (only when the file is complete)
928
+ if (b.complete && b.socketPath) {
929
+ const openable = await probeSocketOpenable(b.socketPath);
930
+ out.push({
931
+ name: "bridge socket",
932
+ status: openable ? "pass" : "fail",
933
+ detail: openable ? `socket openable at ${b.socketPath}` : `socket not answering at ${b.socketPath}`,
934
+ ...(openable ? {} : { hint: "stale bridge artifact — restart the Clipy app" }),
935
+ data: { socketPath: b.socketPath, openable },
936
+ });
937
+ if (openable) {
938
+ const info = bridgeInfoFromFile();
939
+ if (info) {
940
+ const hs = await probeBridgeHandshake(info);
941
+ if (hs.ok) {
942
+ const match = !hs.appVersion || !b.appVersion || hs.appVersion === b.appVersion;
943
+ out.push({
944
+ name: "bridge handshake",
945
+ status: match ? "pass" : "fail",
946
+ detail: match
947
+ ? `app answered "status" (v${hs.appVersion ?? "?"})`
948
+ : `discovery file says v${b.appVersion} but the running app reports v${hs.appVersion} — stale bridge artifact`,
949
+ ...(match ? {} : { hint: "restart the Clipy app so it rewrites the discovery file" }),
950
+ data: { fileAppVersion: b.appVersion, liveAppVersion: hs.appVersion ?? null },
951
+ });
952
+ }
953
+ else {
954
+ out.push({
955
+ name: "bridge handshake",
956
+ status: "fail",
957
+ detail: `no answer to a "status" handshake: ${hs.error}`,
958
+ hint: bridgeAppOutdated(b.appVersion)
959
+ ? `your installed Clipy app likely predates the agent bridge (needs v${MIN_BRIDGE_APP_VERSION}+) — update via https://clipy.online/download`
960
+ : "stale bridge artifact — restart the Clipy app",
961
+ });
962
+ }
963
+ }
964
+ }
965
+ }
966
+ return out;
967
+ }
968
+ async function doctorPlaywrightCheck() {
969
+ const res = await resolvePlaywright();
970
+ if (res.ok) {
971
+ // "PASS" here only means Clipy can load Playwright — NOT that the user's own
972
+ // --expose-cdp driver script will, since it resolves from a different cwd.
973
+ // Report where we found it, and always hand back the NODE_PATH escape hatch.
974
+ const nodeModulesDir = res.path ? nodeModulesDirOf(res.path) : null;
975
+ return {
976
+ name: "playwright",
977
+ status: "pass",
978
+ detail: `resolved via ${res.source}${res.path ? ` (${res.path})` : ""}`,
979
+ hint: "your own scripts (e.g. --expose-cdp drivers) resolve Playwright independently — from another directory `require('playwright')` can fail; run them with NODE_PATH=$(clipy playwright-path) or install Playwright there",
980
+ data: { source: res.source, path: res.path ?? null, nodeModulesDir },
981
+ };
982
+ }
983
+ const { mode } = detectInstallMode();
984
+ return {
985
+ name: "playwright",
986
+ status: "fail",
987
+ detail: `${res.error} — record/session cannot launch a browser`,
988
+ hint: playwrightInstallHint(mode),
989
+ data: { installMode: mode },
990
+ };
991
+ }
992
+ function doctorInstallCheck() {
993
+ const { mode, argv1 } = detectInstallMode();
994
+ const label = {
995
+ npx: "npx cache (isolated)",
996
+ global: "global install",
997
+ local: "project-local install",
998
+ unknown: "unknown (running from source?)",
999
+ };
1000
+ const hint = mode === "npx"
1001
+ ? "for repeated use, `npm i -g @clipy/cli` — a global install can load a global Playwright; the npx cache can't"
1002
+ : undefined;
1003
+ return {
1004
+ name: "install",
1005
+ status: "info",
1006
+ detail: `${label[mode]} — ${argv1 || "?"}`,
1007
+ hint,
1008
+ data: { mode, argv1 },
1009
+ };
1010
+ }
1011
+ function doctorGlyph(status) {
1012
+ switch (status) {
1013
+ case "pass":
1014
+ return c.green("PASS");
1015
+ case "warn":
1016
+ return c.yellow("WARN");
1017
+ case "fail":
1018
+ return c.red("FAIL");
1019
+ case "skip":
1020
+ return c.dim("SKIP");
1021
+ default:
1022
+ return c.dim("INFO");
1023
+ }
1024
+ }
1025
+ async function cmdDoctor(ctx, json) {
1026
+ const checks = [
1027
+ await doctorAuthCheck(ctx),
1028
+ ...(await doctorBridgeChecks()),
1029
+ await doctorPlaywrightCheck(),
1030
+ doctorInstallCheck(),
1031
+ ];
1032
+ const failed = checks.filter((chk) => chk.status === "fail").length;
1033
+ if (json) {
1034
+ printJson({
1035
+ version: VERSION,
1036
+ apiUrl: ctx.apiUrl,
1037
+ ok: failed === 0,
1038
+ checks: checks.map((chk) => ({
1039
+ name: chk.name,
1040
+ status: chk.status,
1041
+ detail: chk.detail,
1042
+ ...(chk.hint ? { hint: chk.hint } : {}),
1043
+ ...(chk.data ? { data: chk.data } : {}),
1044
+ })),
1045
+ });
1046
+ if (failed > 0)
1047
+ process.exitCode = 1;
1048
+ return;
1049
+ }
1050
+ process.stdout.write(`${c.bold("clipy doctor")} ${c.dim(`— v${VERSION} · ${ctx.apiUrl}`)}\n\n`);
1051
+ for (const chk of checks) {
1052
+ // Pad to the longest check name ("bridge handshake") so details align.
1053
+ process.stdout.write(`${doctorGlyph(chk.status)} ${chk.name.padEnd(16)} ${chk.detail}\n`);
1054
+ if (chk.hint)
1055
+ process.stdout.write(` ${c.dim(`↳ ${chk.hint}`)}\n`);
1056
+ }
1057
+ process.stdout.write("\n");
1058
+ if (failed === 0) {
1059
+ process.stdout.write(`${c.green("✓")} no failures\n`);
1060
+ }
1061
+ else {
1062
+ process.stdout.write(`${c.red(`✗ ${failed} check${failed === 1 ? "" : "s"} failed`)} — see the hints above.\n`);
1063
+ process.exitCode = 1;
1064
+ }
1065
+ }
734
1066
  // ---------------------------------------------------------------------------
735
1067
  // record — the ONE write command. Drives a headless browser (Playwright),
736
1068
  // captures the page to WebM, and streams it through Clipy's raw-upload
@@ -844,23 +1176,166 @@ async function ingestPostChunk(ctx, recordingId, uploadToken, partNumber, bytes)
844
1176
  throw new Error(`chunk ${partNumber} failed (HTTP ${res.status})${text ? `: ${text}` : ""}`);
845
1177
  }
846
1178
  }
847
- async function loadChromium() {
1179
+ /** Pull `chromium` out of a dynamically-imported Playwright module. A bare
1180
+ * `import('playwright')` (via the package `exports` map) exposes it as a named
1181
+ * export, but importing the raw index.js by file URL (the cwd-local path
1182
+ * below) hits CJS→ESM interop where it only lands on `.default`. Check both. */
1183
+ function chromiumFrom(mod) {
1184
+ const m = mod;
1185
+ return m.chromium ?? m.default?.chromium;
1186
+ }
1187
+ async function resolvePlaywright() {
1188
+ // 1) Resolve relative to the CLI itself — a normal dependency, or a global
1189
+ // Playwright sitting beside a global `@clipy/cli` in the same node_modules.
848
1190
  for (const mod of ["playwright", "playwright-core"]) {
849
1191
  try {
850
- const pw = (await import(mod));
851
- if (pw.chromium)
852
- return pw.chromium;
1192
+ const chromium = chromiumFrom(await import(mod));
1193
+ if (chromium) {
1194
+ // A bare import doesn't tell us WHERE it loaded from; ask the resolver
1195
+ // for the absolute entry path so doctor/playwright-path can report it.
1196
+ let path;
1197
+ try {
1198
+ path = createRequire(import.meta.url).resolve(mod);
1199
+ }
1200
+ catch {
1201
+ // resolved as a module but not to a concrete file path — leave unknown
1202
+ }
1203
+ return { ok: true, chromium, source: `import('${mod}')`, path };
1204
+ }
1205
+ }
1206
+ catch {
1207
+ // try the next strategy
1208
+ }
1209
+ }
1210
+ // 2) Resolve relative to the user's project (cwd). Under `npx @clipy/cli` the
1211
+ // package lives in an isolated cache that a bare ESM import cannot resolve
1212
+ // a global/project Playwright from, but a require rooted at cwd can.
1213
+ for (const mod of ["playwright", "playwright-core"]) {
1214
+ try {
1215
+ const requireFromCwd = createRequire(join(process.cwd(), "package.json"));
1216
+ const resolved = requireFromCwd.resolve(mod);
1217
+ const chromium = chromiumFrom(await import(pathToFileURL(resolved).href));
1218
+ if (chromium)
1219
+ return { ok: true, chromium, source: `${mod} at ${dirname(resolved)}`, path: resolved };
853
1220
  }
854
1221
  catch {
855
- // try the next module
1222
+ // fall through to the miss
856
1223
  }
857
1224
  }
858
- die(`clipy record needs Playwright (a headless browser). Install it once:\n` +
1225
+ return {
1226
+ ok: false,
1227
+ source: null,
1228
+ error: "Playwright is not installed where this CLI can load it (tried a bundled import and a cwd-local resolve)",
1229
+ };
1230
+ }
1231
+ /** Classify how this CLI was invoked so install hints match the user's setup.
1232
+ * npx runs from an isolated `_npx` cache; a global bin lives outside cwd; a
1233
+ * project-local install sits under cwd/node_modules. */
1234
+ function detectInstallMode() {
1235
+ const raw = process.argv[1] ? resolve(process.argv[1]) : "";
1236
+ // nvm/npm global bins are SYMLINKS (…/bin/clipy → …/lib/node_modules/@clipy/cli/dist/index.js).
1237
+ // Match against the REAL path or every global install misreports as
1238
+ // "unknown (running from source?)"; fall back to the raw path on a broken link.
1239
+ let argv1 = raw;
1240
+ try {
1241
+ if (raw)
1242
+ argv1 = realpathSync(raw);
1243
+ }
1244
+ catch {
1245
+ // dangling/permission-denied symlink — keep the raw path
1246
+ }
1247
+ const norm = argv1.replace(/\\/g, "/");
1248
+ const cwd = resolve(process.cwd()).replace(/\\/g, "/");
1249
+ let mode = "unknown";
1250
+ if (/\/_npx\//.test(norm))
1251
+ mode = "npx";
1252
+ else if (norm.startsWith(`${cwd}/`) && /\/node_modules\//.test(norm))
1253
+ mode = "local";
1254
+ else if (/\/node_modules\//.test(norm))
1255
+ mode = "global";
1256
+ return { mode, argv1 };
1257
+ }
1258
+ /** From a resolved package entry file, the node_modules DIRECTORY that contains
1259
+ * it — the substring up to and including the last "node_modules" segment — so
1260
+ * `NODE_PATH=$(clipy playwright-path) node driver.js` can require playwright.
1261
+ * Returns null when the entry isn't under a node_modules dir (linked/monorepo). */
1262
+ function nodeModulesDirOf(entryPath) {
1263
+ // \\→/ is a 1:1 char swap, so the index is valid against the original string.
1264
+ const idx = entryPath.replace(/\\/g, "/").lastIndexOf("/node_modules");
1265
+ if (idx < 0)
1266
+ return null;
1267
+ return entryPath.slice(0, idx + "/node_modules".length);
1268
+ }
1269
+ /** One-line install hint keyed to the install mode (the `doctor` ↳ line). For
1270
+ * npx we LEAD with the cwd-local install — the only guaranteed-working fix,
1271
+ * since the resolver's cwd-local strategy loads it and the npx cache can't see
1272
+ * a global one. */
1273
+ function playwrightInstallHint(mode) {
1274
+ if (mode === "npx") {
1275
+ return "in your project dir: npm i playwright && npx playwright install chromium (then re-run) — or install globally: npm i -g @clipy/cli playwright && clipy …";
1276
+ }
1277
+ if (mode === "local")
1278
+ return "npm i -D playwright && npx playwright install chromium";
1279
+ return "npm install -g playwright && npx playwright install chromium";
1280
+ }
1281
+ /** The full, multi-line message record/daemon die() with when Playwright is
1282
+ * missing — the npx branch is the important fix: `npm i -g playwright` cannot
1283
+ * help a package running from the npx cache (ESM there can't see globals), so
1284
+ * we lead with the cwd-local install, which the resolver DOES load. */
1285
+ function playwrightMissingMessage(mode) {
1286
+ const head = "clipy record needs Playwright (a headless browser), but it isn't installed where this CLI can load it.";
1287
+ if (mode === "npx") {
1288
+ return (`${head}\n` +
1289
+ `You're running via npx, whose isolated cache can't load a globally-installed Playwright. The reliable fix is a project-local install — run this in your project directory (the one you'll run clipy from):\n` +
1290
+ ` ${c.bold("npm i playwright && npx playwright install chromium")}\n` +
1291
+ `then re-run your command. Alternatively, install everything globally and run the global clipy (not npx):\n` +
1292
+ ` ${c.bold("npm i -g @clipy/cli playwright && npx playwright install chromium && clipy record …")}`);
1293
+ }
1294
+ if (mode === "local") {
1295
+ return (`${head}\n` +
1296
+ ` ${c.bold("npm i -D playwright && npx playwright install chromium")}\n` +
1297
+ `Then re-run your command.`);
1298
+ }
1299
+ return (`${head}\n` +
859
1300
  ` ${c.bold("npm install -g playwright")}\n` +
860
1301
  ` ${c.bold("npx playwright install chromium")}\n` +
861
1302
  `Then re-run your command. (Playwright is kept out of the base CLI so the ` +
862
1303
  `read-only commands stay a small, dependency-free install.)`);
863
1304
  }
1305
+ async function loadChromium() {
1306
+ const res = await resolvePlaywright();
1307
+ if (res.ok)
1308
+ return res.chromium;
1309
+ die(playwrightMissingMessage(detectInstallMode().mode));
1310
+ }
1311
+ /** `clipy playwright-path` — print the node_modules DIRECTORY holding the
1312
+ * Playwright this CLI resolves, so a user's own driver script can find the same
1313
+ * copy: `NODE_PATH=$(clipy playwright-path) node driver.js`. Exits non-zero
1314
+ * (empty stdout) if Playwright is unresolvable, so the command substitution
1315
+ * fails loudly rather than handing NODE_PATH a bogus value. */
1316
+ async function cmdPlaywrightPath(json) {
1317
+ const res = await resolvePlaywright();
1318
+ if (!res.ok) {
1319
+ if (json) {
1320
+ printJson({ path: null, nodeModulesDir: null, source: null });
1321
+ process.exitCode = 1;
1322
+ return;
1323
+ }
1324
+ die(`${res.error}\n${playwrightInstallHint(detectInstallMode().mode)}`, 1);
1325
+ }
1326
+ const nodeModulesDir = res.path ? nodeModulesDirOf(res.path) : null;
1327
+ if (json) {
1328
+ printJson({ path: res.path ?? null, nodeModulesDir, source: res.source });
1329
+ if (!nodeModulesDir)
1330
+ process.exitCode = 1;
1331
+ return;
1332
+ }
1333
+ if (!nodeModulesDir) {
1334
+ die(`Playwright resolved${res.path ? ` at ${res.path}` : ""} but not from a node_modules directory — ` +
1335
+ `NODE_PATH can't point at it; install Playwright in your script's project instead`, 1);
1336
+ }
1337
+ process.stdout.write(`${nodeModulesDir}\n`);
1338
+ }
864
1339
  /** Named viewport presets for `--viewports` (agent demos across screen sizes). */
865
1340
  const VIEWPORT_ALIASES = {
866
1341
  mobile: { width: 390, height: 844 },
@@ -887,13 +1362,55 @@ function parseViewports(spec) {
887
1362
  die("--viewports supports at most 8 sizes per recording", 2);
888
1363
  return out;
889
1364
  }
890
- /** Parses a `--note` flag value: "12: opened settings" or "12.5s: text" → note
891
- * at 12s. A value with no timestamp prefix becomes a note at 0s. */
1365
+ /**
1366
+ * Parses a `--note` flag value. Strict grammar — three shapes:
1367
+ * "12: text" / "12.5s: text" → absolute note at 12s
1368
+ * "pass2: text" → note at the real start of viewport pass 2
1369
+ * "pass2@5: text" / "pass2@5s: t" → 5s into pass 2's real start
1370
+ * A value with no recognized prefix is a bare note at 0s. A value that LOOKS
1371
+ * like a pass directive but is malformed (e.g. "pass2 text" with no colon, or
1372
+ * "pass0:") is REJECTED, not silently demoted to an absolute-0 note — a wrong
1373
+ * timestamp that pairs a note with the wrong pass is worse than a hard error.
1374
+ */
892
1375
  function parseNoteFlag(value) {
893
- const m = value.match(/^\s*(\d+(?:\.\d+)?)s?\s*:\s*(.+)$/);
1376
+ const v = value.trim();
1377
+ const passMatch = v.match(/^pass\s*(\d+)\s*(?:@\s*(\d+(?:\.\d+)?)\s*s?)?\s*:\s*(.+)$/i);
1378
+ if (passMatch) {
1379
+ const pass = parseInt(passMatch[1], 10);
1380
+ if (pass < 1) {
1381
+ die(`invalid --note "${value}": pass number must be an integer ≥ 1 (e.g. "pass2: text")`, 2);
1382
+ }
1383
+ return {
1384
+ pass,
1385
+ passOffsetMs: passMatch[2] ? Math.round(parseFloat(passMatch[2]) * 1000) : 0,
1386
+ text: passMatch[3].trim(),
1387
+ };
1388
+ }
1389
+ // Attempted-but-malformed pass directive ("pass2 text", "pass2@: x", "pass0:").
1390
+ if (/^pass\s*\d/i.test(v)) {
1391
+ die(`invalid --note "${value}": pass-scoped notes are "passN: text" or "passN@<seconds>: text" ` +
1392
+ `(integer pass ≥ 1, optional @seconds), e.g. "pass2: mobile" or "pass2@5: after scroll"`, 2);
1393
+ }
1394
+ const m = v.match(/^(\d+(?:\.\d+)?)\s*s?\s*:\s*(.+)$/);
894
1395
  if (m)
895
1396
  return { startMs: Math.round(parseFloat(m[1]) * 1000), text: m[2].trim() };
896
- return { startMs: 0, text: value.trim() };
1397
+ return { startMs: 0, text: v };
1398
+ }
1399
+ /** Highest pass index referenced by any pass-scoped note (0 = none). */
1400
+ function maxPassRef(parsed) {
1401
+ return parsed.reduce((m, n) => (n.pass != null && n.pass > m ? n.pass : m), 0);
1402
+ }
1403
+ /** Anchor parsed notes to absolute ms using the recorded pass start offsets
1404
+ * (index 0 = pass 1). Pass-scoped notes land at their pass's real start (+offset);
1405
+ * absolute notes pass through. An out-of-range pass clamps to the last pass. */
1406
+ function resolveNarrationNotes(parsed, passStartsMs) {
1407
+ return parsed.map((n) => {
1408
+ if (n.pass != null) {
1409
+ const base = passStartsMs[n.pass - 1] ?? passStartsMs[passStartsMs.length - 1] ?? 0;
1410
+ return { startMs: Math.max(0, Math.round(base + (n.passOffsetMs ?? 0))), text: n.text };
1411
+ }
1412
+ return { startMs: Math.max(0, Math.round(n.startMs ?? 0)), text: n.text };
1413
+ });
897
1414
  }
898
1415
  /** WebM/Matroska files start with the EBML magic. Refuse to upload anything
899
1416
  * else — a crashed Chromium can leave a zero-byte or garbage file behind. */
@@ -914,6 +1431,51 @@ function validateWebmFile(videoPath) {
914
1431
  }
915
1432
  return size;
916
1433
  }
1434
+ // --- Recording kind (--type) -----------------------------------------------
1435
+ // Declares what a recording IS, so the AI summary doesn't misread a demo as a
1436
+ // bug report. Sent as `recordingKind` on raw-upload/complete. The literals +
1437
+ // aliases mirror the server contract exactly (server also normalizes and
1438
+ // ignores unknowns); the CLI validates locally so agents get instant feedback.
1439
+ const RECORDING_KINDS = [
1440
+ "bug_report",
1441
+ "feature_request",
1442
+ "product_demo",
1443
+ "walkthrough_tutorial",
1444
+ "feedback_review",
1445
+ "discussion_talk",
1446
+ "other",
1447
+ ];
1448
+ const RECORDING_KIND_ALIASES = {
1449
+ bug: "bug_report",
1450
+ feature: "feature_request",
1451
+ demo: "product_demo",
1452
+ product: "product_demo",
1453
+ walkthrough: "walkthrough_tutorial",
1454
+ tutorial: "walkthrough_tutorial",
1455
+ guide: "walkthrough_tutorial",
1456
+ feedback: "feedback_review",
1457
+ review: "feedback_review",
1458
+ discussion: "discussion_talk",
1459
+ talk: "discussion_talk",
1460
+ meeting: "discussion_talk",
1461
+ };
1462
+ /** Normalize a --type value (case/space/hyphen-insensitive) to a canonical
1463
+ * recordingKind literal, or null if unrecognized. */
1464
+ function normalizeRecordingKind(input) {
1465
+ const norm = input.trim().toLowerCase().replace(/[\s-]+/g, "_");
1466
+ if (RECORDING_KINDS.includes(norm))
1467
+ return norm;
1468
+ return RECORDING_KIND_ALIASES[norm] ?? null;
1469
+ }
1470
+ /** Validate a --type value; die() with the accepted list on a miss. */
1471
+ function requireRecordingKind(input) {
1472
+ const kind = normalizeRecordingKind(input);
1473
+ if (!kind) {
1474
+ die(`--type "${input}" is not a recording kind. Accepted: ${RECORDING_KINDS.join(", ")} ` +
1475
+ `(aliases: bug, feature, demo/product, walkthrough/tutorial/guide, feedback/review, discussion/talk/meeting)`, 2);
1476
+ }
1477
+ return kind;
1478
+ }
917
1479
  /**
918
1480
  * Streams a captured WebM through Clipy's raw-upload pipeline
919
1481
  * (initiate → chunks → finalize → complete). Shared by `clipy record` and
@@ -979,6 +1541,7 @@ async function uploadWebmToClipy(ctx, opts) {
979
1541
  description: opts.description,
980
1542
  sourcePlatform: "web",
981
1543
  sourceVersion: `cli/${VERSION}`,
1544
+ ...(opts.recordingKind ? { recordingKind: opts.recordingKind } : {}),
982
1545
  ...(opts.narration && (opts.narration.text || opts.narration.notes?.length)
983
1546
  ? { narration: opts.narration }
984
1547
  : {}),
@@ -1002,6 +1565,189 @@ async function uploadWebmToClipy(ctx, opts) {
1002
1565
  sizeBytes,
1003
1566
  };
1004
1567
  }
1568
+ /**
1569
+ * Blank-frame heuristic. We can't decode pixels without a dependency, so JPEG
1570
+ * size per megapixel is our stddev/complexity proxy: a uniform "still
1571
+ * compiling" screen compresses to a tiny JPEG, real UI to a much larger one.
1572
+ * Calibrated at quality 30 on a 1280×720 viewport — solid colours, a bare
1573
+ * "Compiling…" line, and a lone spinner all land ~6.7–7.0 KB/MP; a real page
1574
+ * with a header, nav, text and a table is ~22 KB/MP. 12 KB/MP sits well clear
1575
+ * of both, biased to treat splash/compile screens as blank.
1576
+ */
1577
+ function isBlankFrame(jpeg, width, height) {
1578
+ const px = Math.max(1, width * height);
1579
+ const bytesPerMegapixel = (jpeg.length / px) * 1_000_000;
1580
+ return bytesPerMegapixel < 12_000;
1581
+ }
1582
+ /**
1583
+ * Poll cheap JPEG screenshots until the frame has real content (not the blank
1584
+ * t=0 a still-compiling dev server shows) or a 10s cap, so the capture clock —
1585
+ * and every note anchored to it — starts on the first meaningful frame, not on
1586
+ * a blank one. Returns the ms spent waiting; logs when it waited meaningfully.
1587
+ */
1588
+ async function waitForFirstPaint(page, size, log) {
1589
+ const CAP_MS = 10_000;
1590
+ const POLL_MS = 250;
1591
+ const start = Date.now();
1592
+ for (;;) {
1593
+ let blank = true;
1594
+ try {
1595
+ const buf = await page.screenshot({ type: "jpeg", quality: 30 });
1596
+ blank = isBlankFrame(buf, size.width, size.height);
1597
+ }
1598
+ catch {
1599
+ blank = true; // screenshot failed (page not ready yet) — keep waiting
1600
+ }
1601
+ if (!blank)
1602
+ break;
1603
+ if (Date.now() - start >= CAP_MS) {
1604
+ log(c.yellow(`no meaningful paint after ${Math.round(CAP_MS / 1000)}s — starting the clock anyway (a blank app shell is fine)`));
1605
+ break;
1606
+ }
1607
+ await page.waitForTimeout(POLL_MS);
1608
+ }
1609
+ const waited = Date.now() - start;
1610
+ if (waited >= POLL_MS * 2)
1611
+ log(c.dim(`waited ${(waited / 1000).toFixed(1)}s for first meaningful paint`));
1612
+ return waited;
1613
+ }
1614
+ /** Parse one `--cookie` value into a Playwright cookie. Grammar:
1615
+ * `name=value[; Domain=d; Path=p; Secure; HttpOnly; SameSite=Lax]`. The first
1616
+ * `;`-segment is name=value (split on the first `=`); later segments are
1617
+ * case-insensitive attributes. Without a Domain we url-scope the cookie to the
1618
+ * target; with one we domain-scope it. Throws on a malformed spec so the parent
1619
+ * can turn it into a die(2). */
1620
+ function parseCookieSpec(spec, targetUrl) {
1621
+ const segments = spec.split(";").map((s) => s.trim()).filter(Boolean);
1622
+ if (segments.length === 0)
1623
+ throw new Error(`--cookie "${spec}" is empty`);
1624
+ const eq = segments[0].indexOf("=");
1625
+ if (eq < 1)
1626
+ throw new Error(`--cookie "${spec}" must start with name=value`);
1627
+ const name = segments[0].slice(0, eq).trim();
1628
+ const value = segments[0].slice(eq + 1).trim();
1629
+ if (!name)
1630
+ throw new Error(`--cookie "${spec}" has an empty name`);
1631
+ let domain;
1632
+ let path;
1633
+ let secure = false;
1634
+ let httpOnly = false;
1635
+ let sameSite;
1636
+ for (const seg of segments.slice(1)) {
1637
+ const aEq = seg.indexOf("=");
1638
+ const attr = (aEq >= 0 ? seg.slice(0, aEq) : seg).trim().toLowerCase();
1639
+ const aVal = aEq >= 0 ? seg.slice(aEq + 1).trim() : "";
1640
+ switch (attr) {
1641
+ case "domain":
1642
+ domain = aVal;
1643
+ break;
1644
+ case "path":
1645
+ path = aVal;
1646
+ break;
1647
+ case "secure":
1648
+ secure = true;
1649
+ break;
1650
+ case "httponly":
1651
+ httpOnly = true;
1652
+ break;
1653
+ case "samesite": {
1654
+ const s = aVal.toLowerCase();
1655
+ sameSite = s === "strict" ? "Strict" : s === "none" ? "None" : "Lax";
1656
+ break;
1657
+ }
1658
+ default:
1659
+ throw new Error(`--cookie "${spec}": unknown attribute "${attr}" (accepted: Domain, Path, Secure, HttpOnly, SameSite)`);
1660
+ }
1661
+ }
1662
+ if (domain) {
1663
+ return { name, value, domain, path: path || "/", secure, httpOnly, ...(sameSite ? { sameSite } : {}) };
1664
+ }
1665
+ return { name, value, url: targetUrl };
1666
+ }
1667
+ /** Parse one `--local-storage` value ("key=value"; value may be empty). */
1668
+ function parseLocalStorageSpec(spec) {
1669
+ const eq = spec.indexOf("=");
1670
+ if (eq < 1)
1671
+ throw new Error(`--local-storage "${spec}" must be key=value`);
1672
+ return [spec.slice(0, eq), spec.slice(eq + 1)];
1673
+ }
1674
+ /** The single init script that seeds localStorage. Each pair is origin-guarded
1675
+ * so it never leaks into an unexpected origin the page might navigate to, and
1676
+ * runs before page scripts so route guards see the storage on first paint. */
1677
+ function localStorageInitScript(pairs, origin) {
1678
+ return pairs
1679
+ .map(([k, v]) => `if (location.origin === ${JSON.stringify(origin)}) localStorage.setItem(${JSON.stringify(k)}, ${JSON.stringify(v)});`)
1680
+ .join("\n");
1681
+ }
1682
+ /** Validate the auth-capture flags in the PARENT process — before launching a
1683
+ * browser or daemonizing — so an agent gets an instant, precise usage error
1684
+ * instead of a cryptic daemon-log failure. NEVER prints the storage-state
1685
+ * contents: it holds live credentials; only a shape warning is emitted. */
1686
+ function validateAuthCapture(auth, targetUrl) {
1687
+ if (auth.storageStatePath) {
1688
+ let raw;
1689
+ try {
1690
+ raw = readFileSync(auth.storageStatePath, "utf8");
1691
+ }
1692
+ catch {
1693
+ die(`--storage-state file not found or unreadable: ${auth.storageStatePath}`, 2);
1694
+ }
1695
+ let parsed;
1696
+ try {
1697
+ parsed = JSON.parse(raw);
1698
+ }
1699
+ catch {
1700
+ die(`--storage-state is not valid JSON: ${auth.storageStatePath}`, 2);
1701
+ }
1702
+ if (typeof parsed !== "object" || parsed === null || Array.isArray(parsed)) {
1703
+ die(`--storage-state must be a Playwright storageState JSON object: ${auth.storageStatePath}`, 2);
1704
+ }
1705
+ if (!("cookies" in parsed) && !("origins" in parsed)) {
1706
+ process.stderr.write(`${c.yellow("warning:")} --storage-state has neither "cookies" nor "origins" — it may not be a Playwright storageState file\n`);
1707
+ }
1708
+ }
1709
+ if (auth.initScriptPath) {
1710
+ try {
1711
+ statSync(auth.initScriptPath);
1712
+ }
1713
+ catch {
1714
+ die(`--init-script file not found: ${auth.initScriptPath}`, 2);
1715
+ }
1716
+ }
1717
+ // Parse the cookie / local-storage specs now purely to surface grammar errors
1718
+ // up front; the values are re-parsed where they're applied.
1719
+ for (const spec of auth.cookieSpecs) {
1720
+ try {
1721
+ parseCookieSpec(spec, targetUrl);
1722
+ }
1723
+ catch (e) {
1724
+ die(e.message, 2);
1725
+ }
1726
+ }
1727
+ for (const spec of auth.localStorageSpecs) {
1728
+ try {
1729
+ parseLocalStorageSpec(spec);
1730
+ }
1731
+ catch (e) {
1732
+ die(e.message, 2);
1733
+ }
1734
+ }
1735
+ }
1736
+ /** Apply cookies, seeded localStorage, and the user init script to a freshly
1737
+ * created context, in that order, BEFORE newPage()/goto. --storage-state is
1738
+ * applied by the caller at newContext() time (Playwright takes the file path
1739
+ * directly), not here. Re-parses the raw specs the parent already validated. */
1740
+ async function applyAuthCapture(context, auth, targetUrl) {
1741
+ const cookies = auth.cookieSpecs.map((s) => parseCookieSpec(s, targetUrl));
1742
+ if (cookies.length)
1743
+ await context.addCookies(cookies);
1744
+ const pairs = auth.localStorageSpecs.map(parseLocalStorageSpec);
1745
+ if (pairs.length) {
1746
+ await context.addInitScript({ content: localStorageInitScript(pairs, new URL(targetUrl).origin) });
1747
+ }
1748
+ if (auth.initScriptPath)
1749
+ await context.addInitScript({ path: auth.initScriptPath });
1750
+ }
1005
1751
  async function cmdRecord(ctx, opts) {
1006
1752
  // Validate the target URL up front — a headless browser will happily hang on
1007
1753
  // a typo'd or non-http(s) URL otherwise.
@@ -1015,6 +1761,7 @@ async function cmdRecord(ctx, opts) {
1015
1761
  if (target.protocol !== "http:" && target.protocol !== "https:") {
1016
1762
  die(`--url must be http(s), got ${target.protocol}`, 2);
1017
1763
  }
1764
+ validateAuthCapture(opts.auth, target.href); // usage errors (exit 2) before auth/browser
1018
1765
  requireKey(ctx); // fail fast before we spin up a browser
1019
1766
  const chromium = await loadChromium();
1020
1767
  const tmpDir = join(tmpdir(), `clipy-record-${randomUUID()}`);
@@ -1034,8 +1781,18 @@ async function cmdRecord(ctx, opts) {
1034
1781
  width: Math.max(...passes.map((v) => v.width)),
1035
1782
  height: Math.max(...passes.map((v) => v.height)),
1036
1783
  };
1784
+ // A pass-scoped note ("pass3: …") that names a pass we won't record is almost
1785
+ // always a mistake — fail fast before spinning up the browser.
1786
+ const maxRef = maxPassRef(opts.notes);
1787
+ if (maxRef > passes.length) {
1788
+ die(`--note "pass${maxRef}: …" refers to pass ${maxRef}, but this recording has ${passes.length} pass${passes.length === 1 ? "" : "es"}` +
1789
+ `${opts.viewports ? "" : " (pass-scoped notes are for --viewports; use an absolute timestamp otherwise)"}`, 2);
1790
+ }
1037
1791
  let uploaded;
1038
1792
  const autoNotes = [];
1793
+ // The real start of each pass, measured from the capture clock (index 0 =
1794
+ // pass 1). Pass-scoped notes anchor to these actual times, not fixed guesses.
1795
+ const passStartsMs = [];
1039
1796
  try {
1040
1797
  // --- Capture -----------------------------------------------------------
1041
1798
  let videoPath;
@@ -1051,16 +1808,18 @@ async function cmdRecord(ctx, opts) {
1051
1808
  const context = await browser.newContext({
1052
1809
  viewport: { width: frame.width, height: frame.height },
1053
1810
  recordVideo: { dir: tmpDir, size: frame },
1811
+ // Playwright takes the storageState file path directly (cookies + origins).
1812
+ ...(opts.auth.storageStatePath ? { storageState: opts.auth.storageStatePath } : {}),
1054
1813
  });
1814
+ // Seed cookies/localStorage/init-script before the first navigation.
1815
+ await applyAuthCapture(context, opts.auth, target.href);
1055
1816
  const page = await context.newPage();
1056
- const captureStart = Date.now();
1817
+ // captureStart is set AFTER the first meaningful paint (below), so notes
1818
+ // and pass marks aren't anchored to the blank t=0 a compiling app shows.
1819
+ let captureStart = 0;
1057
1820
  for (const [i, vp] of passes.entries()) {
1058
1821
  if (opts.viewports) {
1059
1822
  await page.setViewportSize({ width: vp.width, height: vp.height }).catch(() => { });
1060
- autoNotes.push({
1061
- startMs: Date.now() - captureStart,
1062
- text: `[auto] Viewport pass ${i + 1}/${passes.length}: ${vp.label}`,
1063
- });
1064
1823
  log(`${c.dim(`viewport ${vp.label}…`)}`);
1065
1824
  }
1066
1825
  log(`${c.dim(`opening ${target.href}…`)}`);
@@ -1072,6 +1831,21 @@ async function cmdRecord(ctx, opts) {
1072
1831
  // asked to capture whatever is on screen for --for seconds.
1073
1832
  log(c.yellow(`page load timed out; recording current state anyway`));
1074
1833
  }
1834
+ // Gate the capture clock on first meaningful paint (once, on pass 1).
1835
+ if (i === 0) {
1836
+ await waitForFirstPaint(page, frame, log);
1837
+ captureStart = Date.now();
1838
+ }
1839
+ const passStart = Date.now() - captureStart;
1840
+ passStartsMs[i] = passStart;
1841
+ if (opts.viewports) {
1842
+ autoNotes.push({
1843
+ startMs: passStart,
1844
+ // "pass N/M start" is a deterministic, machine-parseable tag so
1845
+ // downstream key-moment alignment knows exactly where each pass began.
1846
+ text: `[auto] Viewport pass ${i + 1}/${passes.length} start: ${vp.label}`,
1847
+ });
1848
+ }
1075
1849
  log(`${c.dim(`recording for ${opts.forSec}s…`)}`);
1076
1850
  if (opts.viewports) {
1077
1851
  // Slow scroll through the page so each size shows real layout, not
@@ -1099,11 +1873,12 @@ async function cmdRecord(ctx, opts) {
1099
1873
  await browser.close().catch(() => { });
1100
1874
  }
1101
1875
  // --- Upload ------------------------------------------------------------
1102
- const notes = [...autoNotes, ...opts.notes].sort((a, b) => a.startMs - b.startMs);
1876
+ const notes = [...autoNotes, ...resolveNarrationNotes(opts.notes, passStartsMs)].sort((a, b) => a.startMs - b.startMs);
1103
1877
  uploaded = await uploadWebmToClipy(ctx, {
1104
1878
  videoPath,
1105
1879
  name: opts.name,
1106
1880
  description: opts.description,
1881
+ recordingKind: opts.recordingKind,
1107
1882
  narration: notes.length ? { notes } : undefined,
1108
1883
  log,
1109
1884
  });
@@ -1168,7 +1943,16 @@ function readSessionState(file) {
1168
1943
  function writeSessionState(file, state) {
1169
1944
  mkdirSync(dirname(file), { recursive: true });
1170
1945
  const tmp = `${file}.${process.pid}.tmp`;
1946
+ // 0600: the state file can hold a CDP endpoint that grants full control of
1947
+ // the recording browser — keep it owner-only. mode on writeFileSync is
1948
+ // umask-masked, so chmod explicitly to guarantee it.
1171
1949
  writeFileSync(tmp, `${JSON.stringify(state, null, 2)}\n`, { mode: 0o600 });
1950
+ try {
1951
+ chmodSync(tmp, 0o600);
1952
+ }
1953
+ catch {
1954
+ // best-effort on platforms without POSIX modes
1955
+ }
1172
1956
  renameSync(tmp, file);
1173
1957
  }
1174
1958
  function pidAlive(pid) {
@@ -1194,6 +1978,113 @@ function cleanupSessionFiles(state, file) {
1194
1978
  }
1195
1979
  }
1196
1980
  }
1981
+ /** Compile a URL glob to a RegExp: `**` → `.*`, a lone `*` → `[^/]*`, every
1982
+ * other regex metachar escaped. A glob with NO `*` is treated as a bare
1983
+ * substring match (the common "is this path in the URL" case). */
1984
+ function urlGlobMatches(glob, url) {
1985
+ if (!glob.includes("*"))
1986
+ return url.includes(glob);
1987
+ // Escape regex metachars, then restore the glob wildcards. \x00 is a private
1988
+ // placeholder so `**` isn't clobbered while we expand single `*`.
1989
+ const escaped = glob
1990
+ .replace(/[.+?^${}()|[\]\\]/g, "\\$&")
1991
+ .replace(/\*\*/g, "\x00")
1992
+ .replace(/\*/g, "[^/]*")
1993
+ .replace(/\x00/g, ".*");
1994
+ try {
1995
+ return new RegExp(`^${escaped}$`).test(url);
1996
+ }
1997
+ catch {
1998
+ return url.includes(glob.replace(/\*/g, ""));
1999
+ }
2000
+ }
2001
+ /** POST to the web daemon's local control endpoint with the bearer token.
2002
+ * Throws on connection failure / non-2xx (the caller decides whether to fall
2003
+ * back to the marks file or die). */
2004
+ async function postToControl(state, path, body, timeoutMs) {
2005
+ const controller = new AbortController();
2006
+ const timer = setTimeout(() => controller.abort(), timeoutMs);
2007
+ try {
2008
+ const res = await fetch(`http://127.0.0.1:${state.controlPort}${path}`, {
2009
+ method: "POST",
2010
+ headers: {
2011
+ Authorization: `Bearer ${state.controlToken}`,
2012
+ "Content-Type": "application/json",
2013
+ },
2014
+ body: JSON.stringify(body ?? {}),
2015
+ signal: controller.signal,
2016
+ });
2017
+ const text = await res.text();
2018
+ let parsed = {};
2019
+ try {
2020
+ parsed = text ? JSON.parse(text) : {};
2021
+ }
2022
+ catch {
2023
+ parsed = { raw: text };
2024
+ }
2025
+ if (!res.ok) {
2026
+ throw new Error(typeof parsed.error === "string" ? parsed.error : `control endpoint error ${res.status}`);
2027
+ }
2028
+ return parsed;
2029
+ }
2030
+ catch (e) {
2031
+ if (e.name === "AbortError")
2032
+ throw new Error(`control endpoint timed out after ${timeoutMs / 1000}s`);
2033
+ throw e;
2034
+ }
2035
+ finally {
2036
+ clearTimeout(timer);
2037
+ }
2038
+ }
2039
+ /** Evaluate an assertion against the daemon's live page. Wraps the single
2040
+ * page.evaluate in a 5s race so an unresponsive page throws (a caught error the
2041
+ * caller turns into a 5xx) instead of hanging the daemon. A selector that
2042
+ * simply doesn't match is a normal FAIL, not an error. */
2043
+ async function evaluateAssertion(page, assert) {
2044
+ const expected = [];
2045
+ const observed = [];
2046
+ let passed = true;
2047
+ if (assert.urlGlob) {
2048
+ const url = page.url();
2049
+ expected.push(`url~"${assert.urlGlob}"`);
2050
+ observed.push(`url=${url}`);
2051
+ if (!urlGlobMatches(assert.urlGlob, url))
2052
+ passed = false;
2053
+ }
2054
+ if (assert.selector) {
2055
+ const sel = assert.selector;
2056
+ // Runs in the browser; typed locally so the CLI needs no DOM lib to build.
2057
+ const lookup = page.evaluate((s) => {
2058
+ const doc = globalThis.document;
2059
+ const el = doc?.querySelector(s);
2060
+ if (!el)
2061
+ return { match: false };
2062
+ const raw = (el.textContent ?? "").trim().replace(/\s+/g, " ");
2063
+ return { match: true, text: raw.slice(0, 200) };
2064
+ }, sel);
2065
+ const result = await Promise.race([
2066
+ lookup,
2067
+ new Promise((_, reject) => setTimeout(() => reject(new Error("page did not respond within 5s")), 5000)),
2068
+ ]);
2069
+ if (!result.match) {
2070
+ passed = false;
2071
+ expected.push(assert.expectText ? `${sel} containing "${assert.expectText}"` : `${sel} present`);
2072
+ observed.push(`${sel}=no match`);
2073
+ }
2074
+ else {
2075
+ observed.push(`${sel}=${result.text ? `"${result.text}"` : "(empty)"}`);
2076
+ if (assert.expectText != null && assert.expectText !== "") {
2077
+ expected.push(`"${assert.expectText}"`);
2078
+ if (!result.text.includes(assert.expectText))
2079
+ passed = false;
2080
+ }
2081
+ else {
2082
+ expected.push(`${sel} present`);
2083
+ }
2084
+ }
2085
+ }
2086
+ return { passed, observed: observed.join("; "), expected: expected.join("; ") };
2087
+ }
1197
2088
  // --- Mac bridge flows (--source mac-screen): the desktop app records -------
1198
2089
  /** Resolves --window/--display to a bridge capture source (null = app default,
1199
2090
  * i.e. the full primary display). die()s with the candidate list on no/ambiguous
@@ -1210,6 +2101,12 @@ async function resolveBridgeTarget(info, opts) {
1210
2101
  }
1211
2102
  /** One-shot real-screen recording through the running Clipy app. */
1212
2103
  async function cmdRecordMac(opts) {
2104
+ // A real-screen capture is one continuous take — there are no viewport passes
2105
+ // to anchor pass-scoped notes against.
2106
+ const macMaxRef = maxPassRef(opts.notes);
2107
+ if (macMaxRef > 1) {
2108
+ die(`--note "pass${macMaxRef}: …" needs --viewports (multiple passes). --source mac-screen is one continuous capture — use an absolute timestamp, e.g. --note "12: text".`, 2);
2109
+ }
1213
2110
  const info = readBridgeInfo();
1214
2111
  const log = (m) => {
1215
2112
  if (!opts.json)
@@ -1217,13 +2114,23 @@ async function cmdRecordMac(opts) {
1217
2114
  };
1218
2115
  const target = await resolveBridgeTarget(info, opts);
1219
2116
  log(`${c.dim(`asking the Clipy app (v${info.appVersion}) to record ${target?.label ?? "the screen"}…`)}`);
2117
+ // --type on the mac path: the current Clipy app doesn't forward recordingKind
2118
+ // from the bridge to its raw-upload/complete call (its AgentCompleteExtras has
2119
+ // no such field — desktop follow-up). We still send it (serde ignores unknown
2120
+ // start-args, so it's forward-compatible) but tell the user it isn't applied
2121
+ // yet, rather than silently dropping their intent.
2122
+ if (opts.recordingKind) {
2123
+ log(c.yellow(`note: --type is not applied to --source mac-screen recordings yet (needs a Clipy app update)`));
2124
+ }
2125
+ const notes = resolveNarrationNotes(opts.notes, [0]);
1220
2126
  await bridgeRequest(info, "start", {
1221
2127
  // The recording is stopped by us after forSec; maxSec is the safety net
1222
2128
  // in case this CLI process dies mid-wait.
1223
2129
  maxSec: Math.min(opts.forSec + 60, 1800),
1224
2130
  title: opts.name,
1225
2131
  description: opts.description,
1226
- notes: opts.notes.map((n) => ({ startMs: n.startMs, text: n.text })),
2132
+ ...(opts.recordingKind ? { recordingKind: opts.recordingKind } : {}),
2133
+ notes: notes.map((n) => ({ startMs: n.startMs, text: n.text })),
1227
2134
  ...(target ? { source: target.source } : {}),
1228
2135
  });
1229
2136
  log(`${c.dim(`recording for ${opts.forSec}s…`)}`);
@@ -1267,6 +2174,23 @@ function bridgeInfoFromSession(state) {
1267
2174
  protocolVersion: 1,
1268
2175
  };
1269
2176
  }
2177
+ /** The ready-to-run Playwright snippet printed after `session start --expose-cdp`.
2178
+ * Encodes the four gotchas that otherwise cost an agent a debugging round:
2179
+ * use connectOverCDP; the recorded page is contexts()[0].pages()[0] (a fresh
2180
+ * context/page is NOT the one being recorded); viewportSize() is null over CDP;
2181
+ * and a resize needs a CDP Emulation.setDeviceMetricsOverride, not setViewportSize. */
2182
+ function cdpDriverSnippet(cdpHttpUrl) {
2183
+ return [
2184
+ `${c.dim("drive the recorded page with your own Playwright:")}`,
2185
+ c.dim(` const { chromium } = require('playwright');`),
2186
+ c.dim(` const browser = await chromium.connectOverCDP(${JSON.stringify(cdpHttpUrl)});`),
2187
+ c.dim(` const page = browser.contexts()[0].pages()[0]; // the page being recorded (a NEW context/page is not captured)`),
2188
+ c.dim(` await page.goto('https://…'); // navigate / click / fill as usual`),
2189
+ c.dim(` const cdp = await browser.newCDPSession(page); // page.viewportSize() is null over CDP —`),
2190
+ c.dim(` await cdp.send('Emulation.setDeviceMetricsOverride', { width: 1280, height: 720, deviceScaleFactor: 1, mobile: false });`),
2191
+ c.dim(` resolve playwright for your script: NODE_PATH=$(clipy playwright-path) node driver.js`),
2192
+ ].join("\n");
2193
+ }
1270
2194
  async function cmdSessionStart(ctx, opts) {
1271
2195
  if (opts.source === "mac-screen") {
1272
2196
  const file = sessionFilePath(process.cwd());
@@ -1277,10 +2201,16 @@ async function cmdSessionStart(ctx, opts) {
1277
2201
  const info = readBridgeInfo();
1278
2202
  const maxSec = Math.min(Math.max(1, opts.maxSec), SESSION_HARD_CAP_SEC);
1279
2203
  const target = await resolveBridgeTarget(info, opts);
2204
+ // See cmdRecordMac: --type isn't applied on the mac path yet (desktop gap);
2205
+ // send it forward-compat but tell the user.
2206
+ if (opts.recordingKind && !opts.json) {
2207
+ process.stderr.write(`${c.yellow("note: --type is not applied to --source mac-screen recordings yet (needs a Clipy app update)")}\n`);
2208
+ }
1280
2209
  await bridgeRequest(info, "start", {
1281
2210
  maxSec,
1282
2211
  title: opts.name,
1283
2212
  description: opts.description,
2213
+ ...(opts.recordingKind ? { recordingKind: opts.recordingKind } : {}),
1284
2214
  ...(target ? { source: target.source } : {}),
1285
2215
  });
1286
2216
  writeSessionState(file, macSessionState(info, maxSec));
@@ -1303,6 +2233,7 @@ async function cmdSessionStart(ctx, opts) {
1303
2233
  if (target.protocol !== "http:" && target.protocol !== "https:") {
1304
2234
  die(`--url must be http(s), got ${target.protocol}`, 2);
1305
2235
  }
2236
+ validateAuthCapture(opts.auth, target.href); // usage errors (exit 2) before auth/daemonizing
1306
2237
  const key = requireKey(ctx);
1307
2238
  await loadChromium(); // fail fast with install instructions before daemonizing
1308
2239
  const file = sessionFilePath(process.cwd());
@@ -1324,9 +2255,15 @@ async function cmdSessionStart(ctx, opts) {
1324
2255
  url: target.href,
1325
2256
  name: opts.name,
1326
2257
  description: opts.description,
2258
+ recordingKind: opts.recordingKind,
1327
2259
  maxSec,
1328
2260
  width: opts.width,
1329
2261
  height: opts.height,
2262
+ exposeCdp: opts.exposeCdp,
2263
+ storageStatePath: opts.auth.storageStatePath,
2264
+ initScriptPath: opts.auth.initScriptPath,
2265
+ cookieSpecs: opts.auth.cookieSpecs.length ? opts.auth.cookieSpecs : undefined,
2266
+ localStorageSpecs: opts.auth.localStorageSpecs.length ? opts.auth.localStorageSpecs : undefined,
1330
2267
  state: "starting",
1331
2268
  marksPath: join(dir, `marks-${id}.jsonl`),
1332
2269
  controlPath: join(dir, `control-${id}.json`),
@@ -1365,11 +2302,29 @@ async function cmdSessionStart(ctx, opts) {
1365
2302
  }
1366
2303
  await new Promise((r) => setTimeout(r, 300));
1367
2304
  }
2305
+ const started = readSessionState(file);
1368
2306
  if (opts.json) {
1369
- printJson({ state: "recording", url: target.href, maxSec, sessionFile: file });
2307
+ printJson({
2308
+ state: "recording",
2309
+ url: target.href,
2310
+ maxSec,
2311
+ sessionFile: file,
2312
+ cdpUrl: started?.cdpUrl ?? null,
2313
+ cdpHttpUrl: started?.cdpHttpUrl ?? null,
2314
+ });
1370
2315
  return;
1371
2316
  }
1372
2317
  process.stdout.write(`${c.green("✓")} recording ${c.bold(target.href)} (max ${maxSec}s)\n`);
2318
+ if (started?.cdpHttpUrl) {
2319
+ process.stdout.write(`${c.yellow("⚠ CDP exposed:")} any local process can attach to and control this browser while the session runs.\n`);
2320
+ process.stdout.write(`${cdpDriverSnippet(started.cdpHttpUrl)}\n`);
2321
+ }
2322
+ else if (opts.exposeCdp) {
2323
+ // Asked for it, but it isn't up — either env-disabled or discovery failed.
2324
+ process.stdout.write(`${c.dim(process.env.CLIPY_DISABLE_CDP === "1"
2325
+ ? "CDP not exposed (CLIPY_DISABLE_CDP=1 overrides --expose-cdp)"
2326
+ : "CDP requested but the endpoint could not be established — see the daemon log")}\n`);
2327
+ }
1373
2328
  process.stdout.write(`${c.dim("while it runs:")} clipy mark "what just happened"\n` +
1374
2329
  `${c.dim("when finished:")} clipy session stop ${c.dim("· discard:")} clipy session abort\n`);
1375
2330
  }
@@ -1381,9 +2336,33 @@ function requireSession() {
1381
2336
  }
1382
2337
  return { file, state };
1383
2338
  }
1384
- async function cmdMark(text, json) {
2339
+ /** Print a /mark or /chapter control response (or a file-fallback shape). A
2340
+ * failed assertion prints a red ✗; everything else a green ✓. The mark text is
2341
+ * already annotated daemon-side, so it carries the ✓/✗ + observed inline. */
2342
+ function printMarkResult(res, json) {
2343
+ if (json) {
2344
+ printJson(res);
2345
+ return;
2346
+ }
2347
+ const sec = (Number(res.tMs ?? 0) / 1000).toFixed(1);
2348
+ const assert = res.assert;
2349
+ const glyph = assert && assert.passed === false ? c.red("✗") : c.green("✓");
2350
+ process.stdout.write(`${glyph} mark @ ${sec}s — ${String(res.text ?? "")}\n`);
2351
+ }
2352
+ async function cmdMark(text, json, opts) {
1385
2353
  const { file, state } = requireSession();
2354
+ const hasAssert = !!opts.assert;
2355
+ const backdated = opts.atSec != null || opts.agoSec != null;
1386
2356
  if (state.kind === "mac") {
2357
+ // The Mac app records the real screen — there is no page to probe, and the
2358
+ // bridge stamps every mark on its own clock, so assertions and backdating
2359
+ // are web-session features.
2360
+ if (hasAssert) {
2361
+ die("assertions need a web session — the Mac app records the real screen; there is no page to probe", 2);
2362
+ }
2363
+ if (backdated) {
2364
+ die("--at/--ago need a web session — the Mac bridge stamps each mark on its own clock", 2);
2365
+ }
1387
2366
  const result = await bridgeRequest(bridgeInfoFromSession(state), "mark", { text }).catch((e) => {
1388
2367
  if (e instanceof BridgeUnavailableError) {
1389
2368
  cleanupSessionFiles(state, file);
@@ -1405,14 +2384,102 @@ async function cmdMark(text, json) {
1405
2384
  if (state.state !== "recording" || !state.recordStartEpochMs) {
1406
2385
  die(`session is ${state.state} — marks can only be added while recording`);
1407
2386
  }
2387
+ // --at is an absolute recording-clock time; --ago is N seconds before now,
2388
+ // both computed against the SAME recordStartEpochMs the daemon saved. Absent ⇒
2389
+ // let the daemon stamp its live clock (undefined atMs).
2390
+ const atMs = backdated
2391
+ ? opts.atSec != null
2392
+ ? Math.max(0, Math.round(opts.atSec * 1000))
2393
+ : Math.max(0, Date.now() - state.recordStartEpochMs - Math.round((opts.agoSec ?? 0) * 1000))
2394
+ : undefined;
2395
+ if (state.controlPort && state.controlToken) {
2396
+ let res;
2397
+ try {
2398
+ res = await postToControl(state, "/mark", {
2399
+ text: text.trim(),
2400
+ ...(atMs != null ? { atMs } : {}),
2401
+ ...(hasAssert ? { assert: opts.assert } : {}),
2402
+ }, 5000);
2403
+ }
2404
+ catch (e) {
2405
+ // Assertions REQUIRE the live page — there's no honest file fallback for a
2406
+ // verification the daemon couldn't run. Plain marks fall back to the file.
2407
+ if (hasAssert) {
2408
+ die(`the session daemon isn't answering — assertions need the live page (${e.message})`);
2409
+ }
2410
+ const tMs = atMs != null ? atMs : Math.max(0, Date.now() - state.recordStartEpochMs);
2411
+ appendFileSync(state.marksPath, `${JSON.stringify({ tMs, text: text.trim() })}\n`, { mode: 0o600 });
2412
+ printMarkResult({ tMs, text: text.trim() }, json);
2413
+ return;
2414
+ }
2415
+ if (res.aborted) {
2416
+ // A failed assertion with --fail-mode abort discarded the session. Show
2417
+ // the ✗ mark, then die loudly so the agent can't mistake this for success.
2418
+ printMarkResult(res, json);
2419
+ die("session ABORTED by a failed assertion (--fail-mode abort) — nothing was uploaded. Fix the condition, then start a new session.");
2420
+ }
2421
+ printMarkResult(res, json);
2422
+ return;
2423
+ }
2424
+ // No control endpoint (session started by a pre-0.6 CLI): assertions can't run.
2425
+ if (hasAssert) {
2426
+ die("this session has no control endpoint (started by an older clipy) — stop it and run `clipy session start` again to use assertion marks");
2427
+ }
2428
+ const tMs = atMs != null ? atMs : Math.max(0, Date.now() - state.recordStartEpochMs);
2429
+ appendFileSync(state.marksPath, `${JSON.stringify({ tMs, text: text.trim() })}\n`, { mode: 0o600 });
2430
+ printMarkResult({ tMs, text: text.trim() }, json);
2431
+ }
2432
+ /** `clipy chapter "<label>"` — a chapter is a specially-formatted mark
2433
+ * (=== CHAPTER: <label> ===) that splits one recording into BEFORE/AFTER
2434
+ * sections (demo base branch → chapter "AFTER" → swap branch → demo the fix). */
2435
+ async function cmdChapter(label, json) {
2436
+ const { file, state } = requireSession();
2437
+ const chapterText = `=== CHAPTER: ${label} ===`;
2438
+ if (state.kind === "mac") {
2439
+ const result = await bridgeRequest(bridgeInfoFromSession(state), "mark", { text: chapterText }).catch((e) => {
2440
+ if (e instanceof BridgeUnavailableError) {
2441
+ cleanupSessionFiles(state, file);
2442
+ die("the Clipy app is no longer running — session cleared. Start a new one.");
2443
+ }
2444
+ die(e.message);
2445
+ });
2446
+ if (json) {
2447
+ printJson({ tMs: Number(result.atSeconds ?? 0) * 1000, label, text: chapterText });
2448
+ return;
2449
+ }
2450
+ process.stdout.write(`${c.green("✓")} chapter @ ${Number(result.atSeconds ?? 0).toFixed(1)}s — ${label}\n`);
2451
+ return;
2452
+ }
2453
+ if (!pidAlive(state.pid)) {
2454
+ cleanupSessionFiles(state, file);
2455
+ die("the session daemon is no longer running (crashed?) — session cleared. Start a new one.");
2456
+ }
2457
+ if (state.state !== "recording" || !state.recordStartEpochMs) {
2458
+ die(`session is ${state.state} — chapters can only be added while recording`);
2459
+ }
2460
+ if (state.controlPort && state.controlToken) {
2461
+ try {
2462
+ const res = await postToControl(state, "/chapter", { label }, 5000);
2463
+ if (json) {
2464
+ printJson({ tMs: Number(res.tMs ?? 0), label, text: chapterText });
2465
+ }
2466
+ else {
2467
+ process.stdout.write(`${c.green("✓")} chapter @ ${(Number(res.tMs ?? 0) / 1000).toFixed(1)}s — ${label}\n`);
2468
+ }
2469
+ return;
2470
+ }
2471
+ catch {
2472
+ // Chapters aren't assertions — fall back to the marks file on failure.
2473
+ }
2474
+ }
1408
2475
  const tMs = Math.max(0, Date.now() - state.recordStartEpochMs);
1409
- appendFileSync(state.marksPath, `${JSON.stringify({ tMs, text: text.trim() })}\n`);
2476
+ appendFileSync(state.marksPath, `${JSON.stringify({ tMs, text: chapterText })}\n`, { mode: 0o600 });
1410
2477
  if (json) {
1411
- printJson({ tMs, text: text.trim() });
1412
- return;
2478
+ printJson({ tMs, label, text: chapterText });
2479
+ }
2480
+ else {
2481
+ process.stdout.write(`${c.green("✓")} chapter @ ${(tMs / 1000).toFixed(1)}s — ${label}\n`);
1413
2482
  }
1414
- const sec = (tMs / 1000).toFixed(1);
1415
- process.stdout.write(`${c.green("✓")} mark @ ${sec}s — ${text.trim()}\n`);
1416
2483
  }
1417
2484
  async function cmdSessionStop(json) {
1418
2485
  const { file, state } = requireSession();
@@ -1521,8 +2588,60 @@ async function cmdSessionAbort(json) {
1521
2588
  await new Promise((r) => setTimeout(r, 300));
1522
2589
  }
1523
2590
  const final = readSessionState(file);
2591
+ const alive = final ? pidAlive(final.pid) : false;
2592
+ // The daemon is still alive AND mid-upload of a stop/max capture — the abort
2593
+ // arrived after it committed to finishing. Killing it would strand a partial
2594
+ // server-side upload, so let it finish; the user can collect it with
2595
+ // `session stop`. Leave the state file in place for that.
2596
+ if (final && alive && (final.state === "stopping" || final.state === "uploading")) {
2597
+ if (json) {
2598
+ printJson({ state: "finishing" });
2599
+ }
2600
+ else {
2601
+ process.stderr.write(`${c.yellow("!")} the recording is already being uploaded (abort came too late) — it will finish; run ${c.bold("clipy session stop")} to collect the link\n`);
2602
+ }
2603
+ process.exitCode = 1;
2604
+ return;
2605
+ }
2606
+ // Still recording after the full wait ⇒ the abort didn't take (wedged Chromium
2607
+ // / hung page). Don't quietly delete the state file out from under a process
2608
+ // that may still be recording — escalate: SIGTERM, a short grace, then SIGKILL,
2609
+ // and only THEN clean up. This is what makes `session run`'s "guaranteed
2610
+ // cleanup" honest.
2611
+ const wedged = final ? alive && (final.state === "starting" || final.state === "recording") : false;
2612
+ if (wedged && final) {
2613
+ try {
2614
+ process.kill(final.pid, "SIGTERM");
2615
+ }
2616
+ catch {
2617
+ // already gone
2618
+ }
2619
+ const graceDeadline = Date.now() + 3000;
2620
+ while (pidAlive(final.pid) && Date.now() < graceDeadline) {
2621
+ await new Promise((r) => setTimeout(r, 150));
2622
+ }
2623
+ if (pidAlive(final.pid)) {
2624
+ try {
2625
+ process.kill(final.pid, "SIGKILL");
2626
+ }
2627
+ catch {
2628
+ // already gone
2629
+ }
2630
+ }
2631
+ }
1524
2632
  if (final)
1525
2633
  cleanupSessionFiles(final, file);
2634
+ if (wedged) {
2635
+ // Exit non-zero (and truthfully) — the daemon had to be force-killed, so we
2636
+ // can't promise a clean discard. Use process.exitCode (not process.exit) so
2637
+ // a caller like `session run` can still override with the child's code.
2638
+ if (json)
2639
+ printJson({ state: "killed", pid: final?.pid ?? null });
2640
+ else
2641
+ process.stderr.write(`${c.yellow("!")} the session daemon ignored abort for 30s and was force-killed (pid ${final?.pid}); nothing was uploaded\n`);
2642
+ process.exitCode = 1;
2643
+ return;
2644
+ }
1526
2645
  if (json)
1527
2646
  printJson({ state: "aborted" });
1528
2647
  else
@@ -1584,11 +2703,114 @@ async function cmdSessionStatus(json) {
1584
2703
  elapsedSec: elapsed,
1585
2704
  maxSec: state.maxSec,
1586
2705
  pid: state.pid,
2706
+ cdpUrl: state.cdpUrl ?? null,
2707
+ cdpHttpUrl: state.cdpHttpUrl ?? null,
1587
2708
  });
1588
2709
  return;
1589
2710
  }
1590
2711
  process.stdout.write(`${c.bold(state.state)}${alive ? "" : c.red(" (daemon dead)")} — ${state.url}` +
1591
2712
  `${elapsed != null ? ` — ${elapsed}s elapsed (max ${state.maxSec}s)` : ""}\n`);
2713
+ if (state.cdpHttpUrl && state.state === "recording" && alive) {
2714
+ process.stdout.write(`${c.dim(`drive the recorded page: connectOverCDP(${state.cdpHttpUrl}) → browser.contexts()[0].pages()[0] · resize via CDP Emulation.setDeviceMetricsOverride · resolve playwright with NODE_PATH=$(clipy playwright-path)`)}\n`);
2715
+ }
2716
+ }
2717
+ /**
2718
+ * `clipy session run [start-flags] -- <command …>` — the crash-safe wrapper.
2719
+ * Starts a session, runs the command with inherited stdio, and GUARANTEES
2720
+ * cleanup: exit 0 uploads (session stop), any non-zero exit / signal discards
2721
+ * (session abort) and propagates the child's code. This is the fleet answer to
2722
+ * a crashed driver recording dead air to its max ceiling.
2723
+ */
2724
+ async function cmdSessionRun(ctx, startOpts, childArgv) {
2725
+ if (childArgv.length === 0) {
2726
+ die("usage: clipy session run [start flags] -- <command …> (everything after -- is the command to run)", 2);
2727
+ }
2728
+ // Start the session and block until it's recording. Force human output — the
2729
+ // child inherits our stdio and the deliverable is the wrapped run, not JSON.
2730
+ await cmdSessionStart(ctx, { ...startOpts, json: false });
2731
+ const file = sessionFilePath(process.cwd());
2732
+ const cdpHttpUrl = readSessionState(file)?.cdpHttpUrl;
2733
+ const [cmd, ...args] = childArgv;
2734
+ process.stderr.write(`${c.dim(`running: ${childArgv.join(" ")}`)}\n`);
2735
+ const child = spawn(cmd, args, {
2736
+ stdio: "inherit",
2737
+ env: {
2738
+ ...process.env,
2739
+ // Signals to the child that it's being recorded, and where to drive.
2740
+ CLIPY_SESSION: "1",
2741
+ ...(cdpHttpUrl ? { CLIPY_CDP_URL: cdpHttpUrl } : {}),
2742
+ },
2743
+ });
2744
+ // Forward Ctrl-C / termination to the child; its exit then drives the abort
2745
+ // path below (so we never double-abort or race the child).
2746
+ let forwarded = false;
2747
+ const forward = (sig) => {
2748
+ forwarded = true;
2749
+ try {
2750
+ child.kill(sig);
2751
+ }
2752
+ catch {
2753
+ // child already gone
2754
+ }
2755
+ };
2756
+ const onSigint = () => forward("SIGINT");
2757
+ const onSigterm = () => forward("SIGTERM");
2758
+ process.on("SIGINT", onSigint);
2759
+ process.on("SIGTERM", onSigterm);
2760
+ const outcome = await new Promise((res) => {
2761
+ child.on("error", (e) => {
2762
+ // Couldn't even spawn the command — don't leave the session recording.
2763
+ void cmdSessionAbort(false)
2764
+ .catch(() => { })
2765
+ .finally(() => die(`failed to run command "${cmd}": ${e.message}`));
2766
+ });
2767
+ child.on("exit", (code, signal) => res({ code, signal }));
2768
+ });
2769
+ process.off("SIGINT", onSigint);
2770
+ process.off("SIGTERM", onSigterm);
2771
+ if (outcome.code === 0 && !outcome.signal && !forwarded) {
2772
+ await cmdSessionStop(false); // clean exit → upload + print the share link
2773
+ return;
2774
+ }
2775
+ process.stderr.write(`${c.yellow(`command ${outcome.signal ? `terminated by ${outcome.signal}` : `exited ${outcome.code}`} — discarding the recording`)}\n`);
2776
+ await cmdSessionAbort(false);
2777
+ process.exit(outcome.code ?? 1); // propagate the child's failure
2778
+ }
2779
+ /** Reserve a free localhost TCP port for Chromium's CDP endpoint. Binding to
2780
+ * :0 then closing hands us a concrete port to pass to --remote-debugging-port,
2781
+ * which we can then poll — passing 0 directly leaves the chosen port only in
2782
+ * Chromium's DevToolsActivePort file, which Playwright's temp profile hides. */
2783
+ function pickFreePort() {
2784
+ return new Promise((resolve, reject) => {
2785
+ const srv = createServer();
2786
+ srv.on("error", reject);
2787
+ srv.listen(0, "127.0.0.1", () => {
2788
+ const addr = srv.address();
2789
+ const port = typeof addr === "object" && addr ? addr.port : 0;
2790
+ srv.close(() => (port ? resolve(port) : reject(new Error("no port"))));
2791
+ });
2792
+ });
2793
+ }
2794
+ /** After Chromium is up with --remote-debugging-port, its HTTP endpoint exposes
2795
+ * the browser-level ws URL at /json/version. Poll until it answers (or 10s). */
2796
+ async function discoverCdpWsUrl(port) {
2797
+ const deadline = Date.now() + 10_000;
2798
+ for (;;) {
2799
+ try {
2800
+ const res = await fetch(`http://127.0.0.1:${port}/json/version`);
2801
+ if (res.ok) {
2802
+ const body = (await res.json());
2803
+ if (body.webSocketDebuggerUrl)
2804
+ return body.webSocketDebuggerUrl;
2805
+ }
2806
+ }
2807
+ catch {
2808
+ // endpoint not up yet
2809
+ }
2810
+ if (Date.now() >= deadline)
2811
+ return null;
2812
+ await new Promise((r) => setTimeout(r, 200));
2813
+ }
1592
2814
  }
1593
2815
  async function runSessionDaemon(file) {
1594
2816
  const state = readSessionState(file);
@@ -1612,20 +2834,98 @@ async function runSessionDaemon(file) {
1612
2834
  return;
1613
2835
  autoMarks.push({ startMs: Math.max(0, Date.now() - recordStart), text });
1614
2836
  };
2837
+ // Marks that arrive over the control endpoint (`clipy mark`/`chapter`) or the
2838
+ // in-page __clipyMark/__clipyChapter bindings. Kept in memory (like autoMarks)
2839
+ // and merged at stop. A hard 200 cap here is the server limit; storeDaemonMark
2840
+ // refuses past it so `clipy mark` gets an error rather than a silent drop.
2841
+ const daemonMarks = [];
2842
+ const storeDaemonMark = (note) => {
2843
+ if (daemonMarks.length >= 200)
2844
+ return false;
2845
+ daemonMarks.push(note);
2846
+ return true;
2847
+ };
2848
+ // Assertion tallies → the leading [verification] note at stop.
2849
+ let assertRan = 0;
2850
+ let assertPassed = 0;
2851
+ let assertFailed = 0;
2852
+ // A failed --fail-mode=abort assertion sets this; the main loop discards.
2853
+ let controlSignal = null;
1615
2854
  mkdirSync(state.tmpDir, { recursive: true });
1616
2855
  let browser = null;
2856
+ let controlServer = null;
1617
2857
  try {
1618
2858
  const chromium = await loadChromium();
1619
2859
  log(`launching chromium for ${state.url}`);
2860
+ // CDP is OPT-IN (--expose-cdp) and the env kill switch wins over the flag:
2861
+ // no debugging port is opened unless the user asked AND CLIPY_DISABLE_CDP
2862
+ // isn't set. When enabled, Playwright still controls the browser over its
2863
+ // own pipe; the extra --remote-debugging-port opens a parallel TCP endpoint
2864
+ // an agent can attach to.
2865
+ const wantCdp = !!state.exposeCdp && process.env.CLIPY_DISABLE_CDP !== "1";
2866
+ if (state.exposeCdp && !wantCdp)
2867
+ log("CDP disabled by CLIPY_DISABLE_CDP=1 — not opening a debugging port");
2868
+ const cdpPort = wantCdp ? await pickFreePort().catch(() => 0) : 0;
1620
2869
  browser = await chromium.launch({
1621
2870
  headless: true,
1622
- args: ["--no-sandbox", "--disable-dev-shm-usage"],
2871
+ args: [
2872
+ "--no-sandbox",
2873
+ "--disable-dev-shm-usage",
2874
+ ...(cdpPort ? [`--remote-debugging-port=${cdpPort}`] : []),
2875
+ ],
1623
2876
  });
1624
2877
  const context = await browser.newContext({
1625
2878
  viewport: { width: state.width, height: state.height },
1626
2879
  recordVideo: { dir: state.tmpDir, size: { width: state.width, height: state.height } },
2880
+ // Playwright takes the storageState file path directly (cookies + origins).
2881
+ ...(state.storageStatePath ? { storageState: state.storageStatePath } : {}),
1627
2882
  });
2883
+ // Seed cookies/localStorage/init-script before the first navigation — re-parse
2884
+ // the raw specs the parent CLI already validated. A bad spec here is caught by
2885
+ // the outer try/catch and fails the session cleanly.
2886
+ await applyAuthCapture(context, {
2887
+ storageStatePath: state.storageStatePath,
2888
+ initScriptPath: state.initScriptPath,
2889
+ cookieSpecs: state.cookieSpecs ?? [],
2890
+ localStorageSpecs: state.localStorageSpecs ?? [],
2891
+ }, state.url);
2892
+ // In-page mark/chapter bindings — only under --expose-cdp, and only alongside
2893
+ // the debugging port a driver already uses. A page.evaluate(() =>
2894
+ // window.__clipyMark("…")) emits a mark with ZERO spawn latency (no `clipy
2895
+ // mark` process). Same 200-cap store as the HTTP path. NOTE: while CDP is
2896
+ // exposed, the page's own scripts can call these too — that's within the
2897
+ // existing --expose-cdp trust model (any local process can already drive the
2898
+ // browser), and it's documented in the README's --expose-cdp section.
2899
+ if (wantCdp) {
2900
+ const inPageMark = (label) => {
2901
+ if (recordStart === 0)
2902
+ return;
2903
+ const text = label.trim();
2904
+ if (text)
2905
+ storeDaemonMark({ startMs: Math.max(0, Date.now() - recordStart), text });
2906
+ };
2907
+ await context
2908
+ .exposeBinding("__clipyMark", (_src, ...args) => inPageMark(String(args[0] ?? "")))
2909
+ .catch((e) => log(`__clipyMark binding failed: ${e.message}`));
2910
+ await context
2911
+ .exposeBinding("__clipyChapter", (_src, ...args) => inPageMark(`=== CHAPTER: ${String(args[0] ?? "").trim()} ===`))
2912
+ .catch((e) => log(`__clipyChapter binding failed: ${e.message}`));
2913
+ }
1628
2914
  const page = await context.newPage();
2915
+ // Best-effort: publish the CDP URL so `session start`/`status` can hand it
2916
+ // to the agent. The recording works fine even if discovery fails.
2917
+ let cdpUrl;
2918
+ let cdpHttpUrl;
2919
+ if (cdpPort) {
2920
+ cdpUrl = (await discoverCdpWsUrl(cdpPort)) ?? undefined;
2921
+ if (cdpUrl) {
2922
+ cdpHttpUrl = `http://127.0.0.1:${cdpPort}`;
2923
+ log(`CDP endpoint ready at ${cdpHttpUrl} (${cdpUrl})`);
2924
+ }
2925
+ else {
2926
+ log(`CDP endpoint not reachable on port ${cdpPort} — browser drive unavailable`);
2927
+ }
2928
+ }
1629
2929
  // Auto-marks: instrumentation ground truth alongside the agent's intent
1630
2930
  // marks. Type-tagged with [auto] so the transcript distinguishes them.
1631
2931
  page.on("framenavigated", ((frame) => {
@@ -1647,8 +2947,156 @@ async function runSessionDaemon(file) {
1647
2947
  // ignore
1648
2948
  }
1649
2949
  }));
2950
+ // Local control endpoint: `clipy mark`/`chapter` POST here so the daemon —
2951
+ // which owns the live page — evaluates assertions and stamps marks on its
2952
+ // own clock. 127.0.0.1 only, bearer-token auth (random UUID). If it can't
2953
+ // bind, the recording still runs and marks fall back to the marks file.
2954
+ const controlToken = randomUUID();
2955
+ let controlPort = 0;
2956
+ /** POST /mark → tMs (atMs override or live clock), optional assertion run
2957
+ * against the page, stored (annotated) mark, and the response the CLI shows. */
2958
+ const handleMark = async (body) => {
2959
+ const text = typeof body.text === "string" ? body.text.trim() : "";
2960
+ if (!text)
2961
+ throw new Error("mark text is required");
2962
+ const tMs = typeof body.atMs === "number" && Number.isFinite(body.atMs)
2963
+ ? Math.max(0, Math.round(body.atMs))
2964
+ : Math.max(0, Date.now() - recordStart);
2965
+ let annotated = text;
2966
+ let assertOut;
2967
+ let aborted = false;
2968
+ const assertSpec = body.assert;
2969
+ if (assertSpec && typeof assertSpec === "object") {
2970
+ // evaluateAssertion throws if the page is unresponsive — surfaced as a
2971
+ // 5xx so the CLI die()s rather than recording an unverified claim.
2972
+ const ev = await evaluateAssertion(page, assertSpec);
2973
+ assertRan++;
2974
+ if (ev.passed)
2975
+ assertPassed++;
2976
+ else
2977
+ assertFailed++;
2978
+ annotated = ev.passed
2979
+ ? `${text} [assert ✓ ${ev.observed}]`
2980
+ : `${text} [ASSERT ✗ expected ${ev.expected}; observed ${ev.observed}]`;
2981
+ assertOut = { passed: ev.passed, observed: ev.observed };
2982
+ if (!ev.passed && assertSpec.failMode === "abort")
2983
+ aborted = true;
2984
+ }
2985
+ if (!storeDaemonMark({ startMs: tMs, text: annotated })) {
2986
+ throw new Error("mark limit reached (200 marks per recording)");
2987
+ }
2988
+ if (aborted)
2989
+ controlSignal = "abort";
2990
+ return {
2991
+ tMs,
2992
+ text: annotated,
2993
+ ...(assertOut ? { assert: assertOut } : {}),
2994
+ ...(aborted ? { aborted: true } : {}),
2995
+ };
2996
+ };
2997
+ /** POST /chapter → a =={ CHAPTER }== mark at the live clock. */
2998
+ const handleChapter = (body) => {
2999
+ const label = typeof body.label === "string" ? body.label.trim() : "";
3000
+ if (!label)
3001
+ throw new Error("chapter label is required");
3002
+ const tMs = Math.max(0, Date.now() - recordStart);
3003
+ if (!storeDaemonMark({ startMs: tMs, text: `=== CHAPTER: ${label} ===` })) {
3004
+ throw new Error("mark limit reached (200 marks per recording)");
3005
+ }
3006
+ return { tMs };
3007
+ };
3008
+ const BODY_CAP = 1_000_000;
3009
+ controlServer = createHttpServer((req, res) => {
3010
+ const respond = (status, obj) => {
3011
+ res.writeHead(status, { "Content-Type": "application/json" });
3012
+ res.end(JSON.stringify(obj));
3013
+ };
3014
+ if (req.headers.authorization !== `Bearer ${controlToken}`) {
3015
+ respond(401, { error: "unauthorized" });
3016
+ return;
3017
+ }
3018
+ if (req.method !== "POST") {
3019
+ respond(405, { error: "method not allowed" });
3020
+ return;
3021
+ }
3022
+ // Only JSON — a wrong content-type is almost always a confused client.
3023
+ if (!String(req.headers["content-type"] ?? "").toLowerCase().includes("application/json")) {
3024
+ respond(415, { error: "content-type must be application/json" });
3025
+ return;
3026
+ }
3027
+ // Reject an over-cap body: first by its declared Content-Length (before
3028
+ // reading a byte), then again if the stream itself exceeds the cap. Send an
3029
+ // explicit 413 and DRAIN the rest (req.resume) so a mid-upload client reads
3030
+ // the status instead of hitting the opaque socket error a bare destroy gave.
3031
+ const declared = Number(req.headers["content-length"] ?? "");
3032
+ if (Number.isFinite(declared) && declared > BODY_CAP) {
3033
+ respond(413, { error: "request body too large (1MB cap)" });
3034
+ req.resume();
3035
+ return;
3036
+ }
3037
+ let raw = "";
3038
+ let tooLarge = false;
3039
+ req.on("data", (chunk) => {
3040
+ if (tooLarge)
3041
+ return; // keep consuming (draining) but stop accumulating
3042
+ raw += chunk;
3043
+ if (raw.length > BODY_CAP) {
3044
+ tooLarge = true;
3045
+ respond(413, { error: "request body too large (1MB cap)" });
3046
+ }
3047
+ });
3048
+ req.on("end", () => {
3049
+ if (tooLarge)
3050
+ return;
3051
+ void (async () => {
3052
+ let body;
3053
+ try {
3054
+ body = raw ? JSON.parse(raw) : {};
3055
+ }
3056
+ catch {
3057
+ respond(400, { error: "invalid JSON body" });
3058
+ return;
3059
+ }
3060
+ try {
3061
+ if (req.url === "/mark")
3062
+ respond(200, await handleMark(body));
3063
+ else if (req.url === "/chapter")
3064
+ respond(200, handleChapter(body));
3065
+ else
3066
+ respond(404, { error: "not found" });
3067
+ }
3068
+ catch (e) {
3069
+ respond(500, { error: e.message });
3070
+ }
3071
+ })();
3072
+ });
3073
+ });
3074
+ // Tight timeouts (Node defaults are minutes) so a wedged local client can't
3075
+ // pin daemon sockets open. headersTimeout must be ≤ requestTimeout.
3076
+ controlServer.requestTimeout = 10_000;
3077
+ controlServer.headersTimeout = 10_000;
3078
+ try {
3079
+ await new Promise((resolveBind, rejectBind) => {
3080
+ controlServer.on("error", rejectBind);
3081
+ controlServer.listen(0, "127.0.0.1", () => resolveBind());
3082
+ });
3083
+ const addr = controlServer.address();
3084
+ controlPort = typeof addr === "object" && addr ? addr.port : 0;
3085
+ log(`control endpoint listening on 127.0.0.1:${controlPort}`);
3086
+ }
3087
+ catch (e) {
3088
+ log(`control endpoint failed to bind (${e.message}) — marks will use the file fallback`);
3089
+ controlServer = null;
3090
+ controlPort = 0;
3091
+ }
1650
3092
  recordStart = Date.now();
1651
- save({ state: "recording", recordStartEpochMs: recordStart });
3093
+ save({
3094
+ state: "recording",
3095
+ recordStartEpochMs: recordStart,
3096
+ cdpUrl,
3097
+ cdpHttpUrl,
3098
+ ...(controlPort ? { controlPort, controlToken } : {}),
3099
+ });
1652
3100
  try {
1653
3101
  await page.goto(state.url, { waitUntil: "load", timeout: 30_000 });
1654
3102
  }
@@ -1659,6 +3107,12 @@ async function runSessionDaemon(file) {
1659
3107
  let stopReason = "stop";
1660
3108
  for (;;) {
1661
3109
  await page.waitForTimeout(400);
3110
+ // A failed --fail-mode=abort assertion (set by the control handler) discards
3111
+ // the session just like a control-file abort.
3112
+ if (controlSignal === "abort") {
3113
+ stopReason = "abort";
3114
+ break;
3115
+ }
1662
3116
  let control = null;
1663
3117
  try {
1664
3118
  control = JSON.parse(readFileSync(state.controlPath, "utf8"));
@@ -1705,28 +3159,47 @@ async function runSessionDaemon(file) {
1705
3159
  const videoPath = await video.path();
1706
3160
  await browser.close().catch(() => { });
1707
3161
  browser = null;
1708
- // Merge the agent's marks (written live by `clipy mark` with its own
1709
- // clock) with the [auto] instrumentation marks.
1710
- const agentMarks = [];
3162
+ // Merge marks from three sources: the file (fallback path, written by
3163
+ // `clipy mark` when the control endpoint was unreachable), the daemon-side
3164
+ // marks (control endpoint + in-page bindings, already assertion-annotated),
3165
+ // and the [auto] instrumentation marks.
3166
+ const fileMarks = [];
1711
3167
  try {
1712
3168
  for (const line of readFileSync(state.marksPath, "utf8").split("\n")) {
1713
3169
  if (!line.trim())
1714
3170
  continue;
1715
3171
  const m = JSON.parse(line);
1716
3172
  if (typeof m.tMs === "number" && typeof m.text === "string" && m.text.trim()) {
1717
- agentMarks.push({ startMs: Math.max(0, Math.round(m.tMs)), text: m.text.trim() });
3173
+ fileMarks.push({ startMs: Math.max(0, Math.round(m.tMs)), text: m.text.trim() });
1718
3174
  }
1719
3175
  }
1720
3176
  }
1721
3177
  catch {
1722
3178
  // no marks file — fine
1723
3179
  }
1724
- const notes = [...agentMarks, ...autoMarks].sort((a, b) => a.startMs - b.startMs);
3180
+ let notes = [...fileMarks, ...daemonMarks, ...autoMarks].sort((a, b) => a.startMs - b.startMs);
3181
+ // If any assertions ran, prepend a 0ms verification summary so it LEADS the
3182
+ // transcript and the .md context (a stable sort keeps it ahead of other 0ms
3183
+ // marks). This is the "recordings are evidence" headline.
3184
+ if (assertRan > 0) {
3185
+ notes.unshift({
3186
+ startMs: 0,
3187
+ text: `[verification] ${assertRan} assertion(s): ${assertPassed} passed, ${assertFailed} failed`,
3188
+ });
3189
+ notes.sort((a, b) => a.startMs - b.startMs);
3190
+ }
3191
+ // Server limit: cap the merged set at 200 marks (the verification note sorts
3192
+ // to 0ms so it always survives the slice).
3193
+ if (notes.length > 200) {
3194
+ log(`mark limit: merged ${notes.length} marks — keeping the first 200 (dropped ${notes.length - 200})`);
3195
+ notes = notes.slice(0, 200);
3196
+ }
1725
3197
  save({ state: "uploading" });
1726
3198
  const uploaded = await uploadWebmToClipy(ctx, {
1727
3199
  videoPath,
1728
3200
  name: state.name,
1729
3201
  description: state.description,
3202
+ recordingKind: state.recordingKind,
1730
3203
  narration: notes.length ? { notes } : undefined,
1731
3204
  log: (m) => log(m.replace(/\x1b\[[0-9;]*m/g, "")),
1732
3205
  }).catch((e) => {
@@ -1756,6 +3229,8 @@ async function runSessionDaemon(file) {
1756
3229
  process.exitCode = 1;
1757
3230
  }
1758
3231
  finally {
3232
+ if (controlServer)
3233
+ controlServer.close();
1759
3234
  if (browser)
1760
3235
  await browser.close().catch(() => { });
1761
3236
  }
@@ -1849,7 +3324,7 @@ async function cmdAgents(ctx, sub, targetRaw, json) {
1849
3324
  // command's shape without trial-and-error. Bump GUIDE_SCHEMA_VERSION when the
1850
3325
  // contract changes.
1851
3326
  // ---------------------------------------------------------------------------
1852
- const GUIDE_SCHEMA_VERSION = 1;
3327
+ const GUIDE_SCHEMA_VERSION = 5;
1853
3328
  function cmdGuide(json) {
1854
3329
  if (!json) {
1855
3330
  process.stdout.write(HELP);
@@ -1876,6 +3351,7 @@ function cmdGuide(json) {
1876
3351
  env: [
1877
3352
  { name: "CLIPY_API_KEY", description: "API key (clipy_sk_live_…) from clipy.online/settings/api-keys; write commands need the 'ingest' scope" },
1878
3353
  { name: "CLIPY_API_URL", description: "API base URL override (default https://clipy.online)" },
3354
+ { name: "CLIPY_DISABLE_CDP", description: "set to 1 to force session --expose-cdp off (a hard kill switch that wins over the flag)" },
1879
3355
  { name: "NO_COLOR", description: "disable ANSI color" },
1880
3356
  ],
1881
3357
  exitCodes: [
@@ -1898,9 +3374,12 @@ function cmdGuide(json) {
1898
3374
  cmdDoc("download", "clipy download <id> [-o path]", "Download the MP4"),
1899
3375
  cmdDoc("open", "clipy open <id>", "Open the share page in a browser"),
1900
3376
  cmdDoc("wait", "clipy wait <id> [--for transcript|summary|both] [--timeout sec]", "Block until artifacts are ready"),
1901
- cmdDoc("record", "clipy record --url <url> [--for sec] [--viewports list] [--title t] [--note '12: text']… [--wait] [--json]", "Headless one-shot capture of a web app; notes become the transcript. With --source mac-screen: records the real screen via the Clipy Mac app; --window '<title|app|id>' or --display <id> target one window/display (ids from clipy sources)", ["--for", "--viewports", "--title", "--description", "--note", "--width", "--height", "--wait", "--source", "--window", "--display"]),
1902
- cmdDoc("session", "clipy session <start|stop|abort|status> [--url <url>] [--max sec] [--source web|mac-screen] [--window w] [--display d]", "Background recording session; auto-stops + uploads at --max (default 600s, cap 1800s). --window/--display (with --source mac-screen) record one window/display"),
1903
- cmdDoc("mark", "clipy mark \"<text>\"", "Drop a live-timestamped note into the active session"),
3377
+ 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>. With --source mac-screen: records the real screen via the Clipy Mac app (--type not yet applied on mac; auth flags rejected — the screen is already logged in); --window '<title|app|id>' or --display <id> target one window/display (ids from clipy sources). --json prints {id, shareUrl, contextUrl, sizeBytes}", ["--for", "--viewports", "--title", "--description", "--type", "--note", "--storage-state", "--cookie", "--local-storage", "--init-script", "--width", "--height", "--wait", "--source", "--window", "--display", "--json"]),
3378
+ cmdDoc("session", "clipy session <start|run|stop|abort|status> [--url <url>] [--max sec] [--type kind] [--source web|mac-screen] [--window w] [--display d] [--expose-cdp] [--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). --window/--display (with --source mac-screen) record one window/display. --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), then GUARANTEES cleanup: exit 0 uploads, any non-zero exit or signal discards (session abort) and propagates the child's code — the crash-safe wrapper so a dead driver never records dead air. Accepts the same auth flags as record (--storage-state/--cookie/--local-storage/--init-script; web only, rejected on --source mac-screen). --json is supported on start/stop/status (start returns cdpUrl/cdpHttpUrl)", ["run", "--url", "--max", "--type", "--source", "--window", "--display", "--expose-cdp", "--storage-state", "--cookie", "--local-storage", "--init-script", "--json"]),
3379
+ cmdDoc("mark", "clipy mark \"<text>\" [--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. ASSERTION MARKS make the note evidence instead of a claim: --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 ✓ <observed>]', fail ⇒ '<text> [ASSERT ✗ 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 assertions ran, a leading 0ms '[verification] N assertion(s): P passed, F failed' note is prepended. --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.", ["--assert-selector", "--assert-text", "--assert-url", "--fail-mode", "--at", "--ago", "--json"]),
3380
+ 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"]),
3381
+ cmdDoc("doctor", "clipy doctor [--json]", "One-shot health check: 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), and install mode (npx/global/local) — each a pass/warn/fail with a fix hint; exits non-zero if any check fails", ["--json"]),
3382
+ cmdDoc("playwright-path", "clipy playwright-path [--json]", "Print the node_modules directory of the Playwright this CLI resolves, so your own --expose-cdp driver scripts can load the same copy: NODE_PATH=$(clipy playwright-path) node driver.js. Exits 1 (empty stdout) if Playwright is unresolvable. --json prints {path, nodeModulesDir, source}", ["--json"]),
1904
3383
  cmdDoc("sources", "clipy sources [--json]", "List displays + windows the Clipy Mac app can capture — ids feed --window/--display"),
1905
3384
  cmdDoc("agents", "clipy agents <status|install|uninstall> <claude|codex|cursor>", "Install the bundled Clipy skill for a coding agent; install triggers a browser login first when no key is configured (interactive terminals only)"),
1906
3385
  cmdDoc("guide", "clipy guide --json", "This manifest"),
@@ -1911,6 +3390,17 @@ function cmdGuide(json) {
1911
3390
  "login opens a browser to approve this device (loopback redirect to 127.0.0.1); use --key/--paste or a piped key on headless boxes.",
1912
3391
  "record/session/mark/transcript --replace are the only write commands; they need a key with the 'ingest' permission.",
1913
3392
  "Headless captures have no audio: --note flags and session marks become the transcript, labeled agent-narration.",
3393
+ "--note is absolute ('12: text') or pass-scoped ('pass2: text' / 'pass2@5: text'); pass-scoped notes anchor to the real start of a --viewports pass, so they don't drift when load time shifts the pass boundaries. A malformed pass note (e.g. 'pass2 text' with no colon) is a usage error, not silently demoted.",
3394
+ "--type declares what a recording IS (bug_report/feature_request/product_demo/walkthrough_tutorial/feedback_review/discussion_talk/other, plus short aliases) so the AI summary doesn't misread a demo as a bug report. Applied on web today; --source mac-screen support is pending a Clipy app update.",
3395
+ "Assertion marks are the differentiator: assert what you claim. `clipy mark \"X\" --assert-selector '.status' --assert-text Active` records X only alongside the live-page truth — the daemon runs the check against its Playwright page and annotates the mark ✓/✗ with what it actually observed, so a false claim cannot pass as fact in the transcript. --fail-mode abort turns a failed assertion into a discarded session (nothing uploaded, non-zero exit). Assertions need a web session and the daemon's control endpoint (started by clipy 0.6+); they are rejected on --source mac-screen.",
3396
+ "clipy chapter \"<label>\" splits one recording into BEFORE/AFTER sections for PR-review-style demos: record the base branch, `clipy chapter \"AFTER — fix applied\"`, swap branches + restart, record the fix. One video carries both states.",
3397
+ "clipy session run [start flags] -- <command…> is the crash-safe wrapper: it starts a session, runs your driver command with inherited stdio (env CLIPY_SESSION=1, plus CLIPY_CDP_URL when --expose-cdp), and guarantees cleanup — exit 0 uploads, any non-zero exit or signal discards and propagates the code. Use it so a crashing driver never records dead air to the max ceiling.",
3398
+ "clipy mark --at <sec> stamps at an absolute recording time; --ago <sec> stamps N seconds before now — a `clipy mark` spawn lands ~100-300ms late, so backdate to align a mark with the state it describes. When driving over --expose-cdp, call window.__clipyMark(\"text\") / window.__clipyChapter(\"label\") IN-PAGE (page.evaluate) to emit marks/chapters with zero spawn latency; while CDP is exposed the page's own scripts can call these too (within the existing --expose-cdp trust model).",
3399
+ "session --expose-cdp (web, opt-in) publishes a CDP endpoint (cdpHttpUrl) in `session start`/`session status` output and the 0600 session state file; connect with playwright.connectOverCDP() to drive the recorded page. Off by default (any local process could attach); CLIPY_DISABLE_CDP=1 forces it off.",
3400
+ "Driving an --expose-cdp session: connect with playwright.connectOverCDP(cdpHttpUrl); the recorded page is browser.contexts()[0].pages()[0] (a fresh context/page you open is NOT captured); page.viewportSize() is null over a CDP attach; resize with a CDP session's Emulation.setDeviceMetricsOverride, not setViewportSize. Your own driver script resolves Playwright from its own cwd — run it as NODE_PATH=$(clipy playwright-path) node driver.js if require('playwright') can't find it.",
3401
+ "Auth for headless web capture (record + session start): --storage-state <playwright storageState JSON> is passed straight to Playwright's newContext; --cookie / --local-storage / --init-script are applied to the context BEFORE the first navigation, so a logged-in SPA's route guard sees the state on first paint (seeding it after navigating loses that race). --cookie without a Domain is url-scoped to the target; with a Domain it is domain-scoped. --local-storage pairs are origin-guarded to the target. All four are web-only and are rejected on --source mac-screen, which records the real, already-signed-in screen. The storage-state file may hold live credentials; the CLI never prints its contents and the session state file that carries these specs is chmod 0600.",
3402
+ "clipy record gates its capture clock on the first non-blank frame (up to a 10s cap, then starts anyway) so notes aren't anchored to a still-compiling t=0.",
3403
+ "Run `clipy doctor` first when record/session or --source mac-screen fails — it names the exact missing piece (key, bridge socket/handshake/version, Playwright, install mode).",
1914
3404
  "Public recordings have an unauthenticated context document at https://clipy.online/video/<id>.md.",
1915
3405
  ],
1916
3406
  });
@@ -1962,9 +3452,24 @@ async function cmdTranscriptReplace(ctx, id, file) {
1962
3452
  // ---------------------------------------------------------------------------
1963
3453
  // Entry
1964
3454
  // ---------------------------------------------------------------------------
3455
+ /** Parse a --at/--ago seconds value (fractional allowed, must be ≥ 0). */
3456
+ function parseSeconds(v, flag) {
3457
+ const n = Number(v);
3458
+ if (!Number.isFinite(n) || n < 0)
3459
+ die(`${flag} must be a non-negative number of seconds`, 2);
3460
+ return n;
3461
+ }
1965
3462
  async function main() {
3463
+ // Split on the first `--` ourselves so `session run … -- <cmd> [--child-flags]`
3464
+ // never feeds the child's own flags to parseArgs (strict:false would otherwise
3465
+ // fold them into `values`). Everything after `--` is the child command verbatim;
3466
+ // for every other command childArgv is simply unused.
3467
+ const rawArgv = process.argv.slice(2);
3468
+ const ddIndex = rawArgv.indexOf("--");
3469
+ const childArgv = ddIndex >= 0 ? rawArgv.slice(ddIndex + 1) : [];
3470
+ const parseArgv = ddIndex >= 0 ? rawArgv.slice(0, ddIndex) : rawArgv;
1966
3471
  const { values, positionals } = parseArgs({
1967
- args: process.argv.slice(2),
3472
+ args: parseArgv,
1968
3473
  allowPositionals: true,
1969
3474
  strict: false,
1970
3475
  options: {
@@ -1993,6 +3498,18 @@ async function main() {
1993
3498
  source: { type: "string" },
1994
3499
  window: { type: "string" },
1995
3500
  display: { type: "string" },
3501
+ type: { type: "string" },
3502
+ "assert-selector": { type: "string" },
3503
+ "assert-text": { type: "string" },
3504
+ "assert-url": { type: "string" },
3505
+ "fail-mode": { type: "string" },
3506
+ at: { type: "string" },
3507
+ ago: { type: "string" },
3508
+ "expose-cdp": { type: "boolean", default: false },
3509
+ "storage-state": { type: "string" },
3510
+ "init-script": { type: "string" },
3511
+ cookie: { type: "string", multiple: true },
3512
+ "local-storage": { type: "string", multiple: true },
1996
3513
  width: { type: "string" },
1997
3514
  height: { type: "string" },
1998
3515
  wait: { type: "boolean", default: false },
@@ -2024,6 +3541,21 @@ async function main() {
2024
3541
  const n = parseInt(String(v ?? ""), 10);
2025
3542
  return Number.isFinite(n) && n > 0 ? n : dflt;
2026
3543
  };
3544
+ // Auth-capture flags seed a logged-in session into headless web capture; they
3545
+ // don't apply to --source mac-screen (which records the real, already-signed-in
3546
+ // screen). Resolve the file paths to absolute so the detached daemon — spawned
3547
+ // without an explicit cwd — reads the same files the parent validated.
3548
+ const authFlagsPresent = Boolean(values["storage-state"] ||
3549
+ values["init-script"] ||
3550
+ values.cookie?.length ||
3551
+ values["local-storage"]?.length);
3552
+ const authCapture = () => ({
3553
+ storageStatePath: values["storage-state"] ? resolve(String(values["storage-state"])) : undefined,
3554
+ initScriptPath: values["init-script"] ? resolve(String(values["init-script"])) : undefined,
3555
+ cookieSpecs: values.cookie ?? [],
3556
+ localStorageSpecs: values["local-storage"] ?? [],
3557
+ });
3558
+ const macAuthGuard = "auth state applies to headless web capture — --source mac-screen records the real, already-logged-in screen";
2027
3559
  switch (command) {
2028
3560
  case "login":
2029
3561
  await cmdLogin(ctx, {
@@ -2108,6 +3640,12 @@ async function main() {
2108
3640
  case "mcp":
2109
3641
  cmdMcp();
2110
3642
  return;
3643
+ case "doctor":
3644
+ await cmdDoctor(ctx, json);
3645
+ return;
3646
+ case "playwright-path":
3647
+ await cmdPlaywrightPath(json);
3648
+ return;
2111
3649
  case "agents":
2112
3650
  await cmdAgents(ctx, rest[0], rest[1], json);
2113
3651
  return;
@@ -2148,6 +3686,9 @@ async function main() {
2148
3686
  if (values.window && values.display) {
2149
3687
  die("--window and --display are mutually exclusive — pick one capture source", 2);
2150
3688
  }
3689
+ if (source === "mac-screen" && authFlagsPresent)
3690
+ die(macAuthGuard, 2);
3691
+ const recordingKind = values.type ? requireRecordingKind(String(values.type)) : undefined;
2151
3692
  if (source === "mac-screen") {
2152
3693
  const noteFlags = values.note ?? [];
2153
3694
  const forSec = num(values.for, 15);
@@ -2162,6 +3703,7 @@ async function main() {
2162
3703
  name: (values.title ?? values.name)?.trim() ||
2163
3704
  undefined,
2164
3705
  description: values.description?.trim() || undefined,
3706
+ recordingKind,
2165
3707
  window: values.window?.trim() || undefined,
2166
3708
  display: values.display?.trim() || undefined,
2167
3709
  notes: noteFlags.map(parseNoteFlag),
@@ -2194,18 +3736,23 @@ async function main() {
2194
3736
  name: (values.title ?? values.name)?.trim() ||
2195
3737
  undefined,
2196
3738
  description: values.description?.trim() || undefined,
3739
+ recordingKind,
2197
3740
  notes: noteFlags.map(parseNoteFlag),
2198
3741
  viewports: values.viewports ? parseViewports(String(values.viewports)) : null,
2199
3742
  width: num(values.width, 1280),
2200
3743
  height: num(values.height, 720),
2201
3744
  wait: Boolean(values.wait),
2202
3745
  json,
3746
+ auth: authCapture(),
2203
3747
  });
2204
3748
  return;
2205
3749
  }
2206
3750
  case "session": {
2207
3751
  const sub = rest[0];
2208
- if (sub === "start") {
3752
+ // Shared by `start` and `run`: validate the capture flags and build the
3753
+ // cmdSessionStart opts. `positionalUrl` is rest[1] for `start` (session
3754
+ // start <url>) — `run` has no positional url, only --url.
3755
+ const buildStartOpts = (positionalUrl) => {
2209
3756
  const source = String(values.source ?? "web");
2210
3757
  if (source !== "web" && source !== "mac-screen") {
2211
3758
  die("--source must be web (headless browser) or mac-screen (the Clipy Mac app)", 2);
@@ -2216,23 +3763,36 @@ async function main() {
2216
3763
  if (values.window && values.display) {
2217
3764
  die("--window and --display are mutually exclusive — pick one capture source", 2);
2218
3765
  }
2219
- const url = values.url?.trim() || rest[1];
3766
+ if (source === "mac-screen" && authFlagsPresent)
3767
+ die(macAuthGuard, 2);
3768
+ const url = values.url?.trim() || positionalUrl;
2220
3769
  if (!url && source === "web") {
2221
3770
  die("usage: clipy session start --url <http(s) url> [--max <sec>] [--source web|mac-screen]", 2);
2222
3771
  }
2223
- await cmdSessionStart(ctx, {
3772
+ return {
2224
3773
  url: url || "mac-screen",
2225
3774
  window: values.window?.trim() || undefined,
2226
3775
  display: values.display?.trim() || undefined,
2227
3776
  name: (values.title ?? values.name)?.trim() ||
2228
3777
  undefined,
2229
3778
  description: values.description?.trim() || undefined,
3779
+ recordingKind: values.type ? requireRecordingKind(String(values.type)) : undefined,
2230
3780
  maxSec: num(values.max, SESSION_DEFAULT_MAX_SEC),
2231
3781
  width: num(values.width, 1280),
2232
3782
  height: num(values.height, 720),
2233
3783
  json,
2234
- source,
2235
- });
3784
+ source: source,
3785
+ exposeCdp: Boolean(values["expose-cdp"]),
3786
+ auth: authCapture(),
3787
+ };
3788
+ };
3789
+ if (sub === "start") {
3790
+ await cmdSessionStart(ctx, buildStartOpts(rest[1]));
3791
+ return;
3792
+ }
3793
+ if (sub === "run") {
3794
+ // Everything after `--` is the command; start flags come before it.
3795
+ await cmdSessionRun(ctx, buildStartOpts(undefined), childArgv);
2236
3796
  return;
2237
3797
  }
2238
3798
  if (sub === "stop") {
@@ -2247,14 +3807,47 @@ async function main() {
2247
3807
  await cmdSessionStatus(json);
2248
3808
  return;
2249
3809
  }
2250
- die("usage: clipy session <start|stop|abort|status>", 2);
3810
+ die("usage: clipy session <start|run|stop|abort|status>", 2);
2251
3811
  return;
2252
3812
  }
2253
3813
  case "mark": {
2254
3814
  const text = rest.join(" ").trim();
2255
- if (!text)
2256
- die('usage: clipy mark "<what just happened>"', 2);
2257
- await cmdMark(text, json);
3815
+ if (!text) {
3816
+ die('usage: clipy mark "<what just happened>" [--assert-selector <css> [--assert-text <substr>]] [--assert-url <glob>] [--fail-mode warn|abort] [--at <sec>|--ago <sec>]', 2);
3817
+ }
3818
+ const selector = values["assert-selector"]?.trim() || undefined;
3819
+ const expectText = values["assert-text"]; // exact, not trimmed
3820
+ const urlGlob = values["assert-url"]?.trim() || undefined;
3821
+ if (expectText != null && !selector) {
3822
+ die("--assert-text needs --assert-selector (the substring is checked against that element's text)", 2);
3823
+ }
3824
+ const failModeRaw = values["fail-mode"]?.trim().toLowerCase();
3825
+ if (failModeRaw && failModeRaw !== "warn" && failModeRaw !== "abort") {
3826
+ die("--fail-mode must be warn or abort", 2);
3827
+ }
3828
+ const hasAssert = Boolean(selector || (expectText != null && expectText !== "") || urlGlob);
3829
+ if (failModeRaw && !hasAssert) {
3830
+ die("--fail-mode only applies with an assertion (--assert-selector / --assert-text / --assert-url)", 2);
3831
+ }
3832
+ if (values.at != null && values.ago != null)
3833
+ die("--at and --ago are mutually exclusive", 2);
3834
+ const atSec = values.at != null ? parseSeconds(String(values.at), "--at") : undefined;
3835
+ const agoSec = values.ago != null ? parseSeconds(String(values.ago), "--ago") : undefined;
3836
+ await cmdMark(text, json, {
3837
+ atSec,
3838
+ agoSec,
3839
+ assert: hasAssert
3840
+ ? { selector, expectText, urlGlob, failMode: failModeRaw || "warn" }
3841
+ : undefined,
3842
+ });
3843
+ return;
3844
+ }
3845
+ case "chapter": {
3846
+ const label = rest.join(" ").trim();
3847
+ if (!label) {
3848
+ die('usage: clipy chapter "<label>" e.g. clipy chapter "AFTER — fix applied"', 2);
3849
+ }
3850
+ await cmdChapter(label, json);
2258
3851
  return;
2259
3852
  }
2260
3853
  case "__session-daemon": {