worktrust 0.10.23 → 0.10.25

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
@@ -1,5 +1,19 @@
1
1
  # worktrust
2
2
 
3
+ ## Candidate 0.10.24: delivery and account limits
4
+
5
+ Not published yet. After an approved update, WorkTrust receives the running version without
6
+ an activity upload. Pending metadata batches can be resumed with `worktrust history --resume`,
7
+ even after an AI app removed the original session files. Review-held revisions need review;
8
+ reconnecting does not approve them. Keep archives for work that was never queued.
9
+
10
+ The corresponding server candidate limits new personal registrations to five active device
11
+ identities. AI apps sharing one key share one slot; cloned keys share account upload capacity.
12
+ Retiring a device preserves earlier data. Existing accounts above the limit are preserved but
13
+ cannot add another identity. Version labels and device signatures are not independent evidence
14
+ of time or correctness. A CLI update does not automatically publish a passport.
15
+
16
+
3
17
  Couple a computer to [WorkTrust](https://worktrust.io) in one command. WorkTrust keeps a verified
4
18
  record of the work you do with AI without anyone reading that work: it receives metadata only.
5
19
 
@@ -496,3 +510,10 @@ claim eligibility remains the server publication gate's responsibility.
496
510
  Revoking a computer key stops new submissions, not the validity of every historical publication.
497
511
  Passport withdrawal is a separate audited operation. Neither operation automatically erases the
498
512
  person's prior data. Release signing keys, computer keys and passport signing keys are separate.
513
+
514
+ In 0.10.25, hooks and helper processes from the official launcher stay inside the checked
515
+ release. The old loose `~/.worktrust/count-behaviour.mjs` and individual-script download
516
+ fallbacks are no longer executed. Persistent Python hooks use the host Python to check the
517
+ copied Node runtime before starting it, even after the temporary uvx/pipx cache is removed.
518
+ Keep that host Python installed. Updating preserves credentials, pending uploads and archives;
519
+ it does not approve held history or publish a passport automatically.
package/SECURITY.md CHANGED
@@ -9,11 +9,11 @@ private transcripts or account data in a public issue.
9
9
 
10
10
  - Setup changes client configuration and local coupling files; preservation can change retention
11
11
  settings and create or append archives. See the README for the paths and individual options.
12
- A setup dry run is not a sandbox for the whole invocation: the standalone bootstrap can download
13
- scripts first, and the interactive entry can check for a newer release.
12
+ The complete official release is required. Individual script download fallbacks are removed;
13
+ interactive commands may check for a newer release.
14
14
  - Submissions go to the configured WorkTrust MCP endpoint. Interactive commands can also contact
15
- the npm registry for a version notice. The unpublished patch based on 0.10.21 no longer executes a newer version from that notice. The npm package bundles its runtime
16
- modules, but installation and automatic relay still use the network. `preserve` itself is local.
15
+ the npm registry for a version notice. Release notices never execute a different version. The npm package bundles its runtime
16
+ modules, but package-manager installation and explicit upgrades still use the network. `preserve` itself is local.
17
17
  A custom `--origin`, URL or registry override changes whom you trust.
18
18
  - The key it receives is a WorkTrust coupling for this computer: it can submit work metadata to your
19
19
  record and cannot read your record back. Revoke it in WorkTrust at any time.
@@ -131,3 +131,23 @@ selection and consent. It is not an automatic SDK upload or an MCP submission. D
131
131
  recording does not erase a separately imported copy; delete that copy through the private app.
132
132
  See the service [privacy policy](https://worktrust.io/privacy) and
133
133
  [support](https://worktrust.io/support) for account data requests.
134
+
135
+ ## Execution boundary in 0.10.25
136
+
137
+ The official launcher starts helpers from its checked release, never a loose counter, hook or
138
+ reader in `~/.worktrust`. Its helper processes re-enter the launcher and its manifest check.
139
+ A missing or changed release is refused with an instruction to reinstall; it is not repaired
140
+ by downloading individual scripts. Earlier loose files may remain for recovery but are not
141
+ used as executable fallbacks.
142
+
143
+ Python's persistent installation now starts with the package manager's host Python in isolated
144
+ mode. A standard-library bootstrap checks the copied Node binary and engine before Node
145
+ executes, against hashes authenticated during installation. It does not trust a rewritten local
146
+ `runtime.json` or `installation.json` to authorize changes. The initial Python package still
147
+ verifies its publisher signature before installation. The host Python must remain available.
148
+
149
+ Bootstrap files, host interpreters, client configuration and processes running as the owner
150
+ remain trust boundaries. Replacing the bootstrap or racing file changes after a check cannot
151
+ be prevented by self-verification on an owner-controlled computer. Generated Claude/OpenCode
152
+ client plugins and user transcript/SDK inputs are not remote attestation. Server claim and
153
+ publication gates remain necessary; a matching client hash never proves truthful activity.
@@ -1 +1 @@
1
- {"keyId":"608168ccdef72562fc91f9c0f9f2c2d6876bece7f7362cb545b818f7947da6b5","payload":{"files":{"chat-exports.mjs":"04eafe333940ec03d5058d8d51062124aa12ab882bf04db03bcda5613ec69298","claude-mod.mjs":"02d86b0cdddf39879efc5194c0a5be6b41456faedec28963dc123a4e88dc3942","config-edits.mjs":"0eba2f176ef6f7afba071d6e00de0ff19ba2b283180a801dfd957aa38c1edd94","count-behaviour.mjs":"1beaec2a4d0aead76d166f89cc52441a9cf48f2e69da9888ca2091dd3a10a37b","log-session.mjs":"b99f082a58f0a92375026f52b62eb72173f06614b844e3def06b3ed40942b103","orchestration-contract.mjs":"ec08f303a166365b99e70b675de4cfe76c6156c2567e14b5569f6d992f0231b7","orchestration-evidence.mjs":"d0d06cecf0eb08e5c6e653c62a4f45b1eddf2119c2acb8341056b34f488d214a","orchestration-report.mjs":"d4e0a9ad8e4a01b462d22c6b1866aac291565c533ff476085d3367cb6d59bc1b","package-integrity.mjs":"b9d81dc88cf5c19ccfbf334a7af84a0c4e299a0e9e4d4091132253e22f855dc3","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":"b563a702634b41c064fdd0b6ad842c77ff851dfcf682b370c677114f8f75c061"},"format":"worktrust-package/1","kind":"engine","version":"0.10.23"},"signature":"g-Lbodi3WAsZnCC1kW05ecOXhxXCNgSITU67By6g3zJMQB5T7ksGWIO5FIP1d1Yf3IP5PlCyMTiJjm0C__8wCg"}
1
+ {"keyId":"608168ccdef72562fc91f9c0f9f2c2d6876bece7f7362cb545b818f7947da6b5","payload":{"files":{"chat-exports.mjs":"04eafe333940ec03d5058d8d51062124aa12ab882bf04db03bcda5613ec69298","claude-mod.mjs":"02d86b0cdddf39879efc5194c0a5be6b41456faedec28963dc123a4e88dc3942","config-edits.mjs":"0eba2f176ef6f7afba071d6e00de0ff19ba2b283180a801dfd957aa38c1edd94","count-behaviour.mjs":"1beaec2a4d0aead76d166f89cc52441a9cf48f2e69da9888ca2091dd3a10a37b","history-outbox.mjs":"1bdca17b807c76e4a8e7bf42c6f07e12e8ae8e4466417cafdd26b1f58bf178a5","log-session.mjs":"c5e6e4d44a85768f21c25945b8630f31306ec2665193886870c1010ef6bf3c26","orchestration-contract.mjs":"ec08f303a166365b99e70b675de4cfe76c6156c2567e14b5569f6d992f0231b7","orchestration-evidence.mjs":"d0d06cecf0eb08e5c6e653c62a4f45b1eddf2119c2acb8341056b34f488d214a","orchestration-report.mjs":"d4e0a9ad8e4a01b462d22c6b1866aac291565c533ff476085d3367cb6d59bc1b","package-integrity.mjs":"a8210c9494a56bfb9a5ea3d10064c7a269f0b6330c0af7c0700e706c3c0224e3","preserve-lines.mjs":"2df64a69687aa51219bf7b86b88d175cc50990fa29574b31897e41a9ebeecf43","preserve-summary.mjs":"137f781ed7021596a3f0ea67afcf2ab8616ac293f833dbb8f176e838e0ed8321","preserve.mjs":"9add279352750be94d94873738145e379819d793c20c6c6503219969608e2c2f","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":"bd208923c08a16ed640f25417ae381d0c3e3dda02e56aad4aee66497cdd494b9"},"format":"worktrust-package/1","kind":"engine","version":"0.10.25"},"signature":"3nt9U84E4YOoRtRh-5jp8WJcJVzCafdMYgFiI0WPhK2_OGYHnFAlD2mJYYYuO_8_Utrwh_41AQKHqYbNqJ7BAQ"}
@@ -0,0 +1,93 @@
1
+ /** Local metadata queue. Never reads transcripts, credentials or the network; preserve does not load it. */
2
+ import {createHash,randomBytes} from 'node:crypto';
3
+ import {existsSync,lstatSync,mkdirSync,readdirSync,readFileSync,openSync,writeFileSync,fsyncSync,closeSync,renameSync,unlinkSync,constants} from 'node:fs';
4
+ import {join} from 'node:path';
5
+ import {homedir} from 'node:os';
6
+ const MAX_RETRY_SECONDS=24*60*60;
7
+ const digest=s=>createHash('sha256').update(s).digest('hex');
8
+ const scopeOf=target=>digest(target.url+'\0'+(target.token===process.env.WORKTRUST_MCP_TOKEN && /^[a-f0-9]{64}$/.test(process.env.WORKTRUST_HISTORY_SCOPE??'') ? 'device:'+process.env.WORKTRUST_HISTORY_SCOPE : 'token:'+target.token));
9
+ const regular=p=>{const s=lstatSync(p);if(s.isSymbolicLink()||!s.isFile())throw Error('HISTORY_QUEUE_UNSAFE');return s;};
10
+ function directory(p) {if(!existsSync(p))mkdirSync(p,{mode:0o700});const s=lstatSync(p);if(s.isSymbolicLink()||!s.isDirectory())throw Error('HISTORY_QUEUE_UNSAFE');}
11
+ function write(p,value) {
12
+ const temporary=p+'.'+randomBytes(8).toString('hex')+'.tmp';
13
+ const fd=openSync(temporary,constants.O_CREAT|constants.O_EXCL|constants.O_WRONLY|(constants.O_NOFOLLOW??0),0o600);
14
+ try {writeFileSync(fd,JSON.stringify(value));fsyncSync(fd);}finally{closeSync(fd);}
15
+ try {if(existsSync(p))regular(p);renameSync(temporary,p);}finally{if(existsSync(temporary))unlinkSync(temporary);}
16
+ }
17
+ /** Serialize local space reservations; never wait in a hook for another process. */
18
+ function reservation(root,run) {
19
+ const path=join(root,'.reservation');let fd;
20
+ try {fd=openSync(path,constants.O_CREAT|constants.O_EXCL|constants.O_WRONLY,0o600);}
21
+ catch(error) {
22
+ if(error.code!=='EEXIST')throw error;
23
+ const lock=read(path),before=regular(path);
24
+ if(!Number.isSafeInteger(lock?.pid)||lock.pid<=0)throw Error('HISTORY_QUEUE_BUSY');
25
+ try{process.kill(lock.pid,0);throw Error('HISTORY_QUEUE_BUSY');}
26
+ catch(error){if(error.code!=='ESRCH')throw Error('HISTORY_QUEUE_BUSY');}
27
+ if(regular(path).ino!==before.ino)throw Error('HISTORY_QUEUE_BUSY');
28
+ unlinkSync(path);return reservation(root,run);
29
+ }
30
+ try{writeFileSync(fd,JSON.stringify({pid:process.pid}));fsyncSync(fd);return run();}
31
+ finally{closeSync(fd);unlinkSync(path);}
32
+ }
33
+ function read(p) {if(!existsSync(p))return null;if(regular(p).size>4_500_000)throw Error('HISTORY_QUEUE_UNSAFE');return JSON.parse(readFileSync(p,'utf8'));}
34
+ export function queuedHistory(target,body,source) {
35
+ const home=join(homedir(),'.worktrust');directory(home);
36
+ const root=join(home,'history-outbox');directory(root);
37
+ // No bearer, endpoint, local path or user content is stored as an identifier.
38
+ const scope=scopeOf(target),id=digest(scope+'\0'+source+'\0'+body);
39
+ const request=join(root,id+'.request.json'),ack=join(root,id+'.ack.json'),state=join(root,id+'.state.json');
40
+ const acknowledged=read(ack);
41
+ if(acknowledged?.id===id)return {status:'acknowledged',confirm(){},defer(){}};
42
+ const current=read(state);
43
+ reservation(root,()=>{
44
+ if(!existsSync(request)) {
45
+ const files=readdirSync(root);let bytes=0,pending=0;
46
+ for(const file of files) {const stat=regular(join(root,file));bytes+=stat.size;if(file.endsWith('.request.json'))pending++;}
47
+ if(files.length>=12000||pending>=512||bytes+Buffer.byteLength(JSON.stringify({id,scope,source,body}))+1024>64*1024*1024)throw Error('HISTORY_QUEUE_FULL');
48
+ write(request,{id,scope,source,body});
49
+ } else if(read(request)?.body!==body)throw Error('HISTORY_QUEUE_CHANGED');
50
+ });
51
+ const status=current?.status==='review'?'review':Number(current?.retryAt)>Date.now()?'waiting':'pending';
52
+ return {status,retryAt:current?.retryAt??null,
53
+ confirm(){write(ack,{id,confirmedAt:new Date().toISOString()});if(existsSync(request)){regular(request);unlinkSync(request);}if(existsSync(state)){regular(state);unlinkSync(state);}},
54
+ defer(reason,seconds=0){if(existsSync(ack))return;write(state,{id,status:reason==='review'?'review':'retry',retryAt:Date.now()+Math.max(0,Math.min(MAX_RETRY_SECONDS,seconds))*1000});},
55
+ };
56
+ }
57
+ export function historyRefusal(text,response) {
58
+ let rpc;
59
+ try {rpc=JSON.parse(text.trim().startsWith('{')?text:text.split(/\r?\n/).find(s=>s.startsWith('data:'))?.slice(5));}catch{/* Unknown reply stays retryable, never acknowledged. */}
60
+ const review=rpc?.id===1 && (rpc?.error?.data?.outcome==='review' || String(rpc?.error?.message??'').startsWith('history replacement held for review:'));
61
+ const raw=Number(response.headers.get('retry-after'));
62
+ return {reason:review?'review':response.status===429?'capacity':'unconfirmed',seconds:Number.isFinite(raw)&&raw>0?Math.min(MAX_RETRY_SECONDS,raw):0};
63
+ }
64
+
65
+ /** Explicit recovery, even after the AI client removed its source files. A changed account/key
66
+ * cannot replay another coupling's pending data. Review is retried only on an explicit request. */
67
+ export async function resumeHistory(target, {send, confirmed, note, retryReview=false, dry=false}) {
68
+ const root=join(homedir(),'.worktrust','history-outbox'),scope=scopeOf(target);
69
+ const totals={received:0,review:0,waiting:0,batches:0};let paused=null;
70
+ if(!existsSync(root))return totals;
71
+ directory(root);
72
+ const files=readdirSync(root);if(files.length>12000)throw Error('HISTORY_QUEUE_FULL');
73
+ for(const file of files.sort()) {
74
+ if(!/^[a-f0-9]{64}\.request\.json$/.test(file))continue;
75
+ const item=read(join(root,file));if(item?.scope!==scope)continue;
76
+ if(typeof item.body!=='string'||typeof item.source!=='string'||item.id!==digest(scope+'\0'+item.source+'\0'+item.body)||file!==item.id+'.request.json')throw Error('HISTORY_QUEUE_CHANGED');
77
+ const rpc=JSON.parse(item.body),entries=rpc?.params?.arguments?.entries;
78
+ if(rpc.jsonrpc!=='2.0'||rpc.id!==1||rpc.method!=='tools/call'||rpc.params.name!=='import_history'||!Array.isArray(entries)||!entries.length||entries.length>200)throw Error('HISTORY_QUEUE_CHANGED');
79
+ const queued=queuedHistory(target,item.body,item.source);totals.batches++;
80
+ if(queued.status==='acknowledged')continue;
81
+ if(queued.status==='review'&&!retryReview){totals.review+=entries.length;continue;}
82
+ if(dry){totals.waiting+=entries.length;continue;}
83
+ if(queued.status==='waiting'&&!paused)paused={reason:'unconfirmed',seconds:Math.max(1,Math.ceil((queued.retryAt-Date.now())/1000))};
84
+ if(paused){if(queued.status==='review'){totals.review+=entries.length;continue;}queued.defer(paused.reason,paused.seconds);totals.waiting+=entries.length;continue;}
85
+ try {
86
+ const response=await send(item.body,item.source),text=await response.text();
87
+ try{if(!response.ok)throw Error();confirmed(text,entries.length);}
88
+ catch{const refusal=historyRefusal(text,response);if(refusal.reason!=='review')paused={reason:refusal.reason,seconds:refusal.seconds>0?refusal.seconds:5};queued.defer(refusal.reason,paused?.seconds??refusal.seconds);totals[refusal.reason==='review'?'review':'waiting']+=entries.length;continue;}
89
+ queued.confirm();totals.received+=entries.length;note(text);
90
+ }catch{paused={reason:'unconfirmed',seconds:5};queued.defer(paused.reason,paused.seconds);totals.waiting+=entries.length;}
91
+ }
92
+ return totals;
93
+ }
package/log-session.mjs CHANGED
@@ -60,12 +60,14 @@
60
60
  * honoured here too, matched against the transcript's project directory, before a file is read.
61
61
  */
62
62
  import { execFileSync, spawn, spawnSync } from "node:child_process";
63
- import { copyFileSync, existsSync, mkdirSync, readFileSync, readdirSync, rmSync, statSync, writeFileSync, lstatSync, openSync, closeSync, fsyncSync, linkSync, unlinkSync, constants } from "node:fs";
63
+ import { existsSync, mkdirSync, readFileSync, readdirSync, rmSync, statSync, writeFileSync, lstatSync, openSync, closeSync, fsyncSync, linkSync, unlinkSync, constants } from "node:fs";
64
64
  import { homedir } from "node:os";
65
65
  import { dirname, join, resolve, sep } from "node:path";
66
66
  import { fileURLToPath } from "node:url";
67
67
  import { createHash, createPrivateKey, createPublicKey, randomBytes, sign as cryptoSign } from "node:crypto";
68
68
 
69
+ import { moduleArgs, moduleExecutable } from "./package-integrity.mjs";
70
+
69
71
  async function main() {
70
72
  const args = process.argv.slice(2), NODE_FLAGS = process.versions.node === "26.5.0" ? ["--no-concurrent-sparkplug"] : [];
71
73
  const flag = (name) => args.includes(`--${name}`), value = (name) => { const i = args.indexOf(`--${name}`); return i >= 0 ? args[i + 1] : undefined; }, DRY = flag("dry-run");
@@ -83,37 +85,13 @@ const exitFlushed = (code) => new Promise((resolve) => process.stdout.write("",
83
85
  * may stage, only the owner may count — and a hook that could send counts by itself would put an
84
86
  * automatic writer on the one surface that describes how a person thinks.
85
87
  */
86
- const COUNTER = join(homedir(), ".worktrust", "count-behaviour.mjs");
87
- /** PINNED (2026-10-03): from the npm package, the counter is the package's copy, never refreshed from the network. */
88
+ const RELEASE_DIR = dirname(fileURLToPath(import.meta.url));
89
+ const COUNTER = join(RELEASE_DIR, "count-behaviour.mjs");
90
+ /** Legacy marker, used only when the person explicitly purges the old installation. */
88
91
  const PINNED = join(homedir(), ".worktrust", "pinned");
89
92
  /** A hook command is ours when it runs this file, or the `worktrust hook` wrapper that hands it the key from the key file. */
90
- const ours = (command) => /log-session|worktrust\.mjs" hook|worktrust\.mjs hook/.test(String(command ?? ""));
93
+ const ours = (command) => /log-session|worktrust(?:-launch)?\.(?:mjs|py)" (?:hook|--internal-module)|worktrust(?:-launch)?\.(?:mjs|py) hook/.test(String(command ?? ""));
91
94
  const COUNTER_EVERY_MS = 24 * 3600_000;
92
- /**
93
- * THE COUNTER KEEPS UP WITH THE DEPLOYMENT. The install fetched it once and never again, so a
94
- * machine set up in August counted with an August rubric in September while the door already
95
- * spoke a newer vocabulary. Now the version stamped in the local copy is compared with the one the
96
- * deployment serves — numerically, the way the door picks its newest rubric — and a newer copy
97
- * replaces the old one. A rubric bump is what makes the previous reading superseded on the
98
- * mirror; this is how the machine hears about it. Nothing else is read off the network here.
99
- */
100
- const versionOf = (text) => /export const ANALYZER_VERSION = "counter@(\d+)\.(\d+)\.(\d+)"/.exec(text ?? "")?.slice(1, 4).map(Number) ?? null;
101
- const newer = (a, b) => { if (!a || !b) return false; for (let i = 0; i < 3; i += 1) { if (a[i] === b[i]) continue; return a[i] > b[i]; } return false; };
102
- async function refreshCounter(origin, announce) {
103
- if (!origin || !existsSync(COUNTER) || existsSync(PINNED)) return false;
104
- try {
105
- const response = await fetch(`${origin}/counter/count-behaviour.mjs`);
106
- if (!response.ok) return false;
107
- const remote = await response.text();
108
- const have = versionOf(readFileSync(COUNTER, "utf8")), theirs = versionOf(remote);
109
- if (!newer(theirs, have)) return false;
110
- writeFileSync(COUNTER, remote);
111
- await installReaders(origin, true);
112
- announce?.(`counter: updated to counter@${theirs.join(".")} (was counter@${have?.join(".") ?? "?"}) — the next reading counts under the new rubric`);
113
- return true;
114
- } catch { return false; }
115
- }
116
-
117
95
  /**
118
96
  * The live door refuses stretches older than two days; older work uses the history door.
119
97
  *
@@ -258,21 +236,7 @@ const { stackOfFiles = () => [], displayStackOfFiles = () => [] } = (await impor
258
236
  const EXPORT_PATHS = []; for (let i = 0; i < args.length; i += 1) if (args[i] === "--export" && args[i + 1]) EXPORT_PATHS.push(args[i + 1]);
259
237
  const DATABASE_CLIENTS = ["hermes", "goose", "opencode", "openclaw", "cursor", "copilot"]; // the registry's keys, the name each line carries
260
238
  const LIVE_SOURCE = new RegExp(`^(codex|antigravity|${DATABASE_CLIENTS.join("|")}):`); // a sweep entry's id → the client it names (every database client, 0.6.16)
261
- const READER_FILES = ["transcript-readers.mjs", "session-databases.mjs", "stretch-evidence.mjs", "chat-exports.mjs", "stack-rules.mjs", "claude-mod.mjs"]; // 0.7.4: the derived record travels with the hook; 0.10.10: the export reader; 0.10.11: the stack rules; 0.10.15: the mod
262
- /** The readers go where the hook and the counter run: copied from beside this file, else (or for a newer counter) from the deployment. */
263
- async function installReaders(origin, fromNetwork = false) {
264
- let installed = true;
265
- for (const name of READER_FILES) { // Hermes, Goose, OpenCode and OpenClaw are read by session-databases.mjs
266
- const here = join(dirname(fileURLToPath(import.meta.url)), name), home = join(homedir(), ".worktrust", name);
267
- try {
268
- if (!fromNetwork && existsSync(here)) { mkdirSync(dirname(home), { recursive: true }); if (here !== home) copyFileSync(here, home); continue; }
269
- const response = origin ? await fetch(`${origin}/counter/${name}`) : null;
270
- if (response?.ok) writeFileSync(home, await response.text()); else installed = false;
271
- } catch { installed = false; }
272
- }
273
- return installed;
274
- }
275
-
239
+ const READER_FILES = ["history-outbox.mjs", "transcript-readers.mjs", "session-databases.mjs", "stretch-evidence.mjs", "chat-exports.mjs", "stack-rules.mjs", "claude-mod.mjs"]; // 0.7.4: the derived record travels with the hook; 0.10.10: the export reader; 0.10.11: the stack rules; 0.10.15: the mod
276
240
  /** The roots this machine's transcripts live under; a test names its own. */
277
241
  const claudeRoot = () => value("transcript-root") ?? join(homedir(), ".claude", "projects");
278
242
  const codexRoot = () => { const given = value("codex-root"); if (given) return given.replace(/^~(?=\/|$)/, homedir()); return value("transcript-root") ? null : join(homedir(), ".codex", "sessions"); };
@@ -735,31 +699,44 @@ function retainMeasurement(payload, source) {
735
699
  }
736
700
  } finally { closeSync(fd); unlinkSync(temporary); }
737
701
  }
702
+ const HISTORY_DELIVERY = { review: 0, waiting: 0 };
738
703
  async function sendHistory(door, entries, announce = false, rebuild = false, named = false, { byDay = false, withdrawUnknown = false } = {}) {
739
704
  let accepted = 0;
740
- // A Codex entry goes through Codex's own coupling where one exists (see codexDoor), the rest
741
- // through the door given: the record files a line under the coupling that sent it. Antigravity's
742
- // go apart too, so their batch can name the client (clientOf).
743
- // An export's lines go as their own group too (0.10.10), so the record names the product (ChatGPT, Claude on the web).
744
- for (const [source, group] of [["claude", entries.filter((entry) => !entrySource.has(entry))], ["codex", entries.filter((entry) => entrySource.get(entry) === "codex")], ...["antigravity", ...DATABASE_CLIENTS, ...EXPORT_CLIENTS].map((client) => [client, entries.filter((entry) => entrySource.get(entry) === client)])]) {
705
+ const { queuedHistory, historyRefusal } = await import("./history-outbox.mjs");
706
+ // Keep each source and its approved coupling separate.
707
+ const groups = [["claude", entries.filter((entry) => !entrySource.has(entry))], ["codex", entries.filter((entry) => entrySource.get(entry) === "codex")], ...["antigravity", ...DATABASE_CLIENTS, ...EXPORT_CLIENTS].map((client) => [client, entries.filter((entry) => entrySource.get(entry) === client)])];
708
+ const encodeBatch = batch => JSON.stringify({ jsonrpc: "2.0", id: 1, method: "tools/call", params: { name: "import_history", arguments: { ...(rebuild ? { rebuild: true } : {}), ...(withdrawUnknown ? { withdraw_unknown: true } : {}), entries: batch.map(({commits, ...rest}) => { void commits; return rest; }) } } });
709
+ // Persist the approved plan before sending, so later batches survive removed source files too.
710
+ try { for (const [source, group] of groups) { const target = source === "codex" ? codexDoor ?? door : door; if (target) for (const batch of batchesOf(group, byDay)) queuedHistory(target, encodeBatch(batch), source); } }
711
+ catch { console.error("History queue is full, busy or unavailable. Resume the saved batches before retrying this import; nothing was marked complete."); HISTORY_DELIVERY.waiting += entries.length; return 0; }
712
+ for (const [source, group] of groups) {
745
713
  const target = source === "codex" ? codexDoor ?? door : door;
746
714
  if (group.length === 0 || !target) continue;
747
715
  let number = 0;
748
716
  for (const batch of batchesOf(group, byDay)) {
749
717
  number += 1;
750
- // History carries no shas: an imported line forms no session, and the join is the live route's. REBUILD (owner, 2026-10-07): `rebuild: true`
751
- // tells the door to replace this computer's earlier lines on the days and for the client the batch carries, and every group names its client.
752
- // WITHDRAW UNKNOWN (owner, 2026-10-10): with an export, after the person's yes, `withdraw_unknown: true` also withdraws the AI-app lines on its days.
753
- const body = JSON.stringify({ jsonrpc: "2.0", id: 1, method: "tools/call", params: { name: "import_history", arguments: { ...(rebuild ? { rebuild: true } : {}), ...(withdrawUnknown ? { withdraw_unknown: true } : {}), entries: batch.map((entry) => { const { commits, ...rest } = entry; void commits; return rest; }) } } });
718
+ // Imported entries carry no live commit/session join.
719
+ const body = encodeBatch(batch);
754
720
  for (const entry of batch) retainMeasurement(entry, source);
755
721
  // `named` (0.10.10): a copied folder's lines name their client too, so the record says which app the copy came from.
756
- const response = await fetch(target.url, { method: "POST", headers: { "content-type": "application/json", accept: "application/json, text/event-stream", authorization: `Bearer ${target.token}`, ...clientOf(source, rebuild || named), ...proofFor(target.url, body) }, body });
757
- const text = await response.text();
758
- if (announce) console.log(`batch ${number}: ${response.status} ${text.slice(0, 200).replace(/\\n/g, " ")}`);
759
- if (!response.ok) break;
760
- try { confirmedReceipt(text, batch.length); } catch { break; }
761
- accepted += batch.length;
762
- noteReceipt(text);
722
+ let queued;
723
+ try { queued = queuedHistory(target, body, source); }
724
+ catch { console.error("Pending history could not be stored safely. Nothing was marked complete; keep the local WorkTrust folder for recovery."); HISTORY_DELIVERY.waiting += batch.length; break; }
725
+ if (queued.status === "acknowledged" && !byDay) { accepted += batch.length; RECEIPTS.alreadyHeld += batch.length; continue; }
726
+ if (queued.status === "review" && !flag("retry-review")) { HISTORY_DELIVERY.review += batch.length; continue; }
727
+ if (queued.status === "waiting") { HISTORY_DELIVERY.waiting += batch.length; continue; }
728
+ try {
729
+ const response = await fetch(target.url, { method: "POST", headers: { "content-type": "application/json", accept: "application/json, text/event-stream", authorization: `Bearer ${target.token}`, ...clientOf(source, rebuild || named), ...proofFor(target.url, body) }, body, redirect: "error", signal: AbortSignal.timeout(65_000) });
730
+ const text = await response.text();
731
+ try { if (!response.ok) throw Error(); confirmedReceipt(text, batch.length); }
732
+ catch {
733
+ const refusal = historyRefusal(text, response); queued.defer(refusal.reason, refusal.seconds);
734
+ if (refusal.reason === "review") { HISTORY_DELIVERY.review += batch.length; continue; }
735
+ HISTORY_DELIVERY.waiting += batch.length; break;
736
+ }
737
+ queued.confirm(); accepted += batch.length; noteReceipt(text);
738
+ if (announce) console.log(`batch ${number}: received ${batch.length}`);
739
+ } catch { queued.defer("unconfirmed"); HISTORY_DELIVERY.waiting += batch.length; break; }
763
740
  }
764
741
  }
765
742
  return accepted;
@@ -792,7 +769,7 @@ const proofFor = (url, body) => {
792
769
  * on this computer, and the door names a coupling's clients by the user-agent it hears (mcp_identify's
793
770
  * agents_seen). An Antigravity line names Antigravity: the product name, nothing of the work.
794
771
  */
795
- const clientOf = (source, always = false) => (always || source === "antigravity" || DATABASE_CLIENTS.includes(source) || EXPORT_CLIENTS.includes(source) ? { "user-agent": `${source ?? "claude"}/hook (worktrust-hook)` } : {});
772
+ const clientOf = (source, always = false) => (CLI_VERSION_SENT || always || source === "antigravity" || DATABASE_CLIENTS.includes(source) || EXPORT_CLIENTS.includes(source) ? { "user-agent": `${source ?? "claude"}/hook (worktrust-hook)${CLI_VERSION_SENT ? ` worktrust-cli/${CLI_VERSION_SENT}` : ""}` } : {});
796
773
 
797
774
  async function send(door, payload) {
798
775
  retainMeasurement(payload, entrySource.get(payload));
@@ -1062,7 +1039,7 @@ if (flag("uninstall")) {
1062
1039
  }
1063
1040
  const removed = before !== JSON.stringify(HOOK_EVENTS.map((event) => settings.hooks?.[event] ?? []));
1064
1041
  if (removed) writeFileSync(file, JSON.stringify(settings, null, 2));
1065
- if (flag("purge")) for (const path of [COUNTER, PINNED, join(homedir(), ".worktrust", "log-session.mjs"), STATE, ...READER_FILES.map((name) => join(homedir(), ".worktrust", name)), join(homedir(), ".worktrust", "antigravity.json")]) { try { rmSync(path); } catch { /* already gone */ } }
1042
+ if (flag("purge")) for (const path of [join(homedir(), ".worktrust", "count-behaviour.mjs"), PINNED, join(homedir(), ".worktrust", "log-session.mjs"), STATE, ...READER_FILES.map((name) => join(homedir(), ".worktrust", name)), join(homedir(), ".worktrust", "antigravity.json")]) { try { rmSync(path); } catch { /* already gone */ } }
1066
1043
  console.log(`${removed ? "removed" : "nothing wired"}: ${file}${flag("purge") ? "\n purged ~/.worktrust" : ""}`);
1067
1044
  console.log("the coupling itself still exists: end it in the app (Sources → the computer's row → end this coupling)");
1068
1045
  return await exitFlushed(0);
@@ -1077,32 +1054,17 @@ if (flag("install")) {
1077
1054
  if (value("history-floor") === "now") floors.__historyFloor = now;
1078
1055
  writeState(floors);
1079
1056
  }
1080
- // Wired to SessionEnd, not to every reply: the door asks for one call per PIECE of work, and a
1081
- // hook that fired per message would report a hundred stretches for one afternoon.
1082
- //
1083
- // AND WIRED TO A PATH THAT SURVIVES. `curl -O` leaves the file wherever the terminal happened to
1084
- // be — a Downloads folder, a repository, a temp directory somebody empties on Monday — and a
1085
- // hook whose command has gone missing fails silently, which on this record is indistinguishable
1086
- // from a person who stopped working. So install copies itself to ~/.worktrust and wires that.
1087
- const home = join(homedir(), ".worktrust", "log-session.mjs");
1088
- const self = process.argv[1];
1089
- // The copy that runs is refreshed from the file you ran — and SAYS so, because "already installed —
1090
- // nothing changed" after a newer download read as "your hook is old" to the person who had just updated it.
1091
- let hookRefreshed = false;
1092
- if (self !== home) {
1093
- const next = readFileSync(self, "utf8");
1094
- const current = existsSync(home) ? readFileSync(home, "utf8") : null;
1095
- mkdirSync(dirname(home), { recursive: true });
1096
- if (current !== next) { writeFileSync(home, next); hookRefreshed = current !== null; }
1057
+ // Only complete, verified releases may be installed. Old loose scripts are never copied or fetched.
1058
+ const home = join(RELEASE_DIR, "log-session.mjs");
1059
+ let via = value("via");
1060
+ if (!via) {
1061
+ const { installSignedPackage } = await import("./package-integrity.mjs");
1062
+ via = installSignedPackage(RELEASE_DIR, join(homedir(), ".worktrust"));
1097
1063
  }
1098
- // A counter handed over by the package (`--counter <path>`) is copied and pinned: nothing below fetches one.
1099
- const given = args.indexOf("--counter") >= 0 ? args[args.indexOf("--counter") + 1] : null;
1100
- if (given) { mkdirSync(dirname(COUNTER), { recursive: true }); writeFileSync(COUNTER, readFileSync(given, "utf8")); writeFileSync(PINNED, "the counter comes with the worktrust package; it is not refreshed from the network\n"); console.log(`counter: ${COUNTER} — from the package, pinned`); }
1101
1064
  const file = join(homedir(), ".claude", "settings.json");
1102
1065
  const settings = existsSync(file) ? JSON.parse(readFileSync(file, "utf8")) : {};
1103
- // `--via <worktrust.mjs>`: the key lives in ~/.worktrust/key.json, so Claude Code runs the wrapper, which reads it and starts this hook.
1104
- const via = args.indexOf("--via") >= 0 ? args[args.indexOf("--via") + 1] : null;
1105
- const command = `"${process.env.WORKTRUST_NODE || process.execPath}" "${via ?? home}"${via ? " hook" : ""}`;
1066
+ const direct = flag("direct");
1067
+ const command = `"${process.env.WORKTRUST_NODE || process.execPath}"${process.env.WORKTRUST_NODE_ARGS === '["-I"]' ? " -I" : ""} "${via}"${direct ? " --internal-module log-session.mjs" : " hook"}`;
1106
1068
  settings.hooks ??= {};
1107
1069
  for (const event of HOOK_EVENTS) settings.hooks[event] ??= [];
1108
1070
  // A WIRING THAT POINTS SOMEWHERE ELSE IS REPAIRED, NOT LEFT. An earlier install wired whatever
@@ -1127,24 +1089,7 @@ if (flag("install")) {
1127
1089
  // how a person ends up certain that a thing works which does not.
1128
1090
  const added = HOOK_EVENTS.filter((event) => !wired.has(event));
1129
1091
  const already = added.length === 0;
1130
- // The counting half, from the same deployment the hook came from: one command installs both, or
1131
- // says plainly that it could not — a half nobody knows is missing is the worse outcome.
1132
- const counterOrigin = coupling()?.url ? new URL(coupling().url).origin : null;
1133
- if (!(await installReaders(counterOrigin))) console.log("readers: transcript-readers.mjs or session-databases.mjs not found beside this file nor at the deployment; the clients they read are not read until they are");
1134
- if (existsSync(COUNTER)) await refreshCounter(counterOrigin, (line) => console.log(line));
1135
- if (!existsSync(COUNTER)) {
1136
- const origin = counterOrigin;
1137
- if (!origin) console.log("counter: not installed — no coupling found to name the deployment; fetch /counter/count-behaviour.mjs yourself");
1138
- else {
1139
- try {
1140
- const response = await fetch(`${origin}/counter/count-behaviour.mjs`);
1141
- if (!response.ok) throw new Error(String(response.status));
1142
- writeFileSync(COUNTER, await response.text());
1143
- console.log(`counter: ${COUNTER} — it runs once a day from this hook and STAGES its reading; nothing counts until you click Import in the app`);
1144
- } catch (error) { console.log(`counter: could not fetch it (${error.message}) — the hook works without it; fetch /counter/count-behaviour.mjs later`); }
1145
- }
1146
- }
1147
- if (already && !repaired) { console.log(hookRefreshed ? `hook updated: ${home} now runs the version you downloaded; the wiring was already right (${command})` : `already installed — nothing changed (${command})`); return await exitFlushed(0); }
1092
+ if (already && !repaired) { console.log(`already installed — nothing changed (${command})`); return await exitFlushed(0); }
1148
1093
  for (const event of added) settings.hooks[event].push({ hooks: [{ type: "command", command }] });
1149
1094
  mkdirSync(dirname(file), { recursive: true });
1150
1095
  writeFileSync(file, JSON.stringify(settings, null, 2));
@@ -1201,6 +1146,21 @@ if (!door && !codexDoor && !DRY) { return await exitFlushed(0); } // Not coupled
1201
1146
  * device key (only lines this computer signed travel), an archive that verifies, a stretch whose session is gone from
1202
1147
  * this computer (one still here goes through the ordinary history), a door that knows the mark, and the person asking.
1203
1148
  */
1149
+ if (flag("history") && flag("resume")) {
1150
+ const { resumeHistory } = await import("./history-outbox.mjs");
1151
+ const totals = { received: 0, review: 0, waiting: 0, batches: 0 };
1152
+ try {
1153
+ for (const target of [door, ...(codexDoor && codexDoor.token !== door?.token ? [codexDoor] : [])].filter(Boolean)) {
1154
+ const result = await resumeHistory(target, { dry: DRY, retryReview: flag("retry-review"), confirmed: confirmedReceipt, note: noteReceipt,
1155
+ send: (body, source) => fetch(target.url, { method: "POST", headers: { "content-type": "application/json", accept: "application/json, text/event-stream", authorization: `Bearer ${target.token}`, ...clientOf(source, true), ...proofFor(target.url, body) }, body, redirect: "error", signal: AbortSignal.timeout(65_000) }),
1156
+ });
1157
+ for (const key of Object.keys(totals)) totals[key] += result[key];
1158
+ }
1159
+ console.log(JSON.stringify({ resumed: totals.received, ...totals, ...RECEIPTS }));
1160
+ return await exitFlushed(DRY || (!totals.waiting && !totals.review) ? 0 : 1);
1161
+ } catch { console.log("Pending history could not be read safely. Nothing was marked complete; keep the local WorkTrust folder for recovery."); return await exitFlushed(1); }
1162
+ }
1163
+
1204
1164
  if (flag("history") && flag("from-archive")) {
1205
1165
  const named = value("from-archive"), dir = named && !named.startsWith("--") ? named.replace(/^~(?=\/|$)/, homedir()) : join(homedir(), "AI-Evidence");
1206
1166
  const say = (text) => console.log(text);
@@ -1211,7 +1171,7 @@ if (flag("history") && flag("from-archive")) {
1211
1171
  // archive must still verify whole, and only stretches no longer in any AI app here travel.
1212
1172
  let ownKey = null;
1213
1173
  try { ownKey = pem ? createPublicKey(createPrivateKey(pem)).export({ format: "jwk" }).x : null; } catch { ownKey = null; }
1214
- const verified = spawnSync(process.execPath, [...NODE_FLAGS, join(dirname(fileURLToPath(import.meta.url)), "preserve.mjs"), "--verify", dir], { encoding: "utf8" });
1174
+ const verified = spawnSync(moduleExecutable(RELEASE_DIR), [...moduleArgs(RELEASE_DIR, "preserve.mjs", ["--verify", dir])], { encoding: "utf8" });
1215
1175
  if (verified.status !== 0) { say(`The archive in ${dir} does not verify, so nothing was sent: ${(verified.stdout || verified.stderr || "").trim().split("\n").pop()}`); return await exitFlushed(1); }
1216
1176
  const { archiveEntries = null } = (await import("./preserve-lines.mjs").catch(() => null)) ?? {};
1217
1177
  if (!archiveEntries) { say("preserve-lines.mjs is not beside this file. Nothing was sent."); return await exitFlushed(1); }
@@ -1262,7 +1222,7 @@ if (flag("history")) {
1262
1222
  // An export that arrived whole is remembered by its digest (never by a conversation), so the bare command offers it no more.
1263
1223
  if (fromExports && accepted === entries.length) for (const report of fromExports.reports) rememberExport(report.digest, { vendor: report.vendor, sent: true, at: new Date().toISOString(), conversations: report.conversations });
1264
1224
  // ONE LINE FOR THE COMMAND TO ASK WITH (2026-10-10): what the door replaced, how many AI-app lines lie on the export's days, how many it withdrew.
1265
- if (fromExports) console.log(JSON.stringify({ export_sent: accepted, of: entries.length, ...RECEIPTS })); else console.log(JSON.stringify({ history_sent: accepted, of: entries.length, ...RECEIPTS })); // the same line for a history send: what the door did with it, and WorkTrust's measuredSeconds for what it stored
1225
+ if (fromExports) console.log(JSON.stringify({ export_sent: accepted, of: entries.length, ...RECEIPTS })); else console.log(JSON.stringify({ history_sent: accepted, of: entries.length, ...RECEIPTS, delivery: HISTORY_DELIVERY })); // the same line for a history send: what the door did with it, and WorkTrust's measuredSeconds for what it stored
1266
1226
  return await exitFlushed(accepted === entries.length ? 0 : 1);
1267
1227
  }
1268
1228
 
@@ -1337,12 +1297,10 @@ if (!DRY && (sent > 0 || filed > 0)) writeState(state);
1337
1297
  // `--send`: staging is idempotent on the reading's own digest, so a day that changed nothing
1338
1298
  // leaves nothing behind.
1339
1299
  if (!DRY && existsSync(COUNTER)) {
1340
- // Before the day's count: the deployment's counter, if it is newer than the one on this machine.
1341
- await refreshCounter(door?.url ? new URL(door.url).origin : null, (line) => console.log(line));
1342
1300
  const last = state.__counter?.at ? Date.parse(state.__counter.at) : 0;
1343
1301
  if (Date.now() - last > COUNTER_EVERY_MS) {
1344
1302
  try {
1345
- const child = spawn(process.execPath, [...NODE_FLAGS, COUNTER, "--stage"], { detached: true, stdio: "ignore" });
1303
+ const child = spawn(moduleExecutable(RELEASE_DIR), moduleArgs(RELEASE_DIR, "count-behaviour.mjs", ["--stage"]), { detached: true, stdio: ["ignore", "ignore", "inherit"] });
1346
1304
  child.unref();
1347
1305
  state.__counter = { at: new Date().toISOString() };
1348
1306
  writeState(state);
@@ -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":"560104ad89115bb9392a39ba31431546296605e23ba7134aebb65e398b54741d","SECURITY.md":"e3ed1927cbceef97b38ca630aadd0a91a0df02368f822f4fd66e3ed0b6a07e8d","chat-exports.mjs":"04eafe333940ec03d5058d8d51062124aa12ab882bf04db03bcda5613ec69298","claude-mod.mjs":"02d86b0cdddf39879efc5194c0a5be6b41456faedec28963dc123a4e88dc3942","config-edits.mjs":"0eba2f176ef6f7afba071d6e00de0ff19ba2b283180a801dfd957aa38c1edd94","count-behaviour.mjs":"1beaec2a4d0aead76d166f89cc52441a9cf48f2e69da9888ca2091dd3a10a37b","engine-release.json":"1b8113feffe4a6c8c513f885c2a507eac002c661a79526734ac054453a6466a2","log-session.mjs":"b99f082a58f0a92375026f52b62eb72173f06614b844e3def06b3ed40942b103","orchestration-contract.mjs":"ec08f303a166365b99e70b675de4cfe76c6156c2567e14b5569f6d992f0231b7","orchestration-evidence.mjs":"d0d06cecf0eb08e5c6e653c62a4f45b1eddf2119c2acb8341056b34f488d214a","orchestration-report.mjs":"d4e0a9ad8e4a01b462d22c6b1866aac291565c533ff476085d3367cb6d59bc1b","package-integrity.mjs":"b9d81dc88cf5c19ccfbf334a7af84a0c4e299a0e9e4d4091132253e22f855dc3","package.json":"29ed1c5bfa3075d6970b94a7b922d85dfdcce7a4e3afc6808d340ae421a3aa0d","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":"b563a702634b41c064fdd0b6ad842c77ff851dfcf682b370c677114f8f75c061"},"format":"worktrust-package/1","kind":"npm","version":"0.10.23"},"signature":"WESSe1_j0LegjJCE5a8xKYLoeKmDic5pLIK8bUpCSV2yqnU7P4UIfOosoux_buhU6-khECj2I_rNUTz4YQsbCw"}
1
+ {"keyId":"608168ccdef72562fc91f9c0f9f2c2d6876bece7f7362cb545b818f7947da6b5","payload":{"files":{"AGENTS.md":"d1db152d88338df23b5900beed6a69bedc2900b6f53fef3f036b46dd7a07b841","CLAUDE.md":"5933504f93e5a40369a4790e96dd5dad791d849d3178b1833eb64088e456aaeb","LICENSE":"3096ed1693974a90e1f4f59bf01c9559d94a7941d933e36fb81d3995a97f25c1","README.md":"0677478b03ee480c869121f3243cb510b45990d18849df64643982d621913088","SECURITY.md":"02c049a69fb6104813c1ff223b312e1e91ec70cfe776f1c2853f7952e818c09b","chat-exports.mjs":"04eafe333940ec03d5058d8d51062124aa12ab882bf04db03bcda5613ec69298","claude-mod.mjs":"02d86b0cdddf39879efc5194c0a5be6b41456faedec28963dc123a4e88dc3942","config-edits.mjs":"0eba2f176ef6f7afba071d6e00de0ff19ba2b283180a801dfd957aa38c1edd94","count-behaviour.mjs":"1beaec2a4d0aead76d166f89cc52441a9cf48f2e69da9888ca2091dd3a10a37b","engine-release.json":"514abde48bf6206e489387f3819d92c3d3de2c6a1f9f71a1b171013683ec3677","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":"6d47c91ff4672cd6f5f7ed72971dd11e2951f73b25b6f83b157255f69193733b","preserve-lines.mjs":"2df64a69687aa51219bf7b86b88d175cc50990fa29574b31897e41a9ebeecf43","preserve-summary.mjs":"137f781ed7021596a3f0ea67afcf2ab8616ac293f833dbb8f176e838e0ed8321","preserve.mjs":"9add279352750be94d94873738145e379819d793c20c6c6503219969608e2c2f","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":"bd208923c08a16ed640f25417ae381d0c3e3dda02e56aad4aee66497cdd494b9"},"format":"worktrust-package/1","kind":"npm","version":"0.10.25"},"signature":"CS95agn012vWfW2TtV68C9Fe30xdxSmmaeWNJfi3k6STlWASh9caZvuYvMrh5m53vImITnKY9oVbt9Re8jqAAA"}