@clipy/cli 0.8.1 → 0.8.3
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/README.md +110 -36
- package/dist/index.js +513 -91
- package/dist/skill.js +103 -29
- package/package.json +1 -1
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";
|
|
@@ -321,9 +321,12 @@ ${c.bold("RECORD")} ${c.dim("(needs an API key with the \"ingest\" permission)")
|
|
|
321
321
|
--cookie "n=v[; Domain=d; Path=p; Secure; HttpOnly; SameSite=Lax]" (repeatable)
|
|
322
322
|
--local-storage "k=v" Seed a localStorage pair for the target origin (repeatable)
|
|
323
323
|
--init-script <f> Run a JS file before every page load
|
|
324
|
-
--user-data-dir <d> Launch a persistent Chromium
|
|
325
|
-
logged-in identity). Excl. with --storage-state;
|
|
326
|
-
|
|
324
|
+
--user-data-dir <d> Launch from a persistent Chromium user-data ROOT (its
|
|
325
|
+
whole logged-in identity). Excl. with --storage-state;
|
|
326
|
+
pass the root, not a profile subdir
|
|
327
|
+
--profile-directory <name> With --user-data-dir: pick a named profile
|
|
328
|
+
(e.g. "Profile 12"). Clipy copies it to a temp root and
|
|
329
|
+
records the copy — real profile untouched, deleted after
|
|
327
330
|
|
|
328
331
|
${c.bold("SESSION")} ${c.dim("(agent works, Clipy records — one active session per directory)")}
|
|
329
332
|
${c.dim("--source mac-screen on record/session records the REAL screen via the")}
|
|
@@ -351,8 +354,15 @@ ${c.bold("SESSION")} ${c.dim("(agent works, Clipy records — one active session
|
|
|
351
354
|
CLIPY_CDP_URL with --expose-cdp). Crash-safe
|
|
352
355
|
wrapper for driver scripts — no dead-air uploads.
|
|
353
356
|
mark "<what just happened>" Drop a live timestamped note; marks become the
|
|
354
|
-
recording's transcript.
|
|
355
|
-
|
|
357
|
+
recording's transcript. Attach evidence — one
|
|
358
|
+
provenance per mark, never pooled:
|
|
359
|
+
--observed "<values>" --verdict pass|fail
|
|
360
|
+
DRIVER-ATTESTED: you drove the browser and report
|
|
361
|
+
what you saw (works in every session type, incl.
|
|
362
|
+
--source mac-screen). Clipy vouches you SAID it,
|
|
363
|
+
not that Clipy verified it — put real values here
|
|
364
|
+
--assert-selector <css> CLIPY-VERIFIED (Clipy-owned page only): assert an
|
|
365
|
+
element exists (observed text recorded)
|
|
356
366
|
--assert-text <substr> require that element's text to contain <substr>
|
|
357
367
|
--assert-url <glob> assert the page URL matches (**/* wildcards)
|
|
358
368
|
--fail-mode warn|abort warn (default) annotates ASSERT ✗; abort
|
|
@@ -1758,12 +1768,13 @@ async function applyAuthCapture(context, auth, targetUrl) {
|
|
|
1758
1768
|
if (auth.initScriptPath)
|
|
1759
1769
|
await context.addInitScript({ path: auth.initScriptPath });
|
|
1760
1770
|
}
|
|
1761
|
-
/** Validate a --user-data-dir before launch. It must exist
|
|
1762
|
-
*
|
|
1763
|
-
*
|
|
1764
|
-
*
|
|
1765
|
-
*
|
|
1766
|
-
|
|
1771
|
+
/** Validate a --user-data-dir before launch. It must exist, must be a user-data
|
|
1772
|
+
* ROOT (not a Chrome PROFILE subdir — Chromium would silently mint a blank
|
|
1773
|
+
* logged-out Default inside it), and, in direct-open mode (no --profile-directory),
|
|
1774
|
+
* must not be a profile a live Chrome is holding open. With a profileName the
|
|
1775
|
+
* named subdir must exist; the live-lock is handled by the copy path (a warn),
|
|
1776
|
+
* not a refusal, since we never open the real root. die(2) on any miss. */
|
|
1777
|
+
function validateUserDataDir(dir, profileName) {
|
|
1767
1778
|
let st;
|
|
1768
1779
|
try {
|
|
1769
1780
|
st = statSync(dir);
|
|
@@ -1773,12 +1784,187 @@ function validateUserDataDir(dir) {
|
|
|
1773
1784
|
}
|
|
1774
1785
|
if (!st.isDirectory())
|
|
1775
1786
|
die(`--user-data-dir is not a directory: ${dir}`, 2);
|
|
1787
|
+
// Reject a Chrome PROFILE directory passed as the root. Chrome stores profiles
|
|
1788
|
+
// as subdirs (Default, Profile 1, …) of the user-data ROOT (which holds
|
|
1789
|
+
// 'Local State'); pointing --user-data-dir at a profile makes Chromium treat it
|
|
1790
|
+
// as a root and create a blank Default inside the real profile.
|
|
1791
|
+
const base = basename(dir);
|
|
1792
|
+
const looksLikeProfileName = /^(Default|Profile \d+)$/.test(base);
|
|
1793
|
+
const hasProfileFiles = existsSync(join(dir, "Preferences")) ||
|
|
1794
|
+
existsSync(join(dir, "Cookies")) ||
|
|
1795
|
+
existsSync(join(dir, "History"));
|
|
1796
|
+
if (looksLikeProfileName || (hasProfileFiles && !existsSync(join(dir, "Local State")))) {
|
|
1797
|
+
die(`--user-data-dir looks like a Chrome PROFILE directory, not a user-data root: ${dir}\n` +
|
|
1798
|
+
`Pass the PARENT directory (the one containing 'Local State') plus --profile-directory '${looksLikeProfileName ? base : "<name>"}'.`, 2);
|
|
1799
|
+
}
|
|
1800
|
+
if (profileName != null) {
|
|
1801
|
+
// Copy mode: the named profile subdir must exist inside the root.
|
|
1802
|
+
if (!existsSync(join(dir, profileName))) {
|
|
1803
|
+
const profiles = (() => {
|
|
1804
|
+
try {
|
|
1805
|
+
return readdirSync(dir, { withFileTypes: true })
|
|
1806
|
+
.filter((e) => e.isDirectory() && /^(Default|Profile \d+)$/.test(e.name))
|
|
1807
|
+
.map((e) => e.name);
|
|
1808
|
+
}
|
|
1809
|
+
catch {
|
|
1810
|
+
return [];
|
|
1811
|
+
}
|
|
1812
|
+
})();
|
|
1813
|
+
die(`--profile-directory '${profileName}' not found under ${dir}` +
|
|
1814
|
+
(profiles.length ? ` (available: ${profiles.join(", ")})` : "") +
|
|
1815
|
+
`\nFind the exact folder name at chrome://version → "Profile Path".`, 2);
|
|
1816
|
+
}
|
|
1817
|
+
return; // the copy path handles a running Chrome (a warn), never opens the root
|
|
1818
|
+
}
|
|
1819
|
+
// Direct-open mode: refuse a profile a live Chrome is holding open.
|
|
1776
1820
|
for (const lock of ["SingletonLock", "SingletonSocket"]) {
|
|
1777
1821
|
if (existsSync(join(dir, lock))) {
|
|
1778
1822
|
die(`--user-data-dir looks like a live/locked Chrome profile (${lock} present): ${dir}\n` +
|
|
1779
1823
|
`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
1824
|
}
|
|
1781
1825
|
}
|
|
1826
|
+
// A bare --user-data-dir at a REAL Chrome installation opens its Default profile
|
|
1827
|
+
// IN PLACE — the recording browser can write to it. Warn (don't refuse: a quit
|
|
1828
|
+
// Chrome is a legitimate, if lossy, way to record). Scratch/dedicated roots have
|
|
1829
|
+
// no Local State + Default/Preferences pair and stay silent.
|
|
1830
|
+
if (existsSync(join(dir, "Local State")) && existsSync(join(dir, "Default", "Preferences"))) {
|
|
1831
|
+
process.stderr.write(`${c.yellow("warning:")} this opens your real Chrome Default profile in place — the recording browser can write to it; ` +
|
|
1832
|
+
`prefer --profile-directory '<name>' (records an ephemeral copy, original untouched) or --source mac-screen\n`);
|
|
1833
|
+
}
|
|
1834
|
+
}
|
|
1835
|
+
// --- --profile-directory: copy a named Chrome profile into a scratch root ----
|
|
1836
|
+
// Playwright's launchPersistentContext ignores --profile-directory (verified: the
|
|
1837
|
+
// switch is stripped and Default is always loaded), so selecting a named profile
|
|
1838
|
+
// means making it the Default of the root we open. We COPY <root>/<name> into a
|
|
1839
|
+
// temp scratch root's Default/ (+ the root's 'Local State') and launch against
|
|
1840
|
+
// that. The user's real profile is never opened or written. LOUD by design — this
|
|
1841
|
+
// whole track exists because silent profile substitution is the enemy.
|
|
1842
|
+
const PROFILE_COPY_PREFIX = "clipy-profile-";
|
|
1843
|
+
// Bulk cache dirs — identity lives in Cookies / Login Data / Local Storage /
|
|
1844
|
+
// Preferences, so we skip these to keep the copy small.
|
|
1845
|
+
const PROFILE_SKIP_TOP = new Set(["Cache", "Code Cache", "GPUCache"]);
|
|
1846
|
+
const SW_CACHE_FRAGMENT = join("Service Worker", "CacheStorage");
|
|
1847
|
+
/** Bytes we'll actually copy (identity, minus the skipped cache dirs). */
|
|
1848
|
+
function profileCopyableSize(profileDir) {
|
|
1849
|
+
let total = 0;
|
|
1850
|
+
const walk = (p, top) => {
|
|
1851
|
+
let entries;
|
|
1852
|
+
try {
|
|
1853
|
+
entries = readdirSync(p, { withFileTypes: true });
|
|
1854
|
+
}
|
|
1855
|
+
catch {
|
|
1856
|
+
return;
|
|
1857
|
+
}
|
|
1858
|
+
for (const e of entries) {
|
|
1859
|
+
if (top && (e.name.startsWith("Singleton") || PROFILE_SKIP_TOP.has(e.name)))
|
|
1860
|
+
continue;
|
|
1861
|
+
const full = join(p, e.name);
|
|
1862
|
+
if (full.includes(SW_CACHE_FRAGMENT))
|
|
1863
|
+
continue;
|
|
1864
|
+
try {
|
|
1865
|
+
if (e.isDirectory())
|
|
1866
|
+
walk(full, false);
|
|
1867
|
+
else
|
|
1868
|
+
total += statSync(full).size;
|
|
1869
|
+
}
|
|
1870
|
+
catch {
|
|
1871
|
+
// unreadable — skip
|
|
1872
|
+
}
|
|
1873
|
+
}
|
|
1874
|
+
};
|
|
1875
|
+
walk(profileDir, true);
|
|
1876
|
+
return total;
|
|
1877
|
+
}
|
|
1878
|
+
/** Copy <userDataDir>/<profileName> into a fresh 0700 scratch root's Default/
|
|
1879
|
+
* (plus the root's 'Local State'), skipping Singleton-locks and cache dirs.
|
|
1880
|
+
* Prints the loud disclosure and a running-Chrome warning. Best-effort per
|
|
1881
|
+
* top-level entry, so a locked file loses only that entry. Returns the scratch
|
|
1882
|
+
* root to launch against. */
|
|
1883
|
+
function copyProfileToScratchRoot(userDataDir, profileName, log) {
|
|
1884
|
+
const srcProfile = join(userDataDir, profileName);
|
|
1885
|
+
if (existsSync(join(userDataDir, "SingletonLock")) || existsSync(join(userDataDir, "SingletonSocket"))) {
|
|
1886
|
+
log(c.yellow("warning: Chrome appears to be running — in-use databases may copy inconsistently; quit Chrome for a guaranteed-clean copy"));
|
|
1887
|
+
}
|
|
1888
|
+
const size = profileCopyableSize(srcProfile);
|
|
1889
|
+
// LOUD, always — the user must know their profile is being copied (never silent).
|
|
1890
|
+
log(`${c.dim("→")} copying profile '${profileName}' (${fmtBytes(size)}) into a temporary recording root — ` +
|
|
1891
|
+
`your real profile is never modified; the copy carries your logged-in identity and is deleted after upload`);
|
|
1892
|
+
// FALSE-IDENTITY GUARD (macOS): Chrome encrypts its cookies with a Keychain key
|
|
1893
|
+
// scoped to "Chrome Safe Storage", but the recorder runs Playwright's Chromium,
|
|
1894
|
+
// which reads "Chromium Safe Storage" — so a copied real-Chrome profile can open
|
|
1895
|
+
// LOOKING like the user (bookmarks, prefs, localStorage) while being silently
|
|
1896
|
+
// signed out. That's the exact class --profile-directory exists to prevent, so it
|
|
1897
|
+
// is a loud warning, never a docs footnote.
|
|
1898
|
+
if (process.platform === "darwin") {
|
|
1899
|
+
log(c.yellow("warning: On macOS, cookie-based logins in a real Chrome profile may not decrypt under the recorder's Chromium " +
|
|
1900
|
+
"(Chrome and Chromium use different Keychain keys) — localStorage/Preferences sessions survive. " +
|
|
1901
|
+
"If the recording lands logged out, that's why: record your real browser with --source mac-screen, " +
|
|
1902
|
+
"or drive your own browser and attach evidence with --observed/--verdict."));
|
|
1903
|
+
}
|
|
1904
|
+
const scratchRoot = join(tmpdir(), `${PROFILE_COPY_PREFIX}${randomUUID()}`);
|
|
1905
|
+
mkdirSync(scratchRoot, { recursive: true });
|
|
1906
|
+
try {
|
|
1907
|
+
chmodSync(scratchRoot, 0o700);
|
|
1908
|
+
}
|
|
1909
|
+
catch {
|
|
1910
|
+
// best-effort on platforms without POSIX modes
|
|
1911
|
+
}
|
|
1912
|
+
const destDefault = join(scratchRoot, "Default");
|
|
1913
|
+
mkdirSync(destDefault, { recursive: true });
|
|
1914
|
+
const skipped = [];
|
|
1915
|
+
for (const entry of readdirSync(srcProfile, { withFileTypes: true })) {
|
|
1916
|
+
const name = entry.name;
|
|
1917
|
+
if (name.startsWith("Singleton") || PROFILE_SKIP_TOP.has(name))
|
|
1918
|
+
continue;
|
|
1919
|
+
try {
|
|
1920
|
+
cpSync(join(srcProfile, name), join(destDefault, name), {
|
|
1921
|
+
recursive: true,
|
|
1922
|
+
// Skip the bulk CacheStorage nested under Service Worker.
|
|
1923
|
+
filter: (s) => !s.includes(SW_CACHE_FRAGMENT),
|
|
1924
|
+
});
|
|
1925
|
+
}
|
|
1926
|
+
catch {
|
|
1927
|
+
skipped.push(name); // locked/unreadable — best-effort
|
|
1928
|
+
}
|
|
1929
|
+
}
|
|
1930
|
+
// 'Local State' lives at the root and carries the os_crypt key Linux uses to
|
|
1931
|
+
// decrypt Cookies/Login Data (harmless elsewhere — macOS keys off the Keychain).
|
|
1932
|
+
try {
|
|
1933
|
+
if (existsSync(join(userDataDir, "Local State"))) {
|
|
1934
|
+
cpSync(join(userDataDir, "Local State"), join(scratchRoot, "Local State"));
|
|
1935
|
+
}
|
|
1936
|
+
}
|
|
1937
|
+
catch {
|
|
1938
|
+
// best-effort
|
|
1939
|
+
}
|
|
1940
|
+
if (skipped.length) {
|
|
1941
|
+
log(c.yellow(`note: skipped ${skipped.length} locked/unreadable profile entr${skipped.length === 1 ? "y" : "ies"} (${skipped.join(", ")})`));
|
|
1942
|
+
}
|
|
1943
|
+
return scratchRoot;
|
|
1944
|
+
}
|
|
1945
|
+
/** Remove stranded profile copies (a SIGKILL between copy and cleanup can leave
|
|
1946
|
+
* one). Swept at the start of every record/session start. Best-effort. */
|
|
1947
|
+
function sweepStaleProfileCopies() {
|
|
1948
|
+
const now = Date.now();
|
|
1949
|
+
let entries;
|
|
1950
|
+
try {
|
|
1951
|
+
entries = readdirSync(tmpdir(), { withFileTypes: true });
|
|
1952
|
+
}
|
|
1953
|
+
catch {
|
|
1954
|
+
return;
|
|
1955
|
+
}
|
|
1956
|
+
for (const e of entries) {
|
|
1957
|
+
if (!e.isDirectory() || !e.name.startsWith(PROFILE_COPY_PREFIX))
|
|
1958
|
+
continue;
|
|
1959
|
+
const full = join(tmpdir(), e.name);
|
|
1960
|
+
try {
|
|
1961
|
+
if (now - statSync(full).mtimeMs > 24 * 3600 * 1000)
|
|
1962
|
+
rmSync(full, { recursive: true, force: true });
|
|
1963
|
+
}
|
|
1964
|
+
catch {
|
|
1965
|
+
// best-effort
|
|
1966
|
+
}
|
|
1967
|
+
}
|
|
1782
1968
|
}
|
|
1783
1969
|
/** Launch a recording context. With userDataDir: a PERSISTENT context bound to
|
|
1784
1970
|
* that dir (launchPersistentContext — it IS the context, there's no separate
|
|
@@ -1820,8 +2006,9 @@ async function cmdRecord(ctx, opts) {
|
|
|
1820
2006
|
}
|
|
1821
2007
|
validateAuthCapture(opts.auth, target.href); // usage errors (exit 2) before auth/browser
|
|
1822
2008
|
if (opts.userDataDir)
|
|
1823
|
-
validateUserDataDir(opts.userDataDir);
|
|
2009
|
+
validateUserDataDir(opts.userDataDir, opts.profileDirectory);
|
|
1824
2010
|
requireKey(ctx); // fail fast before we spin up a browser
|
|
2011
|
+
sweepStaleProfileCopies(); // clear any profile copy a prior SIGKILL stranded
|
|
1825
2012
|
const chromium = await loadChromium();
|
|
1826
2013
|
const tmpDir = join(tmpdir(), `clipy-record-${randomUUID()}`);
|
|
1827
2014
|
mkdirSync(tmpDir, { recursive: true });
|
|
@@ -1829,6 +2016,18 @@ async function cmdRecord(ctx, opts) {
|
|
|
1829
2016
|
if (!opts.json)
|
|
1830
2017
|
process.stderr.write(`${m}\n`);
|
|
1831
2018
|
};
|
|
2019
|
+
// --profile-directory ⇒ copy the named profile into a scratch root's Default and
|
|
2020
|
+
// launch against THAT (Playwright can't select a named profile in-place). The
|
|
2021
|
+
// copy is disclosed loudly and cleaned up in the finally below. Always writes
|
|
2022
|
+
// the disclosure to stderr, even under --json (no silent profile substitution).
|
|
2023
|
+
let profileScratchRoot;
|
|
2024
|
+
const launchUserDataDir = (() => {
|
|
2025
|
+
if (opts.userDataDir && opts.profileDirectory) {
|
|
2026
|
+
profileScratchRoot = copyProfileToScratchRoot(opts.userDataDir, opts.profileDirectory, (m) => process.stderr.write(`${m}\n`));
|
|
2027
|
+
return profileScratchRoot;
|
|
2028
|
+
}
|
|
2029
|
+
return opts.userDataDir;
|
|
2030
|
+
})();
|
|
1832
2031
|
// Multi-viewport mode records every size sequentially into ONE video; the
|
|
1833
2032
|
// frame is sized to the largest viewport and smaller passes letterbox
|
|
1834
2033
|
// inside it. Each pass emits an auto note so the transcript chapters the
|
|
@@ -1861,7 +2060,7 @@ async function cmdRecord(ctx, opts) {
|
|
|
1861
2060
|
// browser sandbox isn't a trust boundary here. --user-data-dir ⇒ a persistent
|
|
1862
2061
|
// context (its own browser); else an ephemeral browser + context.
|
|
1863
2062
|
const { context, browser } = await launchRecordingContext(chromium, {
|
|
1864
|
-
userDataDir:
|
|
2063
|
+
userDataDir: launchUserDataDir,
|
|
1865
2064
|
viewport: frame,
|
|
1866
2065
|
recordVideoDir: tmpDir,
|
|
1867
2066
|
args: ["--no-sandbox", "--disable-dev-shm-usage"],
|
|
@@ -1954,6 +2153,14 @@ async function cmdRecord(ctx, opts) {
|
|
|
1954
2153
|
catch {
|
|
1955
2154
|
// best-effort temp cleanup
|
|
1956
2155
|
}
|
|
2156
|
+
if (profileScratchRoot) {
|
|
2157
|
+
try {
|
|
2158
|
+
rmSync(profileScratchRoot, { recursive: true, force: true });
|
|
2159
|
+
}
|
|
2160
|
+
catch {
|
|
2161
|
+
// best-effort — the 24h sweep will catch a stranded copy
|
|
2162
|
+
}
|
|
2163
|
+
}
|
|
1957
2164
|
}
|
|
1958
2165
|
if (opts.wait && uploaded.publicId) {
|
|
1959
2166
|
log(`${c.dim("waiting for transcript…")}`);
|
|
@@ -2050,6 +2257,38 @@ function cleanupSessionFiles(state, file) {
|
|
|
2050
2257
|
}
|
|
2051
2258
|
}
|
|
2052
2259
|
}
|
|
2260
|
+
/** Annotation for a mark Clipy itself evaluated against its own live page. */
|
|
2261
|
+
function verifiedMarkAnnotation(passed, expected, observed) {
|
|
2262
|
+
return passed
|
|
2263
|
+
? `[assert ✓ verified-by-clipy; ${observed}]`
|
|
2264
|
+
: `[ASSERT ✗ verified-by-clipy; expected ${expected}; observed ${observed}]`;
|
|
2265
|
+
}
|
|
2266
|
+
/** Annotation for a mark the DRIVER attested — Clipy records the claim and the
|
|
2267
|
+
* agent's observed values, and never presents it as its own verification. */
|
|
2268
|
+
function attestedMarkAnnotation(verdict, observed) {
|
|
2269
|
+
return `[ASSERT ${verdict === "pass" ? "✓" : "✗"} driver-attested; observed=${observed}]`;
|
|
2270
|
+
}
|
|
2271
|
+
/** The leading [verification] note. The two provenances are SEPARATE segments and
|
|
2272
|
+
* are never pooled: clipy-verified (what Clipy checked against its own page) vs
|
|
2273
|
+
* driver-attested (what the agent reported). With only clipy-verified marks the
|
|
2274
|
+
* rendering stays byte-identical to the pre-0.8.3 single-segment form, so existing
|
|
2275
|
+
* consumers don't churn. Returns [] when nothing was asserted. */
|
|
2276
|
+
function verificationNote(t) {
|
|
2277
|
+
const clipyN = t.clipyPassed + t.clipyFailed + t.clipyUnverified;
|
|
2278
|
+
const driverN = t.driverPassed + t.driverFailed;
|
|
2279
|
+
if (clipyN === 0 && driverN === 0)
|
|
2280
|
+
return [];
|
|
2281
|
+
const clipyBody = `${t.clipyPassed} passed, ${t.clipyFailed} failed` +
|
|
2282
|
+
(t.clipyUnverified > 0 ? `, ${t.clipyUnverified} unverified` : "");
|
|
2283
|
+
if (driverN === 0) {
|
|
2284
|
+
return [{ startMs: 0, text: `[verification] ${clipyN} assertion(s): ${clipyBody}` }];
|
|
2285
|
+
}
|
|
2286
|
+
const segments = [];
|
|
2287
|
+
if (clipyN > 0)
|
|
2288
|
+
segments.push(`${clipyN} clipy-verified: ${clipyBody}`);
|
|
2289
|
+
segments.push(`${driverN} driver-attested: ${t.driverPassed} passed, ${t.driverFailed} failed`);
|
|
2290
|
+
return [{ startMs: 0, text: `[verification] ${segments.join(" · ")}` }];
|
|
2291
|
+
}
|
|
2053
2292
|
/** Compile a URL glob to a RegExp: `**` → `.*`, a lone `*` → `[^/]*`, every
|
|
2054
2293
|
* other regex metachar escaped. A glob with NO `*` is treated as a bare
|
|
2055
2294
|
* substring match (the common "is this path in the URL" case). */
|
|
@@ -2307,9 +2546,10 @@ async function cmdSessionStart(ctx, opts) {
|
|
|
2307
2546
|
}
|
|
2308
2547
|
validateAuthCapture(opts.auth, target.href); // usage errors (exit 2) before auth/daemonizing
|
|
2309
2548
|
if (opts.userDataDir)
|
|
2310
|
-
validateUserDataDir(opts.userDataDir);
|
|
2549
|
+
validateUserDataDir(opts.userDataDir, opts.profileDirectory);
|
|
2311
2550
|
const key = requireKey(ctx);
|
|
2312
2551
|
await loadChromium(); // fail fast with install instructions before daemonizing
|
|
2552
|
+
sweepStaleProfileCopies();
|
|
2313
2553
|
const file = sessionFilePath(process.cwd());
|
|
2314
2554
|
const existing = readSessionState(file);
|
|
2315
2555
|
if (existing && sessionIsActive(existing)) {
|
|
@@ -2318,6 +2558,14 @@ async function cmdSessionStart(ctx, opts) {
|
|
|
2318
2558
|
}
|
|
2319
2559
|
if (existing)
|
|
2320
2560
|
cleanupSessionFiles(existing, file); // stale (daemon died) — clear
|
|
2561
|
+
// --profile-directory ⇒ copy the named profile into a scratch root HERE, in the
|
|
2562
|
+
// parent, so the user sees the loud disclosure (the daemon's stdout goes to a
|
|
2563
|
+
// log). The daemon launches against the scratch root and removes it at stop/abort;
|
|
2564
|
+
// profileScratchRoot flags it. Disclosure always to stderr, even under --json.
|
|
2565
|
+
let profileScratchRoot;
|
|
2566
|
+
const launchUserDataDir = opts.userDataDir && opts.profileDirectory
|
|
2567
|
+
? (profileScratchRoot = copyProfileToScratchRoot(opts.userDataDir, opts.profileDirectory, (m) => process.stderr.write(`${m}\n`)))
|
|
2568
|
+
: opts.userDataDir;
|
|
2321
2569
|
const maxSec = Math.min(Math.max(1, opts.maxSec), SESSION_HARD_CAP_SEC);
|
|
2322
2570
|
const id = randomUUID();
|
|
2323
2571
|
const dir = sessionDir();
|
|
@@ -2338,7 +2586,8 @@ async function cmdSessionStart(ctx, opts) {
|
|
|
2338
2586
|
initScriptPath: opts.auth.initScriptPath,
|
|
2339
2587
|
cookieSpecs: opts.auth.cookieSpecs.length ? opts.auth.cookieSpecs : undefined,
|
|
2340
2588
|
localStorageSpecs: opts.auth.localStorageSpecs.length ? opts.auth.localStorageSpecs : undefined,
|
|
2341
|
-
userDataDir:
|
|
2589
|
+
userDataDir: launchUserDataDir,
|
|
2590
|
+
profileScratchRoot,
|
|
2342
2591
|
state: "starting",
|
|
2343
2592
|
marksPath: join(dir, `marks-${id}.jsonl`),
|
|
2344
2593
|
controlPath: join(dir, `control-${id}.json`),
|
|
@@ -2427,29 +2676,42 @@ function printMarkResult(res, json) {
|
|
|
2427
2676
|
async function cmdMark(text, json, opts) {
|
|
2428
2677
|
const { file, state } = requireSession();
|
|
2429
2678
|
const hasAssert = !!opts.assert;
|
|
2679
|
+
const attest = opts.attest;
|
|
2430
2680
|
const backdated = opts.atSec != null || opts.agoSec != null;
|
|
2431
2681
|
if (state.kind === "mac") {
|
|
2432
|
-
// The Mac app records the real screen — there is no page to probe,
|
|
2433
|
-
//
|
|
2434
|
-
//
|
|
2682
|
+
// The Mac app records the real screen — there is no Clipy-owned page to probe,
|
|
2683
|
+
// so Clipy-EVALUATED assertions can't run here. Driver-attested marks CAN: the
|
|
2684
|
+
// agent brings its own observation and Clipy holds the ledger.
|
|
2435
2685
|
if (hasAssert) {
|
|
2436
|
-
die("assertions need a
|
|
2686
|
+
die("Clipy-evaluated assertions need a Clipy-owned page — use --observed/--verdict to attach evidence you collected yourself", 2);
|
|
2437
2687
|
}
|
|
2438
2688
|
if (backdated) {
|
|
2439
2689
|
die("--at/--ago need a web session — the Mac bridge stamps each mark on its own clock", 2);
|
|
2440
2690
|
}
|
|
2441
|
-
|
|
2691
|
+
// Driver-attested: annotate here (nothing to evaluate) and keep a CLI-side
|
|
2692
|
+
// tally in the session file — there's no daemon to compute one, so
|
|
2693
|
+
// `session stop` emits the [verification] summary as a final bridge mark.
|
|
2694
|
+
const macText = attest ? `${text.trim()} ${attestedMarkAnnotation(attest.verdict, attest.observed)}` : text;
|
|
2695
|
+
const result = await bridgeRequest(bridgeInfoFromSession(state), "mark", { text: macText }).catch((e) => {
|
|
2442
2696
|
if (e instanceof BridgeUnavailableError) {
|
|
2443
2697
|
cleanupSessionFiles(state, file);
|
|
2444
2698
|
die("the Clipy app is no longer running — session cleared. Start a new one.");
|
|
2445
2699
|
}
|
|
2446
2700
|
die(e.message);
|
|
2447
2701
|
});
|
|
2702
|
+
if (attest) {
|
|
2703
|
+
if (attest.verdict === "pass")
|
|
2704
|
+
state.attestedPassed = (state.attestedPassed ?? 0) + 1;
|
|
2705
|
+
else
|
|
2706
|
+
state.attestedFailed = (state.attestedFailed ?? 0) + 1;
|
|
2707
|
+
writeSessionState(file, state);
|
|
2708
|
+
}
|
|
2448
2709
|
if (json) {
|
|
2449
|
-
printJson(result);
|
|
2710
|
+
printJson({ ...result, text: macText, ...(attest ? { assert: { passed: attest.verdict === "pass", observed: attest.observed, attested: true } } : {}) });
|
|
2450
2711
|
return;
|
|
2451
2712
|
}
|
|
2452
|
-
|
|
2713
|
+
const glyph = attest && attest.verdict === "fail" ? c.red("✗") : c.green("✓");
|
|
2714
|
+
process.stdout.write(`${glyph} mark @ ${Number(result.atSeconds ?? 0).toFixed(1)}s — ${macText}\n`);
|
|
2453
2715
|
return;
|
|
2454
2716
|
}
|
|
2455
2717
|
if (!pidAlive(state.pid)) {
|
|
@@ -2481,14 +2743,23 @@ async function cmdMark(text, json, opts) {
|
|
|
2481
2743
|
text: cleanText,
|
|
2482
2744
|
...(atMs != null ? { atMs } : {}),
|
|
2483
2745
|
...(hasAssert ? { assert: opts.assert } : {}),
|
|
2746
|
+
...(attest ? { attest } : {}),
|
|
2484
2747
|
}, CONTROL_TIMEOUT_MS);
|
|
2485
2748
|
}
|
|
2486
2749
|
catch (e) {
|
|
2487
2750
|
const reason = String(e.message).slice(0, 120);
|
|
2488
2751
|
// NEVER drop a mark. If the daemon didn't answer, record the narration to
|
|
2489
|
-
// the file regardless.
|
|
2490
|
-
//
|
|
2491
|
-
|
|
2752
|
+
// the file regardless. A driver-attested mark needs no evaluation, so the
|
|
2753
|
+
// client annotates it here and it still counts in the driver segment.
|
|
2754
|
+
if (attest) {
|
|
2755
|
+
const annotated = `${cleanText} ${attestedMarkAnnotation(attest.verdict, attest.observed)}`;
|
|
2756
|
+
appendFileSync(state.marksPath, `${JSON.stringify({ id: markId, tMs: localTMs, text: annotated, attested: true, verdict: attest.verdict })}\n`, { mode: 0o600 });
|
|
2757
|
+
printMarkResult({ tMs: localTMs, text: annotated, assert: { passed: attest.verdict === "pass", observed: attest.observed, attested: true } }, json);
|
|
2758
|
+
return;
|
|
2759
|
+
}
|
|
2760
|
+
// For an ASSERTED mark we couldn't verify the claim, so tag it honestly
|
|
2761
|
+
// ⚠ UNVERIFIED (never a silent pass) — the daemon counts {unverified:true}
|
|
2762
|
+
// file marks into the clipy segment's third bucket.
|
|
2492
2763
|
if (hasAssert) {
|
|
2493
2764
|
const annotated = `${cleanText} [ASSERT ⚠ could not evaluate — ${reason}]`;
|
|
2494
2765
|
appendFileSync(state.marksPath, `${JSON.stringify({ id: markId, tMs: localTMs, text: annotated, unverified: true })}\n`, { mode: 0o600 });
|
|
@@ -2513,7 +2784,14 @@ async function cmdMark(text, json, opts) {
|
|
|
2513
2784
|
printMarkResult(res, json);
|
|
2514
2785
|
return;
|
|
2515
2786
|
}
|
|
2516
|
-
// No control endpoint (session started by a pre-0.6 CLI):
|
|
2787
|
+
// No control endpoint (session started by a pre-0.6 CLI): Clipy can't evaluate
|
|
2788
|
+
// anything, but a driver-attested mark needs no evaluation — annotate + record it.
|
|
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
|
+
}
|
|
2517
2795
|
if (hasAssert) {
|
|
2518
2796
|
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
2797
|
}
|
|
@@ -2580,6 +2858,20 @@ async function cmdSessionStop(json) {
|
|
|
2580
2858
|
if (state.kind === "mac") {
|
|
2581
2859
|
if (!json)
|
|
2582
2860
|
process.stderr.write(`${c.dim("stopping + uploading…")}\n`);
|
|
2861
|
+
// No daemon on the mac path to merge a tally, so emit the [verification]
|
|
2862
|
+
// summary ourselves as a final bridge mark (stamped at stop) BEFORE stopping.
|
|
2863
|
+
const macTally = verificationNote({
|
|
2864
|
+
clipyPassed: 0,
|
|
2865
|
+
clipyFailed: 0,
|
|
2866
|
+
clipyUnverified: 0,
|
|
2867
|
+
driverPassed: state.attestedPassed ?? 0,
|
|
2868
|
+
driverFailed: state.attestedFailed ?? 0,
|
|
2869
|
+
});
|
|
2870
|
+
if (macTally.length) {
|
|
2871
|
+
await bridgeRequest(bridgeInfoFromSession(state), "mark", { text: macTally[0].text }).catch(() => {
|
|
2872
|
+
// best-effort: never block the stop on the summary mark
|
|
2873
|
+
});
|
|
2874
|
+
}
|
|
2583
2875
|
const result = await bridgeRequest(bridgeInfoFromSession(state), "stop").catch((e) => {
|
|
2584
2876
|
cleanupSessionFiles(state, file);
|
|
2585
2877
|
die(e.message);
|
|
@@ -2931,27 +3223,15 @@ async function runSessionDaemon(file) {
|
|
|
2931
3223
|
return;
|
|
2932
3224
|
autoMarks.push({ startMs: Math.max(0, Date.now() - recordStart), text });
|
|
2933
3225
|
};
|
|
2934
|
-
// Marks that arrive over the control endpoint (`clipy mark`/`chapter`) or the
|
|
2935
|
-
// in-page __clipyMark/__clipyChapter bindings. Kept in memory (like autoMarks)
|
|
2936
|
-
// and merged at stop. A hard 200 cap here is the server limit; storeDaemonMark
|
|
2937
|
-
// refuses past it so `clipy mark` gets an error rather than a silent drop.
|
|
2938
3226
|
const daemonMarks = [];
|
|
2939
|
-
const storeDaemonMark = (
|
|
3227
|
+
const storeDaemonMark = (m) => {
|
|
2940
3228
|
if (daemonMarks.length >= 200)
|
|
2941
3229
|
return false;
|
|
2942
|
-
daemonMarks.push(
|
|
3230
|
+
daemonMarks.push(m);
|
|
2943
3231
|
return true;
|
|
2944
3232
|
};
|
|
2945
|
-
// Assertion tallies → the leading [verification] note at stop.
|
|
2946
|
-
let assertRan = 0;
|
|
2947
|
-
let assertPassed = 0;
|
|
2948
|
-
let assertFailed = 0;
|
|
2949
3233
|
// A failed --fail-mode=abort assertion sets this; the main loop discards.
|
|
2950
3234
|
let controlSignal = null;
|
|
2951
|
-
// Client-generated ids of marks/chapters we processed over HTTP — so at merge
|
|
2952
|
-
// we can drop a file duplicate the client wrote after its call timed out but
|
|
2953
|
-
// the daemon actually completed it.
|
|
2954
|
-
const processedMarkIds = new Set();
|
|
2955
3235
|
mkdirSync(state.tmpDir, { recursive: true });
|
|
2956
3236
|
let browser = null;
|
|
2957
3237
|
// Persistent (--user-data-dir) contexts have no separate browser, so track the
|
|
@@ -3044,31 +3324,53 @@ async function runSessionDaemon(file) {
|
|
|
3044
3324
|
const tMs = typeof m.atMs === "number" && Number.isFinite(m.atMs)
|
|
3045
3325
|
? Math.max(0, Math.round(m.atMs))
|
|
3046
3326
|
: Math.max(0, Date.now() - recordStart);
|
|
3327
|
+
const evalAtMs = Math.max(0, Date.now() - recordStart);
|
|
3047
3328
|
let annotated = text;
|
|
3048
3329
|
let assertOut;
|
|
3330
|
+
let assertOutcome;
|
|
3049
3331
|
let aborted = false;
|
|
3050
|
-
if (m.
|
|
3332
|
+
if (m.attest && typeof m.attest === "object") {
|
|
3333
|
+
// DRIVER-ATTESTED: the agent brought its own observation. Clipy evaluates
|
|
3334
|
+
// nothing here — it records the claim + the agent's observed values, labeled
|
|
3335
|
+
// so it can never be read as a Clipy verification.
|
|
3336
|
+
const passed = m.attest.verdict === "pass";
|
|
3337
|
+
annotated = `${text} ${attestedMarkAnnotation(m.attest.verdict, m.attest.observed)}`;
|
|
3338
|
+
assertOut = { passed, observed: m.attest.observed, attested: true };
|
|
3339
|
+
assertOutcome = { kind: "driver", passed, expected: "", observed: m.attest.observed };
|
|
3340
|
+
}
|
|
3341
|
+
else if (m.assert && typeof m.assert === "object") {
|
|
3051
3342
|
// evaluateAssertion throws if the page is unresponsive — the HTTP path
|
|
3052
3343
|
// turns that into a 5xx (the CLI then records a ⚠ UNVERIFIED file mark),
|
|
3053
3344
|
// and the in-page path rejects to the driver.
|
|
3054
3345
|
const ev = await evaluateAssertion(page, m.assert);
|
|
3055
|
-
|
|
3056
|
-
if (ev.passed)
|
|
3057
|
-
assertPassed++;
|
|
3058
|
-
else
|
|
3059
|
-
assertFailed++;
|
|
3060
|
-
annotated = ev.passed
|
|
3061
|
-
? `${text} [assert ✓ ${ev.observed}]`
|
|
3062
|
-
: `${text} [ASSERT ✗ expected ${ev.expected}; observed ${ev.observed}]`;
|
|
3346
|
+
annotated = `${text} ${verifiedMarkAnnotation(ev.passed, ev.expected, ev.observed)}`;
|
|
3063
3347
|
assertOut = { passed: ev.passed, observed: ev.observed };
|
|
3348
|
+
assertOutcome = { kind: "clipy", passed: ev.passed, expected: ev.expected, observed: ev.observed };
|
|
3064
3349
|
if (!ev.passed && m.assert.failMode === "abort")
|
|
3065
3350
|
aborted = true;
|
|
3351
|
+
// Backdated assertion divergence: a --at/--ago mark is stamped in the past
|
|
3352
|
+
// but the assertion judged the LIVE page. If the verdict was observed more
|
|
3353
|
+
// than 2s from the backdated position, keep the mark where the agent put it
|
|
3354
|
+
// but say so in the text (and expose a signed drift), so the ✓/✗ isn't read
|
|
3355
|
+
// as describing the page at the backdated moment. Live-clock asserted marks
|
|
3356
|
+
// (no atMs) and backdated PLAIN marks get nothing.
|
|
3357
|
+
if (m.atMs != null) {
|
|
3358
|
+
const driftMs = evalAtMs - tMs; // + = observed AFTER the backdated stamp
|
|
3359
|
+
if (Math.abs(driftMs) > 2000) {
|
|
3360
|
+
const n = Math.round(Math.abs(driftMs) / 1000);
|
|
3361
|
+
const dir = driftMs >= 0 ? "after" : "before";
|
|
3362
|
+
annotated += ` (assertion observed ${n}s ${dir} this backdated mark — the verdict describes the page at observation time)`;
|
|
3363
|
+
assertOut.driftSec = Math.round(driftMs / 1000); // signed, for --json
|
|
3364
|
+
}
|
|
3365
|
+
}
|
|
3066
3366
|
}
|
|
3067
|
-
|
|
3367
|
+
// Store the provisional mark of record at the claim time. The merge decides
|
|
3368
|
+
// whether it stays the record (no client timeout) or becomes a late check
|
|
3369
|
+
// (the client already wrote a ⚠ mark of record for this id). P/F is counted
|
|
3370
|
+
// at merge from assertOutcome, so a late eval never lands in the tally.
|
|
3371
|
+
if (!storeDaemonMark({ startMs: tMs, text: annotated, id: m.id, evalAtMs, claim: text, assertOutcome })) {
|
|
3068
3372
|
throw new Error("mark limit reached (200 marks per recording)");
|
|
3069
3373
|
}
|
|
3070
|
-
if (m.id)
|
|
3071
|
-
processedMarkIds.add(m.id);
|
|
3072
3374
|
if (aborted)
|
|
3073
3375
|
controlSignal = "abort";
|
|
3074
3376
|
return {
|
|
@@ -3084,9 +3386,12 @@ async function runSessionDaemon(file) {
|
|
|
3084
3386
|
// daemon-side assertion + annotation as the CLI flags, at ZERO spawn cost.
|
|
3085
3387
|
// NOTE: while CDP is exposed the page's own scripts can call these too —
|
|
3086
3388
|
// within the existing --expose-cdp trust model (documented in the README).
|
|
3389
|
+
// The bindings are exposed under *Impl names and re-declared with explicit
|
|
3390
|
+
// arity below, so an agent probing window.__clipyMark.length sees 2 (not the
|
|
3391
|
+
// 0 an exposeBinding wrapper reports).
|
|
3087
3392
|
if (wantCdp) {
|
|
3088
3393
|
await context
|
|
3089
|
-
.exposeBinding("
|
|
3394
|
+
.exposeBinding("__clipyMarkImpl", async (_src, ...args) => {
|
|
3090
3395
|
if (recordStart === 0)
|
|
3091
3396
|
return { skipped: true };
|
|
3092
3397
|
const o = (args[1] ?? {});
|
|
@@ -3108,7 +3413,7 @@ async function runSessionDaemon(file) {
|
|
|
3108
3413
|
})
|
|
3109
3414
|
.catch((e) => log(`__clipyMark binding failed: ${e.message}`));
|
|
3110
3415
|
await context
|
|
3111
|
-
.exposeBinding("
|
|
3416
|
+
.exposeBinding("__clipyChapterImpl", (_src, ...args) => {
|
|
3112
3417
|
if (recordStart === 0)
|
|
3113
3418
|
return;
|
|
3114
3419
|
const label = String(args[0] ?? "").trim();
|
|
@@ -3117,6 +3422,14 @@ async function runSessionDaemon(file) {
|
|
|
3117
3422
|
}
|
|
3118
3423
|
})
|
|
3119
3424
|
.catch((e) => log(`__clipyChapter binding failed: ${e.message}`));
|
|
3425
|
+
// Declared-arity wrappers so window.__clipyMark.length === 2 / __clipyChapter
|
|
3426
|
+
// === 1 (they resolve the *Impl bindings lazily, at call time).
|
|
3427
|
+
await context
|
|
3428
|
+
.addInitScript({
|
|
3429
|
+
content: "window.__clipyMark = (text, opts) => window.__clipyMarkImpl(text, opts);\n" +
|
|
3430
|
+
"window.__clipyChapter = (label) => window.__clipyChapterImpl(label);",
|
|
3431
|
+
})
|
|
3432
|
+
.catch((e) => log(`in-page binding wrappers failed: ${e.message}`));
|
|
3120
3433
|
}
|
|
3121
3434
|
// Local control endpoint: `clipy mark`/`chapter` POST here so the daemon —
|
|
3122
3435
|
// which owns the live page — evaluates assertions and stamps marks on its
|
|
@@ -3131,19 +3444,23 @@ async function runSessionDaemon(file) {
|
|
|
3131
3444
|
text: typeof body.text === "string" ? body.text : "",
|
|
3132
3445
|
atMs: typeof body.atMs === "number" ? body.atMs : undefined,
|
|
3133
3446
|
assert: body.assert,
|
|
3447
|
+
attest: body.attest,
|
|
3134
3448
|
id: typeof body.id === "string" ? body.id : undefined,
|
|
3135
3449
|
});
|
|
3136
|
-
/** POST /chapter → a === CHAPTER === mark at the live clock.
|
|
3450
|
+
/** POST /chapter → a === CHAPTER === mark at the live clock. Carries its
|
|
3451
|
+
* client id so a timed-out-but-processed chapter dedups against the file. */
|
|
3137
3452
|
const handleChapter = (body) => {
|
|
3138
3453
|
const label = typeof body.label === "string" ? body.label.trim() : "";
|
|
3139
3454
|
if (!label)
|
|
3140
3455
|
throw new Error("chapter label is required");
|
|
3141
3456
|
const tMs = Math.max(0, Date.now() - recordStart);
|
|
3142
|
-
if (!storeDaemonMark({
|
|
3457
|
+
if (!storeDaemonMark({
|
|
3458
|
+
startMs: tMs,
|
|
3459
|
+
text: `=== CHAPTER: ${label} ===`,
|
|
3460
|
+
id: typeof body.id === "string" ? body.id : undefined,
|
|
3461
|
+
})) {
|
|
3143
3462
|
throw new Error("mark limit reached (200 marks per recording)");
|
|
3144
3463
|
}
|
|
3145
|
-
if (typeof body.id === "string" && body.id)
|
|
3146
|
-
processedMarkIds.add(body.id);
|
|
3147
3464
|
return { tMs };
|
|
3148
3465
|
};
|
|
3149
3466
|
const BODY_CAP = 1_000_000;
|
|
@@ -3303,12 +3620,20 @@ async function runSessionDaemon(file) {
|
|
|
3303
3620
|
if (browser)
|
|
3304
3621
|
await browser.close().catch(() => { });
|
|
3305
3622
|
browser = null;
|
|
3306
|
-
// Merge marks
|
|
3307
|
-
//
|
|
3308
|
-
//
|
|
3309
|
-
//
|
|
3623
|
+
// Merge marks. The FILE is the mark of record: `clipy mark` writes there when
|
|
3624
|
+
// its control call fails, and a timed-out ASSERTION is recorded ⚠-unverified.
|
|
3625
|
+
// That ⚠ is authoritative — if the daemon later evaluated the same mark, that
|
|
3626
|
+
// late verdict must NOT overwrite the ⚠ (it judged a LATER page state), so we
|
|
3627
|
+
// keep the ⚠ and re-stamp the late evaluation as a self-describing "late check"
|
|
3628
|
+
// at its own time. K counts the ⚠; the late check counts toward neither P/F/K.
|
|
3310
3629
|
const fileMarks = [];
|
|
3311
|
-
|
|
3630
|
+
const unverifiedClaimById = new Map(); // id → claim time (ms)
|
|
3631
|
+
const abandonedIds = new Set(); // any id the client wrote to the file
|
|
3632
|
+
let assertUnverified = 0; // K (clipy-verified marks we couldn't evaluate)
|
|
3633
|
+
// Driver-attested marks the client wrote to the file (control endpoint down):
|
|
3634
|
+
// they're already annotated client-side (nothing to evaluate) and still count.
|
|
3635
|
+
let driverPassed = 0;
|
|
3636
|
+
let driverFailed = 0;
|
|
3312
3637
|
try {
|
|
3313
3638
|
for (const line of readFileSync(state.marksPath, "utf8").split("\n")) {
|
|
3314
3639
|
if (!line.trim())
|
|
@@ -3316,31 +3641,82 @@ async function runSessionDaemon(file) {
|
|
|
3316
3641
|
const m = JSON.parse(line);
|
|
3317
3642
|
if (typeof m.tMs !== "number" || typeof m.text !== "string" || !m.text.trim())
|
|
3318
3643
|
continue;
|
|
3319
|
-
|
|
3320
|
-
|
|
3321
|
-
|
|
3322
|
-
|
|
3323
|
-
|
|
3324
|
-
|
|
3325
|
-
|
|
3326
|
-
|
|
3644
|
+
const startMs = Math.max(0, Math.round(m.tMs));
|
|
3645
|
+
fileMarks.push({ startMs, text: m.text.trim() }); // the mark of record, verbatim
|
|
3646
|
+
if (m.attested) {
|
|
3647
|
+
if (m.verdict === "pass")
|
|
3648
|
+
driverPassed++;
|
|
3649
|
+
else
|
|
3650
|
+
driverFailed++;
|
|
3651
|
+
}
|
|
3652
|
+
if (m.id) {
|
|
3653
|
+
abandonedIds.add(m.id);
|
|
3654
|
+
if (m.unverified) {
|
|
3655
|
+
unverifiedClaimById.set(m.id, startMs);
|
|
3656
|
+
assertUnverified++;
|
|
3657
|
+
}
|
|
3658
|
+
}
|
|
3327
3659
|
}
|
|
3328
3660
|
}
|
|
3329
3661
|
catch {
|
|
3330
3662
|
// no marks file — fine
|
|
3331
3663
|
}
|
|
3332
|
-
|
|
3333
|
-
|
|
3334
|
-
|
|
3335
|
-
|
|
3336
|
-
|
|
3337
|
-
|
|
3338
|
-
|
|
3339
|
-
|
|
3340
|
-
|
|
3341
|
-
|
|
3342
|
-
|
|
3664
|
+
// Resolve the daemon marks against the file marks of record.
|
|
3665
|
+
const resolvedDaemon = [];
|
|
3666
|
+
let assertPassed = 0;
|
|
3667
|
+
let assertFailed = 0;
|
|
3668
|
+
for (const dm of daemonMarks) {
|
|
3669
|
+
if (dm.id && unverifiedClaimById.has(dm.id)) {
|
|
3670
|
+
// The client already recorded a ⚠ mark of record for this assertion; this
|
|
3671
|
+
// daemon copy is a LATE evaluation. Emit it as a separate, honestly-timed
|
|
3672
|
+
// "late check" annotation (not counted in P/F/K).
|
|
3673
|
+
const claimMs = unverifiedClaimById.get(dm.id);
|
|
3674
|
+
const evalAt = Math.max(0, dm.evalAtMs ?? dm.startMs);
|
|
3675
|
+
const afterSec = Math.max(0, Math.round((evalAt - claimMs) / 1000));
|
|
3676
|
+
const oc = dm.assertOutcome;
|
|
3677
|
+
const verdict = oc
|
|
3678
|
+
? oc.passed
|
|
3679
|
+
? `✓ ${oc.observed}`
|
|
3680
|
+
: `✗ expected ${oc.expected}; observed ${oc.observed}`
|
|
3681
|
+
: "(no result)";
|
|
3682
|
+
resolvedDaemon.push({
|
|
3683
|
+
startMs: evalAt,
|
|
3684
|
+
text: `[late check of "${dm.claim ?? ""}" — evaluated ${afterSec}s after the claim: ${verdict}]`,
|
|
3685
|
+
});
|
|
3686
|
+
continue;
|
|
3687
|
+
}
|
|
3688
|
+
if (dm.id && abandonedIds.has(dm.id)) {
|
|
3689
|
+
// A plain mark/chapter the client already wrote to the file — dedup, the
|
|
3690
|
+
// file copy is the mark of record. (Exactly once.)
|
|
3691
|
+
continue;
|
|
3692
|
+
}
|
|
3693
|
+
resolvedDaemon.push({ startMs: dm.startMs, text: dm.text });
|
|
3694
|
+
if (dm.assertOutcome) {
|
|
3695
|
+
const bump = dm.assertOutcome.passed ? 1 : 0;
|
|
3696
|
+
if (dm.assertOutcome.kind === "driver") {
|
|
3697
|
+
driverPassed += bump;
|
|
3698
|
+
driverFailed += 1 - bump;
|
|
3699
|
+
}
|
|
3700
|
+
else {
|
|
3701
|
+
assertPassed += bump;
|
|
3702
|
+
assertFailed += 1 - bump;
|
|
3703
|
+
}
|
|
3704
|
+
}
|
|
3343
3705
|
}
|
|
3706
|
+
let notes = [...fileMarks, ...resolvedDaemon, ...autoMarks].sort((a, b) => a.startMs - b.startMs);
|
|
3707
|
+
// If any ORIGINAL assertion was attempted, prepend a 0ms verification summary so
|
|
3708
|
+
// it LEADS the transcript (a stable sort keeps it ahead of other 0ms marks). The
|
|
3709
|
+
// two provenances are reported as SEPARATE segments and never pooled. When only
|
|
3710
|
+
// clipy-verified marks exist the legacy single-segment rendering is byte-identical
|
|
3711
|
+
// (no churn for existing consumers). Late checks count toward neither.
|
|
3712
|
+
notes.unshift(...verificationNote({
|
|
3713
|
+
clipyPassed: assertPassed,
|
|
3714
|
+
clipyFailed: assertFailed,
|
|
3715
|
+
clipyUnverified: assertUnverified,
|
|
3716
|
+
driverPassed,
|
|
3717
|
+
driverFailed,
|
|
3718
|
+
}));
|
|
3719
|
+
notes.sort((a, b) => a.startMs - b.startMs);
|
|
3344
3720
|
// Server limit: cap the merged set at 200 marks (the verification note sorts
|
|
3345
3721
|
// to 0ms so it always survives the slice).
|
|
3346
3722
|
if (notes.length > 200) {
|
|
@@ -3391,6 +3767,16 @@ async function runSessionDaemon(file) {
|
|
|
3391
3767
|
await ctxToClose.close().catch(() => { });
|
|
3392
3768
|
if (browser)
|
|
3393
3769
|
await browser.close().catch(() => { });
|
|
3770
|
+
// Remove the copied-profile scratch root (a SIGKILL strands it → the 24h
|
|
3771
|
+
// sweep at the next record/session start catches that).
|
|
3772
|
+
if (state.profileScratchRoot) {
|
|
3773
|
+
try {
|
|
3774
|
+
rmSync(state.profileScratchRoot, { recursive: true, force: true });
|
|
3775
|
+
}
|
|
3776
|
+
catch {
|
|
3777
|
+
// best-effort
|
|
3778
|
+
}
|
|
3779
|
+
}
|
|
3394
3780
|
}
|
|
3395
3781
|
}
|
|
3396
3782
|
// ---------------------------------------------------------------------------
|
|
@@ -3482,7 +3868,7 @@ async function cmdAgents(ctx, sub, targetRaw, json) {
|
|
|
3482
3868
|
// command's shape without trial-and-error. Bump GUIDE_SCHEMA_VERSION when the
|
|
3483
3869
|
// contract changes.
|
|
3484
3870
|
// ---------------------------------------------------------------------------
|
|
3485
|
-
const GUIDE_SCHEMA_VERSION =
|
|
3871
|
+
const GUIDE_SCHEMA_VERSION = 9;
|
|
3486
3872
|
function cmdGuide(json) {
|
|
3487
3873
|
if (!json) {
|
|
3488
3874
|
process.stdout.write(HELP);
|
|
@@ -3533,9 +3919,9 @@ function cmdGuide(json) {
|
|
|
3533
3919
|
cmdDoc("download", "clipy download <id> [-o path]", "Download the MP4"),
|
|
3534
3920
|
cmdDoc("open", "clipy open <id>", "Open the share page in a browser"),
|
|
3535
3921
|
cmdDoc("wait", "clipy wait <id> [--for transcript|summary|both] [--timeout sec]", "Block until artifacts are ready"),
|
|
3536
|
-
cmdDoc("record", "clipy record --url <url> [--for sec] [--viewports list] [--title t] [--type kind] [--note '12: text']… [--storage-state f] [--cookie 'n=v']… [--local-storage 'k=v']… [--init-script f] [--wait] [--json]", "Headless one-shot capture of a web app; notes become the transcript. Notes are absolute ('12: text') or pass-scoped ('pass2: text' / 'pass2@5: text', anchored to a --viewports pass's real start; a malformed pass note is rejected). --type declares the recording kind (bug_report|feature_request|product_demo|walkthrough_tutorial|feedback_review|discussion_talk|other, plus aliases bug/feature/demo/walkthrough/feedback/discussion) so the AI summary reads it correctly. Auth (web capture only, applied before the first navigation so a logged-in SPA's route guard sees it): --storage-state <playwright storageState JSON path>, --cookie 'name=value[; Domain=d; Path=p; Secure; HttpOnly; SameSite=Lax]' (repeatable), --local-storage 'key=value' (repeatable, target origin only), --init-script <js file run before every page load>, --user-data-dir <dir> (launch a persistent Chromium
|
|
3537
|
-
cmdDoc("session", "clipy session <start|run|stop|abort|status> [--url <url>] [--max sec] [--type kind] [--source web|mac-screen] [--window w] [--display d] [--expose-cdp] [--storage-state f] [--cookie 'n=v']… [--local-storage 'k=v']… [--init-script f] [--json]", "Background recording session; auto-stops + uploads at --max (default 600s, cap 1800s). --type sets the recording kind (see record). --window/--display (with --source mac-screen) record one window/display. --expose-cdp (web sessions) opens a CDP endpoint (cdpUrl/cdpHttpUrl in the state file + session start/status output) so your own tools can drive the page while it records; OFF by default (any local process could attach), and CLIPY_DISABLE_CDP=1 forces it off. `session run [start flags] -- <command…>` starts a session, runs the command with inherited stdio (env CLIPY_SESSION=1, plus CLIPY_CDP_URL when --expose-cdp), then GUARANTEES cleanup: exit 0 uploads, any non-zero exit or signal discards (session abort) and propagates the child's code — the crash-safe wrapper so a dead driver never records dead air. Accepts the same auth flags as record (--storage-state/--user-data-dir/--cookie/--local-storage/--init-script; web only, rejected on --source mac-screen). `session run` exports CLIPY_SESSION_FILE to the child so mark/chapter resolve the session from any cwd. --json is supported on start/stop/status (start returns cdpUrl/cdpHttpUrl)", ["run", "--url", "--max", "--type", "--source", "--window", "--display", "--expose-cdp", "--storage-state", "--user-data-dir", "--cookie", "--local-storage", "--init-script", "--json"]),
|
|
3538
|
-
cmdDoc("mark", "clipy mark \"<text>\" [--assert-selector <css> [--assert-text <substr>]] [--assert-url <glob>] [--fail-mode warn|abort] [--at <sec>|--ago <sec>] [--json]", "Drop a live-timestamped note into the active session.
|
|
3922
|
+
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"]),
|
|
3923
|
+
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"]),
|
|
3924
|
+
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>]' (or ✗) 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"]),
|
|
3539
3925
|
cmdDoc("chapter", "clipy chapter \"<label>\" [--json]", "Mark a BEFORE/AFTER section boundary in the active recording (stored as '=== CHAPTER: <label> ==='). The PR-review shape: demo the base branch, run `clipy chapter \"AFTER — fix applied\"`, swap branches + restart the dev server, demo the fix — one video carrying both states. Works on web + --source mac-screen sessions.", ["--json"]),
|
|
3540
3926
|
cmdDoc("doctor", "clipy doctor [--json]", "One-shot health check: API key + whoami round-trip, Mac agent bridge (exists/parses/pid/appVersion>=" + MIN_BRIDGE_APP_VERSION + "), Playwright resolvability (and the resolved path/node_modules dir), and install mode (npx/global/local) — each a pass/warn/fail with a fix hint; exits non-zero if any check fails", ["--json"]),
|
|
3541
3927
|
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"]),
|
|
@@ -3551,14 +3937,16 @@ function cmdGuide(json) {
|
|
|
3551
3937
|
"Headless captures have no audio: --note flags and session marks become the transcript, labeled agent-narration.",
|
|
3552
3938
|
"--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.",
|
|
3553
3939
|
"--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.",
|
|
3940
|
+
"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=…]' and clipy-evaluated ones '[assert ✓ verified-by-clipy; …]', 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.",
|
|
3554
3941
|
"Assertion marks are the differentiator: assert what you claim. `clipy mark \"X\" --assert-selector '.status' --assert-text Active` records X only alongside the live-page truth — the daemon runs the check against its Playwright page and annotates the mark ✓/✗ with what it actually observed, so a false claim cannot pass as fact in the transcript. --fail-mode abort turns a failed assertion into a discarded session (nothing uploaded, non-zero exit). Assertions need a web session and the daemon's control endpoint (started by clipy 0.6+); they are rejected on --source mac-screen.",
|
|
3555
|
-
"A mark is NEVER dropped. If the daemon can't be reached to evaluate an assertion (its event loop briefly starved during a dev-server recompile), `clipy mark` records the narration anyway tagged '[ASSERT ⚠ could not evaluate — <reason>]', prints a loud ⚠, and exits 0 — an unverified claim is flagged, never promoted to a ✓. The tally's third bucket counts these: '[verification] N assertion(s): P passed, F failed, K unverified' (the ', K unverified' clause is omitted when K=0).
|
|
3942
|
+
"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).",
|
|
3556
3943
|
"clipy chapter \"<label>\" splits one recording into BEFORE/AFTER sections for PR-review-style demos: record the base branch, `clipy chapter \"AFTER — fix applied\"`, swap branches + restart, record the fix. One video carries both states.",
|
|
3557
3944
|
"clipy session run [start flags] -- <command…> is the crash-safe wrapper: it starts a session, runs your driver command with inherited stdio (env CLIPY_SESSION=1, plus CLIPY_CDP_URL when --expose-cdp), and guarantees cleanup — exit 0 uploads, any non-zero exit or signal discards and propagates the code. Use it so a crashing driver never records dead air to the max ceiling.",
|
|
3558
|
-
"clipy mark --at <sec> stamps at an absolute recording time; --ago <sec> stamps N seconds before now — a `clipy mark` spawn lands ~100-300ms late, so backdate to align a mark with the state it describes. When driving over --expose-cdp, call window.__clipyMark(text, opts?) / window.__clipyChapter(label) IN-PAGE (page.evaluate) to emit marks/chapters with zero spawn latency, evaluated daemon-side with the page in hand. __clipyMark's opts {assertSelector, assertText, assertUrl, failMode} run the SAME assertions as the CLI flags (assertText requires assertSelector or the call rejects; failMode 'abort' discards the session); it returns the annotated {tMs, text, assert}. While CDP is exposed the page's own scripts can call these too (within the existing --expose-cdp trust model).",
|
|
3945
|
+
"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).",
|
|
3559
3946
|
"session --expose-cdp (web, opt-in) publishes a CDP endpoint (cdpHttpUrl) in `session start`/`session status` output and the 0600 session state file; connect with playwright.connectOverCDP() to drive the recorded page. Off by default (any local process could attach); CLIPY_DISABLE_CDP=1 forces it off.",
|
|
3560
3947
|
"Driving an --expose-cdp session: connect with playwright.connectOverCDP(cdpHttpUrl); the recorded page is browser.contexts()[0].pages()[0] (a fresh context/page you open is NOT captured); page.viewportSize() is null over a CDP attach; resize with a CDP session's Emulation.setDeviceMetricsOverride, not setViewportSize. Your own driver script resolves Playwright from its own cwd — run it as NODE_PATH=$(clipy playwright-path) node driver.js if require('playwright') can't find it.",
|
|
3561
3948
|
"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.",
|
|
3949
|
+
"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.",
|
|
3562
3950
|
"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.",
|
|
3563
3951
|
"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).",
|
|
3564
3952
|
"Public recordings have an unauthenticated context document at https://clipy.online/video/<id>.md.",
|
|
@@ -3663,11 +4051,14 @@ async function main() {
|
|
|
3663
4051
|
"assert-text": { type: "string" },
|
|
3664
4052
|
"assert-url": { type: "string" },
|
|
3665
4053
|
"fail-mode": { type: "string" },
|
|
4054
|
+
observed: { type: "string" },
|
|
4055
|
+
verdict: { type: "string" },
|
|
3666
4056
|
at: { type: "string" },
|
|
3667
4057
|
ago: { type: "string" },
|
|
3668
4058
|
"expose-cdp": { type: "boolean", default: false },
|
|
3669
4059
|
"storage-state": { type: "string" },
|
|
3670
4060
|
"user-data-dir": { type: "string" },
|
|
4061
|
+
"profile-directory": { type: "string" },
|
|
3671
4062
|
"init-script": { type: "string" },
|
|
3672
4063
|
cookie: { type: "string", multiple: true },
|
|
3673
4064
|
"local-storage": { type: "string", multiple: true },
|
|
@@ -3708,6 +4099,7 @@ async function main() {
|
|
|
3708
4099
|
// without an explicit cwd — reads the same files the parent validated.
|
|
3709
4100
|
const authFlagsPresent = Boolean(values["storage-state"] ||
|
|
3710
4101
|
values["user-data-dir"] ||
|
|
4102
|
+
values["profile-directory"] ||
|
|
3711
4103
|
values["init-script"] ||
|
|
3712
4104
|
values.cookie?.length ||
|
|
3713
4105
|
values["local-storage"]?.length);
|
|
@@ -3728,6 +4120,17 @@ async function main() {
|
|
|
3728
4120
|
}
|
|
3729
4121
|
return resolve(String(values["user-data-dir"]));
|
|
3730
4122
|
};
|
|
4123
|
+
// --profile-directory names a profile subdir inside --user-data-dir; only
|
|
4124
|
+
// meaningful WITH it (Clipy copies that subdir into a scratch root's Default).
|
|
4125
|
+
const profileDirectory = () => {
|
|
4126
|
+
const pd = values["profile-directory"]?.trim();
|
|
4127
|
+
if (!pd)
|
|
4128
|
+
return undefined;
|
|
4129
|
+
if (!values["user-data-dir"]) {
|
|
4130
|
+
die("--profile-directory names a profile inside --user-data-dir — pass --user-data-dir <chrome user-data root> too", 2);
|
|
4131
|
+
}
|
|
4132
|
+
return pd;
|
|
4133
|
+
};
|
|
3731
4134
|
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";
|
|
3732
4135
|
switch (command) {
|
|
3733
4136
|
case "login":
|
|
@@ -3918,6 +4321,7 @@ async function main() {
|
|
|
3918
4321
|
json,
|
|
3919
4322
|
auth: authCapture(),
|
|
3920
4323
|
userDataDir: userDataDir(),
|
|
4324
|
+
profileDirectory: profileDirectory(),
|
|
3921
4325
|
});
|
|
3922
4326
|
return;
|
|
3923
4327
|
}
|
|
@@ -3959,6 +4363,7 @@ async function main() {
|
|
|
3959
4363
|
exposeCdp: Boolean(values["expose-cdp"]),
|
|
3960
4364
|
auth: authCapture(),
|
|
3961
4365
|
userDataDir: userDataDir(),
|
|
4366
|
+
profileDirectory: profileDirectory(),
|
|
3962
4367
|
};
|
|
3963
4368
|
};
|
|
3964
4369
|
if (sub === "start") {
|
|
@@ -3988,7 +4393,7 @@ async function main() {
|
|
|
3988
4393
|
case "mark": {
|
|
3989
4394
|
const text = rest.join(" ").trim();
|
|
3990
4395
|
if (!text) {
|
|
3991
|
-
die('usage: clipy mark "<what just happened>" [--assert-selector <css> [--assert-text <substr>]] [--assert-url <glob>] [--fail-mode warn|abort] [--at <sec>|--ago <sec>]', 2);
|
|
4396
|
+
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);
|
|
3992
4397
|
}
|
|
3993
4398
|
const selector = values["assert-selector"]?.trim() || undefined;
|
|
3994
4399
|
const expectText = values["assert-text"]; // exact, not trimmed
|
|
@@ -4001,6 +4406,22 @@ async function main() {
|
|
|
4001
4406
|
die("--fail-mode must be warn or abort", 2);
|
|
4002
4407
|
}
|
|
4003
4408
|
const hasAssert = Boolean(selector || (expectText != null && expectText !== "") || urlGlob);
|
|
4409
|
+
// Driver-attested provenance: --observed + --verdict travel together, and a
|
|
4410
|
+
// mark carries exactly ONE provenance (Clipy verified it, or the agent did).
|
|
4411
|
+
const observed = values.observed;
|
|
4412
|
+
const verdictRaw = values.verdict?.trim().toLowerCase();
|
|
4413
|
+
if ((observed == null) !== (verdictRaw == null)) {
|
|
4414
|
+
die("--observed and --verdict go together — pass both (the observed values you collected, and your pass/fail verdict)", 2);
|
|
4415
|
+
}
|
|
4416
|
+
if (verdictRaw != null && verdictRaw !== "pass" && verdictRaw !== "fail") {
|
|
4417
|
+
die("--verdict must be pass or fail", 2);
|
|
4418
|
+
}
|
|
4419
|
+
const attest = observed != null && verdictRaw != null
|
|
4420
|
+
? { observed, verdict: verdictRaw }
|
|
4421
|
+
: undefined;
|
|
4422
|
+
if (attest && hasAssert) {
|
|
4423
|
+
die("--observed/--verdict (driver-attested) and --assert-* (Clipy-verified) are different provenances — use one per mark", 2);
|
|
4424
|
+
}
|
|
4004
4425
|
if (failModeRaw && !hasAssert) {
|
|
4005
4426
|
die("--fail-mode only applies with an assertion (--assert-selector / --assert-text / --assert-url)", 2);
|
|
4006
4427
|
}
|
|
@@ -4014,6 +4435,7 @@ async function main() {
|
|
|
4014
4435
|
assert: hasAssert
|
|
4015
4436
|
? { selector, expectText, urlGlob, failMode: failModeRaw || "warn" }
|
|
4016
4437
|
: undefined,
|
|
4438
|
+
attest,
|
|
4017
4439
|
});
|
|
4018
4440
|
return;
|
|
4019
4441
|
}
|