worktrust 0.10.35 → 0.10.37

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
@@ -58,7 +58,7 @@
58
58
  *
59
59
  * No dependencies: Node 18 or later.
60
60
  */
61
- import { execFileSync, spawn } from "node:child_process";
61
+ import { execFileSync, spawn, spawnSync } from "node:child_process";
62
62
  import { createHash, createPublicKey, generateKeyPairSync, randomBytes, sign } from "node:crypto";
63
63
  import { createServer } from "node:http";
64
64
  import { chmodSync, closeSync, copyFileSync, existsSync, lstatSync, mkdirSync, openSync, readFileSync, readdirSync, renameSync, rmSync, statSync, writeFileSync, writeSync } from "node:fs";
@@ -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.35";
79
+ const CLI_VERSION = "0.10.37";
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
@@ -108,7 +108,7 @@ const ORIGIN = (flag("origin") ?? process.env.WORKTRUST_ORIGIN ?? "https://app.w
108
108
  const MCP = flag("url") ?? process.env.WORKTRUST_MCP_URL ?? `${ORIGIN}/api/mcp`;
109
109
  const HOME_DIR = join(homedir(), ".worktrust");
110
110
  const HERE = dirname(fileURLToPath(import.meta.url));
111
- const SCRIPTS = ["credential-store.mjs", "credential-vault.mjs", "credential-vault-scripts.mjs", "history-outbox.mjs", "setup-mcp.mjs", "log-session.mjs", "count-behaviour.mjs", "transcript-readers.mjs", "session-databases.mjs", "config-edits.mjs", "stretch-evidence.mjs", "chat-exports.mjs", "stack-rules.mjs", "runtime-install.mjs", "orchestration-contract.mjs", "orchestration-evidence.mjs", "orchestration-report.mjs", "claude-mod.mjs", "package-integrity.mjs", "worktrust-launch.mjs", "commit-rules.mjs", "git-commits.mjs"];
111
+ const SCRIPTS = ["credential-store.mjs", "credential-vault.mjs", "credential-vault-scripts.mjs", "history-outbox.mjs", "setup-mcp.mjs", "log-session.mjs", "count-behaviour.mjs", "transcript-readers.mjs", "session-databases.mjs", "config-edits.mjs", "stretch-evidence.mjs", "chat-exports.mjs", "stack-rules.mjs", "runtime-install.mjs", "orchestration-contract.mjs", "orchestration-evidence.mjs", "orchestration-report.mjs", "claude-mod.mjs", "package-integrity.mjs", "worktrust-launch.mjs", "commit-rules.mjs", "git-commits.mjs", "self-update.mjs", "history-progress.mjs"];
112
112
  /** The modules the scripts import by name from beside them; a download keeps that name. */
113
113
  const IMPORTED = new Set(["transcript-readers.mjs", "session-databases.mjs", "config-edits.mjs", "stretch-evidence.mjs", "chat-exports.mjs", "stack-rules.mjs", "runtime-install.mjs", "orchestration-contract.mjs", "orchestration-evidence.mjs", "orchestration-report.mjs", "commit-rules.mjs", "git-commits.mjs"]);
114
114
  const downloaded = (name) => (IMPORTED.has(name) ? name : `${name}.download.mjs`);
@@ -121,6 +121,8 @@ class CliFailure extends Error {}
121
121
  const fail = (line) => { process.stderr.write(`worktrust: ${line}\n`); throw new CliFailure(); };
122
122
  const NODE_FLAGS = process.versions.node === "26.5.0" ? ["--no-concurrent-sparkplug"] : [];
123
123
  const OS = { darwin: "macos", win32: "windows", linux: "linux" }[platform()] ?? "other";
124
+ /** The shells AI agents run commands in (AGENTS.md): a person-only command stops there (main). */
125
+ const AGENT_ENV = ["CLAUDECODE", "CLAUDE_CODE_ENTRYPOINT", "CODEX_SANDBOX", "CODEX_CI", "GEMINI_CLI", "CURSOR_AGENT", "OPENCODE", "CLINE_ACTIVE", "AIDER_CHAT", "ANTIGRAVITY_AGENT", "WINDSURF_AGENT"];
124
126
  const OS_NAME = { macos: "macOS", windows: "Windows", linux: "Linux", other: "this system" }[OS];
125
127
 
126
128
  /**
@@ -164,16 +166,43 @@ function historyQueueScope(token) {
164
166
  catch { return ""; }
165
167
  }
166
168
 
167
- /** Run a script; its output is shown, or collected for the plan. The key travels in the environment only. */
168
- function run(path, scriptArgs, token, collect = false, extraEnv = {}) {
169
+ /** Run a script; its output is shown, or collected for the plan. The key travels in the environment only. `watch` (2026-11-05):
170
+ * `line` hears each line of the collected stdout as it comes (a line it answers true for is its own, a progress event, and is
171
+ * not kept); a Ctrl+C or SIGTERM is passed to the script, which stops safely (the script runs in a process group of its own, so
172
+ * a terminal's Ctrl+C reaches it once, through here), and the answer says `stopped`; a second one calls `now` at once. */
173
+ function run(path, scriptArgs, token, collect = false, extraEnv = {}, watch = null) {
169
174
  return new Promise((resolve) => {
170
- const child = spawn(moduleExecutable(HERE), [...moduleArgs(HERE, basename(path), scriptArgs)], { stdio: collect ? ["ignore", "pipe", "pipe"] : "inherit", env: { ...process.env, WORKTRUST_MCP_URL: MCP, WORKTRUST_MCP_TOKEN: token, WORKTRUST_NODE: NODE, WORKTRUST_NODE_ARGS: JSON.stringify(NODE_ARGS), WORKTRUST_CLI_VERSION: CLI_VERSION, WORKTRUST_MEASURE_RULES: String(MEASURE_RULES), WORKTRUST_HISTORY_SCOPE: historyQueueScope(token), ...extraEnv } });
171
- let out = "";
172
- child.stdout?.on("data", (chunk) => { out += chunk; });
173
- child.stderr?.on("data", (chunk) => { out += chunk; });
174
- child.on("exit", (code) => resolve({ code: code ?? 1, out }));
175
+ const child = spawn(moduleExecutable(HERE), [...moduleArgs(HERE, basename(path), scriptArgs)], { stdio: collect ? ["ignore", "pipe", "pipe"] : "inherit", detached: Boolean(watch) && OS !== "windows", env: { ...process.env, WORKTRUST_MCP_URL: MCP, WORKTRUST_MCP_TOKEN: token, WORKTRUST_NODE: NODE, WORKTRUST_NODE_ARGS: JSON.stringify(NODE_ARGS), WORKTRUST_CLI_VERSION: CLI_VERSION, WORKTRUST_MEASURE_RULES: String(MEASURE_RULES), WORKTRUST_HISTORY_SCOPE: historyQueueScope(token), ...extraEnv } });
176
+ let out = "", pending = "", stops = 0, said = ""; // watched, stderr is kept apart and put first: the last line stays the script's own answer on stdout
177
+ const heard = (text) => { if (!watch.line(text)) out += `${text}\n`; };
178
+ const stop = (signal) => { stops += 1; try { child.kill(signal); } catch { /* already gone */ } if (stops > 1) watch.now?.(); };
179
+ if (watch) { process.on("SIGINT", stop); process.on("SIGTERM", stop); }
180
+ child.stdout?.on("data", (chunk) => {
181
+ if (!watch) { out += chunk; return; }
182
+ pending += chunk; const rows = pending.split("\n"); pending = rows.pop(); for (const row of rows) heard(row);
183
+ });
184
+ child.stderr?.on("data", (chunk) => { if (watch) said += chunk; else out += chunk; });
185
+ // Watched, the answer waits for the streams to close, so the last event is heard before the command speaks.
186
+ child.on(watch ? "close" : "exit", (code) => { if (watch) { process.off("SIGINT", stop); process.off("SIGTERM", stop); if (pending) heard(pending); pending = ""; } resolve({ code: code ?? 1, out: said + out, stopped: stops > 0 }); });
175
187
  });
176
188
  }
189
+ /**
190
+ * THE LONG STEPS, AS THEY GO (owner, incident 2026-11-05: an export of 5,003 conversations read and sent for minutes with nothing
191
+ * on the screen). The hook, asked by WORKTRUST_HISTORY_PROGRESS, prints each step's counts as an event (the read of an export's
192
+ * parts or of the sessions here, each batch); history-progress.mjs draws them (one line rewritten in place on a terminal, plain
193
+ * lines when piped) and closes with the totals. Counts only: never a title, a text or a file's name. AND A SAFE STOP: Ctrl+C
194
+ * (or SIGTERM) asks the hook to stop after abandoning the call in flight; the line is restored, where it stopped is said with how
195
+ * to go on, and the command exits 130. A second Ctrl+C exits at once. An older module without the display runs as before.
196
+ */
197
+ async function sendShown(paths, scriptArgs, token, extraEnv, words = {}) {
198
+ let shown = null;
199
+ try { shown = (await import(pathToFileURL(paths["history-progress.mjs"]).href)).historyProgress?.({ stream: process.stdout }) ?? null; } catch { shown = null; }
200
+ const leave = () => { shown?.stop(words); process.stdout.write("", () => process.exit(130)); };
201
+ const sent = await run(paths["log-session.mjs"], scriptArgs, token, true, { ...extraEnv, ...(shown ? { WORKTRUST_HISTORY_PROGRESS: "1" } : {}) }, { line: (line) => shown?.line(line) ?? false, now: leave });
202
+ if (sent.stopped) { leave(); return new Promise(() => {}); } // the command ends here, 130
203
+ shown?.end();
204
+ return sent;
205
+ }
177
206
 
178
207
  /** `yes` is the answer Enter gives, and the one `--yes` gives: a question whose default is No stays No under --yes. */
179
208
  async function ask(question, yes = true) {
@@ -445,10 +474,10 @@ function proof(device, url, body) {
445
474
  }
446
475
 
447
476
  /** Whether the door accepts a key: one call that reads nothing back. */
448
- async function accepted(url, token, device) {
477
+ async function accepted(url, token, device, agentTail = "") {
449
478
  try {
450
479
  const body = JSON.stringify({ jsonrpc: "2.0", id: 0, method: "tools/list" });
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}`, ...proof(device, url, body) }, body, redirect: "error", signal: AbortSignal.timeout(5000) });
480
+ 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) });
452
481
  if (response.status === 401 || response.status === 403) return false;
453
482
  if (response.status !== 200) return null;
454
483
  const answer = await response.json();
@@ -567,6 +596,7 @@ async function bridge() {
567
596
  try { key = await freshKey(); }
568
597
  catch { key = null; if (message.id !== undefined) answer(message.id, "WorkTrust credential storage is unavailable. Unlock your OS vault and retry; no request was sent."); continue; }
569
598
  if (!key) { if (message.id !== undefined) answer(message.id, "WorkTrust is not connected on this computer: run `npx worktrust connect`."); continue; }
599
+ if (measurePaused()) { if (message.id !== undefined) answer(message.id, "WorkTrust is paused on this computer by its owner (Sources): nothing is sent until it is turned on again."); continue; }
570
600
  try {
571
601
  const response = await fetch(key.url, { method: "POST", headers: { "content-type": "application/json", accept: "application/json, text/event-stream", authorization: `Bearer ${key.token}`, "user-agent": agent, ...(session ? { "mcp-session-id": session } : {}), ...proof(key.device, key.url, line) }, body: line });
572
602
  session = response.headers.get("mcp-session-id") ?? session;
@@ -595,7 +625,11 @@ async function hook() {
595
625
  if (has("hermes") || has("goose")) return sessionEnd();
596
626
  const key = await freshKey();
597
627
  if (!key) return;
598
- 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
628
+ await followDoorWish(key);
629
+ // CLI ACTIVE OFF (owner, 2026-11-05): the owner paused this computer in Sources. Nothing is measured and nothing is sent until
630
+ // it is turned on again; nothing is deleted here or there, and the hook still asks for the wish so turning on is heard.
631
+ if (measurePaused()) return;
632
+ 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
599
633
  process.exitCode = await new Promise((resolve, reject) => { child.on("error", reject); child.on("close", (code) => resolve(code ?? 1)); });
600
634
  }
601
635
 
@@ -650,16 +684,19 @@ async function update() {
650
684
  say(` WorkTrust · update ${hostname().replace(/\.local$/i, "")} to ${CLI_VERSION}`);
651
685
  say();
652
686
  const paths = await scripts();
687
+ if (!doorState() && !has("dry-run")) saveDoorState({ mode: await chooseDoor(), asked: new Date().toISOString() }); // once, for a computer coupled before 0.10.37
688
+ const doorIsOff = doorOff();
653
689
  const plan = await run(paths["setup-mcp.mjs"], ["--bridge", STABLE], PLACEHOLDER, true);
654
690
  // AGREED BEFORE, REFRESHED WITHOUT A QUESTION (0.10.30): an app or hook the person said yes to is brought onto this
655
691
  // version's launcher; only what is NEW here is shown in full and asked about, and --yes leaves the new ones as they are.
656
692
  const agreed = await consent();
657
693
  say(" Every AI app found here gets the WorkTrust door, the local command that reads the key:");
658
- const found = planLines(plan.out, true).filter((line) => !line.includes("not on this machine"));
694
+ const found = doorIsOff ? [] : planLines(plan.out, true).filter((line) => !line.includes("not on this machine"));
695
+ if (doorIsOff) say(` the door stays off here (hours only, ${DOOR_SWITCH})`);
659
696
  const apps = [...new Set(found.map(labelOf).filter(Boolean))], fresh = apps.filter((app) => !agreed.has(`door:${app}`));
660
697
  for (const app of apps) if (!fresh.includes(app)) say(` ✓ ${app}: refreshed (${agreed.said(`door:${app}`)})`);
661
698
  for (const line of found) if (fresh.includes(labelOf(line))) say(`${line} · new`);
662
- if (found.length === 0) say(" (no AI app found here)");
699
+ if (found.length === 0 && !doorIsOff) say(" (no AI app found here)");
663
700
  const hookFresh = !agreed.has("session-hook");
664
701
  say(` The session hook and ${STABLE} are brought to ${CLI_VERSION}.`);
665
702
  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)`);
@@ -679,8 +716,10 @@ async function update() {
679
716
  say(` ✓ ${STABLE} is now ${CLI_VERSION}`);
680
717
  // 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.
681
718
  const skipArgs = skip.length > 0 ? ["--skip", skip.join(",")] : [];
682
- await run(paths["setup-mcp.mjs"], ["--remove", "--write", ...skipArgs], key.token, true);
683
- 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.");
719
+ // WHAT WAS THERE, KEPT IN MEMORY (security review L3): an add that does not finish puts every door it took out back.
720
+ const before = (await run(paths["setup-mcp.mjs"], ["--snapshot"], key.token, true)).out.trim().split("\n").pop() ?? "";
721
+ 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
722
+ if (!doorIsOff && (await run(paths["setup-mcp.mjs"], ["--write", "--bridge", STABLE, ...skipArgs], key.token)).code !== 0) { putBack(paths, key.token, before); fail("coupling the AI apps failed; the doors taken out were put back as they were. The output above says where."); }
684
723
  const hookArgs = ["--install", "--via", STABLE];
685
724
  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.");
686
725
  for (const name of [...apps.filter((app) => !skip.includes(app)).map((app) => `door:${app}`), ...(hookOn ? ["session-hook"] : [])]) agreed.agree(name, "typed");
@@ -688,13 +727,21 @@ async function update() {
688
727
  // Codex installed since, or a No said at connect: the one question, asked again (or "already set").
689
728
  await offerCodex();
690
729
  await offerAntigravity();
691
- const reported = await accepted(key.url, key.token, key.device);
730
+ const reported = await accepted(key.url, key.token, key.device, doorModeAgent());
692
731
  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.");
693
732
  await offerRebuild(previous, paths, key);
733
+ doubleDoorNotice();
694
734
  say();
695
735
  say(" Done. Quit your AI apps completely and open them again to use the updated CLI.");
696
736
  }
697
737
 
738
+ /** `setup-mcp --restore` with the snapshot on stdin: never on a command line, never in a file. */
739
+ function putBack(paths, token, snapshot) {
740
+ if (!snapshot.startsWith("{")) return;
741
+ const done = spawnSync(moduleExecutable(HERE), [...moduleArgs(HERE, basename(paths["setup-mcp.mjs"]), ["--restore"])], { input: snapshot, encoding: "utf8", env: { ...process.env, WORKTRUST_MCP_URL: MCP, WORKTRUST_MCP_TOKEN: token, WORKTRUST_NODE: NODE, WORKTRUST_NODE_ARGS: JSON.stringify(NODE_ARGS) }, timeout: 120_000 });
742
+ process.stdout.write(done.stdout ?? "");
743
+ }
744
+
698
745
  async function connect() {
699
746
  if (has("direct") && keyStore.protected()) fail("Protected credentials use the local bridge; --direct would expose them in app settings.");
700
747
  const host = (flag("name") ?? hostname()).replace(/\.local$/i, "").slice(0, 64);
@@ -732,6 +779,7 @@ async function connect() {
732
779
  say();
733
780
  if (has("dry-run")) { say(" Dry run: nothing was written and nothing was sent."); return; }
734
781
  if (!(await ask("Continue?"))) { say(" Stopped. Nothing was written and nothing was sent."); return; }
782
+ const doorChoice = await chooseDoor();
735
783
  await prepareBundledRuntime();
736
784
  const agreed = await consent(); // read before anything is written, so what this run writes is not taken for an earlier yes
737
785
 
@@ -755,7 +803,9 @@ async function connect() {
755
803
  saveStableEntry();
756
804
  say(` ✓ Key kept in ${KEY_PLACE}`);
757
805
  }
758
- 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.");
806
+ saveDoorState({ mode: doorChoice, asked: new Date().toISOString() });
807
+ if (doorChoice === "hours_only") say(` ✓ Hours only: no AI app gets the WorkTrust door (${DOOR_SWITCH})`);
808
+ 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.");
759
809
  say();
760
810
  // The old key ends now that the new one is in place (never before: a failed pairing must not leave the computer uncoupled).
761
811
  if (previous?.token) await releasePrevious(previous, pairing.prefix);
@@ -766,7 +816,7 @@ async function connect() {
766
816
  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.");
767
817
  // WHAT WAS AGREED HERE (0.10.30): the apps and the hook this "Continue?" covered; another account starts with none from before.
768
818
  if (switched) agreed.reset();
769
- 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");
819
+ 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");
770
820
  await offerCodex();
771
821
  await offerAntigravity();
772
822
  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."); }
@@ -775,6 +825,7 @@ async function connect() {
775
825
  // ONE LINE, NO CHANGE (2026-10-06): Claude Code deletes what the hook measures from; `preserve --apply` keeps it, on a yes.
776
826
  const keeps = claudeKeepsDays();
777
827
  if (keeps !== null && keeps < 90) say(` Claude Code deletes sessions after ${keeps} days. Keep them: npx worktrust@latest preserve --apply`);
828
+ doubleDoorNotice();
778
829
  say(" Done. Quit your AI apps completely and open them again. This computer appears in WorkTrust");
779
830
  say(" under Sources → CLI once one of them has spoken.");
780
831
  }
@@ -787,7 +838,7 @@ async function connect() {
787
838
  */
788
839
  async function offerHistory(paths, token, devicePem, url = MCP, rebuild = false, agreedInAdvance = false) {
789
840
  const env = { WORKTRUST_MCP_URL: url, ...(devicePem ? { WORKTRUST_DEVICE_KEY: devicePem } : {}) };
790
- const counted = await run(paths["log-session.mjs"], ["--history", "--dry-run", "--summary"], token, true, env);
841
+ const counted = await sendShown(paths, ["--history", "--dry-run", "--summary"], token, env);
791
842
  let found = null;
792
843
  try { found = JSON.parse(counted.out.trim().split("\n").pop()); } catch { /* no line: nothing to offer */ }
793
844
  say();
@@ -806,7 +857,7 @@ async function offerHistory(paths, token, devicePem, url = MCP, rebuild = false,
806
857
  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; }
807
858
  // 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.
808
859
  historyDone(false);
809
- 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);
860
+ const sent = await sendShown(paths, ["--history", ...(rebuild ? ["--rebuild"] : []), ...(rebuild && has("force-days") ? ["--force-days"] : []), ...(has("retry-review") ? ["--retry-review"] : [])], token, env);
810
861
  historyDone(sent.code === 0);
811
862
  // WHAT ACTUALLY HAPPENED, FROM THE DOOR'S RECEIPTS (owner, 2026-10-10): a re-measure in which nothing changed must not say
812
863
  // "replaced". The hook sums the receipts of every batch and prints one line; without it (an older hook) the sentence stays neutral.
@@ -830,17 +881,28 @@ async function offerHistory(paths, token, devicePem, url = MCP, rebuild = false,
830
881
  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.`);
831
882
  // 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.
832
883
  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.");
833
- // 0.10.35: a re-measure refused for older measure rules is told in WorkTrust's own words (the hook passes them on, cleaned).
834
- if (Number(did?.delivery?.refused) > 0) say(typeof did.delivery.said === "string" ? ` ${did.delivery.said.replace(/[\u0000-\u001f\u007f-\u009f]/g, " ").slice(0, 400)}` : ` 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.`);
884
+ { const answered = doorAnswer(sent.out); if (answered) say(answered); } // 0.10.37: and why, in WorkTrust's words
885
+ // A REFUSAL IN WORKTRUST'S OWN WORDS (0.10.35 for older measure rules; every final refusal since 2026-10-31): the hook passes
886
+ // 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
887
+ // alone, never a guessed reason: 0.10.35 said "it missed a batch for seven days" of a batch refused for its lines.
888
+ 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.`);
889
+ // THE RUN, AS WORKTRUST HOLDS IT (2026-10-31): the hook counts each run's batches against the receipts. A run missing a batch
890
+ // is never "re-measured" (on 2026-10-30 three receipts of a run of four printed "holds all 3 batches"): WorkTrust rebuilds
891
+ // a run's days only once every batch has arrived. A batch still on its way is said above, and goes again by itself.
892
+ const staging = rebuild && did?.run && Number.isInteger(did.run.batches) && Number.isInteger(did.run.arrived) ? did.run : null;
893
+ const notWhole = staging?.whole === false;
894
+ 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.`);
835
895
  // 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.
836
- if (rebuild && n(did?.staged) > 0 && !Number(did?.delivery?.review) && !Number(did?.delivery?.waiting)) {
837
- 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.`);
896
+ if (rebuild && staging?.whole === true && n(did?.staged) > 0 && sent.code === 0 && !Number(did?.delivery?.review) && !Number(did?.delivery?.waiting)) {
897
+ 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.`);
838
898
  // 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.
839
899
  const queued = did?.queued;
840
900
  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`);
841
901
  }
842
- 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.");
902
+ 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.");
843
903
  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.");
904
+ // 0.10.37 (owner 2026-11-05): an export send's seconds are RECONSTRUCTED, never measured; the door says which (reconstructedSeconds).
905
+ if (did && Number(did.reconstructedSeconds) > 0) say(` Reconstructed by WorkTrust from the export: ${(Number(did.reconstructedSeconds) / 3600).toFixed(1)} h for what this send stored (beside your measured hours, never in them).`);
844
906
  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)` : ""}.`);
845
907
  }
846
908
 
@@ -958,12 +1020,12 @@ async function history() {
958
1020
  async function offerArchive(paths, key) {
959
1021
  const at = process.argv.indexOf("--from-archive"), named = process.argv[at + 1], dir = named && !named.startsWith("--") ? [named] : [];
960
1022
  const env = { WORKTRUST_MCP_URL: key.url, ...(key.device ? { WORKTRUST_DEVICE_KEY: key.device } : {}) };
961
- const plan = await run(paths["log-session.mjs"], ["--history", "--from-archive", ...dir, "--dry-run"], key.token, true, env);
1023
+ const plan = await sendShown(paths, ["--history", "--from-archive", ...dir, "--dry-run"], key.token, env);
962
1024
  say();
963
1025
  for (const line of plan.out.trim().split("\n").filter((text) => !text.startsWith(" ") && !text.startsWith("{") && !text.startsWith("}") && text.trim())) say(` ${line}`);
964
1026
  if (plan.code !== 0 || /Nothing to send/.test(plan.out) || has("dry-run")) return;
965
1027
  if (!(await ask("Send them as history, marked as from your archive?", false))) { say(" Not sent."); return; }
966
- const sent = await run(paths["log-session.mjs"], ["--history", "--from-archive", ...dir], key.token, true, env);
1028
+ const sent = await sendShown(paths, ["--history", "--from-archive", ...dir], key.token, env);
967
1029
  say(sent.code === 0 ? " ✓ Sent as history from your archive. It shows in WorkTrust as earlier work, marked as such, never as verified hours." : ` Not sent: ${sent.out.trim().split("\n").pop()}`);
968
1030
  }
969
1031
 
@@ -980,7 +1042,7 @@ const EXPORT_PRODUCT = { chatgpt: "ChatGPT", "claude-web": "Claude on the web" }
980
1042
  const EXPORT_CONNECTOR = { chatgpt: "ChatGPT", "claude-web": "Claude" };
981
1043
  async function offerExport(paths, key, path) {
982
1044
  const env = { WORKTRUST_MCP_URL: key.url, ...(key.device ? { WORKTRUST_DEVICE_KEY: key.device } : {}) };
983
- const counted = await run(paths["log-session.mjs"], ["--history", "--export", path, "--dry-run", "--summary"], key.token, true, env);
1045
+ const counted = await sendShown(paths, ["--history", "--export", path, "--dry-run", "--summary"], key.token, env);
984
1046
  let found = null;
985
1047
  try { found = JSON.parse(counted.out.trim().split("\n").pop()); } catch { /* no line: the export could not be read */ }
986
1048
  const report = found?.exports?.[0];
@@ -988,15 +1050,21 @@ async function offerExport(paths, key, path) {
988
1050
  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; }
989
1051
  const product = EXPORT_PRODUCT[report.vendor] ?? report.vendor, connector = EXPORT_CONNECTOR[report.vendor] ?? report.vendor;
990
1052
  if (!report.days) { say(` ${product} export · ${report.conversations} conversations, none with a clock to place: nothing to send.`); return true; }
991
- say(` ${product} export · ${report.conversations} conversations · ${report.days} days · ${String(report.first).slice(0, 7)} … ${String(report.last).slice(0, 7)}`);
1053
+ const cuts = Array.isArray(report.cut) ? report.cut : [];
1054
+ // THE READ IN ONE LINE (2026-11-05): conversations, days, months, and what the send will be: the parts read, batches and lines.
1055
+ const plural = (n, one, many) => `${Number(n).toLocaleString("en-US")} ${n === 1 ? one : many}`;
1056
+ const batches = Number.isInteger(found?.batches?.count) ? found.batches.count : null, lines = Array.isArray(found?.batches?.each) ? found.batches.each.reduce((n, one) => n + (Number(one?.lines) || 0), 0) : null;
1057
+ say(` ${product} export${cuts.length > 0 ? ", cut off" : ""} · ${Number(report.conversations).toLocaleString("en-US")} conversations · ${Number(report.days).toLocaleString("en-US")} days · ${String(report.first).slice(0, 7)} … ${String(report.last).slice(0, 7)}${Number.isInteger(report.parts) ? ` · ${plural(report.parts, "part", "parts")}` : ""}${batches !== null ? ` · ${plural(batches, "batch", "batches")}` : ""}${lines !== null ? ` · ${plural(lines, "line", "lines")}` : ""}`);
1058
+ // 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.
1059
+ 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.`);
992
1060
  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.");
993
1061
  // LEFT OUT AND COUNTED (0.10.18): a conversation whose kept fields outgrew the reader's budget is passed over, never the export.
994
1062
  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.`);
995
1063
  if (has("dry-run")) { say(" Dry run: nothing was sent."); return false; }
996
- 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; }
997
- const sent = await run(paths["log-session.mjs"], ["--history", "--export", path], key.token, true, env);
1064
+ 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; }
1065
+ const sent = await sendShown(paths, ["--history", "--export", path], key.token, env);
998
1066
  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.`);
999
- if (sent.code !== 0) return false;
1067
+ if (sent.code !== 0) { const answered = doorAnswer(sent.out); if (answered) say(answered); return false; }
1000
1068
  // THE EXPORT REPLACES (owner, 2026-10-10): the door withdrew the product's earlier connector lines on the export's days by itself and
1001
1069
  // 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.
1002
1070
  const counts = lastCounts(sent.out);
@@ -1009,13 +1077,25 @@ async function offerExport(paths, key, path) {
1009
1077
  const n = counts.unknownOnDays;
1010
1078
  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.`);
1011
1079
  if (has("withdraw-unknown") || (await ask(`Also withdraw ${n} earlier line${n === 1 ? "" : "s"} your ${connector} connector reported for these days?`, false))) {
1012
- const again = await run(paths["log-session.mjs"], ["--history", "--export", path, "--withdraw-unknown"], key.token, true, env);
1080
+ const again = await sendShown(paths, ["--history", "--export", path, "--withdraw-unknown"], key.token, env);
1013
1081
  const done = lastCounts(again.out);
1014
1082
  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()}`);
1015
1083
  } else say(` Kept. Later: npx worktrust history --export ${path} --withdraw-unknown`);
1016
1084
  }
1017
1085
  return true;
1018
1086
  }
1087
+ /**
1088
+ * WHY A BATCH DID NOT ARRIVE, IN WORKTRUST'S OWN WORDS (0.10.37, incident 2026-11-05: 0.10.36 said only "Not all of it arrived",
1089
+ * and the reason, "could not import (57014)", took a database to find). The hook's last line carries the door's sentence for a
1090
+ * batch that waits (`delivery.reason`); said as one line, control characters taken out, at most 400 characters. Null without one.
1091
+ */
1092
+ function doorAnswer(out) {
1093
+ try {
1094
+ const line = out.trim().split("\n").reverse().find((text) => /^\{"(history|export)_sent"/.test(text));
1095
+ const said = JSON.parse(line ?? "null")?.delivery?.reason;
1096
+ return typeof said === "string" && said.trim() ? ` WorkTrust answered: ${said.replace(/[\u0000-\u001f\u007f-\u009f]/g, " ").trim().slice(0, 400)}` : null;
1097
+ } catch { return null; }
1098
+ }
1019
1099
  /** The hook's last line of counts after an export send (superseded, unknownOnDays, unknownWithdrawn); zeros when there is none. */
1020
1100
  function lastCounts(out) {
1021
1101
  try { const line = out.trim().split("\n").filter((text) => text.startsWith("{")).pop(); const json = JSON.parse(line ?? "{}"); return { superseded: Number(json.superseded) || 0, unknownOnDays: Number(json.unknownOnDays) || 0, unknownWithdrawn: Number(json.unknownWithdrawn) || 0 }; } catch { return { superseded: 0, unknownOnDays: 0, unknownWithdrawn: 0 }; }
@@ -1048,7 +1128,7 @@ async function offerDownloads(paths, key) {
1048
1128
  */
1049
1129
  async function offerFolder(paths, key, dir) {
1050
1130
  const env = { WORKTRUST_MCP_URL: key.url, ...(key.device ? { WORKTRUST_DEVICE_KEY: key.device } : {}) };
1051
- const counted = await run(paths["log-session.mjs"], ["--history", "--from-folder", dir, "--dry-run", "--summary"], key.token, true, env);
1131
+ const counted = await sendShown(paths, ["--history", "--from-folder", dir, "--dry-run", "--summary"], key.token, env);
1052
1132
  let found = null;
1053
1133
  try { found = JSON.parse(counted.out.trim().split("\n").pop()); } catch { /* no line: the folder could not be read */ }
1054
1134
  const report = found?.folder;
@@ -1059,8 +1139,9 @@ async function offerFolder(paths, key, dir) {
1059
1139
  say(" Hours reconstructed from the copy's own clocks: shown with their origin, never verified hours. Never text.");
1060
1140
  if (has("dry-run")) { say(" Dry run: nothing was sent."); return; }
1061
1141
  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 --from-folder ${dir}`); return; }
1062
- const sent = await run(paths["log-session.mjs"], ["--history", "--from-folder", dir], key.token, true, env);
1142
+ const sent = await sendShown(paths, ["--history", "--from-folder", dir], key.token, env);
1063
1143
  say(sent.code === 0 ? " ✓ Sent as history. It shows in WorkTrust as reconstructed, from a copied session folder, never as verified hours; a line already received is kept once." : ` Not all of it arrived. Run npx worktrust history --from-folder ${dir} again: a line already received is kept once.`);
1144
+ if (sent.code !== 0) { const answered = doorAnswer(sent.out); if (answered) say(answered); }
1064
1145
  }
1065
1146
 
1066
1147
  /**
@@ -1274,6 +1355,12 @@ async function status() {
1274
1355
  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)");
1275
1356
  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)");
1276
1357
  say(sessionHookHere() ? " Session hook: installed" : " Session hook: not installed");
1358
+ say(` AI work lines: ${doorLine()}`);
1359
+ if (measurePaused()) say(` Measuring: paused by you in Sources since ${String(measureState()?.since ?? "").slice(0, 10)}; nothing is measured or sent until you turn it on there`);
1360
+ // THE LAST UPDATE ON TURN-ON (0.10.37): what happened, in words; the details are in ~/.worktrust/update.log, on this computer only.
1361
+ { const state = updateState(); if (state) { const code = (await selfUpdateModule()).updateResult(state);
1362
+ const words = { installed: `updated itself to ${state.version}`, current: `already on ${state.version} or newer`, python: "installed with Python: update it with the package manager you installed WorkTrust with", unsupported: "this installation cannot update itself: run npx worktrust@latest update", unverified: `${state.version} could not be verified, so nothing was installed`, failed: `the update to ${state.version} did not finish; the CLI stays as it was` };
1363
+ say(` Update when turned on: ${words[code] ?? `to ${state.version}, under way`}${["unverified", "failed"].includes(code) ? " (~/.worktrust/update.log)" : ""}`); } }
1277
1364
  // 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.
1278
1365
  { let unread = null; try { unread = JSON.parse(readFileSync(join(HOME_DIR, "sessions.json"), "utf8")).__unreadable ?? null; } catch { /* no state yet */ }
1279
1366
  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)`); }
@@ -1324,7 +1411,8 @@ async function preserve() {
1324
1411
  const script = join(HERE, "preserve.mjs");
1325
1412
  if (!existsSync(script)) fail("preserve runs from the package: npx worktrust@latest preserve");
1326
1413
  const child = spawn(moduleExecutable(HERE), [...moduleArgs(HERE, "preserve.mjs", args.filter((arg) => arg !== "preserve"))], { stdio: "inherit", env: { ...process.env, WORKTRUST_COLLECTOR: `worktrust-cli/${CLI_VERSION}` } });
1327
- process.exitCode = await new Promise((resolve) => child.on("exit", (code) => resolve(code ?? 1)));
1414
+ const pass = (signal) => { try { child.kill(signal); } catch { /* already gone */ } }; process.on("SIGINT", pass); process.on("SIGTERM", pass); // preserve.mjs stops safely, 130
1415
+ process.exitCode = await new Promise((resolve) => child.on("exit", (code, signal) => resolve(code ?? (signal ? 130 : 1))));
1328
1416
  }
1329
1417
 
1330
1418
  /**
@@ -1362,6 +1450,175 @@ async function gitCommits() {
1362
1450
  process.exitCode = await gitMain(sub, { say, ask, send, consent: await consent(), salt: archiveSalt(), dryRun: has("dry-run") });
1363
1451
  }
1364
1452
 
1453
+ /**
1454
+ * HOURS ONLY, OR ALSO WORK LINES (owner, 2026-10-31, after an engineer: "every session loads ~600 tokens from the WorkTrust
1455
+ * MCP"). The passport's hours come from the session hook, which reads the AI apps' own transcripts and needs no door; the
1456
+ * door adds only the AI's own `log_work` lines, and loads its instruction (and, in clients that load every tool, its tool
1457
+ * definitions) into every session. So the person chooses, here, and the choice is kept in ~/.worktrust/door.json (600):
1458
+ * `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
1459
+ * names the mode to WorkTrust beside the CLI version (a closed word in its user-agent), so a pause in work lines reads as
1460
+ * the person's choice. Turning the door on sends nothing from the off period: work lines are live only, and earlier work
1461
+ * goes only through `history`, on the person's yes.
1462
+ */
1463
+ const DOOR_FILE = join(HOME_DIR, "door.json");
1464
+ const DOOR_MODES = ["hours_only", "work_lines"];
1465
+ const DOOR_SWITCH = "npx worktrust mcp on / mcp off";
1466
+ function doorState() { try { const state = JSON.parse(readPrivateFile(DOOR_FILE) ?? "null"); return DOOR_MODES.includes(state?.mode) ? state : null; } catch { return null; } }
1467
+ 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 */ } }
1468
+ const doorOff = () => doorState()?.mode === "hours_only";
1469
+ /** The mode and the moment it last changed here (whole seconds), so the last change wins against a wish from Sources. */
1470
+ 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; };
1471
+ const doorModeEnv = () => (doorSaid() ? { WORKTRUST_DOOR_MODE: doorSaid() } : {});
1472
+ const doorModeAgent = () => `${doorSaid() ? ` worktrust-mode/${doorSaid()}` : ""}${measureSaid() ? ` worktrust-measure/${measureSaid()}` : ""}${updateSaid() ? ` worktrust-update/${updateSaid()}` : ""}`;
1473
+ 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)"; };
1474
+ /** The first question: Enter, --yes and a closed terminal keep the door, as before; --hours-only and --work-lines say it in advance. */
1475
+ async function chooseDoor() {
1476
+ if (has("hours-only")) return "hours_only";
1477
+ if (has("work-lines")) return "work_lines";
1478
+ say();
1479
+ say(" How should your AI apps work with WorkTrust?");
1480
+ say(" 1 Hours only: the session hook measures your hours; nothing of WorkTrust loads into your sessions");
1481
+ say(" 2 Also let your AI log finished work: the WorkTrust door in each app, about 40 tokens per session");
1482
+ if (has("yes") || has("dry-run") || !process.stdin.isTTY) { say(` Kept: 2, the door, as before. Switch any time: ${DOOR_SWITCH}`); return "work_lines"; }
1483
+ const prompt = createInterface({ input: process.stdin, output: process.stdout });
1484
+ const answer = (await prompt.question(" Which one? [1/2, Enter = 2] ")).trim();
1485
+ prompt.close();
1486
+ return answer === "1" ? "hours_only" : "work_lines";
1487
+ }
1488
+ /**
1489
+ * TWO DOORS IN ONE CLAUDE CODE (owner, 2026-10-31). Claude Code also loads the connectors of the person's claude.ai account,
1490
+ * so a WorkTrust connector added there arrives beside the local door and its instruction loads twice. The local door is the
1491
+ * one to keep (it carries this computer's device key); a claude.ai connector is managed only at claude.ai, so the CLI says
1492
+ * where, once. Claude Code records the connectors it has EVER connected (`claudeAiMcpEverConnected`), not the ones on now,
1493
+ * and asking `claude mcp list` would start every server; so this is a notice, never a removal and never a claim.
1494
+ */
1495
+ 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; } }
1496
+ function doubleDoorNotice(always = false) {
1497
+ const connector = claudeAiDoor();
1498
+ if (!connector || (!always && doorState()?.noticed)) return;
1499
+ say();
1500
+ 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.`
1501
+ : ` ! 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).`);
1502
+ say(" Remove the other at https://claude.ai/customize/connectors (the CLI cannot change your claude.ai account).");
1503
+ if (!always) saveDoorState({ noticed: new Date().toISOString() });
1504
+ }
1505
+ /**
1506
+ * THE OWNER'S SWITCH IN SOURCES, DONE HERE (owner, 2026-10-31). At a session's start or end the hook asks WorkTrust, with
1507
+ * this computer's signed key, whether the owner asked for a mode (at most every ten minutes, three seconds at most, silent
1508
+ * on any failure). A wish newer than the last choice made on this computer is done on WorkTrust's own entries in the AI
1509
+ * apps, recorded in door.json and reported back beside the version, which settles it; a choice made here later wins.
1510
+ * Nothing is printed: the hook's output belongs to the AI app.
1511
+ */
1512
+ async function followDoorWish(key) {
1513
+ const state = doorState();
1514
+ if (!key.device || (state?.checkedAt && Date.now() - Date.parse(state.checkedAt) < 10 * 60_000)) return;
1515
+ let wish = null, doorClock = NaN;
1516
+ try {
1517
+ const url = new URL("/api/cli/door", key.url).href, body = "{}";
1518
+ 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) });
1519
+ if (response.ok) { wish = await response.json(); doorClock = Date.parse(response.headers.get("date") ?? ""); }
1520
+ } catch { /* offline: asked again next time */ }
1521
+ saveDoorState({ checkedAt: new Date().toISOString() });
1522
+ await followMeasureWish(key, wish);
1523
+ await followUpdateWish(key, wish, doorClock);
1524
+ if (!DOOR_MODES.includes(wish?.mode) || wish.mode === state?.mode || !(Date.parse(wish.at) > Date.parse(state?.since ?? state?.asked ?? 0))) return;
1525
+ const paths = await scripts();
1526
+ if (wish.mode === "work_lines") { await prepareBundledRuntime(); await run(paths["setup-mcp.mjs"], ["--remove", "--write"], key.token, true); }
1527
+ const done = await run(paths["setup-mcp.mjs"], wish.mode === "hours_only" ? ["--remove", "--write"] : ["--write", "--bridge", STABLE], key.token, true);
1528
+ if (done.code !== 0) return;
1529
+ saveDoorState({ mode: wish.mode, asked: state?.asked ?? new Date().toISOString() });
1530
+ await accepted(key.url, key.token, key.device, doorModeAgent());
1531
+ }
1532
+ /**
1533
+ * CLI ACTIVE, PER COMPUTER (owner, 2026-11-05; 0.10.37). The owner may pause this computer's CLI from Sources: the same answer
1534
+ * from api/cli/door carries `measure` (active | paused) and its moment. A wish newer than the last change here is kept in
1535
+ * ~/.worktrust/measure.json (0600); while paused the hook measures nothing and sends nothing and the bridge forwards nothing.
1536
+ * The state is reported back beside the version as worktrust-measure/<state>.<epoch> (retried until WorkTrust accepted it),
1537
+ * which settles the wish; until then Sources says "asked", never "off". Nothing is deleted. A CLI before 0.10.37 never reads
1538
+ * the wish and keeps measuring. Turning on installs a newer CLI only through the one-shot instruction below (followUpdateWish).
1539
+ */
1540
+ const MEASURE_FILE = join(HOME_DIR, "measure.json");
1541
+ const MEASURES = ["active", "paused"];
1542
+ function measureState() { try { const state = JSON.parse(readPrivateFile(MEASURE_FILE) ?? "null"); return MEASURES.includes(state?.state) ? state : null; } catch { return null; } }
1543
+ function saveMeasureState(next) { if (has("dry-run")) return; try { ensureHome(); writePrivateFile(MEASURE_FILE, `${JSON.stringify({ ...(measureState() ?? {}), ...next })}\n`); } catch { /* not kept: asked again next time */ } }
1544
+ const measurePaused = () => measureState()?.state === "paused";
1545
+ const measureSaid = () => { const state = measureState(); if (!state) return null; const at = Math.floor(Date.parse(state.since ?? "") / 1000); return Number.isFinite(at) && at > 0 ? `${state.state}.${at}` : state.state; };
1546
+ async function followMeasureWish(key, wish) {
1547
+ const here = measureState();
1548
+ if (MEASURES.includes(wish?.measure) && wish.measure !== (here?.state ?? "active") && Date.parse(wish.measureAt) > Date.parse(here?.since ?? 0)) saveMeasureState({ state: wish.measure, since: new Date().toISOString(), reported: null });
1549
+ const now = measureState();
1550
+ if (now && now.reported !== now.since && (await accepted(key.url, key.token, key.device, doorModeAgent())) === true) saveMeasureState({ reported: now.since });
1551
+ }
1552
+ /**
1553
+ * TURNED ON, IT UPDATES ITSELF (owner, 2026-11-05; 0.10.37; SECURITY.md "Updating itself when you turn it on"). When the owner
1554
+ * turns CLI active back on in Sources for this computer after it had paused, the door's answer carries ONE instruction:
1555
+ * `update: { version, at }`, `at` being that resume (its id). Taken once per id, never while paused, never from a version
1556
+ * string alone: it is kept in ~/.worktrust/update.json (0600) and handed to `self-update`, detached, so the hook returns at
1557
+ * once. Everything else (the method, a newer version, npm's registry signature and provenance bound to WorkTrust's publish
1558
+ * workflow, WorkTrust's own release signature) is decided there (self-update.mjs). The outcome goes back as
1559
+ * worktrust-update/<code>.<id> beside the version, a code and never content, which settles the instruction in WorkTrust.
1560
+ */
1561
+ const UPDATE_FILE = join(HOME_DIR, "update.json");
1562
+ function updateState() { try { const state = JSON.parse(readPrivateFile(UPDATE_FILE) ?? "null"); return Number.isSafeInteger(state?.id) ? state : null; } catch { return null; } }
1563
+ function saveUpdateState(next) { if (has("dry-run")) return; try { ensureHome(); writePrivateFile(UPDATE_FILE, `${JSON.stringify({ ...(updateState() ?? {}), ...next })}\n`); } catch { /* not kept: no attempt is started */ } }
1564
+ let updateModule = null;
1565
+ const selfUpdateModule = async () => (updateModule ??= await import("./self-update.mjs"));
1566
+ /** The outcome not yet accepted by WorkTrust, as `<code>.<id>`; null while nothing is to be said. */
1567
+ const updateSaid = () => { const state = updateState(); const code = state && updateModule?.updateResult(state); return code && state.reported !== state.id ? `${code}.${state.id}` : null; };
1568
+ /** How this CLI was installed, for the one decision: the launcher-verified npm copy, a Python installation, or neither. */
1569
+ function installMethod() {
1570
+ if (moduleExecutable(HERE) !== process.execPath || process.env.WORKTRUST_BUNDLED_PYTHON || process.env.WORKTRUST_BUNDLED_RUNTIME_DIR) return "python";
1571
+ return globalThis[Symbol.for("worktrust.verifiedReleaseRoot")] === HERE && existsSync(join(HERE, "package.json")) && existsSync(join(HERE, "package-release.json")) ? "npm" : "unknown";
1572
+ }
1573
+ async function followUpdateWish(key, wish, doorClock = NaN, agentEnv = AGENT_ENV) {
1574
+ const { updateOffer, updateResult } = await selfUpdateModule();
1575
+ const offer = updateOffer(wish?.update), here = updateState();
1576
+ // A HOSTILE OR BROKEN ANSWER (security review L3): an id past the door's own clock (its Date header) would outrank every
1577
+ // later turn-on; it is refused. One attempt that did not install backs off a day; one under way is left to finish.
1578
+ const clock = Number.isFinite(doorClock) ? doorClock : Date.now();
1579
+ const outcome = here ? updateResult(here) : null;
1580
+ const waiting = here && (outcome === null || (outcome !== "installed" && Date.now() - Date.parse(here.at ?? "") < 24 * 3600_000));
1581
+ if (offer && offer.id * 1000 <= clock + 5 * 60_000 && !measurePaused() && !(here && here.id >= offer.id) && !waiting) {
1582
+ saveUpdateState({ id: offer.id, version: offer.version, state: "pending", at: new Date().toISOString(), reported: null });
1583
+ if (updateState()?.id === offer.id) {
1584
+ // Detached, without an agent's markers (this is the owner's act from Sources, not an agent's command), output to nobody.
1585
+ const env = Object.fromEntries(Object.entries(process.env).filter(([name]) => !agentEnv.includes(name)));
1586
+ try { spawn(moduleExecutable(HERE), [...moduleArgs(HERE, "worktrust.mjs", ["self-update"])], { detached: true, stdio: "ignore", env, cwd: HOME_DIR, windowsHide: true }).unref(); } catch { /* reported as failed once stale */ }
1587
+ }
1588
+ }
1589
+ const said = updateSaid();
1590
+ if (said && (await accepted(key.url, key.token, key.device, doorModeAgent())) === true) saveUpdateState({ reported: Number(said.split(".")[1]) });
1591
+ }
1592
+ /** `worktrust self-update`: started by the hook, acts only on an instruction it recorded (update.json, pending). */
1593
+ async function selfUpdate(agentEnv) {
1594
+ const { runSelfUpdate } = await selfUpdateModule();
1595
+ const { verifyPackage, installSignedPackage } = await import("./package-integrity.mjs");
1596
+ await runSelfUpdate({ home: HOME_DIR, method: installMethod(), current: CLI_VERSION, readState: updateState, saveState: saveUpdateState, verifyPackage, installSignedPackage, nodeArgs: NODE_FLAGS, agentEnv, env: process.env });
1597
+ }
1598
+ async function doorCommand(sub) {
1599
+ say();
1600
+ 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; }
1601
+ const key = await freshKey();
1602
+ if (!key) fail("this computer has no WorkTrust key file yet. Run npx worktrust connect.");
1603
+ const paths = await scripts();
1604
+ if (sub === "off") {
1605
+ 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.");
1606
+ saveDoorState({ mode: "hours_only", asked: doorState()?.asked ?? new Date().toISOString() });
1607
+ say(" ✓ Hours only: the WorkTrust door is out of every AI app here, and update leaves it out.");
1608
+ say(" The session hook keeps measuring your hours. npx worktrust mcp on brings the door back.");
1609
+ } else {
1610
+ await prepareBundledRuntime(); ensureHome(); saveStableEntry();
1611
+ await run(paths["setup-mcp.mjs"], ["--remove", "--write"], key.token, true);
1612
+ 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.");
1613
+ saveDoorState({ mode: "work_lines", asked: doorState()?.asked ?? new Date().toISOString() });
1614
+ say(" ✓ The WorkTrust door is back: your AI can log finished work from now on. Nothing from the time it was off is sent.");
1615
+ }
1616
+ const reported = await accepted(key.url, key.token, key.device, doorModeAgent());
1617
+ say(reported === true ? " ✓ WorkTrust was told the mode (shown under Sources, Devices)." : " ! Kept here; WorkTrust is told on the next connection.");
1618
+ doubleDoorNotice();
1619
+ say(" Quit your AI apps completely and open them again.");
1620
+ }
1621
+
1365
1622
  function help() {
1366
1623
  say("WorkTrust: couple this computer to your record. Metadata only.");
1367
1624
  say();
@@ -1397,6 +1654,10 @@ function help() {
1397
1654
  say(" days this computer's own sessions lack, reconstructed, never verified hours (asks first)");
1398
1655
  say(" worktrust disconnect take WorkTrust out of every AI app here (asks first)");
1399
1656
  say(" worktrust status what is coupled here");
1657
+ say(" worktrust mcp off hours only: the WorkTrust door out of every AI app here, nothing of it in your sessions;");
1658
+ say(" the session hook keeps measuring your hours, and update leaves the door out");
1659
+ say(" worktrust mcp on the door back in, so your AI can log finished work (about 40 tokens per session)");
1660
+ say(" worktrust mcp which of the two this computer is in");
1400
1661
  say(" worktrust protect-key after update: move credential protection into the OS vault (asks first)");
1401
1662
  say(" worktrust orchestration report --file recording.jsonl inspect local agent metadata; sends nothing");
1402
1663
  say(" worktrust mod the WorkTrust mod for Claude Code: what it counts, and whether it is on");
@@ -1422,19 +1683,21 @@ function help() {
1422
1683
  async function main() {
1423
1684
  if (!moduleArgs || !moduleExecutable || !createCredentialStore) fail("Use the complete WorkTrust package from npm/PyPI or the signed preservation kit; individual scripts cannot run.");
1424
1685
  if (Number(process.versions.node.split(".")[0]) < 18) fail("needs Node 18 or later (fetch is built in from 18).");
1425
- const AGENT_ENV = ["CLAUDECODE", "CLAUDE_CODE_ENTRYPOINT", "CODEX_SANDBOX", "CODEX_CI", "GEMINI_CLI", "CURSOR_AGENT", "OPENCODE", "CLINE_ACTIVE", "AIDER_CHAT", "ANTIGRAVITY_AGENT", "WINDSURF_AGENT"];
1426
- const PERSON_ONLY = new Set(["default", "connect", "update", "history", "disconnect", "preserve", "codex", "antigravity", "sources", "web", "import", "orchestration", "mod", "protect-key", "git"]);
1686
+ // `self-update` is never an agent's either: the hook starts it without the markers, on the owner's turn-on in Sources.
1687
+ const PERSON_ONLY = new Set(["default", "connect", "update", "history", "disconnect", "preserve", "codex", "antigravity", "sources", "web", "import", "orchestration", "mod", "protect-key", "git", "self-update"]);
1427
1688
  const agentShell = AGENT_ENV.find((name) => process.env[name] && process.env[name] !== "0");
1428
- if (agentShell && PERSON_ONLY.has(command)) {
1689
+ // `mcp off` and `mcp on` change what this computer's AI apps load: the person's. Bare `mcp` stays the bridge the apps start.
1690
+ const doorSwitch = command === "mcp" && ["off", "on"].includes(args[args.indexOf("mcp") + 1]);
1691
+ if (agentShell && (PERSON_ONLY.has(command) || doorSwitch)) {
1429
1692
  say();
1430
1693
  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}).`);
1431
1694
  say(" Nothing was read, sent or changed. See AGENTS.md in the package: https://www.npmjs.com/package/worktrust");
1432
1695
  return (process.exitCode = 3);
1433
1696
  }
1434
1697
 
1435
- /** Interactive version notice only. Registry metadata is not a trusted signed release catalogue.
1436
- * Hooks, bridge and offline preserve never check. Installation remains with the person's package manager
1437
- * until the signed release updater has a provisioned trust root and has passed the distribution gates.
1698
+ /** Interactive version notice only. Registry metadata is not a trusted signed release catalogue, and a notice never
1699
+ * installs. Hooks, bridge and offline preserve never check. Installation remains with the person's package manager, with
1700
+ * one exception the notice never drives: the owner's turn-on in Sources (followUpdateWish, self-update.mjs, SECURITY.md).
1438
1701
  */
1439
1702
  const RELAY_COMMANDS = new Set(["default", "connect", "update", "history", "status", "disconnect", "codex", "antigravity"]);
1440
1703
  const semverNewer = (a, b) => { const x = a.split(".").map(Number), y = b.split(".").map(Number); for (let i = 0; i < 3; i += 1) if (x[i] !== y[i]) return x[i] > y[i]; return false; };
@@ -1461,10 +1724,12 @@ if (!["version", "help", "preserve"].includes(command)) {
1461
1724
  }
1462
1725
  if (command === "version") say(CLI_VERSION);
1463
1726
  else if (command === "default") { if (keyStore.load()) await again(); else await connect(); }
1727
+ else if (command === "mcp" && (doorSwitch || args[args.indexOf("mcp") + 1] === "status" || (process.stdin.isTTY && process.stdout.isTTY))) await doorCommand(args[args.indexOf("mcp") + 1]);
1464
1728
  else if (command === "mcp") await bridge();
1465
1729
  else if (command === "hook") await hook();
1466
1730
  else if (command === "connect") await connect();
1467
1731
  else if (command === "update") await update();
1732
+ else if (command === "self-update") await selfUpdate(AGENT_ENV);
1468
1733
  else if (command === "protect-key") await protectKey();
1469
1734
  else if (command === "history") await history();
1470
1735
  // NOT FROM THE TERMINAL (owner, 2026-10-04): an ACCOUNT is connected under Sources in the app, where the