worktrust 0.10.24 → 0.10.26

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.
@@ -1,7 +1,7 @@
1
1
  /** Official launcher verification. Pinned keys are generated from reviewed release configuration. */
2
2
  import { createHash, createPublicKey, verify, randomBytes } from 'node:crypto';
3
- import { existsSync, lstatSync, readFileSync, readdirSync, mkdirSync, writeFileSync, renameSync, rmSync } from 'node:fs';
4
- import { join, dirname } from 'node:path';
3
+ import { existsSync, lstatSync, readFileSync, readdirSync, mkdirSync, writeFileSync, renameSync, rmSync, constants, openSync, closeSync, fstatSync, fchmodSync, readSync, fsyncSync } from 'node:fs';
4
+ import { join, dirname, basename, isAbsolute } from 'node:path';
5
5
 
6
6
  export const RELEASE_KEYS = {"608168ccdef72562fc91f9c0f9f2c2d6876bece7f7362cb545b818f7947da6b5":"-----BEGIN PUBLIC KEY-----\nMCowBQYDK2VwAyEAxe/h8yLe+e4iKYSx/2lzS7MgHIgzM+mi1XjofW1VKo4=\n-----END PUBLIC KEY-----\n"}; // GENERATED_RELEASE_KEYS
7
7
  const hash = bytes => createHash('sha256').update(bytes).digest('hex');
@@ -16,7 +16,7 @@ const exact = (value, keys) => value && Object.keys(value).sort().join(',') ===
16
16
  const safe = name => {
17
17
  if (typeof name !== 'string' || name.length > 240) return false;
18
18
  const parts = name.split('/');
19
- return parts.every((p, i) => (/^[A-Za-z0-9][A-Za-z0-9._-]*$/.test(p) && p !== '..')
19
+ return parts.every((p, i) => (/^[A-Za-z0-9_][A-Za-z0-9._-]*$/.test(p) && p !== '..')
20
20
  || (p === '.claude-plugin' && i > 0 && i < parts.length - 1 && parts[i - 1] === 'agent'));
21
21
  };
22
22
  function regular(path) {
@@ -44,7 +44,7 @@ export function verifyPackage(root, kind = 'npm') {
44
44
  || !verify(null, Buffer.from('worktrust:package:1\n' + canonical(signed.payload)), key, Buffer.from(signed.signature, 'base64url'))) throw Error('PACKAGE_UNTRUSTED_SIGNATURE');
45
45
  const m = signed.payload;
46
46
  if (!exact(m, ['format', 'kind', 'version', 'files']) || m.format !== 'worktrust-package/1' || m.kind !== kind || !/^\d+\.\d+\.\d+$/.test(m.version)
47
- || !m.files || Array.isArray(m.files) || typeof m.files !== 'object' || Object.keys(m.files).length > 2000 || !Object.hasOwn(m.files, 'worktrust.mjs')) throw Error('PACKAGE_INVALID_MANIFEST');
47
+ || !m.files || Array.isArray(m.files) || typeof m.files !== 'object' || Object.keys(m.files).length > 2000 || !Object.hasOwn(m.files, kind === 'python' ? 'bundle/worktrust.mjs' : 'worktrust.mjs')) throw Error('PACKAGE_INVALID_MANIFEST');
48
48
  const expected = Object.keys(m.files).sort();
49
49
  for (const name of expected) {
50
50
  if (!safe(name) || name === signatureName || !/^[a-f0-9]{64}$/.test(m.files[name])) throw Error('PACKAGE_INVALID_MANIFEST');
@@ -53,9 +53,9 @@ export function verifyPackage(root, kind = 'npm') {
53
53
  const file = join(root, name);
54
54
  if (regular(file).size > 128 * 1024 * 1024 || hash(readFileSync(file)) !== m.files[name]) throw Error('PACKAGE_FILE_CHANGED');
55
55
  }
56
- const found = filesIn(root).filter(name => name !== signatureName && (kind !== 'engine' || name.endsWith('.mjs'))).sort();
56
+ const found = filesIn(root).filter(name => (kind !== 'python' || !name.split('/').includes('__pycache__')) && name !== signatureName && (kind !== 'engine' || name.endsWith('.mjs'))).sort();
57
57
  if (JSON.stringify(found) !== JSON.stringify(expected)) throw Error('PACKAGE_FILE_LIST_CHANGED');
58
- if (/const CLI_VERSION = "([^"]+)";/.exec(readFileSync(join(root, 'worktrust.mjs'), 'utf8'))?.[1] !== m.version) throw Error('PACKAGE_VERSION_MISMATCH');
58
+ if (/const CLI_VERSION = "([^"]+)";/.exec(readFileSync(join(root, kind === 'python' ? 'bundle/worktrust.mjs' : 'worktrust.mjs'), 'utf8'))?.[1] !== m.version) throw Error('PACKAGE_VERSION_MISMATCH');
59
59
  return { manifest: m, identity: hash(readFileSync(path)), signatureName };
60
60
  }
61
61
  export function installSignedPackage(source, home) {
@@ -80,3 +80,80 @@ export function installSignedPackage(source, home) {
80
80
  } finally { rmSync(pending, { recursive: true, force: true }); }
81
81
  return join(target, 'worktrust-launch.mjs');
82
82
  }
83
+
84
+ /** Child processes of the official launcher re-enter verification, including long-lived MCP bridges.
85
+ * Raw source test harnesses retain direct entry; they are not authenticated release launches.
86
+ */
87
+ function persistentPython(root) {
88
+ return globalThis[Symbol.for("worktrust.verifiedReleaseRoot")] === root
89
+ && basename(root) === "engine" && /^[a-f0-9]{64}$/.test(basename(dirname(root)))
90
+ && basename(dirname(dirname(root))) === "installations"
91
+ && typeof process.env.WORKTRUST_BUNDLED_PYTHON === "string" && isAbsolute(process.env.WORKTRUST_BUNDLED_PYTHON)
92
+ && process.env.WORKTRUST_INSTALLED_LAUNCHER === join(dirname(root), "worktrust-launch.py")
93
+ && process.env.WORKTRUST_BUNDLED_PYTHON;
94
+ }
95
+ export function moduleExecutable(root) { return persistentPython(root) || process.execPath; }
96
+ export function moduleArgs(root, name, args = []) {
97
+ if (!["worktrust.mjs", "setup-mcp.mjs", "log-session.mjs", "count-behaviour.mjs", "preserve.mjs"].includes(name)) throw Error("PACKAGE_INVALID_ENTRY");
98
+ if (persistentPython(root)) return ["-I", process.env.WORKTRUST_INSTALLED_LAUNCHER, "--internal-module", name, ...args];
99
+ const flags = process.versions.node === "26.5.0" ? ["--no-concurrent-sparkplug"] : [];
100
+ return globalThis[Symbol.for("worktrust.verifiedReleaseRoot")] === root
101
+ ? [...flags, join(root, "worktrust-launch.mjs"), "--internal-module", name, ...args]
102
+ : [...flags, join(root, name), ...args];
103
+ }
104
+
105
+ // Credentials stay outside the immutable release. File hygiene reduces cross-user theft;
106
+ // it does not attest the machine owner or the truth of data they choose to sign.
107
+ function privateDirectory(path, create) {
108
+ if (create) mkdirSync(path, { recursive: true, mode: 0o700 });
109
+ const before = lstatSync(path);
110
+ if (!before.isDirectory() || before.isSymbolicLink() || (process.getuid && before.uid !== process.getuid())) throw Error('KEY_FILE_UNSAFE');
111
+ // Windows ACLs remain the responsibility of the user's private profile directory.
112
+ if (process.platform !== 'win32') {
113
+ const fd = openSync(path, constants.O_RDONLY | (constants.O_NOFOLLOW ?? 0));
114
+ try { const current = fstatSync(fd); if (current.ino !== before.ino || current.dev !== before.dev) throw Error('KEY_FILE_UNSAFE'); fchmodSync(fd, 0o700); }
115
+ finally { closeSync(fd); }
116
+ }
117
+ }
118
+ function privateStat(stat) {
119
+ if (!stat.isFile() || stat.isSymbolicLink() || stat.nlink !== 1 || stat.size > 65536 || (process.getuid && stat.uid !== process.getuid())) throw Error('KEY_FILE_UNSAFE');
120
+ }
121
+ /** Bounded descriptor read; never follow a linked credential, pipe, device or directory. */
122
+ export function readPrivateFile(file) {
123
+ let fd;
124
+ try {
125
+ privateDirectory(dirname(file), false);
126
+ const before = lstatSync(file); privateStat(before);
127
+ fd = openSync(file, constants.O_RDONLY | (constants.O_NOFOLLOW ?? 0) | (constants.O_NONBLOCK ?? 0));
128
+ const current = fstatSync(fd); privateStat(current);
129
+ if (current.ino !== before.ino || current.dev !== before.dev) throw Error('KEY_FILE_UNSAFE');
130
+ if (process.platform !== 'win32') fchmodSync(fd, 0o600);
131
+ const bytes = Buffer.alloc(65537); let size = 0, next;
132
+ while (size < bytes.length && (next = readSync(fd, bytes, size, bytes.length - size, null)) > 0) size += next;
133
+ if (size > 65536) throw Error('KEY_FILE_UNSAFE');
134
+ return bytes.subarray(0, size).toString('utf8');
135
+ } catch (error) {
136
+ if (error.code === 'ENOENT') return null;
137
+ throw Error('KEY_FILE_UNSAFE');
138
+ } finally { if (fd !== undefined) closeSync(fd); }
139
+ }
140
+ /** Exclusive random temp, flush, atomic replace. Existing credentials survive a failed write. */
141
+ export function writePrivateFile(file, bytes) {
142
+ if (Buffer.byteLength(bytes) > 65536) throw Error('KEY_FILE_UNSAFE');
143
+ privateDirectory(dirname(file), true);
144
+ try { privateStat(lstatSync(file)); } catch (error) { if (error.code !== 'ENOENT') throw Error('KEY_FILE_UNSAFE'); }
145
+ const temporary = file + '.' + randomBytes(16).toString('hex') + '.tmp'; let fd;
146
+ try {
147
+ fd = openSync(temporary, constants.O_WRONLY | constants.O_CREAT | constants.O_EXCL | (constants.O_NOFOLLOW ?? 0), 0o600);
148
+ writeFileSync(fd, bytes); fsyncSync(fd); closeSync(fd); fd = undefined;
149
+ renameSync(temporary, file);
150
+ } finally { if (fd !== undefined) closeSync(fd); rmSync(temporary, { force: true }); }
151
+ }
152
+
153
+ /** First creation only, used by offline archive secrets; never overwrite an existing key. */
154
+ export function createPrivateFile(file, bytes) {
155
+ if (Buffer.byteLength(bytes) > 65536) throw Error('KEY_FILE_UNSAFE');
156
+ privateDirectory(dirname(file), true);
157
+ const fd = openSync(file, constants.O_WRONLY | constants.O_CREAT | constants.O_EXCL | (constants.O_NOFOLLOW ?? 0), 0o600);
158
+ try { writeFileSync(fd, bytes); fsyncSync(fd); } finally { closeSync(fd); }
159
+ }
@@ -1 +1 @@
1
- {"keyId":"608168ccdef72562fc91f9c0f9f2c2d6876bece7f7362cb545b818f7947da6b5","payload":{"files":{"AGENTS.md":"d1db152d88338df23b5900beed6a69bedc2900b6f53fef3f036b46dd7a07b841","CLAUDE.md":"5933504f93e5a40369a4790e96dd5dad791d849d3178b1833eb64088e456aaeb","LICENSE":"3096ed1693974a90e1f4f59bf01c9559d94a7941d933e36fb81d3995a97f25c1","README.md":"d6db7aff9f8c6ff8da1c67e9f16aa8ebf4a55efc21265e16c81b6408237ab056","SECURITY.md":"e3ed1927cbceef97b38ca630aadd0a91a0df02368f822f4fd66e3ed0b6a07e8d","chat-exports.mjs":"04eafe333940ec03d5058d8d51062124aa12ab882bf04db03bcda5613ec69298","claude-mod.mjs":"02d86b0cdddf39879efc5194c0a5be6b41456faedec28963dc123a4e88dc3942","config-edits.mjs":"0eba2f176ef6f7afba071d6e00de0ff19ba2b283180a801dfd957aa38c1edd94","count-behaviour.mjs":"1beaec2a4d0aead76d166f89cc52441a9cf48f2e69da9888ca2091dd3a10a37b","engine-release.json":"c31900cf37fb8ff571190ef1235fab4bed57007fc8c111e701da26dc5ad6dc90","history-outbox.mjs":"1bdca17b807c76e4a8e7bf42c6f07e12e8ae8e4466417cafdd26b1f58bf178a5","log-session.mjs":"6098eedb253b165819fdb4293adb6ddaa6c5843db0bbb007759701918955f664","orchestration-contract.mjs":"ec08f303a166365b99e70b675de4cfe76c6156c2567e14b5569f6d992f0231b7","orchestration-evidence.mjs":"d0d06cecf0eb08e5c6e653c62a4f45b1eddf2119c2acb8341056b34f488d214a","orchestration-report.mjs":"d4e0a9ad8e4a01b462d22c6b1866aac291565c533ff476085d3367cb6d59bc1b","package-integrity.mjs":"b9d81dc88cf5c19ccfbf334a7af84a0c4e299a0e9e4d4091132253e22f855dc3","package.json":"e2994c95ae40d276855b29263b3f284baccd1536f84db44a29259757dcf46b99","preserve-lines.mjs":"18081b745b8c47838448b0a49a129a363e29d3f2f5207bc591187d860157b456","preserve-summary.mjs":"137f781ed7021596a3f0ea67afcf2ab8616ac293f833dbb8f176e838e0ed8321","preserve.mjs":"38f83bd933853a986fef61f4e452c27d4a3adc6000f5c9201ef70f270b404eac","runtime-install.mjs":"b9d2e4febbf400a679eeb3a14b74eef6c2062c5b626d45872a193b7502d3201c","session-databases.mjs":"543fd3b82d28d96d789be0a1dc9186c5fafa783e98b87e5b3b17b211542e2b4d","setup-mcp.mjs":"70f63b61cf1e28fb2b7471e7768d596b0cf166ccdc9d1ce859ee58d29b2ecabc","stack-rules.mjs":"b23c56e72ec56ba02b17ed895f869172d988c468a697e8d6026b0e268f61e489","stretch-evidence.mjs":"5b31a6f29b785d277e92257532f3c7cee366a79759decc7a75cfbaec2686ee13","transcript-readers.mjs":"413948644a74dc0bf1b49548be193bf596bcf82ac7eae668f624345a18e189e7","worktrust-launch.mjs":"f28f699f986c72d99af8a7542d317f6dbb9e26d114f6ad083013567e08b8a650","worktrust.mjs":"c1cce642ba2ef4099b0fc3d375a4f8e8cb669b6694b0c99f08164a38d5d943d9"},"format":"worktrust-package/1","kind":"npm","version":"0.10.24"},"signature":"L6nxsuFrIoXcxsVvNrPkxkMV_woNpE5IGJLWjsvwGKdxtUkq2P6Foe7r2HmWavXleroNIcWcPf4CljteUCO9CQ"}
1
+ {"keyId":"608168ccdef72562fc91f9c0f9f2c2d6876bece7f7362cb545b818f7947da6b5","payload":{"files":{"AGENTS.md":"c6f5280c5bf81a14db4bdc282218fb005706e92dd9a9170c0e727716ee91685a","CLAUDE.md":"5933504f93e5a40369a4790e96dd5dad791d849d3178b1833eb64088e456aaeb","LICENSE":"3096ed1693974a90e1f4f59bf01c9559d94a7941d933e36fb81d3995a97f25c1","README.md":"997cb24638d7fda2d8961203c4e603de24cdb587968198644185140267753607","SECURITY.md":"f43e38504c477dc8ccdeed28cb2b244b6db3c816e962975645c250dde44cc86b","chat-exports.mjs":"04eafe333940ec03d5058d8d51062124aa12ab882bf04db03bcda5613ec69298","claude-mod.mjs":"02d86b0cdddf39879efc5194c0a5be6b41456faedec28963dc123a4e88dc3942","config-edits.mjs":"0eba2f176ef6f7afba071d6e00de0ff19ba2b283180a801dfd957aa38c1edd94","count-behaviour.mjs":"1beaec2a4d0aead76d166f89cc52441a9cf48f2e69da9888ca2091dd3a10a37b","credential-store.mjs":"a4b3540a61f4ce19e535c7f1d260c0d817686cd066d559a76db2ab108144abba","credential-vault-scripts.mjs":"7e42fe1db3885c2dec6f1de87bebfbefe2292d29179a68f3da87d19eb6c7704b","credential-vault.mjs":"279baabb217e2a3f170e8d7f2b271a88484531f9031c441360ea91561a70da99","engine-release.json":"feee10195c45a0e9083df08683542f6614c1897ff4ee05fb364da9dec463b66c","history-outbox.mjs":"1bdca17b807c76e4a8e7bf42c6f07e12e8ae8e4466417cafdd26b1f58bf178a5","log-session.mjs":"c5e6e4d44a85768f21c25945b8630f31306ec2665193886870c1010ef6bf3c26","orchestration-contract.mjs":"ec08f303a166365b99e70b675de4cfe76c6156c2567e14b5569f6d992f0231b7","orchestration-evidence.mjs":"d0d06cecf0eb08e5c6e653c62a4f45b1eddf2119c2acb8341056b34f488d214a","orchestration-report.mjs":"d4e0a9ad8e4a01b462d22c6b1866aac291565c533ff476085d3367cb6d59bc1b","package-integrity.mjs":"a8210c9494a56bfb9a5ea3d10064c7a269f0b6330c0af7c0700e706c3c0224e3","package.json":"6e09593a7aff4ad236eca7553c532635e30008a2a31ed11118fbeeb4ecadf895","preserve-lines.mjs":"2df64a69687aa51219bf7b86b88d175cc50990fa29574b31897e41a9ebeecf43","preserve-summary.mjs":"137f781ed7021596a3f0ea67afcf2ab8616ac293f833dbb8f176e838e0ed8321","preserve.mjs":"3e369083ba43bcda2fa0622fd526aa64fcf8ad66e7b6e8f23821752c4d47ad27","runtime-install.mjs":"aab47b52c79d726ef428a24f982c648fa3f1c2dc2b574f633611d02924864e5f","session-databases.mjs":"543fd3b82d28d96d789be0a1dc9186c5fafa783e98b87e5b3b17b211542e2b4d","setup-mcp.mjs":"6ecfbf44f001dd433512b26736031ebc855b154e2bb0a401e2512b43623cd9cd","stack-rules.mjs":"b23c56e72ec56ba02b17ed895f869172d988c468a697e8d6026b0e268f61e489","stretch-evidence.mjs":"5b31a6f29b785d277e92257532f3c7cee366a79759decc7a75cfbaec2686ee13","transcript-readers.mjs":"413948644a74dc0bf1b49548be193bf596bcf82ac7eae668f624345a18e189e7","worktrust-launch.mjs":"84801bd29d472d48188c126b9ebe3989a3132b54e13cc4fe534ff7c383a294ee","worktrust.mjs":"78260b4615226ac901211094a908e7535e2d8b8ff18856d907a817f3cb5a1e08"},"format":"worktrust-package/1","kind":"npm","version":"0.10.26"},"signature":"q5cJvi49xrDpbczLrs3W4GQ9pW4By9E0FkoR3yDzkLEi8672crlnZ7THHLFZEjgP9skpCY7liNsf2ENL1FpLDQ"}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "worktrust",
3
- "version": "0.10.24",
3
+ "version": "0.10.26",
4
4
  "description": "Couple this computer to WorkTrust: approve a code in your browser, and every AI app here reports what you built. Metadata only, no dependencies.",
5
5
  "type": "module",
6
6
  "bin": {
@@ -34,7 +34,10 @@
34
34
  "worktrust-launch.mjs",
35
35
  "engine-release.json",
36
36
  "package-release.json",
37
- "history-outbox.mjs"
37
+ "history-outbox.mjs",
38
+ "credential-store.mjs",
39
+ "credential-vault.mjs",
40
+ "credential-vault-scripts.mjs"
38
41
  ],
39
42
  "engines": {
40
43
  "node": ">=18"
@@ -3,6 +3,7 @@
3
3
  * and the behaviour signals joined on `stretch_ref`. A key not named here never reaches the archive. The capability
4
4
  * tranches (docs/CAPABILITY-EVIDENCE-ROADMAP.md) add their fields here, each with its own check.
5
5
  */
6
+ import { moduleArgs, moduleExecutable } from "./package-integrity.mjs";
6
7
  import { spawnSync } from "node:child_process";
7
8
  import { createHash, createHmac } from "node:crypto";
8
9
  import { existsSync, readFileSync, readdirSync } from "node:fs";
@@ -25,7 +26,7 @@ const WORD = /^[a-z][A-Za-z]{1,31}$/;
25
26
  export function stretchSignals(here, say) {
26
27
  const counter = join(here, "count-behaviour.mjs");
27
28
  if (!existsSync(counter)) return null;
28
- const run = spawnSync(process.execPath, [counter, "--stretch-signals", "--months", "120"], { encoding: "utf8", maxBuffer: 1 << 29, env: { ...process.env, WORKTRUST_MCP_URL: "", WORKTRUST_MCP_TOKEN: "" } });
29
+ const run = spawnSync(moduleExecutable(here), moduleArgs(here, "count-behaviour.mjs", ["--stretch-signals", "--months", "120"]), { encoding: "utf8", maxBuffer: 1 << 29, env: { ...process.env, WORKTRUST_MCP_URL: "", WORKTRUST_MCP_TOKEN: "" } });
29
30
  const rows = (run.stdout ?? "").split("\n").filter((text) => text.startsWith("{")).map((text) => { try { return JSON.parse(text); } catch { return null; } });
30
31
  const end = rows.at(-1)?.stretch_signals_end;
31
32
  if (run.status !== 0 || !Number.isInteger(end) || end !== rows.length - 1) { say(" The behaviour counter did not answer whole, so these lines carry no signals; the next run adds them to new lines."); return null; }
package/preserve.mjs CHANGED
@@ -23,6 +23,8 @@
23
23
  * (`prev`, `hash`), appended and never rewritten; each day has proofs/<day>.json, its root, signed with the device key
24
24
  * (~/.worktrust/key.json) when there is one. Today waits for the next run. Nothing leaves this computer.
25
25
  */
26
+ import { readDeviceSigningKey } from "./credential-store.mjs";
27
+ import { moduleArgs, moduleExecutable, readPrivateFile, createPrivateFile } from "./package-integrity.mjs";
26
28
  import { execFileSync, spawnSync } from "node:child_process";
27
29
  import { createHash, createPrivateKey, createPublicKey, generateKeyPairSync, randomBytes, sign, verify } from "node:crypto";
28
30
  import { appendFileSync, chmodSync, copyFileSync, existsSync, mkdirSync, readFileSync, readdirSync, statSync, writeFileSync } from "node:fs";
@@ -185,17 +187,16 @@ function computerIds() {
185
187
  /** This computer's own secret for the archive's project hashes (0.8.6): made once, readable by its owner alone, never archived. */
186
188
  function archiveSalt() {
187
189
  const file = home(".worktrust", "archive-salt");
188
- try { const kept = readFileSync(file, "utf8").trim(); if (/^[0-9a-f]{64}$/.test(kept)) return kept; } catch { /* first run */ }
189
- try { mkdirSync(home(".worktrust"), { recursive: true, mode: 0o700 }); const made = randomBytes(32).toString("hex"); writeFileSync(file, `${made}\n`, { mode: 0o600, flag: "wx" }); return made; } catch { try { return readFileSync(file, "utf8").trim(); } catch { return null; } }
190
+ try { const kept = readPrivateFile(file)?.trim(); if (/^[0-9a-f]{64}$/.test(kept)) return kept; } catch { /* first run */ }
191
+ try { const made = randomBytes(32).toString("hex"); createPrivateFile(file, `${made}\n`); return made; } catch { try { return readPrivateFile(file)?.trim() ?? null; } catch { return null; } }
190
192
  }
191
193
  /** The device key, when this computer is coupled: its private half signs, its public half goes into the proof. */
192
- function deviceKey() {
193
- try {
194
- const key = JSON.parse(Buffer.from(readFileSync(home(".worktrust", "key.json"), "utf8"), "base64").toString("utf8"));
195
- const privateKey = createPrivateKey(key.device);
196
- return { privateKey, publicX: createPublicKey(privateKey).export({ format: "jwk" }).x, kind: "device" };
197
- } catch { return null; }
194
+ let cachedDeviceKey;
195
+ function deviceKey(required = false) {
196
+ try { if (cachedDeviceKey === undefined) cachedDeviceKey = readDeviceSigningKey(home(".worktrust", "key.json")); return cachedDeviceKey; }
197
+ catch (error) { if (required) throw error; return null; }
198
198
  }
199
+
199
200
  /**
200
201
  * THE LOCAL ARCHIVE KEY (owner, 2026-10-10): a computer that is not coupled still signs its archive, with an Ed25519 key made
201
202
  * here (~/.worktrust/archive-key.json, mode 600, folder 700), so a day's root can be told from an edit and the chain stays one
@@ -207,7 +208,7 @@ function deviceKey() {
207
208
  const ARCHIVE_KEY_FILE = home(".worktrust", "archive-key.json");
208
209
  function archiveKey(create = false) {
209
210
  try {
210
- const kept = JSON.parse(readFileSync(ARCHIVE_KEY_FILE, "utf8"));
211
+ const kept = JSON.parse(readPrivateFile(ARCHIVE_KEY_FILE));
211
212
  const privateKey = createPrivateKey(kept.private);
212
213
  return { privateKey, publicX: createPublicKey(privateKey).export({ format: "jwk" }).x, kind: "archive", made: false };
213
214
  } catch { /* none yet, or unreadable */ }
@@ -215,10 +216,7 @@ function archiveKey(create = false) {
215
216
  try {
216
217
  const pair = generateKeyPairSync("ed25519");
217
218
  const privatePem = pair.privateKey.export({ format: "pem", type: "pkcs8" }), publicX = pair.publicKey.export({ format: "jwk" }).x;
218
- mkdirSync(home(".worktrust"), { recursive: true, mode: 0o700 });
219
- try { chmodSync(home(".worktrust"), 0o700); } catch { /* Windows */ }
220
- writeFileSync(ARCHIVE_KEY_FILE, `${JSON.stringify({ format: "worktrust-archive-key/1", public: publicX, private: privatePem, created: new Date().toISOString() }, null, 1)}\n`, { mode: 0o600, flag: "wx" });
221
- try { chmodSync(ARCHIVE_KEY_FILE, 0o600); } catch { /* Windows */ }
219
+ createPrivateFile(ARCHIVE_KEY_FILE, `${JSON.stringify({ format: "worktrust-archive-key/1", public: publicX, private: privatePem, created: new Date().toISOString() }, null, 1)}\n`);
222
220
  return { privateKey: pair.privateKey, publicX, kind: "archive", made: true };
223
221
  } catch { return archiveKey(false); }
224
222
  }
@@ -289,7 +287,7 @@ function archive(dir) {
289
287
  IDS = computerIds();
290
288
  const existing = existsSync(join(dir, "manifest.json")) || readArchive(dir).length > 0 ? check(dir) : { lines: [], manifest: null };
291
289
  if (existing.broken) { say(` The archive in ${dir} does not verify, so nothing was added: ${existing.broken}`); process.exit(1); }
292
- const hook = spawnSync(process.execPath, [join(HERE, "log-session.mjs"), "--archive-lines"], { encoding: "utf8", maxBuffer: 1 << 29, env: { ...process.env, WORKTRUST_MCP_URL: "", WORKTRUST_MCP_TOKEN: "", WORKTRUST_HOOK_INPUT: "" } });
290
+ const hook = spawnSync(moduleExecutable(HERE), moduleArgs(HERE, "log-session.mjs", ["--archive-lines"]), { encoding: "utf8", maxBuffer: 1 << 29, env: { ...process.env, WORKTRUST_MCP_URL: "", WORKTRUST_MCP_TOKEN: "", WORKTRUST_HOOK_INPUT: "" } });
293
291
  if (hook.status !== 0) { say(` The session hook could not read this computer's sessions: ${(hook.stderr || "").trim().split("\n").pop()}`); process.exit(1); }
294
292
  // A WHOLE ANSWER OR NOTHING: the hook ends with its own count; one line missing or cut is a read to refuse, never part of an archive.
295
293
  const rows = hook.stdout.split("\n").filter(Boolean), end = (() => { try { return JSON.parse(rows.at(-1) ?? "").archive_end; } catch { return undefined; } })();
@@ -310,6 +308,9 @@ function archive(dir) {
310
308
  fresh.push(line);
311
309
  }
312
310
  fresh.sort((a, b) => a.started_at.localeCompare(b.started_at) || a.client.localeCompare(b.client) || a.stretch_ref.localeCompare(b.stretch_ref));
311
+ let key;
312
+ try { key = deviceKey(true) ?? archiveKey(true); }
313
+ catch { say(" Signing key unavailable. Unlock your OS vault and retry. No archive data was changed."); process.exitCode = 1; return; }
313
314
  mkdirSync(dir, { recursive: true, mode: 0o700 });
314
315
  let prev = existing.lines.at(-1)?.hash ?? null, seq = existing.lines.length;
315
316
  const all = [...existing.lines];
@@ -324,9 +325,7 @@ function archive(dir) {
324
325
  // A day that gained lines gets its root again over all of its lines; the lines themselves are never rewritten.
325
326
  // THIS KEY SIGNS ONLY ITS OWN LINES (0.6.18, audit S7): a day is signed when every earlier line of it was already under
326
327
  // this key's signature (or there were none); a day that came into the folder from elsewhere keeps an unsigned root.
327
- // THE SIGNING KEY (owner, 2026-10-10): the device key when this computer is coupled, else the local archive key, made now when
328
- // there is none. A day or a manifest either of this computer's keys sealed is this computer's to seal again.
329
- const key = deviceKey() ?? archiveKey(true);
328
+ // Either of this computer's keys may reseal its own days; the signer was resolved before mutation.
330
329
  const mineX = new Set(ownKeys().map((own) => own.publicX));
331
330
  const ours = (document) => !document || (key && typeof document.signature === "string" && mineX.has(document.public_key));
332
331
  mkdirSync(join(dir, "proofs"), { recursive: true });
@@ -2,8 +2,9 @@
2
2
  * Called only after the person's connect/update confirmation. No network, credentials or measurement logic.
3
3
  */
4
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";
5
+ import { existsSync, realpathSync, lstatSync, mkdirSync, readFileSync, readdirSync, renameSync, rmSync, writeFileSync } from "node:fs";
6
+ import { join, dirname, resolve, isAbsolute } from "node:path";
7
+ import { verifyPackage } from "./package-integrity.mjs";
7
8
 
8
9
  const hash = (bytes) => createHash("sha256").update(bytes).digest("hex");
9
10
  const regular = (path) => { const stat = lstatSync(path); if (!stat.isFile() || stat.isSymbolicLink()) throw Error("bundled installation requires regular files"); };
@@ -12,6 +13,13 @@ const checkedBytes = (path) => { regular(path); return readFileSync(path); };
12
13
 
13
14
  export function installRuntime(runtime, engine, home, moduleNames) {
14
15
  directory(runtime); directory(engine); directory(home);
16
+ const python = process.env.WORKTRUST_BUNDLED_PYTHON;
17
+ if (!python || !isAbsolute(python) || !existsSync(python)) throw Error("trusted Python interpreter required");
18
+ // The Python entry authenticates this package before Node starts; check again before persisting it.
19
+ const packageRoot = dirname(realpathSync(engine));
20
+ if (realpathSync(runtime) !== join(resolve(packageRoot), "runtime") || realpathSync(engine) !== join(resolve(packageRoot), "bundle")) throw Error("bundled distribution layout mismatch");
21
+ verifyPackage(packageRoot, "python");
22
+ verifyPackage(engine, "engine");
15
23
  const descriptor = checkedBytes(join(runtime, "runtime.json"));
16
24
  const manifest = JSON.parse(descriptor);
17
25
  const executable = process.platform === "win32" ? "node.exe" : "node";
@@ -32,19 +40,53 @@ export function installRuntime(runtime, engine, home, moduleNames) {
32
40
  }
33
41
  if (existsSync(join(engine, "engine-release.json"))) contents.set("engine/engine-release.json", checkedBytes(join(engine, "engine-release.json")));
34
42
  const identities = Object.fromEntries([...contents].map(([name, bytes]) => [name, hash(bytes)]));
35
- const identity = Buffer.from(JSON.stringify(identities));
36
- const installations = join(home, "installations"), installed = join(installations, hash(identity));
43
+ const identity = Buffer.from(JSON.stringify({ format: "worktrust-installation/2", files: identities }));
44
+ // The external, package-manager Python starts BEFORE the copied Node executable. This bootstrap
45
+ // pins the hashes authenticated above; it never trusts a locally rewritten descriptor to bless code.
46
+ const bootstrap = Buffer.from(`import hashlib, json, os, pathlib, subprocess, sys
47
+ EXPECTED = json.loads(${JSON.stringify(JSON.stringify(identities))})
48
+ IDENTITY = ${JSON.stringify(identity.toString())}
49
+ root = pathlib.Path(__file__).absolute().parent.resolve()
50
+ try:
51
+ if not sys.flags.isolated or root.is_symlink(): raise ValueError("PACKAGE_BOOTSTRAP_REQUIRED")
52
+ if set(p.name for p in root.iterdir()) != {"engine", "runtime", "installation.json", "worktrust-launch.py"}: raise ValueError("PACKAGE_FILE_LIST_CHANGED")
53
+ for group in ("engine", "runtime"):
54
+ folder = root / group
55
+ if folder.is_symlink() or not folder.is_dir(): raise ValueError("PACKAGE_NON_REGULAR_DIRECTORY")
56
+ if set(p.name for p in folder.iterdir()) != {name.split("/", 1)[1] for name in EXPECTED if name.startswith(group + "/")}: raise ValueError("PACKAGE_FILE_LIST_CHANGED")
57
+ marker = root / "installation.json"
58
+ if marker.is_symlink() or marker.read_text() != IDENTITY: raise ValueError("PACKAGE_INSTALLATION_IDENTITY_MISMATCH")
59
+ for name, digest in EXPECTED.items():
60
+ file = root / name
61
+ if file.is_symlink() or not file.is_file() or file.stat().st_size > 128 * 1024 * 1024 or hashlib.sha256(file.read_bytes()).hexdigest() != digest: raise ValueError("PACKAGE_FILE_CHANGED")
62
+ except (OSError, ValueError):
63
+ print("worktrust: PACKAGE_VERIFICATION_FAILED. Execution stopped; reinstall an official WorkTrust release.", file=sys.stderr)
64
+ sys.exit(1)
65
+ node = root / "runtime" / ${JSON.stringify(executable)}
66
+ entry = root / "engine" / "worktrust-launch.mjs"
67
+ env = dict(os.environ)
68
+ env["WORKTRUST_BUNDLED_PYTHON"] = sys.executable
69
+ env["WORKTRUST_INSTALLED_LAUNCHER"] = str(root / "worktrust-launch.py")
70
+ for key in ("NODE_OPTIONS", "NODE_PATH", "WORKTRUST_BUNDLED_RUNTIME_DIR"):
71
+ env.pop(key, None)
72
+ argv = [str(node), str(entry), *sys.argv[1:]]
73
+ if os.name != "nt": os.execve(node, argv, env)
74
+ sys.exit(subprocess.call(argv, env=env))
75
+ `);
76
+ contents.set("worktrust-launch.py", bootstrap);
77
+ const installations = join(home, "installations"), installed = join(installations, hash(Buffer.concat([identity, bootstrap])));
37
78
  if (!existsSync(installations)) mkdirSync(installations, { mode: 0o700 });
38
79
  directory(installations);
39
80
  const verify = (place) => {
40
81
  directory(place);
41
- if (JSON.stringify(readdirSync(place).sort()) !== JSON.stringify(["engine", "installation.json", "runtime"])) throw Error("installed bundle file list mismatch");
82
+ if (JSON.stringify(readdirSync(place).sort()) !== JSON.stringify(["engine", "installation.json", "runtime", "worktrust-launch.py"])) throw Error("installed bundle file list mismatch");
42
83
  if (!checkedBytes(join(place, "installation.json")).equals(identity)) throw Error("installed bundle identity mismatch");
43
84
  for (const group of ["engine", "runtime"]) {
44
85
  directory(join(place, group));
45
86
  const expected = [...contents.keys()].filter(name => name.startsWith(`${group}/`)).map(name => name.slice(group.length + 1)).sort();
46
87
  if (JSON.stringify(readdirSync(join(place, group)).sort()) !== JSON.stringify(expected)) throw Error("installed bundle file list mismatch");
47
88
  }
89
+ if (!checkedBytes(join(place, "worktrust-launch.py")).equals(bootstrap)) throw Error("installed bootstrap integrity check failed");
48
90
  for (const [name, digest] of Object.entries(identities)) if (hash(checkedBytes(join(place, name))) !== digest) throw Error("installed bundle integrity check failed");
49
91
  };
50
92
  if (existsSync(installed)) verify(installed);
@@ -61,5 +103,5 @@ export function installRuntime(runtime, engine, home, moduleNames) {
61
103
  } finally { rmSync(temporary, { recursive: true, force: true }); }
62
104
  }
63
105
  // Existing immutable directories are never replaced, including executables used by Windows processes.
64
- return { executable: join(installed, "runtime", executable), bridge: join(installed, "engine", contents.has("engine/engine-release.json") ? "worktrust-launch.mjs" : "worktrust.mjs") };
106
+ return { executable: python, args: ["-I"], bridge: join(installed, "worktrust-launch.py") };
65
107
  }
package/setup-mcp.mjs CHANGED
@@ -33,6 +33,8 @@ const NAME = value("name") ?? "worktrust";
33
33
  */
34
34
  const BRIDGE = value("bridge");
35
35
  const NODE = process.env.WORKTRUST_NODE || process.execPath;
36
+ const NODE_ARGS = process.env.WORKTRUST_NODE_ARGS === '["-I"]' ? ["-I"] : [];
37
+ const NODE_COMMAND = `"${NODE}"${NODE_ARGS.length ? " -I" : ""}`;
36
38
 
37
39
  /** The coupling: given, or the one Claude Code already holds (the counter reads it the same way). */
38
40
  function fromClaude() {
@@ -65,7 +67,7 @@ const URL_ = value("url") ?? process.env.WORKTRUST_MCP_URL ?? discovered?.url;
65
67
  const TOKEN = value("token") ?? process.env.WORKTRUST_MCP_TOKEN ?? discovered?.token;
66
68
  if (!URL_ || (!TOKEN && !BRIDGE)) { console.error("no coupling: pass --url and --token (from Sources → Claude (MCP) → Add coupling), or couple Claude Code first"); process.exit(1); }
67
69
  const masked = BRIDGE ? "kept in ~/.worktrust/key.json, not in these files" : `${TOKEN.slice(0, 6)}…${TOKEN.slice(-4)}`;
68
- const stdio = { command: NODE, args: [BRIDGE ?? "", "mcp"] };
70
+ const stdio = { command: NODE, args: [...NODE_ARGS, BRIDGE ?? "", "mcp"] };
69
71
  const home = homedir();
70
72
  /** Whether Claude Code's own command is on this machine: asked of the shell, never guessed from a file. */
71
73
  /**
@@ -98,8 +100,8 @@ const hermesHomes = () => {
98
100
  try { for (const name of readdirSync(join(HERMES_BASE, "profiles")).sort()) homes.add(join(HERMES_BASE, "profiles", name)); } catch { /* no profiles */ }
99
101
  return [...homes].filter((dir) => existsSync(dir));
100
102
  };
101
- const HERMES_HOOK = `"${NODE}" "${BRIDGE ?? ""}" hook --hermes`;
102
- const ours = (text) => text.includes(URL_) || /worktrust\.mjs/.test(text);
103
+ const HERMES_HOOK = `${NODE_COMMAND} "${BRIDGE ?? ""}" hook --hermes`;
104
+ const ours = (text) => text.includes(URL_) || /worktrust(?:-launch)?\.(?:mjs|py)/.test(text);
103
105
  /** A YAML client's file with our entry (and hook) taken out and, unless removing, put back in; null when it cannot be. */
104
106
  function yamlConfig(client, text, remove) {
105
107
  const lines = text.trim() === "" ? [] : text.replace(/\n$/, "").split("\n");
@@ -112,7 +114,7 @@ function yamlConfig(client, text, remove) {
112
114
  return lines.length ? `${lines.join("\n")}\n` : "";
113
115
  }
114
116
  const bridgeOrUrl = (local, remote) => (BRIDGE ? local : remote);
115
- const HERMES_SERVER = bridgeOrUrl([`${NAME}:`, ` command: ${JSON.stringify(NODE)}`, ` args: [${JSON.stringify(BRIDGE)}, "mcp"]`], [`${NAME}:`, ` url: ${JSON.stringify(URL_)}`, " headers:", ` Authorization: ${JSON.stringify(`Bearer ${TOKEN}`)}`]);
117
+ const HERMES_SERVER = bridgeOrUrl([`${NAME}:`, ` command: ${JSON.stringify(NODE)}`, ` args: [${[...NODE_ARGS, BRIDGE, "mcp"].map(arg => JSON.stringify(arg)).join(", ")}]`], [`${NAME}:`, ` url: ${JSON.stringify(URL_)}`, " headers:", ` Authorization: ${JSON.stringify(`Bearer ${TOKEN}`)}`]);
116
118
  /**
117
119
  * GOOSE (2026-10-05, aaif-goose/goose: crates/goose/src/config/extensions.rs, agents/extension.rs; documentation
118
120
  * guides/config-files.md): `extensions` in config.yaml (~/.config/goose, %APPDATA%\\Block\\goose\\config on Windows,
@@ -121,12 +123,12 @@ const HERMES_SERVER = bridgeOrUrl([`${NAME}:`, ` command: ${JSON.stringify(NODE
121
123
  * guides/context-engineering/hooks.md); with the bridge one plugin named worktrust runs the session hook on SessionEnd.
122
124
  */
123
125
  const GOOSE_SERVER = bridgeOrUrl(
124
- [`${NAME}:`, " type: stdio", ` name: ${NAME}`, " enabled: true", ` cmd: ${JSON.stringify(NODE)}`, ` args: [${JSON.stringify(BRIDGE)}, "mcp"]`, " envs: {}", " timeout: 300"],
126
+ [`${NAME}:`, " type: stdio", ` name: ${NAME}`, " enabled: true", ` cmd: ${JSON.stringify(NODE)}`, ` args: [${[...NODE_ARGS, BRIDGE, "mcp"].map(arg => JSON.stringify(arg)).join(", ")}]`, " envs: {}", " timeout: 300"],
125
127
  [`${NAME}:`, " type: streamable_http", ` name: ${NAME}`, " enabled: true", ` uri: ${JSON.stringify(URL_)}`, " headers:", ` Authorization: ${JSON.stringify(`Bearer ${TOKEN}`)}`, " envs: {}", " timeout: 300"],
126
128
  );
127
129
  const gooseDirs = () => [...new Set([...(process.env.GOOSE_PATH_ROOT ? [join(process.env.GOOSE_PATH_ROOT, "config")] : []), join(home, ".config", "goose"), ...(platform() === "win32" && process.env.APPDATA ? [join(process.env.APPDATA, "Block", "goose", "config")] : [])])].filter((dir) => existsSync(dir));
128
130
  const GOOSE_PLUGIN = join(process.env.GOOSE_PATH_ROOT || home, ".agents", "plugins", NAME);
129
- const GOOSE_HOOKS = { hooks: { SessionEnd: [{ hooks: [{ type: "command", command: `"${NODE}" "${BRIDGE ?? ""}" hook --goose`, timeout: 30 }] }] } };
131
+ const GOOSE_HOOKS = { hooks: { SessionEnd: [{ hooks: [{ type: "command", command: `${NODE_COMMAND} "${BRIDGE ?? ""}" hook --goose`, timeout: 30 }] }] } };
130
132
  const goosePluginStands = () => { try { return JSON.stringify(JSON.parse(readFileSync(join(GOOSE_PLUGIN, "hooks", "hooks.json"), "utf8"))) === JSON.stringify(GOOSE_HOOKS); } catch { return false; } };
131
133
  /** Our plugin folder in, or out; another plugin is never touched, and a folder of that name that is not ours stays. */
132
134
  function goosePlugin(remove) {
@@ -157,7 +159,7 @@ export const WorkTrust = async () => ({
157
159
  event: async ({ event }) => {
158
160
  if (event?.type !== "session.idle" || Date.now() - last < 30_000) return;
159
161
  last = Date.now();
160
- try { spawn(${JSON.stringify(NODE)}, [${JSON.stringify(BRIDGE ?? "")}, "hook"], { detached: true, stdio: "ignore" }).unref(); } catch { /* the next run sweeps it */ }
162
+ try { spawn(${JSON.stringify(NODE)}, ${JSON.stringify([...NODE_ARGS, BRIDGE ?? "", "hook"])}, { detached: true, stdio: "ignore" }).unref(); } catch { /* the next run sweeps it */ }
161
163
  },
162
164
  });
163
165
  `;
@@ -179,25 +181,25 @@ const opencodePluginStands = () => { try { return readFileSync(OPENCODE_PLUGIN,
179
181
  * sessions are read whenever another client's hook runs.
180
182
  */
181
183
  const OPENCLAW_FILE = process.env.OPENCLAW_CONFIG_PATH || join(process.env.OPENCLAW_STATE_DIR || join(home, ".openclaw"), "openclaw.json");
182
- const OPENCLAW_ENTRY = BRIDGE ? { command: NODE, args: [BRIDGE, "mcp"] } : { url: URL_, transport: "streamable-http", headers: { Authorization: `Bearer ${TOKEN}` } };
184
+ const OPENCLAW_ENTRY = BRIDGE ? { command: NODE, args: [...NODE_ARGS, BRIDGE, "mcp"] } : { url: URL_, transport: "streamable-http", headers: { Authorization: `Bearer ${TOKEN}` } };
183
185
 
184
186
  /** Each client: where it lives, how it says "an HTTP MCP server with a header". */
185
187
  const CLIENTS = [
186
188
  { key: "cursor", label: "Cursor", present: () => existsSync(join(home, ".cursor")), file: join(home, ".cursor", "mcp.json"), shape: "json", root: "mcpServers", entry: BRIDGE ? stdio : { url: URL_, headers: { Authorization: `Bearer ${TOKEN}` } } },
187
- { key: "codex", label: "Codex CLI", present: () => existsSync(join(home, ".codex")), file: join(home, ".codex", "config.toml"), shape: "toml", block: BRIDGE ? `\n[mcp_servers.${NAME}]\ncommand = ${JSON.stringify(NODE)}\nargs = [${JSON.stringify(BRIDGE)}, "mcp"]\n` : `\n[mcp_servers.${NAME}]\nurl = "${URL_}"\nhttp_headers = { Authorization = "Bearer ${TOKEN}" }\n` },
189
+ { key: "codex", label: "Codex CLI", present: () => existsSync(join(home, ".codex")), file: join(home, ".codex", "config.toml"), shape: "toml", block: BRIDGE ? `\n[mcp_servers.${NAME}]\ncommand = ${JSON.stringify(NODE)}\nargs = [${[...NODE_ARGS, BRIDGE, "mcp"].map(arg => JSON.stringify(arg)).join(", ")}]\n` : `\n[mcp_servers.${NAME}]\nurl = "${URL_}"\nhttp_headers = { Authorization = "Bearer ${TOKEN}" }\n` },
188
190
  { key: "gemini", label: "Gemini CLI", present: () => existsSync(join(home, ".gemini")), file: join(home, ".gemini", "settings.json"), shape: "json", root: "mcpServers", entry: BRIDGE ? stdio : { httpUrl: URL_, headers: { Authorization: `Bearer ${TOKEN}` } } },
189
191
  { key: "copilot", label: "VS Code (Copilot agent mode)", present: () => existsSync(vscodeUser), file: join(vscodeUser, "mcp.json"), shape: "json", root: "servers", entry: BRIDGE ? { type: "stdio", ...stdio } : { type: "http", url: URL_, headers: { Authorization: `Bearer ${TOKEN}` } } },
190
192
  { key: "windsurf", label: "Windsurf", present: () => existsSync(join(home, ".codeium", "windsurf")), file: join(home, ".codeium", "windsurf", "mcp_config.json"), shape: "json", root: "mcpServers", entry: BRIDGE ? stdio : { serverUrl: URL_, headers: { Authorization: `Bearer ${TOKEN}` } } },
191
193
  // MISTRAL VIBE (2026-10-04, docs.mistral.ai/vibe/code/cli/mcp-servers): `[[mcp_servers]]` tables in
192
194
  // ~/.vibe/config.toml (or $VIBE_HOME), each with a name, a transport and a url or a command.
193
- { key: "vibe", label: "Mistral Vibe", present: () => existsSync(VIBE_DIR), file: join(VIBE_DIR, "config.toml"), shape: "vibe", block: BRIDGE ? `\n[[mcp_servers]]\nname = "${NAME}"\ntransport = "stdio"\ncommand = ${JSON.stringify(NODE)}\nargs = [${JSON.stringify(BRIDGE)}, "mcp"]\n` : `\n[[mcp_servers]]\nname = "${NAME}"\ntransport = "streamable-http"\nurl = "${URL_}"\nheaders = { "Authorization" = "Bearer ${TOKEN}" }\n` },
195
+ { key: "vibe", label: "Mistral Vibe", present: () => existsSync(VIBE_DIR), file: join(VIBE_DIR, "config.toml"), shape: "vibe", block: BRIDGE ? `\n[[mcp_servers]]\nname = "${NAME}"\ntransport = "stdio"\ncommand = ${JSON.stringify(NODE)}\nargs = [${[...NODE_ARGS, BRIDGE, "mcp"].map(arg => JSON.stringify(arg)).join(", ")}]\n` : `\n[[mcp_servers]]\nname = "${NAME}"\ntransport = "streamable-http"\nurl = "${URL_}"\nheaders = { "Authorization" = "Bearer ${TOKEN}" }\n` },
194
196
  // GOOGLE ANTIGRAVITY (2026-10-04, antigravity.google/docs/mcp/): the 2.0 app, the `agy` CLI and the IDE read
195
197
  // ~/.gemini/config/mcp_config.json; a remote server is `serverUrl` with headers (`url` and `httpUrl` are not
196
198
  // read), a local one `command` and `args`. Present when its config folder or one of its data folders is here.
197
199
  { key: "antigravity", label: "Antigravity", present: () => existsSync(join(home, ".gemini", "config")) || (() => { try { return readdirSync(join(home, ".gemini")).some((name) => /^antigravity/.test(name)); } catch { return false; } })(), file: join(home, ".gemini", "config", "mcp_config.json"), shape: "json", root: "mcpServers", entry: BRIDGE ? stdio : { serverUrl: URL_, headers: { Authorization: `Bearer ${TOKEN}` } } },
198
200
  // GROK BUILD (2026-10-04, docs.x.ai/build/settings/reference): `[mcp_servers.<name>]` in ~/.grok/config.toml (or
199
201
  // $GROK_HOME), `url` and `headers` for a remote server, `command` and `args` for a local one.
200
- { key: "grok", label: "Grok Build", present: () => existsSync(GROK_DIR), file: join(GROK_DIR, "config.toml"), shape: "toml", block: BRIDGE ? `\n[mcp_servers.${NAME}]\ncommand = ${JSON.stringify(NODE)}\nargs = [${JSON.stringify(BRIDGE)}, "mcp"]\n` : `\n[mcp_servers.${NAME}]\nurl = "${URL_}"\nheaders = { Authorization = "Bearer ${TOKEN}" }\n` },
202
+ { key: "grok", label: "Grok Build", present: () => existsSync(GROK_DIR), file: join(GROK_DIR, "config.toml"), shape: "toml", block: BRIDGE ? `\n[mcp_servers.${NAME}]\ncommand = ${JSON.stringify(NODE)}\nargs = [${[...NODE_ARGS, BRIDGE, "mcp"].map(arg => JSON.stringify(arg)).join(", ")}]\n` : `\n[mcp_servers.${NAME}]\nurl = "${URL_}"\nheaders = { Authorization = "Bearer ${TOKEN}" }\n` },
201
203
  // ZED (zed.dev/docs/ai/mcp): `context_servers` in its settings.json, `url` and `headers` for a remote server.
202
204
  { key: "zed", label: "Zed", present: () => existsSync(ZED_DIR), file: join(ZED_DIR, "settings.json"), shape: "json", root: "context_servers", entry: BRIDGE ? { ...stdio, env: {} } : { url: URL_, headers: { Authorization: `Bearer ${TOKEN}` } } },
203
205
  // CLINE (docs.cline.bot/mcp): `mcpServers` in the extension's cline_mcp_settings.json; `type` must be
@@ -205,7 +207,7 @@ const CLIENTS = [
205
207
  { key: "cline", label: "Cline (VS Code)", present: () => existsSync(CLINE_DIR), file: join(CLINE_DIR, "cline_mcp_settings.json"), shape: "json", root: "mcpServers", entry: BRIDGE ? { ...stdio, disabled: false } : { type: "streamableHttp", url: URL_, headers: { Authorization: `Bearer ${TOKEN}` }, disabled: false } },
206
208
  ...hermesHomes().map((dir) => ({ key: "hermes", label: dir === HERMES_BASE ? "Hermes Agent" : `Hermes Agent (${dir.split(/[\\/]/).pop()})`, present: () => true, file: join(dir, "config.yaml"), shape: "yaml", root: "mcp_servers", server: HERMES_SERVER, hook: { path: ["hooks", "on_session_end"], unit: [`- command: ${JSON.stringify(HERMES_HOOK)}`, " timeout: 30"], note: "an on_session_end hook (Hermes asks once before it runs it)" } })),
207
209
  ...gooseDirs().map((dir) => ({ key: "goose", label: "Goose", present: () => true, file: join(dir, "config.yaml"), shape: "yaml", root: "extensions", server: GOOSE_SERVER, plugin: true })),
208
- { key: "opencode", label: "OpenCode", present: () => existsSync(OPENCODE_DIR), file: OPENCODE_FILE, shape: "json", root: "mcp", entry: BRIDGE ? { type: "local", command: [NODE, BRIDGE, "mcp"], enabled: true } : { type: "remote", url: URL_, headers: { Authorization: `Bearer ${TOKEN}` }, enabled: true }, plugin: "opencode" },
210
+ { key: "opencode", label: "OpenCode", present: () => existsSync(OPENCODE_DIR), file: OPENCODE_FILE, shape: "json", root: "mcp", entry: BRIDGE ? { type: "local", command: [NODE, ...NODE_ARGS, BRIDGE, "mcp"], enabled: true } : { type: "remote", url: URL_, headers: { Authorization: `Bearer ${TOKEN}` }, enabled: true }, plugin: "opencode" },
209
211
  { key: "openclaw", label: "OpenClaw", present: () => existsSync(dirname(OPENCLAW_FILE)) || onPath("openclaw"), file: OPENCLAW_FILE, shape: "openclaw" },
210
212
  { key: "claude", label: "Claude Code", present: () => existsSync(join(home, ".claude.json")), file: join(home, ".claude.json"), shape: "claude" },
211
213
  ];
@@ -233,8 +235,8 @@ for (const client of CLIENTS) {
233
235
  // the verb when the `claude` command is on this machine (2026-09-28; before, the line was only
234
236
  // printed, and a person who had just run one command was handed a second to type), and prints
235
237
  // it when the command is not. User scope, so the coupling holds in every folder on this machine.
236
- const claudeArgs = REMOVE ? ["mcp", "remove", "-s", "user", NAME] : BRIDGE ? ["mcp", "add", "-s", "user", NAME, "--", NODE, BRIDGE, "mcp"] : ["mcp", "add", "--transport", "http", "-s", "user", NAME, URL_, "-H", `Authorization: Bearer ${TOKEN}`];
237
- const shown = REMOVE ? `claude mcp remove -s user ${NAME}` : BRIDGE ? `claude mcp add -s user ${NAME} -- "${NODE}" "${BRIDGE}" mcp` : `claude mcp add --transport http -s user ${NAME} "${URL_}" -H "Authorization: Bearer <token>"`;
238
+ const claudeArgs = REMOVE ? ["mcp", "remove", "-s", "user", NAME] : BRIDGE ? ["mcp", "add", "-s", "user", NAME, "--", NODE, ...NODE_ARGS, BRIDGE, "mcp"] : ["mcp", "add", "--transport", "http", "-s", "user", NAME, URL_, "-H", `Authorization: Bearer ${TOKEN}`];
239
+ const shown = REMOVE ? `claude mcp remove -s user ${NAME}` : BRIDGE ? `claude mcp add -s user ${NAME} -- ${NODE_COMMAND} "${BRIDGE}" mcp` : `claude mcp add --transport http -s user ${NAME} "${URL_}" -H "Authorization: Bearer <token>"`;
238
240
  const direct = directClaudeEntries();
239
241
  if (!REMOVE && (BRIDGE ? direct.bridged && direct.entries.length === 0 : discovered)) { console.log(` ✓ ${client.label}: already coupled`); standing += 1; continue; }
240
242
  // A direct entry under any name is replaced by the bridge, and every one goes on removal.
@@ -255,7 +257,7 @@ for (const client of CLIENTS) {
255
257
  }
256
258
  const text = existsSync(client.file) ? readFileSync(client.file, "utf8") : "";
257
259
  // With the bridge, coupled means the bridge is in AND no entry with a key in it is left beside it.
258
- const already = client.shape === "yaml" && !REMOVE ? (BRIDGE !== undefined ? text.includes(JSON.stringify(BRIDGE)) && (!client.plugin || goosePluginStands()) : text.includes(URL_)) && yamlConfig(client, text, false) === text : REMOVE ? text.includes(URL_) || /worktrust\.mjs/.test(text) : BRIDGE !== undefined ? text.includes(JSON.stringify(BRIDGE).slice(1, -1)) && !text.includes(URL_) : text.includes(URL_);
260
+ const already = client.shape === "yaml" && !REMOVE ? (BRIDGE !== undefined ? text.includes(JSON.stringify(BRIDGE)) && (!client.plugin || goosePluginStands()) : text.includes(URL_)) && yamlConfig(client, text, false) === text : REMOVE ? text.includes(URL_) || /worktrust(?:-launch)?\.(?:mjs|py)/.test(text) : BRIDGE !== undefined ? text.includes(JSON.stringify(BRIDGE).slice(1, -1)) && !text.includes(URL_) : text.includes(URL_);
259
261
  // THE WAY OUT, ON THE MACHINE. Uncoupling in the app ends the TOKEN; the config that names the
260
262
  // door stays behind on every client here, so the next person to read this file believes the
261
263
  // machine is coupled. `--remove` takes the entry out; the account side is a separate act and
@@ -268,7 +270,7 @@ for (const client of CLIENTS) {
268
270
  try { config = JSON.parse(readFileSync(client.file, "utf8")); } catch { console.log(` ! ${client.label}: ${client.file} is not plain JSON; take the "${NAME}" entry out by hand`); continue; }
269
271
  const root = config[client.root] ?? {};
270
272
  for (const [key, entry] of Object.entries(root)) {
271
- const named = JSON.stringify(entry ?? {}).includes(URL_) || /worktrust\.mjs/.test(JSON.stringify(entry ?? {}));
273
+ const named = JSON.stringify(entry ?? {}).includes(URL_) || /worktrust(?:-launch)?\.(?:mjs|py)/.test(JSON.stringify(entry ?? {}));
272
274
  if (key === NAME || named) delete root[key];
273
275
  }
274
276
  config[client.root] = root;
@@ -282,7 +284,7 @@ for (const client of CLIENTS) {
282
284
  // Vibe's servers are an ARRAY of tables, so a block is found by what it says, not by its header: every
283
285
  // `[[mcp_servers]]` that names ours, the door, or the bridge goes, up to the next header at a line start.
284
286
  const text = readFileSync(client.file, "utf8");
285
- const stripped = text.replace(/\n?\[\[mcp_servers\]\][\s\S]*?(?=\n\[|$)/g, (block) => (block.includes(`name = "${NAME}"`) || block.includes(URL_) || /worktrust\.mjs/.test(block) ? "" : block));
287
+ const stripped = text.replace(/\n?\[\[mcp_servers\]\][\s\S]*?(?=\n\[|$)/g, (block) => (block.includes(`name = "${NAME}"`) || block.includes(URL_) || /worktrust(?:-launch)?\.(?:mjs|py)/.test(block) ? "" : block));
286
288
  console.log(` − ${client.label}: ${WRITE ? "removed from" : "would remove from"} ${client.file}`);
287
289
  if (WRITE) writeFileSync(client.file, stripped);
288
290
  } else if (client.shape === "toml") {
@@ -291,7 +293,7 @@ for (const client of CLIENTS) {
291
293
  // Every block that names the door, under any name (a hand-made one too, 2026-10-04), or ours.
292
294
  // A block runs to the next table header at the START of a line, never to the next "[" — the
293
295
  // bridge's own `args = ["…", "mcp"]` holds one, and cutting there left half a block behind.
294
- const stripped = text.replace(/\n?\[mcp_servers\.("?)([A-Za-z0-9_.-]+)\1\][\s\S]*?(?=\n\[|$)/g, (block, _q, name) => (name === NAME || block.includes(URL_) || /worktrust\.mjs/.test(block) ? "" : block));
296
+ const stripped = text.replace(/\n?\[mcp_servers\.("?)([A-Za-z0-9_.-]+)\1\][\s\S]*?(?=\n\[|$)/g, (block, _q, name) => (name === NAME || block.includes(URL_) || /worktrust(?:-launch)?\.(?:mjs|py)/.test(block) ? "" : block));
295
297
  console.log(` − ${client.label}: ${WRITE ? "removed from" : "would remove from"} ${client.file}`);
296
298
  if (WRITE) writeFileSync(client.file, stripped);
297
299
  }