worktrust 0.10.12 → 0.10.13

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -7,7 +7,7 @@ record of the work you do with AI without anyone reading that work: it receives
7
7
  npx worktrust@latest
8
8
  ```
9
9
 
10
- **The only official package** is `worktrust`, published by the npm account **worktrustio** with
10
+ **The official npm package** is `worktrust`, published by the npm account **worktrustio** with
11
11
  provenance from this repository (github.com/fhomey/worktrust-cli). Check it on npmjs.com before you run
12
12
  it; a package of another name or from another publisher is not ours. Without npm, the same script runs
13
13
  from WorkTrust's own site:
@@ -16,6 +16,18 @@ from WorkTrust's own site:
16
16
  curl -fsSO https://app.worktrust.io/counter/worktrust.mjs && node worktrust.mjs
17
17
  ```
18
18
 
19
+ **Python tool runners:** this repository also builds `worktrust` for `uvx` and `pipx` from the
20
+ same measurement modules. Version 0.10.13's native wheels include a pinned official Node runtime,
21
+ so that route needs no separate Node/npm installation. See the
22
+ [Python distribution](https://github.com/fhomey/worktrust-cli/tree/main/python) for supported
23
+ platforms, release status and installation commands. npm and Python versions are checked together.
24
+
25
+ Connecting through the Python package installs the runtime and engine in an immutable directory
26
+ under `~/.worktrust/installations/`; client hooks use that persistent path, so clearing a tool-runner
27
+ cache does not break the coupling. Updates retain older installations for running clients.
28
+ Run `worktrust disconnect` before removing an installed Python tool if you also want to remove its
29
+ WorkTrust coupling. Disconnect removes the key and client wiring; it leaves runtime files in place.
30
+
19
31
  **No account? Keep your history anyway.** Claude Code and Gemini CLI delete their sessions after 30
20
32
  days by default, and a deleted session can never be measured again. `npx worktrust@latest preserve` shows what
21
33
  each AI app on this computer keeps, keeps it longer on your yes, and writes a local, metadata-only
package/log-session.mjs CHANGED
@@ -1080,7 +1080,7 @@ if (flag("install")) {
1080
1080
  const settings = existsSync(file) ? JSON.parse(readFileSync(file, "utf8")) : {};
1081
1081
  // `--via <worktrust.mjs>`: the key lives in ~/.worktrust/key.json, so Claude Code runs the wrapper, which reads it and starts this hook.
1082
1082
  const via = args.indexOf("--via") >= 0 ? args[args.indexOf("--via") + 1] : null;
1083
- const command = via ? `"${process.env.WORKTRUST_NODE || process.execPath}" "${via}" hook` : `node ${home}`;
1083
+ const command = `"${process.env.WORKTRUST_NODE || process.execPath}" "${via ?? home}"${via ? " hook" : ""}`;
1084
1084
  settings.hooks ??= {};
1085
1085
  for (const event of HOOK_EVENTS) settings.hooks[event] ??= [];
1086
1086
  // A WIRING THAT POINTS SOMEWHERE ELSE IS REPAIRED, NOT LEFT. An earlier install wired whatever
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "worktrust",
3
- "version": "0.10.12",
3
+ "version": "0.10.13",
4
4
  "description": "Couple this computer to WorkTrust: approve a code in your browser, and every AI app here reports what you built. Metadata only, no dependencies.",
5
5
  "type": "module",
6
6
  "bin": {
@@ -20,6 +20,7 @@
20
20
  "stretch-evidence.mjs",
21
21
  "chat-exports.mjs",
22
22
  "stack-rules.mjs",
23
+ "runtime-install.mjs",
23
24
  "README.md",
24
25
  "SECURITY.md",
25
26
  "LICENSE",
@@ -0,0 +1,64 @@
1
+ /** Immutable, owned runtime + engine installation for Python tool-runner caches.
2
+ * Called only after the person's connect/update confirmation. No network, credentials or measurement logic.
3
+ */
4
+ import { createHash, randomBytes } from "node:crypto";
5
+ import { existsSync, lstatSync, mkdirSync, readFileSync, readdirSync, renameSync, rmSync, writeFileSync } from "node:fs";
6
+ import { join } from "node:path";
7
+
8
+ const hash = (bytes) => createHash("sha256").update(bytes).digest("hex");
9
+ const regular = (path) => { const stat = lstatSync(path); if (!stat.isFile() || stat.isSymbolicLink()) throw Error("bundled installation requires regular files"); };
10
+ const directory = (path) => { const stat = lstatSync(path); if (!stat.isDirectory() || stat.isSymbolicLink()) throw Error("bundled installation requires owned directories, not symlinks"); };
11
+ const checkedBytes = (path) => { regular(path); return readFileSync(path); };
12
+
13
+ export function installRuntime(runtime, engine, home, moduleNames) {
14
+ directory(runtime); directory(engine); directory(home);
15
+ const descriptor = checkedBytes(join(runtime, "runtime.json"));
16
+ const manifest = JSON.parse(descriptor);
17
+ const executable = process.platform === "win32" ? "node.exe" : "node";
18
+ const target = `${process.platform === "win32" ? "win" : process.platform}-${process.arch}`;
19
+ if (manifest.platform !== target || manifest.executable !== executable || !/^\d+\.\d+\.\d+$/.test(manifest.version) || !/^[a-f0-9]{64}$/.test(manifest.archive_sha256)) throw Error("bundled runtime identity mismatch");
20
+ const names = [executable, "LICENSE"].sort();
21
+ if (!manifest.files || JSON.stringify(Object.keys(manifest.files).sort()) !== JSON.stringify(names) || JSON.stringify(readdirSync(runtime).sort()) !== JSON.stringify([...names, "runtime.json"].sort())) throw Error("bundled runtime file list mismatch");
22
+ const contents = new Map([["runtime/runtime.json", descriptor]]);
23
+ for (const name of names) {
24
+ const bytes = checkedBytes(join(runtime, name));
25
+ if (hash(bytes) !== manifest.files[name]) throw Error("bundled runtime integrity check failed");
26
+ contents.set(`runtime/${name}`, bytes);
27
+ }
28
+ if (!Array.isArray(moduleNames) || !moduleNames.includes("worktrust.mjs") || new Set(moduleNames).size !== moduleNames.length) throw Error("invalid engine module list");
29
+ for (const name of [...moduleNames].sort()) {
30
+ if (!/^[a-z][a-z0-9-]*\.mjs$/.test(name)) throw Error("invalid engine module name");
31
+ contents.set(`engine/${name}`, checkedBytes(join(engine, name)));
32
+ }
33
+ const identities = Object.fromEntries([...contents].map(([name, bytes]) => [name, hash(bytes)]));
34
+ const identity = Buffer.from(JSON.stringify(identities));
35
+ const installations = join(home, "installations"), installed = join(installations, hash(identity));
36
+ if (!existsSync(installations)) mkdirSync(installations, { mode: 0o700 });
37
+ directory(installations);
38
+ const verify = (place) => {
39
+ directory(place);
40
+ if (JSON.stringify(readdirSync(place).sort()) !== JSON.stringify(["engine", "installation.json", "runtime"])) throw Error("installed bundle file list mismatch");
41
+ if (!checkedBytes(join(place, "installation.json")).equals(identity)) throw Error("installed bundle identity mismatch");
42
+ for (const group of ["engine", "runtime"]) {
43
+ directory(join(place, group));
44
+ const expected = [...contents.keys()].filter(name => name.startsWith(`${group}/`)).map(name => name.slice(group.length + 1)).sort();
45
+ if (JSON.stringify(readdirSync(join(place, group)).sort()) !== JSON.stringify(expected)) throw Error("installed bundle file list mismatch");
46
+ }
47
+ for (const [name, digest] of Object.entries(identities)) if (hash(checkedBytes(join(place, name))) !== digest) throw Error("installed bundle integrity check failed");
48
+ };
49
+ if (existsSync(installed)) verify(installed);
50
+ else {
51
+ const temporary = join(installations, `.install-${process.pid}-${randomBytes(8).toString("hex")}`);
52
+ mkdirSync(temporary, { mode: 0o700 });
53
+ try {
54
+ mkdirSync(join(temporary, "engine"), { mode: 0o700 }); mkdirSync(join(temporary, "runtime"), { mode: 0o700 });
55
+ for (const [name, bytes] of contents) writeFileSync(join(temporary, name), bytes, { flag: "wx", mode: name === `runtime/${executable}` ? 0o755 : 0o600 });
56
+ writeFileSync(join(temporary, "installation.json"), identity, { flag: "wx", mode: 0o600 });
57
+ verify(temporary);
58
+ try { renameSync(temporary, installed); }
59
+ catch (error) { if (!existsSync(installed)) throw error; verify(installed); }
60
+ } finally { rmSync(temporary, { recursive: true, force: true }); }
61
+ }
62
+ // Existing immutable directories are never replaced, including executables used by Windows processes.
63
+ return { executable: join(installed, "runtime", executable), bridge: join(installed, "engine", "worktrust.mjs") };
64
+ }
package/worktrust.mjs CHANGED
@@ -70,7 +70,7 @@
70
70
  import { execFileSync, spawn } from "node:child_process";
71
71
  import { createHash, generateKeyPairSync, randomBytes, sign } from "node:crypto";
72
72
  import { createServer } from "node:http";
73
- import { chmodSync, closeSync, copyFileSync, existsSync, mkdirSync, openSync, readFileSync, readdirSync, renameSync, rmSync, statSync, writeFileSync, writeSync } from "node:fs";
73
+ import { chmodSync, closeSync, copyFileSync, existsSync, lstatSync, mkdirSync, openSync, readFileSync, readdirSync, renameSync, rmSync, statSync, writeFileSync, writeSync } from "node:fs";
74
74
  import { homedir, hostname, platform } from "node:os";
75
75
  import { dirname, join } from "node:path";
76
76
  import { createInterface } from "node:readline/promises";
@@ -83,14 +83,14 @@ const command = args.includes("--help") ? "help" : args.includes("--version") ?
83
83
  const flag = (name) => { const at = args.indexOf(`--${name}`); return at >= 0 ? args[at + 1] : undefined; };
84
84
  const has = (name) => args.includes(`--${name}`);
85
85
  /** This CLI's version, said to the door so the app can tell which computer runs an old one (check-cli-package holds it equal to package.json). */
86
- const CLI_VERSION = "0.10.12";
86
+ const CLI_VERSION = "0.10.13";
87
87
  const ORIGIN = (flag("origin") ?? process.env.WORKTRUST_ORIGIN ?? "https://app.worktrust.io").replace(/\/$/, "");
88
88
  const MCP = flag("url") ?? process.env.WORKTRUST_MCP_URL ?? `${ORIGIN}/api/mcp`;
89
89
  const HOME_DIR = join(homedir(), ".worktrust");
90
90
  const HERE = dirname(fileURLToPath(import.meta.url));
91
- const SCRIPTS = ["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"];
91
+ const SCRIPTS = ["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"];
92
92
  /** The modules the scripts import by name from beside them; a download keeps that name. */
93
- const IMPORTED = new Set(["transcript-readers.mjs", "session-databases.mjs", "config-edits.mjs", "stretch-evidence.mjs", "chat-exports.mjs", "stack-rules.mjs"]);
93
+ 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"]);
94
94
  const downloaded = (name) => (IMPORTED.has(name) ? name : `${name}.download.mjs`);
95
95
  const BUNDLED = SCRIPTS.every((name) => existsSync(join(HERE, name)));
96
96
  const PLACEHOLDER = `wt_${"0".repeat(43)}`;
@@ -272,13 +272,29 @@ async function pairByCode(host, extra) {
272
272
  * that survives an upgrade), not this process's resolved path, which names one version and breaks
273
273
  * with the next `brew upgrade node`.
274
274
  */
275
- const NODE = (process.env.PATH ?? "").split(OS === "windows" ? ";" : ":").map((dir) => join(dir, OS === "windows" ? "node.exe" : "node")).find((path) => existsSync(path)) ?? process.execPath;
275
+ let NODE = process.env.WORKTRUST_BUNDLED_RUNTIME_DIR ? process.execPath : (process.env.PATH ?? "").split(OS === "windows" ? ";" : ":").map((dir) => join(dir, OS === "windows" ? "node.exe" : "node")).find((path) => existsSync(path)) ?? process.execPath;
276
276
  const KEY_FILE = join(HOME_DIR, "key.json");
277
- const STABLE = join(HOME_DIR, "worktrust.mjs");
277
+ const STABLE_FILE = join(HOME_DIR, "worktrust.mjs");
278
+ let STABLE = STABLE_FILE, runtimePrepared = false;
278
279
  const RENEW_EVERY_MS = 7 * 24 * 3600_000;
279
280
  const KEY_PLACE = "~/.worktrust/key.json (only you can read it)";
280
281
  const ensureHome = () => { mkdirSync(HOME_DIR, { recursive: true, mode: 0o700 }); try { chmodSync(HOME_DIR, 0o700); } catch { /* Windows */ } };
281
282
 
283
+ /** A tool-runner cache is disposable. Install the whole verified runtime/engine before changing wiring. */
284
+ async function prepareBundledRuntime() {
285
+ if (!process.env.WORKTRUST_BUNDLED_RUNTIME_DIR || runtimePrepared) return;
286
+ const { installRuntime } = await import("./runtime-install.mjs");
287
+ if (existsSync(HOME_DIR) && (!lstatSync(HOME_DIR).isDirectory() || lstatSync(HOME_DIR).isSymbolicLink())) fail("the WorkTrust directory must be a directory, not a symlink.");
288
+ ensureHome();
289
+ const installed = installRuntime(process.env.WORKTRUST_BUNDLED_RUNTIME_DIR, HERE, HOME_DIR, ["worktrust.mjs", ...SCRIPTS, "preserve.mjs", "preserve-lines.mjs", "preserve-summary.mjs"]);
290
+ NODE = installed.executable; STABLE = installed.bridge; runtimePrepared = true;
291
+ }
292
+ function saveStableEntry() {
293
+ const temporary = `${STABLE_FILE}.${randomBytes(8).toString("hex")}.tmp`;
294
+ try { writeFileSync(temporary, readFileSync(fileURLToPath(import.meta.url)), { flag: "wx", mode: 0o600 }); renameSync(temporary, STABLE_FILE); }
295
+ finally { try { rmSync(temporary); } catch { /* already renamed */ } }
296
+ }
297
+
282
298
  /**
283
299
  * THE KEY'S PLACE: one file only you can read (mode 600 in a 700 folder), holding the key, its device
284
300
  * private key and when it was last renewed. NO KEYCHAIN (owner, 2026-10-03): a keychain tool can ask
@@ -490,7 +506,7 @@ async function hook() {
490
506
  if (has("hermes") || has("goose")) return sessionEnd();
491
507
  const key = await freshKey();
492
508
  if (!key) process.exit(0);
493
- const child = spawn(process.execPath, [join(HOME_DIR, "log-session.mjs"), ...args.filter((arg) => arg !== "hook")], { stdio: "inherit", env: { ...process.env, WORKTRUST_MCP_URL: key.url, WORKTRUST_MCP_TOKEN: key.token, ...(key.device ? { WORKTRUST_DEVICE_KEY: key.device } : {}) } });
509
+ const child = spawn(process.execPath, [join(BUNDLED ? HERE : HOME_DIR, "log-session.mjs"), ...args.filter((arg) => arg !== "hook")], { stdio: "inherit", env: { ...process.env, WORKTRUST_MCP_URL: key.url, WORKTRUST_MCP_TOKEN: key.token, ...(key.device ? { WORKTRUST_DEVICE_KEY: key.device } : {}) } });
494
510
  child.on("exit", (code) => process.exit(code ?? 0));
495
511
  }
496
512
 
@@ -555,9 +571,10 @@ async function update() {
555
571
  say();
556
572
  if (has("dry-run")) { say(" Dry run: nothing was written and nothing was sent."); return; }
557
573
  if (!(await ask("Continue?"))) { say(" Stopped. Nothing was written."); return; }
558
- ensureHome();
559
574
  const previousVersion = stableVersion();
560
- copyFileSync(fileURLToPath(import.meta.url), STABLE);
575
+ await prepareBundledRuntime();
576
+ ensureHome();
577
+ saveStableEntry();
561
578
  say(` ✓ ${STABLE} is now ${CLI_VERSION}`);
562
579
  // Out first, then in: an app that held a key of its own (a hand-made entry) moves onto the bridge.
563
580
  await run(paths["setup-mcp.mjs"], ["--remove", "--write"], key.token, true);
@@ -610,6 +627,7 @@ async function connect() {
610
627
  say();
611
628
  if (has("dry-run")) { say(" Dry run: nothing was written and nothing was sent."); return; }
612
629
  if (!(await ask("Continue?"))) { say(" Stopped. Nothing was written and nothing was sent."); return; }
630
+ await prepareBundledRuntime();
613
631
 
614
632
  // The device key: made here, its private half kept with the key, its public half bound at WorkTrust.
615
633
  const device = direct ? null : generateKeyPairSync("ed25519");
@@ -628,7 +646,7 @@ async function connect() {
628
646
  keyStore.save({ url: MCP, token, renewedAt: new Date().toISOString(), coupledAt: new Date().toISOString(), identified: true, profile: computerIds().profile_id, account: pairing.account, accountRef: pairing.accountRef, device: device.privateKey.export({ format: "pem", type: "pkcs8" }) });
629
647
  previousNote.erase();
630
648
  ensureHome();
631
- copyFileSync(fileURLToPath(import.meta.url), STABLE);
649
+ saveStableEntry();
632
650
  say(` ✓ Key kept in ${KEY_PLACE}`);
633
651
  }
634
652
  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.");
@@ -692,7 +710,7 @@ async function offerHistory(paths, token, devicePem, url = MCP, rebuild = false)
692
710
  }
693
711
 
694
712
  /** The version stamped in the stable copy in ~/.worktrust, the CLI this computer ran before an update; null without one. */
695
- const stableVersion = () => { try { return /const CLI_VERSION = "([^"]+)";/.exec(readFileSync(STABLE, "utf8"))?.[1] ?? null; } catch { return null; } };
713
+ const stableVersion = () => { try { return /const CLI_VERSION = "([^"]+)";/.exec(readFileSync(STABLE_FILE, "utf8"))?.[1] ?? null; } catch { return null; } };
696
714
 
697
715
  /**
698
716
  * OFFERED ONCE, BY `update`, IN PLAIN WORDS (owner, 2026-10-07): when the computer's earlier lines were made by an earlier CLI
@@ -898,7 +916,8 @@ async function offerCodex() {
898
916
  const viaBridge = existsSync(STABLE);
899
917
  const hookFile = viaBridge ? STABLE : join(HOME_DIR, "log-session.mjs");
900
918
  if (!existsSync(hookFile)) { say(" Couple this computer first: npx worktrust"); return; }
901
- const want = `notify = [${(viaBridge ? [NODE, STABLE, "hook", "--codex-notify"] : [NODE, hookFile, "--codex-notify"]).map((part) => JSON.stringify(part)).join(", ")}]`;
919
+ const desired = () => `notify = [${(viaBridge ? [NODE, STABLE, "hook", "--codex-notify"] : [NODE, hookFile, "--codex-notify"]).map((part) => JSON.stringify(part)).join(", ")}]`;
920
+ let want = desired();
902
921
  const found = codexNotify();
903
922
  say();
904
923
  if (found.text === want) { say(" ✓ Codex already wakes the session hook at the end of every turn."); return; }
@@ -911,6 +930,7 @@ async function offerCodex() {
911
930
  say(` ${found.text ? "↻" : "+"} ${CODEX_CONFIG} → ${want}`);
912
931
  if (has("dry-run")) { say(" Dry run: nothing was written."); return; }
913
932
  if (!has("codex") && !(await ask("Let Codex wake the session hook?", false))) { say(" Not set. npx worktrust update asks again."); return; }
933
+ await prepareBundledRuntime(); want = desired();
914
934
  const rows = [...found.rows];
915
935
  if (found.text) rows.splice(found.at, found.end - found.at + 1, want);
916
936
  else rows.splice(found.insert, 0, ...(found.insert < rows.length && rows[found.insert] !== "" ? [want, ""] : [want]));
@@ -943,7 +963,8 @@ function writeAgyHooks(hooks) {
943
963
  async function offerAntigravity() {
944
964
  if (!antigravityHere()) { if (command === "antigravity") say(" Antigravity is not on this computer (no ~/.gemini/config or ~/.gemini/antigravity*)."); return; }
945
965
  if (!existsSync(STABLE)) { say(" Couple this computer first: npx worktrust"); return; }
946
- const want = { enabled: true, Stop: [{ type: "command", command: `"${NODE}" "${STABLE}" hook --antigravity-stop`, timeout: 10 }] };
966
+ const desired = () => ({ enabled: true, Stop: [{ type: "command", command: `"${NODE}" "${STABLE}" hook --antigravity-stop`, timeout: 10 }] });
967
+ let want = desired();
947
968
  const hooks = agyHooks();
948
969
  say();
949
970
  if (hooks === null) { say(` ${AGY_HOOKS} is not readable JSON, so it is left as it is; Antigravity sessions are still sent whenever another hook runs.`); return; }
@@ -952,6 +973,7 @@ async function offerAntigravity() {
952
973
  say(` ${hooks.worktrust ? "↻" : "+"} ${AGY_HOOKS} → worktrust: Stop runs ${want.Stop[0].command}`);
953
974
  if (has("dry-run")) { say(" Dry run: nothing was written."); return; }
954
975
  if (!has("antigravity") && !(await ask("Let Antigravity wake the session hook?", false))) { say(" Not set. npx worktrust update asks again."); return; }
976
+ await prepareBundledRuntime(); want = desired();
955
977
  writeAgyHooks({ ...hooks, worktrust: want });
956
978
  say(` ✓ Antigravity wakes the session hook. Restart Antigravity to pick it up${existsSync(`${AGY_HOOKS}.worktrust-backup`) ? "; the earlier file is kept as hooks.json.worktrust-backup" : ""}.`);
957
979
  }