worktrust 0.10.17 → 0.10.20

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/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "worktrust",
3
- "version": "0.10.17",
3
+ "version": "0.10.20",
4
4
  "description": "Couple this computer to WorkTrust: approve a code in your browser, and every AI app here reports what you built. Metadata only, no dependencies.",
5
5
  "type": "module",
6
6
  "bin": {
@@ -34,7 +34,7 @@
34
34
  "engines": {
35
35
  "node": ">=18"
36
36
  },
37
- "license": "MIT",
37
+ "license": "SEE LICENSE IN LICENSE",
38
38
  "homepage": "https://worktrust.io",
39
39
  "keywords": [
40
40
  "worktrust",
@@ -36,6 +36,8 @@ export function archiveLine(entry, behaviour = null, { ids = {}, collector, salt
36
36
  if (typeof entry?.client !== "string" || !/^[a-z][a-z0-9-]{0,31}$/.test(entry.client) || !ISO.test(entry.started_at ?? "") || !ISO.test(entry.at ?? "") || !/^[A-Za-z0-9_-]{16,128}$/.test(entry.stretch_ref ?? "")) return null;
37
37
  const line = { client: entry.client, day: entry.started_at.slice(0, 10), started_at: entry.started_at, ended_at: entry.at };
38
38
  for (const key of COUNTS) if (typeof entry[key] === "number" && Number.isFinite(entry[key]) && entry[key] >= 0) line[key] = entry[key];
39
+ // THE TIMELINE (0.10.20): the stretch's clock as step kinds and gaps, the shape and nothing else; WorkTrust computes the figures from it when the archive is sent.
40
+ if (typeof entry.timeline === "string" && entry.timeline.length <= 200000 && /^(G?[HIURATWhiuratw][0-9]{1,6})+$/.test(entry.timeline)) line.timeline = entry.timeline;
39
41
  if (typeof entry.model === "string" && /^[A-Za-z0-9][A-Za-z0-9._:/ -]{0,63}$/.test(entry.model)) line.model = entry.model;
40
42
  for (const key of WORDS) if (typeof entry[key] === "string" && WORD.test(entry[key])) line[key] = entry[key];
41
43
  if (Array.isArray(entry.layers) && entry.layers.length > 1 && entry.layers.every((word) => typeof word === "string" && WORD.test(word))) line.layers = entry.layers.slice(0, 8);
@@ -205,8 +207,9 @@ export function archiveEntries(dir, ownKey) {
205
207
  const entry = {
206
208
  title: line.layer ? `AI-assisted work · ${line.layer}` : "AI-assisted work",
207
209
  ...(line.kind ? { kind: line.kind } : {}), ...(line.layer ? { layer: line.layer } : {}), ...(line.layers ? { layers: line.layers } : {}),
208
- ...(typeof line.seconds === "number" ? { seconds: line.seconds, duration_basis: line.duration_basis ?? "measured" } : {}),
209
- ...Object.fromEntries(["tokens_in", "tokens_out", "token_basis", "tokens_cache_read", "tokens_cache_write", "exchanges", "turn_basis", "model", "steered_from", "model_seconds", "tool_seconds", "human_seconds", "idle_seconds", "agent_runs", "agent_seconds", "agent_peak", "interrupts", "steers", "utc_offset"].filter((key) => line[key] !== undefined).map((key) => [key, line[key]])),
210
+ // An older archive carries the figures it computed (sent as they are, marked client at the door); one since 0.10.20 carries the timeline, and the basis goes with either.
211
+ ...(typeof line.seconds === "number" ? { seconds: line.seconds, duration_basis: line.duration_basis ?? "measured" } : typeof line.timeline === "string" ? { duration_basis: line.duration_basis ?? "measured" } : {}),
212
+ ...Object.fromEntries(["timeline", "tokens_in", "tokens_out", "token_basis", "tokens_cache_read", "tokens_cache_write", "exchanges", "turn_basis", "model", "steered_from", "model_seconds", "tool_seconds", "human_seconds", "idle_seconds", "agent_runs", "agent_seconds", "agent_peak", "interrupts", "steers", "utc_offset"].filter((key) => line[key] !== undefined).map((key) => [key, line[key]])),
210
213
  stretch_ref: line.stretch_ref, started_at: line.started_at, at: line.ended_at, from_archive: true,
211
214
  };
212
215
  out.push({ entry, client: line.client ?? "claude", signed });
@@ -25,7 +25,7 @@ export function summaryLines(lines) {
25
25
  }
26
26
  const hours = (seconds) => (seconds / 3600).toFixed(1);
27
27
  for (const [key, m] of [...months].sort()) {
28
- out.push(` ${key} ${hours(m.seconds)} h measured`);
28
+ out.push(` ${key} ${m.seconds > 0 ? `${hours(m.seconds)} h measured` : "hours measured by WorkTrust on arrival"}`); // an archive since 0.10.20 carries timelines, not figures
29
29
  for (const [model, tokens] of [...m.models].sort((a, b) => b[1] - a[1])) out.push(` ${model.padEnd(28)} ${tokens.toLocaleString("en")} tokens`);
30
30
  if (m.input > 0) out.push(` cache share of input ${Math.round((m.cached / m.input) * 100)}%`);
31
31
  if (m.delivered > 0) out.push(` verified before delivery ${m.verifiedFirst} of ${m.delivered} stretch${m.delivered === 1 ? "" : "es"} that delivered`);
package/worktrust.mjs CHANGED
@@ -1,7 +1,6 @@
1
1
  #!/usr/bin/env node
2
2
  /**
3
3
  * WorkTrust on a computer, in one command — like `gh auth login` (2026-10-03).
4
- *
5
4
  * npx worktrust show the plan, ask, approve this computer in the app, couple (0.10.7: a person's
6
5
  * command always runs the newest version, whatever npx had cached);
7
6
  * on a computer already coupled: what is coupled here
@@ -30,27 +29,23 @@
30
29
  * --archive [dir] a local metadata-only record, --verify [dir] checks it,
31
30
  * --summary [dir] counts hours, tokens and parallel sessions from it);
32
31
  * local only: no account, no key, no network (preserve.mjs)
33
- *
34
32
  * WHAT RUNS. From the npm package, everything that runs is in the package: this file,
35
33
  * `setup-mcp.mjs` (gives every AI app here the WorkTrust door), `log-session.mjs` (the session hook)
36
34
  * and `count-behaviour.mjs` (the local counter, pinned: never replaced from the network), with
37
35
  * `transcript-readers.mjs` (how Codex and Antigravity logs are read, imported by the last two). Nothing
38
36
  * is downloaded. Run as a single file from WorkTrust's site instead, it fetches those from that
39
37
  * same site, and says so before it asks.
40
- *
41
38
  * HOW THE ACCOUNT IS DECIDED. By default this terminal listens on 127.0.0.1 for one answer and holds
42
39
  * a PKCE secret. Your browser opens WorkTrust, you approve this computer there (signed in, second
43
40
  * factor), and the browser is sent back to 127.0.0.1 with a one-time code that only this terminal,
44
41
  * with its secret, can exchange for the key. Nothing is typed, and a link forwarded to someone else
45
42
  * approves nothing they can collect. Without a browser (`--device`, or over SSH) the terminal shows
46
43
  * a code that you type yourself at app.worktrust.io/connect/computer.
47
- *
48
44
  * WHERE THE KEY LIVES. In one file only you can read (~/.worktrust/key.json, mode 600, folder 700).
49
45
  * No keychain is touched. The AI apps never hold it:
50
46
  * each runs `worktrust.mjs mcp`, a small local bridge that reads the key and speaks to WorkTrust for
51
47
  * them, and the session hook runs through `worktrust.mjs hook` the same way. `--direct` writes the
52
48
  * key into each app's settings instead (for an app that cannot run a local command).
53
- *
54
49
  * THE KEY ONLY WORKS ON THIS COMPUTER. connect makes an Ed25519 key pair; the public half goes to
55
50
  * WorkTrust, the private half stays in the key file. Every call the bridge, the hook and
56
51
  * the counter make carries a fresh signature (`WorkTrust-Proof`), and WorkTrust refuses a call
@@ -83,7 +78,7 @@ const command = args.includes("--help") ? "help" : args.includes("--version") ?
83
78
  const flag = (name) => { const at = args.indexOf(`--${name}`); return at >= 0 ? args[at + 1] : undefined; };
84
79
  const has = (name) => args.includes(`--${name}`);
85
80
  /** This CLI's version, said to the door so the app can tell which computer runs an old one (check-cli-package holds it equal to package.json). */
86
- const CLI_VERSION = "0.10.17";
81
+ const CLI_VERSION = "0.10.20";
87
82
  const ORIGIN = (flag("origin") ?? process.env.WORKTRUST_ORIGIN ?? "https://app.worktrust.io").replace(/\/$/, "");
88
83
  const MCP = flag("url") ?? process.env.WORKTRUST_MCP_URL ?? `${ORIGIN}/api/mcp`;
89
84
  const HOME_DIR = join(homedir(), ".worktrust");
@@ -97,7 +92,9 @@ const PLACEHOLDER = `wt_${"0".repeat(43)}`;
97
92
  const say = (line = "") => process.stdout.write(`${line}\n`);
98
93
  // A reader that closed the pipe (`worktrust status | head`) wants no more: stop quietly, never an EPIPE stack (0.6.16, audit L4).
99
94
  process.stdout.on("error", (error) => { if (error?.code === "EPIPE") process.exit(0); throw error; });
100
- const fail = (line) => { process.stderr.write(`worktrust: ${line}\n`); process.exit(1); };
95
+ class CliFailure extends Error {}
96
+ const fail = (line) => { process.stderr.write(`worktrust: ${line}\n`); throw new CliFailure(); };
97
+ const NODE_FLAGS = process.versions.node === "26.5.0" ? ["--no-concurrent-sparkplug"] : [];
101
98
  const OS = { darwin: "macos", win32: "windows", linux: "linux" }[platform()] ?? "other";
102
99
  const OS_NAME = { macos: "macOS", windows: "Windows", linux: "Linux", other: "this system" }[OS];
103
100
 
@@ -123,8 +120,6 @@ function computerIds() {
123
120
  return { device_id: hash(`worktrust-machine|${machine.toLowerCase()}`), profile_id: hash(`worktrust-profile|${machine.toLowerCase()}|${homedir()}`) };
124
121
  }
125
122
 
126
- if (Number(process.versions.node.split(".")[0]) < 18) fail("needs Node 18 or later (fetch is built in from 18).");
127
-
128
123
  async function post(path, body) {
129
124
  const response = await fetch(`${ORIGIN}${path}`, { method: "POST", headers: { "content-type": "application/json" }, body: JSON.stringify(body) });
130
125
  return { status: response.status, json: await response.json().catch(() => ({})) };
@@ -147,7 +142,7 @@ async function scripts() {
147
142
  /** Run a script; its output is shown, or collected for the plan. The key travels in the environment only. */
148
143
  function run(path, scriptArgs, token, collect = false, extraEnv = {}) {
149
144
  return new Promise((resolve) => {
150
- const child = spawn(process.execPath, [path, ...scriptArgs], { stdio: collect ? ["ignore", "pipe", "pipe"] : "inherit", env: { ...process.env, WORKTRUST_MCP_URL: MCP, WORKTRUST_MCP_TOKEN: token, WORKTRUST_NODE: NODE, ...extraEnv } });
145
+ const child = spawn(process.execPath, [...NODE_FLAGS, path, ...scriptArgs], { stdio: collect ? ["ignore", "pipe", "pipe"] : "inherit", env: { ...process.env, WORKTRUST_MCP_URL: MCP, WORKTRUST_MCP_TOKEN: token, WORKTRUST_NODE: NODE, WORKTRUST_CLI_VERSION: CLI_VERSION, ...extraEnv } });
151
146
  let out = "";
152
147
  child.stdout?.on("data", (chunk) => { out += chunk; });
153
148
  child.stderr?.on("data", (chunk) => { out += chunk; });
@@ -463,7 +458,7 @@ function sweepAtMostHourly() {
463
458
  const stamp = join(HOME_DIR, "bridge-swept-at");
464
459
  try { if (Date.now() - Number(readFileSync(stamp, "utf8")) < 3_600_000) return; } catch { /* never swept here */ }
465
460
  try { mkdirSync(HOME_DIR, { recursive: true }); writeFileSync(stamp, String(Date.now())); } catch { return; }
466
- try { spawn(process.execPath, [fileURLToPath(import.meta.url), "hook"], { detached: true, stdio: "ignore" }).unref(); } catch { /* the next start sweeps */ }
461
+ try { spawn(process.execPath, [...NODE_FLAGS, fileURLToPath(import.meta.url), "hook"], { detached: true, stdio: "ignore" }).unref(); } catch { /* the next start sweeps */ }
467
462
  }
468
463
 
469
464
  async function bridge() {
@@ -505,9 +500,9 @@ async function hook() {
505
500
  if (has("antigravity-stop")) return antigravityStop();
506
501
  if (has("hermes") || has("goose")) return sessionEnd();
507
502
  const key = await freshKey();
508
- if (!key) process.exit(0);
509
- const child = spawn(process.execPath, [join(BUNDLED ? HERE : HOME_DIR, "log-session.mjs"), ...args.filter((arg) => arg !== "hook")], { stdio: "inherit", env: { ...process.env, WORKTRUST_MCP_URL: key.url, WORKTRUST_MCP_TOKEN: key.token, ...(key.device ? { WORKTRUST_DEVICE_KEY: key.device } : {}) } });
510
- child.on("exit", (code) => process.exit(code ?? 0));
503
+ if (!key) return;
504
+ const child = spawn(process.execPath, [...NODE_FLAGS, join(BUNDLED ? HERE : HOME_DIR, "log-session.mjs"), ...args.filter((arg) => arg !== "hook")], { stdio: "inherit", env: { ...process.env, WORKTRUST_MCP_URL: key.url, WORKTRUST_MCP_TOKEN: key.token, WORKTRUST_CLI_VERSION: CLI_VERSION, ...(key.device ? { WORKTRUST_DEVICE_KEY: key.device } : {}) } }); // 0.10.20: the hook names the version that started it, beside each line
505
+ process.exitCode = await new Promise((resolve, reject) => { child.on("error", reject); child.on("close", (code) => resolve(code ?? 1)); });
511
506
  }
512
507
 
513
508
  /**
@@ -529,8 +524,8 @@ async function antigravityStop() {
529
524
  process.stdin.on("end", () => { clearTimeout(timer); resolve(text); });
530
525
  process.stdin.on("error", () => { clearTimeout(timer); resolve(text); });
531
526
  });
532
- try { spawn(process.execPath, [fileURLToPath(import.meta.url), "hook", "--antigravity"], { detached: true, stdio: "ignore", env: { ...process.env, WORKTRUST_HOOK_INPUT: input.slice(0, 65536) } }).unref(); } catch { /* the next run sweeps it */ }
533
- process.exit(0);
527
+ try { spawn(process.execPath, [...NODE_FLAGS, fileURLToPath(import.meta.url), "hook", "--antigravity"], { detached: true, stdio: "ignore", env: { ...process.env, WORKTRUST_HOOK_INPUT: input.slice(0, 65536) } }).unref(); } catch { /* the next run sweeps it */ }
528
+ process.stdin.pause(); return;
534
529
  }
535
530
 
536
531
  /**
@@ -543,8 +538,8 @@ async function antigravityStop() {
543
538
  async function sessionEnd() {
544
539
  writeSync(1, "{}\n");
545
540
  if (!process.stdin.isTTY) await new Promise((resolve) => { const timer = setTimeout(resolve, 2000); process.stdin.on("data", () => {}); process.stdin.on("end", () => { clearTimeout(timer); resolve(); }); process.stdin.on("error", () => { clearTimeout(timer); resolve(); }); });
546
- try { spawn(process.execPath, [fileURLToPath(import.meta.url), "hook"], { detached: true, stdio: "ignore" }).unref(); } catch { /* the next run sweeps it */ }
547
- process.exit(0);
541
+ try { spawn(process.execPath, [...NODE_FLAGS, fileURLToPath(import.meta.url), "hook"], { detached: true, stdio: "ignore" }).unref(); } catch { /* the next run sweeps it */ }
542
+ process.stdin.pause(); return;
548
543
  }
549
544
 
550
545
  /**
@@ -683,10 +678,10 @@ async function offerHistory(paths, token, devicePem, url = MCP, rebuild = false)
683
678
  try { found = JSON.parse(counted.out.trim().split("\n").pop()); } catch { /* no line: nothing to offer */ }
684
679
  say();
685
680
  if (!found?.sessions) { historyDone(true); say(rebuild ? " Your AI apps hold no earlier sessions on this computer to re-measure." : " Your AI apps hold no earlier sessions on this computer to send."); return; }
686
- say(` This computer holds ${found.sessions} earlier sessions of your AI apps · ${found.hours} measured hours · ${found.first} … ${found.last}.`);
681
+ say(` This computer holds ${found.sessions} earlier sessions of your AI apps · ${found.days} days · ${found.first} … ${found.last}. WorkTrust measures the hours when they arrive.`);
687
682
  // REBUILD (owner, 2026-10-07): the plan per AI app, in days and hours, and what it replaces, before the one question. Enter is No.
688
683
  if (rebuild) {
689
- for (const row of found.clients ?? []) say(` ${row.client.padEnd(12)} ${String(row.days).padStart(4)} days ${String(row.hours).padStart(7)} h ${row.first} … ${row.last}`);
684
+ for (const row of found.clients ?? []) say(` ${row.client.padEnd(12)} ${String(row.days).padStart(4)} days ${row.first} … ${row.last}`);
690
685
  say(" Re-measured with the current rules (what the seconds were, your own turns, tokens with the cache, every AI app above).");
691
686
  say(" WorkTrust REPLACES this computer's earlier lines for those days and apps: each earlier line is withdrawn and kept,");
692
687
  say(" never deleted, so a day is counted once. Other computers, web sources and days not listed are not touched.");
@@ -707,6 +702,7 @@ async function offerHistory(paths, token, devicePem, url = MCP, rebuild = false)
707
702
  : `${n(did.new)} new lines${n(did.filled) > 0 ? `, ${n(did.filled)} lines gained what was missing` : ""}; ${n(did.alreadyHeld)} already held.`;
708
703
  if (rebuild) say(sent.code === 0 ? ` ✓ Re-measured. ${outcome}` : " Not all of it arrived. Run npx worktrust again: it finishes what did not arrive, a day already rebuilt is counted once.");
709
704
  else say(sent.code === 0 ? " ✓ Sent as history. Measured sessions count toward your verified hours; a day WorkTrust already holds is kept once." : " Not all of it arrived. Run npx worktrust history again: a line already received is kept once.");
705
+ if (did && Number(did.measuredSeconds) > 0) say(` Measured by WorkTrust: ${(Number(did.measuredSeconds) / 3600).toFixed(1)} h for what this send stored${n(did.corrected) > 0 ? ` (${n(did.corrected)} lines corrected: a figure sent beside the timeline differed)` : ""}.`);
710
706
  }
711
707
 
712
708
  /** The version stamped in the stable copy in ~/.worktrust, the CLI this computer ran before an update; null without one. */
@@ -800,6 +796,8 @@ async function offerArchive(paths, key) {
800
796
  * `--dry-run` stops before it; `--history` says yes in advance. Answers whether the export arrived whole.
801
797
  */
802
798
  const EXPORT_PRODUCT = { chatgpt: "ChatGPT", "claude-web": "Claude on the web" };
799
+ /** The connector of the export's vendor (0.10.19): the only lines an export may withdraw are the ones this connector reported. */
800
+ const EXPORT_CONNECTOR = { chatgpt: "ChatGPT", "claude-web": "Claude" };
803
801
  async function offerExport(paths, key, path) {
804
802
  const env = { WORKTRUST_MCP_URL: key.url, ...(key.device ? { WORKTRUST_DEVICE_KEY: key.device } : {}) };
805
803
  const counted = await run(paths["log-session.mjs"], ["--history", "--export", path, "--dry-run", "--summary"], key.token, true, env);
@@ -808,10 +806,12 @@ async function offerExport(paths, key, path) {
808
806
  const report = found?.exports?.[0];
809
807
  say();
810
808
  if (counted.code !== 0 || !report) { say(` ${counted.out.trim().split("\n").filter(Boolean).pop() ?? "export: it could not be read"}. Nothing was sent.`); return false; }
811
- const product = EXPORT_PRODUCT[report.vendor] ?? report.vendor;
809
+ const product = EXPORT_PRODUCT[report.vendor] ?? report.vendor, connector = EXPORT_CONNECTOR[report.vendor] ?? report.vendor;
812
810
  if (!report.days) { say(` ${product} export · ${report.conversations} conversations, none with a clock to place: nothing to send.`); return true; }
813
- say(` ${product} export · ${report.conversations} conversations · ${report.days} days · ${report.hours} reconstructed hours · ${String(report.first).slice(0, 7)} … ${String(report.last).slice(0, 7)}`);
814
- say(" Hours reconstructed from the export's own clocks: shown with their origin, never verified hours. Never a title or a message.");
811
+ say(` ${product} export · ${report.conversations} conversations · ${report.days} days · ${String(report.first).slice(0, 7)} … ${String(report.last).slice(0, 7)}`);
812
+ say(" WorkTrust reconstructs the hours from the export's own clocks when they arrive: shown with their origin, never verified hours. Never a title or a message.");
813
+ // LEFT OUT AND COUNTED (0.10.18): a conversation whose kept fields outgrew the reader's budget is passed over, never the export.
814
+ if (report.oversized > 0) say(` ${report.oversized} conversation${report.oversized === 1 ? "" : "s"} too large to read ${report.oversized === 1 ? "is" : "are"} left out; the rest is read.`);
815
815
  if (has("dry-run")) { say(" Dry run: nothing was sent."); return false; }
816
816
  if (!has("history") && !(await ask("Send it as history (reconstructed hours per day; never text)?", false))) { say(` Not sent. Send it later with: npx worktrust history --export ${path}`); return false; }
817
817
  const sent = await run(paths["log-session.mjs"], ["--history", "--export", path], key.token, true, env);
@@ -820,13 +820,15 @@ async function offerExport(paths, key, path) {
820
820
  // THE EXPORT REPLACES (owner, 2026-10-10): the door withdrew the product's earlier connector lines on the export's days by itself and
821
821
  // says so; the lines an AI app reported under no product on those days may describe the same conversations, and go only on a yes.
822
822
  const counts = lastCounts(sent.out);
823
- if (counts.superseded > 0) say(` ${counts.superseded} earlier line${counts.superseded === 1 ? "" : "s"} of ${product} on those days, brought in by a connector, ${counts.superseded === 1 ? "is" : "are"} withdrawn and kept (each with a correction row): the export's lines count, a day counts once.`);
823
+ // WHAT AN EXPORT MAY WITHDRAW (0.10.19, after the incident of 2026-10-18): lines your connector of the same vendor reported, and nothing a computer of yours wrote;
824
+ // the door holds the rule, the counts here are the door's own, and the question names exactly what the second send will touch.
825
+ if (counts.superseded > 0) say(` ${counts.superseded} earlier line${counts.superseded === 1 ? "" : "s"} of ${product} your ${connector} connector reported for those days ${counts.superseded === 1 ? "is" : "are"} withdrawn and kept (each with a correction row): the export's lines count, a day counts once.`);
824
826
  // ONE STRETCH PER RUN (0.10.17): a conversation-day sent before as one envelope is now its runs; the door withdrew the envelope.
825
827
  if (counts.recut > 0) say(` ${counts.recut} earlier line${counts.recut === 1 ? "" : "s"} of this export, one per conversation and day, ${counts.recut === 1 ? "is" : "are"} replaced by one line per run of activity (withdrawn and kept, the same total).`);
826
828
  if (counts.unknownOnDays > 0) {
827
829
  const n = counts.unknownOnDays;
828
- say(` ${n} earlier line${n === 1 ? "" : "s"} an AI app reported for these days, under no product, may describe the same conversations.`);
829
- if (has("withdraw-unknown") || (await ask(`Also withdraw ${n} earlier line${n === 1 ? "" : "s"} an AI app reported for these days?`, false))) {
830
+ say(` ${n} earlier line${n === 1 ? "" : "s"} your ${connector} connector reported for these days under no product may describe the same conversations. Your own computers' lines are never touched.`);
831
+ if (has("withdraw-unknown") || (await ask(`Also withdraw ${n} earlier line${n === 1 ? "" : "s"} your ${connector} connector reported for these days?`, false))) {
830
832
  const again = await run(paths["log-session.mjs"], ["--history", "--export", path, "--withdraw-unknown"], key.token, true, env);
831
833
  const done = lastCounts(again.out);
832
834
  say(again.code === 0 ? ` ✓ Withdrawn and kept: ${done.unknownWithdrawn} earlier line${done.unknownWithdrawn === 1 ? "" : "s"}, each with a correction row; never deleted.` : ` Not withdrawn: ${again.out.trim().split("\n").pop()}`);
@@ -872,7 +874,7 @@ async function offerFolder(paths, key, dir) {
872
874
  const report = found?.folder;
873
875
  say();
874
876
  if (counted.code !== 0 || !report) { say(` ${counted.out.trim().split("\n").filter(Boolean).pop() ?? "folder: it could not be read"}. Nothing was sent.`); return; }
875
- say(` Copied session folder · ${report.stretches} stretch${report.stretches === 1 ? "" : "es"} (${report.skipped} already among this computer's own sessions, skipped) · ${report.days} day${report.days === 1 ? "" : "s"} · ${report.hours} reconstructed hours${report.first ? ` · ${report.first} … ${report.last}` : ""}`);
877
+ say(` Copied session folder · ${report.stretches} stretch${report.stretches === 1 ? "" : "es"} (${report.skipped} already among this computer's own sessions, skipped) · ${report.days} day${report.days === 1 ? "" : "s"} · measured by WorkTrust on arrival${report.first ? ` · ${report.first} … ${report.last}` : ""}`);
876
878
  if (!report.days) { say(" Nothing to send: every day of the copy is already among this computer's own sessions."); return; }
877
879
  say(" Hours reconstructed from the copy's own clocks: shown with their origin, never verified hours. Never text.");
878
880
  if (has("dry-run")) { say(" Dry run: nothing was sent."); return; }
@@ -1104,7 +1106,7 @@ async function measuredHere() {
1104
1106
  if (!m || !m.stretches) { say(" Measured here, last 30 days: no finished work stretch yet."); return; }
1105
1107
  const of = (part, whole, one, many) => `${part} of ${whole} ${whole === 1 ? one : many}`;
1106
1108
  say();
1107
- say(` Measured here, last 30 days: ${m.stretches} work stretch${m.stretches === 1 ? "" : "es"} · ${m.hours >= 1 ? `${m.hours} h` : "under 1 h"}`);
1109
+ say(` Measured here, last 30 days: ${m.stretches} work stretch${m.stretches === 1 ? "" : "es"} (the hours are WorkTrust's: see the app)`);
1108
1110
  if (m.delivered) say(` verified before delivery ${of(m.verified_first, m.delivered, "stretch that delivered", "stretches that delivered")}`);
1109
1111
  if (m.failures) say(` recovered failures ${of(m.recovered, m.failures, "failed tool call", "failed tool calls")} (${m.blind_retries} retried unchanged)`);
1110
1112
  if (m.steers) say(` steering that worked ${of(m.effective_steers, m.steers, "time you stepped in", "times you stepped in")}`);
@@ -1129,7 +1131,7 @@ function claudeKeepsDays() {
1129
1131
  async function preserve() {
1130
1132
  const script = join(HERE, "preserve.mjs");
1131
1133
  if (!existsSync(script)) fail("preserve runs from the package: npx worktrust@latest preserve");
1132
- const child = spawn(process.execPath, [script, ...args.filter((arg) => arg !== "preserve")], { stdio: "inherit", env: { ...process.env, WORKTRUST_COLLECTOR: `worktrust-cli/${CLI_VERSION}` } });
1134
+ const child = spawn(process.execPath, [...NODE_FLAGS, script, ...args.filter((arg) => arg !== "preserve")], { stdio: "inherit", env: { ...process.env, WORKTRUST_COLLECTOR: `worktrust-cli/${CLI_VERSION}` } });
1133
1135
  process.exitCode = await new Promise((resolve) => child.on("exit", (code) => resolve(code ?? 1)));
1134
1136
  }
1135
1137
 
@@ -1155,7 +1157,7 @@ function help() {
1155
1157
  say(" --export <path> a ChatGPT or Claude data export (the zip, its folder, conversations.json, a conversations part or the manifest) as history:");
1156
1158
  say(" hours reconstructed from its clocks, shown with their origin, never verified hours (asks first);");
1157
1159
  say(" on its days the export replaces the product's earlier connector lines (withdrawn, kept)");
1158
- say(" --withdraw-unknown with --export: yes in advance to withdrawing the earlier lines an AI app reported for those days");
1160
+ say(" --withdraw-unknown with --export: yes in advance to withdrawing the earlier lines your connector of that vendor reported for those days under no product");
1159
1161
  say(" --from-folder <dir> your own copy of an AI app's session folder (a backed-up ~/.claude/projects, ~/.codex/sessions):");
1160
1162
  say(" days this computer's own sessions lack, reconstructed, never verified hours (asks first)");
1161
1163
  say(" worktrust disconnect take WorkTrust out of every AI app here (asks first)");
@@ -1172,12 +1174,13 @@ function help() {
1172
1174
  }
1173
1175
 
1174
1176
  // THE BARE COMMAND COUPLES (owner, 2026-10-03: "zo kort mogelijk"). `npx worktrust` on a computer
1175
- // without a key here shows the plan and asks, exactly as `connect` does; with one it says what is
1176
- // coupled, so running it twice never re-pairs by surprise.
1177
+ // An existing key shows the current coupling; no key starts the pairing plan.
1177
1178
  // AN AGENT DOES NOT RUN WORKTRUST FOR A PERSON (owner, 2026-10-08; AGENTS.md). The commands that change what this
1178
1179
  // computer sends, couples or rebuilds are the person's to run in their own terminal: in an AI agent's shell they stop
1179
1180
  // before anything is read or written, --yes included. The hook and the MCP bridge are started by the agent's client
1180
1181
  // itself and stay as they are; `status` only reads.
1182
+ async function main() {
1183
+ if (Number(process.versions.node.split(".")[0]) < 18) fail("needs Node 18 or later (fetch is built in from 18).");
1181
1184
  const AGENT_ENV = ["CLAUDECODE", "CLAUDE_CODE_ENTRYPOINT", "CODEX_SANDBOX", "CODEX_CI", "GEMINI_CLI", "CURSOR_AGENT", "OPENCODE", "CLINE_ACTIVE", "AIDER_CHAT", "ANTIGRAVITY_AGENT", "WINDSURF_AGENT"];
1182
1185
  const PERSON_ONLY = new Set(["default", "connect", "update", "history", "disconnect", "preserve", "codex", "antigravity", "sources", "web", "import", "orchestration", "mod"]);
1183
1186
  const agentShell = AGENT_ENV.find((name) => process.env[name] && process.env[name] !== "0");
@@ -1185,7 +1188,7 @@ if (agentShell && PERSON_ONLY.has(command)) {
1185
1188
  say();
1186
1189
  say(` worktrust${command === "default" ? "" : ` ${command}`} is run by the person, in their own terminal, never by an AI agent for them (this shell is an agent's: ${agentShell}).`);
1187
1190
  say(" Nothing was read, sent or changed. See AGENTS.md in the package: https://www.npmjs.com/package/worktrust");
1188
- process.exit(3);
1191
+ return (process.exitCode = 3);
1189
1192
  }
1190
1193
 
1191
1194
  /**
@@ -1219,9 +1222,9 @@ async function relayToNewest() {
1219
1222
  const child = platform() === "win32" ? spawn(["npx", ...argv].map(quote).join(" "), { stdio: "inherit", env, shell: true }) : spawn("npx", argv, { stdio: "inherit", env });
1220
1223
  const code = await new Promise((done) => { child.on("error", () => done(null)); child.on("close", (exit) => done(exit)); });
1221
1224
  if (code === null) { say(" The newest could not be started; this version runs instead."); return; }
1222
- process.exit(code);
1225
+ process.exitCode = code; return true;
1223
1226
  }
1224
- await relayToNewest();
1227
+ if (await relayToNewest()) return;
1225
1228
 
1226
1229
  if (command === "version") say(CLI_VERSION);
1227
1230
  else if (command === "default") { if (keyStore.load()) await again(); else await connect(); }
@@ -1248,3 +1251,6 @@ else if (command === "orchestration") {
1248
1251
  const { reportFile } = await import("./orchestration-report.mjs"); reportFile(args.slice(1));
1249
1252
  }
1250
1253
  else help();
1254
+
1255
+ }
1256
+ try { await main(); } catch (error) { if (!(error instanceof CliFailure)) throw error; process.exitCode = 1; }