@clipy/cli 0.5.0 → 0.8.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (4) hide show
  1. package/README.md +209 -10
  2. package/dist/index.js +1163 -64
  3. package/dist/skill.js +141 -0
  4. package/package.json +4 -2
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, existsSync, 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";
@@ -24,6 +24,7 @@ import { pipeline } from "node:stream/promises";
24
24
  import { createRequire } from "node:module";
25
25
  import { pathToFileURL } from "node:url";
26
26
  import { createServer } from "node:net";
27
+ import { createServer as createHttpServer } from "node:http";
27
28
  import { CLIPY_SKILL_MD } from "./skill.js";
28
29
  import { browserLogin, shouldUseManualLogin } from "./browserLogin.js";
29
30
  import { BridgeUnavailableError, bridgeRequest, inspectBridge, listSources, readBridgeInfo, resolveCaptureSource, windowLabel, probeSocketOpenable, probeBridgeHandshake, bridgeInfoFromFile, bridgeAppOutdated, MIN_BRIDGE_APP_VERSION, } from "./macBridge.js";
@@ -131,6 +132,13 @@ function writeConfig(cfg) {
131
132
  }
132
133
  }
133
134
  const FETCH_TIMEOUT_MS = 20_000;
135
+ // Timeout for a `clipy mark`/`chapter` control call to the session daemon.
136
+ // Generous (the daemon's event loop can stall during a heavy client recompile —
137
+ // two observed drops took ~5.6s/5.9s), env-overridable so tests don't wait it out.
138
+ const CONTROL_TIMEOUT_MS = (() => {
139
+ const n = Number(process.env.CLIPY_CONTROL_TIMEOUT_MS);
140
+ return Number.isFinite(n) && n > 0 ? n : 15_000;
141
+ })();
134
142
  function requireKey(ctx) {
135
143
  if (ctx.apiKey)
136
144
  return ctx.apiKey;
@@ -306,6 +314,16 @@ ${c.bold("RECORD")} ${c.dim("(needs an API key with the \"ingest\" permission)")
306
314
  notes become the transcript
307
315
  --width/--height Viewport + video size (default 1280×720)
308
316
  --wait Block until the transcript is ready before printing
317
+ --json Print {id, shareUrl, contextUrl, sizeBytes}
318
+ ${c.dim("auth (headless web capture only) — seed a logged-in session BEFORE the")}
319
+ ${c.dim("first navigation, so an app's route guard sees it (never on --source mac-screen):")}
320
+ --storage-state <f> Playwright storageState JSON (cookies + localStorage)
321
+ --cookie "n=v[; Domain=d; Path=p; Secure; HttpOnly; SameSite=Lax]" (repeatable)
322
+ --local-storage "k=v" Seed a localStorage pair for the target origin (repeatable)
323
+ --init-script <f> Run a JS file before every page load
324
+ --user-data-dir <d> Launch a persistent Chromium profile dir (its whole
325
+ logged-in identity). Excl. with --storage-state; use a
326
+ copy, never a live/locked Chrome profile
309
327
 
310
328
  ${c.bold("SESSION")} ${c.dim("(agent works, Clipy records — one active session per directory)")}
311
329
  ${c.dim("--source mac-screen on record/session records the REAL screen via the")}
@@ -321,9 +339,27 @@ ${c.bold("SESSION")} ${c.dim("(agent works, Clipy records — one active session
321
339
  the recording kind (see record). --expose-cdp
322
340
  opens a CDP endpoint so your tools can drive the
323
341
  page as it records (off by default; any local
324
- process could attach — CLIPY_DISABLE_CDP=1 forces off)
325
- mark "<what just happened>" Drop a live timestamped note; marks become
326
- the recording's transcript chapters
342
+ process could attach — CLIPY_DISABLE_CDP=1 forces off).
343
+ Accepts the same auth flags as record
344
+ (--storage-state/--cookie/--local-storage/--init-script)
345
+ and --json (returns cdpUrl/cdpHttpUrl)
346
+ session run [start flags] -- <command …>
347
+ Start a session, run the command (inherited
348
+ stdio), then GUARANTEE cleanup: exit 0 uploads,
349
+ any non-zero exit or signal discards and
350
+ propagates the code. Sets CLIPY_SESSION=1 (+
351
+ CLIPY_CDP_URL with --expose-cdp). Crash-safe
352
+ wrapper for driver scripts — no dead-air uploads.
353
+ mark "<what just happened>" Drop a live timestamped note; marks become the
354
+ recording's transcript. Verify what you claim:
355
+ --assert-selector <css> assert an element exists (observed text recorded)
356
+ --assert-text <substr> require that element's text to contain <substr>
357
+ --assert-url <glob> assert the page URL matches (**/* wildcards)
358
+ --fail-mode warn|abort warn (default) annotates ASSERT ✗; abort
359
+ discards the whole session on a failed assertion
360
+ --at <sec> | --ago <sec> backdate the mark (absolute / N seconds ago)
361
+ chapter "<label>" Split the recording into BEFORE/AFTER sections
362
+ (demo base → chapter "AFTER" → demo the fix)
327
363
  session stop Finish: close browser, upload, print link
328
364
  session abort Discard the session — nothing is uploaded
329
365
  session status Show the active session's state
@@ -337,6 +373,9 @@ ${c.bold("AGENTS")}
337
373
  Playwright, and install mode — with fix hints
338
374
  guide --json Machine-readable manifest: every command,
339
375
  flag, env var, and exit code
376
+ playwright-path [--json] Print the node_modules dir of the Playwright
377
+ this CLI resolves, for your own driver scripts:
378
+ ${c.dim("NODE_PATH=$(clipy playwright-path) node driver.js")}
340
379
  transcript <id> --replace <file> Replace a transcript with agent-authored
341
380
  JSON ({segments} or {plaintext}); regenerates
342
381
  the summary ${c.dim("(needs the \"ingest\" permission)")}
@@ -345,7 +384,9 @@ ${c.bold("AGENTS")}
345
384
  ${c.bold("GLOBAL FLAGS")}
346
385
  --key <key> API key for this invocation (else CLIPY_API_KEY, else stored login)
347
386
  --api-url <url> API base (else CLIPY_API_URL, default https://clipy.online)
348
- --json Machine-readable output (list/search/show/transcript/summary/moments/wait)
387
+ --json Machine-readable output. Supported on: list, search, show,
388
+ transcript, summary, moments, wait, record, session
389
+ start/stop/status, mark, chapter, doctor, playwright-path
349
390
  -v, --version Print version
350
391
 
351
392
  ${c.bold("EXIT CODES")}
@@ -937,7 +978,17 @@ async function doctorBridgeChecks() {
937
978
  async function doctorPlaywrightCheck() {
938
979
  const res = await resolvePlaywright();
939
980
  if (res.ok) {
940
- return { name: "playwright", status: "pass", detail: `resolved via ${res.source}`, data: { source: res.source } };
981
+ // "PASS" here only means Clipy can load Playwright — NOT that the user's own
982
+ // --expose-cdp driver script will, since it resolves from a different cwd.
983
+ // Report where we found it, and always hand back the NODE_PATH escape hatch.
984
+ const nodeModulesDir = res.path ? nodeModulesDirOf(res.path) : null;
985
+ return {
986
+ name: "playwright",
987
+ status: "pass",
988
+ detail: `resolved via ${res.source}${res.path ? ` (${res.path})` : ""}`,
989
+ 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",
990
+ data: { source: res.source, path: res.path ?? null, nodeModulesDir },
991
+ };
941
992
  }
942
993
  const { mode } = detectInstallMode();
943
994
  return {
@@ -1149,8 +1200,18 @@ async function resolvePlaywright() {
1149
1200
  for (const mod of ["playwright", "playwright-core"]) {
1150
1201
  try {
1151
1202
  const chromium = chromiumFrom(await import(mod));
1152
- if (chromium)
1153
- return { ok: true, chromium, source: `import('${mod}')` };
1203
+ if (chromium) {
1204
+ // A bare import doesn't tell us WHERE it loaded from; ask the resolver
1205
+ // for the absolute entry path so doctor/playwright-path can report it.
1206
+ let path;
1207
+ try {
1208
+ path = createRequire(import.meta.url).resolve(mod);
1209
+ }
1210
+ catch {
1211
+ // resolved as a module but not to a concrete file path — leave unknown
1212
+ }
1213
+ return { ok: true, chromium, source: `import('${mod}')`, path };
1214
+ }
1154
1215
  }
1155
1216
  catch {
1156
1217
  // try the next strategy
@@ -1165,7 +1226,7 @@ async function resolvePlaywright() {
1165
1226
  const resolved = requireFromCwd.resolve(mod);
1166
1227
  const chromium = chromiumFrom(await import(pathToFileURL(resolved).href));
1167
1228
  if (chromium)
1168
- return { ok: true, chromium, source: `${mod} at ${dirname(resolved)}` };
1229
+ return { ok: true, chromium, source: `${mod} at ${dirname(resolved)}`, path: resolved };
1169
1230
  }
1170
1231
  catch {
1171
1232
  // fall through to the miss
@@ -1181,7 +1242,18 @@ async function resolvePlaywright() {
1181
1242
  * npx runs from an isolated `_npx` cache; a global bin lives outside cwd; a
1182
1243
  * project-local install sits under cwd/node_modules. */
1183
1244
  function detectInstallMode() {
1184
- const argv1 = process.argv[1] ? resolve(process.argv[1]) : "";
1245
+ const raw = process.argv[1] ? resolve(process.argv[1]) : "";
1246
+ // nvm/npm global bins are SYMLINKS (…/bin/clipy → …/lib/node_modules/@clipy/cli/dist/index.js).
1247
+ // Match against the REAL path or every global install misreports as
1248
+ // "unknown (running from source?)"; fall back to the raw path on a broken link.
1249
+ let argv1 = raw;
1250
+ try {
1251
+ if (raw)
1252
+ argv1 = realpathSync(raw);
1253
+ }
1254
+ catch {
1255
+ // dangling/permission-denied symlink — keep the raw path
1256
+ }
1185
1257
  const norm = argv1.replace(/\\/g, "/");
1186
1258
  const cwd = resolve(process.cwd()).replace(/\\/g, "/");
1187
1259
  let mode = "unknown";
@@ -1193,6 +1265,17 @@ function detectInstallMode() {
1193
1265
  mode = "global";
1194
1266
  return { mode, argv1 };
1195
1267
  }
1268
+ /** From a resolved package entry file, the node_modules DIRECTORY that contains
1269
+ * it — the substring up to and including the last "node_modules" segment — so
1270
+ * `NODE_PATH=$(clipy playwright-path) node driver.js` can require playwright.
1271
+ * Returns null when the entry isn't under a node_modules dir (linked/monorepo). */
1272
+ function nodeModulesDirOf(entryPath) {
1273
+ // \\→/ is a 1:1 char swap, so the index is valid against the original string.
1274
+ const idx = entryPath.replace(/\\/g, "/").lastIndexOf("/node_modules");
1275
+ if (idx < 0)
1276
+ return null;
1277
+ return entryPath.slice(0, idx + "/node_modules".length);
1278
+ }
1196
1279
  /** One-line install hint keyed to the install mode (the `doctor` ↳ line). For
1197
1280
  * npx we LEAD with the cwd-local install — the only guaranteed-working fix,
1198
1281
  * since the resolver's cwd-local strategy loads it and the npx cache can't see
@@ -1235,6 +1318,34 @@ async function loadChromium() {
1235
1318
  return res.chromium;
1236
1319
  die(playwrightMissingMessage(detectInstallMode().mode));
1237
1320
  }
1321
+ /** `clipy playwright-path` — print the node_modules DIRECTORY holding the
1322
+ * Playwright this CLI resolves, so a user's own driver script can find the same
1323
+ * copy: `NODE_PATH=$(clipy playwright-path) node driver.js`. Exits non-zero
1324
+ * (empty stdout) if Playwright is unresolvable, so the command substitution
1325
+ * fails loudly rather than handing NODE_PATH a bogus value. */
1326
+ async function cmdPlaywrightPath(json) {
1327
+ const res = await resolvePlaywright();
1328
+ if (!res.ok) {
1329
+ if (json) {
1330
+ printJson({ path: null, nodeModulesDir: null, source: null });
1331
+ process.exitCode = 1;
1332
+ return;
1333
+ }
1334
+ die(`${res.error}\n${playwrightInstallHint(detectInstallMode().mode)}`, 1);
1335
+ }
1336
+ const nodeModulesDir = res.path ? nodeModulesDirOf(res.path) : null;
1337
+ if (json) {
1338
+ printJson({ path: res.path ?? null, nodeModulesDir, source: res.source });
1339
+ if (!nodeModulesDir)
1340
+ process.exitCode = 1;
1341
+ return;
1342
+ }
1343
+ if (!nodeModulesDir) {
1344
+ die(`Playwright resolved${res.path ? ` at ${res.path}` : ""} but not from a node_modules directory — ` +
1345
+ `NODE_PATH can't point at it; install Playwright in your script's project instead`, 1);
1346
+ }
1347
+ process.stdout.write(`${nodeModulesDir}\n`);
1348
+ }
1238
1349
  /** Named viewport presets for `--viewports` (agent demos across screen sizes). */
1239
1350
  const VIEWPORT_ALIASES = {
1240
1351
  mobile: { width: 390, height: 844 },
@@ -1510,6 +1621,190 @@ async function waitForFirstPaint(page, size, log) {
1510
1621
  log(c.dim(`waited ${(waited / 1000).toFixed(1)}s for first meaningful paint`));
1511
1622
  return waited;
1512
1623
  }
1624
+ /** Parse one `--cookie` value into a Playwright cookie. Grammar:
1625
+ * `name=value[; Domain=d; Path=p; Secure; HttpOnly; SameSite=Lax]`. The first
1626
+ * `;`-segment is name=value (split on the first `=`); later segments are
1627
+ * case-insensitive attributes. Without a Domain we url-scope the cookie to the
1628
+ * target; with one we domain-scope it. Throws on a malformed spec so the parent
1629
+ * can turn it into a die(2). */
1630
+ function parseCookieSpec(spec, targetUrl) {
1631
+ const segments = spec.split(";").map((s) => s.trim()).filter(Boolean);
1632
+ if (segments.length === 0)
1633
+ throw new Error(`--cookie "${spec}" is empty`);
1634
+ const eq = segments[0].indexOf("=");
1635
+ if (eq < 1)
1636
+ throw new Error(`--cookie "${spec}" must start with name=value`);
1637
+ const name = segments[0].slice(0, eq).trim();
1638
+ const value = segments[0].slice(eq + 1).trim();
1639
+ if (!name)
1640
+ throw new Error(`--cookie "${spec}" has an empty name`);
1641
+ let domain;
1642
+ let path;
1643
+ let secure = false;
1644
+ let httpOnly = false;
1645
+ let sameSite;
1646
+ for (const seg of segments.slice(1)) {
1647
+ const aEq = seg.indexOf("=");
1648
+ const attr = (aEq >= 0 ? seg.slice(0, aEq) : seg).trim().toLowerCase();
1649
+ const aVal = aEq >= 0 ? seg.slice(aEq + 1).trim() : "";
1650
+ switch (attr) {
1651
+ case "domain":
1652
+ domain = aVal;
1653
+ break;
1654
+ case "path":
1655
+ path = aVal;
1656
+ break;
1657
+ case "secure":
1658
+ secure = true;
1659
+ break;
1660
+ case "httponly":
1661
+ httpOnly = true;
1662
+ break;
1663
+ case "samesite": {
1664
+ const s = aVal.toLowerCase();
1665
+ sameSite = s === "strict" ? "Strict" : s === "none" ? "None" : "Lax";
1666
+ break;
1667
+ }
1668
+ default:
1669
+ throw new Error(`--cookie "${spec}": unknown attribute "${attr}" (accepted: Domain, Path, Secure, HttpOnly, SameSite)`);
1670
+ }
1671
+ }
1672
+ if (domain) {
1673
+ return { name, value, domain, path: path || "/", secure, httpOnly, ...(sameSite ? { sameSite } : {}) };
1674
+ }
1675
+ return { name, value, url: targetUrl };
1676
+ }
1677
+ /** Parse one `--local-storage` value ("key=value"; value may be empty). */
1678
+ function parseLocalStorageSpec(spec) {
1679
+ const eq = spec.indexOf("=");
1680
+ if (eq < 1)
1681
+ throw new Error(`--local-storage "${spec}" must be key=value`);
1682
+ return [spec.slice(0, eq), spec.slice(eq + 1)];
1683
+ }
1684
+ /** The single init script that seeds localStorage. Each pair is origin-guarded
1685
+ * so it never leaks into an unexpected origin the page might navigate to, and
1686
+ * runs before page scripts so route guards see the storage on first paint. */
1687
+ function localStorageInitScript(pairs, origin) {
1688
+ return pairs
1689
+ .map(([k, v]) => `if (location.origin === ${JSON.stringify(origin)}) localStorage.setItem(${JSON.stringify(k)}, ${JSON.stringify(v)});`)
1690
+ .join("\n");
1691
+ }
1692
+ /** Validate the auth-capture flags in the PARENT process — before launching a
1693
+ * browser or daemonizing — so an agent gets an instant, precise usage error
1694
+ * instead of a cryptic daemon-log failure. NEVER prints the storage-state
1695
+ * contents: it holds live credentials; only a shape warning is emitted. */
1696
+ function validateAuthCapture(auth, targetUrl) {
1697
+ if (auth.storageStatePath) {
1698
+ let raw;
1699
+ try {
1700
+ raw = readFileSync(auth.storageStatePath, "utf8");
1701
+ }
1702
+ catch {
1703
+ die(`--storage-state file not found or unreadable: ${auth.storageStatePath}`, 2);
1704
+ }
1705
+ let parsed;
1706
+ try {
1707
+ parsed = JSON.parse(raw);
1708
+ }
1709
+ catch {
1710
+ die(`--storage-state is not valid JSON: ${auth.storageStatePath}`, 2);
1711
+ }
1712
+ if (typeof parsed !== "object" || parsed === null || Array.isArray(parsed)) {
1713
+ die(`--storage-state must be a Playwright storageState JSON object: ${auth.storageStatePath}`, 2);
1714
+ }
1715
+ if (!("cookies" in parsed) && !("origins" in parsed)) {
1716
+ process.stderr.write(`${c.yellow("warning:")} --storage-state has neither "cookies" nor "origins" — it may not be a Playwright storageState file\n`);
1717
+ }
1718
+ }
1719
+ if (auth.initScriptPath) {
1720
+ try {
1721
+ statSync(auth.initScriptPath);
1722
+ }
1723
+ catch {
1724
+ die(`--init-script file not found: ${auth.initScriptPath}`, 2);
1725
+ }
1726
+ }
1727
+ // Parse the cookie / local-storage specs now purely to surface grammar errors
1728
+ // up front; the values are re-parsed where they're applied.
1729
+ for (const spec of auth.cookieSpecs) {
1730
+ try {
1731
+ parseCookieSpec(spec, targetUrl);
1732
+ }
1733
+ catch (e) {
1734
+ die(e.message, 2);
1735
+ }
1736
+ }
1737
+ for (const spec of auth.localStorageSpecs) {
1738
+ try {
1739
+ parseLocalStorageSpec(spec);
1740
+ }
1741
+ catch (e) {
1742
+ die(e.message, 2);
1743
+ }
1744
+ }
1745
+ }
1746
+ /** Apply cookies, seeded localStorage, and the user init script to a freshly
1747
+ * created context, in that order, BEFORE newPage()/goto. --storage-state is
1748
+ * applied by the caller at newContext() time (Playwright takes the file path
1749
+ * directly), not here. Re-parses the raw specs the parent already validated. */
1750
+ async function applyAuthCapture(context, auth, targetUrl) {
1751
+ const cookies = auth.cookieSpecs.map((s) => parseCookieSpec(s, targetUrl));
1752
+ if (cookies.length)
1753
+ await context.addCookies(cookies);
1754
+ const pairs = auth.localStorageSpecs.map(parseLocalStorageSpec);
1755
+ if (pairs.length) {
1756
+ await context.addInitScript({ content: localStorageInitScript(pairs, new URL(targetUrl).origin) });
1757
+ }
1758
+ if (auth.initScriptPath)
1759
+ await context.addInitScript({ path: auth.initScriptPath });
1760
+ }
1761
+ /** Validate a --user-data-dir before launch. It must exist and must NOT look
1762
+ * like a profile a live Chrome is holding open — Chrome locks its profile with
1763
+ * Singleton{Lock,Socket} entries, and pointing Playwright at a locked profile
1764
+ * either fails or forces a flaky copy. The docs boundary: never the live default
1765
+ * profile; use a copy or a dedicated logged-in profile dir. die(2) on any miss. */
1766
+ function validateUserDataDir(dir) {
1767
+ let st;
1768
+ try {
1769
+ st = statSync(dir);
1770
+ }
1771
+ catch {
1772
+ die(`--user-data-dir not found: ${dir} (create it, or use a copy of a logged-in profile)`, 2);
1773
+ }
1774
+ if (!st.isDirectory())
1775
+ die(`--user-data-dir is not a directory: ${dir}`, 2);
1776
+ for (const lock of ["SingletonLock", "SingletonSocket"]) {
1777
+ if (existsSync(join(dir, lock))) {
1778
+ die(`--user-data-dir looks like a live/locked Chrome profile (${lock} present): ${dir}\n` +
1779
+ `Never point Clipy at a running Chrome's profile — Chrome locks it while open. Close that Chrome, or use a COPY / a dedicated logged-in profile dir.`, 2);
1780
+ }
1781
+ }
1782
+ }
1783
+ /** Launch a recording context. With userDataDir: a PERSISTENT context bound to
1784
+ * that dir (launchPersistentContext — it IS the context, there's no separate
1785
+ * browser; recordVideo/init-scripts/cookies still apply). Without: an ephemeral
1786
+ * browser + newContext (storageState only applies here). Either way the caller
1787
+ * gets {context, browser} — browser is null in persistent mode, and closing the
1788
+ * context tears down that browser. */
1789
+ async function launchRecordingContext(chromium, opts) {
1790
+ const recordVideo = { dir: opts.recordVideoDir, size: opts.viewport };
1791
+ if (opts.userDataDir) {
1792
+ const context = await chromium.launchPersistentContext(opts.userDataDir, {
1793
+ headless: true,
1794
+ viewport: opts.viewport,
1795
+ recordVideo,
1796
+ args: opts.args,
1797
+ });
1798
+ return { context, browser: null };
1799
+ }
1800
+ const browser = await chromium.launch({ headless: true, args: opts.args });
1801
+ const context = await browser.newContext({
1802
+ viewport: opts.viewport,
1803
+ recordVideo,
1804
+ ...(opts.storageStatePath ? { storageState: opts.storageStatePath } : {}),
1805
+ });
1806
+ return { context, browser };
1807
+ }
1513
1808
  async function cmdRecord(ctx, opts) {
1514
1809
  // Validate the target URL up front — a headless browser will happily hang on
1515
1810
  // a typo'd or non-http(s) URL otherwise.
@@ -1523,6 +1818,9 @@ async function cmdRecord(ctx, opts) {
1523
1818
  if (target.protocol !== "http:" && target.protocol !== "https:") {
1524
1819
  die(`--url must be http(s), got ${target.protocol}`, 2);
1525
1820
  }
1821
+ validateAuthCapture(opts.auth, target.href); // usage errors (exit 2) before auth/browser
1822
+ if (opts.userDataDir)
1823
+ validateUserDataDir(opts.userDataDir);
1526
1824
  requireKey(ctx); // fail fast before we spin up a browser
1527
1825
  const chromium = await loadChromium();
1528
1826
  const tmpDir = join(tmpdir(), `clipy-record-${randomUUID()}`);
@@ -1557,20 +1855,24 @@ async function cmdRecord(ctx, opts) {
1557
1855
  try {
1558
1856
  // --- Capture -----------------------------------------------------------
1559
1857
  let videoPath;
1560
- log(`${c.dim("launching headless chromium…")}`);
1561
- const browser = await chromium.launch({
1562
- headless: true,
1563
- // Cloud sandboxes / CI containers run as root where Chromium's own
1564
- // sandbox can't initialize; this is a user-driven capture of a URL they
1565
- // chose, so the browser sandbox isn't a trust boundary here.
1858
+ log(`${c.dim(opts.userDataDir ? "launching chromium (persistent profile)…" : "launching headless chromium…")}`);
1859
+ // Cloud sandboxes / CI containers run as root where Chromium's own sandbox
1860
+ // can't initialize; this is a user-driven capture of a URL they chose, so the
1861
+ // browser sandbox isn't a trust boundary here. --user-data-dir ⇒ a persistent
1862
+ // context (its own browser); else an ephemeral browser + context.
1863
+ const { context, browser } = await launchRecordingContext(chromium, {
1864
+ userDataDir: opts.userDataDir,
1865
+ viewport: frame,
1866
+ recordVideoDir: tmpDir,
1566
1867
  args: ["--no-sandbox", "--disable-dev-shm-usage"],
1868
+ storageStatePath: opts.auth.storageStatePath,
1567
1869
  });
1568
1870
  try {
1569
- const context = await browser.newContext({
1570
- viewport: { width: frame.width, height: frame.height },
1571
- recordVideo: { dir: tmpDir, size: frame },
1572
- });
1573
- const page = await context.newPage();
1871
+ // Seed cookies/localStorage/init-script before the first navigation. These
1872
+ // compose with a persistent profile too; --storage-state does not (rejected
1873
+ // together at parse time).
1874
+ await applyAuthCapture(context, opts.auth, target.href);
1875
+ const page = context.pages()[0] ?? (await context.newPage());
1574
1876
  // captureStart is set AFTER the first meaningful paint (below), so notes
1575
1877
  // and pass marks aren't anchored to the blank t=0 a compiling app shows.
1576
1878
  let captureStart = 0;
@@ -1627,7 +1929,12 @@ async function cmdRecord(ctx, opts) {
1627
1929
  videoPath = await video.path();
1628
1930
  }
1629
1931
  finally {
1630
- await browser.close().catch(() => { });
1932
+ // Persistent mode has no separate browser — closing the context (above, or
1933
+ // here on an early throw) tears down its Chromium.
1934
+ if (browser)
1935
+ await browser.close().catch(() => { });
1936
+ else
1937
+ await context.close().catch(() => { });
1631
1938
  }
1632
1939
  // --- Upload ------------------------------------------------------------
1633
1940
  const notes = [...autoNotes, ...resolveNarrationNotes(opts.notes, passStartsMs)].sort((a, b) => a.startMs - b.startMs);
@@ -1689,6 +1996,14 @@ function sessionFilePath(cwd) {
1689
1996
  const digest = createHash("sha1").update(cwd).digest("hex").slice(0, 16);
1690
1997
  return join(sessionDir(), `session-${digest}.json`);
1691
1998
  }
1999
+ /** Which session file the mark/chapter/stop/abort/status verbs operate on.
2000
+ * CLIPY_SESSION_FILE (exported by `session run` to its child) wins, so a driver
2001
+ * invoked from a different cwd than the session still finds it; the cwd hash is
2002
+ * the fallback for a plain interactive session. */
2003
+ function sessionFileToUse() {
2004
+ const fromEnv = process.env.CLIPY_SESSION_FILE?.trim();
2005
+ return fromEnv || sessionFilePath(process.cwd());
2006
+ }
1692
2007
  function readSessionState(file) {
1693
2008
  try {
1694
2009
  return JSON.parse(readFileSync(file, "utf8"));
@@ -1735,6 +2050,113 @@ function cleanupSessionFiles(state, file) {
1735
2050
  }
1736
2051
  }
1737
2052
  }
2053
+ /** Compile a URL glob to a RegExp: `**` → `.*`, a lone `*` → `[^/]*`, every
2054
+ * other regex metachar escaped. A glob with NO `*` is treated as a bare
2055
+ * substring match (the common "is this path in the URL" case). */
2056
+ function urlGlobMatches(glob, url) {
2057
+ if (!glob.includes("*"))
2058
+ return url.includes(glob);
2059
+ // Escape regex metachars, then restore the glob wildcards. \x00 is a private
2060
+ // placeholder so `**` isn't clobbered while we expand single `*`.
2061
+ const escaped = glob
2062
+ .replace(/[.+?^${}()|[\]\\]/g, "\\$&")
2063
+ .replace(/\*\*/g, "\x00")
2064
+ .replace(/\*/g, "[^/]*")
2065
+ .replace(/\x00/g, ".*");
2066
+ try {
2067
+ return new RegExp(`^${escaped}$`).test(url);
2068
+ }
2069
+ catch {
2070
+ return url.includes(glob.replace(/\*/g, ""));
2071
+ }
2072
+ }
2073
+ /** POST to the web daemon's local control endpoint with the bearer token.
2074
+ * Throws on connection failure / non-2xx (the caller decides whether to fall
2075
+ * back to the marks file or die). */
2076
+ async function postToControl(state, path, body, timeoutMs) {
2077
+ const controller = new AbortController();
2078
+ const timer = setTimeout(() => controller.abort(), timeoutMs);
2079
+ try {
2080
+ const res = await fetch(`http://127.0.0.1:${state.controlPort}${path}`, {
2081
+ method: "POST",
2082
+ headers: {
2083
+ Authorization: `Bearer ${state.controlToken}`,
2084
+ "Content-Type": "application/json",
2085
+ },
2086
+ body: JSON.stringify(body ?? {}),
2087
+ signal: controller.signal,
2088
+ });
2089
+ const text = await res.text();
2090
+ let parsed = {};
2091
+ try {
2092
+ parsed = text ? JSON.parse(text) : {};
2093
+ }
2094
+ catch {
2095
+ parsed = { raw: text };
2096
+ }
2097
+ if (!res.ok) {
2098
+ throw new Error(typeof parsed.error === "string" ? parsed.error : `control endpoint error ${res.status}`);
2099
+ }
2100
+ return parsed;
2101
+ }
2102
+ catch (e) {
2103
+ if (e.name === "AbortError")
2104
+ throw new Error(`control endpoint timed out after ${timeoutMs / 1000}s`);
2105
+ throw e;
2106
+ }
2107
+ finally {
2108
+ clearTimeout(timer);
2109
+ }
2110
+ }
2111
+ /** Evaluate an assertion against the daemon's live page. Wraps the single
2112
+ * page.evaluate in a 5s race so an unresponsive page throws (a caught error the
2113
+ * caller turns into a 5xx) instead of hanging the daemon. A selector that
2114
+ * simply doesn't match is a normal FAIL, not an error. */
2115
+ async function evaluateAssertion(page, assert) {
2116
+ const expected = [];
2117
+ const observed = [];
2118
+ let passed = true;
2119
+ if (assert.urlGlob) {
2120
+ const url = page.url();
2121
+ expected.push(`url~"${assert.urlGlob}"`);
2122
+ observed.push(`url=${url}`);
2123
+ if (!urlGlobMatches(assert.urlGlob, url))
2124
+ passed = false;
2125
+ }
2126
+ if (assert.selector) {
2127
+ const sel = assert.selector;
2128
+ // Runs in the browser; typed locally so the CLI needs no DOM lib to build.
2129
+ const lookup = page.evaluate((s) => {
2130
+ const doc = globalThis.document;
2131
+ const el = doc?.querySelector(s);
2132
+ if (!el)
2133
+ return { match: false };
2134
+ const raw = (el.textContent ?? "").trim().replace(/\s+/g, " ");
2135
+ return { match: true, text: raw.slice(0, 200) };
2136
+ }, sel);
2137
+ const result = await Promise.race([
2138
+ lookup,
2139
+ new Promise((_, reject) => setTimeout(() => reject(new Error("page did not respond within 5s")), 5000)),
2140
+ ]);
2141
+ if (!result.match) {
2142
+ passed = false;
2143
+ expected.push(assert.expectText ? `${sel} containing "${assert.expectText}"` : `${sel} present`);
2144
+ observed.push(`${sel}=no match`);
2145
+ }
2146
+ else {
2147
+ observed.push(`${sel}=${result.text ? `"${result.text}"` : "(empty)"}`);
2148
+ if (assert.expectText != null && assert.expectText !== "") {
2149
+ expected.push(`"${assert.expectText}"`);
2150
+ if (!result.text.includes(assert.expectText))
2151
+ passed = false;
2152
+ }
2153
+ else {
2154
+ expected.push(`${sel} present`);
2155
+ }
2156
+ }
2157
+ }
2158
+ return { passed, observed: observed.join("; "), expected: expected.join("; ") };
2159
+ }
1738
2160
  // --- Mac bridge flows (--source mac-screen): the desktop app records -------
1739
2161
  /** Resolves --window/--display to a bridge capture source (null = app default,
1740
2162
  * i.e. the full primary display). die()s with the candidate list on no/ambiguous
@@ -1824,6 +2246,23 @@ function bridgeInfoFromSession(state) {
1824
2246
  protocolVersion: 1,
1825
2247
  };
1826
2248
  }
2249
+ /** The ready-to-run Playwright snippet printed after `session start --expose-cdp`.
2250
+ * Encodes the four gotchas that otherwise cost an agent a debugging round:
2251
+ * use connectOverCDP; the recorded page is contexts()[0].pages()[0] (a fresh
2252
+ * context/page is NOT the one being recorded); viewportSize() is null over CDP;
2253
+ * and a resize needs a CDP Emulation.setDeviceMetricsOverride, not setViewportSize. */
2254
+ function cdpDriverSnippet(cdpHttpUrl) {
2255
+ return [
2256
+ `${c.dim("drive the recorded page with your own Playwright:")}`,
2257
+ c.dim(` const { chromium } = require('playwright');`),
2258
+ c.dim(` const browser = await chromium.connectOverCDP(${JSON.stringify(cdpHttpUrl)});`),
2259
+ c.dim(` const page = browser.contexts()[0].pages()[0]; // the page being recorded (a NEW context/page is not captured)`),
2260
+ c.dim(` await page.goto('https://…'); // navigate / click / fill as usual`),
2261
+ c.dim(` const cdp = await browser.newCDPSession(page); // page.viewportSize() is null over CDP —`),
2262
+ c.dim(` await cdp.send('Emulation.setDeviceMetricsOverride', { width: 1280, height: 720, deviceScaleFactor: 1, mobile: false });`),
2263
+ c.dim(` resolve playwright for your script: NODE_PATH=$(clipy playwright-path) node driver.js`),
2264
+ ].join("\n");
2265
+ }
1827
2266
  async function cmdSessionStart(ctx, opts) {
1828
2267
  if (opts.source === "mac-screen") {
1829
2268
  const file = sessionFilePath(process.cwd());
@@ -1866,6 +2305,9 @@ async function cmdSessionStart(ctx, opts) {
1866
2305
  if (target.protocol !== "http:" && target.protocol !== "https:") {
1867
2306
  die(`--url must be http(s), got ${target.protocol}`, 2);
1868
2307
  }
2308
+ validateAuthCapture(opts.auth, target.href); // usage errors (exit 2) before auth/daemonizing
2309
+ if (opts.userDataDir)
2310
+ validateUserDataDir(opts.userDataDir);
1869
2311
  const key = requireKey(ctx);
1870
2312
  await loadChromium(); // fail fast with install instructions before daemonizing
1871
2313
  const file = sessionFilePath(process.cwd());
@@ -1892,6 +2334,11 @@ async function cmdSessionStart(ctx, opts) {
1892
2334
  width: opts.width,
1893
2335
  height: opts.height,
1894
2336
  exposeCdp: opts.exposeCdp,
2337
+ storageStatePath: opts.auth.storageStatePath,
2338
+ initScriptPath: opts.auth.initScriptPath,
2339
+ cookieSpecs: opts.auth.cookieSpecs.length ? opts.auth.cookieSpecs : undefined,
2340
+ localStorageSpecs: opts.auth.localStorageSpecs.length ? opts.auth.localStorageSpecs : undefined,
2341
+ userDataDir: opts.userDataDir,
1895
2342
  state: "starting",
1896
2343
  marksPath: join(dir, `marks-${id}.jsonl`),
1897
2344
  controlPath: join(dir, `control-${id}.json`),
@@ -1944,8 +2391,8 @@ async function cmdSessionStart(ctx, opts) {
1944
2391
  }
1945
2392
  process.stdout.write(`${c.green("✓")} recording ${c.bold(target.href)} (max ${maxSec}s)\n`);
1946
2393
  if (started?.cdpHttpUrl) {
1947
- process.stdout.write(`${c.yellow("⚠ CDP exposed:")} any local process can attach to and control this browser while the session runs.\n` +
1948
- `${c.dim(`drive the browser: connect your tools to ${started.cdpHttpUrl}`)}\n`);
2394
+ process.stdout.write(`${c.yellow("⚠ CDP exposed:")} any local process can attach to and control this browser while the session runs.\n`);
2395
+ process.stdout.write(`${cdpDriverSnippet(started.cdpHttpUrl)}\n`);
1949
2396
  }
1950
2397
  else if (opts.exposeCdp) {
1951
2398
  // Asked for it, but it isn't up — either env-disabled or discovery failed.
@@ -1957,16 +2404,40 @@ async function cmdSessionStart(ctx, opts) {
1957
2404
  `${c.dim("when finished:")} clipy session stop ${c.dim("· discard:")} clipy session abort\n`);
1958
2405
  }
1959
2406
  function requireSession() {
1960
- const file = sessionFilePath(process.cwd());
2407
+ const file = sessionFileToUse();
1961
2408
  const state = readSessionState(file);
1962
2409
  if (!state) {
1963
2410
  die(`no recording session in this workspace. Start one with \`clipy session start --url <app>\`.`);
1964
2411
  }
1965
2412
  return { file, state };
1966
2413
  }
1967
- async function cmdMark(text, json) {
2414
+ /** Print a /mark or /chapter control response (or a file-fallback shape). A
2415
+ * failed assertion prints a red ✗; everything else a green ✓. The mark text is
2416
+ * already annotated daemon-side, so it carries the ✓/✗ + observed inline. */
2417
+ function printMarkResult(res, json) {
2418
+ if (json) {
2419
+ printJson(res);
2420
+ return;
2421
+ }
2422
+ const sec = (Number(res.tMs ?? 0) / 1000).toFixed(1);
2423
+ const assert = res.assert;
2424
+ const glyph = assert && assert.passed === false ? c.red("✗") : c.green("✓");
2425
+ process.stdout.write(`${glyph} mark @ ${sec}s — ${String(res.text ?? "")}\n`);
2426
+ }
2427
+ async function cmdMark(text, json, opts) {
1968
2428
  const { file, state } = requireSession();
2429
+ const hasAssert = !!opts.assert;
2430
+ const backdated = opts.atSec != null || opts.agoSec != null;
1969
2431
  if (state.kind === "mac") {
2432
+ // The Mac app records the real screen — there is no page to probe, and the
2433
+ // bridge stamps every mark on its own clock, so assertions and backdating
2434
+ // are web-session features.
2435
+ if (hasAssert) {
2436
+ die("assertions need a web session — the Mac app records the real screen; there is no page to probe", 2);
2437
+ }
2438
+ if (backdated) {
2439
+ die("--at/--ago need a web session — the Mac bridge stamps each mark on its own clock", 2);
2440
+ }
1970
2441
  const result = await bridgeRequest(bridgeInfoFromSession(state), "mark", { text }).catch((e) => {
1971
2442
  if (e instanceof BridgeUnavailableError) {
1972
2443
  cleanupSessionFiles(state, file);
@@ -1988,14 +2459,121 @@ async function cmdMark(text, json) {
1988
2459
  if (state.state !== "recording" || !state.recordStartEpochMs) {
1989
2460
  die(`session is ${state.state} — marks can only be added while recording`);
1990
2461
  }
2462
+ // --at is an absolute recording-clock time; --ago is N seconds before now,
2463
+ // both computed against the SAME recordStartEpochMs the daemon saved. Absent ⇒
2464
+ // let the daemon stamp its live clock (undefined atMs).
2465
+ const atMs = backdated
2466
+ ? opts.atSec != null
2467
+ ? Math.max(0, Math.round(opts.atSec * 1000))
2468
+ : Math.max(0, Date.now() - state.recordStartEpochMs - Math.round((opts.agoSec ?? 0) * 1000))
2469
+ : undefined;
2470
+ // A client-generated id rides both the HTTP call and any file fallback so the
2471
+ // daemon can drop a file duplicate of an HTTP mark it already processed (the
2472
+ // client timed out, the daemon didn't).
2473
+ const markId = randomUUID();
2474
+ const cleanText = text.trim();
2475
+ const localTMs = atMs != null ? atMs : Math.max(0, Date.now() - state.recordStartEpochMs);
2476
+ if (state.controlPort && state.controlToken) {
2477
+ let res;
2478
+ try {
2479
+ res = await postToControl(state, "/mark", {
2480
+ id: markId,
2481
+ text: cleanText,
2482
+ ...(atMs != null ? { atMs } : {}),
2483
+ ...(hasAssert ? { assert: opts.assert } : {}),
2484
+ }, CONTROL_TIMEOUT_MS);
2485
+ }
2486
+ catch (e) {
2487
+ const reason = String(e.message).slice(0, 120);
2488
+ // NEVER drop a mark. If the daemon didn't answer, record the narration to
2489
+ // the file regardless. For an ASSERTED mark we couldn't verify the claim,
2490
+ // so tag it honestly ⚠ UNVERIFIED (never a silent pass) — the daemon counts
2491
+ // {unverified:true} file marks into the tally's third bucket.
2492
+ if (hasAssert) {
2493
+ const annotated = `${cleanText} [ASSERT ⚠ could not evaluate — ${reason}]`;
2494
+ appendFileSync(state.marksPath, `${JSON.stringify({ id: markId, tMs: localTMs, text: annotated, unverified: true })}\n`, { mode: 0o600 });
2495
+ if (json) {
2496
+ printJson({ tMs: localTMs, text: annotated, assert: { unverified: true, reason } });
2497
+ }
2498
+ else {
2499
+ process.stderr.write(`${c.yellow("⚠")} mark recorded, assertion UNVERIFIED (${reason}) @ ${(localTMs / 1000).toFixed(1)}s — ${annotated}\n`);
2500
+ }
2501
+ return;
2502
+ }
2503
+ appendFileSync(state.marksPath, `${JSON.stringify({ id: markId, tMs: localTMs, text: cleanText })}\n`, { mode: 0o600 });
2504
+ printMarkResult({ tMs: localTMs, text: cleanText }, json);
2505
+ return;
2506
+ }
2507
+ if (res.aborted) {
2508
+ // A failed assertion with --fail-mode abort discarded the session. Show
2509
+ // the ✗ mark, then die loudly so the agent can't mistake this for success.
2510
+ printMarkResult(res, json);
2511
+ die("session ABORTED by a failed assertion (--fail-mode abort) — nothing was uploaded. Fix the condition, then start a new session.");
2512
+ }
2513
+ printMarkResult(res, json);
2514
+ return;
2515
+ }
2516
+ // No control endpoint (session started by a pre-0.6 CLI): assertions can't run.
2517
+ if (hasAssert) {
2518
+ die("this session has no control endpoint (started by an older clipy) — stop it and run `clipy session start` again to use assertion marks");
2519
+ }
2520
+ appendFileSync(state.marksPath, `${JSON.stringify({ id: markId, tMs: localTMs, text: cleanText })}\n`, { mode: 0o600 });
2521
+ printMarkResult({ tMs: localTMs, text: cleanText }, json);
2522
+ }
2523
+ /** `clipy chapter "<label>"` — a chapter is a specially-formatted mark
2524
+ * (=== CHAPTER: <label> ===) that splits one recording into BEFORE/AFTER
2525
+ * sections (demo base branch → chapter "AFTER" → swap branch → demo the fix). */
2526
+ async function cmdChapter(label, json) {
2527
+ const { file, state } = requireSession();
2528
+ const chapterText = `=== CHAPTER: ${label} ===`;
2529
+ if (state.kind === "mac") {
2530
+ const result = await bridgeRequest(bridgeInfoFromSession(state), "mark", { text: chapterText }).catch((e) => {
2531
+ if (e instanceof BridgeUnavailableError) {
2532
+ cleanupSessionFiles(state, file);
2533
+ die("the Clipy app is no longer running — session cleared. Start a new one.");
2534
+ }
2535
+ die(e.message);
2536
+ });
2537
+ if (json) {
2538
+ printJson({ tMs: Number(result.atSeconds ?? 0) * 1000, label, text: chapterText });
2539
+ return;
2540
+ }
2541
+ process.stdout.write(`${c.green("✓")} chapter @ ${Number(result.atSeconds ?? 0).toFixed(1)}s — ${label}\n`);
2542
+ return;
2543
+ }
2544
+ if (!pidAlive(state.pid)) {
2545
+ cleanupSessionFiles(state, file);
2546
+ die("the session daemon is no longer running (crashed?) — session cleared. Start a new one.");
2547
+ }
2548
+ if (state.state !== "recording" || !state.recordStartEpochMs) {
2549
+ die(`session is ${state.state} — chapters can only be added while recording`);
2550
+ }
2551
+ // Client id for HTTP↔file dedup, same as marks (a timed-out chapter that the
2552
+ // daemon still processed shouldn't double up).
2553
+ const chapterId = randomUUID();
2554
+ if (state.controlPort && state.controlToken) {
2555
+ try {
2556
+ const res = await postToControl(state, "/chapter", { id: chapterId, label }, CONTROL_TIMEOUT_MS);
2557
+ if (json) {
2558
+ printJson({ tMs: Number(res.tMs ?? 0), label, text: chapterText });
2559
+ }
2560
+ else {
2561
+ process.stdout.write(`${c.green("✓")} chapter @ ${(Number(res.tMs ?? 0) / 1000).toFixed(1)}s — ${label}\n`);
2562
+ }
2563
+ return;
2564
+ }
2565
+ catch {
2566
+ // Chapters aren't assertions — fall back to the marks file on failure.
2567
+ }
2568
+ }
1991
2569
  const tMs = Math.max(0, Date.now() - state.recordStartEpochMs);
1992
- appendFileSync(state.marksPath, `${JSON.stringify({ tMs, text: text.trim() })}\n`);
2570
+ appendFileSync(state.marksPath, `${JSON.stringify({ id: chapterId, tMs, text: chapterText })}\n`, { mode: 0o600 });
1993
2571
  if (json) {
1994
- printJson({ tMs, text: text.trim() });
1995
- return;
2572
+ printJson({ tMs, label, text: chapterText });
2573
+ }
2574
+ else {
2575
+ process.stdout.write(`${c.green("✓")} chapter @ ${(tMs / 1000).toFixed(1)}s — ${label}\n`);
1996
2576
  }
1997
- const sec = (tMs / 1000).toFixed(1);
1998
- process.stdout.write(`${c.green("✓")} mark @ ${sec}s — ${text.trim()}\n`);
1999
2577
  }
2000
2578
  async function cmdSessionStop(json) {
2001
2579
  const { file, state } = requireSession();
@@ -2104,15 +2682,67 @@ async function cmdSessionAbort(json) {
2104
2682
  await new Promise((r) => setTimeout(r, 300));
2105
2683
  }
2106
2684
  const final = readSessionState(file);
2685
+ const alive = final ? pidAlive(final.pid) : false;
2686
+ // The daemon is still alive AND mid-upload of a stop/max capture — the abort
2687
+ // arrived after it committed to finishing. Killing it would strand a partial
2688
+ // server-side upload, so let it finish; the user can collect it with
2689
+ // `session stop`. Leave the state file in place for that.
2690
+ if (final && alive && (final.state === "stopping" || final.state === "uploading")) {
2691
+ if (json) {
2692
+ printJson({ state: "finishing" });
2693
+ }
2694
+ else {
2695
+ 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`);
2696
+ }
2697
+ process.exitCode = 1;
2698
+ return;
2699
+ }
2700
+ // Still recording after the full wait ⇒ the abort didn't take (wedged Chromium
2701
+ // / hung page). Don't quietly delete the state file out from under a process
2702
+ // that may still be recording — escalate: SIGTERM, a short grace, then SIGKILL,
2703
+ // and only THEN clean up. This is what makes `session run`'s "guaranteed
2704
+ // cleanup" honest.
2705
+ const wedged = final ? alive && (final.state === "starting" || final.state === "recording") : false;
2706
+ if (wedged && final) {
2707
+ try {
2708
+ process.kill(final.pid, "SIGTERM");
2709
+ }
2710
+ catch {
2711
+ // already gone
2712
+ }
2713
+ const graceDeadline = Date.now() + 3000;
2714
+ while (pidAlive(final.pid) && Date.now() < graceDeadline) {
2715
+ await new Promise((r) => setTimeout(r, 150));
2716
+ }
2717
+ if (pidAlive(final.pid)) {
2718
+ try {
2719
+ process.kill(final.pid, "SIGKILL");
2720
+ }
2721
+ catch {
2722
+ // already gone
2723
+ }
2724
+ }
2725
+ }
2107
2726
  if (final)
2108
2727
  cleanupSessionFiles(final, file);
2728
+ if (wedged) {
2729
+ // Exit non-zero (and truthfully) — the daemon had to be force-killed, so we
2730
+ // can't promise a clean discard. Use process.exitCode (not process.exit) so
2731
+ // a caller like `session run` can still override with the child's code.
2732
+ if (json)
2733
+ printJson({ state: "killed", pid: final?.pid ?? null });
2734
+ else
2735
+ process.stderr.write(`${c.yellow("!")} the session daemon ignored abort for 30s and was force-killed (pid ${final?.pid}); nothing was uploaded\n`);
2736
+ process.exitCode = 1;
2737
+ return;
2738
+ }
2109
2739
  if (json)
2110
2740
  printJson({ state: "aborted" });
2111
2741
  else
2112
2742
  process.stdout.write(`${c.green("✓")} session aborted — nothing was uploaded\n`);
2113
2743
  }
2114
2744
  async function cmdSessionStatus(json) {
2115
- const file = sessionFilePath(process.cwd());
2745
+ const file = sessionFileToUse();
2116
2746
  const state = readSessionState(file);
2117
2747
  if (!state) {
2118
2748
  if (json)
@@ -2175,8 +2805,73 @@ async function cmdSessionStatus(json) {
2175
2805
  process.stdout.write(`${c.bold(state.state)}${alive ? "" : c.red(" (daemon dead)")} — ${state.url}` +
2176
2806
  `${elapsed != null ? ` — ${elapsed}s elapsed (max ${state.maxSec}s)` : ""}\n`);
2177
2807
  if (state.cdpHttpUrl && state.state === "recording" && alive) {
2178
- process.stdout.write(`${c.dim(`drive the browser: connect your tools to ${state.cdpHttpUrl}`)}\n`);
2808
+ 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`);
2809
+ }
2810
+ }
2811
+ /**
2812
+ * `clipy session run [start-flags] -- <command …>` — the crash-safe wrapper.
2813
+ * Starts a session, runs the command with inherited stdio, and GUARANTEES
2814
+ * cleanup: exit 0 uploads (session stop), any non-zero exit / signal discards
2815
+ * (session abort) and propagates the child's code. This is the fleet answer to
2816
+ * a crashed driver recording dead air to its max ceiling.
2817
+ */
2818
+ async function cmdSessionRun(ctx, startOpts, childArgv) {
2819
+ if (childArgv.length === 0) {
2820
+ die("usage: clipy session run [start flags] -- <command …> (everything after -- is the command to run)", 2);
2821
+ }
2822
+ // Start the session and block until it's recording. Force human output — the
2823
+ // child inherits our stdio and the deliverable is the wrapped run, not JSON.
2824
+ await cmdSessionStart(ctx, { ...startOpts, json: false });
2825
+ const file = sessionFilePath(process.cwd());
2826
+ const cdpHttpUrl = readSessionState(file)?.cdpHttpUrl;
2827
+ const [cmd, ...args] = childArgv;
2828
+ process.stderr.write(`${c.dim(`running: ${childArgv.join(" ")}`)}\n`);
2829
+ const child = spawn(cmd, args, {
2830
+ stdio: "inherit",
2831
+ env: {
2832
+ ...process.env,
2833
+ // Signals to the child that it's being recorded, and where to drive. The
2834
+ // session file is exported explicitly so `clipy mark`/`chapter` resolve it
2835
+ // even from a different cwd than this session's (the reporter's driver did).
2836
+ CLIPY_SESSION: "1",
2837
+ CLIPY_SESSION_FILE: file,
2838
+ ...(cdpHttpUrl ? { CLIPY_CDP_URL: cdpHttpUrl } : {}),
2839
+ },
2840
+ });
2841
+ // Forward Ctrl-C / termination to the child; its exit then drives the abort
2842
+ // path below (so we never double-abort or race the child).
2843
+ let forwarded = false;
2844
+ const forward = (sig) => {
2845
+ forwarded = true;
2846
+ try {
2847
+ child.kill(sig);
2848
+ }
2849
+ catch {
2850
+ // child already gone
2851
+ }
2852
+ };
2853
+ const onSigint = () => forward("SIGINT");
2854
+ const onSigterm = () => forward("SIGTERM");
2855
+ process.on("SIGINT", onSigint);
2856
+ process.on("SIGTERM", onSigterm);
2857
+ const outcome = await new Promise((res) => {
2858
+ child.on("error", (e) => {
2859
+ // Couldn't even spawn the command — don't leave the session recording.
2860
+ void cmdSessionAbort(false)
2861
+ .catch(() => { })
2862
+ .finally(() => die(`failed to run command "${cmd}": ${e.message}`));
2863
+ });
2864
+ child.on("exit", (code, signal) => res({ code, signal }));
2865
+ });
2866
+ process.off("SIGINT", onSigint);
2867
+ process.off("SIGTERM", onSigterm);
2868
+ if (outcome.code === 0 && !outcome.signal && !forwarded) {
2869
+ await cmdSessionStop(false); // clean exit → upload + print the share link
2870
+ return;
2179
2871
  }
2872
+ process.stderr.write(`${c.yellow(`command ${outcome.signal ? `terminated by ${outcome.signal}` : `exited ${outcome.code}`} — discarding the recording`)}\n`);
2873
+ await cmdSessionAbort(false);
2874
+ process.exit(outcome.code ?? 1); // propagate the child's failure
2180
2875
  }
2181
2876
  /** Reserve a free localhost TCP port for Chromium's CDP endpoint. Binding to
2182
2877
  * :0 then closing hands us a concrete port to pass to --remote-debugging-port,
@@ -2236,8 +2931,34 @@ async function runSessionDaemon(file) {
2236
2931
  return;
2237
2932
  autoMarks.push({ startMs: Math.max(0, Date.now() - recordStart), text });
2238
2933
  };
2934
+ // Marks that arrive over the control endpoint (`clipy mark`/`chapter`) or the
2935
+ // in-page __clipyMark/__clipyChapter bindings. Kept in memory (like autoMarks)
2936
+ // and merged at stop. A hard 200 cap here is the server limit; storeDaemonMark
2937
+ // refuses past it so `clipy mark` gets an error rather than a silent drop.
2938
+ const daemonMarks = [];
2939
+ const storeDaemonMark = (note) => {
2940
+ if (daemonMarks.length >= 200)
2941
+ return false;
2942
+ daemonMarks.push(note);
2943
+ return true;
2944
+ };
2945
+ // Assertion tallies → the leading [verification] note at stop.
2946
+ let assertRan = 0;
2947
+ let assertPassed = 0;
2948
+ let assertFailed = 0;
2949
+ // A failed --fail-mode=abort assertion sets this; the main loop discards.
2950
+ let controlSignal = null;
2951
+ // Client-generated ids of marks/chapters we processed over HTTP — so at merge
2952
+ // we can drop a file duplicate the client wrote after its call timed out but
2953
+ // the daemon actually completed it.
2954
+ const processedMarkIds = new Set();
2239
2955
  mkdirSync(state.tmpDir, { recursive: true });
2240
2956
  let browser = null;
2957
+ // Persistent (--user-data-dir) contexts have no separate browser, so track the
2958
+ // context too for the finally cleanup (an exception before stop must not leak
2959
+ // the Chromium).
2960
+ let ctxToClose = null;
2961
+ let controlServer = null;
2241
2962
  try {
2242
2963
  const chromium = await loadChromium();
2243
2964
  log(`launching chromium for ${state.url}`);
@@ -2250,19 +2971,33 @@ async function runSessionDaemon(file) {
2250
2971
  if (state.exposeCdp && !wantCdp)
2251
2972
  log("CDP disabled by CLIPY_DISABLE_CDP=1 — not opening a debugging port");
2252
2973
  const cdpPort = wantCdp ? await pickFreePort().catch(() => 0) : 0;
2253
- browser = await chromium.launch({
2254
- headless: true,
2974
+ // --user-data-dir ⇒ a persistent context (its own browser); else an ephemeral
2975
+ // browser + context. The CDP debugging port (if any) rides the launch args.
2976
+ const { context, browser: launchedBrowser } = await launchRecordingContext(chromium, {
2977
+ userDataDir: state.userDataDir,
2978
+ viewport: { width: state.width, height: state.height },
2979
+ recordVideoDir: state.tmpDir,
2255
2980
  args: [
2256
2981
  "--no-sandbox",
2257
2982
  "--disable-dev-shm-usage",
2258
2983
  ...(cdpPort ? [`--remote-debugging-port=${cdpPort}`] : []),
2259
2984
  ],
2985
+ storageStatePath: state.storageStatePath,
2260
2986
  });
2261
- const context = await browser.newContext({
2262
- viewport: { width: state.width, height: state.height },
2263
- recordVideo: { dir: state.tmpDir, size: { width: state.width, height: state.height } },
2264
- });
2265
- const page = await context.newPage();
2987
+ browser = launchedBrowser;
2988
+ ctxToClose = context;
2989
+ // Seed cookies/localStorage/init-script before the first navigation — re-parse
2990
+ // the raw specs the parent CLI already validated. A bad spec here is caught by
2991
+ // the outer try/catch and fails the session cleanly. (--storage-state was
2992
+ // applied at launch; it and --user-data-dir are mutually exclusive.)
2993
+ await applyAuthCapture(context, {
2994
+ storageStatePath: state.storageStatePath,
2995
+ initScriptPath: state.initScriptPath,
2996
+ cookieSpecs: state.cookieSpecs ?? [],
2997
+ localStorageSpecs: state.localStorageSpecs ?? [],
2998
+ }, state.url);
2999
+ // Persistent contexts open with a default page; ephemeral ones start empty.
3000
+ const page = context.pages()[0] ?? (await context.newPage());
2266
3001
  // Best-effort: publish the CDP URL so `session start`/`status` can hand it
2267
3002
  // to the agent. The recording works fine even if discovery fails.
2268
3003
  let cdpUrl;
@@ -2298,8 +3033,211 @@ async function runSessionDaemon(file) {
2298
3033
  // ignore
2299
3034
  }
2300
3035
  }));
3036
+ // The ONE place a mark is recorded, shared by the HTTP control endpoint and
3037
+ // the in-page __clipyMark binding, so both evaluate assertions against the
3038
+ // live page identically. Records the (annotated) mark and returns the
3039
+ // CLI/driver-facing response.
3040
+ const applyMark = async (m) => {
3041
+ const text = m.text.trim();
3042
+ if (!text)
3043
+ throw new Error("mark text is required");
3044
+ const tMs = typeof m.atMs === "number" && Number.isFinite(m.atMs)
3045
+ ? Math.max(0, Math.round(m.atMs))
3046
+ : Math.max(0, Date.now() - recordStart);
3047
+ let annotated = text;
3048
+ let assertOut;
3049
+ let aborted = false;
3050
+ if (m.assert && typeof m.assert === "object") {
3051
+ // evaluateAssertion throws if the page is unresponsive — the HTTP path
3052
+ // turns that into a 5xx (the CLI then records a ⚠ UNVERIFIED file mark),
3053
+ // and the in-page path rejects to the driver.
3054
+ const ev = await evaluateAssertion(page, m.assert);
3055
+ assertRan++;
3056
+ if (ev.passed)
3057
+ assertPassed++;
3058
+ else
3059
+ assertFailed++;
3060
+ annotated = ev.passed
3061
+ ? `${text} [assert ✓ ${ev.observed}]`
3062
+ : `${text} [ASSERT ✗ expected ${ev.expected}; observed ${ev.observed}]`;
3063
+ assertOut = { passed: ev.passed, observed: ev.observed };
3064
+ if (!ev.passed && m.assert.failMode === "abort")
3065
+ aborted = true;
3066
+ }
3067
+ if (!storeDaemonMark({ startMs: tMs, text: annotated })) {
3068
+ throw new Error("mark limit reached (200 marks per recording)");
3069
+ }
3070
+ if (m.id)
3071
+ processedMarkIds.add(m.id);
3072
+ if (aborted)
3073
+ controlSignal = "abort";
3074
+ return {
3075
+ tMs,
3076
+ text: annotated,
3077
+ ...(assertOut ? { assert: assertOut } : {}),
3078
+ ...(aborted ? { aborted: true } : {}),
3079
+ };
3080
+ };
3081
+ // In-page mark/chapter bindings — only under --expose-cdp, alongside the
3082
+ // debugging port a driver already uses. window.__clipyMark(text, opts?) with
3083
+ // opts {assertSelector, assertText, assertUrl, failMode} runs the SAME
3084
+ // daemon-side assertion + annotation as the CLI flags, at ZERO spawn cost.
3085
+ // NOTE: while CDP is exposed the page's own scripts can call these too —
3086
+ // within the existing --expose-cdp trust model (documented in the README).
3087
+ if (wantCdp) {
3088
+ await context
3089
+ .exposeBinding("__clipyMark", async (_src, ...args) => {
3090
+ if (recordStart === 0)
3091
+ return { skipped: true };
3092
+ const o = (args[1] ?? {});
3093
+ let assert;
3094
+ if (o.assertSelector || o.assertText || o.assertUrl) {
3095
+ // Thrown here ⇒ the page's `await window.__clipyMark(...)` rejects, so
3096
+ // the driver sees the misuse (mirrors the CLI's die(2)).
3097
+ if (o.assertText != null && !o.assertSelector) {
3098
+ throw new Error("__clipyMark: assertText requires assertSelector");
3099
+ }
3100
+ assert = {
3101
+ selector: o.assertSelector,
3102
+ expectText: o.assertText,
3103
+ urlGlob: o.assertUrl,
3104
+ failMode: o.failMode === "abort" ? "abort" : "warn",
3105
+ };
3106
+ }
3107
+ return await applyMark({ text: String(args[0] ?? ""), assert });
3108
+ })
3109
+ .catch((e) => log(`__clipyMark binding failed: ${e.message}`));
3110
+ await context
3111
+ .exposeBinding("__clipyChapter", (_src, ...args) => {
3112
+ if (recordStart === 0)
3113
+ return;
3114
+ const label = String(args[0] ?? "").trim();
3115
+ if (label) {
3116
+ storeDaemonMark({ startMs: Math.max(0, Date.now() - recordStart), text: `=== CHAPTER: ${label} ===` });
3117
+ }
3118
+ })
3119
+ .catch((e) => log(`__clipyChapter binding failed: ${e.message}`));
3120
+ }
3121
+ // Local control endpoint: `clipy mark`/`chapter` POST here so the daemon —
3122
+ // which owns the live page — evaluates assertions and stamps marks on its
3123
+ // own clock. 127.0.0.1 only, bearer-token auth (random UUID). If it can't
3124
+ // bind, the recording still runs and marks fall back to the marks file.
3125
+ const controlToken = randomUUID();
3126
+ let controlPort = 0;
3127
+ /** POST /mark → applyMark (shared with the in-page binding): stamp, optional
3128
+ * assertion against the live page, store, and return the CLI-facing shape.
3129
+ * The client id rides through so a timed-out-but-processed mark is deduped. */
3130
+ const handleMark = (body) => applyMark({
3131
+ text: typeof body.text === "string" ? body.text : "",
3132
+ atMs: typeof body.atMs === "number" ? body.atMs : undefined,
3133
+ assert: body.assert,
3134
+ id: typeof body.id === "string" ? body.id : undefined,
3135
+ });
3136
+ /** POST /chapter → a === CHAPTER === mark at the live clock. */
3137
+ const handleChapter = (body) => {
3138
+ const label = typeof body.label === "string" ? body.label.trim() : "";
3139
+ if (!label)
3140
+ throw new Error("chapter label is required");
3141
+ const tMs = Math.max(0, Date.now() - recordStart);
3142
+ if (!storeDaemonMark({ startMs: tMs, text: `=== CHAPTER: ${label} ===` })) {
3143
+ throw new Error("mark limit reached (200 marks per recording)");
3144
+ }
3145
+ if (typeof body.id === "string" && body.id)
3146
+ processedMarkIds.add(body.id);
3147
+ return { tMs };
3148
+ };
3149
+ const BODY_CAP = 1_000_000;
3150
+ controlServer = createHttpServer((req, res) => {
3151
+ const respond = (status, obj) => {
3152
+ res.writeHead(status, { "Content-Type": "application/json" });
3153
+ res.end(JSON.stringify(obj));
3154
+ };
3155
+ if (req.headers.authorization !== `Bearer ${controlToken}`) {
3156
+ respond(401, { error: "unauthorized" });
3157
+ return;
3158
+ }
3159
+ if (req.method !== "POST") {
3160
+ respond(405, { error: "method not allowed" });
3161
+ return;
3162
+ }
3163
+ // Only JSON — a wrong content-type is almost always a confused client.
3164
+ if (!String(req.headers["content-type"] ?? "").toLowerCase().includes("application/json")) {
3165
+ respond(415, { error: "content-type must be application/json" });
3166
+ return;
3167
+ }
3168
+ // Reject an over-cap body: first by its declared Content-Length (before
3169
+ // reading a byte), then again if the stream itself exceeds the cap. Send an
3170
+ // explicit 413 and DRAIN the rest (req.resume) so a mid-upload client reads
3171
+ // the status instead of hitting the opaque socket error a bare destroy gave.
3172
+ const declared = Number(req.headers["content-length"] ?? "");
3173
+ if (Number.isFinite(declared) && declared > BODY_CAP) {
3174
+ respond(413, { error: "request body too large (1MB cap)" });
3175
+ req.resume();
3176
+ return;
3177
+ }
3178
+ let raw = "";
3179
+ let tooLarge = false;
3180
+ req.on("data", (chunk) => {
3181
+ if (tooLarge)
3182
+ return; // keep consuming (draining) but stop accumulating
3183
+ raw += chunk;
3184
+ if (raw.length > BODY_CAP) {
3185
+ tooLarge = true;
3186
+ respond(413, { error: "request body too large (1MB cap)" });
3187
+ }
3188
+ });
3189
+ req.on("end", () => {
3190
+ if (tooLarge)
3191
+ return;
3192
+ void (async () => {
3193
+ let body;
3194
+ try {
3195
+ body = raw ? JSON.parse(raw) : {};
3196
+ }
3197
+ catch {
3198
+ respond(400, { error: "invalid JSON body" });
3199
+ return;
3200
+ }
3201
+ try {
3202
+ if (req.url === "/mark")
3203
+ respond(200, await handleMark(body));
3204
+ else if (req.url === "/chapter")
3205
+ respond(200, handleChapter(body));
3206
+ else
3207
+ respond(404, { error: "not found" });
3208
+ }
3209
+ catch (e) {
3210
+ respond(500, { error: e.message });
3211
+ }
3212
+ })();
3213
+ });
3214
+ });
3215
+ // Tight timeouts (Node defaults are minutes) so a wedged local client can't
3216
+ // pin daemon sockets open. headersTimeout must be ≤ requestTimeout.
3217
+ controlServer.requestTimeout = 10_000;
3218
+ controlServer.headersTimeout = 10_000;
3219
+ try {
3220
+ await new Promise((resolveBind, rejectBind) => {
3221
+ controlServer.on("error", rejectBind);
3222
+ controlServer.listen(0, "127.0.0.1", () => resolveBind());
3223
+ });
3224
+ const addr = controlServer.address();
3225
+ controlPort = typeof addr === "object" && addr ? addr.port : 0;
3226
+ log(`control endpoint listening on 127.0.0.1:${controlPort}`);
3227
+ }
3228
+ catch (e) {
3229
+ log(`control endpoint failed to bind (${e.message}) — marks will use the file fallback`);
3230
+ controlServer = null;
3231
+ controlPort = 0;
3232
+ }
2301
3233
  recordStart = Date.now();
2302
- save({ state: "recording", recordStartEpochMs: recordStart, cdpUrl, cdpHttpUrl });
3234
+ save({
3235
+ state: "recording",
3236
+ recordStartEpochMs: recordStart,
3237
+ cdpUrl,
3238
+ cdpHttpUrl,
3239
+ ...(controlPort ? { controlPort, controlToken } : {}),
3240
+ });
2303
3241
  try {
2304
3242
  await page.goto(state.url, { waitUntil: "load", timeout: 30_000 });
2305
3243
  }
@@ -2310,6 +3248,12 @@ async function runSessionDaemon(file) {
2310
3248
  let stopReason = "stop";
2311
3249
  for (;;) {
2312
3250
  await page.waitForTimeout(400);
3251
+ // A failed --fail-mode=abort assertion (set by the control handler) discards
3252
+ // the session just like a control-file abort.
3253
+ if (controlSignal === "abort") {
3254
+ stopReason = "abort";
3255
+ break;
3256
+ }
2313
3257
  let control = null;
2314
3258
  try {
2315
3259
  control = JSON.parse(readFileSync(state.controlPath, "utf8"));
@@ -2354,25 +3298,55 @@ async function runSessionDaemon(file) {
2354
3298
  if (!video)
2355
3299
  throw new Error("browser did not produce a video (recordVideo unavailable)");
2356
3300
  const videoPath = await video.path();
2357
- await browser.close().catch(() => { });
3301
+ // Persistent mode: context.close() (above) already tore down Chromium; there
3302
+ // is no separate browser to close.
3303
+ if (browser)
3304
+ await browser.close().catch(() => { });
2358
3305
  browser = null;
2359
- // Merge the agent's marks (written live by `clipy mark` with its own
2360
- // clock) with the [auto] instrumentation marks.
2361
- const agentMarks = [];
3306
+ // Merge marks from three sources: the file (fallback path, written by
3307
+ // `clipy mark` when the control endpoint was unreachable), the daemon-side
3308
+ // marks (control endpoint + in-page bindings, already assertion-annotated),
3309
+ // and the [auto] instrumentation marks.
3310
+ const fileMarks = [];
3311
+ let assertUnverified = 0;
2362
3312
  try {
2363
3313
  for (const line of readFileSync(state.marksPath, "utf8").split("\n")) {
2364
3314
  if (!line.trim())
2365
3315
  continue;
2366
3316
  const m = JSON.parse(line);
2367
- if (typeof m.tMs === "number" && typeof m.text === "string" && m.text.trim()) {
2368
- agentMarks.push({ startMs: Math.max(0, Math.round(m.tMs)), text: m.text.trim() });
2369
- }
3317
+ if (typeof m.tMs !== "number" || typeof m.text !== "string" || !m.text.trim())
3318
+ continue;
3319
+ // Dedup: the daemon already processed this mark over HTTP (the client's
3320
+ // control call timed out, but the daemon completed it) — keep the daemon's
3321
+ // evaluated copy, drop this file duplicate.
3322
+ if (m.id && processedMarkIds.has(m.id))
3323
+ continue;
3324
+ fileMarks.push({ startMs: Math.max(0, Math.round(m.tMs)), text: m.text.trim() });
3325
+ if (m.unverified)
3326
+ assertUnverified++; // ⚠ marks the CLI recorded but couldn't verify
2370
3327
  }
2371
3328
  }
2372
3329
  catch {
2373
3330
  // no marks file — fine
2374
3331
  }
2375
- const notes = [...agentMarks, ...autoMarks].sort((a, b) => a.startMs - b.startMs);
3332
+ let notes = [...fileMarks, ...daemonMarks, ...autoMarks].sort((a, b) => a.startMs - b.startMs);
3333
+ // If any assertion was ATTEMPTED (evaluated pass/fail OR recorded ⚠-unverified),
3334
+ // prepend a 0ms verification summary so it LEADS the transcript (a stable sort
3335
+ // keeps it ahead of other 0ms marks). The K-unverified clause is omitted when
3336
+ // K=0 so existing renderings don't churn.
3337
+ const assertN = assertPassed + assertFailed + assertUnverified;
3338
+ if (assertN > 0) {
3339
+ const tally = `${assertN} assertion(s): ${assertPassed} passed, ${assertFailed} failed` +
3340
+ (assertUnverified > 0 ? `, ${assertUnverified} unverified` : "");
3341
+ notes.unshift({ startMs: 0, text: `[verification] ${tally}` });
3342
+ notes.sort((a, b) => a.startMs - b.startMs);
3343
+ }
3344
+ // Server limit: cap the merged set at 200 marks (the verification note sorts
3345
+ // to 0ms so it always survives the slice).
3346
+ if (notes.length > 200) {
3347
+ log(`mark limit: merged ${notes.length} marks — keeping the first 200 (dropped ${notes.length - 200})`);
3348
+ notes = notes.slice(0, 200);
3349
+ }
2376
3350
  save({ state: "uploading" });
2377
3351
  const uploaded = await uploadWebmToClipy(ctx, {
2378
3352
  videoPath,
@@ -2408,6 +3382,13 @@ async function runSessionDaemon(file) {
2408
3382
  process.exitCode = 1;
2409
3383
  }
2410
3384
  finally {
3385
+ if (controlServer)
3386
+ controlServer.close();
3387
+ // Persistent (--user-data-dir) contexts have no separate browser, so an
3388
+ // exception before the stop/abort path must close the context to avoid
3389
+ // leaking Chromium. Both closes are no-ops if the object is already closed.
3390
+ if (ctxToClose)
3391
+ await ctxToClose.close().catch(() => { });
2411
3392
  if (browser)
2412
3393
  await browser.close().catch(() => { });
2413
3394
  }
@@ -2501,7 +3482,7 @@ async function cmdAgents(ctx, sub, targetRaw, json) {
2501
3482
  // command's shape without trial-and-error. Bump GUIDE_SCHEMA_VERSION when the
2502
3483
  // contract changes.
2503
3484
  // ---------------------------------------------------------------------------
2504
- const GUIDE_SCHEMA_VERSION = 3;
3485
+ const GUIDE_SCHEMA_VERSION = 6;
2505
3486
  function cmdGuide(json) {
2506
3487
  if (!json) {
2507
3488
  process.stdout.write(HELP);
@@ -2529,6 +3510,7 @@ function cmdGuide(json) {
2529
3510
  { name: "CLIPY_API_KEY", description: "API key (clipy_sk_live_…) from clipy.online/settings/api-keys; write commands need the 'ingest' scope" },
2530
3511
  { name: "CLIPY_API_URL", description: "API base URL override (default https://clipy.online)" },
2531
3512
  { name: "CLIPY_DISABLE_CDP", description: "set to 1 to force session --expose-cdp off (a hard kill switch that wins over the flag)" },
3513
+ { name: "CLIPY_SESSION_FILE", description: "path to a session state file that mark/chapter/session stop|abort|status resolve FIRST (before the cwd hash). `session run` exports it to the child so a driver can mark from any cwd." },
2532
3514
  { name: "NO_COLOR", description: "disable ANSI color" },
2533
3515
  ],
2534
3516
  exitCodes: [
@@ -2551,10 +3533,12 @@ function cmdGuide(json) {
2551
3533
  cmdDoc("download", "clipy download <id> [-o path]", "Download the MP4"),
2552
3534
  cmdDoc("open", "clipy open <id>", "Open the share page in a browser"),
2553
3535
  cmdDoc("wait", "clipy wait <id> [--for transcript|summary|both] [--timeout sec]", "Block until artifacts are ready"),
2554
- cmdDoc("record", "clipy record --url <url> [--for sec] [--viewports list] [--title t] [--type kind] [--note '12: text']… [--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. With --source mac-screen: records the real screen via the Clipy Mac app (--type not yet applied on mac); --window '<title|app|id>' or --display <id> target one window/display (ids from clipy sources)", ["--for", "--viewports", "--title", "--description", "--type", "--note", "--width", "--height", "--wait", "--source", "--window", "--display"]),
2555
- cmdDoc("session", "clipy session <start|stop|abort|status> [--url <url>] [--max sec] [--type kind] [--source web|mac-screen] [--window w] [--display d] [--expose-cdp]", "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", ["--url", "--max", "--type", "--source", "--window", "--display", "--expose-cdp"]),
2556
- cmdDoc("mark", "clipy mark \"<text>\"", "Drop a live-timestamped note into the active session"),
2557
- 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 where it resolved from), and install mode (npx/global/local) — each a pass/warn/fail with a fix hint; exits non-zero if any check fails"),
3536
+ cmdDoc("record", "clipy record --url <url> [--for sec] [--viewports list] [--title t] [--type kind] [--note '12: text']… [--storage-state f] [--cookie 'n=v']… [--local-storage 'k=v']… [--init-script f] [--wait] [--json]", "Headless one-shot capture of a web app; notes become the transcript. Notes are absolute ('12: text') or pass-scoped ('pass2: text' / 'pass2@5: text', anchored to a --viewports pass's real start; a malformed pass note is rejected). --type declares the recording kind (bug_report|feature_request|product_demo|walkthrough_tutorial|feedback_review|discussion_talk|other, plus aliases bug/feature/demo/walkthrough/feedback/discussion) so the AI summary reads it correctly. Auth (web capture only, applied before the first navigation so a logged-in SPA's route guard sees it): --storage-state <playwright storageState JSON path>, --cookie 'name=value[; Domain=d; Path=p; Secure; HttpOnly; SameSite=Lax]' (repeatable), --local-storage 'key=value' (repeatable, target origin only), --init-script <js file run before every page load>, --user-data-dir <dir> (launch a persistent Chromium profile with its whole logged-in identity; web only, mutually exclusive with --storage-state, refused if the dir looks like a live/locked Chrome profile via a SingletonLock/Socket). Auth boundary: --storage-state only seeds what the file contains; for cross-origin auth produce it with `npx playwright open --save-storage=auth.json <login-host>`, or use --user-data-dir, or --source mac-screen --window Chrome. 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", "--user-data-dir", "--width", "--height", "--wait", "--source", "--window", "--display", "--json"]),
3537
+ 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/--user-data-dir/--cookie/--local-storage/--init-script; web only, rejected on --source mac-screen). `session run` exports CLIPY_SESSION_FILE to the child so mark/chapter resolve the session from any cwd. --json is supported on start/stop/status (start returns cdpUrl/cdpHttpUrl)", ["run", "--url", "--max", "--type", "--source", "--window", "--display", "--expose-cdp", "--storage-state", "--user-data-dir", "--cookie", "--local-storage", "--init-script", "--json"]),
3538
+ 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"]),
3539
+ 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"]),
3540
+ 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"]),
3541
+ 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"]),
2558
3542
  cmdDoc("sources", "clipy sources [--json]", "List displays + windows the Clipy Mac app can capture — ids feed --window/--display"),
2559
3543
  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)"),
2560
3544
  cmdDoc("guide", "clipy guide --json", "This manifest"),
@@ -2567,7 +3551,14 @@ function cmdGuide(json) {
2567
3551
  "Headless captures have no audio: --note flags and session marks become the transcript, labeled agent-narration.",
2568
3552
  "--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.",
2569
3553
  "--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.",
3554
+ "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.",
3555
+ "A mark is NEVER dropped. If the daemon can't be reached to evaluate an assertion (its event loop briefly starved during a dev-server recompile), `clipy mark` records the narration anyway tagged '[ASSERT ⚠ could not evaluate — <reason>]', prints a loud ⚠, and exits 0 — an unverified claim is flagged, never promoted to a ✓. The tally's third bucket counts these: '[verification] N assertion(s): P passed, F failed, K unverified' (the ', K unverified' clause is omitted when K=0). Every mark carries a client id so a slow-but-not-gone daemon that later processes the same mark dedups the two — the evaluated copy wins and the mark appears exactly once.",
3556
+ "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.",
3557
+ "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.",
3558
+ "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, opts?) / window.__clipyChapter(label) IN-PAGE (page.evaluate) to emit marks/chapters with zero spawn latency, evaluated daemon-side with the page in hand. __clipyMark's opts {assertSelector, assertText, assertUrl, failMode} run the SAME assertions as the CLI flags (assertText requires assertSelector or the call rejects; failMode 'abort' discards the session); it returns the annotated {tMs, text, assert}. While CDP is exposed the page's own scripts can call these too (within the existing --expose-cdp trust model).",
2570
3559
  "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.",
3560
+ "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.",
3561
+ "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.",
2571
3562
  "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.",
2572
3563
  "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).",
2573
3564
  "Public recordings have an unauthenticated context document at https://clipy.online/video/<id>.md.",
@@ -2621,9 +3612,24 @@ async function cmdTranscriptReplace(ctx, id, file) {
2621
3612
  // ---------------------------------------------------------------------------
2622
3613
  // Entry
2623
3614
  // ---------------------------------------------------------------------------
3615
+ /** Parse a --at/--ago seconds value (fractional allowed, must be ≥ 0). */
3616
+ function parseSeconds(v, flag) {
3617
+ const n = Number(v);
3618
+ if (!Number.isFinite(n) || n < 0)
3619
+ die(`${flag} must be a non-negative number of seconds`, 2);
3620
+ return n;
3621
+ }
2624
3622
  async function main() {
3623
+ // Split on the first `--` ourselves so `session run … -- <cmd> [--child-flags]`
3624
+ // never feeds the child's own flags to parseArgs (strict:false would otherwise
3625
+ // fold them into `values`). Everything after `--` is the child command verbatim;
3626
+ // for every other command childArgv is simply unused.
3627
+ const rawArgv = process.argv.slice(2);
3628
+ const ddIndex = rawArgv.indexOf("--");
3629
+ const childArgv = ddIndex >= 0 ? rawArgv.slice(ddIndex + 1) : [];
3630
+ const parseArgv = ddIndex >= 0 ? rawArgv.slice(0, ddIndex) : rawArgv;
2625
3631
  const { values, positionals } = parseArgs({
2626
- args: process.argv.slice(2),
3632
+ args: parseArgv,
2627
3633
  allowPositionals: true,
2628
3634
  strict: false,
2629
3635
  options: {
@@ -2653,7 +3659,18 @@ async function main() {
2653
3659
  window: { type: "string" },
2654
3660
  display: { type: "string" },
2655
3661
  type: { type: "string" },
3662
+ "assert-selector": { type: "string" },
3663
+ "assert-text": { type: "string" },
3664
+ "assert-url": { type: "string" },
3665
+ "fail-mode": { type: "string" },
3666
+ at: { type: "string" },
3667
+ ago: { type: "string" },
2656
3668
  "expose-cdp": { type: "boolean", default: false },
3669
+ "storage-state": { type: "string" },
3670
+ "user-data-dir": { type: "string" },
3671
+ "init-script": { type: "string" },
3672
+ cookie: { type: "string", multiple: true },
3673
+ "local-storage": { type: "string", multiple: true },
2657
3674
  width: { type: "string" },
2658
3675
  height: { type: "string" },
2659
3676
  wait: { type: "boolean", default: false },
@@ -2685,6 +3702,33 @@ async function main() {
2685
3702
  const n = parseInt(String(v ?? ""), 10);
2686
3703
  return Number.isFinite(n) && n > 0 ? n : dflt;
2687
3704
  };
3705
+ // Auth-capture flags seed a logged-in session into headless web capture; they
3706
+ // don't apply to --source mac-screen (which records the real, already-signed-in
3707
+ // screen). Resolve the file paths to absolute so the detached daemon — spawned
3708
+ // without an explicit cwd — reads the same files the parent validated.
3709
+ const authFlagsPresent = Boolean(values["storage-state"] ||
3710
+ values["user-data-dir"] ||
3711
+ values["init-script"] ||
3712
+ values.cookie?.length ||
3713
+ values["local-storage"]?.length);
3714
+ const authCapture = () => ({
3715
+ storageStatePath: values["storage-state"] ? resolve(String(values["storage-state"])) : undefined,
3716
+ initScriptPath: values["init-script"] ? resolve(String(values["init-script"])) : undefined,
3717
+ cookieSpecs: values.cookie ?? [],
3718
+ localStorageSpecs: values["local-storage"] ?? [],
3719
+ });
3720
+ // --user-data-dir launches a persistent profile context (web only). Resolved to
3721
+ // absolute so the detached daemon (no explicit cwd) opens the same dir. It's
3722
+ // mutually exclusive with --storage-state — die(2) when both are set.
3723
+ const userDataDir = () => {
3724
+ if (!values["user-data-dir"])
3725
+ return undefined;
3726
+ if (values["storage-state"]) {
3727
+ die("--user-data-dir and --storage-state are mutually exclusive — a persistent profile already carries its own storage; pick one", 2);
3728
+ }
3729
+ return resolve(String(values["user-data-dir"]));
3730
+ };
3731
+ const macAuthGuard = "auth state (--storage-state/--user-data-dir/--cookie/--local-storage/--init-script) applies to headless web capture — --source mac-screen records the real, already-logged-in screen";
2688
3732
  switch (command) {
2689
3733
  case "login":
2690
3734
  await cmdLogin(ctx, {
@@ -2772,6 +3816,9 @@ async function main() {
2772
3816
  case "doctor":
2773
3817
  await cmdDoctor(ctx, json);
2774
3818
  return;
3819
+ case "playwright-path":
3820
+ await cmdPlaywrightPath(json);
3821
+ return;
2775
3822
  case "agents":
2776
3823
  await cmdAgents(ctx, rest[0], rest[1], json);
2777
3824
  return;
@@ -2812,6 +3859,8 @@ async function main() {
2812
3859
  if (values.window && values.display) {
2813
3860
  die("--window and --display are mutually exclusive — pick one capture source", 2);
2814
3861
  }
3862
+ if (source === "mac-screen" && authFlagsPresent)
3863
+ die(macAuthGuard, 2);
2815
3864
  const recordingKind = values.type ? requireRecordingKind(String(values.type)) : undefined;
2816
3865
  if (source === "mac-screen") {
2817
3866
  const noteFlags = values.note ?? [];
@@ -2867,12 +3916,17 @@ async function main() {
2867
3916
  height: num(values.height, 720),
2868
3917
  wait: Boolean(values.wait),
2869
3918
  json,
3919
+ auth: authCapture(),
3920
+ userDataDir: userDataDir(),
2870
3921
  });
2871
3922
  return;
2872
3923
  }
2873
3924
  case "session": {
2874
3925
  const sub = rest[0];
2875
- if (sub === "start") {
3926
+ // Shared by `start` and `run`: validate the capture flags and build the
3927
+ // cmdSessionStart opts. `positionalUrl` is rest[1] for `start` (session
3928
+ // start <url>) — `run` has no positional url, only --url.
3929
+ const buildStartOpts = (positionalUrl) => {
2876
3930
  const source = String(values.source ?? "web");
2877
3931
  if (source !== "web" && source !== "mac-screen") {
2878
3932
  die("--source must be web (headless browser) or mac-screen (the Clipy Mac app)", 2);
@@ -2883,11 +3937,13 @@ async function main() {
2883
3937
  if (values.window && values.display) {
2884
3938
  die("--window and --display are mutually exclusive — pick one capture source", 2);
2885
3939
  }
2886
- const url = values.url?.trim() || rest[1];
3940
+ if (source === "mac-screen" && authFlagsPresent)
3941
+ die(macAuthGuard, 2);
3942
+ const url = values.url?.trim() || positionalUrl;
2887
3943
  if (!url && source === "web") {
2888
3944
  die("usage: clipy session start --url <http(s) url> [--max <sec>] [--source web|mac-screen]", 2);
2889
3945
  }
2890
- await cmdSessionStart(ctx, {
3946
+ return {
2891
3947
  url: url || "mac-screen",
2892
3948
  window: values.window?.trim() || undefined,
2893
3949
  display: values.display?.trim() || undefined,
@@ -2899,9 +3955,19 @@ async function main() {
2899
3955
  width: num(values.width, 1280),
2900
3956
  height: num(values.height, 720),
2901
3957
  json,
2902
- source,
3958
+ source: source,
2903
3959
  exposeCdp: Boolean(values["expose-cdp"]),
2904
- });
3960
+ auth: authCapture(),
3961
+ userDataDir: userDataDir(),
3962
+ };
3963
+ };
3964
+ if (sub === "start") {
3965
+ await cmdSessionStart(ctx, buildStartOpts(rest[1]));
3966
+ return;
3967
+ }
3968
+ if (sub === "run") {
3969
+ // Everything after `--` is the command; start flags come before it.
3970
+ await cmdSessionRun(ctx, buildStartOpts(undefined), childArgv);
2905
3971
  return;
2906
3972
  }
2907
3973
  if (sub === "stop") {
@@ -2916,14 +3982,47 @@ async function main() {
2916
3982
  await cmdSessionStatus(json);
2917
3983
  return;
2918
3984
  }
2919
- die("usage: clipy session <start|stop|abort|status>", 2);
3985
+ die("usage: clipy session <start|run|stop|abort|status>", 2);
2920
3986
  return;
2921
3987
  }
2922
3988
  case "mark": {
2923
3989
  const text = rest.join(" ").trim();
2924
- if (!text)
2925
- die('usage: clipy mark "<what just happened>"', 2);
2926
- await cmdMark(text, json);
3990
+ if (!text) {
3991
+ 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);
3992
+ }
3993
+ const selector = values["assert-selector"]?.trim() || undefined;
3994
+ const expectText = values["assert-text"]; // exact, not trimmed
3995
+ const urlGlob = values["assert-url"]?.trim() || undefined;
3996
+ if (expectText != null && !selector) {
3997
+ die("--assert-text needs --assert-selector (the substring is checked against that element's text)", 2);
3998
+ }
3999
+ const failModeRaw = values["fail-mode"]?.trim().toLowerCase();
4000
+ if (failModeRaw && failModeRaw !== "warn" && failModeRaw !== "abort") {
4001
+ die("--fail-mode must be warn or abort", 2);
4002
+ }
4003
+ const hasAssert = Boolean(selector || (expectText != null && expectText !== "") || urlGlob);
4004
+ if (failModeRaw && !hasAssert) {
4005
+ die("--fail-mode only applies with an assertion (--assert-selector / --assert-text / --assert-url)", 2);
4006
+ }
4007
+ if (values.at != null && values.ago != null)
4008
+ die("--at and --ago are mutually exclusive", 2);
4009
+ const atSec = values.at != null ? parseSeconds(String(values.at), "--at") : undefined;
4010
+ const agoSec = values.ago != null ? parseSeconds(String(values.ago), "--ago") : undefined;
4011
+ await cmdMark(text, json, {
4012
+ atSec,
4013
+ agoSec,
4014
+ assert: hasAssert
4015
+ ? { selector, expectText, urlGlob, failMode: failModeRaw || "warn" }
4016
+ : undefined,
4017
+ });
4018
+ return;
4019
+ }
4020
+ case "chapter": {
4021
+ const label = rest.join(" ").trim();
4022
+ if (!label) {
4023
+ die('usage: clipy chapter "<label>" e.g. clipy chapter "AFTER — fix applied"', 2);
4024
+ }
4025
+ await cmdChapter(label, json);
2927
4026
  return;
2928
4027
  }
2929
4028
  case "__session-daemon": {