@clipy/cli 0.8.2 → 0.8.4

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.js CHANGED
@@ -13,9 +13,9 @@
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, existsSync, mkdirSync, openSync, readFileSync, readSync, realpathSync, renameSync, rmSync, statSync, writeFileSync, chmodSync } from "node:fs";
16
+ import { appendFileSync, closeSync, cpSync, createWriteStream, existsSync, mkdirSync, openSync, readdirSync, readFileSync, readSync, realpathSync, renameSync, rmSync, statSync, writeFileSync, chmodSync } from "node:fs";
17
17
  import { homedir, tmpdir } from "node:os";
18
- import { dirname, join, resolve } from "node:path";
18
+ import { basename, dirname, join, resolve } from "node:path";
19
19
  import { createInterface } from "node:readline";
20
20
  import { spawn } from "node:child_process";
21
21
  import { createHash, randomUUID } from "node:crypto";
@@ -285,8 +285,11 @@ ${c.bold("RECORDINGS")}
285
285
  List your recordings (newest first)
286
286
  search <query> [--json] Full-text search titles + descriptions
287
287
  show <id|url> [--json] One recording's metadata + share link
288
- transcript <id> [--srt|--vtt|--json]
289
- Print the transcript (plaintext by default)
288
+ transcript <id> [--marks-only] [--srt|--vtt|--json]
289
+ Print the transcript — one entry per line,
290
+ timestamp-prefixed. --marks-only drops [auto]
291
+ instrumentation lines (navigations, console
292
+ errors), leaving the narration you wrote
290
293
  summary <id> [--json] AI summary: TL;DR, key points, action items
291
294
  moments <id> [--json] Key moments (timestamps + captions + click coords)
292
295
  context <id> Full agent-context bundle as markdown
@@ -321,9 +324,12 @@ ${c.bold("RECORD")} ${c.dim("(needs an API key with the \"ingest\" permission)")
321
324
  --cookie "n=v[; Domain=d; Path=p; Secure; HttpOnly; SameSite=Lax]" (repeatable)
322
325
  --local-storage "k=v" Seed a localStorage pair for the target origin (repeatable)
323
326
  --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
327
+ --user-data-dir <d> Launch from a persistent Chromium user-data ROOT (its
328
+ whole logged-in identity). Excl. with --storage-state;
329
+ pass the root, not a profile subdir
330
+ --profile-directory <name> With --user-data-dir: pick a named profile
331
+ (e.g. "Profile 12"). Clipy copies it to a temp root and
332
+ records the copy — real profile untouched, deleted after
327
333
 
328
334
  ${c.bold("SESSION")} ${c.dim("(agent works, Clipy records — one active session per directory)")}
329
335
  ${c.dim("--source mac-screen on record/session records the REAL screen via the")}
@@ -351,8 +357,15 @@ ${c.bold("SESSION")} ${c.dim("(agent works, Clipy records — one active session
351
357
  CLIPY_CDP_URL with --expose-cdp). Crash-safe
352
358
  wrapper for driver scripts — no dead-air uploads.
353
359
  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)
360
+ recording's transcript. Attach evidence — one
361
+ provenance per mark, never pooled:
362
+ --observed "<values>" --verdict pass|fail
363
+ DRIVER-ATTESTED: you drove the browser and report
364
+ what you saw (works in every session type, incl.
365
+ --source mac-screen). Clipy vouches you SAID it,
366
+ not that Clipy verified it — put real values here
367
+ --assert-selector <css> CLIPY-VERIFIED (Clipy-owned page only): assert an
368
+ element exists (observed text recorded)
356
369
  --assert-text <substr> require that element's text to contain <substr>
357
370
  --assert-url <glob> assert the page URL matches (**/* wildcards)
358
371
  --fail-mode warn|abort warn (default) annotates ASSERT ✗; abort
@@ -581,7 +594,7 @@ async function cmdShow(ctx, id, json) {
581
594
  for (const [k, v] of kv)
582
595
  process.stdout.write(`${c.dim(k.padEnd(w))} ${v}\n`);
583
596
  }
584
- async function cmdTranscript(ctx, id, fmt) {
597
+ async function cmdTranscript(ctx, id, fmt, marksOnly = false) {
585
598
  const pid = encodeURIComponent(normalizeId(id, ctx));
586
599
  const body = await apiJson(ctx, `/api/v1/recordings/${pid}/transcript`);
587
600
  const status = String(body.status ?? "unknown");
@@ -598,7 +611,29 @@ async function cmdTranscript(ctx, id, fmt) {
598
611
  // The ready payload nests under `transcript`; accept top-level too.
599
612
  const t = (body.transcript ?? body);
600
613
  if (fmt === "text") {
601
- process.stdout.write(`${String(t.plaintext ?? "")}\n`);
614
+ // One entry per line, timestamp-prefixed, chronological — from the same
615
+ // `segments` the --srt/--vtt paths use. An agent-narration transcript is a
616
+ // list of discrete marks/[auto] entries, and concatenating them into one
617
+ // run-on paragraph made it unreadable without piping through sed. Timestamped
618
+ // lines are also how every transcript UI renders speech, so this is the
619
+ // default for both kinds; `--json` still carries the raw `plaintext` for any
620
+ // script that wants the old shape, and a transcript with no segments (or a
621
+ // plaintext-only replacement) falls back to it.
622
+ const segments = (t.segments ?? []);
623
+ if (!segments.length) {
624
+ process.stdout.write(`${String(t.plaintext ?? "")}\n`);
625
+ return;
626
+ }
627
+ const lines = segments
628
+ .map((s) => ({ start: Number(s.start) || 0, text: String(s.text ?? "").trim() }))
629
+ .filter((s) => s.text)
630
+ // --marks-only drops [auto] instrumentation (navigations, console errors),
631
+ // leaving the narration a human actually wrote.
632
+ .filter((s) => !(marksOnly && s.text.startsWith("[auto]")))
633
+ // FLOOR, never round: a transcript timestamp is a seek target, so it must
634
+ // never point past the entry it labels (2.5s must read 0:02, not 0:03).
635
+ .map((s) => `${c.dim(fmtDuration(Math.floor(s.start)).padStart(7))} ${s.text}`);
636
+ process.stdout.write(lines.length ? `${lines.join("\n")}\n` : "");
602
637
  return;
603
638
  }
604
639
  const segments = (t.segments ?? []);
@@ -1758,12 +1793,13 @@ async function applyAuthCapture(context, auth, targetUrl) {
1758
1793
  if (auth.initScriptPath)
1759
1794
  await context.addInitScript({ path: auth.initScriptPath });
1760
1795
  }
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) {
1796
+ /** Validate a --user-data-dir before launch. It must exist, must be a user-data
1797
+ * ROOT (not a Chrome PROFILE subdir — Chromium would silently mint a blank
1798
+ * logged-out Default inside it), and, in direct-open mode (no --profile-directory),
1799
+ * must not be a profile a live Chrome is holding open. With a profileName the
1800
+ * named subdir must exist; the live-lock is handled by the copy path (a warn),
1801
+ * not a refusal, since we never open the real root. die(2) on any miss. */
1802
+ function validateUserDataDir(dir, profileName) {
1767
1803
  let st;
1768
1804
  try {
1769
1805
  st = statSync(dir);
@@ -1773,12 +1809,187 @@ function validateUserDataDir(dir) {
1773
1809
  }
1774
1810
  if (!st.isDirectory())
1775
1811
  die(`--user-data-dir is not a directory: ${dir}`, 2);
1812
+ // Reject a Chrome PROFILE directory passed as the root. Chrome stores profiles
1813
+ // as subdirs (Default, Profile 1, …) of the user-data ROOT (which holds
1814
+ // 'Local State'); pointing --user-data-dir at a profile makes Chromium treat it
1815
+ // as a root and create a blank Default inside the real profile.
1816
+ const base = basename(dir);
1817
+ const looksLikeProfileName = /^(Default|Profile \d+)$/.test(base);
1818
+ const hasProfileFiles = existsSync(join(dir, "Preferences")) ||
1819
+ existsSync(join(dir, "Cookies")) ||
1820
+ existsSync(join(dir, "History"));
1821
+ if (looksLikeProfileName || (hasProfileFiles && !existsSync(join(dir, "Local State")))) {
1822
+ die(`--user-data-dir looks like a Chrome PROFILE directory, not a user-data root: ${dir}\n` +
1823
+ `Pass the PARENT directory (the one containing 'Local State') plus --profile-directory '${looksLikeProfileName ? base : "<name>"}'.`, 2);
1824
+ }
1825
+ if (profileName != null) {
1826
+ // Copy mode: the named profile subdir must exist inside the root.
1827
+ if (!existsSync(join(dir, profileName))) {
1828
+ const profiles = (() => {
1829
+ try {
1830
+ return readdirSync(dir, { withFileTypes: true })
1831
+ .filter((e) => e.isDirectory() && /^(Default|Profile \d+)$/.test(e.name))
1832
+ .map((e) => e.name);
1833
+ }
1834
+ catch {
1835
+ return [];
1836
+ }
1837
+ })();
1838
+ die(`--profile-directory '${profileName}' not found under ${dir}` +
1839
+ (profiles.length ? ` (available: ${profiles.join(", ")})` : "") +
1840
+ `\nFind the exact folder name at chrome://version → "Profile Path".`, 2);
1841
+ }
1842
+ return; // the copy path handles a running Chrome (a warn), never opens the root
1843
+ }
1844
+ // Direct-open mode: refuse a profile a live Chrome is holding open.
1776
1845
  for (const lock of ["SingletonLock", "SingletonSocket"]) {
1777
1846
  if (existsSync(join(dir, lock))) {
1778
1847
  die(`--user-data-dir looks like a live/locked Chrome profile (${lock} present): ${dir}\n` +
1779
1848
  `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
1849
  }
1781
1850
  }
1851
+ // A bare --user-data-dir at a REAL Chrome installation opens its Default profile
1852
+ // IN PLACE — the recording browser can write to it. Warn (don't refuse: a quit
1853
+ // Chrome is a legitimate, if lossy, way to record). Scratch/dedicated roots have
1854
+ // no Local State + Default/Preferences pair and stay silent.
1855
+ if (existsSync(join(dir, "Local State")) && existsSync(join(dir, "Default", "Preferences"))) {
1856
+ process.stderr.write(`${c.yellow("warning:")} this opens your real Chrome Default profile in place — the recording browser can write to it; ` +
1857
+ `prefer --profile-directory '<name>' (records an ephemeral copy, original untouched) or --source mac-screen\n`);
1858
+ }
1859
+ }
1860
+ // --- --profile-directory: copy a named Chrome profile into a scratch root ----
1861
+ // Playwright's launchPersistentContext ignores --profile-directory (verified: the
1862
+ // switch is stripped and Default is always loaded), so selecting a named profile
1863
+ // means making it the Default of the root we open. We COPY <root>/<name> into a
1864
+ // temp scratch root's Default/ (+ the root's 'Local State') and launch against
1865
+ // that. The user's real profile is never opened or written. LOUD by design — this
1866
+ // whole track exists because silent profile substitution is the enemy.
1867
+ const PROFILE_COPY_PREFIX = "clipy-profile-";
1868
+ // Bulk cache dirs — identity lives in Cookies / Login Data / Local Storage /
1869
+ // Preferences, so we skip these to keep the copy small.
1870
+ const PROFILE_SKIP_TOP = new Set(["Cache", "Code Cache", "GPUCache"]);
1871
+ const SW_CACHE_FRAGMENT = join("Service Worker", "CacheStorage");
1872
+ /** Bytes we'll actually copy (identity, minus the skipped cache dirs). */
1873
+ function profileCopyableSize(profileDir) {
1874
+ let total = 0;
1875
+ const walk = (p, top) => {
1876
+ let entries;
1877
+ try {
1878
+ entries = readdirSync(p, { withFileTypes: true });
1879
+ }
1880
+ catch {
1881
+ return;
1882
+ }
1883
+ for (const e of entries) {
1884
+ if (top && (e.name.startsWith("Singleton") || PROFILE_SKIP_TOP.has(e.name)))
1885
+ continue;
1886
+ const full = join(p, e.name);
1887
+ if (full.includes(SW_CACHE_FRAGMENT))
1888
+ continue;
1889
+ try {
1890
+ if (e.isDirectory())
1891
+ walk(full, false);
1892
+ else
1893
+ total += statSync(full).size;
1894
+ }
1895
+ catch {
1896
+ // unreadable — skip
1897
+ }
1898
+ }
1899
+ };
1900
+ walk(profileDir, true);
1901
+ return total;
1902
+ }
1903
+ /** Copy <userDataDir>/<profileName> into a fresh 0700 scratch root's Default/
1904
+ * (plus the root's 'Local State'), skipping Singleton-locks and cache dirs.
1905
+ * Prints the loud disclosure and a running-Chrome warning. Best-effort per
1906
+ * top-level entry, so a locked file loses only that entry. Returns the scratch
1907
+ * root to launch against. */
1908
+ function copyProfileToScratchRoot(userDataDir, profileName, log) {
1909
+ const srcProfile = join(userDataDir, profileName);
1910
+ if (existsSync(join(userDataDir, "SingletonLock")) || existsSync(join(userDataDir, "SingletonSocket"))) {
1911
+ log(c.yellow("warning: Chrome appears to be running — in-use databases may copy inconsistently; quit Chrome for a guaranteed-clean copy"));
1912
+ }
1913
+ const size = profileCopyableSize(srcProfile);
1914
+ // LOUD, always — the user must know their profile is being copied (never silent).
1915
+ log(`${c.dim("→")} copying profile '${profileName}' (${fmtBytes(size)}) into a temporary recording root — ` +
1916
+ `your real profile is never modified; the copy carries your logged-in identity and is deleted after upload`);
1917
+ // FALSE-IDENTITY GUARD (macOS): Chrome encrypts its cookies with a Keychain key
1918
+ // scoped to "Chrome Safe Storage", but the recorder runs Playwright's Chromium,
1919
+ // which reads "Chromium Safe Storage" — so a copied real-Chrome profile can open
1920
+ // LOOKING like the user (bookmarks, prefs, localStorage) while being silently
1921
+ // signed out. That's the exact class --profile-directory exists to prevent, so it
1922
+ // is a loud warning, never a docs footnote.
1923
+ if (process.platform === "darwin") {
1924
+ log(c.yellow("warning: On macOS, cookie-based logins in a real Chrome profile may not decrypt under the recorder's Chromium " +
1925
+ "(Chrome and Chromium use different Keychain keys) — localStorage/Preferences sessions survive. " +
1926
+ "If the recording lands logged out, that's why: record your real browser with --source mac-screen, " +
1927
+ "or drive your own browser and attach evidence with --observed/--verdict."));
1928
+ }
1929
+ const scratchRoot = join(tmpdir(), `${PROFILE_COPY_PREFIX}${randomUUID()}`);
1930
+ mkdirSync(scratchRoot, { recursive: true });
1931
+ try {
1932
+ chmodSync(scratchRoot, 0o700);
1933
+ }
1934
+ catch {
1935
+ // best-effort on platforms without POSIX modes
1936
+ }
1937
+ const destDefault = join(scratchRoot, "Default");
1938
+ mkdirSync(destDefault, { recursive: true });
1939
+ const skipped = [];
1940
+ for (const entry of readdirSync(srcProfile, { withFileTypes: true })) {
1941
+ const name = entry.name;
1942
+ if (name.startsWith("Singleton") || PROFILE_SKIP_TOP.has(name))
1943
+ continue;
1944
+ try {
1945
+ cpSync(join(srcProfile, name), join(destDefault, name), {
1946
+ recursive: true,
1947
+ // Skip the bulk CacheStorage nested under Service Worker.
1948
+ filter: (s) => !s.includes(SW_CACHE_FRAGMENT),
1949
+ });
1950
+ }
1951
+ catch {
1952
+ skipped.push(name); // locked/unreadable — best-effort
1953
+ }
1954
+ }
1955
+ // 'Local State' lives at the root and carries the os_crypt key Linux uses to
1956
+ // decrypt Cookies/Login Data (harmless elsewhere — macOS keys off the Keychain).
1957
+ try {
1958
+ if (existsSync(join(userDataDir, "Local State"))) {
1959
+ cpSync(join(userDataDir, "Local State"), join(scratchRoot, "Local State"));
1960
+ }
1961
+ }
1962
+ catch {
1963
+ // best-effort
1964
+ }
1965
+ if (skipped.length) {
1966
+ log(c.yellow(`note: skipped ${skipped.length} locked/unreadable profile entr${skipped.length === 1 ? "y" : "ies"} (${skipped.join(", ")})`));
1967
+ }
1968
+ return scratchRoot;
1969
+ }
1970
+ /** Remove stranded profile copies (a SIGKILL between copy and cleanup can leave
1971
+ * one). Swept at the start of every record/session start. Best-effort. */
1972
+ function sweepStaleProfileCopies() {
1973
+ const now = Date.now();
1974
+ let entries;
1975
+ try {
1976
+ entries = readdirSync(tmpdir(), { withFileTypes: true });
1977
+ }
1978
+ catch {
1979
+ return;
1980
+ }
1981
+ for (const e of entries) {
1982
+ if (!e.isDirectory() || !e.name.startsWith(PROFILE_COPY_PREFIX))
1983
+ continue;
1984
+ const full = join(tmpdir(), e.name);
1985
+ try {
1986
+ if (now - statSync(full).mtimeMs > 24 * 3600 * 1000)
1987
+ rmSync(full, { recursive: true, force: true });
1988
+ }
1989
+ catch {
1990
+ // best-effort
1991
+ }
1992
+ }
1782
1993
  }
1783
1994
  /** Launch a recording context. With userDataDir: a PERSISTENT context bound to
1784
1995
  * that dir (launchPersistentContext — it IS the context, there's no separate
@@ -1820,8 +2031,9 @@ async function cmdRecord(ctx, opts) {
1820
2031
  }
1821
2032
  validateAuthCapture(opts.auth, target.href); // usage errors (exit 2) before auth/browser
1822
2033
  if (opts.userDataDir)
1823
- validateUserDataDir(opts.userDataDir);
2034
+ validateUserDataDir(opts.userDataDir, opts.profileDirectory);
1824
2035
  requireKey(ctx); // fail fast before we spin up a browser
2036
+ sweepStaleProfileCopies(); // clear any profile copy a prior SIGKILL stranded
1825
2037
  const chromium = await loadChromium();
1826
2038
  const tmpDir = join(tmpdir(), `clipy-record-${randomUUID()}`);
1827
2039
  mkdirSync(tmpDir, { recursive: true });
@@ -1829,6 +2041,18 @@ async function cmdRecord(ctx, opts) {
1829
2041
  if (!opts.json)
1830
2042
  process.stderr.write(`${m}\n`);
1831
2043
  };
2044
+ // --profile-directory ⇒ copy the named profile into a scratch root's Default and
2045
+ // launch against THAT (Playwright can't select a named profile in-place). The
2046
+ // copy is disclosed loudly and cleaned up in the finally below. Always writes
2047
+ // the disclosure to stderr, even under --json (no silent profile substitution).
2048
+ let profileScratchRoot;
2049
+ const launchUserDataDir = (() => {
2050
+ if (opts.userDataDir && opts.profileDirectory) {
2051
+ profileScratchRoot = copyProfileToScratchRoot(opts.userDataDir, opts.profileDirectory, (m) => process.stderr.write(`${m}\n`));
2052
+ return profileScratchRoot;
2053
+ }
2054
+ return opts.userDataDir;
2055
+ })();
1832
2056
  // Multi-viewport mode records every size sequentially into ONE video; the
1833
2057
  // frame is sized to the largest viewport and smaller passes letterbox
1834
2058
  // inside it. Each pass emits an auto note so the transcript chapters the
@@ -1861,7 +2085,7 @@ async function cmdRecord(ctx, opts) {
1861
2085
  // browser sandbox isn't a trust boundary here. --user-data-dir ⇒ a persistent
1862
2086
  // context (its own browser); else an ephemeral browser + context.
1863
2087
  const { context, browser } = await launchRecordingContext(chromium, {
1864
- userDataDir: opts.userDataDir,
2088
+ userDataDir: launchUserDataDir,
1865
2089
  viewport: frame,
1866
2090
  recordVideoDir: tmpDir,
1867
2091
  args: ["--no-sandbox", "--disable-dev-shm-usage"],
@@ -1954,6 +2178,14 @@ async function cmdRecord(ctx, opts) {
1954
2178
  catch {
1955
2179
  // best-effort temp cleanup
1956
2180
  }
2181
+ if (profileScratchRoot) {
2182
+ try {
2183
+ rmSync(profileScratchRoot, { recursive: true, force: true });
2184
+ }
2185
+ catch {
2186
+ // best-effort — the 24h sweep will catch a stranded copy
2187
+ }
2188
+ }
1957
2189
  }
1958
2190
  if (opts.wait && uploaded.publicId) {
1959
2191
  log(`${c.dim("waiting for transcript…")}`);
@@ -2050,6 +2282,42 @@ function cleanupSessionFiles(state, file) {
2050
2282
  }
2051
2283
  }
2052
2284
  }
2285
+ /** Annotation for a mark Clipy itself evaluated against its own live page. */
2286
+ function verifiedMarkAnnotation(passed, expected, observed) {
2287
+ return passed
2288
+ ? `[assert ✓ verified-by-clipy; ${observed}]`
2289
+ : `[ASSERT ✗ verified-by-clipy; expected ${expected}; observed ${observed}]`;
2290
+ }
2291
+ /** Annotation for a mark the DRIVER attested — Clipy records the claim and the
2292
+ * agent's observed values, and never presents it as its own verification.
2293
+ * TYPOGRAPHIC PROVENANCE: this leads with a HEDGE glyph (≈), never ✓/✗, because
2294
+ * the eye reads shape before text — a skimmed column must yield "verified,
2295
+ * verified, attested, attested" without reading the trailing label. Clipy-verified
2296
+ * marks keep ✓/✗; those are the only marks Clipy itself stands behind. */
2297
+ function attestedMarkAnnotation(verdict, observed) {
2298
+ return `[≈ ${verdict === "pass" ? "ASSERT" : "FAILED"} driver-attested; observed=${observed}]`;
2299
+ }
2300
+ /** The leading [verification] note. The two provenances are SEPARATE segments and
2301
+ * are never pooled: clipy-verified (what Clipy checked against its own page) vs
2302
+ * driver-attested (what the agent reported). With only clipy-verified marks the
2303
+ * rendering stays byte-identical to the pre-0.8.3 single-segment form, so existing
2304
+ * consumers don't churn. Returns [] when nothing was asserted. */
2305
+ function verificationNote(t) {
2306
+ const clipyN = t.clipyPassed + t.clipyFailed + t.clipyUnverified;
2307
+ const driverN = t.driverPassed + t.driverFailed;
2308
+ if (clipyN === 0 && driverN === 0)
2309
+ return [];
2310
+ const clipyBody = `${t.clipyPassed} passed, ${t.clipyFailed} failed` +
2311
+ (t.clipyUnverified > 0 ? `, ${t.clipyUnverified} unverified` : "");
2312
+ if (driverN === 0) {
2313
+ return [{ startMs: 0, text: `[verification] ${clipyN} assertion(s): ${clipyBody}` }];
2314
+ }
2315
+ const segments = [];
2316
+ if (clipyN > 0)
2317
+ segments.push(`${clipyN} clipy-verified: ${clipyBody}`);
2318
+ segments.push(`${driverN} driver-attested: ${t.driverPassed} passed, ${t.driverFailed} failed`);
2319
+ return [{ startMs: 0, text: `[verification] ${segments.join(" · ")}` }];
2320
+ }
2053
2321
  /** Compile a URL glob to a RegExp: `**` → `.*`, a lone `*` → `[^/]*`, every
2054
2322
  * other regex metachar escaped. A glob with NO `*` is treated as a bare
2055
2323
  * substring match (the common "is this path in the URL" case). */
@@ -2307,9 +2575,10 @@ async function cmdSessionStart(ctx, opts) {
2307
2575
  }
2308
2576
  validateAuthCapture(opts.auth, target.href); // usage errors (exit 2) before auth/daemonizing
2309
2577
  if (opts.userDataDir)
2310
- validateUserDataDir(opts.userDataDir);
2578
+ validateUserDataDir(opts.userDataDir, opts.profileDirectory);
2311
2579
  const key = requireKey(ctx);
2312
2580
  await loadChromium(); // fail fast with install instructions before daemonizing
2581
+ sweepStaleProfileCopies();
2313
2582
  const file = sessionFilePath(process.cwd());
2314
2583
  const existing = readSessionState(file);
2315
2584
  if (existing && sessionIsActive(existing)) {
@@ -2318,6 +2587,14 @@ async function cmdSessionStart(ctx, opts) {
2318
2587
  }
2319
2588
  if (existing)
2320
2589
  cleanupSessionFiles(existing, file); // stale (daemon died) — clear
2590
+ // --profile-directory ⇒ copy the named profile into a scratch root HERE, in the
2591
+ // parent, so the user sees the loud disclosure (the daemon's stdout goes to a
2592
+ // log). The daemon launches against the scratch root and removes it at stop/abort;
2593
+ // profileScratchRoot flags it. Disclosure always to stderr, even under --json.
2594
+ let profileScratchRoot;
2595
+ const launchUserDataDir = opts.userDataDir && opts.profileDirectory
2596
+ ? (profileScratchRoot = copyProfileToScratchRoot(opts.userDataDir, opts.profileDirectory, (m) => process.stderr.write(`${m}\n`)))
2597
+ : opts.userDataDir;
2321
2598
  const maxSec = Math.min(Math.max(1, opts.maxSec), SESSION_HARD_CAP_SEC);
2322
2599
  const id = randomUUID();
2323
2600
  const dir = sessionDir();
@@ -2338,7 +2615,8 @@ async function cmdSessionStart(ctx, opts) {
2338
2615
  initScriptPath: opts.auth.initScriptPath,
2339
2616
  cookieSpecs: opts.auth.cookieSpecs.length ? opts.auth.cookieSpecs : undefined,
2340
2617
  localStorageSpecs: opts.auth.localStorageSpecs.length ? opts.auth.localStorageSpecs : undefined,
2341
- userDataDir: opts.userDataDir,
2618
+ userDataDir: launchUserDataDir,
2619
+ profileScratchRoot,
2342
2620
  state: "starting",
2343
2621
  marksPath: join(dir, `marks-${id}.jsonl`),
2344
2622
  controlPath: join(dir, `control-${id}.json`),
@@ -2421,35 +2699,54 @@ function printMarkResult(res, json) {
2421
2699
  }
2422
2700
  const sec = (Number(res.tMs ?? 0) / 1000).toFixed(1);
2423
2701
  const assert = res.assert;
2424
- const glyph = assert && assert.passed === false ? c.red("✗") : c.green("✓");
2702
+ // Same typographic rule as the transcript: an ATTESTED mark leads with the hedge
2703
+ // glyph, never ✓/✗ — the terminal skim must read like the transcript skim.
2704
+ const glyph = assert?.attested
2705
+ ? c.yellow("≈")
2706
+ : assert && assert.passed === false
2707
+ ? c.red("✗")
2708
+ : c.green("✓");
2425
2709
  process.stdout.write(`${glyph} mark @ ${sec}s — ${String(res.text ?? "")}\n`);
2426
2710
  }
2427
2711
  async function cmdMark(text, json, opts) {
2428
2712
  const { file, state } = requireSession();
2429
2713
  const hasAssert = !!opts.assert;
2714
+ const attest = opts.attest;
2430
2715
  const backdated = opts.atSec != null || opts.agoSec != null;
2431
2716
  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.
2717
+ // The Mac app records the real screen — there is no Clipy-owned page to probe,
2718
+ // so Clipy-EVALUATED assertions can't run here. Driver-attested marks CAN: the
2719
+ // agent brings its own observation and Clipy holds the ledger.
2435
2720
  if (hasAssert) {
2436
- die("assertions need a web session — the Mac app records the real screen; there is no page to probe", 2);
2721
+ die("Clipy-evaluated assertions need a Clipy-owned page — use --observed/--verdict to attach evidence you collected yourself", 2);
2437
2722
  }
2438
2723
  if (backdated) {
2439
2724
  die("--at/--ago need a web session — the Mac bridge stamps each mark on its own clock", 2);
2440
2725
  }
2441
- const result = await bridgeRequest(bridgeInfoFromSession(state), "mark", { text }).catch((e) => {
2726
+ // Driver-attested: annotate here (nothing to evaluate) and keep a CLI-side
2727
+ // tally in the session file — there's no daemon to compute one, so
2728
+ // `session stop` emits the [verification] summary as a final bridge mark.
2729
+ const macText = attest ? `${text.trim()} ${attestedMarkAnnotation(attest.verdict, attest.observed)}` : text;
2730
+ const result = await bridgeRequest(bridgeInfoFromSession(state), "mark", { text: macText }).catch((e) => {
2442
2731
  if (e instanceof BridgeUnavailableError) {
2443
2732
  cleanupSessionFiles(state, file);
2444
2733
  die("the Clipy app is no longer running — session cleared. Start a new one.");
2445
2734
  }
2446
2735
  die(e.message);
2447
2736
  });
2737
+ if (attest) {
2738
+ if (attest.verdict === "pass")
2739
+ state.attestedPassed = (state.attestedPassed ?? 0) + 1;
2740
+ else
2741
+ state.attestedFailed = (state.attestedFailed ?? 0) + 1;
2742
+ writeSessionState(file, state);
2743
+ }
2448
2744
  if (json) {
2449
- printJson(result);
2745
+ printJson({ ...result, text: macText, ...(attest ? { assert: { passed: attest.verdict === "pass", observed: attest.observed, attested: true } } : {}) });
2450
2746
  return;
2451
2747
  }
2452
- process.stdout.write(`${c.green("✓")} mark @ ${Number(result.atSeconds ?? 0).toFixed(1)}s — ${text.trim()}\n`);
2748
+ const glyph = attest ? c.yellow("≈") : c.green("✓"); // attested ⇒ hedge, never ✓/✗
2749
+ process.stdout.write(`${glyph} mark @ ${Number(result.atSeconds ?? 0).toFixed(1)}s — ${macText}\n`);
2453
2750
  return;
2454
2751
  }
2455
2752
  if (!pidAlive(state.pid)) {
@@ -2481,16 +2778,25 @@ async function cmdMark(text, json, opts) {
2481
2778
  text: cleanText,
2482
2779
  ...(atMs != null ? { atMs } : {}),
2483
2780
  ...(hasAssert ? { assert: opts.assert } : {}),
2781
+ ...(attest ? { attest } : {}),
2484
2782
  }, CONTROL_TIMEOUT_MS);
2485
2783
  }
2486
2784
  catch (e) {
2487
2785
  const reason = String(e.message).slice(0, 120);
2488
2786
  // 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.
2787
+ // the file regardless. A driver-attested mark needs no evaluation, so the
2788
+ // client annotates it here and it still counts in the driver segment.
2789
+ if (attest) {
2790
+ const annotated = `${cleanText} ${attestedMarkAnnotation(attest.verdict, attest.observed)}`;
2791
+ appendFileSync(state.marksPath, `${JSON.stringify({ id: markId, tMs: localTMs, text: annotated, attested: true, verdict: attest.verdict })}\n`, { mode: 0o600 });
2792
+ printMarkResult({ tMs: localTMs, text: annotated, assert: { passed: attest.verdict === "pass", observed: attest.observed, attested: true } }, json);
2793
+ return;
2794
+ }
2795
+ // For an ASSERTED mark we couldn't verify the claim, so tag it honestly
2796
+ // ⚠ UNVERIFIED (never a silent pass) — the daemon counts {unverified:true}
2797
+ // file marks into the clipy segment's third bucket.
2492
2798
  if (hasAssert) {
2493
- const annotated = `${cleanText} [ASSERT ⚠ could not evaluate — ${reason}]`;
2799
+ const annotated = `${cleanText} [ASSERT ⚠ clipy could not evaluate — ${reason}]`;
2494
2800
  appendFileSync(state.marksPath, `${JSON.stringify({ id: markId, tMs: localTMs, text: annotated, unverified: true })}\n`, { mode: 0o600 });
2495
2801
  if (json) {
2496
2802
  printJson({ tMs: localTMs, text: annotated, assert: { unverified: true, reason } });
@@ -2513,7 +2819,14 @@ async function cmdMark(text, json, opts) {
2513
2819
  printMarkResult(res, json);
2514
2820
  return;
2515
2821
  }
2516
- // No control endpoint (session started by a pre-0.6 CLI): assertions can't run.
2822
+ // No control endpoint (session started by a pre-0.6 CLI): Clipy can't evaluate
2823
+ // anything, but a driver-attested mark needs no evaluation — annotate + record it.
2824
+ if (attest) {
2825
+ const annotated = `${cleanText} ${attestedMarkAnnotation(attest.verdict, attest.observed)}`;
2826
+ appendFileSync(state.marksPath, `${JSON.stringify({ id: markId, tMs: localTMs, text: annotated, attested: true, verdict: attest.verdict })}\n`, { mode: 0o600 });
2827
+ printMarkResult({ tMs: localTMs, text: annotated, assert: { passed: attest.verdict === "pass", observed: attest.observed, attested: true } }, json);
2828
+ return;
2829
+ }
2517
2830
  if (hasAssert) {
2518
2831
  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
2832
  }
@@ -2580,6 +2893,20 @@ async function cmdSessionStop(json) {
2580
2893
  if (state.kind === "mac") {
2581
2894
  if (!json)
2582
2895
  process.stderr.write(`${c.dim("stopping + uploading…")}\n`);
2896
+ // No daemon on the mac path to merge a tally, so emit the [verification]
2897
+ // summary ourselves as a final bridge mark (stamped at stop) BEFORE stopping.
2898
+ const macTally = verificationNote({
2899
+ clipyPassed: 0,
2900
+ clipyFailed: 0,
2901
+ clipyUnverified: 0,
2902
+ driverPassed: state.attestedPassed ?? 0,
2903
+ driverFailed: state.attestedFailed ?? 0,
2904
+ });
2905
+ if (macTally.length) {
2906
+ await bridgeRequest(bridgeInfoFromSession(state), "mark", { text: macTally[0].text }).catch(() => {
2907
+ // best-effort: never block the stop on the summary mark
2908
+ });
2909
+ }
2583
2910
  const result = await bridgeRequest(bridgeInfoFromSession(state), "stop").catch((e) => {
2584
2911
  cleanupSessionFiles(state, file);
2585
2912
  die(e.message);
@@ -3037,16 +3364,23 @@ async function runSessionDaemon(file) {
3037
3364
  let assertOut;
3038
3365
  let assertOutcome;
3039
3366
  let aborted = false;
3040
- if (m.assert && typeof m.assert === "object") {
3367
+ if (m.attest && typeof m.attest === "object") {
3368
+ // DRIVER-ATTESTED: the agent brought its own observation. Clipy evaluates
3369
+ // nothing here — it records the claim + the agent's observed values, labeled
3370
+ // so it can never be read as a Clipy verification.
3371
+ const passed = m.attest.verdict === "pass";
3372
+ annotated = `${text} ${attestedMarkAnnotation(m.attest.verdict, m.attest.observed)}`;
3373
+ assertOut = { passed, observed: m.attest.observed, attested: true };
3374
+ assertOutcome = { kind: "driver", passed, expected: "", observed: m.attest.observed };
3375
+ }
3376
+ else if (m.assert && typeof m.assert === "object") {
3041
3377
  // evaluateAssertion throws if the page is unresponsive — the HTTP path
3042
3378
  // turns that into a 5xx (the CLI then records a ⚠ UNVERIFIED file mark),
3043
3379
  // and the in-page path rejects to the driver.
3044
3380
  const ev = await evaluateAssertion(page, m.assert);
3045
- annotated = ev.passed
3046
- ? `${text} [assert ✓ ${ev.observed}]`
3047
- : `${text} [ASSERT ✗ expected ${ev.expected}; observed ${ev.observed}]`;
3381
+ annotated = `${text} ${verifiedMarkAnnotation(ev.passed, ev.expected, ev.observed)}`;
3048
3382
  assertOut = { passed: ev.passed, observed: ev.observed };
3049
- assertOutcome = { passed: ev.passed, expected: ev.expected, observed: ev.observed };
3383
+ assertOutcome = { kind: "clipy", passed: ev.passed, expected: ev.expected, observed: ev.observed };
3050
3384
  if (!ev.passed && m.assert.failMode === "abort")
3051
3385
  aborted = true;
3052
3386
  // Backdated assertion divergence: a --at/--ago mark is stamped in the past
@@ -3145,6 +3479,7 @@ async function runSessionDaemon(file) {
3145
3479
  text: typeof body.text === "string" ? body.text : "",
3146
3480
  atMs: typeof body.atMs === "number" ? body.atMs : undefined,
3147
3481
  assert: body.assert,
3482
+ attest: body.attest,
3148
3483
  id: typeof body.id === "string" ? body.id : undefined,
3149
3484
  });
3150
3485
  /** POST /chapter → a === CHAPTER === mark at the live clock. Carries its
@@ -3329,7 +3664,11 @@ async function runSessionDaemon(file) {
3329
3664
  const fileMarks = [];
3330
3665
  const unverifiedClaimById = new Map(); // id → claim time (ms)
3331
3666
  const abandonedIds = new Set(); // any id the client wrote to the file
3332
- let assertUnverified = 0; // K
3667
+ let assertUnverified = 0; // K (clipy-verified marks we couldn't evaluate)
3668
+ // Driver-attested marks the client wrote to the file (control endpoint down):
3669
+ // they're already annotated client-side (nothing to evaluate) and still count.
3670
+ let driverPassed = 0;
3671
+ let driverFailed = 0;
3333
3672
  try {
3334
3673
  for (const line of readFileSync(state.marksPath, "utf8").split("\n")) {
3335
3674
  if (!line.trim())
@@ -3339,6 +3678,12 @@ async function runSessionDaemon(file) {
3339
3678
  continue;
3340
3679
  const startMs = Math.max(0, Math.round(m.tMs));
3341
3680
  fileMarks.push({ startMs, text: m.text.trim() }); // the mark of record, verbatim
3681
+ if (m.attested) {
3682
+ if (m.verdict === "pass")
3683
+ driverPassed++;
3684
+ else
3685
+ driverFailed++;
3686
+ }
3342
3687
  if (m.id) {
3343
3688
  abandonedIds.add(m.id);
3344
3689
  if (m.unverified) {
@@ -3382,24 +3727,31 @@ async function runSessionDaemon(file) {
3382
3727
  }
3383
3728
  resolvedDaemon.push({ startMs: dm.startMs, text: dm.text });
3384
3729
  if (dm.assertOutcome) {
3385
- if (dm.assertOutcome.passed)
3386
- assertPassed++;
3387
- else
3388
- assertFailed++;
3730
+ const bump = dm.assertOutcome.passed ? 1 : 0;
3731
+ if (dm.assertOutcome.kind === "driver") {
3732
+ driverPassed += bump;
3733
+ driverFailed += 1 - bump;
3734
+ }
3735
+ else {
3736
+ assertPassed += bump;
3737
+ assertFailed += 1 - bump;
3738
+ }
3389
3739
  }
3390
3740
  }
3391
3741
  let notes = [...fileMarks, ...resolvedDaemon, ...autoMarks].sort((a, b) => a.startMs - b.startMs);
3392
- // If any ORIGINAL assertion was attempted (evaluated pass/fail, or recorded
3393
- // ⚠-unverified), prepend a 0ms verification summary so it LEADS the transcript
3394
- // (a stable sort keeps it ahead of other 0ms marks). The K clause is omitted
3395
- // when K=0 so existing renderings don't churn. Late checks don't count.
3396
- const assertN = assertPassed + assertFailed + assertUnverified;
3397
- if (assertN > 0) {
3398
- const tally = `${assertN} assertion(s): ${assertPassed} passed, ${assertFailed} failed` +
3399
- (assertUnverified > 0 ? `, ${assertUnverified} unverified` : "");
3400
- notes.unshift({ startMs: 0, text: `[verification] ${tally}` });
3401
- notes.sort((a, b) => a.startMs - b.startMs);
3402
- }
3742
+ // If any ORIGINAL assertion was attempted, prepend a 0ms verification summary so
3743
+ // it LEADS the transcript (a stable sort keeps it ahead of other 0ms marks). The
3744
+ // two provenances are reported as SEPARATE segments and never pooled. When only
3745
+ // clipy-verified marks exist the legacy single-segment rendering is byte-identical
3746
+ // (no churn for existing consumers). Late checks count toward neither.
3747
+ notes.unshift(...verificationNote({
3748
+ clipyPassed: assertPassed,
3749
+ clipyFailed: assertFailed,
3750
+ clipyUnverified: assertUnverified,
3751
+ driverPassed,
3752
+ driverFailed,
3753
+ }));
3754
+ notes.sort((a, b) => a.startMs - b.startMs);
3403
3755
  // Server limit: cap the merged set at 200 marks (the verification note sorts
3404
3756
  // to 0ms so it always survives the slice).
3405
3757
  if (notes.length > 200) {
@@ -3450,6 +3802,16 @@ async function runSessionDaemon(file) {
3450
3802
  await ctxToClose.close().catch(() => { });
3451
3803
  if (browser)
3452
3804
  await browser.close().catch(() => { });
3805
+ // Remove the copied-profile scratch root (a SIGKILL strands it → the 24h
3806
+ // sweep at the next record/session start catches that).
3807
+ if (state.profileScratchRoot) {
3808
+ try {
3809
+ rmSync(state.profileScratchRoot, { recursive: true, force: true });
3810
+ }
3811
+ catch {
3812
+ // best-effort
3813
+ }
3814
+ }
3453
3815
  }
3454
3816
  }
3455
3817
  // ---------------------------------------------------------------------------
@@ -3541,7 +3903,7 @@ async function cmdAgents(ctx, sub, targetRaw, json) {
3541
3903
  // command's shape without trial-and-error. Bump GUIDE_SCHEMA_VERSION when the
3542
3904
  // contract changes.
3543
3905
  // ---------------------------------------------------------------------------
3544
- const GUIDE_SCHEMA_VERSION = 7;
3906
+ const GUIDE_SCHEMA_VERSION = 10;
3545
3907
  function cmdGuide(json) {
3546
3908
  if (!json) {
3547
3909
  process.stdout.write(HELP);
@@ -3585,16 +3947,16 @@ function cmdGuide(json) {
3585
3947
  cmdDoc("list", "clipy list [-n N] [--page P] [--status s,…] [--json]", "List recordings, newest first"),
3586
3948
  cmdDoc("search", "clipy search <query> [--json]", "Full-text search titles + descriptions"),
3587
3949
  cmdDoc("show", "clipy show <id|url> [--json]", "One recording's metadata + share link"),
3588
- cmdDoc("transcript", "clipy transcript <id> [--srt|--vtt|--json] | clipy transcript <id> --replace <file.json|-> ", "Print the transcript, or REPLACE it (ingest scope; file holds {segments:[{start,end,text}]} or {plaintext}; regenerates the summary)", ["--srt", "--vtt", "--json", "--replace <file>"]),
3950
+ cmdDoc("transcript", "clipy transcript <id> [--marks-only] [--srt|--vtt|--json] | clipy transcript <id> --replace <file.json|-> ", "Print the transcript, or REPLACE it (ingest scope; file holds {segments:[{start,end,text}]} or {plaintext}; regenerates the summary). Default text output is ONE ENTRY PER LINE, chronological and timestamp-prefixed, from the same segments --srt/--vtt use — an agent-narration transcript is a list of discrete marks, and concatenating them into one run-on paragraph made it unreadable. --marks-only drops [auto] instrumentation lines (navigations, console errors) so only the narration a human wrote remains; it applies to the default text output (--srt/--vtt/--json are unaffected). A transcript with no segments falls back to plaintext, and --json still carries the raw plaintext for scripts that want the old shape.", ["--marks-only", "--srt", "--vtt", "--json", "--replace <file>"]),
3589
3951
  cmdDoc("summary", "clipy summary <id> [--json]", "AI summary: TL;DR, key points, action items"),
3590
3952
  cmdDoc("moments", "clipy moments <id> [--json]", "Key moments: timestamps, captions, click coords"),
3591
3953
  cmdDoc("context", "clipy context <id>", "Full agent-context bundle as markdown"),
3592
3954
  cmdDoc("download", "clipy download <id> [-o path]", "Download the MP4"),
3593
3955
  cmdDoc("open", "clipy open <id>", "Open the share page in a browser"),
3594
3956
  cmdDoc("wait", "clipy wait <id> [--for transcript|summary|both] [--timeout sec]", "Block until artifacts are ready"),
3595
- 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"]),
3596
- 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"]),
3597
- 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"]),
3957
+ cmdDoc("record", "clipy record --url <url> [--for sec] [--viewports list] [--title t] [--type kind] [--note '12: text']… [--storage-state f] [--cookie 'n=v']… [--local-storage 'k=v']… [--init-script f] [--wait] [--json]", "Headless one-shot capture of a web app; notes become the transcript. Notes are absolute ('12: text') or pass-scoped ('pass2: text' / 'pass2@5: text', anchored to a --viewports pass's real start; a malformed pass note is rejected). --type declares the recording kind (bug_report|feature_request|product_demo|walkthrough_tutorial|feedback_review|discussion_talk|other, plus aliases bug/feature/demo/walkthrough/feedback/discussion) so the AI summary reads it correctly. Auth (web capture only, applied before the first navigation so a logged-in SPA's route guard sees it): --storage-state <playwright storageState JSON path>, --cookie 'name=value[; Domain=d; Path=p; Secure; HttpOnly; SameSite=Lax]' (repeatable), --local-storage 'key=value' (repeatable, target origin only), --init-script <js file run before every page load>, --user-data-dir <dir> (launch from a persistent Chromium user-data ROOT with its whole logged-in identity; web only, mutually exclusive with --storage-state; refused if <dir> is a profile subdir — pass the root — or, in direct mode, a live-locked root via SingletonLock/Socket), --profile-directory <name> (with --user-data-dir: pick a NAMED profile like 'Profile 12' from chrome://version; Playwright can't select a profile in place, so Clipy COPIES it into a temp recording root and launches the copy — loudly disclosed, the real profile is never opened or written, and the copy is deleted after upload; no need to quit Chrome, though it warns if Chrome is running since in-use DBs may copy inconsistently). Auth boundary: --storage-state only seeds what the file contains; for cross-origin auth produce it with `npx playwright open --save-storage=auth.json <login-host>`, or use --user-data-dir + --profile-directory to record your real profile, or --source mac-screen --window Chrome. With --source 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", "--profile-directory", "--width", "--height", "--wait", "--source", "--window", "--display", "--json"]),
3958
+ 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/--profile-directory/--cookie/--local-storage/--init-script; web only, rejected on --source mac-screen). `session run` exports CLIPY_SESSION_FILE to the child so mark/chapter resolve the session from any cwd. --json is supported on start/stop/status (start returns cdpUrl/cdpHttpUrl)", ["run", "--url", "--max", "--type", "--source", "--window", "--display", "--expose-cdp", "--storage-state", "--user-data-dir", "--profile-directory", "--cookie", "--local-storage", "--init-script", "--json"]),
3959
+ cmdDoc("mark", "clipy mark \"<text>\" [--observed \"<values>\" --verdict pass|fail] [--assert-selector <css> [--assert-text <substr>]] [--assert-url <glob>] [--fail-mode warn|abort] [--at <sec>|--ago <sec>] [--json]", "Drop a live-timestamped note into the active session. A mark carries at most ONE evidence provenance, and the two are labeled + tallied separately so they can never be pooled. DRIVER-ATTESTED (--observed '<values>' --verdict pass|fail, both required together): you drove the browser and report what YOU observed — renders '<text> [≈ ASSERT driver-attested; observed=<values>]' (pass) / '<text> [≈ FAILED driver-attested; observed=<values>]' (fail) — a HEDGE glyph, never ✓/✗, so a skim distinguishes provenance by shape alone and works in EVERY session type including --source mac-screen. Honesty rule: driver-attested means Clipy vouches the agent SAID it, not that Clipy verified it — put real observed values there. Combining --observed/--verdict with --assert-* is a usage error. CLIPY-VERIFIED assertion marks (Clipy-owned page only) make the note evidence Clipy itself checked: --assert-selector checks a CSS selector matches (its trimmed textContent is recorded as 'observed'); --assert-text requires that element's text to contain a substring (needs --assert-selector); --assert-url matches the page URL against a glob (** = any, * = any non-slash, no * = substring). The daemon evaluates against its live page and annotates the mark: pass ⇒ '<text> [assert ✓ verified-by-clipy; <observed>]', fail ⇒ '<text> [ASSERT ✗ verified-by-clipy; expected …; observed …]' — a false claim cannot read as fact. --fail-mode warn (default) records the ✗; --fail-mode abort DISCARDS the whole session on a failed assertion (no upload) and the CLI exits non-zero. If any assertion was attempted, a leading 0ms [verification] note is prepended, reporting the provenances as SEPARATE segments: '[verification] N clipy-verified: P passed, F failed, K unverified · M driver-attested: P passed, F failed' (a segment is omitted when empty; with only clipy-verified marks the legacy 'N assertion(s): …' rendering is byte-identical). --at <sec> stamps at an absolute recording time; --ago <sec> stamps N seconds before now (mutually exclusive). Assertions/backdating need a web session (rejected on --source mac-screen). Up to 200 marks per recording.", ["--observed", "--verdict", "--assert-selector", "--assert-text", "--assert-url", "--fail-mode", "--at", "--ago", "--json"]),
3598
3960
  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"]),
3599
3961
  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"]),
3600
3962
  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"]),
@@ -3610,14 +3972,16 @@ function cmdGuide(json) {
3610
3972
  "Headless captures have no audio: --note flags and session marks become the transcript, labeled agent-narration.",
3611
3973
  "--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.",
3612
3974
  "--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.",
3975
+ "Clipy is a RECORDER, not a driver. When you drive the browser yourself (the usual agent case), the primary path is: record the real app (--source mac-screen --window '<app>', or your own driven browser) and attach evidence with driver-attested marks — `clipy mark \"<claim>\" --observed \"<values you read>\" --verdict pass|fail` — plus `clipy chapter` for before/after. Clipy holds the ledger; it does not drive. The owned-browser auth flags (--storage-state/--user-data-dir/--profile-directory/--cookie/--local-storage/--init-script) are the AGENTLESS/CI fallback for when nothing is driving and Clipy needs its own logged-in context. Provenance is never pooled: driver-attested marks render '[≈ ASSERT driver-attested; observed=…]' / '[≈ FAILED …]' (hedge glyph) and clipy-evaluated ones '[assert ✓ verified-by-clipy; …]' / '[ASSERT ✗ verified-by-clipy; …]' (✓/✗ are reserved for what Clipy itself checked), and the [verification] note counts them in separate segments. The honesty rule: driver-attested means Clipy vouches the agent SAID it, not that Clipy verified it.",
3613
3976
  "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.",
3614
- "A mark is NEVER dropped, and a late verdict never rewrites it. 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). That ⚠ is the MARK OF RECORD: if the daemon was only slow and evaluates the same claim later, that verdict judged a LATER page state, so it does NOT overwrite the ⚠ — it's recorded as a separate '[late check of \"…\" — evaluated Ns after the claim: …]' note at its own time and counts toward none of P/F/K. Plain non-asserted marks the daemon later processes are just deduped (exactly once).",
3977
+ "A mark is NEVER dropped, and a late verdict never rewrites it. 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 ⚠ clipy 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). That ⚠ is the MARK OF RECORD: if the daemon was only slow and evaluates the same claim later, that verdict judged a LATER page state, so it does NOT overwrite the ⚠ — it's recorded as a separate '[late check of \"…\" — evaluated Ns after the claim: …]' note at its own time and counts toward none of P/F/K. Plain non-asserted marks the daemon later processes are just deduped (exactly once).",
3615
3978
  "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.",
3616
3979
  "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.",
3617
3980
  "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. Backdating an ASSERTED mark: it lands at the backdated time but the assertion judges the LIVE page, so if the verdict was observed >2s from the backdated position the text gains '(assertion observed Ns after this backdated mark — the verdict describes the page at observation time)' and --json carries a signed assert.driftSec; live-clock asserted marks and backdated plain marks are unaffected. 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).",
3618
3981
  "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.",
3619
3982
  "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.",
3620
3983
  "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.",
3984
+ "Recording a real Chrome profile: --user-data-dir is the user-data ROOT (the dir with 'Local State'), NOT a profile subdir — pointing it at a 'Default'/'Profile N' dir is refused (Chromium would mint a blank logged-out Default inside your real profile), with a hint to pass the parent + --profile-directory. --profile-directory '<name>' selects a named profile: Playwright's launchPersistentContext IGNORES an in-place --profile-directory switch (verified: it's stripped and Default always loads), so Clipy COPIES <root>/<name> into a temp 0700 scratch root's Default/ (+ the root's 'Local State'; skipping Singleton-locks and Cache/Code Cache/GPUCache/Service Worker CacheStorage), launches the copy, and deletes it after upload. The copy is disclosed loudly on stderr (never silent — that's the whole point), the real profile is never opened or written, a running Chrome only draws a warning (in-use DBs may copy inconsistently), and a stranded copy from a SIGKILL is swept after 24h at the next record/session start.",
3621
3985
  "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.",
3622
3986
  "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).",
3623
3987
  "Public recordings have an unauthenticated context document at https://clipy.online/video/<id>.md.",
@@ -3703,6 +4067,7 @@ async function main() {
3703
4067
  limit: { type: "string" },
3704
4068
  output: { type: "string", short: "o" },
3705
4069
  srt: { type: "boolean", default: false },
4070
+ "marks-only": { type: "boolean", default: false },
3706
4071
  vtt: { type: "boolean", default: false },
3707
4072
  for: { type: "string" },
3708
4073
  timeout: { type: "string" },
@@ -3722,11 +4087,14 @@ async function main() {
3722
4087
  "assert-text": { type: "string" },
3723
4088
  "assert-url": { type: "string" },
3724
4089
  "fail-mode": { type: "string" },
4090
+ observed: { type: "string" },
4091
+ verdict: { type: "string" },
3725
4092
  at: { type: "string" },
3726
4093
  ago: { type: "string" },
3727
4094
  "expose-cdp": { type: "boolean", default: false },
3728
4095
  "storage-state": { type: "string" },
3729
4096
  "user-data-dir": { type: "string" },
4097
+ "profile-directory": { type: "string" },
3730
4098
  "init-script": { type: "string" },
3731
4099
  cookie: { type: "string", multiple: true },
3732
4100
  "local-storage": { type: "string", multiple: true },
@@ -3767,6 +4135,7 @@ async function main() {
3767
4135
  // without an explicit cwd — reads the same files the parent validated.
3768
4136
  const authFlagsPresent = Boolean(values["storage-state"] ||
3769
4137
  values["user-data-dir"] ||
4138
+ values["profile-directory"] ||
3770
4139
  values["init-script"] ||
3771
4140
  values.cookie?.length ||
3772
4141
  values["local-storage"]?.length);
@@ -3787,6 +4156,17 @@ async function main() {
3787
4156
  }
3788
4157
  return resolve(String(values["user-data-dir"]));
3789
4158
  };
4159
+ // --profile-directory names a profile subdir inside --user-data-dir; only
4160
+ // meaningful WITH it (Clipy copies that subdir into a scratch root's Default).
4161
+ const profileDirectory = () => {
4162
+ const pd = values["profile-directory"]?.trim();
4163
+ if (!pd)
4164
+ return undefined;
4165
+ if (!values["user-data-dir"]) {
4166
+ die("--profile-directory names a profile inside --user-data-dir — pass --user-data-dir <chrome user-data root> too", 2);
4167
+ }
4168
+ return pd;
4169
+ };
3790
4170
  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";
3791
4171
  switch (command) {
3792
4172
  case "login":
@@ -3830,7 +4210,7 @@ async function main() {
3830
4210
  return;
3831
4211
  }
3832
4212
  const fmt = json ? "json" : values.srt ? "srt" : values.vtt ? "vtt" : "text";
3833
- await cmdTranscript(ctx, rest[0], fmt);
4213
+ await cmdTranscript(ctx, rest[0], fmt, Boolean(values["marks-only"]));
3834
4214
  return;
3835
4215
  }
3836
4216
  case "summary":
@@ -3977,6 +4357,7 @@ async function main() {
3977
4357
  json,
3978
4358
  auth: authCapture(),
3979
4359
  userDataDir: userDataDir(),
4360
+ profileDirectory: profileDirectory(),
3980
4361
  });
3981
4362
  return;
3982
4363
  }
@@ -4018,6 +4399,7 @@ async function main() {
4018
4399
  exposeCdp: Boolean(values["expose-cdp"]),
4019
4400
  auth: authCapture(),
4020
4401
  userDataDir: userDataDir(),
4402
+ profileDirectory: profileDirectory(),
4021
4403
  };
4022
4404
  };
4023
4405
  if (sub === "start") {
@@ -4047,7 +4429,7 @@ async function main() {
4047
4429
  case "mark": {
4048
4430
  const text = rest.join(" ").trim();
4049
4431
  if (!text) {
4050
- 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);
4432
+ die('usage: clipy mark "<what just happened>" [--observed "<values>" --verdict pass|fail] [--assert-selector <css> [--assert-text <substr>]] [--assert-url <glob>] [--fail-mode warn|abort] [--at <sec>|--ago <sec>]', 2);
4051
4433
  }
4052
4434
  const selector = values["assert-selector"]?.trim() || undefined;
4053
4435
  const expectText = values["assert-text"]; // exact, not trimmed
@@ -4060,6 +4442,22 @@ async function main() {
4060
4442
  die("--fail-mode must be warn or abort", 2);
4061
4443
  }
4062
4444
  const hasAssert = Boolean(selector || (expectText != null && expectText !== "") || urlGlob);
4445
+ // Driver-attested provenance: --observed + --verdict travel together, and a
4446
+ // mark carries exactly ONE provenance (Clipy verified it, or the agent did).
4447
+ const observed = values.observed;
4448
+ const verdictRaw = values.verdict?.trim().toLowerCase();
4449
+ if ((observed == null) !== (verdictRaw == null)) {
4450
+ die("--observed and --verdict go together — pass both (the observed values you collected, and your pass/fail verdict)", 2);
4451
+ }
4452
+ if (verdictRaw != null && verdictRaw !== "pass" && verdictRaw !== "fail") {
4453
+ die("--verdict must be pass or fail", 2);
4454
+ }
4455
+ const attest = observed != null && verdictRaw != null
4456
+ ? { observed, verdict: verdictRaw }
4457
+ : undefined;
4458
+ if (attest && hasAssert) {
4459
+ die("--observed/--verdict (driver-attested) and --assert-* (Clipy-verified) are different provenances — use one per mark", 2);
4460
+ }
4063
4461
  if (failModeRaw && !hasAssert) {
4064
4462
  die("--fail-mode only applies with an assertion (--assert-selector / --assert-text / --assert-url)", 2);
4065
4463
  }
@@ -4073,6 +4471,7 @@ async function main() {
4073
4471
  assert: hasAssert
4074
4472
  ? { selector, expectText, urlGlob, failMode: failModeRaw || "warn" }
4075
4473
  : undefined,
4474
+ attest,
4076
4475
  });
4077
4476
  return;
4078
4477
  }