worktrust 0.10.34 → 0.10.36

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/worktrust.mjs CHANGED
@@ -76,7 +76,7 @@ const command = args.includes("--help") ? "help" : args.includes("--version") ?
76
76
  const flag = (name) => { const at = args.indexOf(`--${name}`); return at >= 0 ? args[at + 1] : undefined; };
77
77
  const has = (name) => args.includes(`--${name}`);
78
78
  /** 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). */
79
- const CLI_VERSION = "0.10.34";
79
+ const CLI_VERSION = "0.10.36";
80
80
  /**
81
81
  * HOW THIS CLI MEASURES, AS A NUMBER OF ITS OWN (0.10.31; owner, 2026-10-28: 0.10.30 offered a re-measure it had no reason
82
82
  * to offer). Raised ONLY when what is measured changes: the timeline, the seconds, the tokens, the steering, the session
@@ -90,12 +90,19 @@ const CLI_VERSION = "0.10.34";
90
90
  * existing data a re-measure would repack is 4 headless lines of one person on 2 days, none scheduled, none with a person's
91
91
  * second and none under the 60 s floor, so a re-measure would move no figure the passport shows; raising would offer every
92
92
  * person a re-measure for nothing. New runs arrive folded from 0.10.33 on.
93
+ * 0.10.35 RAISES IT TO 3 (owner, 2026-10-30): a new READER, Gemini CLI's own session files, so a computer with Gemini CLI has
94
+ * days no earlier rules measured; and every line now names its AI app at the door (source_app, 20261031100000), which lines
95
+ * measured before carry only when re-measured. Raising is what earlier readers would have done had the number existed (it
96
+ * came with 0.10.31): `update` offers the re-measure once, its day digests change with the rules, so the re-measure sends
97
+ * every day again; WorkTrust replaces only the lines of the two buckets (other apps, app not recorded) that name no app
98
+ * (20261031100200) and carries every other line as it is: no figure moves, the Other apps hours move to their app's row.
93
99
  */
94
- const MEASURE_RULES = 2;
100
+ const MEASURE_RULES = 3;
95
101
  /** What each measure-rules version changed, in the words the re-measure offer says (one entry per raise, never rewritten). */
96
102
  const MEASURE_CHANGES = {
97
103
  1: ["each answer's tokens counted once", "nothing lost at midnight", "when each stretch began", "how you steered the agent", "what the seconds were", "more AI apps", "how each session was started"],
98
104
  2: ["which subagents were active at once, and how their failed steps were recovered", "whether each agent call completed", "who wrote each turn of a run no person started"],
105
+ 3: ["Gemini CLI's sessions", "which AI app each earlier line came from (Copilot in VS Code, Gemini CLI and the other apps get their own rows)"],
99
106
  };
100
107
  const ORIGIN = (flag("origin") ?? process.env.WORKTRUST_ORIGIN ?? "https://app.worktrust.io").replace(/\/$/, "");
101
108
  const MCP = flag("url") ?? process.env.WORKTRUST_MCP_URL ?? `${ORIGIN}/api/mcp`;
@@ -438,10 +445,10 @@ function proof(device, url, body) {
438
445
  }
439
446
 
440
447
  /** Whether the door accepts a key: one call that reads nothing back. */
441
- async function accepted(url, token, device) {
448
+ async function accepted(url, token, device, agentTail = "") {
442
449
  try {
443
450
  const body = JSON.stringify({ jsonrpc: "2.0", id: 0, method: "tools/list" });
444
- const response = await fetch(url, { method: "POST", headers: { "content-type": "application/json", accept: "application/json", authorization: `Bearer ${token}`, "user-agent": `worktrust-bridge worktrust-cli/${CLI_VERSION}`, ...proof(device, url, body) }, body, redirect: "error", signal: AbortSignal.timeout(5000) });
451
+ const response = await fetch(url, { method: "POST", headers: { "content-type": "application/json", accept: "application/json", authorization: `Bearer ${token}`, "user-agent": `worktrust-bridge worktrust-cli/${CLI_VERSION}${agentTail}`, ...proof(device, url, body) }, body, redirect: "error", signal: AbortSignal.timeout(5000) });
445
452
  if (response.status === 401 || response.status === 403) return false;
446
453
  if (response.status !== 200) return null;
447
454
  const answer = await response.json();
@@ -588,7 +595,8 @@ async function hook() {
588
595
  if (has("hermes") || has("goose")) return sessionEnd();
589
596
  const key = await freshKey();
590
597
  if (!key) return;
591
- const child = spawn(moduleExecutable(HERE), [...moduleArgs(HERE, "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, WORKTRUST_MEASURE_RULES: String(MEASURE_RULES), WORKTRUST_HISTORY_SCOPE: historyQueueScope(key.token), ...(key.device ? { WORKTRUST_DEVICE_KEY: key.device } : {}) } }); // 0.10.20: the hook names the version that started it, beside each line
598
+ await followDoorWish(key);
599
+ const child = spawn(moduleExecutable(HERE), [...moduleArgs(HERE, "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, ...doorModeEnv(), WORKTRUST_MEASURE_RULES: String(MEASURE_RULES), WORKTRUST_HISTORY_SCOPE: historyQueueScope(key.token), ...(key.device ? { WORKTRUST_DEVICE_KEY: key.device } : {}) } }); // 0.10.20: the hook names the version that started it, beside each line
592
600
  process.exitCode = await new Promise((resolve, reject) => { child.on("error", reject); child.on("close", (code) => resolve(code ?? 1)); });
593
601
  }
594
602
 
@@ -643,16 +651,19 @@ async function update() {
643
651
  say(` WorkTrust · update ${hostname().replace(/\.local$/i, "")} to ${CLI_VERSION}`);
644
652
  say();
645
653
  const paths = await scripts();
654
+ if (!doorState() && !has("dry-run")) saveDoorState({ mode: await chooseDoor(), asked: new Date().toISOString() }); // once, for a computer coupled before 0.10.37
655
+ const doorIsOff = doorOff();
646
656
  const plan = await run(paths["setup-mcp.mjs"], ["--bridge", STABLE], PLACEHOLDER, true);
647
657
  // AGREED BEFORE, REFRESHED WITHOUT A QUESTION (0.10.30): an app or hook the person said yes to is brought onto this
648
658
  // version's launcher; only what is NEW here is shown in full and asked about, and --yes leaves the new ones as they are.
649
659
  const agreed = await consent();
650
660
  say(" Every AI app found here gets the WorkTrust door, the local command that reads the key:");
651
- const found = planLines(plan.out, true).filter((line) => !line.includes("not on this machine"));
661
+ const found = doorIsOff ? [] : planLines(plan.out, true).filter((line) => !line.includes("not on this machine"));
662
+ if (doorIsOff) say(` the door stays off here (hours only, ${DOOR_SWITCH})`);
652
663
  const apps = [...new Set(found.map(labelOf).filter(Boolean))], fresh = apps.filter((app) => !agreed.has(`door:${app}`));
653
664
  for (const app of apps) if (!fresh.includes(app)) say(` ✓ ${app}: refreshed (${agreed.said(`door:${app}`)})`);
654
665
  for (const line of found) if (fresh.includes(labelOf(line))) say(`${line} · new`);
655
- if (found.length === 0) say(" (no AI app found here)");
666
+ if (found.length === 0 && !doorIsOff) say(" (no AI app found here)");
656
667
  const hookFresh = !agreed.has("session-hook");
657
668
  say(` The session hook and ${STABLE} are brought to ${CLI_VERSION}.`);
658
669
  say(hookFresh ? ` + Session hook: ${join(homedir(), ".claude", "settings.json")} → SessionStart, SessionEnd, PreCompact and (at most once an hour) Stop run it · new` : ` ✓ Session hook: refreshed (${agreed.said("session-hook")}; since 0.10.32 it also runs after an answer, at most once an hour, so a long session's finished days arrive the same day)`);
@@ -672,8 +683,8 @@ async function update() {
672
683
  say(` ✓ ${STABLE} is now ${CLI_VERSION}`);
673
684
  // Out first, then in: an app that held a key of its own (a hand-made entry) moves onto the bridge. An app not agreed to is not touched.
674
685
  const skipArgs = skip.length > 0 ? ["--skip", skip.join(",")] : [];
675
- await run(paths["setup-mcp.mjs"], ["--remove", "--write", ...skipArgs], key.token, true);
676
- if ((await run(paths["setup-mcp.mjs"], ["--write", "--bridge", STABLE, ...skipArgs], key.token)).code !== 0) fail("coupling the AI apps failed; the output above says where.");
686
+ await run(paths["setup-mcp.mjs"], ["--remove", "--write", ...skipArgs], key.token, true); // hours only: nothing is skipped (no app was offered), so every door comes out
687
+ if (!doorIsOff && (await run(paths["setup-mcp.mjs"], ["--write", "--bridge", STABLE, ...skipArgs], key.token)).code !== 0) fail("coupling the AI apps failed; the output above says where.");
677
688
  const hookArgs = ["--install", "--via", STABLE];
678
689
  if (hookOn && (await run(paths["log-session.mjs"], hookArgs, key.token, false)).code !== 0) fail("installing the session hook failed; the output above says where.");
679
690
  for (const name of [...apps.filter((app) => !skip.includes(app)).map((app) => `door:${app}`), ...(hookOn ? ["session-hook"] : [])]) agreed.agree(name, "typed");
@@ -681,9 +692,10 @@ async function update() {
681
692
  // Codex installed since, or a No said at connect: the one question, asked again (or "already set").
682
693
  await offerCodex();
683
694
  await offerAntigravity();
684
- const reported = await accepted(key.url, key.token, key.device);
695
+ const reported = await accepted(key.url, key.token, key.device, doorModeAgent());
685
696
  say(reported === true ? ` ✓ WorkTrust received CLI version ${CLI_VERSION}.` : " ! Installed locally. WorkTrust could not confirm the version yet; it will be reported on the next connection.");
686
697
  await offerRebuild(previous, paths, key);
698
+ doubleDoorNotice();
687
699
  say();
688
700
  say(" Done. Quit your AI apps completely and open them again to use the updated CLI.");
689
701
  }
@@ -725,6 +737,7 @@ async function connect() {
725
737
  say();
726
738
  if (has("dry-run")) { say(" Dry run: nothing was written and nothing was sent."); return; }
727
739
  if (!(await ask("Continue?"))) { say(" Stopped. Nothing was written and nothing was sent."); return; }
740
+ const doorChoice = await chooseDoor();
728
741
  await prepareBundledRuntime();
729
742
  const agreed = await consent(); // read before anything is written, so what this run writes is not taken for an earlier yes
730
743
 
@@ -748,7 +761,9 @@ async function connect() {
748
761
  saveStableEntry();
749
762
  say(` ✓ Key kept in ${KEY_PLACE}`);
750
763
  }
751
- if ((await run(paths["setup-mcp.mjs"], direct ? ["--write"] : ["--write", "--bridge", STABLE], token)).code !== 0) fail("coupling the AI apps failed; the output above says where.");
764
+ saveDoorState({ mode: doorChoice, asked: new Date().toISOString() });
765
+ if (doorChoice === "hours_only") say(` ✓ Hours only: no AI app gets the WorkTrust door (${DOOR_SWITCH})`);
766
+ else if ((await run(paths["setup-mcp.mjs"], direct ? ["--write"] : ["--write", "--bridge", STABLE], token)).code !== 0) fail("coupling the AI apps failed; the output above says where.");
752
767
  say();
753
768
  // The old key ends now that the new one is in place (never before: a failed pairing must not leave the computer uncoupled).
754
769
  if (previous?.token) await releasePrevious(previous, pairing.prefix);
@@ -759,7 +774,7 @@ async function connect() {
759
774
  if ((await run(paths["log-session.mjs"], hookArgs, token, false, { WORKTRUST_CODEX_OFFER: "1" })).code !== 0) fail("installing the session hook failed; the output above says where.");
760
775
  // WHAT WAS AGREED HERE (0.10.30): the apps and the hook this "Continue?" covered; another account starts with none from before.
761
776
  if (switched) agreed.reset();
762
- for (const name of [...new Set(foundApps.map(labelOf).filter(Boolean))].map((app) => `door:${app}`).concat("session-hook")) agreed.agree(name, has("yes") ? "flag" : "typed");
777
+ for (const name of (doorChoice === "hours_only" ? [] : [...new Set(foundApps.map(labelOf).filter(Boolean))].map((app) => `door:${app}`)).concat("session-hook")) agreed.agree(name, has("yes") ? "flag" : "typed");
763
778
  await offerCodex();
764
779
  await offerAntigravity();
765
780
  if (switched) { say(); say(" Earlier work on this computer is not offered: it was coupled to another account before. Only work from now on goes to this account."); }
@@ -768,6 +783,7 @@ async function connect() {
768
783
  // ONE LINE, NO CHANGE (2026-10-06): Claude Code deletes what the hook measures from; `preserve --apply` keeps it, on a yes.
769
784
  const keeps = claudeKeepsDays();
770
785
  if (keeps !== null && keeps < 90) say(` Claude Code deletes sessions after ${keeps} days. Keep them: npx worktrust@latest preserve --apply`);
786
+ doubleDoorNotice();
771
787
  say(" Done. Quit your AI apps completely and open them again. This computer appears in WorkTrust");
772
788
  say(" under Sources → CLI once one of them has spoken.");
773
789
  }
@@ -799,7 +815,7 @@ async function offerHistory(paths, token, devicePem, url = MCP, rebuild = false,
799
815
  if (!has("history") && !agreedInAdvance && !(rebuild ? await ask("Send them (re-measured; this computer's earlier lines for these days are replaced, a day is counted once)?", false) : await ask("Send these as history (hours and tokens per day; never text)?", false))) { historyDone(false); say(" Not sent. Send them later with: npx worktrust"); return; }
800
816
  // Marked unfinished before the first batch leaves (0.10.9): a send stopped halfway (Ctrl+C, a closed lid) is finished by the next run.
801
817
  historyDone(false);
802
- const sent = await run(paths["log-session.mjs"], ["--history", ...(rebuild ? ["--rebuild"] : []), ...(has("retry-review") ? ["--retry-review"] : [])], token, true, env);
818
+ const sent = await run(paths["log-session.mjs"], ["--history", ...(rebuild ? ["--rebuild"] : []), ...(rebuild && has("force-days") ? ["--force-days"] : []), ...(has("retry-review") ? ["--retry-review"] : [])], token, true, env);
803
819
  historyDone(sent.code === 0);
804
820
  // WHAT ACTUALLY HAPPENED, FROM THE DOOR'S RECEIPTS (owner, 2026-10-10): a re-measure in which nothing changed must not say
805
821
  // "replaced". The hook sums the receipts of every batch and prints one line; without it (an older hook) the sentence stays neutral.
@@ -823,15 +839,24 @@ async function offerHistory(paths, token, devicePem, url = MCP, rebuild = false,
823
839
  if (Number(did?.delivery?.review) > 0) say(` ${did.delivery.review} lines are waiting for review. Earlier measurements remain unchanged. Reconnecting or repeating the import does not approve them.`);
824
840
  // KEPT ON THE SERVER (0.10.27; owner, 2026-10-21): what did not arrive stays here and goes again by itself; nothing to resume by hand.
825
841
  if (Number(did?.delivery?.waiting) > 0) say(" Some batches did not reach WorkTrust yet. They stay on this computer and are sent again by themselves the next time npx worktrust or your AI app's hook runs.");
826
- if (Number(did?.delivery?.refused) > 0) say(` WorkTrust closed an earlier run of ${did.delivery.refused} lines (it missed a batch for seven days): run npx worktrust@latest history again to send them as a new run.`);
842
+ // A REFUSAL IN WORKTRUST'S OWN WORDS (0.10.35 for older measure rules; every final refusal since 2026-10-31): the hook passes
843
+ // the door's sentence on, cleaned. Without one (a batch let go on an earlier send, or one too large for any call) the count
844
+ // alone, never a guessed reason: 0.10.35 said "it missed a batch for seven days" of a batch refused for its lines.
845
+ if (Number(did?.delivery?.refused) > 0) say(typeof did.delivery.said === "string" ? ` WorkTrust refused ${did.delivery.refused} lines for good: ${did.delivery.said.replace(/[\u0000-\u001f\u007f-\u009f]/g, " ").replace(/^history run refused:\s*/, "").slice(0, 400)}` : ` WorkTrust refused ${did.delivery.refused} lines for good; nothing of them was stored and they are not sent again.`);
846
+ // THE RUN, AS WORKTRUST HOLDS IT (2026-10-31): the hook counts each run's batches against the receipts. A run missing a batch
847
+ // is never "re-measured" (on 2026-10-30 three receipts of a run of four printed "holds all 3 batches"): WorkTrust rebuilds
848
+ // a run's days only once every batch has arrived. A batch still on its way is said above, and goes again by itself.
849
+ const staging = rebuild && did?.run && Number.isInteger(did.run.batches) && Number.isInteger(did.run.arrived) ? did.run : null;
850
+ const notWhole = staging?.whole === false;
851
+ if (notWhole && (!Number(did?.delivery?.waiting) || n(staging.refused) > 0)) say(` ✗ Not re-measured: WorkTrust holds ${staging.arrived} of ${staging.batches} batches of this run and rebuilds nothing until all of them have arrived. Nothing was replaced; your earlier lines keep counting.`);
827
852
  // A STAGED RUN (0.10.27): WorkTrust holds every batch and rebuilds the days itself once the run is whole; the receipts say what it kept.
828
- if (rebuild && n(did?.staged) > 0 && !Number(did?.delivery?.review) && !Number(did?.delivery?.waiting)) {
829
- say(` ✓ Re-measured. WorkTrust holds all ${n(did.staged)} batches (${n(did.kept)} lines) and rebuilds these days itself, every AI app together, a day counted once. Sources › Logs shows it while it works.`);
853
+ if (rebuild && staging?.whole === true && n(did?.staged) > 0 && sent.code === 0 && !Number(did?.delivery?.review) && !Number(did?.delivery?.waiting)) {
854
+ say(` ✓ Re-measured. WorkTrust holds all ${staging.batches} batches (${n(did.kept)} lines) and rebuilds these days itself, every AI app together, a day counted once. Sources › Logs shows it while it works.`);
830
855
  // WHERE IT WAITS (0.10.32): the receipt of the run's last batch names its place in WorkTrust's queue and a time; absent, nothing is guessed.
831
856
  const queued = did?.queued;
832
857
  if (queued && Number.isInteger(queued.position) && queued.position >= 1 && Number.isFinite(Number(queued.eta_minutes))) say(` queued, position ${queued.position}, about ${Math.max(1, Math.ceil(Number(queued.eta_minutes)))} min`);
833
858
  }
834
- else if (rebuild && !Number(did?.delivery?.review) && !Number(did?.delivery?.waiting)) 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.");
859
+ else if (rebuild && !notWhole && !Number(did?.delivery?.review) && !Number(did?.delivery?.waiting)) 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.");
835
860
  else if (!rebuild) say(sent.code === 0 ? " ✓ Sent as history. Activity is recorded with its origin; independent verification and passport publication are separate. 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.");
836
861
  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)` : ""}.`);
837
862
  }
@@ -980,12 +1005,15 @@ async function offerExport(paths, key, path) {
980
1005
  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; }
981
1006
  const product = EXPORT_PRODUCT[report.vendor] ?? report.vendor, connector = EXPORT_CONNECTOR[report.vendor] ?? report.vendor;
982
1007
  if (!report.days) { say(` ${product} export · ${report.conversations} conversations, none with a clock to place: nothing to send.`); return true; }
983
- say(` ${product} export · ${report.conversations} conversations · ${report.days} days · ${String(report.first).slice(0, 7)} … ${String(report.last).slice(0, 7)}`);
1008
+ const cuts = Array.isArray(report.cut) ? report.cut : [];
1009
+ say(` ${product} export${cuts.length > 0 ? ", cut off" : ""} · ${report.conversations} conversations · ${report.days} days · ${String(report.first).slice(0, 7)} … ${String(report.last).slice(0, 7)}`);
1010
+ // A DOWNLOAD CUT OFF (2026-10-31): what the archive held whole before the cut is read, and the person is told it is not the whole export.
1011
+ for (const cut of cuts) say(` The archive was cut off after ${cut.last} (part ${cut.parts}); ${report.conversations} conversations read. Nothing past the cut is read: this is not the whole export. Download it again for the rest; a line already received is kept once.`);
984
1012
  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.");
985
1013
  // LEFT OUT AND COUNTED (0.10.18): a conversation whose kept fields outgrew the reader's budget is passed over, never the export.
986
1014
  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.`);
987
1015
  if (has("dry-run")) { say(" Dry run: nothing was sent."); return false; }
988
- 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; }
1016
+ if (!has("history") && !(await ask(cuts.length > 0 ? "Send what was read before the cut as history (reconstructed hours per day; never text)?" : "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; }
989
1017
  const sent = await run(paths["log-session.mjs"], ["--history", "--export", path], key.token, true, env);
990
1018
  say(sent.code === 0 ? ` ✓ Sent as history. It shows in WorkTrust as ${product}, reconstructed, never as verified hours; a line already received is kept once.` : ` Not all of it arrived. Run npx worktrust history --export ${path} again: a line already received is kept once.`);
991
1019
  if (sent.code !== 0) return false;
@@ -1266,6 +1294,7 @@ async function status() {
1266
1294
  say(key ? ` Key: in ${KEY_PLACE}, ${key.device ? "bound to this computer, " : ""}last renewed ${String(key.renewedAt ?? "").slice(0, 10) || "never"}` : " Key: not on this computer (or written into the apps' settings with --direct)");
1267
1295
  if (key) say(key.account ? ` Account: ${key.account}${key.coupledAt ? `, coupled ${String(key.coupledAt).slice(0, 10)}` : ""}` : " Account: not recorded (coupled by an older version; `npx worktrust connect` records it)");
1268
1296
  say(sessionHookHere() ? " Session hook: installed" : " Session hook: not installed");
1297
+ say(` AI work lines: ${doorLine()}`);
1269
1298
  // A TRANSCRIPT THE HOOK COULD NOT READ (0.10.32): the count of its last run that had any, never which file; WorkTrust has the count too.
1270
1299
  { let unread = null; try { unread = JSON.parse(readFileSync(join(HOME_DIR, "sessions.json"), "utf8")).__unreadable ?? null; } catch { /* no state yet */ }
1271
1300
  if (Number(unread?.count) > 0) say(` Transcripts: ${unread.count} could not be read on ${String(unread.at).slice(0, 10)}; their days are not measured until they can be (WorkTrust was told the count, nothing else)`); }
@@ -1354,6 +1383,107 @@ async function gitCommits() {
1354
1383
  process.exitCode = await gitMain(sub, { say, ask, send, consent: await consent(), salt: archiveSalt(), dryRun: has("dry-run") });
1355
1384
  }
1356
1385
 
1386
+ /**
1387
+ * HOURS ONLY, OR ALSO WORK LINES (owner, 2026-10-31, after an engineer: "every session loads ~600 tokens from the WorkTrust
1388
+ * MCP"). The passport's hours come from the session hook, which reads the AI apps' own transcripts and needs no door; the
1389
+ * door adds only the AI's own `log_work` lines, and loads its instruction (and, in clients that load every tool, its tool
1390
+ * definitions) into every session. So the person chooses, here, and the choice is kept in ~/.worktrust/door.json (600):
1391
+ * `mcp off` takes the door out of every app and `update` leaves it out; `mcp on` puts it back. The hook runs in both, and
1392
+ * names the mode to WorkTrust beside the CLI version (a closed word in its user-agent), so a pause in work lines reads as
1393
+ * the person's choice. Turning the door on sends nothing from the off period: work lines are live only, and earlier work
1394
+ * goes only through `history`, on the person's yes.
1395
+ */
1396
+ const DOOR_FILE = join(HOME_DIR, "door.json");
1397
+ const DOOR_MODES = ["hours_only", "work_lines"];
1398
+ const DOOR_SWITCH = "npx worktrust mcp on / mcp off";
1399
+ function doorState() { try { const state = JSON.parse(readPrivateFile(DOOR_FILE) ?? "null"); return DOOR_MODES.includes(state?.mode) ? state : null; } catch { return null; } }
1400
+ function saveDoorState(next) { if (has("dry-run")) return; try { ensureHome(); writePrivateFile(DOOR_FILE, `${JSON.stringify({ ...(doorState() ?? {}), ...next, ...(next.mode && next.mode !== doorState()?.mode ? { since: new Date().toISOString() } : {}) })}\n`); } catch { /* not kept: asked again next time */ } }
1401
+ const doorOff = () => doorState()?.mode === "hours_only";
1402
+ /** The mode and the moment it last changed here (whole seconds), so the last change wins against a wish from Sources. */
1403
+ const doorSaid = () => { const state = doorState(); if (!state) return null; const at = Math.floor(Date.parse(state.since ?? state.asked ?? "") / 1000); return Number.isFinite(at) && at > 0 ? `${state.mode}.${at}` : state.mode; };
1404
+ const doorModeEnv = () => (doorSaid() ? { WORKTRUST_DOOR_MODE: doorSaid() } : {});
1405
+ const doorModeAgent = () => (doorSaid() ? ` worktrust-mode/${doorSaid()}` : "");
1406
+ const doorLine = () => { const state = doorState(); return state ? `${state.mode === "hours_only" ? "off (hours only)" : "on"}${state.since ? ` since ${String(state.since).slice(0, 10)}` : ""}` : "on (not chosen yet: npx worktrust update asks once)"; };
1407
+ /** The first question: Enter, --yes and a closed terminal keep the door, as before; --hours-only and --work-lines say it in advance. */
1408
+ async function chooseDoor() {
1409
+ if (has("hours-only")) return "hours_only";
1410
+ if (has("work-lines")) return "work_lines";
1411
+ say();
1412
+ say(" How should your AI apps work with WorkTrust?");
1413
+ say(" 1 Hours only: the session hook measures your hours; nothing of WorkTrust loads into your sessions");
1414
+ say(" 2 Also let your AI log finished work: the WorkTrust door in each app, about 40 tokens per session");
1415
+ if (has("yes") || has("dry-run") || !process.stdin.isTTY) { say(` Kept: 2, the door, as before. Switch any time: ${DOOR_SWITCH}`); return "work_lines"; }
1416
+ const prompt = createInterface({ input: process.stdin, output: process.stdout });
1417
+ const answer = (await prompt.question(" Which one? [1/2, Enter = 2] ")).trim();
1418
+ prompt.close();
1419
+ return answer === "1" ? "hours_only" : "work_lines";
1420
+ }
1421
+ /**
1422
+ * TWO DOORS IN ONE CLAUDE CODE (owner, 2026-10-31). Claude Code also loads the connectors of the person's claude.ai account,
1423
+ * so a WorkTrust connector added there arrives beside the local door and its instruction loads twice. The local door is the
1424
+ * one to keep (it carries this computer's device key); a claude.ai connector is managed only at claude.ai, so the CLI says
1425
+ * where, once. Claude Code records the connectors it has EVER connected (`claudeAiMcpEverConnected`), not the ones on now,
1426
+ * and asking `claude mcp list` would start every server; so this is a notice, never a removal and never a claim.
1427
+ */
1428
+ function claudeAiDoor() { try { return (JSON.parse(readFileSync(join(homedir(), ".claude.json"), "utf8")).claudeAiMcpEverConnected ?? []).find((name) => typeof name === "string" && /^claude\.ai .*worktrust/i.test(name)) ?? null; } catch { return null; } }
1429
+ function doubleDoorNotice(always = false) {
1430
+ const connector = claudeAiDoor();
1431
+ if (!connector || (!always && doorState()?.noticed)) return;
1432
+ say();
1433
+ say(doorOff() ? ` ! Claude Code has also been connected to your claude.ai WorkTrust connector ("${connector}"): while it is on there, it still loads in your sessions.`
1434
+ : ` ! Claude Code has also been connected to your claude.ai WorkTrust connector ("${connector}"): with the local door, WorkTrust may load twice. Keep the local one (it carries this computer's key).`);
1435
+ say(" Remove the other at https://claude.ai/customize/connectors (the CLI cannot change your claude.ai account).");
1436
+ if (!always) saveDoorState({ noticed: new Date().toISOString() });
1437
+ }
1438
+ /**
1439
+ * THE OWNER'S SWITCH IN SOURCES, DONE HERE (owner, 2026-10-31). At a session's start or end the hook asks WorkTrust, with
1440
+ * this computer's signed key, whether the owner asked for a mode (at most every ten minutes, three seconds at most, silent
1441
+ * on any failure). A wish newer than the last choice made on this computer is done on WorkTrust's own entries in the AI
1442
+ * apps, recorded in door.json and reported back beside the version, which settles it; a choice made here later wins.
1443
+ * Nothing is printed: the hook's output belongs to the AI app.
1444
+ */
1445
+ async function followDoorWish(key) {
1446
+ const state = doorState();
1447
+ if (!key.device || (state?.checkedAt && Date.now() - Date.parse(state.checkedAt) < 10 * 60_000)) return;
1448
+ let wish = null;
1449
+ try {
1450
+ const url = new URL("/api/cli/door", key.url).href, body = "{}";
1451
+ const response = await fetch(url, { method: "POST", headers: { "content-type": "application/json", authorization: `Bearer ${key.token}`, "user-agent": `worktrust-cli/${CLI_VERSION}`, ...proof(key.device, url, body) }, body, redirect: "error", signal: AbortSignal.timeout(3000) });
1452
+ if (response.ok) wish = await response.json();
1453
+ } catch { /* offline: asked again next time */ }
1454
+ saveDoorState({ checkedAt: new Date().toISOString() });
1455
+ if (!DOOR_MODES.includes(wish?.mode) || wish.mode === state?.mode || !(Date.parse(wish.at) > Date.parse(state?.since ?? state?.asked ?? 0))) return;
1456
+ const paths = await scripts();
1457
+ if (wish.mode === "work_lines") { await prepareBundledRuntime(); await run(paths["setup-mcp.mjs"], ["--remove", "--write"], key.token, true); }
1458
+ const done = await run(paths["setup-mcp.mjs"], wish.mode === "hours_only" ? ["--remove", "--write"] : ["--write", "--bridge", STABLE], key.token, true);
1459
+ if (done.code !== 0) return;
1460
+ saveDoorState({ mode: wish.mode, asked: state?.asked ?? new Date().toISOString() });
1461
+ await accepted(key.url, key.token, key.device, doorModeAgent());
1462
+ }
1463
+ async function doorCommand(sub) {
1464
+ say();
1465
+ if (sub !== "off" && sub !== "on") { say(` AI work lines on this computer: ${doorLine()}`); say(" Your hours are measured by the session hook either way."); say(` ${DOOR_SWITCH}`); doubleDoorNotice(true); return; }
1466
+ const key = await freshKey();
1467
+ if (!key) fail("this computer has no WorkTrust key file yet. Run npx worktrust connect.");
1468
+ const paths = await scripts();
1469
+ if (sub === "off") {
1470
+ if ((await run(paths["setup-mcp.mjs"], ["--remove", "--write"], key.token)).code !== 0) fail("taking the door out failed; the output above says where. Nothing was recorded.");
1471
+ saveDoorState({ mode: "hours_only", asked: doorState()?.asked ?? new Date().toISOString() });
1472
+ say(" ✓ Hours only: the WorkTrust door is out of every AI app here, and update leaves it out.");
1473
+ say(" The session hook keeps measuring your hours. npx worktrust mcp on brings the door back.");
1474
+ } else {
1475
+ await prepareBundledRuntime(); ensureHome(); saveStableEntry();
1476
+ await run(paths["setup-mcp.mjs"], ["--remove", "--write"], key.token, true);
1477
+ if ((await run(paths["setup-mcp.mjs"], ["--write", "--bridge", STABLE], key.token)).code !== 0) fail("coupling the AI apps failed; the output above says where. Nothing was recorded.");
1478
+ saveDoorState({ mode: "work_lines", asked: doorState()?.asked ?? new Date().toISOString() });
1479
+ say(" ✓ The WorkTrust door is back: your AI can log finished work from now on. Nothing from the time it was off is sent.");
1480
+ }
1481
+ const reported = await accepted(key.url, key.token, key.device, doorModeAgent());
1482
+ say(reported === true ? " ✓ WorkTrust was told the mode (shown under Sources, Devices)." : " ! Kept here; WorkTrust is told on the next connection.");
1483
+ doubleDoorNotice();
1484
+ say(" Quit your AI apps completely and open them again.");
1485
+ }
1486
+
1357
1487
  function help() {
1358
1488
  say("WorkTrust: couple this computer to your record. Metadata only.");
1359
1489
  say();
@@ -1376,6 +1506,8 @@ function help() {
1376
1506
  say(" --retry-review explicitly retry held batches after support resolves their review");
1377
1507
  say(" --rebuild re-measure them with the current rules; WorkTrust replaces this computer's earlier lines,");
1378
1508
  say(" day by day, never counting a day twice (shows the plan per AI app, asks first; --dry-run: the plan only)");
1509
+ say(" --force-days with --rebuild: send every day again, also the days WorkTrust holds unchanged, so lines");
1510
+ say(" measured before an app was named per line get their app (every AI app at once)");
1379
1511
  say(" --from-archive [dir] send what your archive (preserve --archive) holds of sessions your AI apps already deleted,");
1380
1512
  say(" marked as from your archive: a day this computer's key signed as measured, every other day");
1381
1513
  say(" as reconstructed, never verified hours (shows the plan, asks first)");
@@ -1387,6 +1519,10 @@ function help() {
1387
1519
  say(" days this computer's own sessions lack, reconstructed, never verified hours (asks first)");
1388
1520
  say(" worktrust disconnect take WorkTrust out of every AI app here (asks first)");
1389
1521
  say(" worktrust status what is coupled here");
1522
+ say(" worktrust mcp off hours only: the WorkTrust door out of every AI app here, nothing of it in your sessions;");
1523
+ say(" the session hook keeps measuring your hours, and update leaves the door out");
1524
+ say(" worktrust mcp on the door back in, so your AI can log finished work (about 40 tokens per session)");
1525
+ say(" worktrust mcp which of the two this computer is in");
1390
1526
  say(" worktrust protect-key after update: move credential protection into the OS vault (asks first)");
1391
1527
  say(" worktrust orchestration report --file recording.jsonl inspect local agent metadata; sends nothing");
1392
1528
  say(" worktrust mod the WorkTrust mod for Claude Code: what it counts, and whether it is on");
@@ -1415,7 +1551,9 @@ if (Number(process.versions.node.split(".")[0]) < 18) fail("needs Node 18 or lat
1415
1551
  const AGENT_ENV = ["CLAUDECODE", "CLAUDE_CODE_ENTRYPOINT", "CODEX_SANDBOX", "CODEX_CI", "GEMINI_CLI", "CURSOR_AGENT", "OPENCODE", "CLINE_ACTIVE", "AIDER_CHAT", "ANTIGRAVITY_AGENT", "WINDSURF_AGENT"];
1416
1552
  const PERSON_ONLY = new Set(["default", "connect", "update", "history", "disconnect", "preserve", "codex", "antigravity", "sources", "web", "import", "orchestration", "mod", "protect-key", "git"]);
1417
1553
  const agentShell = AGENT_ENV.find((name) => process.env[name] && process.env[name] !== "0");
1418
- if (agentShell && PERSON_ONLY.has(command)) {
1554
+ // `mcp off` and `mcp on` change what this computer's AI apps load: the person's. Bare `mcp` stays the bridge the apps start.
1555
+ const doorSwitch = command === "mcp" && ["off", "on"].includes(args[args.indexOf("mcp") + 1]);
1556
+ if (agentShell && (PERSON_ONLY.has(command) || doorSwitch)) {
1419
1557
  say();
1420
1558
  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}).`);
1421
1559
  say(" Nothing was read, sent or changed. See AGENTS.md in the package: https://www.npmjs.com/package/worktrust");
@@ -1451,6 +1589,7 @@ if (!["version", "help", "preserve"].includes(command)) {
1451
1589
  }
1452
1590
  if (command === "version") say(CLI_VERSION);
1453
1591
  else if (command === "default") { if (keyStore.load()) await again(); else await connect(); }
1592
+ else if (command === "mcp" && (doorSwitch || args[args.indexOf("mcp") + 1] === "status" || (process.stdin.isTTY && process.stdout.isTTY))) await doorCommand(args[args.indexOf("mcp") + 1]);
1454
1593
  else if (command === "mcp") await bridge();
1455
1594
  else if (command === "hook") await hook();
1456
1595
  else if (command === "connect") await connect();