@clipy/mcp 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.
Files changed (3) hide show
  1. package/README.md +49 -8
  2. package/dist/index.js +469 -63
  3. package/package.json +1 -1
package/README.md CHANGED
@@ -105,9 +105,9 @@ or the Windsurf MCP config) directly:
105
105
  | `download_recording` | Download the MP4 locally so you can clip it or extract frames yourself (e.g. with ffmpeg). |
106
106
  | `get_key_moments` | Key moments: timestamps, captions, and click coordinates. |
107
107
  | `get_agent_context` | The full agent-context bundle (summary + key moments + transcript) as markdown. |
108
- | `record` | **Record a web app headlessly** and upload it as a Clipy recording; returns its share + agent-context URLs. Accepts a `type` (recording kind), `viewports` (sweep several screen sizes into one video), `storageState`/`userDataDir`/`initScript` (record behind a login), and timestamped `notes` that become the (silent) recording's transcript. Needs Playwright in this server's environment and an `ingest`-scoped key (see below). |
109
- | `start_recording` | **Start a recording session** that keeps recording while you work (drive the page with your own browser tools, run commands, …). Accepts `type`, `storageState`/`userDataDir`/`initScript`, and `exposeCdp` (get a CDP endpoint + in-page `window.__clipyMark`/`window.__clipyChapter` bridge to drive the recorded page). Auto-stops + uploads at `maxSeconds` (default 600) so it can never run away. |
110
- | `add_marker` | Drop a narration marker into the active session (live clock, or backdate with `atSeconds`) — markers become the recording's transcript chapters. Can also **verify** on-screen state (`assertSelector` / `assertText` (requires a selector) / `assertUrl`, `failMode`); an assertion is annotated as a pass (✓), an explicit failure (✗, can abort the session), or **unverified** (⚠, when it couldn't be evaluated — never a silent pass). Navigations + console errors are added automatically as `[auto]` marks. |
108
+ | `record` | **Record a web app headlessly** and upload it as a Clipy recording; returns its share + agent-context URLs. Accepts a `type` (recording kind), `viewports` (sweep several screen sizes into one video), `storageState` / `userDataDir`+`profileDirectory` / `initScript` (record behind a login), and timestamped `notes` that become the (silent) recording's transcript. Needs Playwright in this server's environment and an `ingest`-scoped key (see below). |
109
+ | `start_recording` | **Start a recording session** that keeps recording while you work (drive the page with your own browser tools, run commands, …). Accepts `type`, `storageState` / `userDataDir`+`profileDirectory` / `initScript`, and `exposeCdp` (get a CDP endpoint + in-page `window.__clipyMark`/`window.__clipyChapter` bridge to drive the recorded page). Auto-stops + uploads at `maxSeconds` (default 600) so it can never run away. |
110
+ | `add_marker` | Drop a narration marker into the active session (live clock, or backdate with `atSeconds`) — markers become the recording's transcript chapters. Can carry evidence in one of two provenances: **clipy-verified** (`assertSelector` / `assertText` / `assertUrl`) where Clipy checks the page itself, or **driver-attested** (`observed` + `verdict`) where you report what your own tooling saw. Clipy-verified outcomes render with a verdict glyph (✓ pass, ✗ failure that can abort via `failMode`, ⚠ unverified — never a silent pass); driver-attested ones render with a weaker-looking **hedge glyph** (`≈`) so the two are never mistaken at a glance, and they are tallied in separate segments. Navigations + console errors are added automatically as `[auto]` marks. |
111
111
  | `add_chapter` | Drop a `=== CHAPTER: <label> ===` boundary into the active session — split a recording into named sections (ideal for before/after demos). |
112
112
  | `stop_recording` | Finish the session: close the browser, upload, return the share + agent-context URLs. |
113
113
  | `abort_recording` | Discard the active session; nothing is uploaded. |
@@ -143,11 +143,52 @@ logged), `notes`, and `width`/`height` (default 1280×720, ignored when `viewpor
143
143
 
144
144
  **Recording behind a login.** `storageState` seeds exactly what its JSON contains (cookies +
145
145
  localStorage) but can't reproduce a whole browser identity (IndexedDB, service workers, some
146
- cross-origin auth). For a full identity, produce a storageState with an interactive login
147
- (`npx playwright open --save-storage=state.json <login-url>`) and pass its path, **or** pass
148
- `userDataDir` pointed at a **dedicated** Chromium profile directory — one no running browser
149
- is using (a live/locked profile is refused). `storageState` and `userDataDir` are mutually
150
- exclusive.
146
+ cross-origin auth). For a full identity, pass `userDataDir` — Chrome's **user-data root**
147
+ (macOS: `~/Library/Application Support/Google/Chrome`) — in one of two modes:
148
+
149
+ - **Copy a named profile (recommended).** Add `profileDirectory` (`"Profile 1"`, `"Default"`, …
150
+ — the exact folder from `chrome://version` → *Profile Path*). Clipy **copies** that profile
151
+ into a temporary root and records the copy, so your real profile is never opened or modified
152
+ and the copy is deleted after upload. The tool result discloses the copy (profile name, bytes,
153
+ and a warning if Chrome was running while it was copied).
154
+
155
+ > ⚠️ **macOS: cookie logins may not survive the copy.** Chrome encrypts cookies with the
156
+ > *Chrome Safe Storage* Keychain key; the recorder's bundled Chromium looks for *Chromium Safe
157
+ > Storage*. So on macOS a copied profile can produce a browser that **looks like your identity
158
+ > but is silently logged out** wherever the session is cookie-based — `localStorage`/
159
+ > `Preferences`-based sessions still work. This is a pre-existing Playwright-vs-Chrome
160
+ > constraint, not something the copy introduces, and the copy disclosure repeats it. **If the
161
+ > recording lands logged out, that's why.** Record the real browser with the CLI's
162
+ > `clipy record --source mac-screen`, or drive your own browser and attach evidence via
163
+ > `add_marker`'s `observed`/`verdict`.
164
+ - **Open the `Default` profile directly.** Omit `profileDirectory`. Clipy opens the root's
165
+ `Default` profile **and writes to it**, so it's refused while a live Chrome holds it locked —
166
+ quit Chrome first. When the dir looks like a real Chrome root, the result carries a
167
+ `userDataDirWarning` saying so and pointing you at `profileDirectory` (ephemeral copy) or the
168
+ CLI's `--source mac-screen` instead. Prefer those unless you specifically want in-place use.
169
+
170
+ > Playwright **strips** Chromium's `--profile-directory` (it always loads `Default` from whatever
171
+ > dir it's given), so copying is the only way to record a named profile. Pointing `userDataDir`
172
+ > at a profile subdir (`.../Chrome/Default`) is **refused** — launching from there would silently
173
+ > record a blank, logged-out profile.
174
+
175
+ `storageState` and `userDataDir` are mutually exclusive; `profileDirectory` requires `userDataDir`.
176
+
177
+ ### Evidence on a marker: two provenances
178
+
179
+ `add_marker` can carry evidence in exactly one of two provenances — they are tallied and rendered
180
+ separately, never pooled:
181
+
182
+ | Provenance | How | What it means |
183
+ | --- | --- | --- |
184
+ | **clipy-verified** | `assertSelector` / `assertText` / `assertUrl` | Clipy checked the recorded page itself. Strongest evidence. Renders `[assert ✓ verified-by-clipy; …]`, or `[ASSERT ✗ verified-by-clipy; …]`, or `[ASSERT ⚠ clipy could not evaluate — …]` when it couldn't check. |
185
+ | **driver-attested** | `observed` + `verdict` (both required) | *You* report what your own tooling saw. Clipy vouches only that you **said** it — not that it verified it — which is falsifiable against the recorded frames. Renders with a **hedge glyph** rather than a verdict glyph: `[≈ ASSERT driver-attested; observed=…]`, or `[≈ FAILED driver-attested; observed=…]`. |
186
+
187
+ Use **driver-attested** when your agent drives its own browser/tooling while Clipy records (e.g.
188
+ `--source mac-screen` on the CLI) or when there's no Clipy-owned page to assert against. It's
189
+ weaker than clipy-verified but far stronger than plain prose. The transcript's leading
190
+ `[verification]` note segments the two, e.g.
191
+ `[verification] 3 clipy-verified: 2 passed, 1 failed · 2 driver-attested: 2 passed, 0 failed`.
151
192
 
152
193
  ### Driving the recorded page over CDP (`start_recording` + `exposeCdp: true`)
153
194
 
package/dist/index.js CHANGED
@@ -24,16 +24,16 @@
24
24
  import { McpServer } from "@modelcontextprotocol/sdk/server/mcp.js";
25
25
  import { StdioServerTransport } from "@modelcontextprotocol/sdk/server/stdio.js";
26
26
  import { z } from "zod";
27
- import { closeSync, createWriteStream, mkdirSync, openSync, readdirSync, readFileSync, readSync, rmSync, statSync } from "node:fs";
27
+ import { chmodSync, closeSync, cpSync, createWriteStream, existsSync, mkdirSync, openSync, readdirSync, readFileSync, readSync, rmSync, statSync } from "node:fs";
28
28
  import { randomUUID } from "node:crypto";
29
29
  import { createServer } from "node:net";
30
30
  import { tmpdir } from "node:os";
31
- import { join, resolve } from "node:path";
31
+ import { basename, join, resolve } from "node:path";
32
32
  import { Readable } from "node:stream";
33
33
  import { pipeline } from "node:stream/promises";
34
34
  const API_URL = (process.env.CLIPY_API_URL || "https://clipy.online").replace(/\/+$/, "");
35
35
  const API_KEY = process.env.CLIPY_API_KEY;
36
- const SERVER_VERSION = "0.8.2";
36
+ const SERVER_VERSION = "0.8.4";
37
37
  // The key is checked lazily (per tool call, not at startup) so the server can
38
38
  // start and answer introspection (initialize / tools/list) in keyless
39
39
  // environments like directory health checks.
@@ -462,34 +462,252 @@ function validateInitScriptFile(p) {
462
462
  }
463
463
  return resolved;
464
464
  }
465
- /** Validate a userDataDir (a whole Chromium profile) — resolves, confirms it's a
466
- * directory, and REFUSES a live/locked profile (Chrome leaves SingletonLock /
467
- * SingletonSocket while running). Returns the absolute path. */
468
- function validateUserDataDir(p) {
465
+ /** Does this directory hold a browser PROFILE's own files (as opposed to being a
466
+ * user-data root, which holds 'Local State' + profile subdirs)? Single source of
467
+ * truth for every profile-shape decision below. Chrome writes Preferences;
468
+ * Playwright-made profiles may only have Cookies/History — accept any of them. */
469
+ function looksLikeChromeProfileDir(dir) {
470
+ return (existsSync(join(dir, "Preferences")) ||
471
+ existsSync(join(dir, "Cookies")) ||
472
+ existsSync(join(dir, "History")));
473
+ }
474
+ /** Validate a userDataDir. It must exist and be a user-data ROOT (not a Chrome
475
+ * PROFILE subdir — Chromium would silently mint a blank logged-out Default
476
+ * inside it). Without a profileName (direct-open mode) it must also not be a
477
+ * profile a live Chrome is holding open. WITH a profileName (copy mode) the
478
+ * named subdir must exist; the live-lock becomes a warning at copy time (we
479
+ * never open the real root). Returns the absolute path. Mirrors the CLI. */
480
+ function validateUserDataDir(p, profileName) {
469
481
  const resolved = resolve(p);
470
482
  let st;
471
483
  try {
472
484
  st = statSync(resolved);
473
485
  }
474
486
  catch {
475
- throw new Error(`userDataDir not found: ${resolved}`);
487
+ throw new Error(`userDataDir not found: ${resolved} (create it, or use a copy of a logged-in profile)`);
476
488
  }
477
489
  if (!st.isDirectory())
478
490
  throw new Error(`userDataDir is not a directory: ${resolved}`);
491
+ // Reject a Chrome PROFILE directory passed as the root. Chrome stores profiles
492
+ // as subdirs (Default, Profile 1, …) of the user-data ROOT (which holds
493
+ // 'Local State'); pointing userDataDir at a profile makes Chromium treat it as
494
+ // a root and create a blank Default inside the real profile.
495
+ const base = basename(resolved);
496
+ const looksLikeProfileName = /^(Default|Profile \d+)$/.test(base);
497
+ const hasProfileFiles = looksLikeChromeProfileDir(resolved);
498
+ if (looksLikeProfileName || (hasProfileFiles && !existsSync(join(resolved, "Local State")))) {
499
+ throw new Error(`userDataDir looks like a Chrome PROFILE directory, not a user-data root: ${resolved}. ` +
500
+ `Pass the PARENT directory (the one containing 'Local State') plus profileDirectory '${looksLikeProfileName ? base : "<name>"}'.`);
501
+ }
502
+ if (profileName != null) {
503
+ // Copy mode: the named profile subdir must exist inside the root AND look
504
+ // like a real Chrome profile. (Inverted from the root check on purpose: here
505
+ // the target IS supposed to be a profile.) Copying a missing or non-profile
506
+ // directory would hand back a BLANK identity wearing the profile's name.
507
+ const target = join(resolved, profileName);
508
+ const listProfiles = () => {
509
+ try {
510
+ return readdirSync(resolved, { withFileTypes: true })
511
+ .filter((e) => e.isDirectory() && /^(Default|Profile \d+)$/.test(e.name))
512
+ .map((e) => e.name);
513
+ }
514
+ catch {
515
+ return [];
516
+ }
517
+ };
518
+ if (!existsSync(target)) {
519
+ const available = listProfiles();
520
+ throw new Error(`profileDirectory '${profileName}' not found under ${resolved}` +
521
+ (available.length ? ` (available: ${available.join(", ")})` : "") +
522
+ `. Find the exact folder name at chrome://version → "Profile Path".`);
523
+ }
524
+ if (!looksLikeChromeProfileDir(target)) {
525
+ const available = listProfiles();
526
+ throw new Error(`profileDirectory '${profileName}' (${target}) does not look like a Chrome profile — no Preferences/Cookies/History inside. ` +
527
+ `Copying it would record a BLANK, logged-out identity under that profile's name` +
528
+ (available.length ? ` (available: ${available.join(", ")})` : "") +
529
+ `. Find the exact folder name at chrome://version → "Profile Path".`);
530
+ }
531
+ return resolved; // the copy path handles a running Chrome (a warn), never opens the root
532
+ }
533
+ // Direct-open mode: refuse a profile a live Chrome is holding open.
534
+ for (const lock of ["SingletonLock", "SingletonSocket"]) {
535
+ if (existsSync(join(resolved, lock))) {
536
+ throw new Error(`userDataDir looks like a live/locked Chrome profile (${lock} present): ${resolved}. ` +
537
+ `Close that Chrome, or use a COPY / a dedicated logged-in profile dir — Chrome locks a profile while open.`);
538
+ }
539
+ }
540
+ return resolved;
541
+ }
542
+ // --- profileDirectory: copy a named Chrome profile into a scratch root -------
543
+ // Playwright's launchPersistentContext IGNORES Chromium's --profile-directory
544
+ // (verified 0.8.3: the switch is stripped, Default is always loaded), so
545
+ // selecting a named profile means making it the Default of the root we open. We
546
+ // COPY <root>/<name> into a temp scratch root's Default/ (+ the root's
547
+ // 'Local State') and launch against that; the user's real profile is never
548
+ // opened or written. LOUD by design — silent profile substitution is the enemy.
549
+ // Mirrors the CLI (cli/src/index.ts copyProfileToScratchRoot).
550
+ const PROFILE_COPY_PREFIX = "clipy-profile-";
551
+ // Bulk cache dirs — identity lives in Cookies / Login Data / Local Storage /
552
+ // Preferences, so we skip these to keep the copy small.
553
+ const PROFILE_SKIP_TOP = new Set(["Cache", "Code Cache", "GPUCache"]);
554
+ const SW_CACHE_FRAGMENT = join("Service Worker", "CacheStorage");
555
+ /** Bytes we'll actually copy (identity, minus the skipped cache dirs). */
556
+ function profileCopyableSize(profileDir) {
557
+ let total = 0;
558
+ const walk = (p, top) => {
559
+ let entries;
560
+ try {
561
+ entries = readdirSync(p, { withFileTypes: true });
562
+ }
563
+ catch {
564
+ return;
565
+ }
566
+ for (const e of entries) {
567
+ if (top && (e.name.startsWith("Singleton") || PROFILE_SKIP_TOP.has(e.name)))
568
+ continue;
569
+ const full = join(p, e.name);
570
+ if (full.includes(SW_CACHE_FRAGMENT))
571
+ continue;
572
+ try {
573
+ if (e.isDirectory())
574
+ walk(full, false);
575
+ else
576
+ total += statSync(full).size;
577
+ }
578
+ catch {
579
+ // unreadable — skip
580
+ }
581
+ }
582
+ };
583
+ walk(profileDir, true);
584
+ return total;
585
+ }
586
+ /** Copy <userDataDir>/<profileName> into a fresh 0700 scratch root's Default/
587
+ * (plus the root's 'Local State'), skipping Singleton-locks and cache dirs.
588
+ * Best-effort per top-level entry, so a locked file loses only that entry.
589
+ * Returns the scratch root to launch against + disclosure the caller surfaces. */
590
+ function copyProfileToScratchRoot(userDataDir, profileName) {
591
+ const srcProfile = join(userDataDir, profileName);
592
+ const chromeRunning = existsSync(join(userDataDir, "SingletonLock")) || existsSync(join(userDataDir, "SingletonSocket"));
593
+ const sizeBytes = profileCopyableSize(srcProfile);
594
+ const scratchRoot = join(tmpdir(), `${PROFILE_COPY_PREFIX}${randomUUID()}`);
595
+ mkdirSync(scratchRoot, { recursive: true });
596
+ try {
597
+ chmodSync(scratchRoot, 0o700);
598
+ }
599
+ catch {
600
+ // best-effort on platforms without POSIX modes
601
+ }
602
+ const destDefault = join(scratchRoot, "Default");
603
+ mkdirSync(destDefault, { recursive: true });
604
+ const skipped = [];
605
+ for (const entry of readdirSync(srcProfile, { withFileTypes: true })) {
606
+ const name = entry.name;
607
+ if (name.startsWith("Singleton") || PROFILE_SKIP_TOP.has(name))
608
+ continue;
609
+ try {
610
+ cpSync(join(srcProfile, name), join(destDefault, name), {
611
+ recursive: true,
612
+ // Skip the bulk CacheStorage nested under Service Worker.
613
+ filter: (s) => !s.includes(SW_CACHE_FRAGMENT),
614
+ });
615
+ }
616
+ catch {
617
+ skipped.push(name); // locked/unreadable — best-effort
618
+ }
619
+ }
620
+ // 'Local State' lives at the root and carries the os_crypt key Linux uses to
621
+ // decrypt Cookies/Login Data (harmless elsewhere — macOS keys off the Keychain).
622
+ try {
623
+ if (existsSync(join(userDataDir, "Local State"))) {
624
+ cpSync(join(userDataDir, "Local State"), join(scratchRoot, "Local State"));
625
+ }
626
+ }
627
+ catch {
628
+ // best-effort
629
+ }
630
+ serverLog(`copied profile '${profileName}' (${sizeBytes} bytes) into ${scratchRoot}` +
631
+ (chromeRunning ? " — Chrome appears to be running, copy may be inconsistent" : ""));
632
+ return { scratchRoot, profileName, sizeBytes, chromeRunning, skipped };
633
+ }
634
+ /** Remove stranded profile copies (a SIGKILL between copy and cleanup can leave
635
+ * one). Swept at the start of every record/session start. Best-effort. */
636
+ function sweepStaleProfileCopies() {
637
+ const now = Date.now();
479
638
  let entries;
480
639
  try {
481
- entries = readdirSync(resolved);
640
+ entries = readdirSync(tmpdir(), { withFileTypes: true });
482
641
  }
483
642
  catch {
484
- throw new Error(`userDataDir is not readable: ${resolved}`);
643
+ return;
485
644
  }
486
- // Match by NAME (these are often symlinks/sockets that statSync can't follow).
487
- if (entries.includes("SingletonLock") || entries.includes("SingletonSocket")) {
488
- throw new Error(`userDataDir looks like a LIVE Chrome profile — found a Singleton lock in ${resolved}. ` +
489
- `Close that browser, or point userDataDir at a DEDICATED profile directory no running browser is using. ` +
490
- `Driving a locked profile fails and risks corrupting it.`);
645
+ for (const e of entries) {
646
+ if (!e.isDirectory() || !e.name.startsWith(PROFILE_COPY_PREFIX))
647
+ continue;
648
+ const full = join(tmpdir(), e.name);
649
+ try {
650
+ if (now - statSync(full).mtimeMs > 24 * 3600 * 1000)
651
+ rmSync(full, { recursive: true, force: true });
652
+ }
653
+ catch {
654
+ // best-effort
655
+ }
491
656
  }
492
- return resolved;
657
+ }
658
+ /** Warning for BARE userDataDir (no profileDirectory) pointed at what looks like
659
+ * a REAL Chrome user-data root: that mode opens the root's Default profile in
660
+ * place and Chromium WILL write to it. Returns undefined for a dedicated/scratch
661
+ * dir, where in-place use is exactly what the caller wants. */
662
+ function bareRealRootWarning(userDataDirPath) {
663
+ // Discriminators that mean "the user's real Chrome profile store", chosen so a
664
+ // Clipy/Playwright-managed dedicated dir never trips them: Chrome writes
665
+ // 'Local State' and numbered 'Profile N' dirs, Playwright writes neither (it
666
+ // only ever creates a bare 'Default/'), so a plain Default is NOT a signal.
667
+ const hasLocalState = existsSync(join(userDataDirPath, "Local State"));
668
+ let hasNumberedProfile = false;
669
+ try {
670
+ hasNumberedProfile = readdirSync(userDataDirPath, { withFileTypes: true }).some((e) => e.isDirectory() &&
671
+ /^Profile \d+$/.test(e.name) &&
672
+ looksLikeChromeProfileDir(join(userDataDirPath, e.name)));
673
+ }
674
+ catch {
675
+ hasNumberedProfile = false;
676
+ }
677
+ if (!hasLocalState && !hasNumberedProfile)
678
+ return undefined;
679
+ return (`userDataDir points at what looks like a REAL Chrome user-data root and no profileDirectory was given, ` +
680
+ `so this recording OPENS that root's 'Default' profile in place — Chromium can write to your real profile ` +
681
+ `(history, cookies, session). Prefer profileDirectory:'Default' (Clipy records an ephemeral COPY and never ` +
682
+ `touches the original), or capture the real browser via the CLI's --source mac-screen.`);
683
+ }
684
+ /** Cookie-decryption caveat for a copied REAL Chrome profile on macOS. Chrome
685
+ * encrypts its cookies with the "Chrome Safe Storage" Keychain key, but the
686
+ * recorder's bundled Chromium looks for "Chromium Safe Storage" — so a copied
687
+ * profile can render a browser that LOOKS like the user's identity while being
688
+ * silently logged out of cookie-based sessions. Exactly the false-identity class
689
+ * this feature exists to prevent, so it ships in the disclosure, not a footnote.
690
+ * (Pre-existing Playwright-vs-Chrome constraint, not caused by the copy. Linux
691
+ * keys off the copied 'Local State' and Windows off DPAPI, so it's macOS-only.) */
692
+ const MACOS_COOKIE_CAVEAT = "On macOS, cookie-based logins in a real Chrome profile may NOT decrypt under the recorder's Chromium " +
693
+ "(Chrome and Chromium use different Keychain keys) — localStorage/Preferences-based sessions survive. " +
694
+ "If the recording lands logged out, that is why: record your real browser via the CLI's " +
695
+ "`clipy record --source mac-screen`, or drive your own browser and attach evidence with add_marker's observed/verdict.";
696
+ /** The loud tool-result disclosure for a profile copy. */
697
+ function profileCopyDisclosure(copy, userDataDir) {
698
+ return {
699
+ profile: copy.profileName,
700
+ copiedBytes: copy.sizeBytes,
701
+ note: `Recorded a TEMPORARY COPY of profile '${copy.profileName}' from ${userDataDir}. ` +
702
+ `Your real profile was never opened or modified; the copy is deleted after upload.`,
703
+ ...(process.platform === "darwin" ? { cookieDecryptionCaveat: MACOS_COOKIE_CAVEAT } : {}),
704
+ ...(copy.chromeRunning
705
+ ? {
706
+ warning: "Chrome appears to be running — in-use databases may have copied inconsistently. Quit Chrome for a guaranteed-clean copy.",
707
+ }
708
+ : {}),
709
+ ...(copy.skipped.length ? { skippedEntries: copy.skipped } : {}),
710
+ };
493
711
  }
494
712
  /** First line of an error message, trimmed — keeps annotations/logs one-line. */
495
713
  function firstLine(message) {
@@ -1106,14 +1324,18 @@ server.tool("record", "Record a web app HEADLESSLY and upload it as a Clipy reco
1106
1324
  userDataDir: z
1107
1325
  .string()
1108
1326
  .optional()
1109
- .describe("Path to a DEDICATED Chromium user-data (profile) directory to record with a full browser identity — launched via launchPersistentContext. Use a profile NO running browser is using (a live/locked profile is refused). Mutually exclusive with storageState."),
1327
+ .describe("Path to a Chromium user-data ROOT — the dir holding 'Local State' plus profile subdirs (macOS Chrome: ~/Library/Application Support/Google/Chrome). WITHOUT profileDirectory, Clipy opens this dir's 'Default' profile directly and writes to it, so it is refused while a live Chrome holds it locked (quit Chrome first). WITH profileDirectory, Clipy COPIES that named profile into a temporary root and records the copy — your real profile is never opened or modified. A profile SUBDIR passed as the root is refused. Mutually exclusive with storageState."),
1328
+ profileDirectory: z
1329
+ .string()
1330
+ .optional()
1331
+ .describe("Which profile INSIDE userDataDir to record — 'Default', 'Profile 1', 'Profile 2', … (exact folder name from chrome://version → 'Profile Path'). Clipy COPIES that profile into a temporary scratch root (as its Default) and records the copy: your real profile is never opened or modified, and the copy is deleted after upload. The result discloses the copy. Requires userDataDir. (Playwright strips Chromium's --profile-directory, so copying is the only way to select a named profile.)"),
1110
1332
  initScript: z
1111
1333
  .string()
1112
1334
  .optional()
1113
1335
  .describe("Path to a JS file run in the page before every navigation (context.addInitScript) — e.g. to seed localStorage or stub an API. Contents are never logged."),
1114
1336
  width: z.number().int().min(320).max(3840).optional().describe("Viewport + video width (default 1280). Ignored when `viewports` is set."),
1115
1337
  height: z.number().int().min(240).max(2160).optional().describe("Viewport + video height (default 720). Ignored when `viewports` is set."),
1116
- }, async ({ url, durationSeconds, name, description, type, viewports, notes, storageState, userDataDir, initScript, width, height }) => {
1338
+ }, async ({ url, durationSeconds, name, description, type, viewports, notes, storageState, userDataDir, profileDirectory, initScript, width, height }) => {
1117
1339
  // Validate the URL before spinning up a browser.
1118
1340
  let target;
1119
1341
  try {
@@ -1155,6 +1377,9 @@ server.tool("record", "Record a web app HEADLESSLY and upload it as a Clipy reco
1155
1377
  if (userDataDir && storageState) {
1156
1378
  return fail("userDataDir and storageState are mutually exclusive — userDataDir launches a whole persistent profile; storageState seeds a fresh context. Pick one.");
1157
1379
  }
1380
+ if (profileDirectory && !userDataDir) {
1381
+ return fail("profileDirectory requires userDataDir — it names a profile subdir ('Default', 'Profile 1', …) INSIDE a Chromium user-data root. Pass userDataDir=<the user-data root> too.");
1382
+ }
1158
1383
  let storageStatePath;
1159
1384
  let userDataDirPath;
1160
1385
  let initScriptPath;
@@ -1162,7 +1387,7 @@ server.tool("record", "Record a web app HEADLESSLY and upload it as a Clipy reco
1162
1387
  if (storageState)
1163
1388
  storageStatePath = validateStorageStateFile(storageState);
1164
1389
  if (userDataDir)
1165
- userDataDirPath = validateUserDataDir(userDataDir);
1390
+ userDataDirPath = validateUserDataDir(userDataDir, profileDirectory);
1166
1391
  if (initScript)
1167
1392
  initScriptPath = validateInitScriptFile(initScript);
1168
1393
  }
@@ -1180,6 +1405,23 @@ server.tool("record", "Record a web app HEADLESSLY and upload it as a Clipy reco
1180
1405
  return fail(e.message);
1181
1406
  }
1182
1407
  mkdirSync(dir, { recursive: true });
1408
+ // profileDirectory ⇒ copy the named profile into a scratch root and launch
1409
+ // against that (Playwright can't select a named profile any other way).
1410
+ sweepStaleProfileCopies();
1411
+ let profileCopy;
1412
+ let effectivePersistentDir = userDataDirPath;
1413
+ // Bare userDataDir at a real Chrome root opens (and can write to) the real
1414
+ // Default profile — surface that rather than letting it happen quietly.
1415
+ const bareRootWarning = userDataDirPath && !profileDirectory ? bareRealRootWarning(userDataDirPath) : undefined;
1416
+ if (userDataDirPath && profileDirectory) {
1417
+ try {
1418
+ profileCopy = copyProfileToScratchRoot(userDataDirPath, profileDirectory);
1419
+ effectivePersistentDir = profileCopy.scratchRoot;
1420
+ }
1421
+ catch (e) {
1422
+ return fail(`profile copy failed: ${e.message}`);
1423
+ }
1424
+ }
1183
1425
  let publicId = "";
1184
1426
  let sizeBytes = 0;
1185
1427
  const autoNotes = [];
@@ -1187,7 +1429,7 @@ server.tool("record", "Record a web app HEADLESSLY and upload it as a Clipy reco
1187
1429
  // ── Capture ──
1188
1430
  let videoPath;
1189
1431
  const opened = await openCaptureContext(chromium, {
1190
- userDataDir: userDataDirPath,
1432
+ userDataDir: effectivePersistentDir,
1191
1433
  viewport: { width: frame.width, height: frame.height },
1192
1434
  recordDir: dir,
1193
1435
  recordSize: frame,
@@ -1270,6 +1512,16 @@ server.tool("record", "Record a web app HEADLESSLY and upload it as a Clipy reco
1270
1512
  catch {
1271
1513
  // best-effort temp cleanup
1272
1514
  }
1515
+ // Remove the copied-profile scratch root (a SIGKILL strands it → the 24h
1516
+ // sweep at the next record/session start catches that).
1517
+ if (profileCopy) {
1518
+ try {
1519
+ rmSync(profileCopy.scratchRoot, { recursive: true, force: true });
1520
+ }
1521
+ catch {
1522
+ // best-effort
1523
+ }
1524
+ }
1273
1525
  }
1274
1526
  return ok({
1275
1527
  id: publicId,
@@ -1279,6 +1531,8 @@ server.tool("record", "Record a web app HEADLESSLY and upload it as a Clipy reco
1279
1531
  recordedSeconds: forSec * passes.length,
1280
1532
  ...(recordingKind ? { recordingKind } : {}),
1281
1533
  ...(viewports ? { viewports: passes.map((p) => p.label) } : {}),
1534
+ ...(profileCopy ? { profileCopy: profileCopyDisclosure(profileCopy, userDataDir) } : {}),
1535
+ ...(bareRootWarning ? { userDataDirWarning: bareRootWarning } : {}),
1282
1536
  next: "Processing runs in the background. Call wait_for_artifacts with this id (require:'all'), then get_agent_context / get_transcript to read it.",
1283
1537
  });
1284
1538
  });
@@ -1307,6 +1561,25 @@ function sessionMark(session, text, atMs) {
1307
1561
  session.marks.push(note);
1308
1562
  return note;
1309
1563
  }
1564
+ /** The segmented [verification] transcript note, or "" when no assertion ran.
1565
+ * Format: `[verification] N clipy-verified: P passed, F failed, K unverified ·
1566
+ * M driver-attested: P passed, F failed` — segments omitted when their lane is
1567
+ * empty; the unverified clause omitted when K=0. */
1568
+ function buildVerificationNote(session) {
1569
+ const clipyTotal = session.assertPassed + session.assertFailed + session.assertUnverified;
1570
+ const driverTotal = session.attestPassed + session.attestFailed;
1571
+ if (clipyTotal === 0 && driverTotal === 0)
1572
+ return "";
1573
+ const segments = [];
1574
+ if (clipyTotal > 0) {
1575
+ const unverifiedClause = session.assertUnverified > 0 ? `, ${session.assertUnverified} unverified` : "";
1576
+ segments.push(`${clipyTotal} clipy-verified: ${session.assertPassed} passed, ${session.assertFailed} failed${unverifiedClause}`);
1577
+ }
1578
+ if (driverTotal > 0) {
1579
+ segments.push(`${driverTotal} driver-attested: ${session.attestPassed} passed, ${session.attestFailed} failed`);
1580
+ }
1581
+ return `[verification] ${segments.join(" · ")}`;
1582
+ }
1310
1583
  /** Close the browser, upload the capture (unless aborting), clean up. */
1311
1584
  function finishSession(session, mode) {
1312
1585
  if (session.finishing)
@@ -1325,16 +1598,13 @@ function finishSession(session, mode) {
1325
1598
  const videoPath = await video.path();
1326
1599
  await session.browser?.close().catch(() => { });
1327
1600
  const collected = [...session.marks];
1328
- // If any assertions ran, lead the transcript with a verification summary
1329
- // at 0ms so a reader sees the pass/fail/unverified tally up front.
1330
- const assertionsRan = session.assertPassed + session.assertFailed + session.assertUnverified;
1331
- if (assertionsRan > 0) {
1332
- const unverifiedClause = session.assertUnverified > 0 ? `, ${session.assertUnverified} unverified` : "";
1333
- collected.unshift({
1334
- startMs: 0,
1335
- text: `[verification] ${assertionsRan} assertion${assertionsRan === 1 ? "" : "s"}: ${session.assertPassed} passed, ${session.assertFailed} failed${unverifiedClause}`,
1336
- });
1337
- }
1601
+ // Lead the transcript at 0ms with a SEGMENTED verification summary so a
1602
+ // reader sees the two provenances separately — clipy-verified marks (Clipy
1603
+ // checked the live page) and driver-attested marks (the agent SAID it, Clipy
1604
+ // only vouches it was claimed). Empty segments are omitted.
1605
+ const verificationNote = buildVerificationNote(session);
1606
+ if (verificationNote)
1607
+ collected.unshift({ startMs: 0, text: verificationNote });
1338
1608
  const notes = collected.sort((a, b) => a.startMs - b.startMs);
1339
1609
  const uploaded = await uploadCapturedWebm({
1340
1610
  videoPath,
@@ -1364,6 +1634,16 @@ function finishSession(session, mode) {
1364
1634
  catch {
1365
1635
  // best-effort temp cleanup
1366
1636
  }
1637
+ // Delete the copied-profile scratch root (a SIGKILL strands it → the 24h
1638
+ // sweep at the next record/session start catches that).
1639
+ if (session.profileScratchRoot) {
1640
+ try {
1641
+ rmSync(session.profileScratchRoot, { recursive: true, force: true });
1642
+ }
1643
+ catch {
1644
+ // best-effort
1645
+ }
1646
+ }
1367
1647
  if (activeSession === session)
1368
1648
  activeSession = null;
1369
1649
  }
@@ -1396,14 +1676,18 @@ server.tool("start_recording", "Start a RECORDING SESSION: opens the given URL i
1396
1676
  userDataDir: z
1397
1677
  .string()
1398
1678
  .optional()
1399
- .describe("Path to a DEDICATED Chromium user-data (profile) directory to record with a full browser identity (launchPersistentContext). Use a profile NO running browser is using (a live/locked profile is refused). Mutually exclusive with storageState."),
1679
+ .describe("Path to a Chromium user-data ROOT — the dir holding 'Local State' plus profile subdirs (macOS Chrome: ~/Library/Application Support/Google/Chrome). WITHOUT profileDirectory, Clipy opens this dir's 'Default' profile directly and writes to it, so it is refused while a live Chrome holds it locked (quit Chrome first). WITH profileDirectory, Clipy COPIES that named profile into a temporary root and records the copy — your real profile is never opened or modified. A profile SUBDIR passed as the root is refused. Mutually exclusive with storageState."),
1680
+ profileDirectory: z
1681
+ .string()
1682
+ .optional()
1683
+ .describe("Which profile INSIDE userDataDir to record — 'Default', 'Profile 1', 'Profile 2', … (exact folder name from chrome://version → 'Profile Path'). Clipy COPIES that profile into a temporary scratch root (as its Default) and records the copy: your real profile is never opened or modified, and the copy is deleted after upload. The result discloses the copy. Requires userDataDir. (Playwright strips Chromium's --profile-directory, so copying is the only way to select a named profile.)"),
1400
1684
  initScript: z
1401
1685
  .string()
1402
1686
  .optional()
1403
1687
  .describe("Path to a JS file run in the page before every navigation (context.addInitScript). Contents are never logged."),
1404
1688
  width: z.number().int().min(320).max(3840).optional().describe("Viewport + video width (default 1280)."),
1405
1689
  height: z.number().int().min(240).max(2160).optional().describe("Viewport + video height (default 720)."),
1406
- }, async ({ url, name, description, type, maxSeconds, exposeCdp, storageState, userDataDir, initScript, width, height }) => {
1690
+ }, async ({ url, name, description, type, maxSeconds, exposeCdp, storageState, userDataDir, profileDirectory, initScript, width, height }) => {
1407
1691
  let target;
1408
1692
  try {
1409
1693
  target = new URL(url);
@@ -1430,6 +1714,9 @@ server.tool("start_recording", "Start a RECORDING SESSION: opens the given URL i
1430
1714
  if (userDataDir && storageState) {
1431
1715
  return fail("userDataDir and storageState are mutually exclusive — userDataDir launches a whole persistent profile; storageState seeds a fresh context. Pick one.");
1432
1716
  }
1717
+ if (profileDirectory && !userDataDir) {
1718
+ return fail("profileDirectory requires userDataDir — it names a profile subdir ('Default', 'Profile 1', …) INSIDE a Chromium user-data root. Pass userDataDir=<the user-data root> too.");
1719
+ }
1433
1720
  let storageStatePath;
1434
1721
  let userDataDirPath;
1435
1722
  let initScriptPath;
@@ -1437,7 +1724,7 @@ server.tool("start_recording", "Start a RECORDING SESSION: opens the given URL i
1437
1724
  if (storageState)
1438
1725
  storageStatePath = validateStorageStateFile(storageState);
1439
1726
  if (userDataDir)
1440
- userDataDirPath = validateUserDataDir(userDataDir);
1727
+ userDataDirPath = validateUserDataDir(userDataDir, profileDirectory);
1441
1728
  if (initScript)
1442
1729
  initScriptPath = validateInitScriptFile(initScript);
1443
1730
  }
@@ -1456,6 +1743,30 @@ server.tool("start_recording", "Start a RECORDING SESSION: opens the given URL i
1456
1743
  const maxSec = Math.min(maxSeconds ?? SESSION_DEFAULT_MAX_SEC, SESSION_HARD_CAP_SEC);
1457
1744
  const tmpDirPath = join(tmpdir(), `clipy-mcp-session-${randomUUID()}`);
1458
1745
  mkdirSync(tmpDirPath, { recursive: true });
1746
+ // profileDirectory ⇒ copy the named profile into a scratch root and launch
1747
+ // against that. The scratch root lives for the whole session; finishSession
1748
+ // removes it. On any failure below we clean it up before returning.
1749
+ sweepStaleProfileCopies();
1750
+ let profileCopy;
1751
+ let effectivePersistentDir = userDataDirPath;
1752
+ // Bare userDataDir at a real Chrome root opens (and can write to) the real
1753
+ // Default profile — surface that rather than letting it happen quietly.
1754
+ const bareRootWarning = userDataDirPath && !profileDirectory ? bareRealRootWarning(userDataDirPath) : undefined;
1755
+ if (userDataDirPath && profileDirectory) {
1756
+ try {
1757
+ profileCopy = copyProfileToScratchRoot(userDataDirPath, profileDirectory);
1758
+ effectivePersistentDir = profileCopy.scratchRoot;
1759
+ }
1760
+ catch (e) {
1761
+ try {
1762
+ rmSync(tmpDirPath, { recursive: true, force: true });
1763
+ }
1764
+ catch {
1765
+ // best-effort
1766
+ }
1767
+ return fail(`profile copy failed: ${e.message}`);
1768
+ }
1769
+ }
1459
1770
  // CDP is OPT-IN and the env kill switch wins over the flag: only open a
1460
1771
  // debugging port when the caller asked AND CLIPY_DISABLE_CDP isn't set.
1461
1772
  const cdpDisabled = process.env.CLIPY_DISABLE_CDP === "1";
@@ -1463,7 +1774,7 @@ server.tool("start_recording", "Start a RECORDING SESSION: opens the given URL i
1463
1774
  try {
1464
1775
  const cdpPort = wantCdp ? await pickFreePort().catch(() => 0) : 0;
1465
1776
  const opened = await openCaptureContext(chromium, {
1466
- userDataDir: userDataDirPath,
1777
+ userDataDir: effectivePersistentDir,
1467
1778
  viewport: { width: w, height: h },
1468
1779
  recordDir: tmpDirPath,
1469
1780
  recordSize: { width: w, height: h },
@@ -1490,6 +1801,7 @@ server.tool("start_recording", "Start a RECORDING SESSION: opens the given URL i
1490
1801
  context,
1491
1802
  page,
1492
1803
  tmpDir: tmpDirPath,
1804
+ profileScratchRoot: profileCopy?.scratchRoot,
1493
1805
  url: target.href,
1494
1806
  name,
1495
1807
  description,
@@ -1500,6 +1812,8 @@ server.tool("start_recording", "Start a RECORDING SESSION: opens the given URL i
1500
1812
  assertPassed: 0,
1501
1813
  assertFailed: 0,
1502
1814
  assertUnverified: 0,
1815
+ attestPassed: 0,
1816
+ attestFailed: 0,
1503
1817
  cdpUrl,
1504
1818
  cdpHttpUrl,
1505
1819
  maxTimer: setTimeout(() => { }, 0),
@@ -1517,13 +1831,24 @@ server.tool("start_recording", "Start a RECORDING SESSION: opens the given URL i
1517
1831
  if (session.finishing)
1518
1832
  throw new Error("recording session is finishing — mark ignored");
1519
1833
  const markText = String(args[0] ?? "").slice(0, 1000);
1520
- const { note, assertion, aborted } = await applyMark(session, markText, coerceMarkOpts(args[1]));
1834
+ const { note, assertion, attestation, aborted } = await applyMark(session, markText, coerceMarkOpts(args[1]));
1521
1835
  return {
1522
1836
  atSeconds: Math.round(note.startMs / 100) / 10,
1523
1837
  ...(assertion
1524
1838
  ? assertion.status === "unverified"
1525
- ? { unverified: true, observed: assertion.observed }
1526
- : { passed: assertion.status === "passed", observed: assertion.observed }
1839
+ ? { provenance: "clipy-verified", unverified: true, observed: assertion.observed }
1840
+ : {
1841
+ provenance: "clipy-verified",
1842
+ passed: assertion.status === "passed",
1843
+ observed: assertion.observed,
1844
+ }
1845
+ : {}),
1846
+ ...(attestation
1847
+ ? {
1848
+ provenance: "driver-attested",
1849
+ passed: attestation.verdict === "pass",
1850
+ observed: attestation.observed,
1851
+ }
1527
1852
  : {}),
1528
1853
  ...(aborted ? { aborted: true } : {}),
1529
1854
  };
@@ -1591,6 +1916,8 @@ server.tool("start_recording", "Start a RECORDING SESSION: opens the given URL i
1591
1916
  url: target.href,
1592
1917
  maxSeconds: maxSec,
1593
1918
  ...(recordingKind ? { recordingKind } : {}),
1919
+ ...(profileCopy ? { profileCopy: profileCopyDisclosure(profileCopy, userDataDir) } : {}),
1920
+ ...(bareRootWarning ? { userDataDirWarning: bareRootWarning } : {}),
1594
1921
  ...cdpResult,
1595
1922
  next: "The session is recording. Use add_marker to narrate (and optionally assert) each step, add_chapter for before/after boundaries; call stop_recording when done (or abort_recording to discard). It auto-stops + uploads at the max duration.",
1596
1923
  });
@@ -1602,6 +1929,15 @@ server.tool("start_recording", "Start a RECORDING SESSION: opens the given URL i
1602
1929
  catch {
1603
1930
  // best-effort
1604
1931
  }
1932
+ // Launch failed before the session took ownership of the scratch root — clean it up.
1933
+ if (profileCopy) {
1934
+ try {
1935
+ rmSync(profileCopy.scratchRoot, { recursive: true, force: true });
1936
+ }
1937
+ catch {
1938
+ // best-effort
1939
+ }
1940
+ }
1605
1941
  return fail(e.message);
1606
1942
  }
1607
1943
  });
@@ -1674,21 +2010,49 @@ async function runMarkerAssertions(page, a) {
1674
2010
  }
1675
2011
  return { status: failed ? "failed" : "passed", expected: expected.join("; "), observed: observed.join("; ") };
1676
2012
  }
1677
- /** Apply a mark to the session: strict assertText/assertSelector contract,
1678
- * evaluate assertions, annotate the mark so pass/fail/unverified is explicit,
1679
- * update the tally, and abort the session on a FAILED assert under failMode
1680
- * 'abort'. Shared by the add_marker tool and the in-page CDP bridge. Throws on
1681
- * the assertText-without-assertSelector contract violation (so a CDP driver
1682
- * sees the rejection). */
2013
+ /** Apply a mark to the session. Two mutually-exclusive evidence provenances:
2014
+ * CLIPY-VERIFIED (assertSelector/assertText/assertUrl — Clipy checks the live
2015
+ * page) and DRIVER-ATTESTED (observed/verdict — Clipy only vouches the agent
2016
+ * SAID it). Annotates the mark so the provenance + outcome are explicit (never
2017
+ * pooled), updates the matching tally, and aborts on a FAILED outcome under
2018
+ * failMode 'abort'. Shared by the add_marker tool and the in-page CDP bridge.
2019
+ * Throws on the one-provenance / both-or-neither / assertText-needs-selector
2020
+ * contract violations (so a CDP driver sees the rejection). */
1683
2021
  async function applyMark(session, text, opts) {
2022
+ const hasAttest = opts.observed != null || opts.verdict != null;
2023
+ const hasAssertion = !!(opts.assertSelector || opts.assertText || opts.assertUrl);
2024
+ if (hasAttest && hasAssertion) {
2025
+ throw new Error("driver-attested (observed/verdict) and clipy-evaluated (assertSelector/assertText/assertUrl) are mutually exclusive — one provenance per mark.");
2026
+ }
2027
+ if ((opts.observed != null) !== (opts.verdict != null)) {
2028
+ throw new Error("observed and verdict must be provided together (both or neither).");
2029
+ }
1684
2030
  if (opts.assertText && !opts.assertSelector) {
1685
2031
  throw new Error("assertText requires assertSelector — name the element whose text you're checking. A bare page-body text match is weak evidence, so it's rejected (same rule as the CLI's --assert-text / --assert-selector).");
1686
2032
  }
1687
- const hasAssertion = !!(opts.assertSelector || opts.assertText || opts.assertUrl);
1688
2033
  let markText = text.trim();
1689
2034
  let assertion = null;
2035
+ let attestation = null;
1690
2036
  let observedDriftSec;
1691
- if (hasAssertion) {
2037
+ let failedForAbort = false;
2038
+ if (hasAttest) {
2039
+ // Driver-attested: Clipy vouches the agent SAID this, not that Clipy verified
2040
+ // it — falsifiable against the frames, weaker than clipy-verified. The lane
2041
+ // leads with a HEDGE glyph (≈) instead of ✓/✗ so a skimming reviewer reads it
2042
+ // as weaker at a glance, not just on inspection. Byte-identical to the CLI.
2043
+ const observedStr = String(opts.observed).slice(0, 500);
2044
+ attestation = { verdict: opts.verdict, observed: observedStr };
2045
+ if (opts.verdict === "pass") {
2046
+ session.attestPassed += 1;
2047
+ markText = `${markText} [≈ ASSERT driver-attested; observed=${observedStr}]`;
2048
+ }
2049
+ else {
2050
+ session.attestFailed += 1;
2051
+ markText = `${markText} [≈ FAILED driver-attested; observed=${observedStr}]`;
2052
+ failedForAbort = true;
2053
+ }
2054
+ }
2055
+ else if (hasAssertion) {
1692
2056
  try {
1693
2057
  assertion = await runMarkerAssertions(session.page, {
1694
2058
  assertSelector: opts.assertSelector,
@@ -1703,22 +2067,24 @@ async function applyMark(session, text, opts) {
1703
2067
  }
1704
2068
  if (assertion.status === "passed") {
1705
2069
  session.assertPassed += 1;
1706
- markText = `${markText} [assert ✓ ${assertion.observed}]`;
2070
+ markText = `${markText} [assert ✓ verified-by-clipy; ${assertion.observed}]`;
1707
2071
  }
1708
2072
  else if (assertion.status === "failed") {
1709
2073
  session.assertFailed += 1;
1710
- markText = `${markText} [ASSERT ✗ expected ${assertion.expected}; observed ${assertion.observed}]`;
2074
+ markText = `${markText} [ASSERT ✗ verified-by-clipy; expected ${assertion.expected}; observed ${assertion.observed}]`;
2075
+ failedForAbort = true;
1711
2076
  }
1712
2077
  else {
1713
2078
  session.assertUnverified += 1;
1714
- markText = `${markText} [ASSERT ⚠ could not evaluate — ${assertion.observed}]`;
2079
+ markText = `${markText} [ASSERT ⚠ clipy could not evaluate — ${assertion.observed}]`;
1715
2080
  }
1716
2081
  // A backdated mark (atSeconds) carries an assertion that was observed NOW —
1717
2082
  // right after the evaluate — not at the backdated position. Without atSeconds
1718
2083
  // the stamp IS the observation moment (sessionMark stamps after this await),
1719
2084
  // so there's nothing to reconcile. But when the stamp is decoupled and the
1720
2085
  // two diverge by more than ~2s, annotate it: the verdict must never read as
1721
- // if it pertained to a moment it didn't observe.
2086
+ // if it pertained to a moment it didn't observe. (Driver-attested has no Clipy
2087
+ // observation time, so this never applies to it.)
1722
2088
  if (opts.atSeconds != null) {
1723
2089
  const observedAtMs = Math.max(0, Date.now() - session.recordStartEpochMs);
1724
2090
  const markedAtMs = Math.max(0, Math.round(opts.atSeconds * 1000));
@@ -1732,28 +2098,31 @@ async function applyMark(session, text, opts) {
1732
2098
  }
1733
2099
  }
1734
2100
  const note = sessionMark(session, markText, opts.atSeconds != null ? opts.atSeconds * 1000 : undefined);
1735
- // failMode 'abort' discards the session ONLY on a definitive failure — never
1736
- // on an unverified claim (inability to check must not nuke the recording).
2101
+ // failMode 'abort' discards the session ONLY on a definitive FAILURE (clipy
2102
+ // assert failed, or driver attested a failure) — never on an unverified claim.
1737
2103
  let aborted = false;
1738
- if (assertion && assertion.status === "failed" && opts.failMode === "abort") {
2104
+ if (failedForAbort && opts.failMode === "abort") {
1739
2105
  await finishSession(session, "abort").catch(() => { });
1740
2106
  aborted = true;
1741
2107
  }
1742
- return { note, assertion, aborted, observedDriftSec };
2108
+ return { note, assertion, attestation, aborted, observedDriftSec };
1743
2109
  }
1744
2110
  /** Coerce a bridge-supplied (untrusted) options object into typed mark opts. */
1745
2111
  function coerceMarkOpts(raw) {
1746
2112
  const o = (raw && typeof raw === "object" ? raw : {});
1747
2113
  const str = (v) => (typeof v === "string" && v.trim() ? v : undefined);
1748
2114
  const failMode = o.failMode === "abort" ? "abort" : o.failMode === "warn" ? "warn" : undefined;
2115
+ const verdict = o.verdict === "pass" ? "pass" : o.verdict === "fail" ? "fail" : undefined;
1749
2116
  return {
1750
2117
  assertSelector: str(o.assertSelector),
1751
2118
  assertText: str(o.assertText),
1752
2119
  assertUrl: str(o.assertUrl),
1753
2120
  failMode,
2121
+ observed: str(o.observed),
2122
+ verdict,
1754
2123
  };
1755
2124
  }
1756
- server.tool("add_marker", "Drop a live-timestamped narration marker into the active recording session ('reproduced the bug', 'the fix renders correctly at mobile width'). Markers become the recording's transcript chapters, so narrate as you work — they are how the recording stays agent-readable despite having no audio. Optionally VERIFY on-screen state at the mark: assertSelector (element must exist), assertText (that element must contain the text — requires assertSelector), assertUrl (glob match on the live URL). A failed assertion is annotated into the mark as an explicit FAILURE (never written as fact), counted into the recording's verification summary, and — with failMode 'abort' — discards the whole session. Marks default to the live recording clock; pass atSeconds to backdate one.", {
2125
+ server.tool("add_marker", "Drop a live-timestamped narration marker into the active recording session ('reproduced the bug', 'the fix renders correctly at mobile width'). Markers become the recording's transcript chapters, so narrate as you work — they are how the recording stays agent-readable despite having no audio. A mark can carry evidence in ONE of two provenances, never both. (1) CLIPY-VERIFIED — assertSelector (element must exist), assertText (that element must contain the text; requires assertSelector), assertUrl (glob on the live URL): Clipy itself checks the recorded page, so this is the strongest evidence. (2) DRIVER-ATTESTED — observed + verdict (both required together): you report what YOUR tooling saw and whether it passed. Clipy vouches only that you SAID it — it did NOT verify it — which is falsifiable against the recorded frames: weaker than clipy-verified, far stronger than plain prose. Use driver-attested when your agent drives its OWN browser/tooling while Clipy records (e.g. via mac-screen) or when there is no Clipy-owned page to assert against. The two lanes are rendered so the weaker one LOOKS weaker at a glance: clipy-verified marks lead with a verdict glyph (`[assert ✓ verified-by-clipy; …]` / `[ASSERT ✗ verified-by-clipy; …]`), while driver-attested marks lead with a HEDGE glyph instead (`[≈ ASSERT driver-attested; observed=…]` / `[≈ FAILED driver-attested; observed=…]`) — a skimming reviewer must never mistake an attestation for a verification. Failures are annotated into the mark as explicit FAILURES (never written as fact), tallied in their own segment of the recording's verification summary, and — with failMode 'abort' — discard the whole session. Marks default to the live recording clock; pass atSeconds to backdate one.", {
1757
2126
  text: z.string().min(1).max(1000).describe("What is happening right now."),
1758
2127
  atSeconds: z
1759
2128
  .number()
@@ -1775,33 +2144,51 @@ server.tool("add_marker", "Drop a live-timestamped narration marker into the act
1775
2144
  failMode: z
1776
2145
  .enum(["warn", "abort"])
1777
2146
  .optional()
1778
- .describe("On a FAILED assertion: 'warn' (default) records the failure and keeps recording; 'abort' discards the whole session (like abort_recording) and returns loudly. A passing assertion never aborts."),
1779
- }, async ({ text, atSeconds, assertSelector, assertText, assertUrl, failMode }) => {
2147
+ .describe("On a FAILED outcome (a clipy-verified assertion that failed, or a driver-attested verdict of 'fail'): 'warn' (default) records the failure and keeps recording; 'abort' discards the whole session (like abort_recording) and returns loudly. A pass never aborts; an unverified claim never aborts."),
2148
+ observed: z
2149
+ .string()
2150
+ .optional()
2151
+ .describe("DRIVER-ATTESTED evidence: what YOUR tooling observed (e.g. 'HTTP 200, body contains orderId'). Requires verdict. Mutually exclusive with assertSelector/assertText/assertUrl — one provenance per mark."),
2152
+ verdict: z
2153
+ .enum(["pass", "fail"])
2154
+ .optional()
2155
+ .describe("DRIVER-ATTESTED outcome for `observed`. Requires observed. Mutually exclusive with assertSelector/assertText/assertUrl."),
2156
+ }, async ({ text, atSeconds, assertSelector, assertText, assertUrl, failMode, observed, verdict }) => {
1780
2157
  if (!activeSession || activeSession.finishing) {
1781
2158
  return fail("no active recording session — call start_recording first.");
1782
2159
  }
2160
+ // One provenance per mark: Clipy-verified OR driver-attested, never both.
2161
+ if ((observed != null || verdict != null) && (assertSelector || assertText || assertUrl)) {
2162
+ return fail("driver-attested (observed/verdict) and clipy-evaluated (assertSelector/assertText/assertUrl) are mutually exclusive — one provenance per mark. Pick the one that matches how the evidence was obtained.");
2163
+ }
2164
+ if ((observed != null) !== (verdict != null)) {
2165
+ return fail("observed and verdict must be provided together (both or neither) — an attested observation needs its verdict, and a verdict needs what was observed.");
2166
+ }
1783
2167
  // Stricter contract (matches the CLI): assertText needs a selector to name
1784
2168
  // WHICH element's text is checked — a whole-page-body match is weak evidence.
1785
2169
  if (assertText && !assertSelector) {
1786
2170
  return fail("assertText requires assertSelector — name the element whose text you're checking. A bare page-body text match is weak evidence, so it's rejected (same rule as the CLI's --assert-text / --assert-selector).");
1787
2171
  }
1788
2172
  const session = activeSession;
1789
- const { note, assertion, aborted, observedDriftSec } = await applyMark(session, text, {
2173
+ const { note, assertion, attestation, aborted, observedDriftSec } = await applyMark(session, text, {
1790
2174
  atSeconds,
1791
2175
  assertSelector,
1792
2176
  assertText,
1793
2177
  assertUrl,
1794
2178
  failMode,
2179
+ observed,
2180
+ verdict,
1795
2181
  });
1796
- if (aborted && assertion) {
2182
+ if (aborted) {
1797
2183
  return ok({
1798
2184
  aborted: true,
1799
2185
  assertionFailed: true,
2186
+ provenance: attestation ? "driver-attested" : "clipy-verified",
1800
2187
  marker: note.text,
1801
2188
  atSeconds: Math.round(note.startMs / 100) / 10,
1802
- expected: assertion.expected,
1803
- observed: assertion.observed,
1804
- note: "ASSERTION FAILED and failMode was 'abort' — the recording session was DISCARDED. Nothing was uploaded.",
2189
+ ...(assertion ? { expected: assertion.expected, observed: assertion.observed } : {}),
2190
+ ...(attestation ? { observed: attestation.observed, verdict: attestation.verdict } : {}),
2191
+ note: "FAILED outcome and failMode was 'abort' — the recording session was DISCARDED. Nothing was uploaded.",
1805
2192
  });
1806
2193
  }
1807
2194
  return ok({
@@ -1809,8 +2196,27 @@ server.tool("add_marker", "Drop a live-timestamped narration marker into the act
1809
2196
  text: note.text,
1810
2197
  ...(assertion
1811
2198
  ? assertion.status === "unverified"
1812
- ? { assertion: { verified: false, unverified: true, observed: assertion.observed }, unverified: true }
1813
- : { assertion: { passed: assertion.status === "passed", observed: assertion.observed } }
2199
+ ? {
2200
+ assertion: { provenance: "clipy-verified", verified: false, unverified: true, observed: assertion.observed },
2201
+ unverified: true,
2202
+ }
2203
+ : {
2204
+ assertion: {
2205
+ provenance: "clipy-verified",
2206
+ passed: assertion.status === "passed",
2207
+ observed: assertion.observed,
2208
+ },
2209
+ }
2210
+ : {}),
2211
+ ...(attestation
2212
+ ? {
2213
+ attestation: {
2214
+ provenance: "driver-attested",
2215
+ passed: attestation.verdict === "pass",
2216
+ observed: attestation.observed,
2217
+ note: "Clipy vouches that you REPORTED this — it did not verify it. Falsifiable against the recorded frames.",
2218
+ },
2219
+ }
1814
2220
  : {}),
1815
2221
  // Surface when a backdated mark's assertion was observed at a different
1816
2222
  // time than the mark position, so the caller knows the verdict is about
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@clipy/mcp",
3
- "version": "0.8.2",
3
+ "version": "0.8.4",
4
4
  "mcpName": "online.clipy/mcp",
5
5
  "description": "Model Context Protocol (MCP) server for Clipy — give Claude, Cursor, and other AI agents read access to your screen recordings' transcripts, AI summaries, and key moments with frames.",
6
6
  "license": "MIT",