worktrust 0.10.11 → 0.10.13

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/AGENTS.md CHANGED
@@ -7,13 +7,15 @@ the rules of this package.
7
7
 
8
8
  ## Do not run it for the person
9
9
 
10
- `worktrust connect`, `update`, `history` (and `--rebuild`), `disconnect`, `preserve`, `codex`, `antigravity` and the
10
+ The bare `worktrust` command, `connect`, `update`, `history` (and `--rebuild`), `disconnect`, `preserve`, `codex`, `antigravity` and the
11
11
  import commands change what this computer sends or couples. **Only the person runs them, in their own terminal.** In an
12
- agent's shell the CLI stops before it reads or writes anything, `--yes` included. Do not work around that: do not unset
12
+ agent's shell the CLI refuses these actions, `--yes` included. Version 0.10.12 adds the missing default-command
13
+ guard and tests both fresh and coupled synthetic homes. Do not work around the policy: do not unset
13
14
  the variables your client sets, do not run it through another shell, and do not ask the person for their key.
14
15
 
15
16
  The session hook and the MCP door are started by your client itself and are meant to run; leave their configuration as
16
- the person set it.
17
+ the person set it. This does not authorize an agent to invoke `preserve` through another entry point. Even `status`
18
+ can inspect local evidence and check the registry; do not run it as a generic repository inventory command.
17
19
 
18
20
  ## Do not report work you did not see
19
21
 
@@ -21,18 +23,30 @@ Through the WorkTrust MCP door, send `log_work` only for work you did in this se
21
23
  fields the door asks for and nothing of the content (no prompt, answer, code, path or client name). Never send work to
22
24
  make hours, never resend a day, never invent a test, a review or a result. Hours are verified only by the CLI's own
23
25
  measurement on the person's computer, and corroborated by sources the person coupled; a reported line is never a
24
- verified hour.
26
+ verified hour. Measured duration is distinct from independent source corroboration. Browser exports and copied
27
+ folders are reconstructed; an eligible archive signed by the matching coupled device can preserve measured
28
+ provenance. Parallel agent time does not multiply the person's elapsed time.
25
29
 
26
30
  ## Do not rebuild, fork or strip it
27
31
 
28
- Do not reimplement this client, copy it into another product, remove or weaken its checks, change what it measures, or
29
- publish a modified version under any name. Its value is that its measurement is the same for everyone and can be
30
- checked; a changed copy measures nothing WorkTrust accepts. If the person wants something changed, point them to
31
- https://worktrust.io/support or the issues of https://github.com/fhomey/worktrust-cli.
32
+ Do not bypass measurement, consent, provenance or security checks to manufacture evidence, and do not present a
33
+ modified build as the official WorkTrust release. The MIT licence permits modification and redistribution subject
34
+ to its terms; these instructions do not replace it. A device signature proves key possession, not that the client
35
+ is unmodified or that its measurements are true. Report problems through https://worktrust.io/support or
36
+ https://github.com/fhomey/worktrust-cli/issues (security reports use SECURITY.md).
37
+
38
+ ## Authorized repository maintenance
39
+
40
+ When the owner asks to maintain this source, edits and isolated regression tests are allowed. Use synthetic homes,
41
+ keys, transcripts and localhost mock servers, never the person's real account or session store. Do not publish or
42
+ change a live coupling as a side effect of tests. In the WorkTrust monorepo, the canonical entry lives in
43
+ `apps/worktrust/app/public/counter/worktrust.mjs`; support modules originate in `scripts/`. Run `build-counter.mjs`
44
+ and `tools/worktrust-cli/sync.mjs` after code changes, then both copy checks. The dated CLI review in `docs/` records
45
+ known defects; an instruction update does not fix them.
32
46
 
33
47
  ## What it is
34
48
 
35
49
  - Source, released versions and provenance: https://github.com/fhomey/worktrust-cli and https://www.npmjs.com/package/worktrust
36
50
  - What it reads and sends, field by field: README.md in this package
37
- - Licence: LICENSE in this package. "WorkTrust" and the WorkTrust mark are WorkTrust's; a fork may not carry them.
51
+ - Licence: LICENSE in this package. Do not represent a fork as the official WorkTrust release.
38
52
  - Security reports: SECURITY.md
package/CLAUDE.md CHANGED
@@ -1,4 +1,6 @@
1
1
  # Claude Code
2
2
 
3
- Read AGENTS.md in this package before anything else: this is WorkTrust's measurement client; an agent does not run
4
- its commands for the person, does not report work it did not see, and does not rebuild, fork or strip it.
3
+ Read AGENTS.md and SECURITY.md before working here. An agent does not run person-only commands against the person's
4
+ computer or account, including the bare command, and never reports work it did not see. Authorized source maintenance
5
+ uses isolated synthetic fixtures. Follow the canonical-source and regeneration rules in the monorepo; do not weaken
6
+ measurement checks or claim software signatures attest truthful work. The MIT licence governs reuse.
package/README.md CHANGED
@@ -7,7 +7,7 @@ record of the work you do with AI without anyone reading that work: it receives
7
7
  npx worktrust@latest
8
8
  ```
9
9
 
10
- **The only official package** is `worktrust`, published by the npm account **worktrustio** with
10
+ **The official npm package** is `worktrust`, published by the npm account **worktrustio** with
11
11
  provenance from this repository (github.com/fhomey/worktrust-cli). Check it on npmjs.com before you run
12
12
  it; a package of another name or from another publisher is not ours. Without npm, the same script runs
13
13
  from WorkTrust's own site:
@@ -16,6 +16,18 @@ from WorkTrust's own site:
16
16
  curl -fsSO https://app.worktrust.io/counter/worktrust.mjs && node worktrust.mjs
17
17
  ```
18
18
 
19
+ **Python tool runners:** this repository also builds `worktrust` for `uvx` and `pipx` from the
20
+ same measurement modules. Version 0.10.13's native wheels include a pinned official Node runtime,
21
+ so that route needs no separate Node/npm installation. See the
22
+ [Python distribution](https://github.com/fhomey/worktrust-cli/tree/main/python) for supported
23
+ platforms, release status and installation commands. npm and Python versions are checked together.
24
+
25
+ Connecting through the Python package installs the runtime and engine in an immutable directory
26
+ under `~/.worktrust/installations/`; client hooks use that persistent path, so clearing a tool-runner
27
+ cache does not break the coupling. Updates retain older installations for running clients.
28
+ Run `worktrust disconnect` before removing an installed Python tool if you also want to remove its
29
+ WorkTrust coupling. Disconnect removes the key and client wiring; it leaves runtime files in place.
30
+
19
31
  **No account? Keep your history anyway.** Claude Code and Gemini CLI delete their sessions after 30
20
32
  days by default, and a deleted session can never be measured again. `npx worktrust@latest preserve` shows what
21
33
  each AI app on this computer keeps, keeps it longer on your yes, and writes a local, metadata-only
@@ -339,7 +351,7 @@ which would delete every password on the computer, and many people rightly keep
339
351
  | **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. |
340
352
  | **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/`. |
341
353
  | **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). |
342
- | **Sends, afterwards** | Per measured stretch of work, and nothing else: its durations (`seconds`, `duration_basis`, `model_seconds`, `tool_seconds`, `human_seconds`, `idle_seconds`), 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`), the technologies the touched files name as keys from WorkTrust's closed list (`stack`, `tools_seen`: a `.tsx` file names TypeScript and React, a `Dockerfile` names Docker; read off the paths with the same rules the record uses, since 0.10.11; never a path), counts of how you work (`exchanges`, `turn_basis`, `agent_runs`, `agent_seconds`, `agent_peak`, `interrupts`, `steers`), 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; never a word, a command or a path; since 0.8.3), a hash of the session and the day (`stretch_ref`), `steered_from` when it ran over SSH, and, so the work can be matched to GitHub, the repository as its remote's owner/name (`repo`, only for a repository on GitHub, GitLab or Bitbucket, the hosts WorkTrust can couple; never one on your own or a client's server) and the hashes of the commits made in the stretch (`commits`, never their messages). |
354
+ | **Sends, afterwards** | Per measured stretch of work, and nothing else: its durations (`seconds`, `duration_basis`, `model_seconds`, `tool_seconds`, `human_seconds`, `idle_seconds`), 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`), counts of how you work (`exchanges`, `turn_basis`, `agent_runs`, `agent_seconds`, `agent_peak`, `interrupts`, `steers`), 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; never a word, a command or a path; since 0.8.3), a hash of the session and the day (`stretch_ref`), `steered_from` when it ran over SSH, and, so the work can be matched to GitHub, the repository as its remote's owner/name (`repo`, only for a repository on GitHub, GitLab or Bitbucket, the hosts WorkTrust can couple; never one on your own or a client's server) and the hashes of the commits made in the stretch (`commits`, never their messages). |
343
355
  | **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. |
344
356
 
345
357
  ## Why you can check it
@@ -348,11 +360,12 @@ which would delete every password on the computer, and many people rightly keep
348
360
  in an afternoon: `worktrust.mjs` (this command), `setup-mcp.mjs` (writes the MCP entries),
349
361
  `log-session.mjs` (the session hook), `count-behaviour.mjs` (the local counter) and `preserve.mjs`
350
362
  (keep your history), with the readers they import.
351
- - **Nothing is downloaded at run time.** Everything that runs is in the package. The counter is
352
- pinned: it is not replaced from the network; a new one comes with a new version of this package.
353
- - **Provenance.** Every version is built and published from a public repository by GitHub Actions
354
- with npm provenance: the npm page links each version to the exact commit it was built from,
355
- signed through Sigstore. `npm audit signatures` checks it on your machine.
363
+ - **Bundled measurement modules.** The npm package includes its counter and readers. Interactive
364
+ commands can check the registry and relay through `npx` to a newer package; that can download code.
365
+ The standalone bootstrap can also download support modules. See SECURITY.md for the distinction.
366
+ - **Provenance.** The release workflow requests npm provenance from the public source repository.
367
+ Verify the actual version's attestation and contents before relying on that origin; the manifest
368
+ setting alone does not establish it. `npm audit signatures` checks an installed dependency tree.
356
369
  - **Read it before you run it:** `npm pack worktrust` downloads the package as a file without
357
370
  running anything.
358
371
  - **The key** never appears on a command line a process list could show: it is written to its file
@@ -376,14 +389,19 @@ which would delete every password on the computer, and many people rightly keep
376
389
  ## Undo
377
390
 
378
391
  `npx worktrust@latest disconnect` removes the WorkTrust entries (Hermes's hook with them), the hook (and Codex's `notify` line and
379
- Antigravity's `worktrust` hook when WorkTrust set them) and the key file, and empties
380
- `~/.worktrust` but for one small note of which account it fed (masked), so that a later coupling by
381
- another account offers none of this computer's earlier work.
392
+ Antigravity's `worktrust` hook when WorkTrust set them), the key file and installed bridge scripts.
393
+ A small note of the previous account (masked) remains so that a later coupling by another account
394
+ does not offer its earlier work. Other retained files and your local evidence archive are not an
395
+ automatic server or archive erasure.
382
396
  Then revoke the key in WorkTrust: Sources → Devices → this computer → Revoke.
383
397
 
384
398
  ## Requirements
385
399
 
386
- Node 18 or later. macOS, Linux or Windows.
400
+ Node 18 or later for the base CLI. SQLite session readers require Node 22.5 or later with `node:sqlite`;
401
+ without it, those clients are not read. macOS, Linux or Windows; available readers depend on the local client format.
402
+
403
+ See [SECURITY.md](SECURITY.md) for the credential-file threat model, network/update behaviour and known
404
+ trust limits. A local signature proves possession of a key, not independent observation of the work.
387
405
 
388
406
  Security reports: see [SECURITY.md](SECURITY.md).
389
407
 
package/SECURITY.md CHANGED
@@ -2,15 +2,19 @@
2
2
 
3
3
  ## Reporting a problem
4
4
 
5
- Write to **hello@worktrust.io** with "security" in the subject. Please do not open a public issue
6
- for a vulnerability. You will get an answer within three working days.
5
+ Write to **hello@worktrust.io** with "security" in the subject. Please do not include credentials,
6
+ private transcripts or account data in a public issue.
7
7
 
8
8
  ## What this package can and cannot do
9
9
 
10
- - It writes only the files listed in the README, after showing them and asking. `--dry-run` writes
11
- nothing and sends nothing.
12
- - It contacts one host: the WorkTrust app (`https://app.worktrust.io` unless you pass `--origin`).
13
- It downloads nothing when run from npm.
10
+ - Setup changes client configuration and local coupling files; preservation can change retention
11
+ settings and create or append archives. See the README for the paths and individual options.
12
+ A setup dry run is not a sandbox for the whole invocation: the standalone bootstrap can download
13
+ scripts first, and the interactive entry can check for a newer release.
14
+ - Submissions go to the configured WorkTrust MCP endpoint. Interactive commands can also contact
15
+ the npm registry and relay through `npx` to a newer version. The npm package bundles its runtime
16
+ modules, but installation and automatic relay still use the network. `preserve` itself is local.
17
+ A custom `--origin`, URL or registry override changes whom you trust.
14
18
  - The key it receives is a WorkTrust coupling for this computer: it can submit work metadata to your
15
19
  record and cannot read your record back. Revoke it in WorkTrust at any time.
16
20
  - Approving requires your WorkTrust session and second factor. A pairing expires after ten minutes
@@ -24,19 +28,46 @@ for a vulnerability. You will get an answer within three working days.
24
28
 
25
29
  ## Where the key is, and how long it lives
26
30
 
27
- - In `~/.worktrust/key.json`, readable by you alone (600 in a 700 folder). No keychain is used. Not
28
- in any AI app's settings, unless you chose `--direct`.
29
- - Bound to this computer: every call carries an Ed25519 signature made with a private key that is in
30
- that file only. WorkTrust refuses a bound key without a fresh signature (two minutes, a nonce that
31
- is spent once), so a key leaked from a log or a config is useless on its own. Someone who can read
32
- your home folder can read the file: revoke the computer in WorkTrust if that happens.
33
- - Renewed every week by the computer itself: only the new key's hash is sent, signed, and the old
34
- key stops working.
31
+ - In `~/.worktrust/key.json`, alongside the software private key. The client requests mode 600 in
32
+ a 700 folder; Windows permissions need their own access-control check. Base64 is not encryption.
33
+ No keychain or hardware-backed key is used. Another process running as you may read both secrets.
34
+ - In the default mode, requests carry an Ed25519 proof. WorkTrust refuses a bound token without a
35
+ fresh signature (two minutes, a nonce spent once). A bearer token alone is insufficient; theft of
36
+ the whole credential file defeats that protection. Profile/device hashes are not hardware
37
+ attestation. Revoke the computer in WorkTrust if its credential file may have been copied.
38
+ - `--direct` instead places an unbound bearer token in AI client settings and does not provide the
39
+ same proof requirement. Do not apply the default mode's guarantees to that mode.
40
+ - The client attempts weekly renewal using a signed request containing the new token's hash.
41
+ Interrupted renewal retains recovery state. From 0.10.12, promotion requires the expected successful
42
+ response; errors, redirects and malformed replies preserve recovery state. Requests have deadlines.
43
+ A server error is not evidence that a credential works.
35
44
  - The key can submit metadata to your record and cannot read it back. It ends when you revoke it,
36
45
  and by itself 90 days after its last use.
46
+ - Local `disconnect` is distinct from server revocation and archive deletion. Revoke through
47
+ WorkTrust's device settings when the server credential must stop working.
48
+
49
+ ## What measurement signatures establish
50
+
51
+ Request proofs authenticate possession of the device key. Archive seals make later changes
52
+ detectable relative to their trusted key/root. Neither proves that the client is unmodified, that
53
+ local input files are authentic, or that work really happened. Local-only archive keys do not grant
54
+ measured provenance. Server provenance and corroboration rules remain necessary.
55
+
56
+ The client derives metadata by reading supported local session data. It does not submit raw prompts,
57
+ answers, code or file paths, but can submit repository owner/name and commit hashes. These remain
58
+ potentially identifying metadata; see the README's complete payload list.
59
+
60
+ Agent-shell detection is a workflow safeguard, not protection from malicious same-user software.
61
+ Agents must follow AGENTS.md. From 0.10.12 the bare invocation is covered by the same guard as explicit
62
+ person-only commands; help and version are safe informational paths. Export parsing limits ZIP size
63
+ to 2 GiB, directory size to 8 MiB, compressed/decoded JSON to 64 MiB, nesting to 64, structural tokens
64
+ to 1,000,000 and conversations to 50,000. Larger inputs are refused. These are resource bounds,
65
+ not a sandbox or independent validation of the export's truth.
37
66
 
38
67
  ## Verifying a version
39
68
 
40
- Each version is published from the public repository by GitHub Actions with npm provenance.
41
- On npmjs.com the version shows where and from which commit it was built; locally,
42
- `npm audit signatures` checks the signatures of what you installed.
69
+ The release configuration names https://github.com/fhomey/worktrust-cli and requests npm provenance.
70
+ Check the particular published version's attestation and compare its contents to that commit before
71
+ relying on those properties. A manifest flag or matching version string alone is not proof that an
72
+ artifact was built from reviewed source. `npm audit signatures` can inspect an installed dependency
73
+ tree; verification coverage and failures must be reported for that actual installation.
package/chat-exports.mjs CHANGED
@@ -16,7 +16,7 @@
16
16
  * findExports(dir) the exports lying in one folder (its top level only), by path and vendor
17
17
  */
18
18
  import { createHash } from "node:crypto";
19
- import { existsSync, openSync, readSync, closeSync, readFileSync, readdirSync, statSync } from "node:fs";
19
+ import { existsSync, openSync, readSync, closeSync, fstatSync, readdirSync, statSync, constants } from "node:fs";
20
20
  import { homedir } from "node:os";
21
21
  import { basename, join } from "node:path";
22
22
  import { inflateRawSync } from "node:zlib";
@@ -30,52 +30,108 @@ export const exportProductName = (vendor) => PRODUCT_NAMES[vendor] ?? vendor;
30
30
  const FILE = "conversations.json";
31
31
  const expand = (path) => String(path).replace(/^~(?=\/|$)/, homedir());
32
32
 
33
+ // Bound allocations and parsing work before touching untrusted sizes. Large attachment-bearing ZIPs
34
+ // need not fit in memory; only the directory and conversations entry are ever read. No limit override.
35
+ export const EXPORT_LIMITS = Object.freeze({ fileBytes: 2 * 1024 ** 3, directoryBytes: 8 * 1024 ** 2,
36
+ jsonBytes: 64 * 1024 ** 2, compressedBytes: 64 * 1024 ** 2, depth: 64, structure: 1_000_000, conversations: 50_000 });
37
+ const limit = (condition, label) => { if (!condition) throw Error(`export limit exceeded: ${label}`); };
38
+ const damaged = (condition) => { if (!condition) throw Error("a damaged zip archive"); };
39
+ /** One descriptor, bounded reads: reject special files/short reads and bound concurrent file growth. */
40
+ function openExport(path, maximum) {
41
+ const fd = openSync(path, constants.O_RDONLY | constants.O_NONBLOCK);
42
+ try {
43
+ const stat = fstatSync(fd);
44
+ if (!stat.isFile()) throw Error("export must be a regular file");
45
+ limit(stat.size <= maximum, "file bytes");
46
+ const readAt = (at, length, end = stat.size) => {
47
+ damaged(Number.isSafeInteger(at) && Number.isSafeInteger(length) && at >= 0 && length >= 0 && at + length <= end && end <= stat.size);
48
+ const buffer = Buffer.alloc(length);
49
+ let got = 0;
50
+ while (got < length) { const count = readSync(fd, buffer, got, length - got, at + got); damaged(count > 0); got += count; }
51
+ return buffer;
52
+ };
53
+ return { fd, size: stat.size, readAt };
54
+ } catch (error) { closeSync(fd); throw error; }
55
+ }
56
+
33
57
  /**
34
58
  * A ZIP, READ FOR ONE ENTRY. No dependency: the end-of-central-directory record is found from the back, the central
35
59
  * directory walked for the one name, and only that entry's bytes inflated (stored or deflated; anything else, and a
36
60
  * zip64 archive, is refused by name). Nothing else in the archive is touched.
37
61
  */
38
62
  function zipEntry(path, wanted) {
39
- const size = statSync(path).size;
40
- const fd = openSync(path, "r");
41
- const readAt = (at, length) => { const buffer = Buffer.alloc(length); const got = readSync(fd, buffer, 0, length, at); return buffer.subarray(0, got); };
63
+ const { fd, size, readAt } = openExport(path, EXPORT_LIMITS.fileBytes);
42
64
  try {
43
65
  const tailLength = Math.min(size, 65_557);
44
66
  const tail = readAt(size - tailLength, tailLength);
45
67
  let eocd = -1;
46
- for (let at = tail.length - 22; at >= 0; at -= 1) if (tail.readUInt32LE(at) === 0x06054b50) { eocd = at; break; }
68
+ for (let at = tail.length - 22; at >= 0; at -= 1) if (tail.readUInt32LE(at) === 0x06054b50 && at + 22 + tail.readUInt16LE(at + 20) === tail.length) { eocd = at; break; }
47
69
  if (eocd < 0) throw Error(`not a zip archive: ${path}`);
48
70
  const entries = tail.readUInt16LE(eocd + 10), directorySize = tail.readUInt32LE(eocd + 12), directoryAt = tail.readUInt32LE(eocd + 16);
49
71
  if (entries === 0xffff || directorySize === 0xffffffff || directoryAt === 0xffffffff) throw Error(`a zip64 archive is not read: ${path}`);
72
+ if (tail.readUInt16LE(eocd + 4) !== 0 || tail.readUInt16LE(eocd + 6) !== 0) throw Error("unsupported zip: multiple disks");
73
+ damaged(tail.readUInt16LE(eocd + 8) === entries);
74
+ limit(directorySize <= EXPORT_LIMITS.directoryBytes, "zip directory bytes");
75
+ damaged(directoryAt + directorySize === size - tailLength + eocd);
50
76
  const directory = readAt(directoryAt, directorySize);
51
- let at = 0;
52
- for (let index = 0; index < entries && at + 46 <= directory.length; index += 1) {
53
- if (directory.readUInt32LE(at) !== 0x02014b50) throw Error(`a damaged zip archive: ${path}`);
77
+ let at = 0, selected = null;
78
+ for (let index = 0; index < entries; index += 1) {
79
+ damaged(at + 46 <= directory.length && directory.readUInt32LE(at) === 0x02014b50);
54
80
  const method = directory.readUInt16LE(at + 10), compressed = directory.readUInt32LE(at + 20), uncompressed = directory.readUInt32LE(at + 24);
55
81
  const nameLength = directory.readUInt16LE(at + 28), extraLength = directory.readUInt16LE(at + 30), commentLength = directory.readUInt16LE(at + 32), localAt = directory.readUInt32LE(at + 42);
82
+ const flags = directory.readUInt16LE(at + 8), disk = directory.readUInt16LE(at + 34);
83
+ damaged(at + 46 + nameLength + extraLength + commentLength <= directory.length);
56
84
  const name = directory.toString("utf8", at + 46, at + 46 + nameLength);
57
85
  at += 46 + nameLength + extraLength + commentLength;
58
86
  if (basename(name) !== wanted || name.endsWith("/")) continue;
59
87
  if (compressed === 0xffffffff || uncompressed === 0xffffffff || localAt === 0xffffffff) throw Error(`a zip64 entry is not read: ${path}`);
60
- const local = readAt(localAt, 30);
61
- if (local.readUInt32LE(0) !== 0x04034b50) throw Error(`a damaged zip archive: ${path}`);
62
- const dataAt = localAt + 30 + local.readUInt16LE(26) + local.readUInt16LE(28);
63
- const bytes = readAt(dataAt, compressed);
64
- if (method === 0) return bytes;
65
- if (method === 8) return inflateRawSync(bytes);
66
- throw Error(`${wanted} in ${path} is compressed in a way this reader does not open (method ${method})`);
88
+ limit(compressed <= EXPORT_LIMITS.compressedBytes, "compressed entry bytes");
89
+ limit(uncompressed <= EXPORT_LIMITS.jsonBytes, "expanded entry bytes");
90
+ if ((flags & (1 | 64)) !== 0 || disk !== 0) throw Error("unsupported zip: encrypted or multi-disk entry");
91
+ damaged(selected === null);
92
+ selected = { name, method, flags, compressed, uncompressed, localAt };
67
93
  }
68
- return null;
94
+ damaged(at === directory.length);
95
+ if (!selected) return null;
96
+ const { name, method, flags, compressed, uncompressed, localAt } = selected;
97
+ const local = readAt(localAt, 30, directoryAt);
98
+ damaged(local.readUInt32LE(0) === 0x04034b50 && local.readUInt16LE(8) === method && local.readUInt16LE(6) === flags);
99
+ const nameLength = local.readUInt16LE(26), dataAt = localAt + 30 + nameLength + local.readUInt16LE(28);
100
+ damaged(readAt(localAt + 30, nameLength, directoryAt).toString("utf8") === name);
101
+ if (!(flags & 8)) damaged(local.readUInt32LE(18) === compressed && local.readUInt32LE(22) === uncompressed);
102
+ const bytes = readAt(dataAt, compressed, directoryAt);
103
+ if (method === 0) { damaged(compressed === uncompressed); return bytes; }
104
+ if (method !== 8) throw Error(`${wanted} in ${path} is compressed in a way this reader does not open (method ${method})`);
105
+ let inflated;
106
+ try { inflated = inflateRawSync(bytes, { maxOutputLength: Math.max(1, uncompressed) }); }
107
+ catch { throw Error("a damaged zip archive or export limit exceeded: expanded entry bytes"); }
108
+ damaged(inflated.length === uncompressed);
109
+ return inflated;
69
110
  } finally { closeSync(fd); }
70
111
  }
71
112
 
72
113
  /** The bytes of `conversations.json`, wherever the given path keeps them: a folder, the file itself, or the vendor's zip. */
73
114
  function exportBytes(given) {
74
- const path = expand(given);
115
+ let path = expand(given);
75
116
  let stat; try { stat = statSync(path); } catch { throw Error(`export not found: ${given}`); }
76
- if (stat.isDirectory()) { const file = join(path, FILE); if (!existsSync(file)) throw Error(`no ${FILE} in ${given}`); return { bytes: readFileSync(file), path: file }; }
117
+ if (stat.isDirectory()) { path = join(path, FILE); if (!existsSync(path)) throw Error(`no ${FILE} in ${given}`); }
77
118
  if (/\.zip$/i.test(path)) { const bytes = zipEntry(path, FILE); if (!bytes) throw Error(`no ${FILE} in ${given}`); return { bytes, path }; }
78
- return { bytes: readFileSync(path), path };
119
+ const { fd, size, readAt } = openExport(path, EXPORT_LIMITS.jsonBytes);
120
+ try { return { bytes: readAt(0, size), path }; } finally { closeSync(fd); }
121
+ }
122
+
123
+ /** Scan bytes before JSON.parse allocates an object graph; escaped quotes/brackets inside strings
124
+ * are content, not structure. JSON.parse remains responsible for syntax and UTF-8 string handling. */
125
+ function boundJson(bytes) {
126
+ let quoted = false, escaped = false, depth = 0, structure = 0;
127
+ for (const byte of bytes) {
128
+ if (quoted) { if (escaped) escaped = false; else if (byte === 92) escaped = true; else if (byte === 34) quoted = false; continue; }
129
+ if (byte === 34) quoted = true;
130
+ else if (byte === 91 || byte === 123) { depth += 1; structure += 1; limit(depth <= EXPORT_LIMITS.depth, "JSON depth"); }
131
+ else if (byte === 93 || byte === 125) depth -= 1;
132
+ else if (byte === 44 || byte === 58) structure += 1;
133
+ limit(structure <= EXPORT_LIMITS.structure, "JSON structure");
134
+ }
79
135
  }
80
136
 
81
137
  /** Which vendor wrote these conversations, by their shape alone; mixed or unknown shapes are refused, never guessed. */
@@ -88,8 +144,10 @@ export function vendorOf(conversations) {
88
144
  /** One export, read: its vendor by shape, its conversations, and the digest of its bytes (what `sent` is remembered by). */
89
145
  export function readExport(given, expect = null) {
90
146
  const { bytes, path } = exportBytes(given);
147
+ boundJson(bytes);
91
148
  let conversations; try { conversations = JSON.parse(bytes.toString("utf8")); } catch { throw Error(`export unreadable: ${path}`); }
92
149
  if (!Array.isArray(conversations)) throw Error(`${path} must contain an array of conversations`);
150
+ limit(conversations.length <= EXPORT_LIMITS.conversations, "conversation count");
93
151
  const vendor = vendorOf(conversations);
94
152
  if (conversations.length > 0 && !vendor) throw Error(`${path} is neither a ChatGPT nor a Claude export (or mixes the two)`);
95
153
  if (expect && vendor && vendor !== expect) throw Error(`${path} is a ${exportProductName(vendor)} export, not ${exportProductName(expect)}`);
package/log-session.mjs CHANGED
@@ -2,11 +2,8 @@
2
2
  /**
3
3
  * THE MOMENT OF THE WORK, RECORDED — a Claude Code hook that logs a finished stretch.
4
4
  *
5
- * The record already holds the commits: 3,760 of them on the first record this was built for,
6
- * with green CI on a third. What it did not hold was that a person and an agent were there while
7
- * they were made, so a session carried an artefact change and a validation and no AI interaction
8
- * — and a work unit needs all three. Nine units on seventeen months of work, and the missing half
9
- * was not judgement. It was presence.
5
+ * Session observations complement repository and CI evidence with locally recorded AI activity.
6
+ * They do not establish independent verification or human presence by themselves.
10
7
  *
11
8
  * IT NEVER LOSES A MEASURED DAY. A session is reported day by day, on whichever run comes first,
12
9
  * so a session that stays open for a fortnight is not a fortnight of silence; a machine that was
@@ -57,8 +54,8 @@
57
54
  * WHAT IS MEASURED, AND WHAT IS THEREFORE NOT SENT. A stretch's seconds are the sum of the gaps
58
55
  * between consecutive messages in the transcript, each gap counted only up to IDLE_CAP: two
59
56
  * recorded timestamps at both ends, and a pause longer than the cap is not work. That is what
60
- * `duration_basis: "measured"` means and it is the only basis this script ever sends — a stretch
61
- * whose transcript carries no timestamps is skipped rather than estimated. Tokens are what each
57
+ * `duration_basis: "measured"` means for local sessions; copied/exported history is reconstructed.
58
+ * A local stretch without timestamps is skipped rather than estimated. Tokens are what each
62
59
  * request ADDED (input plus cache creation, cache reads excluded), which the door calls
63
60
  * `newInput`.
64
61
  *
@@ -736,7 +733,7 @@ function batchesOf(group, byDay) {
736
733
  return out;
737
734
  }
738
735
  /** THE RECEIPTS' COUNTS (2026-10-10): what an export send replaced, how many AI-app lines lie on its days, how many were withdrawn; summed over the batches, read for the counts alone. */
739
- const RECEIPTS = { superseded: 0, unknownOnDays: 0, unknownWithdrawn: 0 };
736
+ const RECEIPTS = { new: 0, alreadyHeld: 0, filled: 0, replaced: 0, superseded: 0, unknownOnDays: 0, unknownWithdrawn: 0 }; // 2026-10-10: and what a re-measure did (new, held, filled, replaced), so the command can say it
740
737
  const noteReceipt = (answer) => {
741
738
  try {
742
739
  const json = JSON.parse(answer.trim().startsWith("{") ? answer : answer.split("\n").find((row) => row.startsWith("data:"))?.slice(5) ?? "null");
@@ -1083,7 +1080,7 @@ if (flag("install")) {
1083
1080
  const settings = existsSync(file) ? JSON.parse(readFileSync(file, "utf8")) : {};
1084
1081
  // `--via <worktrust.mjs>`: the key lives in ~/.worktrust/key.json, so Claude Code runs the wrapper, which reads it and starts this hook.
1085
1082
  const via = args.indexOf("--via") >= 0 ? args[args.indexOf("--via") + 1] : null;
1086
- const command = via ? `"${process.env.WORKTRUST_NODE || process.execPath}" "${via}" hook` : `node ${home}`;
1083
+ const command = `"${process.env.WORKTRUST_NODE || process.execPath}" "${via ?? home}"${via ? " hook" : ""}`;
1087
1084
  settings.hooks ??= {};
1088
1085
  for (const event of HOOK_EVENTS) settings.hooks[event] ??= [];
1089
1086
  // A WIRING THAT POINTS SOMEWHERE ELSE IS REPAIRED, NOT LEFT. An earlier install wired whatever
@@ -1243,7 +1240,7 @@ if (flag("history")) {
1243
1240
  // An export that arrived whole is remembered by its digest (never by a conversation), so the bare command offers it no more.
1244
1241
  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 });
1245
1242
  // 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.
1246
- if (fromExports) console.log(JSON.stringify({ export_sent: accepted, of: entries.length, ...RECEIPTS }));
1243
+ if (fromExports) console.log(JSON.stringify({ export_sent: accepted, of: entries.length, ...RECEIPTS })); else console.log(JSON.stringify({ history_sent: accepted, of: entries.length, ...RECEIPTS })); // the same line for a history send: what the door did with it
1247
1244
  await exitFlushed(accepted === entries.length ? 0 : 1);
1248
1245
  }
1249
1246
 
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "worktrust",
3
- "version": "0.10.11",
3
+ "version": "0.10.13",
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": {
@@ -20,6 +20,7 @@
20
20
  "stretch-evidence.mjs",
21
21
  "chat-exports.mjs",
22
22
  "stack-rules.mjs",
23
+ "runtime-install.mjs",
23
24
  "README.md",
24
25
  "SECURITY.md",
25
26
  "LICENSE",
@@ -0,0 +1,64 @@
1
+ /** Immutable, owned runtime + engine installation for Python tool-runner caches.
2
+ * Called only after the person's connect/update confirmation. No network, credentials or measurement logic.
3
+ */
4
+ import { createHash, randomBytes } from "node:crypto";
5
+ import { existsSync, lstatSync, mkdirSync, readFileSync, readdirSync, renameSync, rmSync, writeFileSync } from "node:fs";
6
+ import { join } from "node:path";
7
+
8
+ const hash = (bytes) => createHash("sha256").update(bytes).digest("hex");
9
+ const regular = (path) => { const stat = lstatSync(path); if (!stat.isFile() || stat.isSymbolicLink()) throw Error("bundled installation requires regular files"); };
10
+ const directory = (path) => { const stat = lstatSync(path); if (!stat.isDirectory() || stat.isSymbolicLink()) throw Error("bundled installation requires owned directories, not symlinks"); };
11
+ const checkedBytes = (path) => { regular(path); return readFileSync(path); };
12
+
13
+ export function installRuntime(runtime, engine, home, moduleNames) {
14
+ directory(runtime); directory(engine); directory(home);
15
+ const descriptor = checkedBytes(join(runtime, "runtime.json"));
16
+ const manifest = JSON.parse(descriptor);
17
+ const executable = process.platform === "win32" ? "node.exe" : "node";
18
+ const target = `${process.platform === "win32" ? "win" : process.platform}-${process.arch}`;
19
+ if (manifest.platform !== target || manifest.executable !== executable || !/^\d+\.\d+\.\d+$/.test(manifest.version) || !/^[a-f0-9]{64}$/.test(manifest.archive_sha256)) throw Error("bundled runtime identity mismatch");
20
+ const names = [executable, "LICENSE"].sort();
21
+ if (!manifest.files || JSON.stringify(Object.keys(manifest.files).sort()) !== JSON.stringify(names) || JSON.stringify(readdirSync(runtime).sort()) !== JSON.stringify([...names, "runtime.json"].sort())) throw Error("bundled runtime file list mismatch");
22
+ const contents = new Map([["runtime/runtime.json", descriptor]]);
23
+ for (const name of names) {
24
+ const bytes = checkedBytes(join(runtime, name));
25
+ if (hash(bytes) !== manifest.files[name]) throw Error("bundled runtime integrity check failed");
26
+ contents.set(`runtime/${name}`, bytes);
27
+ }
28
+ if (!Array.isArray(moduleNames) || !moduleNames.includes("worktrust.mjs") || new Set(moduleNames).size !== moduleNames.length) throw Error("invalid engine module list");
29
+ for (const name of [...moduleNames].sort()) {
30
+ if (!/^[a-z][a-z0-9-]*\.mjs$/.test(name)) throw Error("invalid engine module name");
31
+ contents.set(`engine/${name}`, checkedBytes(join(engine, name)));
32
+ }
33
+ const identities = Object.fromEntries([...contents].map(([name, bytes]) => [name, hash(bytes)]));
34
+ const identity = Buffer.from(JSON.stringify(identities));
35
+ const installations = join(home, "installations"), installed = join(installations, hash(identity));
36
+ if (!existsSync(installations)) mkdirSync(installations, { mode: 0o700 });
37
+ directory(installations);
38
+ const verify = (place) => {
39
+ directory(place);
40
+ if (JSON.stringify(readdirSync(place).sort()) !== JSON.stringify(["engine", "installation.json", "runtime"])) throw Error("installed bundle file list mismatch");
41
+ if (!checkedBytes(join(place, "installation.json")).equals(identity)) throw Error("installed bundle identity mismatch");
42
+ for (const group of ["engine", "runtime"]) {
43
+ directory(join(place, group));
44
+ const expected = [...contents.keys()].filter(name => name.startsWith(`${group}/`)).map(name => name.slice(group.length + 1)).sort();
45
+ if (JSON.stringify(readdirSync(join(place, group)).sort()) !== JSON.stringify(expected)) throw Error("installed bundle file list mismatch");
46
+ }
47
+ for (const [name, digest] of Object.entries(identities)) if (hash(checkedBytes(join(place, name))) !== digest) throw Error("installed bundle integrity check failed");
48
+ };
49
+ if (existsSync(installed)) verify(installed);
50
+ else {
51
+ const temporary = join(installations, `.install-${process.pid}-${randomBytes(8).toString("hex")}`);
52
+ mkdirSync(temporary, { mode: 0o700 });
53
+ try {
54
+ mkdirSync(join(temporary, "engine"), { mode: 0o700 }); mkdirSync(join(temporary, "runtime"), { mode: 0o700 });
55
+ for (const [name, bytes] of contents) writeFileSync(join(temporary, name), bytes, { flag: "wx", mode: name === `runtime/${executable}` ? 0o755 : 0o600 });
56
+ writeFileSync(join(temporary, "installation.json"), identity, { flag: "wx", mode: 0o600 });
57
+ verify(temporary);
58
+ try { renameSync(temporary, installed); }
59
+ catch (error) { if (!existsSync(installed)) throw error; verify(installed); }
60
+ } finally { rmSync(temporary, { recursive: true, force: true }); }
61
+ }
62
+ // Existing immutable directories are never replaced, including executables used by Windows processes.
63
+ return { executable: join(installed, "runtime", executable), bridge: join(installed, "engine", "worktrust.mjs") };
64
+ }
package/worktrust.mjs CHANGED
@@ -70,7 +70,7 @@
70
70
  import { execFileSync, spawn } from "node:child_process";
71
71
  import { createHash, generateKeyPairSync, randomBytes, sign } from "node:crypto";
72
72
  import { createServer } from "node:http";
73
- import { chmodSync, closeSync, copyFileSync, existsSync, mkdirSync, openSync, readFileSync, readdirSync, renameSync, rmSync, statSync, writeFileSync, writeSync } from "node:fs";
73
+ import { chmodSync, closeSync, copyFileSync, existsSync, lstatSync, mkdirSync, openSync, readFileSync, readdirSync, renameSync, rmSync, statSync, writeFileSync, writeSync } from "node:fs";
74
74
  import { homedir, hostname, platform } from "node:os";
75
75
  import { dirname, join } from "node:path";
76
76
  import { createInterface } from "node:readline/promises";
@@ -79,18 +79,18 @@ import { fileURLToPath } from "node:url";
79
79
 
80
80
  const args = process.argv.slice(2);
81
81
  const VALUED = ["--name", "--origin", "--url", "--export", "--from-folder"];
82
- const command = args.find((arg, at) => !arg.startsWith("--") && !(at > 0 && VALUED.includes(args[at - 1]))) ?? (args.includes("--help") ? "help" : "default");
82
+ const command = args.includes("--help") ? "help" : args.includes("--version") ? "version" : args.find((arg, at) => !arg.startsWith("--") && !(at > 0 && VALUED.includes(args[at - 1]))) ?? "default";
83
83
  const flag = (name) => { const at = args.indexOf(`--${name}`); return at >= 0 ? args[at + 1] : undefined; };
84
84
  const has = (name) => args.includes(`--${name}`);
85
85
  /** 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). */
86
- const CLI_VERSION = "0.10.11";
86
+ const CLI_VERSION = "0.10.13";
87
87
  const ORIGIN = (flag("origin") ?? process.env.WORKTRUST_ORIGIN ?? "https://app.worktrust.io").replace(/\/$/, "");
88
88
  const MCP = flag("url") ?? process.env.WORKTRUST_MCP_URL ?? `${ORIGIN}/api/mcp`;
89
89
  const HOME_DIR = join(homedir(), ".worktrust");
90
90
  const HERE = dirname(fileURLToPath(import.meta.url));
91
- const SCRIPTS = ["setup-mcp.mjs", "log-session.mjs", "count-behaviour.mjs", "transcript-readers.mjs", "session-databases.mjs", "config-edits.mjs", "stretch-evidence.mjs", "chat-exports.mjs", "stack-rules.mjs"];
91
+ const SCRIPTS = ["setup-mcp.mjs", "log-session.mjs", "count-behaviour.mjs", "transcript-readers.mjs", "session-databases.mjs", "config-edits.mjs", "stretch-evidence.mjs", "chat-exports.mjs", "stack-rules.mjs", "runtime-install.mjs"];
92
92
  /** The modules the scripts import by name from beside them; a download keeps that name. */
93
- const IMPORTED = new Set(["transcript-readers.mjs", "session-databases.mjs", "config-edits.mjs", "stretch-evidence.mjs", "chat-exports.mjs", "stack-rules.mjs"]);
93
+ const IMPORTED = new Set(["transcript-readers.mjs", "session-databases.mjs", "config-edits.mjs", "stretch-evidence.mjs", "chat-exports.mjs", "stack-rules.mjs", "runtime-install.mjs"]);
94
94
  const downloaded = (name) => (IMPORTED.has(name) ? name : `${name}.download.mjs`);
95
95
  const BUNDLED = SCRIPTS.every((name) => existsSync(join(HERE, name)));
96
96
  const PLACEHOLDER = `wt_${"0".repeat(43)}`;
@@ -272,13 +272,29 @@ async function pairByCode(host, extra) {
272
272
  * that survives an upgrade), not this process's resolved path, which names one version and breaks
273
273
  * with the next `brew upgrade node`.
274
274
  */
275
- const NODE = (process.env.PATH ?? "").split(OS === "windows" ? ";" : ":").map((dir) => join(dir, OS === "windows" ? "node.exe" : "node")).find((path) => existsSync(path)) ?? process.execPath;
275
+ let NODE = process.env.WORKTRUST_BUNDLED_RUNTIME_DIR ? process.execPath : (process.env.PATH ?? "").split(OS === "windows" ? ";" : ":").map((dir) => join(dir, OS === "windows" ? "node.exe" : "node")).find((path) => existsSync(path)) ?? process.execPath;
276
276
  const KEY_FILE = join(HOME_DIR, "key.json");
277
- const STABLE = join(HOME_DIR, "worktrust.mjs");
277
+ const STABLE_FILE = join(HOME_DIR, "worktrust.mjs");
278
+ let STABLE = STABLE_FILE, runtimePrepared = false;
278
279
  const RENEW_EVERY_MS = 7 * 24 * 3600_000;
279
280
  const KEY_PLACE = "~/.worktrust/key.json (only you can read it)";
280
281
  const ensureHome = () => { mkdirSync(HOME_DIR, { recursive: true, mode: 0o700 }); try { chmodSync(HOME_DIR, 0o700); } catch { /* Windows */ } };
281
282
 
283
+ /** A tool-runner cache is disposable. Install the whole verified runtime/engine before changing wiring. */
284
+ async function prepareBundledRuntime() {
285
+ if (!process.env.WORKTRUST_BUNDLED_RUNTIME_DIR || runtimePrepared) return;
286
+ const { installRuntime } = await import("./runtime-install.mjs");
287
+ if (existsSync(HOME_DIR) && (!lstatSync(HOME_DIR).isDirectory() || lstatSync(HOME_DIR).isSymbolicLink())) fail("the WorkTrust directory must be a directory, not a symlink.");
288
+ ensureHome();
289
+ const installed = installRuntime(process.env.WORKTRUST_BUNDLED_RUNTIME_DIR, HERE, HOME_DIR, ["worktrust.mjs", ...SCRIPTS, "preserve.mjs", "preserve-lines.mjs", "preserve-summary.mjs"]);
290
+ NODE = installed.executable; STABLE = installed.bridge; runtimePrepared = true;
291
+ }
292
+ function saveStableEntry() {
293
+ const temporary = `${STABLE_FILE}.${randomBytes(8).toString("hex")}.tmp`;
294
+ try { writeFileSync(temporary, readFileSync(fileURLToPath(import.meta.url)), { flag: "wx", mode: 0o600 }); renameSync(temporary, STABLE_FILE); }
295
+ finally { try { rmSync(temporary); } catch { /* already renamed */ } }
296
+ }
297
+
282
298
  /**
283
299
  * THE KEY'S PLACE: one file only you can read (mode 600 in a 700 folder), holding the key, its device
284
300
  * private key and when it was last renewed. NO KEYCHAIN (owner, 2026-10-03): a keychain tool can ask
@@ -346,8 +362,11 @@ function proof(device, url, body) {
346
362
  async function accepted(url, token, device) {
347
363
  try {
348
364
  const body = JSON.stringify({ jsonrpc: "2.0", id: 0, method: "tools/list" });
349
- const response = await fetch(url, { method: "POST", headers: { "content-type": "application/json", accept: "application/json, text/event-stream", authorization: `Bearer ${token}`, "user-agent": "worktrust-bridge", ...proof(device, url, body) }, body });
350
- return response.status !== 401 && response.status !== 403;
365
+ const response = await fetch(url, { method: "POST", headers: { "content-type": "application/json", accept: "application/json", authorization: `Bearer ${token}`, "user-agent": "worktrust-bridge", ...proof(device, url, body) }, body, redirect: "error", signal: AbortSignal.timeout(5000) });
366
+ if (response.status === 401 || response.status === 403) return false;
367
+ if (response.status !== 200) return null;
368
+ const answer = await response.json();
369
+ return answer?.jsonrpc === "2.0" && answer.id === 0 && !answer.error && Array.isArray(answer.result?.tools) ? true : null;
351
370
  } catch { return null; }
352
371
  }
353
372
 
@@ -402,6 +421,8 @@ async function freshKey() {
402
421
  const next = await accepted(value.url, value.pending, value.device);
403
422
  if (next === true) { const promoted = { ...value, token: value.pending, renewedAt: new Date().toISOString() }; delete promoted.pending; keyStore.save(promoted); return promoted; }
404
423
  if (next === false) { delete value.pending; keyStore.save(value); }
424
+ // Unknown means the pending token may already be the server's only accepted key. Never replace it on an outage.
425
+ if (next === null) return value;
405
426
  }
406
427
  if (value.identified && Date.now() - Date.parse(value.renewedAt ?? 0) < RENEW_EVERY_MS) return value;
407
428
  const pending = `wt_${randomBytes(32).toString("base64url")}`;
@@ -410,8 +431,13 @@ async function freshKey() {
410
431
  const renewUrl = `${new URL(value.url).origin}/api/cli/renew`;
411
432
  const ids = computerIds();
412
433
  const body = JSON.stringify({ token_hash: createHash("sha256").update(pending).digest("hex"), token_prefix: pending.slice(0, 11), ...ids });
413
- const response = await fetch(renewUrl, { method: "POST", headers: { "content-type": "application/json", authorization: `Bearer ${value.token}`, ...proof(value.device, renewUrl, body) }, body });
414
- if (response.ok) { const renewed = { ...value, token: pending, renewedAt: new Date().toISOString(), identified: true, profile: value.profile ?? ids.profile_id }; keyStore.save(renewed); return renewed; }
434
+ const response = await fetch(renewUrl, { method: "POST", headers: { "content-type": "application/json", authorization: `Bearer ${value.token}`, ...proof(value.device, renewUrl, body) }, body, redirect: "error", signal: AbortSignal.timeout(5000) });
435
+ if (response.status === 200) {
436
+ const answer = await response.json();
437
+ if (typeof answer?.renewed_at === "string" && Number.isFinite(Date.parse(answer.renewed_at))) {
438
+ const renewed = { ...value, token: pending, renewedAt: new Date().toISOString(), identified: true, profile: value.profile ?? ids.profile_id }; keyStore.save(renewed); return renewed;
439
+ }
440
+ }
415
441
  // Refused: drop the pending key only if the file still holds the value this renewal read.
416
442
  if (response.status === 400 || response.status === 401) { const now = keyStore.load(); if (now?.token === value.token && now?.pending === pending) keyStore.save(value); }
417
443
  } catch { /* offline: the pending key is settled next time */ }
@@ -480,7 +506,7 @@ async function hook() {
480
506
  if (has("hermes") || has("goose")) return sessionEnd();
481
507
  const key = await freshKey();
482
508
  if (!key) process.exit(0);
483
- const child = spawn(process.execPath, [join(HOME_DIR, "log-session.mjs"), ...args.filter((arg) => arg !== "hook")], { stdio: "inherit", env: { ...process.env, WORKTRUST_MCP_URL: key.url, WORKTRUST_MCP_TOKEN: key.token, ...(key.device ? { WORKTRUST_DEVICE_KEY: key.device } : {}) } });
509
+ const child = spawn(process.execPath, [join(BUNDLED ? HERE : HOME_DIR, "log-session.mjs"), ...args.filter((arg) => arg !== "hook")], { stdio: "inherit", env: { ...process.env, WORKTRUST_MCP_URL: key.url, WORKTRUST_MCP_TOKEN: key.token, ...(key.device ? { WORKTRUST_DEVICE_KEY: key.device } : {}) } });
484
510
  child.on("exit", (code) => process.exit(code ?? 0));
485
511
  }
486
512
 
@@ -545,9 +571,10 @@ async function update() {
545
571
  say();
546
572
  if (has("dry-run")) { say(" Dry run: nothing was written and nothing was sent."); return; }
547
573
  if (!(await ask("Continue?"))) { say(" Stopped. Nothing was written."); return; }
548
- ensureHome();
549
574
  const previousVersion = stableVersion();
550
- copyFileSync(fileURLToPath(import.meta.url), STABLE);
575
+ await prepareBundledRuntime();
576
+ ensureHome();
577
+ saveStableEntry();
551
578
  say(` ✓ ${STABLE} is now ${CLI_VERSION}`);
552
579
  // Out first, then in: an app that held a key of its own (a hand-made entry) moves onto the bridge.
553
580
  await run(paths["setup-mcp.mjs"], ["--remove", "--write"], key.token, true);
@@ -600,6 +627,7 @@ async function connect() {
600
627
  say();
601
628
  if (has("dry-run")) { say(" Dry run: nothing was written and nothing was sent."); return; }
602
629
  if (!(await ask("Continue?"))) { say(" Stopped. Nothing was written and nothing was sent."); return; }
630
+ await prepareBundledRuntime();
603
631
 
604
632
  // The device key: made here, its private half kept with the key, its public half bound at WorkTrust.
605
633
  const device = direct ? null : generateKeyPairSync("ed25519");
@@ -618,7 +646,7 @@ async function connect() {
618
646
  keyStore.save({ url: MCP, token, renewedAt: new Date().toISOString(), coupledAt: new Date().toISOString(), identified: true, profile: computerIds().profile_id, account: pairing.account, accountRef: pairing.accountRef, device: device.privateKey.export({ format: "pem", type: "pkcs8" }) });
619
647
  previousNote.erase();
620
648
  ensureHome();
621
- copyFileSync(fileURLToPath(import.meta.url), STABLE);
649
+ saveStableEntry();
622
650
  say(` ✓ Key kept in ${KEY_PLACE}`);
623
651
  }
624
652
  if ((await run(paths["setup-mcp.mjs"], direct ? ["--write"] : ["--write", "--bridge", STABLE], token)).code !== 0) fail("coupling the AI apps failed; the output above says where.");
@@ -669,12 +697,20 @@ async function offerHistory(paths, token, devicePem, url = MCP, rebuild = false)
669
697
  historyDone(false);
670
698
  const sent = await run(paths["log-session.mjs"], ["--history", ...(rebuild ? ["--rebuild"] : [])], token, true, env);
671
699
  historyDone(sent.code === 0);
672
- if (rebuild) say(sent.code === 0 ? " ✓ Rebuilt. This computer's earlier lines for those days were replaced; the record shows each replacement." : " Not all of it arrived. Run npx worktrust again: it finishes what did not arrive, a day already rebuilt is counted once.");
700
+ // WHAT ACTUALLY HAPPENED, FROM THE DOOR'S RECEIPTS (owner, 2026-10-10): a re-measure in which nothing changed must not say
701
+ // "replaced". The hook sums the receipts of every batch and prints one line; without it (an older hook) the sentence stays neutral.
702
+ const did = (() => { try { return JSON.parse(sent.out.trim().split("\n").reverse().find((line) => line.startsWith('{"history_sent"')) ?? "null"); } catch { return null; } })();
703
+ const n = (value) => Number(value) || 0;
704
+ const outcome = !did ? "The record shows what changed."
705
+ : n(did.replaced) > 0 ? `${n(did.replaced)} of this computer's earlier lines were replaced (withdrawn and kept, never deleted)${n(did.new) > 0 ? `, ${n(did.new)} new` : ""}${n(did.filled) > 0 ? `, ${n(did.filled)} lines gained what was missing` : ""}.`
706
+ : n(did.new) === 0 ? `Nothing changed: the same measurement${n(did.filled) > 0 ? `; ${n(did.filled)} lines gained what was missing (the stack, the tools seen, a layer)` : ""}; ${n(did.alreadyHeld)} lines already held.`
707
+ : `${n(did.new)} new lines${n(did.filled) > 0 ? `, ${n(did.filled)} lines gained what was missing` : ""}; ${n(did.alreadyHeld)} already held.`;
708
+ if (rebuild) 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.");
673
709
  else say(sent.code === 0 ? " ✓ Sent as history. Measured sessions count toward your verified hours; 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.");
674
710
  }
675
711
 
676
712
  /** The version stamped in the stable copy in ~/.worktrust, the CLI this computer ran before an update; null without one. */
677
- const stableVersion = () => { try { return /const CLI_VERSION = "([^"]+)";/.exec(readFileSync(STABLE, "utf8"))?.[1] ?? null; } catch { return null; } };
713
+ const stableVersion = () => { try { return /const CLI_VERSION = "([^"]+)";/.exec(readFileSync(STABLE_FILE, "utf8"))?.[1] ?? null; } catch { return null; } };
678
714
 
679
715
  /**
680
716
  * OFFERED ONCE, BY `update`, IN PLAIN WORDS (owner, 2026-10-07): when the computer's earlier lines were made by an earlier CLI
@@ -880,7 +916,8 @@ async function offerCodex() {
880
916
  const viaBridge = existsSync(STABLE);
881
917
  const hookFile = viaBridge ? STABLE : join(HOME_DIR, "log-session.mjs");
882
918
  if (!existsSync(hookFile)) { say(" Couple this computer first: npx worktrust"); return; }
883
- const want = `notify = [${(viaBridge ? [NODE, STABLE, "hook", "--codex-notify"] : [NODE, hookFile, "--codex-notify"]).map((part) => JSON.stringify(part)).join(", ")}]`;
919
+ const desired = () => `notify = [${(viaBridge ? [NODE, STABLE, "hook", "--codex-notify"] : [NODE, hookFile, "--codex-notify"]).map((part) => JSON.stringify(part)).join(", ")}]`;
920
+ let want = desired();
884
921
  const found = codexNotify();
885
922
  say();
886
923
  if (found.text === want) { say(" ✓ Codex already wakes the session hook at the end of every turn."); return; }
@@ -893,6 +930,7 @@ async function offerCodex() {
893
930
  say(` ${found.text ? "↻" : "+"} ${CODEX_CONFIG} → ${want}`);
894
931
  if (has("dry-run")) { say(" Dry run: nothing was written."); return; }
895
932
  if (!has("codex") && !(await ask("Let Codex wake the session hook?", false))) { say(" Not set. npx worktrust update asks again."); return; }
933
+ await prepareBundledRuntime(); want = desired();
896
934
  const rows = [...found.rows];
897
935
  if (found.text) rows.splice(found.at, found.end - found.at + 1, want);
898
936
  else rows.splice(found.insert, 0, ...(found.insert < rows.length && rows[found.insert] !== "" ? [want, ""] : [want]));
@@ -925,7 +963,8 @@ function writeAgyHooks(hooks) {
925
963
  async function offerAntigravity() {
926
964
  if (!antigravityHere()) { if (command === "antigravity") say(" Antigravity is not on this computer (no ~/.gemini/config or ~/.gemini/antigravity*)."); return; }
927
965
  if (!existsSync(STABLE)) { say(" Couple this computer first: npx worktrust"); return; }
928
- const want = { enabled: true, Stop: [{ type: "command", command: `"${NODE}" "${STABLE}" hook --antigravity-stop`, timeout: 10 }] };
966
+ const desired = () => ({ enabled: true, Stop: [{ type: "command", command: `"${NODE}" "${STABLE}" hook --antigravity-stop`, timeout: 10 }] });
967
+ let want = desired();
929
968
  const hooks = agyHooks();
930
969
  say();
931
970
  if (hooks === null) { say(` ${AGY_HOOKS} is not readable JSON, so it is left as it is; Antigravity sessions are still sent whenever another hook runs.`); return; }
@@ -934,6 +973,7 @@ async function offerAntigravity() {
934
973
  say(` ${hooks.worktrust ? "↻" : "+"} ${AGY_HOOKS} → worktrust: Stop runs ${want.Stop[0].command}`);
935
974
  if (has("dry-run")) { say(" Dry run: nothing was written."); return; }
936
975
  if (!has("antigravity") && !(await ask("Let Antigravity wake the session hook?", false))) { say(" Not set. npx worktrust update asks again."); return; }
976
+ await prepareBundledRuntime(); want = desired();
937
977
  writeAgyHooks({ ...hooks, worktrust: want });
938
978
  say(` ✓ Antigravity wakes the session hook. Restart Antigravity to pick it up${existsSync(`${AGY_HOOKS}.worktrust-backup`) ? "; the earlier file is kept as hooks.json.worktrust-backup" : ""}.`);
939
979
  }
@@ -1090,11 +1130,11 @@ function help() {
1090
1130
  // before anything is read or written, --yes included. The hook and the MCP bridge are started by the agent's client
1091
1131
  // itself and stay as they are; `status` only reads.
1092
1132
  const AGENT_ENV = ["CLAUDECODE", "CLAUDE_CODE_ENTRYPOINT", "CODEX_SANDBOX", "CODEX_CI", "GEMINI_CLI", "CURSOR_AGENT", "OPENCODE", "CLINE_ACTIVE", "AIDER_CHAT", "ANTIGRAVITY_AGENT", "WINDSURF_AGENT"];
1093
- const PERSON_ONLY = new Set(["connect", "update", "history", "disconnect", "preserve", "codex", "antigravity", "sources", "web", "import"]);
1133
+ const PERSON_ONLY = new Set(["default", "connect", "update", "history", "disconnect", "preserve", "codex", "antigravity", "sources", "web", "import"]);
1094
1134
  const agentShell = AGENT_ENV.find((name) => process.env[name] && process.env[name] !== "0");
1095
1135
  if (agentShell && PERSON_ONLY.has(command)) {
1096
1136
  say();
1097
- say(` worktrust ${command} is run by the person, in their own terminal, never by an AI agent for them (this shell is an agent's: ${agentShell}).`);
1137
+ say(` worktrust${command === "default" ? "" : ` ${command}`} is run by the person, in their own terminal, never by an AI agent for them (this shell is an agent's: ${agentShell}).`);
1098
1138
  say(" Nothing was read, sent or changed. See AGENTS.md in the package: https://www.npmjs.com/package/worktrust");
1099
1139
  process.exit(3);
1100
1140
  }
@@ -1134,7 +1174,8 @@ async function relayToNewest() {
1134
1174
  }
1135
1175
  await relayToNewest();
1136
1176
 
1137
- if (command === "default") { if (keyStore.load()) await again(); else await connect(); }
1177
+ if (command === "version") say(CLI_VERSION);
1178
+ else if (command === "default") { if (keyStore.load()) await again(); else await connect(); }
1138
1179
  else if (command === "mcp") await bridge();
1139
1180
  else if (command === "hook") await hook();
1140
1181
  else if (command === "connect") await connect();