worktrust 0.10.31 → 0.10.32

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,43 @@
1
1
  # worktrust
2
2
 
3
+ ## 0.10.32: a re-measure sends only the days that changed; which subagents were active at once; each call's outcome
4
+
5
+ Before a re-measure sends anything, the CLI asks WorkTrust, once per AI app, which of this computer's days it holds as
6
+ current. The question carries nothing but the question (`import_history` with `rebuild` and `fingerprint`, no line).
7
+ The answer is the digest this computer sent with each such day, its own submission and never the record: no hours, no
8
+ lines, no figure. A day whose digest on this computer is the same is not sent, so a re-run with nothing new sends
9
+ nothing and says so; one changed day sends that day alone. If the answer is not one (an older WorkTrust, an error, no
10
+ network), every day is sent as before. The digest covers each line as it is sent, without the CLI's own version, so
11
+ an update that measures the same sends nothing. When WorkTrust names where the run waits, the command prints
12
+ `queued, position N, about M min`.
13
+
14
+ A Claude Code session's subagents (the transcripts Claude Code keeps in `<session>/subagents/`) now travel with the day's
15
+ stretch as `agents`: per run, by position only, its kind (`builtin`, `own` for an agent type of your own, `background`,
16
+ `fork`, read from the run's `.meta.json`), when it started in whole seconds from the stretch's start, the stretches of time
17
+ it was active (a gap over five minutes ends one) and how many of its tool steps failed and how many of those a later step
18
+ of the same kind recovered. Never a name, a prompt, a path, a tool or an id. At most 64 runs a stretch, 12 active stretches
19
+ a run and 256 in all; the longest are kept. WorkTrust counts a run only while the session it belongs to is steered by you
20
+ (within 8 hours of your last input), and shows how many agents were active at once beside the sessions at once; it is never
21
+ added to your hours.
22
+
23
+ Beside the timeline, each model answer's outcome travels as one character (`call_outcomes`: completed, failed or not
24
+ known), and in a run no person started (headless or scheduled) the length of each of your own turns as a bucket
25
+ (`input_lengths`: short, medium or long) and, when a timer started the run, its cadence word with an opaque reference
26
+ (`schedule_cadence`, `schedule_ref`). Never a word, a command, a path or the timer's name. WorkTrust credits Agentic Hours
27
+ only for calls recorded as completed.
28
+
29
+ The measure rules go to 2, so `update` offers a re-measure once, naming these changes.
30
+
31
+ The session hook no longer reads a Claude Code transcript from its first byte on every run. Beside each session's
32
+ watermark in `~/.worktrust/sessions.json` it keeps where its last read ended: the file's identity (device and inode), the
33
+ offset, a hash of eight 4 KB samples before it, the offset of the first message not yet sent, and what a full read would
34
+ know at that point (the session's working folder, how it was started, a subagent's first moment). That stays on this
35
+ computer and is never sent. The next run reads from the first unsent message, so a day that spans the offset is read
36
+ again from its start, and gives exactly what a full read gives. A file that was truncated, rewritten, replaced or
37
+ compacted, a new CLI version, other measure rules, or a state without positions is read whole, as before. A re-measure
38
+ (`history`, `history --rebuild`, the offer after an update) always reads everything. Measured: 1 MB appended to a 600 MB
39
+ transcript reads about 1 MB.
40
+
3
41
  ## 0.10.31: a re-measure is offered only when measuring changed
4
42
 
5
43
  `update` offers to re-measure this computer's sessions only when the new version MEASURES differently from the one it
@@ -500,9 +538,9 @@ retried safely. A row kept pending on WorkTrust remains excluded from counted ac
500
538
  | | |
501
539
  |---|---|
502
540
  | **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. |
503
- | **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). |
541
+ | **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; four hooks in `~/.claude/settings.json` (SessionStart, SessionEnd, PreCompact and, since 0.10.32, Stop, which sweeps at most once an hour); the bridge, the hook and the counter in `~/.worktrust/`; and `~/.worktrust/consent.json`, what you agreed to (names and days only, 0.10.30). |
504
542
  | **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). |
505
- | **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). |
543
+ | **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 subagent runs that started in the stretch, by position only (`agents`, since 0.10.32: per run its kind, builtin, own, background or fork, its start and active intervals in whole seconds from the stretch's start, and its tool failures and recoveries as counts; never a name, a prompt, a path or an id; at most 64 runs, 12 intervals a run, 256 in all), 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), each model answer's outcome as one character, completed, failed or not known (`call_outcomes`, since 0.10.32), and in a run no person started the length of each of your turns as a bucket (`input_lengths`) and a timer's cadence word with an opaque reference (`schedule_cadence`, `schedule_ref`), 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). With a re-measure (0.10.32), each batch also carries a digest of each day it holds as this computer computed it (`days`: a date and 64 hex, never a line), the question before it asks only for the digests this computer sent before, and a count of transcripts this computer could not read rides beside that question (`unreadable`: a number, never which file). |
506
544
  | **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. |
507
545
 
508
546
  **The clock is WorkTrust's, not this computer's (0.10.20).** A measured stretch travels as its timeline: one step per
package/SECURITY.md CHANGED
@@ -73,6 +73,19 @@ private transcripts or account data in a public issue.
73
73
  here, a wake hook); it cannot widen what is written, sent or read. An unreadable or unsafe file counts as no agreement.
74
74
  - A No drops the entry it answered; `disconnect` deletes the file; a coupling to another account starts it empty.
75
75
 
76
+ ## The question before a re-measure (0.10.32)
77
+
78
+ Before a re-measure, the hook asks the door, per AI app, which days of this computer WorkTrust holds as current. The
79
+ request is `import_history` with `rebuild: true, fingerprint: true` and nothing else: no line, no hours, no path. It
80
+ goes under the computer's own key and, on a bound computer, with its device proof, like every history batch. The
81
+ answer is a list of UTC days and, for each, the 64-hex digest this computer sent with that day: digests of its own
82
+ submissions, never a line, a figure or anything of the record. A digest is computed here from what this computer would
83
+ send; a day that matches is not sent again. An answer that cannot be read means not known, and every day is sent.
84
+
85
+ When a transcript on this computer exists but cannot be read (permissions, a disk error), the hook counts it, keeps the
86
+ count in `~/.worktrust/sessions.json`, shows it in `npx worktrust status`, and at most once a day asks the same question
87
+ with the count beside it (`unreadable: N`): a number, never which file, its path or anything in it.
88
+
76
89
  ## What measurement signatures establish
77
90
 
78
91
  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":"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":"7fdcd2996f0d401a7232467904d2900ee2cc084764ae25d4ffd5f9f4b57da1b3"},"format":"worktrust-package/1","kind":"engine","version":"0.10.31"},"signature":"BFiAtMFcbRPNlWst7-uNb2Flv378GZ195wtGF5nFxLkHaqNEhskqGe0KrzaDKM0T5AKCwf0VoAMOu9r4mf1TDw"}
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":"35d01fb00a472c022560a880c0863b57f24cb8311040bba21c3f0cf903b9074c","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":"5f5667b92adf11b1a5a6330a0f26dd6db73d56fe60823d9a5246dab71d27d380","transcript-readers.mjs":"ed6fef364aa28f39361d8f627abcda2162498cbaa13e90cc5860a768cb355fa2","worktrust-launch.mjs":"84801bd29d472d48188c126b9ebe3989a3132b54e13cc4fe534ff7c383a294ee","worktrust.mjs":"0e481fde109620dd23f750d7b9b0741c0ea831c45961a176164ef2a74f3dd7c0"},"format":"worktrust-package/1","kind":"engine","version":"0.10.32"},"signature":"j7kCqXaW7lS8jyExo_Ag4eCHLtVYFSMIOJY745sZrrFyRTOfOc59k8kYFKCST-KMkQQctNK9QuLZAox_1UzwDQ"}
package/log-session.mjs CHANGED
@@ -60,7 +60,7 @@
60
60
  * honoured here too, matched against the transcript's project directory, before a file is read.
61
61
  */
62
62
  import { execFileSync, spawn, spawnSync } from "node:child_process";
63
- import { existsSync, mkdirSync, readFileSync, readdirSync, rmSync, statSync, writeFileSync, lstatSync, openSync, closeSync, fsyncSync, linkSync, unlinkSync, constants } from "node:fs";
63
+ import { existsSync, mkdirSync, readFileSync, readdirSync, rmSync, statSync, writeFileSync, lstatSync, openSync, closeSync, fsyncSync, fstatSync, linkSync, unlinkSync, readSync, constants } from "node:fs";
64
64
  import { homedir } from "node:os";
65
65
  import { dirname, join, resolve, sep } from "node:path";
66
66
  import { fileURLToPath } from "node:url";
@@ -159,7 +159,15 @@ const DERIVED = new WeakMap();
159
159
  * Running more often costs nothing extra: the watermark means a run with nothing new to say opens
160
160
  * no file, and a day still being worked in is never sent twice.
161
161
  */
162
- const HOOK_EVENTS = ["SessionEnd", "SessionStart", "PreCompact"];
162
+ const HOOK_EVENTS = ["SessionEnd", "SessionStart", "PreCompact", "Stop"];
163
+ /**
164
+ * STOP, AT MOST ONCE AN HOUR (0.10.32, after the owner's session of 2026-10-04 to 10-28). A VS Code session that stays open
165
+ * for weeks fires SessionStart once and compacts rarely, and the live door takes a day for 48 hours only: every finished
166
+ * day arrived late. Claude Code's Stop fires after every answer; the hook answers it at once unless an hour has passed
167
+ * since its last Stop sweep, and then sweeps in a detached copy of itself so the answer is never held. The same hook the
168
+ * person agreed to (the "session hook" of consent.json), on one more of Claude Code's moments.
169
+ */
170
+ const STOP_SWEEP_MS = 3600_000;
163
171
 
164
172
  const STATE = join(homedir(), ".worktrust", "sessions.json");
165
173
  const readState = () => { try { return JSON.parse(readFileSync(STATE, "utf8")); } catch { return {}; } }, writeState = (state) => { mkdirSync(dirname(STATE), { recursive: true }); writeFileSync(STATE, JSON.stringify(state, null, 1)); };
@@ -222,10 +230,10 @@ const excluded = (path) => excludes.some((text) => text && path.includes(text));
222
230
  * reader), the database clients in session-databases.mjs. The install copies both into ~/.worktrust with this hook.
223
231
  * Without them this hook still reads Claude Code; the never-matching patterns keep every other client out.
224
232
  */
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)) ?? {};
233
+ 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" }), turnByPerson = () => null, timerSchedule = () => null } = (await import("./transcript-readers.mjs").catch(() => null)) ?? {};
226
234
  // THE STRETCH'S DERIVED RECORD (0.7.4: split from this file): tool calls named by kind, verification, recovery, delegation,
227
235
  // context and routing, for the local archive only. A copy without the module still measures and sends exactly as before.
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)) ?? {};
236
+ const { callOf = (block) => ({ id: block.id, kinds: [], family: String(block.name), digest: "" }), deriveStretch = () => ({}), complexityOf = null, recoveryOf = null, resultOf = (block) => ({ id: block.tool_use_id, failed: block.is_error === true, refusal: null }) } = (await import("./stretch-evidence.mjs").catch(() => null)) ?? {};
229
237
  const { DATABASE_SESSION = /(?!)/, databaseLines = () => null, databaseSessions = function* () {} } = (await import("./session-databases.mjs").catch(() => null)) ?? {};
230
238
  // A WEB CHAT'S DATA EXPORT AS HISTORY (0.10.10, owner 2026-10-10): chat-exports.mjs reads a ChatGPT or Claude export (the counter
231
239
  // imports the same reader); `--history --export <path>` sends its conversations as RECONSTRUCTED days, never measured, never tokens.
@@ -266,15 +274,97 @@ function* antigravityConversations() {
266
274
  if (!(cwd && excluded(cwd))) yield { id: `antigravity:${conversationId}`, file };
267
275
  }
268
276
  }
269
- /** A transcript's lines as objects, whichever client wrote it; null when the file cannot be read. */
277
+ /**
278
+ * A FILE'S LINES, READ IN CHUNKS (0.10.32). A whole-file `readFileSync(file, "utf8")` throws past the longest string Node
279
+ * makes (about 512 MB), and that throw was read as "this file cannot be read": the owner's VS Code session passed it on
280
+ * 2026-10-18 (797 MB by 10-28) and from then on measured no day at all, live or re-measured. Read 8 MB at a time, one
281
+ * line at a time; re-iterable (each pass opens the file again); null only when the file cannot be opened.
282
+ */
283
+ const CHUNK_BYTES = 8 << 20;
284
+ /**
285
+ * A READ THAT FAILS IS COUNTED, NEVER SILENT (0.10.32): a transcript that exists and cannot be opened or read to its end
286
+ * is one failure. The run keeps the count in sessions.json (`npx worktrust status` says it) and tells WorkTrust the
287
+ * count alone, never which file or what was in it (reportUnreadable).
288
+ */
289
+ const READ_FAILURES = { n: 0 };
290
+ /** The bytes this run read from transcripts (the resume's own measure, below): said on stderr under WORKTRUST_HOOK_DEBUG, never sent. */
291
+ const READ_BYTES = { n: 0 };
292
+ /**
293
+ * What a resume trusts of the bytes it does not read again: eight 4 KB samples before the offset, the first and the last of
294
+ * them at its edges and six spread evenly between, hashed with the offset (32 KB read, whatever the file's length).
295
+ */
296
+ const EDGE_BYTES = 4096, EDGE_SAMPLES = 8;
297
+ const edgesOf = (fd, end) => {
298
+ const hash = createHash("sha256").update(`worktrust-read-position|${end}|`), buffer = Buffer.allocUnsafe(EDGE_BYTES);
299
+ const starts = end <= EDGE_BYTES ? [0] : [...new Set(Array.from({ length: EDGE_SAMPLES }, (_, k) => Math.floor((k * (end - EDGE_BYTES)) / (EDGE_SAMPLES - 1))))];
300
+ for (const from of starts) {
301
+ const want = Math.min(EDGE_BYTES, end - from);
302
+ let got = 0;
303
+ while (got < want) { const n = readSync(fd, buffer, got, want - got, from + got); if (n <= 0) break; got += n; }
304
+ READ_BYTES.n += got;
305
+ hash.update(buffer.subarray(0, got));
306
+ }
307
+ return hash.digest("base64url").slice(0, 22);
308
+ };
309
+ /**
310
+ * The lines from byte `from` (a line boundary), split on the newline BYTE, which no UTF-8 sequence holds, and decoded line by
311
+ * line. `at`, when given, says where each yielded line starts (`at.line`) and, read through the same descriptor the lines came
312
+ * from: the file's identity (`at.dev`, `at.ino`), the offset after its last newline (`at.end`, set before an unterminated last
313
+ * line is yielded) and the hash of its edges before that offset (`at.hash`). `at.failed` is a read that failed (counted, as
314
+ * always); `at.moved` a file that is not the one `expect` names (another identity, shorter than its offset, other bytes at its
315
+ * edges): nothing is yielded and nothing counted, and the caller reads it whole.
316
+ */
317
+ function* chunkedLines(file, from = 0, at = null, expect = null) {
318
+ let fd;
319
+ try { fd = openSync(file, "r"); } catch { READ_FAILURES.n += 1; if (at) at.failed = true; return; }
320
+ try {
321
+ if (at || expect) {
322
+ let stat; try { stat = fstatSync(fd); } catch { READ_FAILURES.n += 1; if (at) at.failed = true; return; }
323
+ if (at) { at.dev = String(stat.dev); at.ino = String(stat.ino); }
324
+ if (expect) {
325
+ let same = false;
326
+ try { same = String(stat.dev) === expect.dev && String(stat.ino) === expect.ino && stat.size >= expect.end && expect.end >= from && (expect.end === 0 ? expect.hash === null : edgesOf(fd, expect.end) === expect.hash); } catch { same = false; }
327
+ if (!same) { if (at) at.moved = true; return; }
328
+ }
329
+ }
330
+ const buffer = Buffer.allocUnsafe(CHUNK_BYTES);
331
+ let pending = [], position = from, lineStart = from;
332
+ for (;;) {
333
+ let n;
334
+ try { n = readSync(fd, buffer, 0, CHUNK_BYTES, position); } catch { READ_FAILURES.n += 1; if (at) at.failed = true; return; }
335
+ if (n <= 0) break;
336
+ READ_BYTES.n += n;
337
+ const chunk = buffer.subarray(0, n);
338
+ let start = 0;
339
+ for (let nl = chunk.indexOf(10); nl !== -1; nl = chunk.indexOf(10, start)) {
340
+ const text = pending.length > 0 ? Buffer.concat([...pending, chunk.subarray(start, nl)]).toString("utf8") : chunk.toString("utf8", start, nl);
341
+ pending = [];
342
+ if (at) at.line = lineStart;
343
+ lineStart = position + nl + 1; start = nl + 1;
344
+ yield text;
345
+ }
346
+ if (start < n) pending.push(Buffer.from(chunk.subarray(start)));
347
+ position += n;
348
+ }
349
+ if (at) { at.end = lineStart; try { at.hash = lineStart > 0 ? edgesOf(fd, lineStart) : null; } catch { READ_FAILURES.n += 1; at.failed = true; } }
350
+ const rest = pending.length > 0 ? Buffer.concat(pending).toString("utf8") : "";
351
+ if (rest) { if (at) at.line = lineStart; yield rest; }
352
+ } finally { closeSync(fd); }
353
+ }
354
+ /** A Claude Code transcript's lines as objects from byte `from`, `at` and `expect` as chunkedLines takes them. */
355
+ function* claudeLinesFrom(file, from, at, expect) { for (const raw of chunkedLines(file, from, at, expect)) { if (!raw.trim()) continue; let line; try { line = JSON.parse(raw); } catch { continue; } yield line; } }
356
+ const fileLines = (file) => {
357
+ try { closeSync(openSync(file, "r")); } catch (error) { if (error?.code !== "ENOENT") READ_FAILURES.n += 1; return null; }
358
+ return { [Symbol.iterator]: () => chunkedLines(file) };
359
+ };
360
+ /** A transcript's lines as objects, whichever client wrote it; null when the file cannot be read. A Claude Code transcript is parsed lazily, as it is read. */
270
361
  const parsedLines = (file) => {
271
362
  if (DATABASE_SESSION.test(file)) return databaseLines(file);
272
- let lines; try { lines = readFileSync(file, "utf8").split("\n"); } catch { return null; }
363
+ const lines = fileLines(file);
364
+ if (!lines) return null;
273
365
  if (CODEX_ROLLOUT.test(file)) return [...codexLines(lines)];
274
366
  if (ANTIGRAVITY_TRANSCRIPT.test(file)) { const id = antigravityIdOf(file); return [...antigravityLines(lines, { id, ...antigravityContext(id) })]; }
275
- const out = [];
276
- for (const raw of lines) { if (!raw.trim()) continue; try { out.push(JSON.parse(raw)); } catch { /* a torn line */ } }
277
- return out;
367
+ return { *[Symbol.iterator]() { for (const raw of lines) { if (!raw.trim()) continue; try { yield JSON.parse(raw); } catch { /* a torn line */ } } } };
278
368
  };
279
369
  /** The coupling Codex holds, when Claude Code holds none: the same door, read from ~/.codex/config.toml. */
280
370
  function codexCoupling() {
@@ -375,7 +465,36 @@ const pathsTouched = (cwd, from, to) => {
375
465
  * left unsaid, and WorkTrust reads an unsaid kind as interactive. A copy without the readers reads every session as unknown.
376
466
  * WorkTrust counts a headless or scheduled session as Agent operations, never as the person's hours.
377
467
  */
378
- function stretchesOf(file, since) {
468
+ /**
469
+ * THE READ POSITION (0.10.32, owner 2026-10-28: the owner's session was 805 MB after 24 days, and every hook run and every
470
+ * hourly Stop sweep read it from its first byte, because the watermark is a TIME filter). Beside a Claude Code transcript's
471
+ * watermark the hook keeps where its last read ended, and the next run reads only what it has to. Per file (the session's
472
+ * own and each of its subagents'):
473
+ * d, i the file's identity (device and inode), read through the descriptor the lines came from;
474
+ * e the offset after the last newline read (an unterminated last line is read again next time);
475
+ * h a hash of eight 4 KB samples before `e` (its edges and six between): a file truncated, rewritten, rotated or compacted
476
+ * fails it, or its identity or length does (a change between the samples of a file the client only appends to is not seen);
477
+ * c / s the CARRY: what a full read would know at `e` of the lines it does not read again (the session's last cwd, the last
478
+ * `steered` a line said, the session-kind reader's state; a subagent's first moment);
479
+ * b the offset of the first line holding a message after `t`: every line before it holds none, so a run whose watermark
480
+ * is `t` or later skips it unread. `b` is at or before the start of the earliest day not yet sent, and a day that spans
481
+ * the offset is therefore read again whole, from its first message: nothing of a stretch is kept between runs.
482
+ * and per transcript: `t` (the watermark `b` was cut for) and `v` (this hook's digest and the measure rules it ran under).
483
+ * A run resumes only with the same `v`, a watermark at or past `t`, and a file whose identity, length (at least `e`) and edges
484
+ * agree; it then reads from `b`, letting the lines between `b` and `e` add messages only and the lines from `e` on add both
485
+ * messages and carry. Anything else is a full read, as before 0.10.32: a new CLI, other measure rules, a state written without
486
+ * positions, a watermark moved back, a file that changed. The re-measure (`--history`, `--history --rebuild`, the offer after
487
+ * an update) never resumes. Proven equal to a full read by scripts/test-cli-read-position.mjs.
488
+ */
489
+ const positionKey = () => (selfDigest ? `${selfDigest.slice(0, 16)}|${DAY_RULES}` : null);
490
+ const resumesHere = (file) => /\.jsonl$/.test(String(file)) && !CODEX_ROLLOUT.test(file) && !ANTIGRAVITY_TRANSCRIPT.test(file) && !DATABASE_SESSION.test(file) && typeof sessionKindReader().state === "function";
491
+ const resumable = (saved, since) => Boolean(saved && typeof saved === "object" && positionKey() !== null && saved.v === positionKey() && (saved.t === null || (Number.isFinite(saved.t) && since !== null && since >= saved.t)));
492
+ const fileMarkOk = (mark) => Boolean(mark && typeof mark === "object" && typeof mark.d === "string" && typeof mark.i === "string" && Number.isSafeInteger(mark.e) && Number.isSafeInteger(mark.b) && mark.b >= 0 && mark.b <= mark.e && (mark.h === null ? mark.e === 0 : typeof mark.h === "string"));
493
+ const expectOf = (mark) => ({ dev: mark.d, ino: mark.i, end: mark.e, hash: mark.h });
494
+ /** The first line holding a message after `t`, among the messages read ([moment, line start]); `end` when there is none. */
495
+ const firstAfter = (pairs, t, end) => { let b = end; for (const [ms, start] of pairs) if ((t === null || ms > t) && start < b) b = start; return b; };
496
+ function stretchesOf(file, since, saved = null) {
497
+ if (resumesHere(file)) return claudeStretchesOf(file, since, resumable(saved, since) ? saved : null);
379
498
  // A file we cannot read is no days, never a null the caller has to remember to check: this
380
499
  // returns a list now, and one caller forgetting that is one silent crash inside a hook.
381
500
  const lines = parsedLines(file);
@@ -397,7 +516,47 @@ function stretchesOf(file, since) {
397
516
  messages.sort((a, b) => a.at - b.at);
398
517
  const byDay = byDayOf(messages);
399
518
  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);
519
+ return [...byDay.entries()].sort(([a], [b]) => a.localeCompare(b)).map(([day, ofDay]) => { const stretch = measure(cwd, ofDay, session); return stretch && { ...stretch, ref: stretchRef(file, day), steered, session, agents: agents.get(day) ?? null, live: liveOf(file, day) }; }).filter(Boolean);
520
+ }
521
+ /** stretchesOf for a Claude Code transcript, from its read position when `saved` holds a usable one; `positionAt(t)` on the list is the position to keep. */
522
+ function claudeStretchesOf(file, since, saved) {
523
+ if (!fileLines(file)) return [];
524
+ const prior = saved && fileMarkOk(saved.f) && saved.f.c && typeof saved.f.c === "object" ? saved.f : null;
525
+ const at = {}, pairs = [], messages = [];
526
+ let cwd = typeof prior?.c.cwd === "string" ? prior.c.cwd : null, lineSteered = typeof prior?.c.steered === "string" ? prior.c.steered : null, carry = null;
527
+ const kind = sessionKindReader(prior?.c.kind ?? null), scanFrom = prior ? prior.e : 0;
528
+ const snap = () => ({ cwd, steered: lineSteered, kind: kind.state() });
529
+ for (const line of claudeLinesFrom(file, prior ? prior.b : 0, at, prior ? expectOf(prior) : null)) {
530
+ if (carry === null && at.end !== undefined) carry = snap(); // the unterminated last line is past `e`: the carry stops before it
531
+ if (at.line >= scanFrom) {
532
+ if (typeof line.cwd === "string") cwd = line.cwd;
533
+ if (typeof line.steered === "string") lineSteered = line.steered;
534
+ kind.note(line);
535
+ }
536
+ if (!line.timestamp || (line.type !== "user" && line.type !== "assistant")) continue;
537
+ const ms = Date.parse(line.timestamp);
538
+ if (!Number.isFinite(ms)) continue;
539
+ if (since && ms <= since) continue;
540
+ messages.push(messageOf(line, ms)); pairs.push([ms, at.line]);
541
+ }
542
+ if (at.moved) return claudeStretchesOf(file, since, null);
543
+ if (carry === null && at.end !== undefined) carry = snap();
544
+ const steered = lineSteered ?? STEERED_HERE;
545
+ let stretches = [], subs = null;
546
+ if (messages.length > 0) {
547
+ messages.sort((a, b) => a.at - b.at);
548
+ const byDay = byDayOf(messages), positions = {};
549
+ const agents = agentsByDay(file, since, saved?.a ?? null, positions), session = kind.kind();
550
+ subs = positions;
551
+ stretches = [...byDay.entries()].sort(([a], [b]) => a.localeCompare(b)).map(([day, ofDay]) => { const stretch = measure(cwd, ofDay, session); return stretch && { ...stretch, ref: stretchRef(file, day), steered, session, agents: agents.get(day) ?? null, live: liveOf(file, day) }; }).filter(Boolean);
552
+ }
553
+ // A read that failed keeps no position: the next run reads the file whole.
554
+ if (!at.failed && at.end !== undefined && carry !== null) {
555
+ stretches.positionAt = (t) => ({ v: positionKey(), t: t ?? null, f: { d: at.dev, i: at.ino, e: at.end, b: firstAfter(pairs, t ?? null, at.end), h: at.hash ?? null, c: carry },
556
+ // Subagents not read this run (no message after the watermark) keep the marks they had: each was cut for a watermark at or before this one.
557
+ a: subs ? Object.fromEntries(Object.entries(subs).map(([name, markAt]) => [name, markAt(t ?? null)]).filter(([, mark]) => mark)) : (saved?.a && typeof saved.a === "object" ? saved.a : {}) });
558
+ }
559
+ return stretches;
401
560
  }
402
561
 
403
562
  /**
@@ -445,6 +604,10 @@ const messageOf = (line, at) => {
445
604
  // A tool that waits for the PERSON (a question, a plan to approve): the gap to its result is the person's, not the tool's. The name is read, never the input.
446
605
  waitsForPerson: line.type === "assistant" && blocks.some((block) => block && block.type === "tool_use" && WAITS_FOR_PERSON.has(String(block.name))),
447
606
  agentic: line.agentic === true, cumulative: line.cumulative === true, // the session's running totals (Hermes, Goose without a ledger)
607
+ // 0.10.32 (owner, 2026-10-28): who wrote a turn on the person's role (true the person, false a program or a timer, null not said),
608
+ // and an answer that did not complete (the app's own API-error line, a refusal), read for the call's outcome and never kept.
609
+ byPerson: line.type === "user" ? turnByPerson(line) : null,
610
+ failedAnswer: line.type === "assistant" && (line.isApiErrorMessage === true || line.message?.stop_reason === "refusal"),
448
611
  // 0.7.1: each tool call's kinds (never its command) and each tool result's outcome, joined on the call's id in `measure`.
449
612
  // 0.7.2: and the call's FAMILY (the tool, and its check kinds) and a digest of its input, compared here and never kept.
450
613
  calls: line.type === "assistant" ? blocks.filter((block) => block && block.type === "tool_use" && typeof block.id === "string").map(callOf) : [],
@@ -453,46 +616,92 @@ const messageOf = (line, at) => {
453
616
  };
454
617
 
455
618
  /**
456
- * SUBAGENTS AS AGENT TIME, NEVER AS HOURS (owner, 2026-10-06). Claude Code writes each subagent's transcript beside its
457
- * session (`<session>/subagents/*.jsonl`: 279 of them beside 48 sessions on the computer this was built on), and the
458
- * sweep read only the sessions, so delegated work was invisible. Each run is read for its clocks: how many runs started
459
- * that day and how many were open at once at the busiest moment (read here for the complexity class). Their SECONDS are
460
- * not computed here since 0.10.20 (no counting rule ships in this file); until a timeline per run travels, the agent
461
- * group is not sent. Only Claude Code keeps subagents this way; every other client answers an empty map.
619
+ * SUBAGENTS AS AGENT TIME, NEVER AS HOURS (owner, 2026-10-06; AGENTS ACTIVE AT ONCE, 0.10.32, owner 2026-10-28). Claude Code
620
+ * writes each subagent's transcript beside its session (`<session>/subagents/*.jsonl`, and a `.meta.json` saying how it was
621
+ * started). Each run that started on a day rides with that day's stretch as one entry of `agents`, by position (the ordinal),
622
+ * never a name, a prompt, a path or an id: its kind (`fork`, else `background`, else `builtin` or the person's `own` type), its
623
+ * start in whole seconds from the stretch's start, its ACTIVE intervals from that start ([from, to, from, to, …]; a gap over
624
+ * 300 s ends one) and its tool failures and recoveries (stretch-evidence's own rule). At most AGENT_RUNS runs a stretch,
625
+ * AGENT_INTERVALS intervals a run and AGENT_INTERVALS_TOTAL in all, the longest kept: a dropped one reads as less, never more.
626
+ * WorkTrust counts a run only inside its parent's steered window (docs/AGENT-HOURS.md). Only Claude Code keeps subagents this way.
462
627
  */
628
+ const AGENT_RUNS = 64, AGENT_INTERVALS = 12, AGENT_INTERVALS_TOTAL = 256, AGENT_GAP_MS = 300_000, BUILTIN_AGENTS = new Set(["general-purpose", "Explore", "Plan", "statusline-setup", "output-style-setup", "claude-code-guide"]);
629
+ const agentKindOf = (meta) => (meta?.isFork === true || meta?.agentType === "fork" ? "fork" : meta?.requestShape === "background" ? "background" : meta?.isBuiltIn === true || !meta || BUILTIN_AGENTS.has(meta.agentType) ? "builtin" : "own");
463
630
  function subagentFiles(file) {
464
631
  if (!/\.jsonl$/.test(String(file)) || CODEX_ROLLOUT.test(file) || ANTIGRAVITY_TRANSCRIPT.test(file) || DATABASE_SESSION.test(file)) return [];
465
632
  const dir = join(String(file).replace(/\.jsonl$/, ""), "subagents");
466
633
  try { return readdirSync(dir).filter((name) => name.endsWith(".jsonl")).map((name) => join(dir, name)); } catch { return []; }
467
634
  }
468
- function agentsByDay(file, since) {
635
+ /** A file whose identity, length and edges are still those of its mark: the bytes before `e` are the ones read then. */
636
+ const unchangedSince = (file, mark) => { let fd; try { fd = openSync(file, "r"); } catch { return false; } try { const stat = fstatSync(fd); return String(stat.dev) === mark.d && String(stat.ino) === mark.i && stat.size >= mark.e && (mark.e === 0 ? mark.h === null : edgesOf(fd, mark.e) === mark.h); } catch { return false; } finally { closeSync(fd); } };
637
+ /** One subagent transcript's lines, from its mark when it has a usable one: its first moment, its stamps and messages after `since`, and the mark to keep. */
638
+ function subagentRead(sub, since, prior) {
639
+ const at = {}, stamps = [], messages = [], pairs = [];
640
+ let started = prior ? (Number.isFinite(prior.s) ? prior.s : Infinity) : Infinity, carry = null;
641
+ for (const line of claudeLinesFrom(sub, prior ? prior.b : 0, at, prior ? expectOf(prior) : null)) {
642
+ if (carry === null && at.end !== undefined) carry = started;
643
+ if (!line.timestamp || (line.type !== "user" && line.type !== "assistant")) continue;
644
+ const ms = Date.parse(line.timestamp);
645
+ if (!Number.isFinite(ms)) continue;
646
+ started = Math.min(started, ms); // a line between `b` and `e` is in the carried minimum already: a minimum taken twice is the same
647
+ if (!(since && ms <= since)) { stamps.push(ms); messages.push(messageOf(line, ms)); pairs.push([ms, at.line]); }
648
+ }
649
+ if (at.moved) return subagentRead(sub, since, null);
650
+ if (carry === null && at.end !== undefined) carry = started;
651
+ const markAt = at.failed || at.end === undefined || carry === null ? () => null : (t) => ({ d: at.dev, i: at.ino, e: at.end, b: firstAfter(pairs, t, at.end), h: at.hash ?? null, s: Number.isFinite(carry) ? carry : null });
652
+ return { started, stamps, messages, markAt };
653
+ }
654
+ function agentsByDay(file, since, saved = null, positions = null) {
469
655
  const byDay = new Map();
470
656
  for (const sub of subagentFiles(file)) {
657
+ const name = String(sub).split(/[\\/]/).pop(), prior = positions && saved && typeof saved === "object" && fileMarkOk(saved[name]) && (saved[name].s === null || Number.isFinite(saved[name].s)) ? saved[name] : null;
658
+ // A RUN THAT STARTED AT OR BEFORE THE WATERMARK is not counted (below), and lines appended since cannot make it start later:
659
+ // a subagent whose kept first moment is at or before the watermark, its bytes unchanged, is not opened again.
660
+ if (prior && since && prior.s !== null && prior.s <= since && unchangedSince(sub, prior)) { positions[name] = () => prior; continue; }
661
+ if (positions ? !fileLines(sub) : false) continue;
662
+ let stamps, messages, started;
663
+ if (positions) { const read = subagentRead(sub, since, prior); ({ stamps, messages, started } = read); positions[name] = read.markAt; }
664
+ else {
471
665
  const lines = parsedLines(sub);
472
666
  if (!lines) continue;
473
- const stamps = [];
474
- let started = Infinity;
667
+ stamps = []; messages = [];
668
+ started = Infinity;
475
669
  for (const line of lines) {
476
670
  if (!line.timestamp || (line.type !== "user" && line.type !== "assistant")) continue;
477
671
  const at = Date.parse(line.timestamp);
478
672
  if (!Number.isFinite(at)) continue;
479
673
  started = Math.min(started, at);
480
- if (!(since && at <= since)) stamps.push(at);
674
+ if (!(since && at <= since)) { stamps.push(at); messages.push(messageOf(line, at)); }
481
675
  }
482
- // A RUN IS COUNTED ONCE, on the side of the watermark where it STARTED (review, 2026-10-06): a run that straddles the
483
- // watermark was sent with the day it began and is not a second run on the next sweep; what it did after the
484
- // watermark stays unsent, which is the safe direction.
676
+ }
677
+ // A RUN IS COUNTED ONCE, on the side of the watermark where it STARTED (review, 2026-10-06), and on the day it started: a run
678
+ // that straddles the watermark was sent with the day it began; what it did after the watermark stays unsent (the safe direction).
485
679
  if (stamps.length === 0 || (since && started <= since)) continue;
486
- stamps.sort((a, b) => a - b);
487
- // A run is counted on the day it started.
680
+ stamps.sort((a, b) => a - b); messages.sort((a, b) => a.at - b.at);
488
681
  const day = new Date(stamps[0]).toISOString().slice(0, 10);
489
- if (!byDay.has(day)) byDay.set(day, { runs: 0, spans: [] });
490
- const entry = byDay.get(day);
682
+ if (!byDay.has(day)) byDay.set(day, { runs: 0, spans: [], list: [] });
683
+ const entry = byDay.get(day), recovery = recoveryOf ? recoveryOf(messages) : null;
684
+ let meta = null; try { meta = JSON.parse(readFileSync(sub.replace(/\.jsonl$/, ".meta.json"), "utf8")); } catch { /* an older client wrote none */ }
491
685
  entry.runs += 1; entry.spans.push([stamps[0], stamps[stamps.length - 1]]);
686
+ entry.list.push({ stamps, kind: agentKindOf(meta), failures: recovery?.failures ?? 0, recovered: recovery?.recovered ?? 0 });
492
687
  }
493
688
  for (const entry of byDay.values()) entry.peak = peakOf(entry.spans);
494
689
  return byDay;
495
690
  }
691
+ /** A day's runs → the payload's `agents`, from the stretch's first moment: whole seconds, the caps applied, null when none ran. */
692
+ function agentRunsOf(list, from) {
693
+ const longest = (items, cap, length) => (items.length <= cap ? items : items.map((item, at) => ({ item, at })).sort((a, b) => length(b.item) - length(a.item) || a.at - b.at).slice(0, cap).sort((a, b) => a.at - b.at).map(({ item }) => item));
694
+ const runs = (list ?? []).map((run) => {
695
+ const spans = [];
696
+ for (const at of run.stamps) { const last = spans.at(-1); if (last && at - last[1] <= AGENT_GAP_MS) last[1] = at; else spans.push([at, at]); }
697
+ return { ...run, spans: spans.map(([lo, hi]) => [Math.max(0, Math.round((lo - from) / 1000)), Math.max(0, Math.round((hi - from) / 1000))]).filter(([lo, hi]) => hi > lo) };
698
+ }).filter((run) => run.spans.length > 0);
699
+ const kept = longest(runs, AGENT_RUNS, (run) => run.spans.reduce((total, [lo, hi]) => total + hi - lo, 0)), length = ([lo, hi]) => hi - lo;
700
+ let per = AGENT_INTERVALS; // the most intervals a run keeps so that all of them together stay inside AGENT_INTERVALS_TOTAL
701
+ while (per > 1 && kept.reduce((total, run) => total + Math.min(per, run.spans.length), 0) > AGENT_INTERVALS_TOTAL) per -= 1;
702
+ return kept.length > 0 ? kept.map((run) => { const spans = longest(run.spans, per, length), start = spans[0][0];
703
+ return { kind: run.kind, start, active: spans.flatMap(([lo, hi]) => [lo - start, hi - start]), failures: run.failures, recovered: Math.min(run.recovered, run.failures) }; }).sort((a, b) => a.start - b.start) : null;
704
+ }
496
705
  /** The most spans open at one instant; a span that ends where another starts does not overlap it. */
497
706
  const peakOf = (spans) => {
498
707
  const events = spans.flatMap(([from, to]) => [[from, 1], [to, -1]]).sort((a, b) => a[0] - b[0] || a[1] - b[1]);
@@ -524,7 +733,7 @@ function isHumanTurn(content) {
524
733
  }
525
734
 
526
735
  /** One day's messages → the stretch: its timeline, its tokens, its model. The server measures it. */
527
- function measure(cwd, messages) {
736
+ function measure(cwd, messages, session = null) {
528
737
  // THE CLOCK IS THE SERVER'S (0.10.20). This hook sends the stretch's timeline and never a duration of its own: every
529
738
  // second WorkTrust counts lies between two recorded timestamps in that timeline, under WorkTrust's rules, and a stretch
530
739
  // too short to time is a stretch WorkTrust answers without a duration. A stretch whose clocks give nothing is still
@@ -534,7 +743,8 @@ function measure(cwd, messages) {
534
743
  const model = [...models.entries()].sort((a, b) => b[1] - a[1])[0]?.[0] ?? null;
535
744
  const tokens = tokensOf(messages);
536
745
  const from = firstOf(messages);
537
- return { cwd, derived: deriveStretch(messages, { isHumanTurn, INTERRUPTED, textOf }), timeline: messages.length > 0 ? timelineOf(messages) : null, ...tokens, cumulative: messages.some((message) => message.cumulative), model, from, to: messages[messages.length - 1].at, offset: offsetAt(from) };
746
+ const unattended = session === "headless" || session === "scheduled";
747
+ return { cwd, derived: deriveStretch(messages, { isHumanTurn, INTERRUPTED, textOf }), timeline: messages.length > 0 ? timelineOf(messages, unattended) : null, outcomes: messages.length > 0 ? callOutcomesOf(messages) : null, lengths: inputLengthsOf(messages, unattended), ...tokens, cumulative: messages.some((message) => message.cumulative), model, from, to: messages[messages.length - 1].at, offset: offsetAt(from) };
538
748
  }
539
749
 
540
750
  /**
@@ -545,16 +755,50 @@ function measure(cwd, messages) {
545
755
  * turns from this with its own rules (private to the server); this file sends no figure of its own, so nothing in it can
546
756
  * move the passport.
547
757
  */
548
- function timelineOf(messages) {
758
+ // 0.10.32: in a run no person started (headless, scheduled) a turn is H only when the app marked it the person's; a program's or
759
+ // a timer's prompt is U, so WorkTrust's clock steers only from a person's input.
760
+ const stepKindOf = (message, unattended) => message.kind === "assistant" ? (message.waitsForPerson ? "W" : message.toolUse ? "T" : "A") : message.kind === "tool_result" ? "R" : INTERRUPTED.test(textOf(message.content).trim()) && !message.meta ? "I" : !message.meta && isHumanTurn(message.content) && (!unattended || message.byPerson === true) ? "H" : "U";
761
+ function timelineOf(messages, unattended = false) {
549
762
  let out = "";
550
763
  for (let i = 0; i < messages.length; i += 1) {
551
764
  const message = messages[i];
552
765
  const gap = i === 0 ? 0 : Math.max(0, Math.round((message.at - messages[i - 1].at) / 1000));
553
- const kind = message.kind === "assistant" ? (message.waitsForPerson ? "W" : message.toolUse ? "T" : "A") : message.kind === "tool_result" ? "R" : INTERRUPTED.test(textOf(message.content).trim()) && !message.meta ? "I" : !message.meta && isHumanTurn(message.content) ? "H" : "U";
766
+ const kind = stepKindOf(message, unattended);
554
767
  out += `${message.agentic ? "G" : ""}${message.bridge ? kind.toLowerCase() : kind}${Math.min(999999, gap)}`;
555
768
  }
556
769
  return out;
557
770
  }
771
+ /**
772
+ * THE PERSON'S INPUTS, AS LENGTH BUCKETS (owner, 2026-10-28; 0.10.32): in a run no person started, one character per H step of
773
+ * the timeline: s up to 80 characters, m up to 400, l longer. Counted here, never sent as text; WorkTrust's steering cap reads it
774
+ * to tell a regular rhythm of short nudges from real steering, as a review signal only.
775
+ */
776
+ function inputLengthsOf(messages, unattended) {
777
+ if (!unattended) return null;
778
+ let out = "";
779
+ for (const message of messages) if (stepKindOf(message, unattended) === "H") { const n = textOf(message.content).trim().length; out += n <= 80 ? "s" : n <= 400 ? "m" : "l"; }
780
+ return out.length > 0 ? out : null;
781
+ }
782
+ /**
783
+ * EACH CALL'S OUTCOME (owner, 2026-10-28; 0.10.32; docs/AGENTIC-OPERATIONS.md "2b"): one character per model answer step of the
784
+ * timeline (A, T, W), in its order. 1: it completed; 0: it did not (a tool result the app marked as an error, a timeout or a
785
+ * refusal among them; an API-error or refusal answer); ?: not known (a tool call without its result, a result no reader could see).
786
+ * A question to the person (W) completed when it was put. Read from the app's own markers, never from a duration; nothing of a
787
+ * message travels.
788
+ */
789
+ function callOutcomesOf(messages) {
790
+ const failed = new Map();
791
+ for (const message of messages) for (const result of message.results ?? []) if (result && typeof result.id === "string") failed.set(result.id, result.failed);
792
+ let out = "";
793
+ for (const message of messages) {
794
+ if (message.kind !== "assistant") continue;
795
+ if (message.failedAnswer) { out += "0"; continue; }
796
+ if (message.waitsForPerson || !message.toolUse) { out += "1"; continue; }
797
+ const outcomes = (message.calls ?? []).map((call) => (failed.has(call.id) ? failed.get(call.id) : null));
798
+ out += outcomes.some((one) => one === true) ? "0" : outcomes.length > 0 && outcomes.every((one) => one === false) ? "1" : "?";
799
+ }
800
+ return /[01]/.test(out) ? out : null;
801
+ }
558
802
  /** A digest of this hook and the readers beside it, as installed: the door records it beside each line as a signal of which code ran, never as proof. */
559
803
  const selfDigest = (() => { try { const here = dirname(fileURLToPath(import.meta.url)); const hash = createHash("sha256"); for (const name of ["log-session.mjs", ...READER_FILES].sort()) { try { hash.update(`${name}\0`).update(readFileSync(join(here, name))).update("\0"); } catch { hash.update(`${name}\0missing\0`); } } return hash.digest("hex"); } catch { return null; } })();
560
804
  const CLI_VERSION_SENT = /^[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,4}$/.test(process.env.WORKTRUST_CLI_VERSION ?? "") ? process.env.WORKTRUST_CLI_VERSION : null; // `worktrust.mjs` hands its own version to the hook it starts
@@ -621,6 +865,7 @@ function payloadFor(stretch) {
621
865
  const coauthored = cwd && touched.shas.length > 0 ? git(cwd, "log", "--no-walk", "--format=%(trailers:key=Co-authored-by,valueonly,separator=%x01)%x00", ...touched.shas.slice(0, 50)).split("\0").filter((entry, index) => index < Math.min(50, touched.shas.length) && AI_COAUTHOR.test(entry)).length : 0;
622
866
  const route = { ...(stretch.derived?.route ?? {}), ...(touched.committed ? gitRouteOf(cwd, touched.shas, changed) : {}) };
623
867
  const derived = stretch.derived ? { ...stretch.derived, ...(Object.keys(route).length > 0 ? { route } : {}), ...(changed.length > 0 ? { changes: { files: changed.length, test_files: tests } } : {}), ...(touched.shas.length > 0 ? { authorship: { commits: Math.min(50, touched.shas.length), ai_coauthored: coauthored } } : {}), ...(contextFilesOf(changed) ? { context_files: contextFilesOf(changed) } : {}), ...(complexityOf ? { complexity: complexityOf(stretch.derived, { layers: Math.max(layers.length, layer ? 1 : 0), agentRuns: stretch.agents?.runs ?? 0, agentPeak: stretch.agents?.peak ?? 0, seconds: null }) } : {}) } : null;
868
+ const agents = agentRunsOf(stretch.agents?.list, stretch.from);
624
869
  const evidence = derived || stretch.live ? { ...(derived ?? {}), ...(stretch.live ? { live: stretch.live } : {}) } : null; // 0.10.15: the mod's counts ride as their own group
625
870
  const payload = {
626
871
  title: layer ? `AI-assisted work · ${layer}` : "AI-assisted work",
@@ -647,11 +892,16 @@ function payloadFor(stretch) {
647
892
  ...(stretch.ref ? { stretch_ref: stretch.ref } : {}), ...(stretch.steered ? { steered_from: stretch.steered } : {}),
648
893
  // HOW THE SESSION WAS STARTED (owner, 2026-10-22): interactive | headless | scheduled, beside the timeline; unknown is unsaid.
649
894
  ...(stretch.timeline && (stretch.session === "interactive" || stretch.session === "headless" || stretch.session === "scheduled") ? { session_kind: stretch.session } : {}),
895
+ // EACH CALL'S OUTCOME and THE TIMER'S SCHEDULE (owner, 2026-10-28; 0.10.32): beside the timeline; a schedule only for a run no person started.
896
+ ...(stretch.timeline && stretch.outcomes ? { call_outcomes: stretch.outcomes } : {}),
897
+ ...(stretch.timeline && stretch.lengths && (stretch.session === "headless" || stretch.session === "scheduled") ? { input_lengths: stretch.lengths } : {}),
898
+ ...(stretch.timeline && stretch.schedule && (stretch.session === "headless" || stretch.session === "scheduled") ? { schedule_cadence: stretch.schedule.cadence, schedule_ref: stretch.schedule.ref } : {}),
899
+ // AGENTS ACTIVE AT ONCE (0.10.32, owner 2026-10-28): the subagent runs that started this day, beside the timeline (agentRunsOf).
900
+ ...(stretch.timeline && agents ? { agents } : {}),
650
901
  // WHICH CODE SENT IT (0.10.20): a version and a digest of this hook's own files, signals never proof.
651
902
  ...(CLI_VERSION_SENT ? { cli_version: CLI_VERSION_SENT } : {}),
652
903
  ...(selfDigest ? { cli_digest: selfDigest } : {}),
653
- // WHEN (0.6.18): the stretch's first moment and the computer's UTC offset then. The interruptions and the mid-task turns are
654
- // read by WorkTrust from the timeline; the subagents' seconds wait for a timeline per run (0.10.20).
904
+ // WHEN (0.6.18): the stretch's first moment and the computer's UTC offset then; the interruptions and mid-task turns are WorkTrust's.
655
905
  started_at: new Date(stretch.from).toISOString(), utc_offset: stretch.offset,
656
906
  // THE STRETCH'S EVIDENCE (0.8.3): what the CLI derived from it here, kinds and counts only (stretch-evidence.mjs); the door keeps it from a CLI key alone.
657
907
  ...(evidence ? { evidence } : {}),
@@ -712,8 +962,13 @@ const noteReceipt = (answer) => {
712
962
  const json = JSON.parse(answer.trim().startsWith("{") ? answer : answer.split("\n").find((row) => row.startsWith("data:"))?.slice(5) ?? "null");
713
963
  const receipt = JSON.parse(json?.result?.content?.[0]?.text ?? "{}");
714
964
  for (const key of Object.keys(RECEIPTS)) RECEIPTS[key] += Number(receipt[key]) || 0;
965
+ // THE QUEUE (0.10.32): the receipt of the batch that completes a run says where the run waits; the last one seen is kept.
966
+ const queued = receipt.queued;
967
+ if (queued && Number.isInteger(queued.position) && queued.position >= 1 && Number.isFinite(Number(queued.eta_minutes)) && Number(queued.eta_minutes) >= 0) QUEUED.at = { position: queued.position, eta_minutes: Math.max(1, Math.ceil(Number(queued.eta_minutes))) };
715
968
  } catch { /* a receipt unread leaves the counts short, never the send */ }
716
969
  };
970
+ /** Where the last completed run waits in WorkTrust's queue (0.10.32): null when no receipt said so (an older server, or not complete yet). */
971
+ const QUEUED = { at: null };
717
972
  /** Only explicit durable receipts authorize a checkpoint. HTTP 200 alone says nothing. */
718
973
  function confirmedReceipt(answer, expectedCount = null) {
719
974
  try {
@@ -739,7 +994,7 @@ function confirmedReceipt(answer, expectedCount = null) {
739
994
  }
740
995
  /** A private metadata journal survives retries, an edited transcript and a later CLI update. */
741
996
  function retainMeasurement(payload, source) {
742
- const fields = ["stretch_ref", "at", "started_at", "timeline", "seconds", "client_seconds", "model_seconds", "tool_seconds", "human_seconds", "idle_seconds", "tokens_in", "tokens_out", "tokens_cache_read", "tokens_cache_write", "exchanges", "interrupts", "steers", "agent_runs", "agent_seconds", "agent_peak", "duration_basis", "token_basis", "turn_basis", "cli_version", "cli_digest"];
997
+ const fields = ["stretch_ref", "at", "started_at", "timeline", "seconds", "client_seconds", "model_seconds", "tool_seconds", "human_seconds", "idle_seconds", "tokens_in", "tokens_out", "tokens_cache_read", "tokens_cache_write", "exchanges", "interrupts", "steers", "agent_runs", "agent_seconds", "agent_peak", "agents", "duration_basis", "token_basis", "turn_basis", "cli_version", "cli_digest"];
743
998
  const metadata = Object.fromEntries(fields.filter(key => Object.hasOwn(payload, key)).map(key => [key, payload[key]]));
744
999
  const body = JSON.stringify({ format: "worktrust-measurement/1", source: source ?? "claude", metadata }) + "\n";
745
1000
  const parent = join(homedir(), ".worktrust"), dir = join(parent, "measurements");
@@ -756,6 +1011,80 @@ function retainMeasurement(payload, source) {
756
1011
  } finally { closeSync(fd); unlinkSync(temporary); }
757
1012
  }
758
1013
  const HISTORY_DELIVERY = { review: 0, waiting: 0, refused: 0 };
1014
+ const HISTORY_PERSISTED = { n: 0 }; // 0.10.32: entries this run put in the outbox on disk (sent now or later, never lost)
1015
+ /**
1016
+ * ONLY THE DAYS THAT CHANGED (0.10.32; owner, 2026-10-28: an identical re-run sends 0 days). Each UTC day of each AI app gets a
1017
+ * digest of its entries exactly as they are sent (the canonical JSON of each, `commits` gone, the CLI's own version and digest
1018
+ * left out, so an update that measures the same sends nothing), under the measure rules the command started this hook with.
1019
+ * Before a re-measure the door is asked, per AI app, which of this computer's days it still holds as current; it answers the
1020
+ * digests this computer sent with them (its own submissions, never the record). A day whose digest is the same is not sent.
1021
+ * An answer that is not one (an error, an older WorkTrust, no network) is NOT KNOWN, and every day goes, as before.
1022
+ */
1023
+ const DAY_RULES = /^[1-9][0-9]{0,3}$/.test(process.env.WORKTRUST_MEASURE_RULES ?? "") ? process.env.WORKTRUST_MEASURE_RULES : "unknown";
1024
+ const canonical = (value) => (Array.isArray(value) ? `[${value.map(canonical).join(",")}]` : value && typeof value === "object" ? `{${Object.keys(value).sort().filter((key) => value[key] !== undefined).map((key) => `${JSON.stringify(key)}:${canonical(value[key])}`).join(",")}}` : JSON.stringify(value) ?? "null");
1025
+ const entryDigest = (entry) => { const { commits: _commits, cli_version: _version, cli_digest: _digest, ...rest } = entry; void _commits; void _version; void _digest; return createHash("sha256").update(canonical(rest)).digest("hex"); };
1026
+ const dayOf = (entry) => new Date(entry.at).toISOString().slice(0, 10);
1027
+ /** One AI app's entries → day → digest, over all of that app's entries of the day (a day cut across two batches has one digest). */
1028
+ function dayDigests(entries) {
1029
+ const byDay = new Map();
1030
+ for (const entry of entries) { const day = dayOf(entry); byDay.set(day, [...(byDay.get(day) ?? []), entryDigest(entry)]); }
1031
+ return new Map([...byDay].map(([day, digests]) => [day, createHash("sha256").update(`worktrust-day/1|rules=${DAY_RULES}|${digests.sort().join("\n")}`).digest("hex")]));
1032
+ }
1033
+ /** The days the door holds as current for this computer and this AI app, or null when that is not known. Never throws. */
1034
+ async function heldDays(target, source) {
1035
+ try {
1036
+ const body = JSON.stringify({ jsonrpc: "2.0", id: 1, method: "tools/call", params: { name: "import_history", arguments: { rebuild: true, fingerprint: true } } });
1037
+ const response = await fetch(target.url, { method: "POST", headers: { "content-type": "application/json", accept: "application/json, text/event-stream", authorization: `Bearer ${target.token}`, ...clientOf(source, true), ...proofFor(target.url, body) }, body, redirect: "error", signal: AbortSignal.timeout(20_000) });
1038
+ if (!response.ok) return null;
1039
+ const text = await response.text();
1040
+ const json = JSON.parse(text.trim().startsWith("{") ? text : text.split("\n").find((row) => row.startsWith("data:"))?.slice(5) ?? "null");
1041
+ if (json?.jsonrpc !== "2.0" || json.error || !json.result || json.result.isError === true) return null;
1042
+ const answer = JSON.parse(json.result.content?.[0]?.text ?? "null");
1043
+ if (answer?.receipt !== "fingerprint" || !answer.days || typeof answer.days !== "object" || Array.isArray(answer.days)) return null;
1044
+ const held = new Map();
1045
+ for (const [day, digest] of Object.entries(answer.days)) if (/^\d{4}-\d{2}-\d{2}$/.test(day) && typeof digest === "string" && /^[0-9a-f]{64}$/.test(digest)) held.set(day, digest);
1046
+ return held;
1047
+ } catch { return null; }
1048
+ }
1049
+ /**
1050
+ * A READ FAILURE, KEPT AND TOLD (0.10.32): the count lands in sessions.json (`__unreadable`, which `npx worktrust status`
1051
+ * prints) and, at most once a day, reaches WorkTrust as the fingerprint question with the count beside it
1052
+ * (`unreadable: n`): a number, never a file name, a path or a line. A run that read everything clears the count.
1053
+ */
1054
+ async function settleReadFailures(target, held = null) {
1055
+ // `held`: the hook's own state object, which later steps write back whole; the count goes into it, not beside it.
1056
+ const state = held ?? readState(), now = new Date().toISOString();
1057
+ if (READ_FAILURES.n === 0) { if (state.__unreadable?.count) { state.__unreadable = { count: 0, at: now }; writeState(state); } return; }
1058
+ state.__unreadable = { count: READ_FAILURES.n, at: now };
1059
+ const told = Date.parse(state.__unreadableTold ?? "") || 0;
1060
+ if (target?.url && target?.token && Date.now() - told > 24 * 3600_000) {
1061
+ try {
1062
+ const body = JSON.stringify({ jsonrpc: "2.0", id: 1, method: "tools/call", params: { name: "import_history", arguments: { rebuild: true, fingerprint: true, unreadable: Math.min(1000, READ_FAILURES.n) } } });
1063
+ const response = await fetch(target.url, { method: "POST", headers: { "content-type": "application/json", accept: "application/json, text/event-stream", authorization: `Bearer ${target.token}`, ...clientOf(undefined, true), ...proofFor(target.url, body) }, body, redirect: "error", signal: AbortSignal.timeout(20_000) });
1064
+ if (response.ok) state.__unreadableTold = now;
1065
+ } catch { /* told next time */ }
1066
+ }
1067
+ writeState(state);
1068
+ }
1069
+ /** What the comparison found, for the command's one line: distinct days compared, and of them how many changed. */
1070
+ const COMPARED = { days: 0, changed: 0, asked: false };
1071
+ /** A re-measure's entries, less every (AI app, day) whose digest WorkTrust holds as current. */
1072
+ async function changedOnly(entries) {
1073
+ const bySource = new Map();
1074
+ for (const entry of entries) { const source = entrySource.get(entry) ?? "claude"; bySource.set(source, [...(bySource.get(source) ?? []), entry]); }
1075
+ const keep = new Set(), allDays = new Set(), changedDays = new Set();
1076
+ for (const [source, group] of bySource) {
1077
+ const target = source === "codex" ? codexDoor ?? door : door;
1078
+ const digests = dayDigests(group);
1079
+ const held = target ? await heldDays(target, source) : null;
1080
+ if (held !== null) COMPARED.asked = true;
1081
+ for (const [day, digest] of digests) { allDays.add(day); if (held?.get(day) !== digest) changedDays.add(`${source}|${day}`); }
1082
+ for (const entry of group) if (changedDays.has(`${source}|${dayOf(entry)}`)) keep.add(entry);
1083
+ }
1084
+ COMPARED.days = allDays.size;
1085
+ COMPARED.changed = new Set([...changedDays].map((key) => key.split("|")[1])).size;
1086
+ return entries.filter((entry) => keep.has(entry));
1087
+ }
759
1088
  /**
760
1089
  * ONE RUN PER COUPLING (0.10.27; owner, 2026-10-21: re-measured history is kept on the server). The batches of a re-measure
761
1090
  * to one key are one run: an id, each batch's number and the run's count ride in every batch, and WorkTrust keeps each batch
@@ -774,13 +1103,15 @@ const historyRunId = (bodies) => {
774
1103
  function historyPlan(door, entries, rebuild = false, { byDay = false, withdrawUnknown = false } = {}) {
775
1104
  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)])];
776
1105
  // Imported entries carry no live commit/session join.
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 } : {}) } } });
1106
+ const encodeBatch = (batch, run = null, days = 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 } : {}), ...(days ? { days } : {}) } } });
778
1107
  const plan = groups.flatMap(([source, group]) => { const target = source === "codex" ? codexDoor ?? door : door; return group.length > 0 && target ? batchesOf(group, byDay).map((batch) => ({ source, target, batch, run: null })) : []; });
779
1108
  if (rebuild && !byDay) for (const token of new Set(plan.map((item) => item.target.token))) {
780
1109
  const run = plan.filter((item) => item.target.token === token), id = historyRunId(run.map((item) => encodeBatch(item.batch)));
781
1110
  run.forEach((item, index) => { item.run = { id, index, count: run.length }; });
782
1111
  }
783
- for (const item of plan) item.body = encodeBatch(item.batch, item.run);
1112
+ // 0.10.32: each batch of a staged run names its days' digests (of the AI app's whole plan for the day), only the days it carries.
1113
+ const digestsOf = new Map(groups.map(([source, group]) => [source, dayDigests(group)]));
1114
+ for (const item of plan) item.body = encodeBatch(item.batch, item.run, item.run ? daysOf(item.batch, digestsOf.get(item.source)) : null);
784
1115
  return plan;
785
1116
  }
786
1117
  /**
@@ -789,21 +1120,25 @@ function historyPlan(door, entries, rebuild = false, { byDay = false, withdrawUn
789
1120
  * 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
1121
  * 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
1122
  */
1123
+ /** A batch's own days and their digests, from the AI app's day digests. */
1124
+ const daysOf = (batch, digests) => Object.fromEntries([...new Set(batch.map(dayOf))].sort().filter((day) => digests?.has(day)).map((day) => [day, digests.get(day)]));
792
1125
  const outboxCut = {
793
1126
  fits: (entries) => fits(entries),
794
1127
  split(rpc, source, tighter) {
795
1128
  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 } } }));
1129
+ return pieces.length < 2 ? [] : pieces.map((batch) => { const { days, ...rest } = args; const own = days && typeof days === "object" ? Object.fromEntries(Object.entries(days).filter(([day]) => batch.some((entry) => dayOf(entry) === day))) : null; return JSON.stringify({ ...rpc, params: { ...rpc.params, arguments: { ...rest, entries: batch, ...(own ? { days: own } : {}) } } }); });
797
1130
  },
798
1131
  replan(batches, tighter) {
799
1132
  const limit = tighter ? halfOf(tighter) : BATCH_LIMIT, bySource = new Map();
800
1133
  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;
1134
+ const { run: _run, entries: _entries, days: _days, ...args } = batches[0].rpc.params.arguments; void _run; void _entries; void _days;
802
1135
  const plan = [...bySource].flatMap(([source, group]) => batchesOf(group, false, limit).map((batch) => ({ source, batch })));
803
1136
  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 } : {}) } } });
1137
+ // 0.10.32: the days' digests follow the new cut, each batch naming only the days it carries.
1138
+ const digests = new Map([...bySource].map(([source, group]) => [source, dayDigests(group)]));
1139
+ const encode = (batch, run = null, days = null) => JSON.stringify({ jsonrpc: "2.0", id: 1, method: "tools/call", params: { name: "import_history", arguments: { ...args, entries: batch, ...(run ? { run } : {}), ...(days ? { days } : {}) } } });
805
1140
  const id = historyRunId(plan.map(({ batch }) => encode(batch)));
806
- return plan.map(({ source, batch }, index) => ({ source, body: encode(batch, { id, index, count: plan.length }) }));
1141
+ return plan.map(({ source, batch }, index) => ({ source, body: encode(batch, { id, index, count: plan.length }, daysOf(batch, digests.get(source))) }));
807
1142
  },
808
1143
  };
809
1144
  async function sendHistory(door, entries, announce = false, rebuild = false, named = false, { byDay = false, withdrawUnknown = false } = {}) {
@@ -813,6 +1148,9 @@ async function sendHistory(door, entries, announce = false, rebuild = false, nam
813
1148
  // Persist the approved plan before sending, so later batches survive removed source files too.
814
1149
  try { for (const item of plan) queuedHistory(item.target, item.body, item.source); }
815
1150
  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; }
1151
+ // Every entry is now in the outbox, on disk, and goes again by itself until WorkTrust takes it (0.10.32: what the hook's
1152
+ // late days may count on, so a late day not yet filed never holds a transcript's newer days back).
1153
+ HISTORY_PERSISTED.n += entries.length;
816
1154
  const numbers = new Map(), stopped = new Set();
817
1155
  // 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
1156
  // 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.
@@ -957,7 +1295,7 @@ function historyEntries(floor = null, all = false) {
957
1295
  // The live window belongs to the hook: a stretch that log_work may still report is not history.
958
1296
  if (!all && Date.now() - last < WINDOW_HOURS * 3600_000) continue;
959
1297
  // The same measure as a live day (seconds, layers, tokens, turns, model); history differs only in the door it goes through.
960
- const entry = payloadFor({ ...measure(cwd, messages), ref: stretchRef(file, day), steered, session, agents: agents.get(day) ?? null, live: liveOf(file, day) });
1298
+ const entry = payloadFor({ ...measure(cwd, messages, session), ref: stretchRef(file, day), steered, session, agents: agents.get(day) ?? null, live: liveOf(file, day) });
961
1299
  if (CODEX_ROLLOUT.test(file)) entrySource.set(entry, "codex");
962
1300
  if (ANTIGRAVITY_TRANSCRIPT.test(file)) entrySource.set(entry, "antigravity");
963
1301
  if (DATABASE_SESSION.test(file)) entrySource.set(entry, file.slice(0, file.indexOf(":")));
@@ -1350,7 +1688,7 @@ if (flag("history")) {
1350
1688
  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
1689
  const kinds = { interactive: 0, headless: 0, scheduled: 0, unknown: 0 };
1352
1690
  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,
1691
+ console.log(JSON.stringify({ sessions: new Set(entries.map((entry) => entryFile.get(entry)?.file)).size, unreadable: READ_FAILURES.n, 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
1692
  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
1693
  return await exitFlushed(0);
1356
1694
  }
@@ -1361,17 +1699,34 @@ if (flag("history")) {
1361
1699
  console.log(`\ndry run — nothing sent. Add --history${flag("rebuild") ? " --rebuild" : ""} without --dry-run to ${flag("rebuild") ? "rebuild" : "import"} them.`);
1362
1700
  return await exitFlushed(0);
1363
1701
  }
1702
+ // ONLY THE DAYS THAT CHANGED (0.10.32): a re-measure of this computer's own sessions asks the door first; an export, a copied
1703
+ // folder and a plain history never do. Not known is every day.
1704
+ const staged = flag("rebuild") && !fromExports && !fromFolder;
1705
+ const sending = staged ? await changedOnly(entries) : entries;
1706
+ if (staged && COMPARED.asked && COMPARED.days > COMPARED.changed) console.log(sending.length === 0 ? `nothing changed: WorkTrust holds all ${COMPARED.days} days as this computer measures them` : `${COMPARED.days - COMPARED.changed} of ${COMPARED.days} days unchanged on WorkTrust; sending the ${COMPARED.changed} that changed`);
1364
1707
  // A batch the door refused is a failure the caller must see, not a quiet zero.
1365
- const accepted = await sendHistory(door, entries, true, flag("rebuild"), Boolean(fromFolder), fromExports ? { byDay: true, withdrawUnknown: flag("withdraw-unknown") } : {});
1708
+ const accepted = sending.length === 0 ? 0 : await sendHistory(door, sending, true, flag("rebuild"), Boolean(fromFolder), fromExports ? { byDay: true, withdrawUnknown: flag("withdraw-unknown") } : {});
1366
1709
  // An export that arrived whole is remembered by its digest (never by a conversation), so the bare command offers it no more.
1367
1710
  if (fromExports && accepted === entries.length) for (const report of fromExports.reports) rememberExport(report.digest, { vendor: report.vendor, sent: true, at: new Date().toISOString(), conversations: report.conversations });
1368
1711
  // ONE LINE FOR THE COMMAND TO ASK WITH (2026-10-10): what the door replaced, how many AI-app lines lie on the export's days, how many it withdrew.
1369
- if (fromExports) console.log(JSON.stringify({ export_sent: accepted, of: entries.length, ...RECEIPTS })); else console.log(JSON.stringify({ history_sent: accepted, of: entries.length, ...RECEIPTS, delivery: HISTORY_DELIVERY })); // the same line for a history send: what the door did with it, and WorkTrust's measuredSeconds for what it stored
1370
- return await exitFlushed(accepted === entries.length ? 0 : 1);
1712
+ if (!fromExports && !fromFolder) await settleReadFailures(door ?? codexDoor); // 0.10.32: a transcript that could not be read is counted and told
1713
+ if (fromExports) console.log(JSON.stringify({ export_sent: accepted, of: entries.length, ...RECEIPTS })); else console.log(JSON.stringify({ history_sent: accepted, of: sending.length, unreadable: READ_FAILURES.n, ...RECEIPTS, delivery: HISTORY_DELIVERY, ...(staged ? { days: { compared: COMPARED.asked ? COMPARED.days : null, changed: COMPARED.asked ? COMPARED.changed : null }, queued: QUEUED.at } : {}) })); // the same line for a history send: what the door did with it, and WorkTrust's measuredSeconds for what it stored
1714
+ return await exitFlushed(accepted === sending.length ? 0 : 1);
1371
1715
  }
1372
1716
 
1373
1717
  const input = hookInput();
1374
1718
  const state = readState();
1719
+ if (input?.hook_event_name === "Stop" && !process.env.WORKTRUST_STOP_CHILD) {
1720
+ if (Date.now() - (Date.parse(state.__stopSweep ?? "") || 0) < STOP_SWEEP_MS) return await exitFlushed(0);
1721
+ if (!DRY) { state.__stopSweep = new Date().toISOString(); writeState(state); }
1722
+ // The sweep itself in a detached copy, so the answer that fired Stop is not held while a large transcript is read.
1723
+ if (!DRY && !process.env.WORKTRUST_STOP_INLINE && existsSync(join(RELEASE_DIR, "log-session.mjs"))) {
1724
+ try {
1725
+ spawn(moduleExecutable(RELEASE_DIR), moduleArgs(RELEASE_DIR, "log-session.mjs", []), { detached: true, stdio: ["ignore", "ignore", "ignore"], env: { ...process.env, WORKTRUST_STOP_CHILD: "1", WORKTRUST_HOOK_INPUT: JSON.stringify(input) } }).unref();
1726
+ return await exitFlushed(0);
1727
+ } catch { /* no detached copy: the sweep runs here */ }
1728
+ }
1729
+ }
1375
1730
  const work = [];
1376
1731
  if (input?.transcript_path && existsSync(input.transcript_path) && !excluded(input.transcript_path)) {
1377
1732
  work.push({ id: String(input.session_id ?? input.transcript_path), file: input.transcript_path });
@@ -1395,7 +1750,14 @@ if (floorOf(state, "__from") === null) {
1395
1750
  if (!DRY) writeState(state);
1396
1751
  }
1397
1752
  const floor = floorOf(state, "__from");
1398
- let sent = 0, filed = 0;
1753
+ // THE TIMER THAT STARTED THIS RUN (0.10.32): read once, for the session the hook was called for, and kept beside its watermark, so a
1754
+ // day sent by a later run (the day was not finished) still carries it. A run no timer started reads none.
1755
+ let scheduleNoted = false;
1756
+ if (work.length > 0 && input?.transcript_path && work[0].file === input.transcript_path) {
1757
+ const found = timerSchedule(), secret = found ? repoCodeSecret() : null, timer = found && secret ? { cadence: found.cadence, ref: createHmac("sha256", secret).update(`worktrust-schedule-ref|${found.ref}`).digest("base64url") } : null; // the label's hash keyed with this computer's secret, as repo_code (L4)
1758
+ if (timer &&state[work[0].id]?.schedule?.ref !== timer.ref) { state[work[0].id] = { ...(state[work[0].id] ?? {}), schedule: timer }; scheduleNoted = true; }
1759
+ }
1760
+ let sent = 0, filed = 0, positioned = false;
1399
1761
  const late = []; // measured days the live door will no longer take: they are not dropped, they are filed
1400
1762
  const heldBack = new Map(); // per transcript with a late day: its state before that day, put back unless history took every late day
1401
1763
  for (const entry of work) {
@@ -1404,7 +1766,8 @@ for (const entry of work) {
1404
1766
  const since = mark !== null && floor !== null ? Math.max(mark, floor) : mark ?? floor;
1405
1767
  // Nothing written since we last read this one: it is not opened. This keeps a sweep over every transcript to one `stat` each.
1406
1768
  if (since !== null && entry.writtenAt && entry.writtenAt <= since) continue;
1407
- const stretches = stretchesOf(entry.file, since);
1769
+ // THE READ POSITION (0.10.32, at stretchesOf): a Claude Code transcript is read from where the last run left it, when nothing says otherwise.
1770
+ const stretches = stretchesOf(entry.file, since, state[entry.id]?.pos ?? null);
1408
1771
  // THE WATERMARK ADVANCES OVER WHAT WAS ACCEPTED, AND STOPS AT THE FIRST REFUSAL. A door that is
1409
1772
  // down must never cost the person a day, so the loop breaks rather than skipping ahead.
1410
1773
  let through = null, before, reported = state[entry.id]?.reported;
@@ -1413,7 +1776,7 @@ for (const entry of work) {
1413
1776
  // every day but today, on whichever run comes first — it no longer waits for its own end.
1414
1777
  if (Date.now() - stretch.to < IDLE_BEFORE_SWEEP) break;
1415
1778
  const total = grownBy(stretch, reported);
1416
- const payload = payloadFor(stretch);
1779
+ const payload = payloadFor({ ...stretch, schedule: state[entry.id]?.schedule ?? null });
1417
1780
  const source = LIVE_SOURCE.exec(String(entry.id))?.[1];
1418
1781
  if (source) entrySource.set(payload, source);
1419
1782
  if (DRY) { console.log(JSON.stringify({ ...payload, client: source ?? "claude", route: Date.now() - stretch.to > WINDOW_HOURS * 3600_000 ? "history" : "log_work" }, null, 1)); through = stretch.to; reported = total; continue; }
@@ -1426,18 +1789,28 @@ for (const entry of work) {
1426
1789
  }
1427
1790
  }
1428
1791
  if (before && !heldBack.has(entry.id)) heldBack.set(entry.id, before.mark);
1429
- if (through !== null) state[entry.id] = { through: new Date(through).toISOString(), ...(reported ? { reported } : {}) };
1792
+ // The position is cut for the watermark kept beside it: the new one, or the one this run read under.
1793
+ const pos = stretches.positionAt?.(through ?? since) ?? null;
1794
+ if (through !== null) state[entry.id] = { through: new Date(through).toISOString(), ...(reported ? { reported } : {}), ...(state[entry.id]?.schedule ? { schedule: state[entry.id].schedule } : {}), ...(pos ? { pos } : {}) };
1795
+ else if (pos && !DRY && canonical(pos) !== canonical(state[entry.id]?.pos ?? null)) { state[entry.id] = { ...(state[entry.id] ?? {}), pos }; positioned = true; }
1430
1796
  }
1431
1797
  // The history door, in batches of two hundred as `--history` sends them. A resend FILLS a line that was missing something, never a twin.
1432
1798
  if (!DRY && late.length > 0) {
1433
1799
  try { filed = await sendHistory(door, late); } catch (error) { if (process.env.WORKTRUST_HOOK_DEBUG) console.error(`worktrust: ${error.message}`); }
1434
- // A LATE DAY THE HISTORY DOOR REFUSED IS NOT PASSED: its transcript's mark goes back to before it, so the next run sends it again.
1435
- if (filed < late.length) for (const [id, mark] of heldBack) { if (mark) state[id] = mark; else delete state[id]; }
1800
+ // A LATE DAY THAT IS NOWHERE IS NOT PASSED: when the outbox could not keep it, its transcript's mark goes back to before it, so
1801
+ // the next run reads it again. A late day the outbox KEEPS is passed (0.10.32): the outbox sends it again by itself until
1802
+ // WorkTrust takes it, and putting the mark back made every newer day of a long session late too, a day at a time, so a
1803
+ // session whose first late day waited (the owner's, from 2026-10-18) never moved again.
1804
+ if (filed < late.length && HISTORY_PERSISTED.n < late.length) for (const [id, mark] of heldBack) { if (mark) state[id] = mark; else delete state[id]; }
1436
1805
  }
1437
- if (!DRY && (sent > 0 || filed > 0)) writeState(state);
1438
- // What an earlier history run left on this computer because the server never received it: a few batches a run, by itself; not in a
1439
- // run that just sent late days itself (a batch it just tried waits for the next run, as it always did).
1806
+ if (!DRY && (sent > 0 || filed > 0 || scheduleNoted || positioned || (late.length > 0 && HISTORY_PERSISTED.n >= late.length))) writeState(state);
1807
+ // What an earlier run left in the outbox because the server never received it: a few batches a run, by itself; not in a run
1808
+ // that just sent late days itself (a batch it just tried waits for the next run). Since 0.10.32 the mark passes a late day the
1809
+ // outbox keeps, so the next run has no late day of its own and asks; before, a long session always had one and never asked.
1440
1810
  if (!DRY && late.length === 0) await resendPending(4);
1811
+ // A transcript that could not be read is counted here and told as a count (0.10.32), never skipped in silence.
1812
+ if (!DRY) await settleReadFailures(door, state);
1813
+ if (process.env.WORKTRUST_HOOK_DEBUG) console.error(`worktrust: read ${READ_BYTES.n} transcript bytes`);
1441
1814
 
1442
1815
  // The counter, at most once a day, detached: reading every transcript takes longer than a hook
1443
1816
  // may hold a session's exit, and its result waits for a click either way. `--stage` and never
@@ -1 +1 @@
1
- {"keyId":"608168ccdef72562fc91f9c0f9f2c2d6876bece7f7362cb545b818f7947da6b5","payload":{"files":{"AGENTS.md":"c6f5280c5bf81a14db4bdc282218fb005706e92dd9a9170c0e727716ee91685a","CLAUDE.md":"5933504f93e5a40369a4790e96dd5dad791d849d3178b1833eb64088e456aaeb","LICENSE":"3096ed1693974a90e1f4f59bf01c9559d94a7941d933e36fb81d3995a97f25c1","README.md":"e0b621c26ba8bdfda128eb132d0c42db404bd2db285ad503d81a4bdcda2d1c9a","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":"02575409b07768da214adc4e11f14ce9118cda8dbf9163d6e330e472f9ee00a5","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":"ba40fbf9fb3ae3ec7bad023c1c327660294db61fc479961bdd5ebdc70e92103e","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":"7fdcd2996f0d401a7232467904d2900ee2cc084764ae25d4ffd5f9f4b57da1b3"},"format":"worktrust-package/1","kind":"npm","version":"0.10.31"},"signature":"5zVtVZzppT1vbBpiUKj8OXIdN7C5HFGN3TXtBEY56jlctT7zYARKRAfRTbSDPnozaYiPeE5juo-5wseGwme4DA"}
1
+ {"keyId":"608168ccdef72562fc91f9c0f9f2c2d6876bece7f7362cb545b818f7947da6b5","payload":{"files":{"AGENTS.md":"c6f5280c5bf81a14db4bdc282218fb005706e92dd9a9170c0e727716ee91685a","CLAUDE.md":"5933504f93e5a40369a4790e96dd5dad791d849d3178b1833eb64088e456aaeb","LICENSE":"3096ed1693974a90e1f4f59bf01c9559d94a7941d933e36fb81d3995a97f25c1","README.md":"34923747bec318637e6c93c543eb49b2a37cf2f67789b971ae3f7527975c860d","SECURITY.md":"b672649c7c7bf18538dd4560d7b533498721e0be765a000796d7d18390b5cbb6","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":"9466dc34e51c5c7443c68c9074cd21fb9be9d86e2633005d5033feb5d865c2cb","history-outbox.mjs":"b84e22542bb2d8195a469ee5f4116356ae9eac4a53ff2d40f0268b5b1de99dc5","log-session.mjs":"35d01fb00a472c022560a880c0863b57f24cb8311040bba21c3f0cf903b9074c","orchestration-contract.mjs":"ec08f303a166365b99e70b675de4cfe76c6156c2567e14b5569f6d992f0231b7","orchestration-evidence.mjs":"d0d06cecf0eb08e5c6e653c62a4f45b1eddf2119c2acb8341056b34f488d214a","orchestration-report.mjs":"d4e0a9ad8e4a01b462d22c6b1866aac291565c533ff476085d3367cb6d59bc1b","package-integrity.mjs":"a8210c9494a56bfb9a5ea3d10064c7a269f0b6330c0af7c0700e706c3c0224e3","package.json":"50adbece5072911c0a1421f92669fe7196013427a6fd08eb81456c7b56b5e5dc","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":"5f5667b92adf11b1a5a6330a0f26dd6db73d56fe60823d9a5246dab71d27d380","transcript-readers.mjs":"ed6fef364aa28f39361d8f627abcda2162498cbaa13e90cc5860a768cb355fa2","worktrust-launch.mjs":"84801bd29d472d48188c126b9ebe3989a3132b54e13cc4fe534ff7c383a294ee","worktrust.mjs":"0e481fde109620dd23f750d7b9b0741c0ea831c45961a176164ef2a74f3dd7c0"},"format":"worktrust-package/1","kind":"npm","version":"0.10.32"},"signature":"r4b807x7NWQzjC04Eu7Rto-dydbPoaNq_pd2MczLVIJC2Z_5fuaf8PQtxPLbrQbCqw1q19b_X_mWBl_giwvtBw"}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "worktrust",
3
- "version": "0.10.31",
3
+ "version": "0.10.32",
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": {
@@ -207,7 +207,7 @@ function delegationOf(messages, { isHumanTurn, INTERRUPTED, textOf }) {
207
207
  * next: the same input again (a blind retry) or a different one (a changed strategy). Inputs are compared by digest on
208
208
  * this computer and never kept. Null when nothing failed.
209
209
  */
210
- function recoveryOf(messages) {
210
+ export function recoveryOf(messages) {
211
211
  const calls = [];
212
212
  const byId = new Map();
213
213
  for (const message of messages) {
@@ -13,9 +13,12 @@
13
13
  * counter's named rules and the hook's measure(), whose payloads are fixed allowlists of numbers,
14
14
  * dates and enum values (log-session.mjs, "WHAT CANNOT LEAVE").
15
15
  */
16
- import { closeSync, mkdirSync, openSync, readFileSync, readSync, readdirSync, statSync, writeFileSync } from "node:fs";
16
+ import { closeSync, existsSync, mkdirSync, openSync, readFileSync, readSync, readdirSync, statSync, writeFileSync } from "node:fs";
17
+ import { createHash } from "node:crypto";
18
+ import { spawnSync } from "node:child_process";
17
19
  import { homedir } from "node:os";
18
20
  import { join } from "node:path";
21
+ import { StringDecoder } from "node:string_decoder";
19
22
  import { fileURLToPath } from "node:url";
20
23
 
21
24
  // ── codex rollout reader ──
@@ -75,9 +78,12 @@ const ORIGIN_OF = { human: "human", scheduled: "scheduled", task_notification: "
75
78
  const entrypointKind = (value) => (typeof value !== "string" ? null : /^sdk(-|$)/.test(value) ? "headless" : value === "cli" || /^claude-/.test(value) ? "interactive" : "unknown");
76
79
  const SESSION_WORDS = new Set(["interactive", "headless", "scheduled", "unknown"]);
77
80
  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;
81
+ export function sessionKindReader(saved = null) {
82
+ // A READ POSITION RESUMES IT (0.10.32): `state()` is what it has read so far, as JSON, and `sessionKindReader(state)` goes on
83
+ // from there, so a transcript read from an offset decides the kind its whole file decides.
84
+ let entry = typeof saved?.entry === "string" ? saved.entry : null, human = saved?.human === true, first = saved && "first" in saved ? saved.first : undefined;
80
85
  return {
86
+ state: () => ({ entry, human, ...(first === undefined ? {} : { first }) }),
81
87
  note(line) {
82
88
  if (!line || typeof line !== "object") return;
83
89
  // What the client said on the line: a reader's word (Codex), else Claude Code's entrypoint. Interactive wins over headless,
@@ -100,6 +106,95 @@ export function sessionKindReader() {
100
106
  }
101
107
  /** One session's kind from its lines, in file order (the hook and the tests read it the same way). */
102
108
  export const sessionKindOf = (lines) => { const reader = sessionKindReader(); for (const line of lines ?? []) reader.note(line); return reader.kind(); };
109
+ /**
110
+ * WHO WROTE THIS TURN (0.10.32): true when the app marked it the person's (`turnOrigin` / `origin.kind` human, or the line's own
111
+ * entrypoint interactive: a `claude --resume` by hand); false when it marked a program or a timer (an `sdk-*` entrypoint, a
112
+ * `scheduled` or program origin); null when it said neither. In a run no person started, only a true turn is a human input.
113
+ */
114
+ export const turnByPerson = (line) => {
115
+ const origin = ORIGIN_OF[typeof line?.turnOrigin === "string" ? line.turnOrigin : typeof line?.origin?.kind === "string" ? line.origin.kind : ""] ?? null;
116
+ if (origin) return origin === "human";
117
+ const kind = entrypointKind(line?.entrypoint);
118
+ return kind === "interactive" ? true : kind === "headless" ? false : null;
119
+ };
120
+
121
+ /**
122
+ * THE TIMER THAT RUNS THIS PROCESS (owner, 2026-10-28; docs/AGENTIC-OPERATIONS.md "2b"; 0.10.32): a run's schedule is read from the
123
+ * timer's own definition, never guessed from when runs happened.
124
+ * launchd the job's label (XPC_SERVICE_NAME, which launchd sets for the job and its children) names a plist in a LaunchAgents
125
+ * or LaunchDaemons folder; its StartInterval (a day, a week) or one StartCalendarInterval entry says the cadence;
126
+ * cron an ancestor process is cron; the command its child runs is exactly one line of the user's crontab; that line's
127
+ * fields say the cadence (`@daily`, `@weekly`, `@monthly`, or minute and hour fixed with one of day-of-month or
128
+ * day-of-week fixed).
129
+ * Anything else (an hourly or irregular timer, several entries, no definition found, two crontab lines alike): null. The ref is a
130
+ * hash of the timer's identity and its cadence (the label, or the cron fields), never of its command: updating what a timer runs
131
+ * keeps its schedule; a new cadence is a new schedule. Nothing of the definition leaves this computer.
132
+ */
133
+ export const SCHEDULE_CADENCES = ["daily", "weekly", "monthly"];
134
+ const scheduleRef = (source, identity, cadence) => createHash("sha256").update(`worktrust-schedule|${source}|${identity}|${cadence}`).digest("base64url");
135
+ const whole = (value) => Number.isInteger(value) && value >= 0;
136
+ /** A launchd job definition (the plist as JSON) → its cadence, or null. */
137
+ export function launchdCadence(plist) {
138
+ if (!plist || typeof plist !== "object") return null;
139
+ if (plist.StartInterval === 86400) return "daily";
140
+ if (plist.StartInterval === 604800) return "weekly";
141
+ if (plist.StartInterval !== undefined) return null;
142
+ const entries = Array.isArray(plist.StartCalendarInterval) ? plist.StartCalendarInterval : plist.StartCalendarInterval ? [plist.StartCalendarInterval] : [];
143
+ if (entries.length !== 1 || typeof entries[0] !== "object") return null;
144
+ const { Minute, Hour, Day, Weekday, Month } = entries[0];
145
+ if (Month !== undefined || !whole(Minute) || !whole(Hour)) return null;
146
+ if (whole(Day) && Weekday === undefined) return "monthly";
147
+ if (whole(Weekday) && Day === undefined) return "weekly";
148
+ if (Day === undefined && Weekday === undefined) return "daily";
149
+ return null;
150
+ }
151
+ /** A crontab line's schedule fields (the five, or one @word) → its cadence, or null. */
152
+ export function cronCadence(fields) {
153
+ const word = { "@daily": "daily", "@midnight": "daily", "@weekly": "weekly", "@monthly": "monthly" };
154
+ if (fields.length === 1) return word[fields[0]] ?? null;
155
+ if (fields.length !== 5) return null;
156
+ const [minute, hour, dom, month, dow] = fields, one = (field) => /^[0-9]{1,2}$/.test(field);
157
+ if (!one(minute) || !one(hour) || month !== "*") return null;
158
+ if (dom === "*" && dow === "*") return "daily";
159
+ if (dom === "*" && one(dow)) return "weekly";
160
+ if (one(dom) && dow === "*") return "monthly";
161
+ return null;
162
+ }
163
+ /** The crontab's lines whose command is `command` → their schedule fields (an @word line has one). */
164
+ export const crontabFields = (crontab, command) => String(crontab ?? "").split("\n").map((line) => line.trim()).filter((line) => line && !line.startsWith("#") && !/^[A-Za-z_][A-Za-z0-9_]*=/.test(line))
165
+ .map((line) => (line.startsWith("@") ? [line.split(/\s+/, 1), line.replace(/^@\S+\s+/, "")] : [line.split(/\s+/).slice(0, 5), line.split(/\s+/).slice(5).join(" ")]))
166
+ .filter(([, cmd]) => cmd === command).map(([fields]) => fields);
167
+ export function timerSchedule({ env = process.env, home = homedir(), run = spawnSync, pid = process.pid } = {}) {
168
+ try {
169
+ const label = typeof env.XPC_SERVICE_NAME === "string" && /^[A-Za-z0-9._-]{1,200}$/.test(env.XPC_SERVICE_NAME) && !/^(0|application\.)/.test(env.XPC_SERVICE_NAME) ? env.XPC_SERVICE_NAME : null;
170
+ if (label) {
171
+ const file = [join(home, "Library/LaunchAgents"), "/Library/LaunchAgents", "/Library/LaunchDaemons"].map((dir) => join(dir, `${label}.plist`)).find((path) => existsSync(path));
172
+ if (!file) return null;
173
+ const read = run("plutil", ["-convert", "json", "-o", "-", file], { encoding: "utf8", timeout: 2000 });
174
+ const cadence = read.status === 0 ? launchdCadence(JSON.parse(read.stdout)) : null;
175
+ return cadence ? { cadence, ref: scheduleRef("launchd", label, cadence) } : null;
176
+ }
177
+ // cron: walk up the process tree (one `ps`), at most twelve steps, for cron and the command it started
178
+ const table = run("ps", ["-A", "-o", "pid=,ppid=,comm="], { encoding: "utf8", timeout: 2000 });
179
+ if (table.status !== 0) return null;
180
+ const parent = new Map(), name = new Map();
181
+ for (const row of table.stdout.split("\n")) { const m = /^\s*(\d+)\s+(\d+)\s+(.+?)\s*$/.exec(row); if (m) { parent.set(Number(m[1]), Number(m[2])); name.set(Number(m[1]), m[3]); } }
182
+ let child = pid, at = parent.get(pid);
183
+ for (let step = 0; step < 12 && at && at > 1; step += 1) {
184
+ if (/(^|\/)(cron|crond)$/.test(name.get(at) ?? "")) {
185
+ const args = run("ps", ["-o", "args=", "-p", String(child)], { encoding: "utf8", timeout: 2000 });
186
+ const command = args.status === 0 ? /^\S*sh -c (.+)$/.exec(args.stdout.trim())?.[1] ?? null : null;
187
+ if (!command) return null;
188
+ const tab = run("crontab", ["-l"], { encoding: "utf8", timeout: 2000 });
189
+ const lines = tab.status === 0 ? crontabFields(tab.stdout, command) : [];
190
+ const cadence = lines.length === 1 ? cronCadence(lines[0]) : null;
191
+ return cadence ? { cadence, ref: scheduleRef("cron", lines[0].join(" "), cadence) } : null;
192
+ }
193
+ child = at; at = parent.get(at);
194
+ }
195
+ return null;
196
+ } catch { return null; }
197
+ }
103
198
  export function* codexLines(records) {
104
199
  let cwd = null, model = null, mode = null, sessionKind = null;
105
200
  const seenResponses = new Set();
@@ -156,12 +251,37 @@ export function* codexLines(records) {
156
251
  * does not say who started them, and a guess is noise. Null when the day shows none of it.
157
252
  */
158
253
  const EFFORT_LEVELS = new Set(["low", "medium", "high", "xhigh", "max"]);
254
+ /**
255
+ * A FILE'S LINES, 8 MB AT A TIME (0.10.32): a whole-file read throws past Node's longest string (about 512 MB), which is
256
+ * how the owner's Claude Code session went unmeasured from 2026-10-18; a rollout is read the same way as a transcript.
257
+ * Null when the file cannot be opened; a read that fails halfway ends the lines there.
258
+ */
259
+ export function streamedLines(file) {
260
+ try { closeSync(openSync(file, "r")); } catch { return null; }
261
+ return { *[Symbol.iterator]() {
262
+ let fd; try { fd = openSync(file, "r"); } catch { return; }
263
+ try {
264
+ const decoder = new StringDecoder("utf8"), buffer = Buffer.allocUnsafe(8 << 20);
265
+ let rest = "";
266
+ for (;;) {
267
+ let n; try { n = readSync(fd, buffer, 0, buffer.length, null); } catch { return; }
268
+ if (n <= 0) break;
269
+ const parts = (rest + decoder.write(buffer.subarray(0, n))).split("\n");
270
+ rest = parts.pop();
271
+ yield* parts;
272
+ }
273
+ rest += decoder.end();
274
+ if (rest) yield rest;
275
+ } finally { closeSync(fd); }
276
+ } };
277
+ }
159
278
  export function codexLive(file, day) {
160
279
  if (!CODEX_ROLLOUT.test(String(file)) || !/^\d{4}-\d{2}-\d{2}$/.test(String(day))) return null;
161
- let text; try { text = readFileSync(file, "utf8"); } catch { return null; }
280
+ const lines = streamedLines(file);
281
+ if (!lines) return null;
162
282
  const out = {}, models = new Set();
163
283
  const peak = (key, value) => { if (Number.isFinite(value)) { const v = Math.max(0, Math.min(100, Math.round(value))); if (v > 0 && (out[key] ?? 0) < v) out[key] = v; } };
164
- for (const raw of text.split("\n")) {
284
+ for (const raw of lines) {
165
285
  if (!raw.includes(day)) continue;
166
286
  let record; try { record = JSON.parse(raw); } catch { continue; }
167
287
  if (String(record?.timestamp ?? "").slice(0, 10) !== day) continue;
package/worktrust.mjs CHANGED
@@ -76,18 +76,20 @@ const command = args.includes("--help") ? "help" : args.includes("--version") ?
76
76
  const flag = (name) => { const at = args.indexOf(`--${name}`); return at >= 0 ? args[at + 1] : undefined; };
77
77
  const has = (name) => args.includes(`--${name}`);
78
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). */
79
- const CLI_VERSION = "0.10.31";
79
+ const CLI_VERSION = "0.10.32";
80
80
  /**
81
81
  * HOW THIS CLI MEASURES, AS A NUMBER OF ITS OWN (0.10.31; owner, 2026-10-28: 0.10.30 offered a re-measure it had no reason
82
82
  * to offer). Raised ONLY when what is measured changes: the timeline, the seconds, the tokens, the steering, the session
83
83
  * kinds, the readers. A release that changes consent, coupling or words keeps it. `update` offers the re-measure only when
84
84
  * the earlier install measured by other rules, and names what changed from MEASURE_CHANGES; installed-release.json and
85
- * history.json record it. 1 is the rules of 0.10.29, which 0.10.30 and 0.10.31 kept.
85
+ * history.json record it. 1 is the rules of 0.10.29, which 0.10.30 and 0.10.31 kept; 2 (0.10.32) adds the subagent runs, each
86
+ * agent call's outcome and who wrote each turn of a run no person started.
86
87
  */
87
- const MEASURE_RULES = 1;
88
+ const MEASURE_RULES = 2;
88
89
  /** What each measure-rules version changed, in the words the re-measure offer says (one entry per raise, never rewritten). */
89
90
  const MEASURE_CHANGES = {
90
91
  1: ["each answer's tokens counted once", "nothing lost at midnight", "when each stretch began", "how you steered the agent", "what the seconds were", "more AI apps", "how each session was started"],
92
+ 2: ["which subagents were active at once, and how their failed steps were recovered", "whether each agent call completed", "who wrote each turn of a run no person started"],
91
93
  };
92
94
  const ORIGIN = (flag("origin") ?? process.env.WORKTRUST_ORIGIN ?? "https://app.worktrust.io").replace(/\/$/, "");
93
95
  const MCP = flag("url") ?? process.env.WORKTRUST_MCP_URL ?? `${ORIGIN}/api/mcp`;
@@ -152,7 +154,7 @@ function historyQueueScope(token) {
152
154
  /** Run a script; its output is shown, or collected for the plan. The key travels in the environment only. */
153
155
  function run(path, scriptArgs, token, collect = false, extraEnv = {}) {
154
156
  return new Promise((resolve) => {
155
- const child = spawn(moduleExecutable(HERE), [...moduleArgs(HERE, basename(path), scriptArgs)], { stdio: collect ? ["ignore", "pipe", "pipe"] : "inherit", env: { ...process.env, WORKTRUST_MCP_URL: MCP, WORKTRUST_MCP_TOKEN: token, WORKTRUST_NODE: NODE, WORKTRUST_NODE_ARGS: JSON.stringify(NODE_ARGS), WORKTRUST_CLI_VERSION: CLI_VERSION, WORKTRUST_HISTORY_SCOPE: historyQueueScope(token), ...extraEnv } });
157
+ const child = spawn(moduleExecutable(HERE), [...moduleArgs(HERE, basename(path), scriptArgs)], { stdio: collect ? ["ignore", "pipe", "pipe"] : "inherit", env: { ...process.env, WORKTRUST_MCP_URL: MCP, WORKTRUST_MCP_TOKEN: token, WORKTRUST_NODE: NODE, WORKTRUST_NODE_ARGS: JSON.stringify(NODE_ARGS), WORKTRUST_CLI_VERSION: CLI_VERSION, WORKTRUST_MEASURE_RULES: String(MEASURE_RULES), WORKTRUST_HISTORY_SCOPE: historyQueueScope(token), ...extraEnv } });
156
158
  let out = "";
157
159
  child.stdout?.on("data", (chunk) => { out += chunk; });
158
160
  child.stderr?.on("data", (chunk) => { out += chunk; });
@@ -580,7 +582,7 @@ async function hook() {
580
582
  if (has("hermes") || has("goose")) return sessionEnd();
581
583
  const key = await freshKey();
582
584
  if (!key) return;
583
- const child = spawn(moduleExecutable(HERE), [...moduleArgs(HERE, "log-session.mjs", args.filter((arg) => arg !== "hook"))], { stdio: "inherit", env: { ...process.env, WORKTRUST_MCP_URL: key.url, WORKTRUST_MCP_TOKEN: key.token, WORKTRUST_CLI_VERSION: CLI_VERSION, WORKTRUST_HISTORY_SCOPE: historyQueueScope(key.token), ...(key.device ? { WORKTRUST_DEVICE_KEY: key.device } : {}) } }); // 0.10.20: the hook names the version that started it, beside each line
585
+ const child = spawn(moduleExecutable(HERE), [...moduleArgs(HERE, "log-session.mjs", args.filter((arg) => arg !== "hook"))], { stdio: "inherit", env: { ...process.env, WORKTRUST_MCP_URL: key.url, WORKTRUST_MCP_TOKEN: key.token, WORKTRUST_CLI_VERSION: CLI_VERSION, WORKTRUST_MEASURE_RULES: String(MEASURE_RULES), WORKTRUST_HISTORY_SCOPE: historyQueueScope(key.token), ...(key.device ? { WORKTRUST_DEVICE_KEY: key.device } : {}) } }); // 0.10.20: the hook names the version that started it, beside each line
584
586
  process.exitCode = await new Promise((resolve, reject) => { child.on("error", reject); child.on("close", (code) => resolve(code ?? 1)); });
585
587
  }
586
588
 
@@ -647,7 +649,7 @@ async function update() {
647
649
  if (found.length === 0) say(" (no AI app found here)");
648
650
  const hookFresh = !agreed.has("session-hook");
649
651
  say(` The session hook and ${STABLE} are brought to ${CLI_VERSION}.`);
650
- say(hookFresh ? ` + Session hook: ${join(homedir(), ".claude", "settings.json")} → SessionStart, SessionEnd and PreCompact run it · new` : ` ✓ Session hook: refreshed (${agreed.said("session-hook")})`);
652
+ say(hookFresh ? ` + Session hook: ${join(homedir(), ".claude", "settings.json")} → SessionStart, SessionEnd, PreCompact and (at most once an hour) Stop run it · new` : ` ✓ Session hook: refreshed (${agreed.said("session-hook")}; since 0.10.32 it also runs after an answer, at most once an hour, so a long session's finished days arrive the same day)`);
651
653
  say(" The key stays as it is: no new pairing, the same computer in WorkTrust.");
652
654
  say();
653
655
  if (has("dry-run")) { say(" Dry run: nothing was written and nothing was sent."); return; }
@@ -709,7 +711,7 @@ async function connect() {
709
711
  if (!direct) say(` 3. The key is kept in ${KEY_PLACE}, works only on this computer (every call is signed) and is renewed every week.`);
710
712
  say(` ${direct ? 3 : 4}. The session hook is installed:`);
711
713
  say(" + The hook and counter from the checked release, retained outside the package-manager cache");
712
- say(` + ${join(homedir(), ".claude", "settings.json")} → SessionStart, SessionEnd and PreCompact run it`);
714
+ say(` + ${join(homedir(), ".claude", "settings.json")} → SessionStart, SessionEnd, PreCompact and (at most once an hour) Stop run it`);
713
715
  say();
714
716
  say(" Sent to WorkTrust afterwards: durations, token counts, model names, a layer keyword, counts,");
715
717
  say(" and, to match the work to GitHub, the repository's owner/name and the commit hashes.");
@@ -805,13 +807,24 @@ async function offerHistory(paths, token, devicePem, url = MCP, rebuild = false,
805
807
  : n(did.replaced) > 0 ? `${n(did.replaced)} of this computer's earlier lines were replaced (withdrawn and kept, never deleted)${landed > 0 ? `, ${landed} new` : ""}${n(did.filled) > 0 ? `, ${n(did.filled)} lines gained what was missing` : ""}.`
806
808
  : landed === 0 ? `Nothing changed: the same measurement${n(did.filled) > 0 ? `; ${n(did.filled)} lines gained what was missing (the stack, the tools seen, a layer)` : ""}; ${n(did.alreadyHeld)} lines already held.`
807
809
  : `${landed} new lines${n(did.restored) > 0 ? ` (${n(did.restored)} timed by WorkTrust in place of lines it had withdrawn)` : ""}${n(did.filled) > 0 ? `, ${n(did.filled)} lines gained what was missing` : ""}; ${n(did.alreadyHeld)} already held.`;
810
+ // ONLY THE DAYS THAT CHANGED (0.10.32): the hook asked WorkTrust which of this computer's days it holds as this CLI measures
811
+ // them and sent the others; every day it compared unchanged is nothing sent, said once. Not asked (an older WorkTrust) says nothing.
812
+ const compared = Number.isInteger(did?.days?.compared) ? did.days.compared : null, changed = Number.isInteger(did?.days?.changed) ? did.days.changed : null;
813
+ if (rebuild && sent.code === 0 && compared !== null && compared > 0 && changed === 0 && n(did.of) === 0) { say(` Nothing changed: WorkTrust holds all ${compared} days as this computer measures them. Nothing was sent.`); return; }
814
+ if (rebuild && compared !== null && changed !== null && compared > changed) say(` ${compared - changed} of ${compared} days unchanged on WorkTrust; sending the ${changed} that changed.`);
815
+ if (n(did?.unreadable) > 0) say(` ${n(did.unreadable)} transcript${n(did.unreadable) === 1 ? "" : "s"} could not be read; ${n(did.unreadable) === 1 ? "its" : "their"} days were not measured. WorkTrust was told the count, nothing else.`);
808
816
  if (n(did?.untimed) > 0) say(` ${n(did.untimed)} lines were refused: they carried no timeline, so WorkTrust could not time them itself. This CLI sends every session's timeline; a line without one came from an older copy or an archive.`);
809
817
  if (Number(did?.delivery?.review) > 0) say(` ${did.delivery.review} lines are waiting for review. Earlier measurements remain unchanged. Reconnecting or repeating the import does not approve them.`);
810
818
  // KEPT ON THE SERVER (0.10.27; owner, 2026-10-21): what did not arrive stays here and goes again by itself; nothing to resume by hand.
811
819
  if (Number(did?.delivery?.waiting) > 0) say(" Some batches did not reach WorkTrust yet. They stay on this computer and are sent again by themselves the next time npx worktrust or your AI app's hook runs.");
812
820
  if (Number(did?.delivery?.refused) > 0) say(` WorkTrust closed an earlier run of ${did.delivery.refused} lines (it missed a batch for seven days): run npx worktrust@latest history again to send them as a new run.`);
813
821
  // A STAGED RUN (0.10.27): WorkTrust holds every batch and rebuilds the days itself once the run is whole; the receipts say what it kept.
814
- if (rebuild && n(did?.staged) > 0 && !Number(did?.delivery?.review) && !Number(did?.delivery?.waiting)) say(` ✓ Re-measured. WorkTrust holds all ${n(did.staged)} batches (${n(did.kept)} lines) and rebuilds these days itself, every AI app together, a day counted once. Sources › Logs shows it while it works.`);
822
+ if (rebuild && n(did?.staged) > 0 && !Number(did?.delivery?.review) && !Number(did?.delivery?.waiting)) {
823
+ say(` ✓ Re-measured. WorkTrust holds all ${n(did.staged)} batches (${n(did.kept)} lines) and rebuilds these days itself, every AI app together, a day counted once. Sources › Logs shows it while it works.`);
824
+ // WHERE IT WAITS (0.10.32): the receipt of the run's last batch names its place in WorkTrust's queue and a time; absent, nothing is guessed.
825
+ const queued = did?.queued;
826
+ if (queued && Number.isInteger(queued.position) && queued.position >= 1 && Number.isFinite(Number(queued.eta_minutes))) say(` queued, position ${queued.position}, about ${Math.max(1, Math.ceil(Number(queued.eta_minutes)))} min`);
827
+ }
815
828
  else if (rebuild && !Number(did?.delivery?.review) && !Number(did?.delivery?.waiting)) say(sent.code === 0 ? ` ✓ Re-measured. ${outcome}` : " Not all of it arrived. Run npx worktrust again: it finishes what did not arrive, a day already rebuilt is counted once.");
816
829
  else if (!rebuild) say(sent.code === 0 ? " ✓ Sent as history. Activity is recorded with its origin; independent verification and passport publication are separate. A day WorkTrust already holds is kept once." : " Not all of it arrived. Run npx worktrust history again: a line already received is kept once.");
817
830
  if (did && Number(did.measuredSeconds) > 0) say(` Measured by WorkTrust: ${(Number(did.measuredSeconds) / 3600).toFixed(1)} h for what this send stored${n(did.corrected) > 0 ? ` (${n(did.corrected)} lines corrected: a figure sent beside the timeline differed)` : ""}.`);
@@ -1247,6 +1260,9 @@ async function status() {
1247
1260
  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)");
1248
1261
  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)");
1249
1262
  say(sessionHookHere() ? " Session hook: installed" : " Session hook: not installed");
1263
+ // A TRANSCRIPT THE HOOK COULD NOT READ (0.10.32): the count of its last run that had any, never which file; WorkTrust has the count too.
1264
+ { let unread = null; try { unread = JSON.parse(readFileSync(join(HOME_DIR, "sessions.json"), "utf8")).__unreadable ?? null; } catch { /* no state yet */ }
1265
+ if (Number(unread?.count) > 0) say(` Transcripts: ${unread.count} could not be read on ${String(unread.at).slice(0, 10)}; their days are not measured until they can be (WorkTrust was told the count, nothing else)`); }
1250
1266
  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)"); }
1251
1267
  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)"); }
1252
1268
  if (antigravityHere()) say(agyHooks()?.worktrust ? " Antigravity: wakes the session hook" : " Antigravity: does not wake the session hook (npx worktrust update asks)");