worktrust 0.10.28 → 0.10.30

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,45 @@
1
1
  # worktrust
2
2
 
3
+ ## 0.10.30: an update asks only what is new
4
+
5
+ `update` remembers what you said yes to. Each AI app's WorkTrust door, the session hook, Codex's `notify` line and
6
+ Antigravity's `Stop` hook that you agreed to are brought onto the new version without a question, each printed as
7
+ `✓ … refreshed (you agreed on <date>)`. Only the launcher's path changes; nothing else about what was agreed. A NEW AI
8
+ app, or a wake hook that is no longer there (you took it out), is shown in full and asked about; `--yes` leaves it as
9
+ it is and lists it as `skipped: new, run without --yes to decide`. A No drops the agreement, and `disconnect` deletes
10
+ the record. It is one small file, `~/.worktrust/consent.json` (see [SECURITY.md](SECURITY.md)). The first update that
11
+ keeps it counts the WorkTrust entries already on this computer as agreed, because only a yes ever wrote them.
12
+
13
+ The re-measure after a new version is one question, asked after its plan (the plan is counted on this computer and
14
+ sends nothing): `Send them (re-measured; …)? [y/N]`. Enter and `--yes` are No. `--rebuild` agrees in advance.
15
+
16
+ One line that updates a computer you coupled before, with no question at all:
17
+
18
+ ```
19
+ npx -y worktrust@latest update --yes --rebuild
20
+ ```
21
+
22
+ - `npx -y`: npm's own flag. It answers npm's `Ok to proceed?` before it downloads the package; WorkTrust never sees it.
23
+ - `worktrust@latest`: the newest published version, never a copy npm cached earlier.
24
+ - `update`: this computer onto that version, the same key, no new pairing.
25
+ - `--yes`: every question whose answer is Yes by default. Anything new stays as it is (skipped, and listed).
26
+ - `--rebuild`: yes in advance to re-measuring this computer's sessions with the new version's rules. WorkTrust
27
+ replaces this computer's earlier lines for those days, each withdrawn and kept, never deleted. Leave it out to
28
+ be asked.
29
+ - `--codex` and `--antigravity` say yes in advance to a NEW Codex or Antigravity wake hook as well.
30
+
31
+ ## 0.10.29: history in calls WorkTrust takes; how each session was started
32
+
33
+ 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
34
+ version queued larger, or one WorkTrust answers with 413, is cut smaller in `~/.worktrust/history-outbox` and sent in
35
+ 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
36
+ part of, or one line too large for any call, is let go and counted, and `npx worktrust@latest history` measures again.
37
+
38
+ Each line now says how its session was started, as the AI app recorded it: `interactive`, `headless` (`claude -p`, an
39
+ Agent SDK program, `codex exec`, a Codex subagent) or `scheduled` (a timer started it), beside its timeline. A session
40
+ the app said nothing about is left unsaid. WorkTrust counts a headless or scheduled session as Agent operations, never
41
+ as the person's hours. `--history --dry-run --summary` prints the planned batches and the session kinds, counts only.
42
+
3
43
  ## 0.10.28: an honest receipt for a re-measure
4
44
 
5
45
  A re-measure that lands as new lines over lines WorkTrust had withdrawn (support's withdrawal of client-computed
@@ -324,9 +364,9 @@ sends them with one difference: WorkTrust **replaces** this computer's earlier l
324
364
  - **Only from this computer's own key.** A connector (an AI signed in on the web) cannot ask for a rebuild; WorkTrust
325
365
  refuses it at the door.
326
366
  - **Offered once by `update`.** When this computer's earlier lines were made by an earlier version (the copy in
327
- `~/.worktrust` says which), `npx worktrust@latest update` says so in plain words and offers the rebuild; Enter is No,
328
- and the same version updated again offers nothing. The command cannot read your record, so it is an offer, not a
329
- finding.
367
+ `~/.worktrust` says which), `npx worktrust@latest update` says so in plain words, shows the plan and asks once
368
+ (0.10.30); Enter and `--yes` are No, `--rebuild` agrees in advance, and the same version updated again offers
369
+ nothing. The command cannot read your record, so it is an offer, not a finding.
330
370
 
331
371
  ## A web chat's data export
332
372
 
@@ -449,9 +489,9 @@ retried safely. A row kept pending on WorkTrust remains excluded from counted ac
449
489
  | | |
450
490
  |---|---|
451
491
  | **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. |
452
- | **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/`. |
492
+ | **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/`; and `~/.worktrust/consent.json`, what you agreed to (names and days only, 0.10.30). |
453
493
  | **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). |
454
- | **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), 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). |
494
+ | **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). |
455
495
  | **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. |
456
496
 
457
497
  **The clock is WorkTrust's, not this computer's (0.10.20).** A measured stretch travels as its timeline: one step per
@@ -497,7 +537,8 @@ never as proof.
497
537
  ## Undo
498
538
 
499
539
  `npx worktrust@latest disconnect` removes the WorkTrust entries (Hermes's hook with them), the hook (and Codex's `notify` line and
500
- Antigravity's `worktrust` hook when WorkTrust set them), the credentials and installed bridge scripts.
540
+ Antigravity's `worktrust` hook when WorkTrust set them), the credentials, installed bridge scripts and the record of
541
+ what you agreed to (`~/.worktrust/consent.json`, 0.10.30).
501
542
  Protected mode retains an encrypted empty slot and its OS wrapping key so reconnecting stays protected.
502
543
  A small note of the previous account (masked) remains so that a later coupling by another account
503
544
  does not offer its earlier work. Other retained files and your local evidence archive are not an
package/SECURITY.md CHANGED
@@ -56,6 +56,23 @@ private transcripts or account data in a public issue.
56
56
  - Local `disconnect` is distinct from server revocation and archive deletion. Revoke through
57
57
  WorkTrust's device settings when the server credential must stop working.
58
58
 
59
+ ## What you agreed to: `~/.worktrust/consent.json` (0.10.30)
60
+
61
+ - One private file (mode 0600, written through the same exclusive-temp, atomic-replace path as the credential file,
62
+ refused when it is a link or not owned by you). Per coupling you said yes to it holds a NAME only
63
+ (`door:<app>` such as `door:Cursor`, `session-hook`, `codex-notify`, `antigravity-stop`), the day, the CLI version
64
+ and how the yes was given (`typed`, `flag` for `--yes`, `--codex` or `--antigravity` said in advance, `found` for a
65
+ WorkTrust entry already on the computer when the file was first made). No key, no token, no path, no command and
66
+ nothing of any config file. It is never sent.
67
+ - What it changes: `update` refreshes an agreed entry without asking when only the launcher's path moves. It never
68
+ turns a new AI app or a wake hook that is no longer there into a yes: those are asked about, and `--yes` skips them.
69
+ It is never read as agreement to send anything: the re-measure of earlier history still needs a typed `y` or
70
+ `--rebuild`, every time a new version offers it.
71
+ - Who can change it: anyone who can write your home folder, which can already edit the AI apps' settings directly.
72
+ A forged entry can at most spare the question for a write WorkTrust would offer anyway (the door in an AI app found
73
+ here, a wake hook); it cannot widen what is written, sent or read. An unreadable or unsafe file counts as no agreement.
74
+ - A No drops the entry it answered; `disconnect` deletes the file; a coupling to another account starts it empty.
75
+
59
76
  ## What measurement signatures establish
60
77
 
61
78
  The metadata journal introduced in the 0.10.21 candidate preserves observations, not their
@@ -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":"11d005f6a87b821c66f006ff62d06d43fcb2cf381305fd5705908ab65ab7f5d0","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":"e79368c66a5eb2c99c07fdd2498efc0e0b7a5bea3e71ad21a0262da5bc42d446"},"format":"worktrust-package/1","kind":"engine","version":"0.10.28"},"signature":"pl6yOiAY_MOFDH6d8Fp8SzlIVziC6DFlWI2tmoz5QU3eys3APzf8pLZbOcIGwQTJsKQt25TXOHzhEQ3i5mbLCg"}
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":"0c29113179561af1c1e9ff8b7a786e7240edf48a2244993e12335e5ee362c812","stack-rules.mjs":"b23c56e72ec56ba02b17ed895f869172d988c468a697e8d6026b0e268f61e489","stretch-evidence.mjs":"5b31a6f29b785d277e92257532f3c7cee366a79759decc7a75cfbaec2686ee13","transcript-readers.mjs":"2f17bb5f234ccd630d51cf3f35c396d1b43240b601330cc3abb193effb5bfc3c","worktrust-launch.mjs":"84801bd29d472d48188c126b9ebe3989a3132b54e13cc4fe534ff7c383a294ee","worktrust.mjs":"7ed5f7a4f50b386943b4848d4ed1065b61541f8953bed52eb00fdac04187afcf"},"format":"worktrust-package/1","kind":"engine","version":"0.10.30"},"signature":"2rFv0Weq_38gvPDk01zX1siW_IFFLEjrI_8CA1DMD0cJL8FrLlb6rXQaAsQKV-qXlZf8ASNPWa5YMqcp674aCA"}
@@ -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
@@ -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)) ?? {};
@@ -368,6 +368,13 @@ const pathsTouched = (cwd, from, to) => {
368
368
  * boundary the history path already uses, it needs no guess about where one piece of work ended,
369
369
  * and it is the unit the record reads back anyway.
370
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
+ */
371
378
  function stretchesOf(file, since) {
372
379
  // A file we cannot read is no days, never a null the caller has to remember to check: this
373
380
  // returns a list now, and one caller forgetting that is one silent crash inside a hook.
@@ -375,9 +382,11 @@ function stretchesOf(file, since) {
375
382
  if (!lines) return [];
376
383
  const messages = [];
377
384
  let cwd = null, steered = STEERED_HERE;
385
+ const kind = sessionKindReader();
378
386
  for (const line of lines) {
379
387
  if (typeof line.cwd === "string") cwd = line.cwd;
380
388
  if (typeof line.steered === "string") steered = line.steered; // a client that says how it was steered (Hermes's source)
389
+ kind.note(line);
381
390
  if (!line.timestamp || (line.type !== "user" && line.type !== "assistant")) continue;
382
391
  const at = Date.parse(line.timestamp);
383
392
  if (!Number.isFinite(at)) continue;
@@ -387,8 +396,8 @@ function stretchesOf(file, since) {
387
396
  if (messages.length === 0) return [];
388
397
  messages.sort((a, b) => a.at - b.at);
389
398
  const byDay = byDayOf(messages);
390
- const agents = agentsByDay(file, since);
391
- 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);
392
401
  }
393
402
 
394
403
  /**
@@ -636,6 +645,8 @@ function payloadFor(stretch) {
636
645
  ...(repoCode ? { repo_code: repoCode } : {}),
637
646
  ...(touched.shas.length > 0 ? { commits: touched.shas.slice(0, 50) } : {}),
638
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 } : {}),
639
650
  // WHICH CODE SENT IT (0.10.20): a version and a digest of this hook's own files, signals never proof.
640
651
  ...(CLI_VERSION_SENT ? { cli_version: CLI_VERSION_SENT } : {}),
641
652
  ...(selfDigest ? { cli_digest: selfDigest } : {}),
@@ -664,18 +675,31 @@ function payloadFor(stretch) {
664
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
665
676
  * day in two batches would be counted twice.
666
677
  */
667
- /** 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. */
668
- 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 };
669
687
  const bytesOf = (entry) => Buffer.byteLength(JSON.stringify(entry), "utf8");
670
- 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; };
671
- function batchesOf(group, byDay) {
672
- 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);
673
696
  const days = new Map();
674
697
  for (const entry of group) { const day = String(entry.at).slice(0, 10); days.set(day, [...(days.get(day) ?? []), entry]); }
675
698
  const out = []; let current = [];
676
699
  for (const ofDay of days.values()) {
677
- 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; }
678
- 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 = []; }
679
703
  current.push(...ofDay);
680
704
  }
681
705
  if (current.length) out.push(current);
@@ -743,10 +767,11 @@ const historyRunId = (bodies) => {
743
767
  const h = createHash("sha256").update(`worktrust-history-run|${new Date().toISOString().slice(0, 10)}|${bodies.join("\n")}`).digest("hex");
744
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)}`;
745
769
  };
746
- async function sendHistory(door, entries, announce = false, rebuild = false, named = false, { byDay = false, withdrawUnknown = false } = {}) {
747
- let accepted = 0;
748
- const { queuedHistory, historyRefusal } = await import("./history-outbox.mjs");
749
- // 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 } = {}) {
750
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)])];
751
776
  // Imported entries carry no live commit/session join.
752
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 } : {}) } } });
@@ -756,12 +781,47 @@ async function sendHistory(door, entries, announce = false, rebuild = false, nam
756
781
  run.forEach((item, index) => { item.run = { id, index, count: run.length }; });
757
782
  }
758
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 });
759
813
  // Persist the approved plan before sending, so later batches survive removed source files too.
760
814
  try { for (const item of plan) queuedHistory(item.target, item.body, item.source); }
761
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; }
762
816
  const numbers = new Map(), stopped = new Set();
763
- 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;
764
823
  if (stopped.has(source)) continue;
824
+ if (item.run && stoppedRuns.has(item.run.id)) { handLater(item); continue; }
765
825
  const number = (numbers.get(source) ?? 0) + 1; numbers.set(source, number);
766
826
  for (const entry of batch) retainMeasurement(entry, source);
767
827
  // `named` (0.10.10): a copied folder's lines name their client too, so the record says which app the copy came from.
@@ -769,6 +829,7 @@ async function sendHistory(door, entries, announce = false, rebuild = false, nam
769
829
  try { queued = queuedHistory(target, body, source); }
770
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; }
771
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; }
772
833
  if (queued.status === "review" && !flag("retry-review")) { HISTORY_DELIVERY.review += batch.length; continue; }
773
834
  if (queued.status === "waiting") { HISTORY_DELIVERY.waiting += batch.length; continue; }
774
835
  try {
@@ -779,14 +840,24 @@ async function sendHistory(door, entries, announce = false, rebuild = false, nam
779
840
  const refusal = historyRefusal(text, response);
780
841
  // A run WorkTrust closed (seven days without its last batch, another computer's key) is final: kept here it would wait forever.
781
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; }
782
844
  queued.defer(refusal.reason, refusal.seconds);
783
845
  if (refusal.reason === "review") { HISTORY_DELIVERY.review += batch.length; continue; }
784
846
  HISTORY_DELIVERY.waiting += batch.length; stopped.add(source); continue;
785
847
  }
786
- queued.confirm(); accepted += batch.length; noteReceipt(text);
848
+ queued.confirm(batch.length); accepted += batch.length; noteReceipt(text);
787
849
  if (announce) console.log(`batch ${number}: received ${batch.length}`);
788
850
  } catch { queued.defer("unconfirmed"); HISTORY_DELIVERY.waiting += batch.length; stopped.add(source); }
789
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
+ }
790
861
  return accepted;
791
862
  }
792
863
 
@@ -802,7 +873,7 @@ async function resendPending(limit) {
802
873
  try {
803
874
  const { resumeHistory } = await import("./history-outbox.mjs");
804
875
  for (const target of [door, ...(codexDoor && codexDoor.token !== door?.token ? [codexDoor] : [])].filter(Boolean))
805
- 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) });
806
877
  } catch (error) { if (process.env.WORKTRUST_HOOK_DEBUG) console.error(`worktrust: ${error.message}`); }
807
878
  }
808
879
 
@@ -865,10 +936,11 @@ function historyEntries(floor = null, all = false) {
865
936
  const lines = parsedLines(file);
866
937
  if (!lines) continue;
867
938
  let cwd = null, steered = null;
868
- const read = [];
939
+ const read = [], kind = sessionKindReader();
869
940
  for (const line of lines) {
870
941
  if (typeof line.cwd === "string") cwd = line.cwd;
871
942
  if (typeof line.steered === "string") steered = line.steered;
943
+ kind.note(line);
872
944
  if (!line.timestamp || (line.type !== "user" && line.type !== "assistant")) continue;
873
945
  const at = Date.parse(line.timestamp);
874
946
  if (!Number.isFinite(at)) continue;
@@ -876,7 +948,7 @@ function historyEntries(floor = null, all = false) {
876
948
  }
877
949
  read.sort((a, b) => a.at - b.at);
878
950
  const byDay = byDayOf(read);
879
- const agents = agentsByDay(file, null);
951
+ const agents = agentsByDay(file, null), session = kind.kind();
880
952
  for (const [day, messages] of byDay) {
881
953
  if (messages.length === 0) continue;
882
954
  // Under-reporting is the safe side (THE FLOORS): a day that began before the account changed is not offered at all.
@@ -885,7 +957,7 @@ function historyEntries(floor = null, all = false) {
885
957
  // The live window belongs to the hook: a stretch that log_work may still report is not history.
886
958
  if (!all && Date.now() - last < WINDOW_HOURS * 3600_000) continue;
887
959
  // The same measure as a live day (seconds, layers, tokens, turns, model); history differs only in the door it goes through.
888
- 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) });
889
961
  if (CODEX_ROLLOUT.test(file)) entrySource.set(entry, "codex");
890
962
  if (ANTIGRAVITY_TRANSCRIPT.test(file)) entrySource.set(entry, "antigravity");
891
963
  if (DATABASE_SESSION.test(file)) entrySource.set(entry, file.slice(0, file.indexOf(":")));
@@ -1212,10 +1284,10 @@ if (!door && !codexDoor && !DRY) { return await exitFlushed(0); } // Not coupled
1212
1284
  */
1213
1285
  if (flag("history") && flag("resume")) {
1214
1286
  const { resumeHistory } = await import("./history-outbox.mjs");
1215
- 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 };
1216
1288
  try {
1217
1289
  for (const target of [door, ...(codexDoor && codexDoor.token !== door?.token ? [codexDoor] : [])].filter(Boolean)) {
1218
- 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) });
1219
1291
  for (const key of Object.keys(totals)) totals[key] += result[key];
1220
1292
  }
1221
1293
  console.log(JSON.stringify({ resumed: totals.received, ...totals, ...RECEIPTS }));
@@ -1271,7 +1343,17 @@ if (flag("history")) {
1271
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,
1272
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.
1273
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) }));
1274
- 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
+ }
1275
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" : ""}`);
1276
1358
  if (DRY) {
1277
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":"7216321b23aa02817322944fcfd76e26d9aa3620695e18e36fbf73b7fef78c7b","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":"0a08942197df86503fd8d171c22127046026d070af381201ae0a6c2f379e8107","history-outbox.mjs":"013885af8239da9fbd0f7fb339383f6dbcb462f439d8900c9290757f63fb597a","log-session.mjs":"11d005f6a87b821c66f006ff62d06d43fcb2cf381305fd5705908ab65ab7f5d0","orchestration-contract.mjs":"ec08f303a166365b99e70b675de4cfe76c6156c2567e14b5569f6d992f0231b7","orchestration-evidence.mjs":"d0d06cecf0eb08e5c6e653c62a4f45b1eddf2119c2acb8341056b34f488d214a","orchestration-report.mjs":"d4e0a9ad8e4a01b462d22c6b1866aac291565c533ff476085d3367cb6d59bc1b","package-integrity.mjs":"a8210c9494a56bfb9a5ea3d10064c7a269f0b6330c0af7c0700e706c3c0224e3","package.json":"09c69b353ef8fe916c9b5ccad9e7050146651f7f6cf028b75ab7e05358c39c70","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":"e79368c66a5eb2c99c07fdd2498efc0e0b7a5bea3e71ad21a0262da5bc42d446"},"format":"worktrust-package/1","kind":"npm","version":"0.10.28"},"signature":"W4F1Gr-yudsBRtwEEO3qym7ktxPZMrzicMU3vY20FfYOCjbNqnxsEYWYPzAskhq0btJ2FyM_HNKEkZpelI__CA"}
1
+ {"keyId":"608168ccdef72562fc91f9c0f9f2c2d6876bece7f7362cb545b818f7947da6b5","payload":{"files":{"AGENTS.md":"c6f5280c5bf81a14db4bdc282218fb005706e92dd9a9170c0e727716ee91685a","CLAUDE.md":"5933504f93e5a40369a4790e96dd5dad791d849d3178b1833eb64088e456aaeb","LICENSE":"3096ed1693974a90e1f4f59bf01c9559d94a7941d933e36fb81d3995a97f25c1","README.md":"ba9f69395ecb09fb0272f6ced835cff5c1a9ae18e296434da80bd3820dff5874","SECURITY.md":"a7f1187b4f384a71e1f69cb25327487597969c0b0422b377dd4c72086b1b9ad9","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":"5838696d584288739d3950fa3bf435e0add7f17e341c26376ac4a84afb93bbcc","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":"ad4556d952977e5e68daa66128b246b9f27c17dc6858fb80dfb4bc34a2694b40","preserve-lines.mjs":"2df64a69687aa51219bf7b86b88d175cc50990fa29574b31897e41a9ebeecf43","preserve-summary.mjs":"137f781ed7021596a3f0ea67afcf2ab8616ac293f833dbb8f176e838e0ed8321","preserve.mjs":"3e369083ba43bcda2fa0622fd526aa64fcf8ad66e7b6e8f23821752c4d47ad27","runtime-install.mjs":"aab47b52c79d726ef428a24f982c648fa3f1c2dc2b574f633611d02924864e5f","session-databases.mjs":"543fd3b82d28d96d789be0a1dc9186c5fafa783e98b87e5b3b17b211542e2b4d","setup-mcp.mjs":"0c29113179561af1c1e9ff8b7a786e7240edf48a2244993e12335e5ee362c812","stack-rules.mjs":"b23c56e72ec56ba02b17ed895f869172d988c468a697e8d6026b0e268f61e489","stretch-evidence.mjs":"5b31a6f29b785d277e92257532f3c7cee366a79759decc7a75cfbaec2686ee13","transcript-readers.mjs":"2f17bb5f234ccd630d51cf3f35c396d1b43240b601330cc3abb193effb5bfc3c","worktrust-launch.mjs":"84801bd29d472d48188c126b9ebe3989a3132b54e13cc4fe534ff7c383a294ee","worktrust.mjs":"7ed5f7a4f50b386943b4848d4ed1065b61541f8953bed52eb00fdac04187afcf"},"format":"worktrust-package/1","kind":"npm","version":"0.10.30"},"signature":"hTe1ztpzEICp88drixUXrlKWTZPJvvzn0FUXMSLlg6Tu9daRjsS34r8N7XCT4KBH4zd-o1E1j6IPto7cKTkDDg"}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "worktrust",
3
- "version": "0.10.28",
3
+ "version": "0.10.30",
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": {
package/setup-mcp.mjs CHANGED
@@ -26,6 +26,8 @@ const value = (name) => { const i = args.indexOf(`--${name}`); return i >= 0 ? a
26
26
  const WRITE = args.includes("--write");
27
27
  const REMOVE = args.includes("--remove");
28
28
  const NAME = value("name") ?? "worktrust";
29
+ /** `--skip "Cursor,Zed"` (0.10.30): apps the person has not agreed to yet are left exactly as they are, in and out. */
30
+ const SKIP = new Set((value("skip") ?? "").split(",").map((label) => label.trim()).filter(Boolean));
29
31
  /**
30
32
  * THE BRIDGE (2026-10-03). With `--bridge <path to worktrust.mjs>` no client is given a key: each
31
33
  * gets a local command (`node worktrust.mjs mcp`) that reads the key from ~/.worktrust/key.json
@@ -217,6 +219,7 @@ let touched = 0;
217
219
  let standing = 0;
218
220
  for (const client of CLIENTS) {
219
221
  if (!client.present()) { console.log(` – ${client.label}: not on this machine`); continue; }
222
+ if (SKIP.has(client.label)) { console.log(` · ${client.label}: left as it is (not agreed yet)`); continue; }
220
223
  if (client.shape === "openclaw") {
221
224
  const text = existsSync(client.file) ? readFileSync(client.file, "utf8") : "";
222
225
  const named = new RegExp(`["']?${NAME}["']?\\s*:\\s*\\{`).test(text) && ours(text);
@@ -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
@@ -8,7 +8,8 @@
8
8
  * npx worktrust --yes no question (for scripts); the computer is still approved in the app
9
9
  * npx worktrust --device a computer without a browser (SSH): type a code on another device
10
10
  * npx worktrust connect couple again, also on a computer already coupled
11
- * npx worktrust update this computer onto the newest CLI, same key, no new pairing
11
+ * npx worktrust update this computer onto the newest CLI, same key, no new pairing (0.10.30: what
12
+ * was agreed before is refreshed unasked; --rebuild agrees to the re-measure)
12
13
  * npx worktrust history send this computer's earlier sessions as history (asks first)
13
14
  * npx worktrust history --rebuild the same as history (0.10.5: history always re-measures); WorkTrust replaces this computer's
14
15
  * earlier lines day by day, never counting a day twice (shows the plan, asks first)
@@ -75,7 +76,7 @@ const command = args.includes("--help") ? "help" : args.includes("--version") ?
75
76
  const flag = (name) => { const at = args.indexOf(`--${name}`); return at >= 0 ? args[at + 1] : undefined; };
76
77
  const has = (name) => args.includes(`--${name}`);
77
78
  /** This CLI's version, said to the door so the app can tell which computer runs an old one (check-cli-package holds it equal to package.json). */
78
- const CLI_VERSION = "0.10.28";
79
+ const CLI_VERSION = "0.10.30";
79
80
  const ORIGIN = (flag("origin") ?? process.env.WORKTRUST_ORIGIN ?? "https://app.worktrust.io").replace(/\/$/, "");
80
81
  const MCP = flag("url") ?? process.env.WORKTRUST_MCP_URL ?? `${ORIGIN}/api/mcp`;
81
82
  const HOME_DIR = join(homedir(), ".worktrust");
@@ -330,6 +331,64 @@ const previousNote = {
330
331
  erase() { try { rmSync(PREVIOUS_FILE); } catch { /* gone */ } },
331
332
  };
332
333
 
334
+ /**
335
+ * WHAT THE PERSON ALREADY AGREED TO (0.10.30, owner 2026-10-28: "an update should need fewer y + Enter"). One small file,
336
+ * ~/.worktrust/consent.json (0600): per coupling the person said yes to, its name only (`door:<app>`, `session-hook`,
337
+ * `codex-notify`, `antigravity-stop`), the day, the CLI version and how (`typed`, `flag`: --yes / --codex / --antigravity
338
+ * said in advance, `found`: a WorkTrust entry already here when this file was first made, which only a yes ever wrote).
339
+ * Never a key, a path or a config's content. `update` refreshes an agreed entry whose only change is the launcher's path
340
+ * without asking; a NEW app or hook still asks, and under --yes is skipped. A No drops the entry; disconnect deletes the
341
+ * file; a coupling to another account starts it empty. An unreadable file counts as no agreement at all.
342
+ */
343
+ const CONSENT_FILE = join(HOME_DIR, "consent.json");
344
+ const CONSENT_NAME = /^(?:door:[^\n,]{1,80}|session-hook|codex-notify|antigravity-stop)$/;
345
+ const CONSENT_HOW = new Set(["typed", "flag", "found"]);
346
+ let consentLoaded = null;
347
+ async function consent() {
348
+ if (consentLoaded) return consentLoaded;
349
+ let file = null;
350
+ try { const text = readPrivateFile(CONSENT_FILE); file = text === null ? null : JSON.parse(text); } catch { file = {}; }
351
+ const entries = {};
352
+ for (const [name, entry] of Object.entries(file?.entries ?? {})) if (CONSENT_NAME.test(name) && /^\d{4}-\d{2}-\d{2}$/.test(entry?.at ?? "") && CONSENT_HOW.has(entry?.how)) entries[name] = { at: entry.at, cli: String(entry.cli ?? "").slice(0, 16), how: entry.how };
353
+ let dirty = false;
354
+ const today = () => new Date().toISOString().slice(0, 10);
355
+ // THE FIRST RUN THAT KEEPS THIS FILE: what WorkTrust already wrote here on an earlier yes counts as that yes, once.
356
+ if (file === null) { for (const name of await consentFound()) entries[name] = { at: today(), cli: CLI_VERSION, how: "found" }; dirty = Object.keys(entries).length > 0; }
357
+ const save = () => { if (!dirty || has("dry-run")) return; try { ensureHome(); writePrivateFile(CONSENT_FILE, `${JSON.stringify({ version: 1, entries })}\n`); dirty = false; } catch { /* not kept: the next run asks again */ } };
358
+ consentLoaded = {
359
+ has: (name) => Boolean(entries[name]),
360
+ said: (name) => (entries[name]?.how === "found" ? "you agreed with an earlier version" : `you agreed on ${entries[name]?.at}`),
361
+ agree(name, how) { if (!entries[name]) { entries[name] = { at: today(), cli: CLI_VERSION, how }; dirty = true; } save(); },
362
+ drop(name) { if (entries[name]) { delete entries[name]; dirty = true; } save(); },
363
+ reset() { for (const name of Object.keys(entries)) delete entries[name]; dirty = true; save(); },
364
+ save,
365
+ };
366
+ return consentLoaded;
367
+ }
368
+ function eraseConsent() { try { rmSync(CONSENT_FILE); } catch { /* none */ } consentLoaded = null; }
369
+ /** The WorkTrust entries already standing here: each app's door (setup-mcp's own removal plan), the session hook, Codex's and Antigravity's wake hooks. */
370
+ async function consentFound() {
371
+ const found = [];
372
+ try {
373
+ const plan = await run((await scripts())["setup-mcp.mjs"], ["--remove"], PLACEHOLDER, true);
374
+ for (const line of plan.out.split("\n")) { const match = /^\s+− ([^:]+): would (?:remove from|run)/.exec(line); if (match && match[1] !== "Claude Code") found.push(`door:${match[1]}`); }
375
+ } catch { /* no plan: nothing found */ }
376
+ if (claudeDoorHere()) found.push("door:Claude Code");
377
+ if (sessionHookHere()) found.push("session-hook");
378
+ if (existsSync(join(homedir(), ".codex")) && isOurNotify(codexNotify().text ?? "")) found.push("codex-notify");
379
+ if (antigravityHere() && agyHooks()?.worktrust) found.push("antigravity-stop");
380
+ return found.filter((name) => CONSENT_NAME.test(name));
381
+ }
382
+ /** Claude Code's own entry for the door, as status reads it; the session hook in its settings. */
383
+ function claudeDoorHere() {
384
+ const servers = {};
385
+ try { const config = JSON.parse(readFileSync(join(homedir(), ".claude.json"), "utf8")); Object.assign(servers, config.mcpServers ?? {}); for (const project of Object.values(config.projects ?? {})) Object.assign(servers, project.mcpServers ?? {}); } catch { /* no Claude Code here */ }
386
+ return Object.entries(servers).find(([name, server]) => /worktrust/i.test(`${name} ${server?.url ?? ""} ${(server?.args ?? []).join(" ")}`)) ?? null;
387
+ }
388
+ function sessionHookHere() { try { return /log-session|worktrust(?:-launch)?\.(?:mjs|py)\\?" hook/.test(readFileSync(join(homedir(), ".claude", "settings.json"), "utf8")); } catch { return false; } }
389
+ /** The app a plan line names: " ✓ Cursor: …" → Cursor. */
390
+ const labelOf = (line) => /^\s*[↻+✓!−-] ([^:]+):/.exec(line)?.[1] ?? null;
391
+
333
392
  /**
334
393
  * THE OLD KEY ENDS WHEN THE COMPUTER IS COUPLED AGAIN (owner, 2026-10-04). Signed with the old key's own
335
394
  * device key, which only this computer holds, and naming the new key by its prefix: WorkTrust ends the
@@ -565,25 +624,40 @@ async function update() {
565
624
  say();
566
625
  const paths = await scripts();
567
626
  const plan = await run(paths["setup-mcp.mjs"], ["--bridge", STABLE], PLACEHOLDER, true);
627
+ // AGREED BEFORE, REFRESHED WITHOUT A QUESTION (0.10.30): an app or hook the person said yes to is brought onto this
628
+ // version's launcher; only what is NEW here is shown in full and asked about, and --yes leaves the new ones as they are.
629
+ const agreed = await consent();
568
630
  say(" Every AI app found here gets the WorkTrust door, the local command that reads the key:");
569
631
  const found = planLines(plan.out, true).filter((line) => !line.includes("not on this machine"));
570
- for (const line of found) say(line);
632
+ const apps = [...new Set(found.map(labelOf).filter(Boolean))], fresh = apps.filter((app) => !agreed.has(`door:${app}`));
633
+ for (const app of apps) if (!fresh.includes(app)) say(` ✓ ${app}: refreshed (${agreed.said(`door:${app}`)})`);
634
+ for (const line of found) if (fresh.includes(labelOf(line))) say(`${line} · new`);
571
635
  if (found.length === 0) say(" (no AI app found here)");
636
+ const hookFresh = !agreed.has("session-hook");
572
637
  say(` The session hook and ${STABLE} are brought to ${CLI_VERSION}.`);
638
+ say(hookFresh ? ` + Session hook: ${join(homedir(), ".claude", "settings.json")} → SessionStart, SessionEnd and PreCompact run it · new` : ` ✓ Session hook: refreshed (${agreed.said("session-hook")})`);
573
639
  say(" The key stays as it is: no new pairing, the same computer in WorkTrust.");
574
640
  say();
575
641
  if (has("dry-run")) { say(" Dry run: nothing was written and nothing was sent."); return; }
576
- if (!(await ask("Continue?"))) { say(" Stopped. Nothing was written."); return; }
642
+ const newOnes = [...fresh, ...(hookFresh ? ["Session hook"] : [])];
643
+ let takeNew = false;
644
+ if (newOnes.length > 0 && has("yes")) say(` skipped: new, run without --yes to decide: ${newOnes.join(", ")}`);
645
+ else if (newOnes.length > 0) takeNew = await ask(`Couple the new ${newOnes.length === 1 ? "one" : "ones"} marked "new" (${newOnes.join(", ")})?`, false);
646
+ if (newOnes.length > 0 && !takeNew && !has("yes")) say(" The new ones stay as they are. npx worktrust update asks again.");
647
+ const skip = takeNew ? [] : fresh, hookOn = !hookFresh || takeNew;
577
648
  const previousVersion = stableVersion();
578
649
  await prepareBundledRuntime();
579
650
  ensureHome();
580
651
  saveStableEntry();
581
652
  say(` ✓ ${STABLE} is now ${CLI_VERSION}`);
582
- // Out first, then in: an app that held a key of its own (a hand-made entry) moves onto the bridge.
583
- await run(paths["setup-mcp.mjs"], ["--remove", "--write"], key.token, true);
584
- if ((await run(paths["setup-mcp.mjs"], ["--write", "--bridge", STABLE], key.token)).code !== 0) fail("coupling the AI apps failed; the output above says where.");
653
+ // Out first, then in: an app that held a key of its own (a hand-made entry) moves onto the bridge. An app not agreed to is not touched.
654
+ const skipArgs = skip.length > 0 ? ["--skip", skip.join(",")] : [];
655
+ await run(paths["setup-mcp.mjs"], ["--remove", "--write", ...skipArgs], key.token, true);
656
+ if ((await run(paths["setup-mcp.mjs"], ["--write", "--bridge", STABLE, ...skipArgs], key.token)).code !== 0) fail("coupling the AI apps failed; the output above says where.");
585
657
  const hookArgs = ["--install", "--via", STABLE];
586
- if ((await run(paths["log-session.mjs"], hookArgs, key.token, false)).code !== 0) fail("installing the session hook failed; the output above says where.");
658
+ if (hookOn && (await run(paths["log-session.mjs"], hookArgs, key.token, false)).code !== 0) fail("installing the session hook failed; the output above says where.");
659
+ for (const name of [...apps.filter((app) => !skip.includes(app)).map((app) => `door:${app}`), ...(hookOn ? ["session-hook"] : [])]) agreed.agree(name, "typed");
660
+ agreed.save();
587
661
  // Codex installed since, or a No said at connect: the one question, asked again (or "already set").
588
662
  await offerCodex();
589
663
  await offerAntigravity();
@@ -632,6 +706,7 @@ async function connect() {
632
706
  if (has("dry-run")) { say(" Dry run: nothing was written and nothing was sent."); return; }
633
707
  if (!(await ask("Continue?"))) { say(" Stopped. Nothing was written and nothing was sent."); return; }
634
708
  await prepareBundledRuntime();
709
+ const agreed = await consent(); // read before anything is written, so what this run writes is not taken for an earlier yes
635
710
 
636
711
  // The device key: made here, its private half kept with the key, its public half bound at WorkTrust.
637
712
  const device = direct ? null : generateKeyPairSync("ed25519");
@@ -662,6 +737,9 @@ async function connect() {
662
737
  const floors = !previous || switched ? ["--from-now", ...(switched ? ["--history-floor", "now"] : [])] : [];
663
738
  const hookArgs = ["--install", ...floors, "--via", STABLE, ...(direct ? ["--direct"] : [])];
664
739
  if ((await run(paths["log-session.mjs"], hookArgs, token, false, { WORKTRUST_CODEX_OFFER: "1" })).code !== 0) fail("installing the session hook failed; the output above says where.");
740
+ // WHAT WAS AGREED HERE (0.10.30): the apps and the hook this "Continue?" covered; another account starts with none from before.
741
+ if (switched) agreed.reset();
742
+ for (const name of [...new Set(foundApps.map(labelOf).filter(Boolean))].map((app) => `door:${app}`).concat("session-hook")) agreed.agree(name, has("yes") ? "flag" : "typed");
665
743
  await offerCodex();
666
744
  await offerAntigravity();
667
745
  if (switched) { say(); say(" Earlier work on this computer is not offered: it was coupled to another account before. Only work from now on goes to this account."); }
@@ -680,7 +758,7 @@ async function connect() {
680
758
  * Enter, --yes and a closed terminal all mean No; `--history` says yes in advance. What goes is hours
681
759
  * and tokens per day, filed as history (never verified hours, never text).
682
760
  */
683
- async function offerHistory(paths, token, devicePem, url = MCP, rebuild = false) {
761
+ async function offerHistory(paths, token, devicePem, url = MCP, rebuild = false, agreedInAdvance = false) {
684
762
  const env = { WORKTRUST_MCP_URL: url, ...(devicePem ? { WORKTRUST_DEVICE_KEY: devicePem } : {}) };
685
763
  const counted = await run(paths["log-session.mjs"], ["--history", "--dry-run", "--summary"], token, true, env);
686
764
  let found = null;
@@ -698,7 +776,7 @@ async function offerHistory(paths, token, devicePem, url = MCP, rebuild = false)
698
776
  say(" never deleted, so a day is counted once. Other computers, web sources and days not listed are not touched.");
699
777
  }
700
778
  if (has("dry-run")) { say(" Dry run: nothing was sent."); return; }
701
- if (!has("history") && !(rebuild ? await ask("Send them (re-measured; this computer's earlier lines for these days are replaced, a day is counted once)?", false) : await ask("Send these as history (hours and tokens per day; never text)?", false))) { historyDone(false); say(" Not sent. Send them later with: npx worktrust"); return; }
779
+ if (!has("history") && !agreedInAdvance && !(rebuild ? await ask("Send them (re-measured; this computer's earlier lines for these days are replaced, a day is counted once)?", false) : await ask("Send these as history (hours and tokens per day; never text)?", false))) { historyDone(false); say(" Not sent. Send them later with: npx worktrust"); return; }
702
780
  // Marked unfinished before the first batch leaves (0.10.9): a send stopped halfway (Ctrl+C, a closed lid) is finished by the next run.
703
781
  historyDone(false);
704
782
  const sent = await run(paths["log-session.mjs"], ["--history", ...(rebuild ? ["--rebuild"] : []), ...(has("retry-review") ? ["--retry-review"] : [])], token, true, env);
@@ -744,8 +822,9 @@ async function offerRebuild(previousVersion, paths, key) {
744
822
  say(" the agent, what the seconds were, more AI apps). You can re-measure the");
745
823
  say(" sessions still on this computer and have WorkTrust replace this computer's earlier lines, day by day, never counting");
746
824
  say(" a day twice. Later: npx worktrust");
747
- if (!(await ask("Show the plan and rebuild now?", false))) { say(" Not now."); return; }
748
- await offerHistory(paths, key.token, key.device ?? null, key.url, true);
825
+ // ONE QUESTION, AFTER THE PLAN (0.10.30): counting the plan reads this computer only and sends nothing, so it is shown
826
+ // first and the send is asked once, Enter is No; `--rebuild` agrees in advance, --yes alone never does.
827
+ await offerHistory(paths, key.token, key.device ?? null, key.url, true, has("rebuild"));
749
828
  }
750
829
 
751
830
  /**
@@ -971,17 +1050,24 @@ async function offerCodex() {
971
1050
  say(" Codex takes one, so it stays as it is; Codex sessions are still sent whenever the Claude Code hook runs.");
972
1051
  return;
973
1052
  }
974
- say(" Codex can wake the session hook at the end of every turn, so Codex work arrives without Claude Code running:");
975
- say(` ${found.text ? "↻" : "+"} ${CODEX_CONFIG} → ${want}`);
1053
+ // AGREED BEFORE (0.10.30): WorkTrust's own line, already said yes to, whose launcher path moved: refreshed without a question.
1054
+ const agreed = await consent(), known = Boolean(found.text) && agreed.has("codex-notify");
1055
+ if (known) say(` ✓ Codex wakes the session hook: refreshed (${agreed.said("codex-notify")}).`);
1056
+ else {
1057
+ say(" Codex can wake the session hook at the end of every turn, so Codex work arrives without Claude Code running:");
1058
+ say(` ${found.text ? "↻" : "+"} ${CODEX_CONFIG} → ${want}`);
1059
+ }
976
1060
  if (has("dry-run")) { say(" Dry run: nothing was written."); return; }
977
- if (!has("codex") && !(await ask("Let Codex wake the session hook?", false))) { say(" Not set. npx worktrust update asks again."); return; }
1061
+ if (!known && !has("codex") && has("yes")) { say(" Not set (skipped: new, run without --yes to decide)."); return; }
1062
+ if (!known && !has("codex") && !(await ask("Let Codex wake the session hook?", false))) { agreed.drop("codex-notify"); say(" Not set. npx worktrust update asks again."); return; }
978
1063
  await prepareBundledRuntime(); want = desired();
979
1064
  const rows = [...found.rows];
980
1065
  if (found.text) rows.splice(found.at, found.end - found.at + 1, want);
981
1066
  else rows.splice(found.insert, 0, ...(found.insert < rows.length && rows[found.insert] !== "" ? [want, ""] : [want]));
982
1067
  if (rows.at(-1) !== "") rows.push("");
983
1068
  writeCodex(rows);
984
- say(" ✓ Codex wakes the session hook. Restart Codex to pick it up; the earlier file is kept as config.toml.worktrust-backup.");
1069
+ agreed.agree("codex-notify", has("codex") ? "flag" : "typed");
1070
+ say(known ? " Restart Codex to pick it up; the earlier file is kept as config.toml.worktrust-backup." : " ✓ Codex wakes the session hook. Restart Codex to pick it up; the earlier file is kept as config.toml.worktrust-backup.");
985
1071
  }
986
1072
 
987
1073
  /**
@@ -1014,13 +1100,20 @@ async function offerAntigravity() {
1014
1100
  say();
1015
1101
  if (hooks === null) { say(` ${AGY_HOOKS} is not readable JSON, so it is left as it is; Antigravity sessions are still sent whenever another hook runs.`); return; }
1016
1102
  if (JSON.stringify(hooks.worktrust) === JSON.stringify(want)) { say(" ✓ Antigravity already wakes the session hook when its agent stops."); return; }
1017
- say(" Antigravity can wake the session hook when its agent stops, so Antigravity work arrives without Claude Code running:");
1018
- say(` ${hooks.worktrust ? "↻" : "+"} ${AGY_HOOKS} → worktrust: Stop runs ${want.Stop[0].command}`);
1103
+ // AGREED BEFORE (0.10.30): WorkTrust's own hook, already said yes to, whose launcher path moved: refreshed without a question.
1104
+ const agreed = await consent(), known = Boolean(hooks.worktrust) && agreed.has("antigravity-stop");
1105
+ if (known) say(` ✓ Antigravity wakes the session hook: refreshed (${agreed.said("antigravity-stop")}).`);
1106
+ else {
1107
+ say(" Antigravity can wake the session hook when its agent stops, so Antigravity work arrives without Claude Code running:");
1108
+ say(` ${hooks.worktrust ? "↻" : "+"} ${AGY_HOOKS} → worktrust: Stop runs ${want.Stop[0].command}`);
1109
+ }
1019
1110
  if (has("dry-run")) { say(" Dry run: nothing was written."); return; }
1020
- if (!has("antigravity") && !(await ask("Let Antigravity wake the session hook?", false))) { say(" Not set. npx worktrust update asks again."); return; }
1111
+ if (!known && !has("antigravity") && has("yes")) { say(" Not set (skipped: new, run without --yes to decide)."); return; }
1112
+ if (!known && !has("antigravity") && !(await ask("Let Antigravity wake the session hook?", false))) { agreed.drop("antigravity-stop"); say(" Not set. npx worktrust update asks again."); return; }
1021
1113
  await prepareBundledRuntime(); want = desired();
1022
1114
  writeAgyHooks({ ...hooks, worktrust: want });
1023
- say(` ✓ Antigravity wakes the session hook. Restart Antigravity to pick it up${existsSync(`${AGY_HOOKS}.worktrust-backup`) ? "; the earlier file is kept as hooks.json.worktrust-backup" : ""}.`);
1115
+ agreed.agree("antigravity-stop", has("antigravity") ? "flag" : "typed");
1116
+ say(` ${known ? " Restart" : "✓ Antigravity wakes the session hook. Restart"} Antigravity to pick it up${existsSync(`${AGY_HOOKS}.worktrust-backup`) ? "; the earlier file is kept as hooks.json.worktrust-backup" : ""}.`);
1024
1117
  }
1025
1118
  /** Disconnect takes the hook named worktrust out of Antigravity's hooks, and nothing else. */
1026
1119
  function removeAntigravityHook() {
@@ -1049,7 +1142,7 @@ async function disconnect() {
1049
1142
  const plan = await run(paths["setup-mcp.mjs"], ["--remove"], PLACEHOLDER, true);
1050
1143
  say(" 1. The WorkTrust door comes out of every AI app here:");
1051
1144
  for (const line of planLines(plan.out)) say(line);
1052
- say(" 2. The session hook comes out of ~/.claude/settings.json (and Codex's notify line and Antigravity's worktrust hook, when WorkTrust set them), credentials are removed (an encrypted empty slot keeps the OS-vault preference)");
1145
+ say(" 2. The session hook comes out of ~/.claude/settings.json (and Codex's notify line and Antigravity's worktrust hook, when WorkTrust set them), credentials are removed (an encrypted empty slot keeps the OS-vault preference), and so is the record of what you agreed to (consent.json)");
1053
1146
  say(" but for one note of which account this computer fed (masked), so a later coupling by another account starts clean.");
1054
1147
  say(" 3. The key itself stays valid until you revoke it: WorkTrust → Sources → Devices → this computer → Revoke.");
1055
1148
  say();
@@ -1063,6 +1156,8 @@ async function disconnect() {
1063
1156
  if (removeAntigravityHook()) say(" ✓ Antigravity no longer wakes the session hook.");
1064
1157
  previousNote.save(keyStore.load());
1065
1158
  keyStore.erase();
1159
+ eraseConsent(); // 0.10.30: what was agreed goes with the coupling; a later connect asks again
1160
+
1066
1161
  // Everything of ours on this computer goes; the folder too, when nothing else is left in it.
1067
1162
  for (const name of [STABLE_FILE, ...SCRIPTS.map((script) => join(HOME_DIR, downloaded(script))), join(HOME_DIR, "pinned")]) { try { rmSync(name); } catch { /* gone */ } }
1068
1163
  try { rmSync(HOME_DIR, { recursive: false }); } catch { /* not empty, or gone */ }
@@ -1112,21 +1207,13 @@ async function mod() {
1112
1207
  }
1113
1208
 
1114
1209
  async function status() {
1115
- const servers = {};
1116
- try {
1117
- const config = JSON.parse(readFileSync(join(homedir(), ".claude.json"), "utf8"));
1118
- Object.assign(servers, config.mcpServers ?? {});
1119
- for (const project of Object.values(config.projects ?? {})) Object.assign(servers, project.mcpServers ?? {});
1120
- } catch { /* no Claude Code here */ }
1121
- const door = Object.entries(servers).find(([name, server]) => /worktrust/i.test(`${name} ${server?.url ?? ""} ${(server?.args ?? []).join(" ")}`));
1210
+ const door = claudeDoorHere();
1122
1211
  say(door ? ` Claude Code: coupled (${door[1].url ?? "through the local bridge"})` : " Claude Code: not coupled. Run `npx worktrust connect`.");
1123
1212
  const key = keyStore.load();
1124
1213
  say(` Credential storage: ${keyStore.protected() ? "OS vault + encrypted local file" : "private local file; use worktrust protect-key after updating"}`);
1125
1214
  say(key ? ` Key: in ${KEY_PLACE}, ${key.device ? "bound to this computer, " : ""}last renewed ${String(key.renewedAt ?? "").slice(0, 10) || "never"}` : " Key: not on this computer (or written into the apps' settings with --direct)");
1126
1215
  if (key) say(key.account ? ` Account: ${key.account}${key.coupledAt ? `, coupled ${String(key.coupledAt).slice(0, 10)}` : ""}` : " Account: not recorded (coupled by an older version; `npx worktrust connect` records it)");
1127
- let hook = false;
1128
- try { hook = /log-session|worktrust(?:-launch)?\.(?:mjs|py)\\?" hook/.test(readFileSync(join(homedir(), ".claude", "settings.json"), "utf8")); } catch { /* none */ }
1129
- say(hook ? " Session hook: installed" : " Session hook: not installed");
1216
+ say(sessionHookHere() ? " Session hook: installed" : " Session hook: not installed");
1130
1217
  if (existsSync(join(homedir(), ".codex"))) { const notify = codexNotify().text ?? ""; say(isOurNotify(notify) ? " Codex: wakes the session hook" : " Codex: does not wake the session hook (npx worktrust update asks)"); }
1131
1218
  if (existsSync(join(homedir(), ".hermes"))) { let text = ""; try { text = readFileSync(join(homedir(), ".hermes", "config.yaml"), "utf8"); } catch { /* none */ } say(/worktrust(?:-launch)?\.(?:mjs|py)\\?" hook --hermes/.test(text) ? " Hermes Agent: wakes the session hook" : " Hermes Agent: does not wake the session hook (npx worktrust update writes it)"); }
1132
1219
  if (antigravityHere()) say(agyHooks()?.worktrust ? " Antigravity: wakes the session hook" : " Antigravity: does not wake the session hook (npx worktrust update asks)");
@@ -1189,7 +1276,11 @@ function help() {
1189
1276
  say(" --direct put the key in each app's settings instead of the key file");
1190
1277
  say(" worktrust connect couple again, also when this computer is already coupled (asks first)");
1191
1278
  say(" --replace yes in advance to coupling a computer that is already coupled");
1192
- say(" worktrust update this computer onto the newest CLI: same key, no new pairing");
1279
+ say(" worktrust update this computer onto the newest CLI: same key, no new pairing; what you agreed to before is");
1280
+ say(" refreshed without a question, a new AI app or hook is asked about (--yes: skipped)");
1281
+ say(" --rebuild yes in advance to the re-measure update offers after a new version (the plan is still shown)");
1282
+ say(" --codex yes in advance to letting Codex wake the session hook (also for connect)");
1283
+ say(" --antigravity yes in advance to letting Antigravity wake the session hook (also for connect)");
1193
1284
  say(" worktrust history send this computer's earlier sessions as history (asks first)");
1194
1285
  say(" --resume retry saved metadata batches, even if source files are gone (asks first)");
1195
1286
  say(" --retry-review explicitly retry held batches after support resolves their review");