worktrust 0.10.27 → 0.10.29

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,24 @@
1
1
  # worktrust
2
2
 
3
+ ## 0.10.29: history in calls WorkTrust takes; how each session was started
4
+
5
+ A history call carries at most 1.9 MB and 1.4 MB of timelines (WorkTrust takes 2 MB and 1.5 MB). A batch an earlier
6
+ version queued larger, or one WorkTrust answers with 413, is cut smaller in `~/.worktrust/history-outbox` and sent in
7
+ pieces, never again as it was; a re-measure's run is cut again whole, under a new run id. A run WorkTrust already holds
8
+ part of, or one line too large for any call, is let go and counted, and `npx worktrust@latest history` measures again.
9
+
10
+ Each line now says how its session was started, as the AI app recorded it: `interactive`, `headless` (`claude -p`, an
11
+ Agent SDK program, `codex exec`, a Codex subagent) or `scheduled` (a timer started it), beside its timeline. A session
12
+ the app said nothing about is left unsaid. WorkTrust counts a headless or scheduled session as Agent operations, never
13
+ as the person's hours. `--history --dry-run --summary` prints the planned batches and the session kinds, counts only.
14
+
15
+ ## 0.10.28: an honest receipt for a re-measure
16
+
17
+ A re-measure that lands as new lines over lines WorkTrust had withdrawn (support's withdrawal of client-computed
18
+ figures, a rebuild) is said as new lines, never as "Nothing changed"; entries WorkTrust refused for carrying no
19
+ timeline are named. This CLI sends every session's timeline and no figure of its own since 0.10.20; WorkTrust times
20
+ every second itself under its own idle cap, so a locally changed constant changes nothing it counts.
21
+
3
22
  ## 0.10.27: history kept on the server
4
23
 
5
24
  A re-measure (`worktrust history`) sends its batches as one run; WorkTrust keeps each batch it
@@ -444,7 +463,7 @@ retried safely. A row kept pending on WorkTrust remains excluded from counted ac
444
463
  | **Reads** | Which AI apps are installed (the settings folders of Claude Code, Codex, Cursor, Gemini CLI, Antigravity, VS Code, Windsurf, Hermes Agent, Goose, OpenCode, OpenClaw), and the chats Cursor and Copilot keep (clocks, models and token counts only). Afterwards, the session hook reads Claude Code's, Codex's and Antigravity's session files, the session databases of Hermes, Goose, OpenCode and OpenClaw, and the chats Cursor and Copilot keep, on this computer to measure durations and token counts. |
445
464
  | **Writes** | The key file (above). In each AI app's MCP settings (`~/.claude.json` through `claude mcp`, `~/.cursor/mcp.json`, `~/.codex/config.toml`, `~/.gemini/settings.json`, `~/.gemini/config/mcp_config.json` (Antigravity), VS Code's `mcp.json`, Windsurf's `mcp_config.json`, Hermes's and Goose's `config.yaml`, OpenCode's `opencode.json`, OpenClaw through `openclaw mcp set`) a WorkTrust entry that runs the local bridge, with no key in it; three hooks in `~/.claude/settings.json`; the bridge, the hook and the counter in `~/.worktrust/`. |
446
465
  | **Sends, to pair** | This computer's system (macOS, Windows, Linux) and host name. WorkTrust also records the network address the request arrives from, as a security record kept 90 days and seen only by WorkTrust staff (to answer a theft or fraud report). |
447
- | **Sends, afterwards** | Per measured stretch of work, and nothing else: its timeline and basis (`timeline`, `duration_basis`: since 0.10.20 the CLI sends no duration and no hours in layers of its own; WorkTrust computes them from the timeline), token counts (`tokens_in`, `tokens_out`, `tokens_cache_read`, `tokens_cache_write`, `token_basis`), the model's name (`model`), the kind of work and one layer keyword such as frontend or backend (`title`, `kind`, `layer`, `layers`), closed technology keys (`stack`) and separate display-only tool keys (`tools_seen`), how the turns are counted (`turn_basis`; the counts themselves WorkTrust reads from the timeline; the subagents' seconds wait for a timeline per run), when it began and ended and your computer's offset from UTC (`started_at`, `at`, `utc_offset`), what the CLI derived from the stretch as kinds and counts (`evidence`: checks run and failed, delivery steps and whether a check passed first, recoveries, delegation, context, routing, steering, refusals, planning, files and test files changed, the complexity class; with the WorkTrust mod on, its `live` counts from inside Claude Code: permission answers, effort levels, context and plan-limit peaks, subagents and setup; never a word, a command or a path; since 0.8.3, `live` since 0.10.15), a hash of the session and the day (`stretch_ref`), `steered_from` when it ran over SSH, the stretch's clock as step kinds and whole seconds so WorkTrust computes the figures itself (`timeline`, since 0.10.20: never a word, a tool name or a path), the CLI's version and a digest of its own files as signals (`cli_version`, `cli_digest`), and, so the work can be matched to GitHub, the repository as its remote's owner/name (`repo`, only for a repository on GitHub, GitLab or Bitbucket, the hosts WorkTrust can couple; never one on your own or a client's server) and the hashes of the commits made in the stretch (`commits`, never their messages). |
466
+ | **Sends, afterwards** | Per measured stretch of work, and nothing else: its timeline and basis (`timeline`, `duration_basis`: since 0.10.20 the CLI sends no duration and no hours in layers of its own; WorkTrust computes them from the timeline), token counts (`tokens_in`, `tokens_out`, `tokens_cache_read`, `tokens_cache_write`, `token_basis`), the model's name (`model`), the kind of work and one layer keyword such as frontend or backend (`title`, `kind`, `layer`, `layers`), closed technology keys (`stack`) and separate display-only tool keys (`tools_seen`), how the turns are counted (`turn_basis`; the counts themselves WorkTrust reads from the timeline; the subagents' seconds wait for a timeline per run), when it began and ended and your computer's offset from UTC (`started_at`, `at`, `utc_offset`), what the CLI derived from the stretch as kinds and counts (`evidence`: checks run and failed, delivery steps and whether a check passed first, recoveries, delegation, context, routing, steering, refusals, planning, files and test files changed, the complexity class; with the WorkTrust mod on, its `live` counts from inside Claude Code: permission answers, effort levels, context and plan-limit peaks, subagents and setup; never a word, a command or a path; since 0.8.3, `live` since 0.10.15), a hash of the session and the day (`stretch_ref`), `steered_from` when it ran over SSH, the stretch's clock as step kinds and whole seconds so WorkTrust computes the figures itself (`timeline`, since 0.10.20: never a word, a tool name or a path), how the session was started as the AI app recorded it, beside the timeline (`session_kind`: interactive, headless or scheduled, since 0.10.29; left out when the app did not say), the CLI's version and a digest of its own files as signals (`cli_version`, `cli_digest`), and, so the work can be matched to GitHub, the repository as its remote's owner/name (`repo`, only for a repository on GitHub, GitLab or Bitbucket, the hosts WorkTrust can couple; never one on your own or a client's server), for any other git repository a code in its place (`repo_code`: 16 hex of an HMAC of its remote, or its root, keyed with this computer's own secret in `~/.worktrust/archive-salt`, which is never sent, so WorkTrust can group its lines but cannot tell which repository it is) and the hashes of the commits made in the stretch (`commits`, never their messages). |
448
467
  | **Never sends** | Prompts, answers, code, file names or paths, commit messages, branch names, or the name of your local folder (a repository is named only as its remote's owner/name, above). The door has no field for them and refuses a submission that carries them. |
449
468
 
450
469
  **The clock is WorkTrust's, not this computer's (0.10.20).** A measured stretch travels as its timeline: one step per
@@ -1 +1 @@
1
- {"keyId":"608168ccdef72562fc91f9c0f9f2c2d6876bece7f7362cb545b818f7947da6b5","payload":{"files":{"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","history-outbox.mjs":"013885af8239da9fbd0f7fb339383f6dbcb462f439d8900c9290757f63fb597a","log-session.mjs":"87066a26e9d2d3947540b24e34139f63b25a1e4f8e13f389fa5e2d398893c368","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":"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":"4fc0b26c65394591ef13a354c53792926c43a4c829357c6dac12570181ac0e47"},"format":"worktrust-package/1","kind":"engine","version":"0.10.27"},"signature":"5m483yf79RTRQEzPghieWXgMJv77iUwp7wmRJMf8Vxu6zvOw5nPCS1V4TPRvAjCwjwedSJ9yI1q7IpG0gZbcCA"}
1
+ {"keyId":"608168ccdef72562fc91f9c0f9f2c2d6876bece7f7362cb545b818f7947da6b5","payload":{"files":{"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","history-outbox.mjs":"b84e22542bb2d8195a469ee5f4116356ae9eac4a53ff2d40f0268b5b1de99dc5","log-session.mjs":"4da610744dfdd1aa939c231263fad9962288376bf8494ef3e0a08128e3d0cb17","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":"3e369083ba43bcda2fa0622fd526aa64fcf8ad66e7b6e8f23821752c4d47ad27","runtime-install.mjs":"aab47b52c79d726ef428a24f982c648fa3f1c2dc2b574f633611d02924864e5f","session-databases.mjs":"543fd3b82d28d96d789be0a1dc9186c5fafa783e98b87e5b3b17b211542e2b4d","setup-mcp.mjs":"6ecfbf44f001dd433512b26736031ebc855b154e2bb0a401e2512b43623cd9cd","stack-rules.mjs":"b23c56e72ec56ba02b17ed895f869172d988c468a697e8d6026b0e268f61e489","stretch-evidence.mjs":"5b31a6f29b785d277e92257532f3c7cee366a79759decc7a75cfbaec2686ee13","transcript-readers.mjs":"2f17bb5f234ccd630d51cf3f35c396d1b43240b601330cc3abb193effb5bfc3c","worktrust-launch.mjs":"84801bd29d472d48188c126b9ebe3989a3132b54e13cc4fe534ff7c383a294ee","worktrust.mjs":"9e3c21c144dfc8397da49cf04b0262c4f6e64619b4233a768bc928f6704026ec"},"format":"worktrust-package/1","kind":"engine","version":"0.10.29"},"signature":"syVJ_vcbmCt6ZhD4wL0yY9KtE0Z2EUzY2OdLEGeNJfDwgBslJU37iCZVwLRKbGyzmMSt0hMUOI74wXbIBQtuAg"}
@@ -38,7 +38,8 @@ export function queuedHistory(target,body,source) {
38
38
  const scope=scopeOf(target),id=digest(scope+'\0'+source+'\0'+body);
39
39
  const request=join(root,id+'.request.json'),ack=join(root,id+'.ack.json'),state=join(root,id+'.state.json');
40
40
  const acknowledged=read(ack);
41
- if(acknowledged?.id===id)return {status:'acknowledged',confirm(){},close(){},defer(){}};
41
+ // REPLACED (0.10.29): a batch cut into smaller ones is acknowledged by its pieces; the caller follows them.
42
+ if(acknowledged?.id===id)return {id,status:Array.isArray(acknowledged.replacedBy)?'replaced':'acknowledged',replacedBy:Array.isArray(acknowledged.replacedBy)?acknowledged.replacedBy.filter(child=>/^[a-f0-9]{64}$/.test(child)):[],lines:Number.isInteger(acknowledged.lines)?acknowledged.lines:null,confirm(){},close(){},defer(){},oversize(){},replace(){return [];}};
42
43
  const current=read(state);
43
44
  reservation(root,()=>{
44
45
  if(!existsSync(request)) {
@@ -48,12 +49,20 @@ export function queuedHistory(target,body,source) {
48
49
  write(request,{id,scope,source,body});
49
50
  } else if(read(request)?.body!==body)throw Error('HISTORY_QUEUE_CHANGED');
50
51
  });
51
- const status=current?.status==='review'?'review':Number(current?.retryAt)>Date.now()?'waiting':'pending';
52
- return {status,retryAt:current?.retryAt??null,
52
+ const status=current?.status==='review'?'review':current?.status==='oversize'?'oversize':Number(current?.retryAt)>Date.now()?'waiting':'pending';
53
+ const done=(value)=>{write(ack,value);if(existsSync(request)){regular(request);unlinkSync(request);}if(existsSync(state)){regular(state);unlinkSync(state);}};
54
+ return {id,status,retryAt:current?.retryAt??null,
53
55
  // close (0.10.27): WorkTrust refused the batch for good (its run closed): kept here it would wait forever, so it is let go.
54
- close(){write(ack,{id,closedAt:new Date().toISOString()});if(existsSync(request)){regular(request);unlinkSync(request);}if(existsSync(state)){regular(state);unlinkSync(state);}},
55
- confirm(){write(ack,{id,confirmedAt:new Date().toISOString()});if(existsSync(request)){regular(request);unlinkSync(request);}if(existsSync(state)){regular(state);unlinkSync(state);}},
56
+ // `reason` (0.10.29): 'oversize' for a batch that can never fit one call (one line too large, a run already partly received).
57
+ close(reason){done({id,closedAt:new Date().toISOString(),...(reason?{reason}:{})});},
58
+ // `lines` (0.10.29): how many lines the receipt confirmed, so a batch later found replaced by its pieces counts them once.
59
+ confirm(lines){done({id,confirmedAt:new Date().toISOString(),...(Number.isInteger(lines)?{lines}:{})});},
56
60
  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});},
61
+ // TOO LARGE FOR ONE CALL (0.10.29): WorkTrust answered 413. Marked, never retried as it is: the next pass cuts it smaller.
62
+ oversize(){if(existsSync(ack))return;write(state,{id,status:'oversize',retryAt:0});},
63
+ // ITS PIECES (0.10.29): each piece is queued first, then this batch is acknowledged as replaced by them, so a stop between the
64
+ // two leaves both, and the next pass cuts the same pieces again (the cut is a pure function of the lines). Answers their ids.
65
+ replace(pieces){const ids=pieces.map(piece=>queuedHistory(target,piece.body,piece.source).id);done({id,replacedAt:new Date().toISOString(),replacedBy:ids});return ids;},
57
66
  };
58
67
  }
59
68
  export function historyRefusal(text,response) {
@@ -63,37 +72,94 @@ export function historyRefusal(text,response) {
63
72
  const raw=Number(response.headers.get('retry-after'));
64
73
  // A staged run WorkTrust closed or refused (0.10.27: another computer's key, seven days without its last batch) is final.
65
74
  const closed=rpc?.id===1 && String(rpc?.error?.message??'').startsWith('history run refused:');
66
- return {reason:review?'review':closed?'closed':response.status===429?'capacity':'unconfirmed',seconds:Number.isFinite(raw)&&raw>0?Math.min(MAX_RETRY_SECONDS,raw):0};
75
+ // A 413 (0.10.29) is the batch, not the queue: it is cut smaller, never sent again as it was, and nothing else waits for it.
76
+ return {reason:review?'review':closed?'closed':response.status===413?'oversize':response.status===429?'capacity':'unconfirmed',seconds:Number.isFinite(raw)&&raw>0?Math.min(MAX_RETRY_SECONDS,raw):0};
67
77
  }
68
78
 
69
79
  /** Explicit recovery, even after the AI client removed its source files. A changed account/key
70
- * cannot replay another coupling's pending data. Review is retried only on an explicit request. */
71
- export async function resumeHistory(target, {send, confirmed, note, retryReview=false, dry=false, limit=Infinity}) {
80
+ * cannot replay another coupling's pending data. Review is retried only on an explicit request.
81
+ *
82
+ * THE RE-SPLIT (0.10.29). WorkTrust takes at most 2 MB and 1.5 MB of timelines in one history call; CLI 0.10.28 and older queued
83
+ * batches up to 3.5 MB. `cutter` (the hook's own cut; this file never reads a transcript) decides what fits. A batch that does not
84
+ * fit, or that WorkTrust answered 413, is replaced here by its pieces and the pieces are sent in its place, never the same batch
85
+ * again. A batch of a staged run carries the run's fixed count, so a run is cut again WHOLE, under a new run id, while every one
86
+ * of its batches is still on this computer; once WorkTrust holds part of a run, the rest can never complete it, and is let go
87
+ * (`refused`: WorkTrust keeps the earlier lines counting, and `npx worktrust@latest history` measures again). A single line too
88
+ * large for a call is let go the same way. `only` limits a pass to those batches (and their pieces): the send that just queued them.
89
+ */
90
+ export async function resumeHistory(target, {send, confirmed, note, retryReview=false, dry=false, limit=Infinity, cutter=null, only=null}) {
72
91
  const root=join(homedir(),'.worktrust','history-outbox'),scope=scopeOf(target);
73
- const totals={received:0,review:0,waiting:0,batches:0,refused:0};let paused=null,sent=0;
92
+ const totals={received:0,review:0,waiting:0,batches:0,refused:0,held:0,split:0};let paused=null,sent=0;
74
93
  if(!existsSync(root))return totals;
75
94
  directory(root);
76
95
  const files=readdirSync(root);if(files.length>12000)throw Error('HISTORY_QUEUE_FULL');
77
- for(const file of files.sort()) {
78
- if(!/^[a-f0-9]{64}\.request\.json$/.test(file))continue;
79
- const item=read(join(root,file));if(item?.scope!==scope)continue;
80
- 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');
96
+ const items=new Map();
97
+ const load=(id)=>{
98
+ if(items.has(id))return items.get(id);
99
+ const item=read(join(root,id+'.request.json'));if(item?.scope!==scope){items.set(id,null);return null;}
100
+ if(typeof item.body!=='string'||typeof item.source!=='string'||item.id!==digest(scope+'\0'+item.source+'\0'+item.body)||item.id!==id)throw Error('HISTORY_QUEUE_CHANGED');
81
101
  const rpc=JSON.parse(item.body),entries=rpc?.params?.arguments?.entries;
82
102
  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');
103
+ const run=rpc.params.arguments.run&&typeof rpc.params.arguments.run.id==='string'?rpc.params.arguments.run:null;
104
+ const loaded={id,body:item.body,source:item.source,rpc,entries,run};items.set(id,loaded);return loaded;
105
+ };
106
+ const ids=files.filter(file=>/^[a-f0-9]{64}\.request\.json$/.test(file)).map(file=>file.slice(0,64)).sort();
107
+ for(const id of ids)load(id);
108
+ // A staged run's batches still on this computer, by run id: the run is cut again whole, or not at all.
109
+ const runOf=(runId)=>[...items.values()].filter(item=>item&&item.run?.id===runId).sort((a,b)=>a.run.index-b.run.index);
110
+ const marked=(id)=>read(join(root,id+'.state.json'))?.status==='oversize';
111
+ const whole=(batches)=>batches.length>0&&batches.length===batches[0].run.count&&batches.every((item,index)=>item.run.index===index&&item.run.count===batches[0].run.count);
112
+ const queue=only?[...only]:[...ids],seen=new Set();
113
+ const letGo=(batches)=>{for(const batch of batches){queuedHistory(target,batch.body,batch.source).close('oversize');items.set(batch.id,null);seen.add(batch.id);totals.refused+=batch.entries.length;}return null;};
114
+ // Cut smaller: answers the pieces' ids, or null when the batch (or its run) can never fit and was let go.
115
+ const resplit=(item,queued,tighter)=>{
116
+ if(item.run){
117
+ const batches=runOf(item.run.id);
118
+ if(!whole(batches))return letGo(batches);
119
+ const pieces=cutter.replan(batches.map(batch=>({rpc:batch.rpc,source:batch.source})),tighter?item.entries:null);
120
+ if(!pieces.length)return letGo(batches);
121
+ let children=[];for(const batch of batches){children=queuedHistory(target,batch.body,batch.source).replace(pieces);items.set(batch.id,null);seen.add(batch.id);}
122
+ totals.split+=batches.length;return children;
123
+ }
124
+ const pieces=cutter.split(item.rpc,item.source,tighter?item.entries:null);
125
+ if(pieces.length<2)return letGo([item]);
126
+ totals.split++;items.set(item.id,null);return queued.replace(pieces.map(body=>({body,source:item.source})));
127
+ };
128
+ while(queue.length) {
129
+ const id=queue.shift();if(seen.has(id))continue;seen.add(id);
130
+ const ack=read(join(root,id+'.ack.json'));
131
+ if(ack?.id===id){if(Array.isArray(ack.replacedBy))queue.unshift(...ack.replacedBy.filter(child=>/^[a-f0-9]{64}$/.test(child)));else if(only&&Number.isInteger(ack.lines))totals.held+=ack.lines;continue;}
132
+ const item=load(id);if(!item)continue;
83
133
  const queued=queuedHistory(target,item.body,item.source);totals.batches++;
84
134
  if(queued.status==='acknowledged')continue;
135
+ if(queued.status==='replaced'){queue.unshift(...queued.replacedBy);continue;}
85
136
  // `limit` (0.10.27): the hook sends a few a run by itself; the rest wait, untouched, for the next run.
86
- if(sent>=limit){totals.waiting+=entries.length;continue;}
87
- if(queued.status==='review'&&!retryReview){totals.review+=entries.length;continue;}
88
- if(dry){totals.waiting+=entries.length;continue;}
137
+ if(sent>=limit){totals.waiting+=item.entries.length;continue;}
138
+ if(queued.status==='review'&&!retryReview){totals.review+=item.entries.length;continue;}
139
+ if(cutter){
140
+ const tighter=queued.status==='oversize',runTooLarge=Boolean(item.run)&&runOf(item.run.id).some(batch=>!cutter.fits(batch.entries)||marked(batch.id));
141
+ if(tighter||!cutter.fits(item.entries)||runTooLarge){
142
+ if(dry){totals.waiting+=item.entries.length;continue;}
143
+ const children=resplit(item,queued,tighter);if(children)queue.unshift(...children);continue;
144
+ }
145
+ }
146
+ if(dry){totals.waiting+=item.entries.length;continue;}
89
147
  if(queued.status==='waiting'&&!paused)paused={reason:'unconfirmed',seconds:Math.max(1,Math.ceil((queued.retryAt-Date.now())/1000))};
90
- if(paused){if(queued.status==='review'){totals.review+=entries.length;continue;}queued.defer(paused.reason,paused.seconds);totals.waiting+=entries.length;continue;}
148
+ if(paused){if(queued.status==='review'){totals.review+=item.entries.length;continue;}queued.defer(paused.reason,paused.seconds);totals.waiting+=item.entries.length;continue;}
91
149
  try {
92
150
  sent++;const response=await send(item.body,item.source),text=await response.text();
93
- try{if(!response.ok)throw Error();confirmed(text,entries.length);}
94
- catch{const refusal=historyRefusal(text,response);if(refusal.reason==='closed'){queued.close();totals.refused+=entries.length;continue;}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;}
95
- queued.confirm();totals.received+=entries.length;note(text);
96
- }catch{paused={reason:'unconfirmed',seconds:5};queued.defer(paused.reason,paused.seconds);totals.waiting+=entries.length;}
151
+ try{if(!response.ok)throw Error();confirmed(text,item.entries.length);}
152
+ catch{
153
+ const refusal=historyRefusal(text,response);
154
+ if(refusal.reason==='closed'){queued.close();totals.refused+=item.entries.length;continue;}
155
+ // Too large (0.10.29): marked and taken again at once, by the cut, never resent as it was. Without a cutter it waits.
156
+ if(refusal.reason==='oversize'){queued.oversize();if(cutter){seen.delete(id);queue.unshift(id);}else totals.waiting+=item.entries.length;continue;}
157
+ 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']+=item.entries.length;continue;
158
+ }
159
+ queued.confirm(item.entries.length);totals.received+=item.entries.length;note(text);
160
+ }catch{paused={reason:'unconfirmed',seconds:5};queued.defer(paused.reason,paused.seconds);totals.waiting+=item.entries.length;}
97
161
  }
98
162
  return totals;
99
163
  }
164
+ /** A queued batch's id, as queuedHistory names it, so a send can hand its own batches to resumeHistory (`only`). */
165
+ export const historyIdOf=(target,body,source)=>digest(scopeOf(target)+'\0'+source+'\0'+body);
package/log-session.mjs CHANGED
@@ -64,9 +64,9 @@ import { existsSync, mkdirSync, readFileSync, readdirSync, rmSync, statSync, wri
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
- import { createHash, createPrivateKey, createPublicKey, randomBytes, sign as cryptoSign } from "node:crypto";
67
+ import { createHash, createHmac, createPrivateKey, createPublicKey, randomBytes, sign as cryptoSign } from "node:crypto";
68
68
 
69
- import { moduleArgs, moduleExecutable } from "./package-integrity.mjs";
69
+ import { moduleArgs, moduleExecutable, readPrivateFile, createPrivateFile } from "./package-integrity.mjs";
70
70
 
71
71
  async function main() {
72
72
  const args = process.argv.slice(2), NODE_FLAGS = process.versions.node === "26.5.0" ? ["--no-concurrent-sparkplug"] : [];
@@ -222,7 +222,7 @@ const excluded = (path) => excludes.some((text) => text && path.includes(text));
222
222
  * reader), the database clients in session-databases.mjs. The install copies both into ~/.worktrust with this hook.
223
223
  * Without them this hook still reads Claude Code; the never-matching patterns keep every other client out.
224
224
  */
225
- const { CODEX_ROLLOUT = /(?!)/, codexIdOf = (file) => String(file).split(/[\\/]/).at(-1).replace(/\.jsonl$/, ""), antigravityIdOf = (file) => String(file).split(/[\\/]/).at(-4), codexLines, codexRolloutFiles = function* () {}, codexCwd = () => null, ANTIGRAVITY_TRANSCRIPT = /(?!)/, antigravityLines, antigravityRoots = () => [], antigravityTranscripts = function* () {}, antigravityContext = () => ({}), rememberAntigravity = () => null, codexLive = () => null } = (await import("./transcript-readers.mjs").catch(() => null)) ?? {};
225
+ const { CODEX_ROLLOUT = /(?!)/, codexIdOf = (file) => String(file).split(/[\\/]/).at(-1).replace(/\.jsonl$/, ""), antigravityIdOf = (file) => String(file).split(/[\\/]/).at(-4), codexLines, codexRolloutFiles = function* () {}, codexCwd = () => null, ANTIGRAVITY_TRANSCRIPT = /(?!)/, antigravityLines, antigravityRoots = () => [], antigravityTranscripts = function* () {}, antigravityContext = () => ({}), rememberAntigravity = () => null, codexLive = () => null, sessionKindReader = () => ({ note() {}, kind: () => "unknown" }) } = (await import("./transcript-readers.mjs").catch(() => null)) ?? {};
226
226
  // THE STRETCH'S DERIVED RECORD (0.7.4: split from this file): tool calls named by kind, verification, recovery, delegation,
227
227
  // context and routing, for the local archive only. A copy without the module still measures and sends exactly as before.
228
228
  const { callOf = (block) => ({ id: block.id, kinds: [], family: String(block.name), digest: "" }), deriveStretch = () => ({}), complexityOf = null, resultOf = (block) => ({ id: block.tool_use_id, failed: block.is_error === true, refusal: null }) } = (await import("./stretch-evidence.mjs").catch(() => null)) ?? {};
@@ -320,6 +320,32 @@ const repoOf = (cwd) => {
320
320
  const match = /[:/]([^/:]+)\/([^/]+?)(?:\.git)?$/.exec(remote);
321
321
  return match ? `${match[1]}/${match[2]}` : null;
322
322
  };
323
+ /**
324
+ * A REPOSITORY IT MAY NOT NAME, AS A CODE ONLY THIS COMPUTER CAN MAKE (owner, 2026-10-21). For a git repository whose remote is
325
+ * on no host WorkTrust can couple (or that has no remote), the name still never travels (0.8.6); what travels is 16 hex of an
326
+ * HMAC-SHA256, keyed with this computer's own secret (~/.worktrust/archive-salt, the archive's, made once with mode 600, never
327
+ * sent), over the normalised remote (host and path, no user, no secret, no .git) or, without one, the repository's root. The
328
+ * same repository gives the same code here, so its lines can be grouped and filed once; WorkTrust cannot turn a code back into
329
+ * a name, because it never holds the key. A folder that is no git repository gets no code.
330
+ */
331
+ let repoSecret;
332
+ const repoCodeSecret = () => {
333
+ if (repoSecret !== undefined) return repoSecret;
334
+ const file = join(homedir(), ".worktrust", "archive-salt");
335
+ try { const kept = readPrivateFile(file)?.trim(); if (/^[0-9a-f]{64}$/.test(kept ?? "")) return (repoSecret = kept); } catch { /* first run */ }
336
+ try { const made = randomBytes(32).toString("hex"); createPrivateFile(file, `${made}\n`); return (repoSecret = made); } catch { try { const kept = readPrivateFile(file)?.trim(); return (repoSecret = /^[0-9a-f]{64}$/.test(kept ?? "") ? kept : null); } catch { return (repoSecret = null); } }
337
+ };
338
+ const repoCodeOf = (cwd) => {
339
+ const root = git(cwd, "rev-parse", "--show-toplevel");
340
+ if (!root) return null;
341
+ const remote = git(cwd, "remote", "get-url", "origin");
342
+ if (remote && CODE_HOSTS.test(remote)) return null;
343
+ const name = remote
344
+ ? `remote:${remote.trim().toLowerCase().replace(/^[a-z][a-z0-9+.-]*:\/\//, "").replace(/^[^@/]+@/, "").replace(/:(?!\d)/, "/").replace(/\.git$/, "").replace(/\/+$/, "")}`
345
+ : `root:${root}`;
346
+ const secret = repoCodeSecret();
347
+ return secret ? createHmac("sha256", secret).update(`worktrust-repo-code|${name}`).digest("hex").slice(0, 16) : null;
348
+ };
323
349
  /** The paths this stretch touched: what was committed inside it, else what is still uncommitted. */
324
350
  const pathsTouched = (cwd, from, to) => {
325
351
  const committed = git(cwd, "log", `--since=${from}`, `--until=${to}`, "--name-only", "--pretty=format:", "--no-merges");
@@ -342,6 +368,13 @@ const pathsTouched = (cwd, from, to) => {
342
368
  * boundary the history path already uses, it needs no guess about where one piece of work ended,
343
369
  * and it is the unit the record reads back anyway.
344
370
  */
371
+ /**
372
+ * HOW THE SESSION WAS STARTED (owner, 2026-10-22; 0.10.29; docs/AGENT-HOURS.md): one word the client itself recorded, never a
373
+ * guess, read by `sessionKindReader` in transcript-readers.mjs over the whole session (its entrypoint, its first turn's origin, a
374
+ * Codex rollout's source) and sent beside a timeline as `session_kind` when it is interactive, headless or scheduled; unknown is
375
+ * left unsaid, and WorkTrust reads an unsaid kind as interactive. A copy without the readers reads every session as unknown.
376
+ * WorkTrust counts a headless or scheduled session as Agent operations, never as the person's hours.
377
+ */
345
378
  function stretchesOf(file, since) {
346
379
  // A file we cannot read is no days, never a null the caller has to remember to check: this
347
380
  // returns a list now, and one caller forgetting that is one silent crash inside a hook.
@@ -349,9 +382,11 @@ function stretchesOf(file, since) {
349
382
  if (!lines) return [];
350
383
  const messages = [];
351
384
  let cwd = null, steered = STEERED_HERE;
385
+ const kind = sessionKindReader();
352
386
  for (const line of lines) {
353
387
  if (typeof line.cwd === "string") cwd = line.cwd;
354
388
  if (typeof line.steered === "string") steered = line.steered; // a client that says how it was steered (Hermes's source)
389
+ kind.note(line);
355
390
  if (!line.timestamp || (line.type !== "user" && line.type !== "assistant")) continue;
356
391
  const at = Date.parse(line.timestamp);
357
392
  if (!Number.isFinite(at)) continue;
@@ -361,8 +396,8 @@ function stretchesOf(file, since) {
361
396
  if (messages.length === 0) return [];
362
397
  messages.sort((a, b) => a.at - b.at);
363
398
  const byDay = byDayOf(messages);
364
- const agents = agentsByDay(file, since);
365
- return [...byDay.entries()].sort(([a], [b]) => a.localeCompare(b)).map(([day, ofDay]) => { const stretch = measure(cwd, ofDay); return stretch && { ...stretch, ref: stretchRef(file, day), steered, agents: agents.get(day) ?? null, live: liveOf(file, day) }; }).filter(Boolean);
399
+ const agents = agentsByDay(file, since), session = kind.kind();
400
+ return [...byDay.entries()].sort(([a], [b]) => a.localeCompare(b)).map(([day, ofDay]) => { const stretch = measure(cwd, ofDay); return stretch && { ...stretch, ref: stretchRef(file, day), steered, session, agents: agents.get(day) ?? null, live: liveOf(file, day) }; }).filter(Boolean);
366
401
  }
367
402
 
368
403
  /**
@@ -573,6 +608,7 @@ const STEERED_HERE = process.env.SSH_CONNECTION || process.env.SSH_CLIENT || pro
573
608
  function payloadFor(stretch) {
574
609
  const cwd = stretch.cwd && existsSync(stretch.cwd) ? stretch.cwd : null;
575
610
  const repo = cwd ? repoOf(cwd) : null;
611
+ const repoCode = cwd && !repo ? repoCodeOf(cwd) : null; // a code, never a name, for a repository it may not name
576
612
  const touched = cwd ? pathsTouched(cwd, new Date(stretch.from).toISOString(), new Date(stretch.to).toISOString()) : { paths: [], committed: false, shas: [] };
577
613
  const { layer, layers } = layersOf(touched.paths), stack = stackOfFiles(touched.paths), toolsSeen = displayStackOfFiles(touched.paths); // 0.10.11: the stack and the tools seen, from the same paths, keys only, two fields
578
614
  // The seventh kind, used as it is defined: a stretch that changed no artefact is knowing
@@ -606,8 +642,11 @@ function payloadFor(stretch) {
606
642
  ...(stretch.shapeKnown && stretch.cacheWrite > 0 ? { tokens_cache_write: stretch.cacheWrite } : {}),
607
643
  ...(stretch.model ? { model: stretch.model } : {}),
608
644
  ...(repo ? { repo } : {}),
645
+ ...(repoCode ? { repo_code: repoCode } : {}),
609
646
  ...(touched.shas.length > 0 ? { commits: touched.shas.slice(0, 50) } : {}),
610
647
  ...(stretch.ref ? { stretch_ref: stretch.ref } : {}), ...(stretch.steered ? { steered_from: stretch.steered } : {}),
648
+ // HOW THE SESSION WAS STARTED (owner, 2026-10-22): interactive | headless | scheduled, beside the timeline; unknown is unsaid.
649
+ ...(stretch.timeline && (stretch.session === "interactive" || stretch.session === "headless" || stretch.session === "scheduled") ? { session_kind: stretch.session } : {}),
611
650
  // WHICH CODE SENT IT (0.10.20): a version and a digest of this hook's own files, signals never proof.
612
651
  ...(CLI_VERSION_SENT ? { cli_version: CLI_VERSION_SENT } : {}),
613
652
  ...(selfDigest ? { cli_digest: selfDigest } : {}),
@@ -636,25 +675,38 @@ function payloadFor(stretch) {
636
675
  * one day alone exceeds the cap: the door's receipt counts per day what it replaced and how many AI-app lines lie there, and a
637
676
  * day in two batches would be counted twice.
638
677
  */
639
- /** A batch stays under the door's body ceiling (4.5 MB) with room for the envelope: a timeline (0.10.20) is up to 200 KB a line, so a batch is cut by bytes as well as by count. */
640
- const BATCH_BYTES = 3_500_000;
678
+ /**
679
+ * A batch stays under the door's ceilings for one history call (2026-10-23, docs/INTAKE-HARDENING.md): 2 MB a call and 1.5 MB of
680
+ * timelines a call, each with room for the envelope. A timeline (0.10.20) is up to 200 KB a line, so a batch is cut by bytes
681
+ * and by timeline bytes as well as by count. Until 0.10.28 the cut was 3.5 MB, under the door's 4.5 MB outer bound only.
682
+ */
683
+ const BATCH_BYTES = 1_900_000;
684
+ const BATCH_TIMELINE_BYTES = 1_400_000;
685
+ /** One call's ceiling as the cut reads it: lines, bytes of the lines, bytes of their timelines (0.10.29: a re-split passes a tighter one). */
686
+ const BATCH_LIMIT = { lines: 200, bytes: BATCH_BYTES, timelineBytes: BATCH_TIMELINE_BYTES };
641
687
  const bytesOf = (entry) => Buffer.byteLength(JSON.stringify(entry), "utf8");
642
- const byBytes = (entries) => { const out = []; let current = [], size = 0; for (const entry of entries) { const bytes = bytesOf(entry); if (current.length > 0 && (current.length >= 200 || size + bytes > BATCH_BYTES)) { out.push(current); current = []; size = 0; } current.push(entry); size += bytes; } if (current.length) out.push(current); return out; };
643
- function batchesOf(group, byDay) {
644
- if (!byDay) return byBytes(group);
688
+ const timelineOfEntry = (entry) => (typeof entry.timeline === "string" ? Buffer.byteLength(entry.timeline, "utf8") : 0);
689
+ const byBytes = (entries, limit = BATCH_LIMIT) => { const out = []; let current = [], size = 0, timelines = 0; for (const entry of entries) { const bytes = bytesOf(entry), timeline = timelineOfEntry(entry); if (current.length > 0 && (current.length >= limit.lines || size + bytes > limit.bytes || timelines + timeline > limit.timelineBytes)) { out.push(current); current = []; size = 0; timelines = 0; } current.push(entry); size += bytes; timelines += timeline; } if (current.length) out.push(current); return out; };
690
+ /** Whether a set of lines fits one call: the count, the bytes and the timelines. */
691
+ const fits = (entries, limit = BATCH_LIMIT) => entries.length <= limit.lines && entries.reduce((n, entry) => n + bytesOf(entry), 0) <= limit.bytes && entries.reduce((n, entry) => n + timelineOfEntry(entry), 0) <= limit.timelineBytes;
692
+ /** HALF OF A BATCH THE DOOR REFUSED (0.10.29): when WorkTrust answers 413 to lines this cut thought fit, the next cut is half of them. */
693
+ const halfOf = (entries) => ({ lines: Math.max(1, Math.ceil(entries.length / 2)), bytes: Math.ceil(entries.reduce((n, entry) => n + bytesOf(entry), 0) / 2), timelineBytes: Math.max(1, Math.ceil(entries.reduce((n, entry) => n + timelineOfEntry(entry), 0) / 2)) });
694
+ function batchesOf(group, byDay, limit = BATCH_LIMIT) {
695
+ if (!byDay) return byBytes(group, limit);
645
696
  const days = new Map();
646
697
  for (const entry of group) { const day = String(entry.at).slice(0, 10); days.set(day, [...(days.get(day) ?? []), entry]); }
647
698
  const out = []; let current = [];
648
699
  for (const ofDay of days.values()) {
649
- if (ofDay.length > 200) { if (current.length) { out.push(current); current = []; } for (let i = 0; i < ofDay.length; i += 200) out.push(ofDay.slice(i, i + 200)); continue; }
650
- if (current.length + ofDay.length > 200) { out.push(current); current = []; }
700
+ // A day that alone does not fit one call is cut by bytes on its own; otherwise a day is never split across two calls.
701
+ if (!fits(ofDay, limit)) { if (current.length) { out.push(current); current = []; } out.push(...byBytes(ofDay, limit)); continue; }
702
+ if (!fits([...current, ...ofDay], limit)) { out.push(current); current = []; }
651
703
  current.push(...ofDay);
652
704
  }
653
705
  if (current.length) out.push(current);
654
706
  return out;
655
707
  }
656
708
  /** THE RECEIPTS' COUNTS (2026-10-10): what an export send replaced, how many AI-app lines lie on its days, how many were withdrawn; summed over the batches, read for the counts alone. */
657
- const RECEIPTS = { new: 0, alreadyHeld: 0, filled: 0, replaced: 0, superseded: 0, recut: 0, unknownOnDays: 0, unknownWithdrawn: 0, corrected: 0, measuredSeconds: 0, staged: 0, kept: 0 }; // 0.10.27: staged, the batches WorkTrust keeps on its server, and kept, their lines // 0.10.20: measuredSeconds is WorkTrust's own figure for what the batch stored, the one the terminal shows // 0.10.17: recut, the one-envelope export lines its runs replaced // 2026-10-10: and what a re-measure did (new, held, filled, replaced), so the command can say it
709
+ const RECEIPTS = { new: 0, alreadyHeld: 0, filled: 0, replaced: 0, superseded: 0, recut: 0, unknownOnDays: 0, unknownWithdrawn: 0, corrected: 0, measuredSeconds: 0, staged: 0, kept: 0, restored: 0, untimed: 0 }; // 0.10.27: staged, the batches WorkTrust keeps on its server, and kept, their lines // 0.10.20: measuredSeconds is WorkTrust's own figure for what the batch stored, the one the terminal shows // 0.10.17: recut, the one-envelope export lines its runs replaced // 2026-10-10: and what a re-measure did (new, held, filled, replaced), so the command can say it
658
710
  const noteReceipt = (answer) => {
659
711
  try {
660
712
  const json = JSON.parse(answer.trim().startsWith("{") ? answer : answer.split("\n").find((row) => row.startsWith("data:"))?.slice(5) ?? "null");
@@ -715,10 +767,11 @@ const historyRunId = (bodies) => {
715
767
  const h = createHash("sha256").update(`worktrust-history-run|${new Date().toISOString().slice(0, 10)}|${bodies.join("\n")}`).digest("hex");
716
768
  return `${h.slice(0, 8)}-${h.slice(8, 12)}-4${h.slice(13, 16)}-${(8 | (parseInt(h[16], 16) & 3)).toString(16)}${h.slice(17, 20)}-${h.slice(20, 32)}`;
717
769
  };
718
- async function sendHistory(door, entries, announce = false, rebuild = false, named = false, { byDay = false, withdrawUnknown = false } = {}) {
719
- let accepted = 0;
720
- const { queuedHistory, historyRefusal } = await import("./history-outbox.mjs");
721
- // Keep each source and its approved coupling separate.
770
+ /**
771
+ * THE PLAN OF A HISTORY SEND (0.10.29: one function, read by the send and by `--summary`, so the numbers a dry run prints are the
772
+ * batches the send would make). Each source and its approved coupling separate; a re-measure is one staged run per coupling.
773
+ */
774
+ function historyPlan(door, entries, rebuild = false, { byDay = false, withdrawUnknown = false } = {}) {
722
775
  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)])];
723
776
  // Imported entries carry no live commit/session join.
724
777
  const encodeBatch = (batch, run = null) => 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; }), ...(run ? { run } : {}) } } });
@@ -728,12 +781,47 @@ async function sendHistory(door, entries, announce = false, rebuild = false, nam
728
781
  run.forEach((item, index) => { item.run = { id, index, count: run.length }; });
729
782
  }
730
783
  for (const item of plan) item.body = encodeBatch(item.batch, item.run);
784
+ return plan;
785
+ }
786
+ /**
787
+ * THE OUTBOX'S CUT (0.10.29). history-outbox.mjs never reads a transcript, so the hook hands it this one: `fits` is the door's
788
+ * ceiling as above; `split` cuts one plain batch again (an export's by whole days, as it was planned); `replan` cuts a staged
789
+ * run's batches again, each AI app on its own, under a new run id and count. `tighter` is a batch WorkTrust answered 413 although
790
+ * it fit here: the next cut is half of it, so every piece is smaller than what was refused and a refused batch never goes again.
791
+ */
792
+ const outboxCut = {
793
+ fits: (entries) => fits(entries),
794
+ split(rpc, source, tighter) {
795
+ const args = rpc.params.arguments, pieces = batchesOf(args.entries, EXPORT_CLIENTS.includes(source), tighter ? halfOf(tighter) : BATCH_LIMIT);
796
+ return pieces.length < 2 ? [] : pieces.map((batch) => JSON.stringify({ ...rpc, params: { ...rpc.params, arguments: { ...args, entries: batch } } }));
797
+ },
798
+ replan(batches, tighter) {
799
+ const limit = tighter ? halfOf(tighter) : BATCH_LIMIT, bySource = new Map();
800
+ for (const { rpc, source } of batches) bySource.set(source, [...(bySource.get(source) ?? []), ...rpc.params.arguments.entries]);
801
+ const { run: _run, entries: _entries, ...args } = batches[0].rpc.params.arguments; void _run; void _entries;
802
+ const plan = [...bySource].flatMap(([source, group]) => batchesOf(group, false, limit).map((batch) => ({ source, batch })));
803
+ if (plan.length > 1000) return [];
804
+ const encode = (batch, run = null) => JSON.stringify({ jsonrpc: "2.0", id: 1, method: "tools/call", params: { name: "import_history", arguments: { ...args, entries: batch, ...(run ? { run } : {}) } } });
805
+ const id = historyRunId(plan.map(({ batch }) => encode(batch)));
806
+ return plan.map(({ source, batch }, index) => ({ source, body: encode(batch, { id, index, count: plan.length }) }));
807
+ },
808
+ };
809
+ async function sendHistory(door, entries, announce = false, rebuild = false, named = false, { byDay = false, withdrawUnknown = false } = {}) {
810
+ let accepted = 0;
811
+ const { queuedHistory, historyRefusal, historyIdOf, resumeHistory } = await import("./history-outbox.mjs");
812
+ const plan = historyPlan(door, entries, rebuild, { byDay, withdrawUnknown });
731
813
  // Persist the approved plan before sending, so later batches survive removed source files too.
732
814
  try { for (const item of plan) queuedHistory(item.target, item.body, item.source); }
733
815
  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; }
734
816
  const numbers = new Map(), stopped = new Set();
735
- for (const { source, target, batch, body } of plan) {
817
+ // TOO LARGE FOR ONE CALL (0.10.29): a batch WorkTrust answered 413, or one an earlier run already cut, is handed after the loop to
818
+ // the outbox's cut with the rest of its run, never sent again as it was. `stoppedRuns`: a run with a refused batch sends no more.
819
+ const later = new Map(), stoppedRuns = new Set();
820
+ const handLater = (item) => { const row = later.get(item.target.token) ?? { target: item.target, ids: [] }; row.ids.push(historyIdOf(item.target, item.body, item.source)); later.set(item.target.token, row); };
821
+ for (const item of plan) {
822
+ const { source, target, batch, body } = item;
736
823
  if (stopped.has(source)) continue;
824
+ if (item.run && stoppedRuns.has(item.run.id)) { handLater(item); continue; }
737
825
  const number = (numbers.get(source) ?? 0) + 1; numbers.set(source, number);
738
826
  for (const entry of batch) retainMeasurement(entry, source);
739
827
  // `named` (0.10.10): a copied folder's lines name their client too, so the record says which app the copy came from.
@@ -741,6 +829,7 @@ async function sendHistory(door, entries, announce = false, rebuild = false, nam
741
829
  try { queued = queuedHistory(target, body, source); }
742
830
  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; stopped.add(source); continue; }
743
831
  if (queued.status === "acknowledged" && !byDay) { accepted += batch.length; RECEIPTS.alreadyHeld += batch.length; continue; }
832
+ if (queued.status === "replaced" || queued.status === "oversize") { handLater(item); if (item.run) stoppedRuns.add(item.run.id); continue; }
744
833
  if (queued.status === "review" && !flag("retry-review")) { HISTORY_DELIVERY.review += batch.length; continue; }
745
834
  if (queued.status === "waiting") { HISTORY_DELIVERY.waiting += batch.length; continue; }
746
835
  try {
@@ -751,14 +840,24 @@ async function sendHistory(door, entries, announce = false, rebuild = false, nam
751
840
  const refusal = historyRefusal(text, response);
752
841
  // A run WorkTrust closed (seven days without its last batch, another computer's key) is final: kept here it would wait forever.
753
842
  if (refusal.reason === "closed") { queued.close(); HISTORY_DELIVERY.refused += batch.length; continue; }
843
+ if (refusal.reason === "oversize") { queued.oversize(); handLater(item); if (item.run) stoppedRuns.add(item.run.id); continue; }
754
844
  queued.defer(refusal.reason, refusal.seconds);
755
845
  if (refusal.reason === "review") { HISTORY_DELIVERY.review += batch.length; continue; }
756
846
  HISTORY_DELIVERY.waiting += batch.length; stopped.add(source); continue;
757
847
  }
758
- queued.confirm(); accepted += batch.length; noteReceipt(text);
848
+ queued.confirm(batch.length); accepted += batch.length; noteReceipt(text);
759
849
  if (announce) console.log(`batch ${number}: received ${batch.length}`);
760
850
  } catch { queued.defer("unconfirmed"); HISTORY_DELIVERY.waiting += batch.length; stopped.add(source); }
761
851
  }
852
+ for (const { target, ids } of later.values()) {
853
+ try {
854
+ const totals = await resumeHistory(target, { only: ids, cutter: outboxCut, retryReview: flag("retry-review"), confirmed: confirmedReceipt, note: noteReceipt, send: sendQueued(target) });
855
+ accepted += totals.received + totals.held; RECEIPTS.alreadyHeld += totals.held;
856
+ HISTORY_DELIVERY.waiting += totals.waiting; HISTORY_DELIVERY.review += totals.review; HISTORY_DELIVERY.refused += totals.refused;
857
+ if (announce && totals.split) console.log(`${totals.split} batch${totals.split === 1 ? "" : "es"} too large for one call: cut smaller and sent again in pieces`);
858
+ if (announce && totals.refused) console.log(`${totals.refused} line${totals.refused === 1 ? "" : "s"} could not be sent in a call WorkTrust takes; the earlier lines keep counting. Run npx worktrust@latest history again to measure them anew.`);
859
+ } catch { console.error("Pending history could not be read safely. Nothing was marked complete; keep the local WorkTrust folder for recovery."); }
860
+ }
762
861
  return accepted;
763
862
  }
764
863
 
@@ -774,7 +873,7 @@ async function resendPending(limit) {
774
873
  try {
775
874
  const { resumeHistory } = await import("./history-outbox.mjs");
776
875
  for (const target of [door, ...(codexDoor && codexDoor.token !== door?.token ? [codexDoor] : [])].filter(Boolean))
777
- await resumeHistory(target, { limit, confirmed: confirmedReceipt, note: noteReceipt, send: sendQueued(target, 20_000) });
876
+ await resumeHistory(target, { limit, cutter: outboxCut, confirmed: confirmedReceipt, note: noteReceipt, send: sendQueued(target, 20_000) });
778
877
  } catch (error) { if (process.env.WORKTRUST_HOOK_DEBUG) console.error(`worktrust: ${error.message}`); }
779
878
  }
780
879
 
@@ -837,10 +936,11 @@ function historyEntries(floor = null, all = false) {
837
936
  const lines = parsedLines(file);
838
937
  if (!lines) continue;
839
938
  let cwd = null, steered = null;
840
- const read = [];
939
+ const read = [], kind = sessionKindReader();
841
940
  for (const line of lines) {
842
941
  if (typeof line.cwd === "string") cwd = line.cwd;
843
942
  if (typeof line.steered === "string") steered = line.steered;
943
+ kind.note(line);
844
944
  if (!line.timestamp || (line.type !== "user" && line.type !== "assistant")) continue;
845
945
  const at = Date.parse(line.timestamp);
846
946
  if (!Number.isFinite(at)) continue;
@@ -848,7 +948,7 @@ function historyEntries(floor = null, all = false) {
848
948
  }
849
949
  read.sort((a, b) => a.at - b.at);
850
950
  const byDay = byDayOf(read);
851
- const agents = agentsByDay(file, null);
951
+ const agents = agentsByDay(file, null), session = kind.kind();
852
952
  for (const [day, messages] of byDay) {
853
953
  if (messages.length === 0) continue;
854
954
  // Under-reporting is the safe side (THE FLOORS): a day that began before the account changed is not offered at all.
@@ -857,7 +957,7 @@ function historyEntries(floor = null, all = false) {
857
957
  // The live window belongs to the hook: a stretch that log_work may still report is not history.
858
958
  if (!all && Date.now() - last < WINDOW_HOURS * 3600_000) continue;
859
959
  // The same measure as a live day (seconds, layers, tokens, turns, model); history differs only in the door it goes through.
860
- const entry = payloadFor({ ...measure(cwd, messages), ref: stretchRef(file, day), steered, agents: agents.get(day) ?? null, live: liveOf(file, day) });
960
+ const entry = payloadFor({ ...measure(cwd, messages), ref: stretchRef(file, day), steered, session, agents: agents.get(day) ?? null, live: liveOf(file, day) });
861
961
  if (CODEX_ROLLOUT.test(file)) entrySource.set(entry, "codex");
862
962
  if (ANTIGRAVITY_TRANSCRIPT.test(file)) entrySource.set(entry, "antigravity");
863
963
  if (DATABASE_SESSION.test(file)) entrySource.set(entry, file.slice(0, file.indexOf(":")));
@@ -1184,10 +1284,10 @@ if (!door && !codexDoor && !DRY) { return await exitFlushed(0); } // Not coupled
1184
1284
  */
1185
1285
  if (flag("history") && flag("resume")) {
1186
1286
  const { resumeHistory } = await import("./history-outbox.mjs");
1187
- const totals = { received: 0, review: 0, waiting: 0, batches: 0, refused: 0 };
1287
+ const totals = { received: 0, review: 0, waiting: 0, batches: 0, refused: 0, split: 0 };
1188
1288
  try {
1189
1289
  for (const target of [door, ...(codexDoor && codexDoor.token !== door?.token ? [codexDoor] : [])].filter(Boolean)) {
1190
- const result = await resumeHistory(target, { dry: DRY, retryReview: flag("retry-review"), confirmed: confirmedReceipt, note: noteReceipt, send: sendQueued(target) });
1290
+ const result = await resumeHistory(target, { dry: DRY, retryReview: flag("retry-review"), cutter: outboxCut, confirmed: confirmedReceipt, note: noteReceipt, send: sendQueued(target) });
1191
1291
  for (const key of Object.keys(totals)) totals[key] += result[key];
1192
1292
  }
1193
1293
  console.log(JSON.stringify({ resumed: totals.received, ...totals, ...RECEIPTS }));
@@ -1243,7 +1343,17 @@ if (flag("history")) {
1243
1343
  // ONE LINE FOR `npx worktrust` TO ASK WITH (2026-10-03): sessions, days, first and last month; per client its days (the rebuild's plan,
1244
1344
  // 2026-10-07); nothing sent. NO HOURS (0.10.20): the hours are WorkTrust's to compute; the receipt after the send carries them.
1245
1345
  const clients = [...entries.reduce((map, entry) => { const client = entrySource.get(entry) ?? "claude", row = map.get(client) ?? { client, days: new Set() }; row.days.add(entry.at.slice(0, 10)); return map.set(client, row); }, new Map()).values()].map((row) => ({ client: row.client, days: row.days.size, first: [...row.days].sort()[0], last: [...row.days].sort().at(-1) }));
1246
- if (flag("summary")) { console.log(JSON.stringify({ sessions: new Set(entries.map((entry) => entryFile.get(entry).file)).size, days: new Set(entries.map((entry) => entry.at.slice(0, 10))).size, first: months[0] ?? null, last: months.at(-1) ?? null, ...(fromExports ? { exports: fromExports.reports } : {}), ...(fromFolder ? { folder: fromFolder.report } : {}), clients })); return await exitFlushed(0); }
1346
+ if (flag("summary")) {
1347
+ // 0.10.29: the batches this send would make (lines, bytes, timeline bytes of each, the largest) and how many day-stretches carry
1348
+ // each session kind (`unknown`: none said, or no timeline to say it beside). Counts and sizes only, nothing of the work.
1349
+ const plan = historyPlan(door ?? codexDoor ?? { url: "", token: "" }, entries, flag("rebuild"), fromExports ? { byDay: true, withdrawUnknown: flag("withdraw-unknown") } : {});
1350
+ const sizes = plan.map((item) => ({ lines: item.batch.length, bytes: Buffer.byteLength(item.body, "utf8"), timeline_bytes: item.batch.reduce((n, entry) => n + timelineOfEntry(entry), 0) }));
1351
+ const kinds = { interactive: 0, headless: 0, scheduled: 0, unknown: 0 };
1352
+ for (const entry of entries) kinds[entry.session_kind ?? "unknown"] += 1;
1353
+ console.log(JSON.stringify({ sessions: new Set(entries.map((entry) => entryFile.get(entry)?.file)).size, days: new Set(entries.map((entry) => entry.at.slice(0, 10))).size, first: months[0] ?? null, last: months.at(-1) ?? null, ...(fromExports ? { exports: fromExports.reports } : {}), ...(fromFolder ? { folder: fromFolder.report } : {}), clients,
1354
+ batches: { count: sizes.length, largest_bytes: Math.max(0, ...sizes.map((one) => one.bytes)), largest_timeline_bytes: Math.max(0, ...sizes.map((one) => one.timeline_bytes)), largest_lines: Math.max(0, ...sizes.map((one) => one.lines)), each: sizes }, session_kinds: kinds }));
1355
+ return await exitFlushed(0);
1356
+ }
1247
1357
  console.log(`${entries.length} day-stretches · ${fromExports || fromFolder ? "reconstructed" : "measured"} by WorkTrust on arrival · ${months.join(", ")}${flag("rebuild") ? " · rebuild: this computer's earlier lines for these days and clients are replaced at the door" : ""}`);
1248
1358
  if (DRY) {
1249
1359
  // One example in full: the shape is the argument for trusting it, and a summary hides it.
@@ -1 +1 @@
1
- {"keyId":"608168ccdef72562fc91f9c0f9f2c2d6876bece7f7362cb545b818f7947da6b5","payload":{"files":{"AGENTS.md":"c6f5280c5bf81a14db4bdc282218fb005706e92dd9a9170c0e727716ee91685a","CLAUDE.md":"5933504f93e5a40369a4790e96dd5dad791d849d3178b1833eb64088e456aaeb","LICENSE":"3096ed1693974a90e1f4f59bf01c9559d94a7941d933e36fb81d3995a97f25c1","README.md":"cc8a27fbabea83b0fb1beabf5ecb88b22bd3b119f277962dbf5a2d8ceb0bdbcd","SECURITY.md":"b0cf3c839c918f3a403ae33e857c947fe62cbbad96bee6cac748bb42924839fc","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":"ba2a3976481100d2dd8e35c95e7ecbc8aa61c58d50a3bd1b1262971e0b42b459","history-outbox.mjs":"013885af8239da9fbd0f7fb339383f6dbcb462f439d8900c9290757f63fb597a","log-session.mjs":"87066a26e9d2d3947540b24e34139f63b25a1e4f8e13f389fa5e2d398893c368","orchestration-contract.mjs":"ec08f303a166365b99e70b675de4cfe76c6156c2567e14b5569f6d992f0231b7","orchestration-evidence.mjs":"d0d06cecf0eb08e5c6e653c62a4f45b1eddf2119c2acb8341056b34f488d214a","orchestration-report.mjs":"d4e0a9ad8e4a01b462d22c6b1866aac291565c533ff476085d3367cb6d59bc1b","package-integrity.mjs":"a8210c9494a56bfb9a5ea3d10064c7a269f0b6330c0af7c0700e706c3c0224e3","package.json":"38a2d376319d548668011efd51db7a43255923b33a742f6963262f3361832f00","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":"4fc0b26c65394591ef13a354c53792926c43a4c829357c6dac12570181ac0e47"},"format":"worktrust-package/1","kind":"npm","version":"0.10.27"},"signature":"P02S_9sBSMsXrW4AmS7ioWEj0ujkHw5HVxQUBAe-lT13zLTfxhp3xVcbjl1G98VextHoGPILd2cUNzDkm3E4CQ"}
1
+ {"keyId":"608168ccdef72562fc91f9c0f9f2c2d6876bece7f7362cb545b818f7947da6b5","payload":{"files":{"AGENTS.md":"c6f5280c5bf81a14db4bdc282218fb005706e92dd9a9170c0e727716ee91685a","CLAUDE.md":"5933504f93e5a40369a4790e96dd5dad791d849d3178b1833eb64088e456aaeb","LICENSE":"3096ed1693974a90e1f4f59bf01c9559d94a7941d933e36fb81d3995a97f25c1","README.md":"6b1932fe3e0dc1c167a964f60a4f7db6b667d5af87b1d71bca6df0d359ed7b42","SECURITY.md":"b0cf3c839c918f3a403ae33e857c947fe62cbbad96bee6cac748bb42924839fc","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":"28ad03e959e2bb94342629b25373e208fc482769a47d88d6ef7e9fce61304625","history-outbox.mjs":"b84e22542bb2d8195a469ee5f4116356ae9eac4a53ff2d40f0268b5b1de99dc5","log-session.mjs":"4da610744dfdd1aa939c231263fad9962288376bf8494ef3e0a08128e3d0cb17","orchestration-contract.mjs":"ec08f303a166365b99e70b675de4cfe76c6156c2567e14b5569f6d992f0231b7","orchestration-evidence.mjs":"d0d06cecf0eb08e5c6e653c62a4f45b1eddf2119c2acb8341056b34f488d214a","orchestration-report.mjs":"d4e0a9ad8e4a01b462d22c6b1866aac291565c533ff476085d3367cb6d59bc1b","package-integrity.mjs":"a8210c9494a56bfb9a5ea3d10064c7a269f0b6330c0af7c0700e706c3c0224e3","package.json":"863e796accfcb4a228afccb6f8c7a9c92748f9fb45848f42be7a32d093ee5194","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":"2f17bb5f234ccd630d51cf3f35c396d1b43240b601330cc3abb193effb5bfc3c","worktrust-launch.mjs":"84801bd29d472d48188c126b9ebe3989a3132b54e13cc4fe534ff7c383a294ee","worktrust.mjs":"9e3c21c144dfc8397da49cf04b0262c4f6e64619b4233a768bc928f6704026ec"},"format":"worktrust-package/1","kind":"npm","version":"0.10.29"},"signature":"IzmnxMIX-w2YY9j8qlkMYDG3iKGlSSgDNMHUZx9aOryhcEbB_NheH_MvvM3LMfgmMU5_aHPCd04dTB95a0aZBw"}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "worktrust",
3
- "version": "0.10.27",
3
+ "version": "0.10.29",
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": {
@@ -55,15 +55,60 @@ export const codexToolInput = (name, raw) => {
55
55
  };
56
56
  export const codexOutputText = (output) => (typeof output === "string" ? output : Array.isArray(output) ? output.map((part) => (typeof part === "string" ? part : part?.text ?? "")).join("\n") : "");
57
57
  /** The rollout's raw JSON lines → transcript-shaped line objects, in file order. */
58
+ /**
59
+ * HOW THE CODEX SESSION WAS STARTED (owner, 2026-10-22/27; docs/AGENT-HOURS.md), from the rollout's own `session_meta`: `cli`,
60
+ * `vscode` interactive; `exec`, `mcp` (another program's MCP server) and `{ subagent: … }` / `thread_source: "subagent"` (a thread an
61
+ * agent spawned: Agent operations) headless; no source: the `originator` (`codex_exec`, `codex_cli_rs`, `codex_vscode`); else unknown.
62
+ */
63
+ export const codexSessionKind = (source, meta = {}) => (source === "cli" || source === "vscode" ? "interactive" : source === "exec" || source === "mcp" || meta.thread_source === "subagent" || (source && typeof source === "object" && Object.hasOwn(source, "subagent")) ? "headless" : source == null ? (meta.originator === "codex_exec" ? "headless" : meta.originator === "codex_cli_rs" || meta.originator === "codex_vscode" ? "interactive" : "unknown") : "unknown");
64
+ /**
65
+ * HOW A SESSION WAS STARTED, READ LINE BY LINE (0.10.29; docs/AGENT-HOURS.md): interactive | headless | scheduled | unknown, only from
66
+ * what the AI app wrote, never a guess (WorkTrust counts headless and scheduled as Agent operations, never the person's hours; unknown
67
+ * is left unsaid). Claude Code: `entrypoint` on every line (`cli`, `claude-*` interactive; `sdk-cli` = `claude -p`, `sdk-ts`, `sdk-py`
68
+ * headless) and, on the person's role, `turnOrigin` / `origin.kind`. Not read (measured on 586 sessions): `promptSource: "sdk"` (it
69
+ * rides on editor sessions), `userType` (`external` on every line); a sidechain (subagent) line never decides the first turn.
70
+ * In order: (1) a headless entrypoint is headless, or scheduled when a timer started its first turn; (2) a turn marked `human`:
71
+ * interactive; (3) a first turn marked `scheduled`: scheduled; (4) a first turn from another program (`peer`, `coordinator`, a task
72
+ * notification, `system`): headless; (5) the entrypoint's or a reader's own word; (6) unknown. An unnamed value decides nothing.
73
+ */
74
+ const ORIGIN_OF = { human: "human", scheduled: "scheduled", task_notification: "program", "task-notification": "program", peer: "program", coordinator: "program", system: "program" };
75
+ const entrypointKind = (value) => (typeof value !== "string" ? null : /^sdk(-|$)/.test(value) ? "headless" : value === "cli" || /^claude-/.test(value) ? "interactive" : "unknown");
76
+ const SESSION_WORDS = new Set(["interactive", "headless", "scheduled", "unknown"]);
77
+ const onlyToolResults = (content) => Array.isArray(content) && content.length > 0 && content.every((part) => part?.type === "tool_result");
78
+ export function sessionKindReader() {
79
+ let entry = null, human = false, first;
80
+ return {
81
+ note(line) {
82
+ if (!line || typeof line !== "object") return;
83
+ // What the client said on the line: a reader's word (Codex), else Claude Code's entrypoint. Interactive wins over headless,
84
+ // headless over unknown (a session resumed by hand after `claude -p` is the person's).
85
+ const said = typeof line.sessionKind === "string" && SESSION_WORDS.has(line.sessionKind) ? line.sessionKind : entrypointKind(line.entrypoint);
86
+ if (said && entry !== "interactive") entry = said === "interactive" ? "interactive" : entry === null || entry === "unknown" ? said : entry;
87
+ if (line.type !== "user" || line.isSidechain === true || line.isMeta === true || line.isCompactSummary === true || onlyToolResults(line.message?.content)) return;
88
+ const origin = ORIGIN_OF[typeof line.turnOrigin === "string" ? line.turnOrigin : typeof line.origin?.kind === "string" ? line.origin.kind : ""] ?? null;
89
+ if (origin === "human") human = true;
90
+ if (first === undefined) first = origin; // the session's first turn, marked or not: an unmarked one decides nothing
91
+ },
92
+ kind() {
93
+ if (entry === "headless") return first === "scheduled" && !human ? "scheduled" : "headless";
94
+ if (human) return "interactive";
95
+ if (first === "scheduled") return "scheduled";
96
+ if (first === "program") return "headless";
97
+ return entry ?? "unknown";
98
+ },
99
+ };
100
+ }
101
+ /** One session's kind from its lines, in file order (the hook and the tests read it the same way). */
102
+ export const sessionKindOf = (lines) => { const reader = sessionKindReader(); for (const line of lines ?? []) reader.note(line); return reader.kind(); };
58
103
  export function* codexLines(records) {
59
- let cwd = null, model = null, mode = null;
104
+ let cwd = null, model = null, mode = null, sessionKind = null;
60
105
  const seenResponses = new Set();
61
106
  for (const raw of records) {
62
107
  if (!raw || !String(raw).trim()) continue;
63
108
  let record; try { record = JSON.parse(raw); } catch { continue; }
64
109
  const timestamp = typeof record?.timestamp === "string" ? record.timestamp : null;
65
110
  const payload = record?.payload && typeof record.payload === "object" ? record.payload : {};
66
- if (record.type === "session_meta") { if (typeof payload.cwd === "string") cwd = payload.cwd; continue; }
111
+ if (record.type === "session_meta") { if (typeof payload.cwd === "string") cwd = payload.cwd; sessionKind ??= codexSessionKind(payload.source, payload); continue; } // the rollout's own (first) meta: a fork's copied history never renames it
67
112
  if (record.type === "turn_context") {
68
113
  if (typeof payload.cwd === "string") cwd = payload.cwd; if (typeof payload.model === "string") model = payload.model;
69
114
  // 0.8.7: Codex's approval policy and sandbox, as one word on the common scale (never asks and full access is "full").
@@ -77,7 +122,7 @@ export function* codexLines(records) {
77
122
  if (!usage || typeof usage !== "object" || (id && seenResponses.has(id))) continue;
78
123
  if (id) seenResponses.add(id);
79
124
  const n = (key) => (typeof usage[key] === "number" && Number.isFinite(usage[key]) ? usage[key] : 0);
80
- yield { type: "assistant", timestamp, cwd, uuid: id ? `codex-usage-${id}` : undefined, message: { ...(model ? { model } : {}), content: [], usage: { input_tokens: Math.max(0, n("input_tokens") - n("cached_input_tokens")), output_tokens: n("output_tokens"), cache_read_input_tokens: n("cached_input_tokens"), cache_creation_input_tokens: n("cache_write_input_tokens") } } };
125
+ yield { ...(sessionKind ? { sessionKind } : {}), type: "assistant", timestamp, cwd, uuid: id ? `codex-usage-${id}` : undefined, message: { ...(model ? { model } : {}), content: [], usage: { input_tokens: Math.max(0, n("input_tokens") - n("cached_input_tokens")), output_tokens: n("output_tokens"), cache_read_input_tokens: n("cached_input_tokens"), cache_creation_input_tokens: n("cache_write_input_tokens") } } };
81
126
  continue;
82
127
  }
83
128
  if (record.type !== "response_item") continue;
@@ -86,18 +131,18 @@ export function* codexLines(records) {
86
131
  if (payload.role !== "user" && payload.role !== "assistant") continue;
87
132
  const text = Array.isArray(payload.content) ? payload.content.filter((part) => typeof part?.text === "string").map((part) => part.text).join("\n") : typeof payload.content === "string" ? payload.content : "";
88
133
  if (payload.role === "user" && CODEX_HARNESS_TURN.test(text)) continue;
89
- yield { type: payload.role, timestamp, cwd, ...(mode ? { permissionMode: mode } : {}), uuid: payload.id ? `codex-${payload.id}` : undefined, message: { ...(payload.role === "assistant" && model ? { model } : {}), content: [{ type: "text", text }] } };
134
+ yield { ...(sessionKind ? { sessionKind } : {}), type: payload.role, timestamp, cwd, ...(mode ? { permissionMode: mode } : {}), uuid: payload.id ? `codex-${payload.id}` : undefined, message: { ...(payload.role === "assistant" && model ? { model } : {}), content: [{ type: "text", text }] } };
90
135
  continue;
91
136
  }
92
137
  if (kind === "custom_tool_call" || kind === "function_call") {
93
138
  const input = kind === "function_call" ? (() => { try { return JSON.parse(payload.arguments ?? "{}"); } catch { return {}; } })() : payload.input;
94
- yield { type: "assistant", timestamp, cwd, uuid: payload.id ? `codex-${payload.id}` : undefined, message: { ...(model ? { model } : {}), content: [{ type: "tool_use", ...(payload.call_id ? { id: String(payload.call_id) } : {}), name: codexToolName(payload.name), input: codexToolInput(payload.name, input) }] } };
139
+ yield { ...(sessionKind ? { sessionKind } : {}), type: "assistant", timestamp, cwd, uuid: payload.id ? `codex-${payload.id}` : undefined, message: { ...(model ? { model } : {}), content: [{ type: "tool_use", ...(payload.call_id ? { id: String(payload.call_id) } : {}), name: codexToolName(payload.name), input: codexToolInput(payload.name, input) }] } };
95
140
  continue;
96
141
  }
97
142
  if (kind === "custom_tool_call_output" || kind === "function_call_output") {
98
143
  const text = codexOutputText(payload.output);
99
144
  const exit = /(?:failed with|exited with|exit code)[:\s]+(-?\d+)/i.exec(text.slice(-400));
100
- yield { type: "user", timestamp, cwd, uuid: payload.id ? `codex-${payload.id}` : undefined, message: { content: [{ type: "tool_result", ...(payload.call_id ? { tool_use_id: String(payload.call_id) } : {}), content: text, is_error: exit ? exit[1] !== "0" : false, ...(exit ? {} : { outcome: "unknown" }) }] } }; // 0.8.5: no exit code (Codex code mode never prints one) is an unknown outcome, never a pass
145
+ yield { ...(sessionKind ? { sessionKind } : {}), type: "user", timestamp, cwd, uuid: payload.id ? `codex-${payload.id}` : undefined, message: { content: [{ type: "tool_result", ...(payload.call_id ? { tool_use_id: String(payload.call_id) } : {}), content: text, is_error: exit ? exit[1] !== "0" : false, ...(exit ? {} : { outcome: "unknown" }) }] } }; // 0.8.5: no exit code (Codex code mode never prints one) is an unknown outcome, never a pass
101
146
  }
102
147
  }
103
148
  }
package/worktrust.mjs CHANGED
@@ -75,7 +75,7 @@ const command = args.includes("--help") ? "help" : args.includes("--version") ?
75
75
  const flag = (name) => { const at = args.indexOf(`--${name}`); return at >= 0 ? args[at + 1] : undefined; };
76
76
  const has = (name) => args.includes(`--${name}`);
77
77
  /** This CLI's version, said to the door so the app can tell which computer runs an old one (check-cli-package holds it equal to package.json). */
78
- const CLI_VERSION = "0.10.27";
78
+ const CLI_VERSION = "0.10.29";
79
79
  const ORIGIN = (flag("origin") ?? process.env.WORKTRUST_ORIGIN ?? "https://app.worktrust.io").replace(/\/$/, "");
80
80
  const MCP = flag("url") ?? process.env.WORKTRUST_MCP_URL ?? `${ORIGIN}/api/mcp`;
81
81
  const HOME_DIR = join(homedir(), ".worktrust");
@@ -707,10 +707,15 @@ async function offerHistory(paths, token, devicePem, url = MCP, rebuild = false)
707
707
  // "replaced". The hook sums the receipts of every batch and prints one line; without it (an older hook) the sentence stays neutral.
708
708
  const did = (() => { try { return JSON.parse(sent.out.trim().split("\n").reverse().find((line) => line.startsWith('{"history_sent"')) ?? "null"); } catch { return null; } })();
709
709
  const n = (value) => Number(value) || 0;
710
+ // AN HONEST RECEIPT (owner, 2026-10-22; 0.10.28): a re-measure that landed as new lines over lines WorkTrust had withdrawn or
711
+ // cut off is said as new lines, never as "Nothing changed"; `restored` counts the ones WorkTrust landed over a support-withdrawn
712
+ // original with its own clock (the withdrawn line stays withdrawn). `untimed` names entries refused for carrying no timeline.
713
+ const landed = n(did.new) + n(did.restored);
710
714
  const outcome = !did ? "The record shows what changed."
711
- : n(did.replaced) > 0 ? `${n(did.replaced)} of this computer's earlier lines were replaced (withdrawn and kept, never deleted)${n(did.new) > 0 ? `, ${n(did.new)} new` : ""}${n(did.filled) > 0 ? `, ${n(did.filled)} lines gained what was missing` : ""}.`
712
- : n(did.new) === 0 ? `Nothing changed: the same measurement${n(did.filled) > 0 ? `; ${n(did.filled)} lines gained what was missing (the stack, the tools seen, a layer)` : ""}; ${n(did.alreadyHeld)} lines already held.`
713
- : `${n(did.new)} new lines${n(did.filled) > 0 ? `, ${n(did.filled)} lines gained what was missing` : ""}; ${n(did.alreadyHeld)} already held.`;
715
+ : n(did.replaced) > 0 ? `${n(did.replaced)} of this computer's earlier lines were replaced (withdrawn and kept, never deleted)${landed > 0 ? `, ${landed} new` : ""}${n(did.filled) > 0 ? `, ${n(did.filled)} lines gained what was missing` : ""}.`
716
+ : landed === 0 ? `Nothing changed: the same measurement${n(did.filled) > 0 ? `; ${n(did.filled)} lines gained what was missing (the stack, the tools seen, a layer)` : ""}; ${n(did.alreadyHeld)} lines already held.`
717
+ : `${landed} new lines${n(did.restored) > 0 ? ` (${n(did.restored)} timed by WorkTrust in place of lines it had withdrawn)` : ""}${n(did.filled) > 0 ? `, ${n(did.filled)} lines gained what was missing` : ""}; ${n(did.alreadyHeld)} already held.`;
718
+ if (n(did?.untimed) > 0) say(` ${n(did.untimed)} lines were refused: they carried no timeline, so WorkTrust could not time them itself. This CLI sends every session's timeline; a line without one came from an older copy or an archive.`);
714
719
  if (Number(did?.delivery?.review) > 0) say(` ${did.delivery.review} lines are waiting for review. Earlier measurements remain unchanged. Reconnecting or repeating the import does not approve them.`);
715
720
  // KEPT ON THE SERVER (0.10.27; owner, 2026-10-21): what did not arrive stays here and goes again by itself; nothing to resume by hand.
716
721
  if (Number(did?.delivery?.waiting) > 0) say(" Some batches did not reach WorkTrust yet. They stay on this computer and are sent again by themselves the next time npx worktrust or your AI app's hook runs.");