worktrust 0.10.11 → 0.10.12

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
@@ -339,7 +339,7 @@ which would delete every password on the computer, and many people rightly keep
339
339
  | **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
340
  | **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
341
  | **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). |
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`), 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
343
  | **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
344
 
345
345
  ## Why you can check it
@@ -348,11 +348,12 @@ which would delete every password on the computer, and many people rightly keep
348
348
  in an afternoon: `worktrust.mjs` (this command), `setup-mcp.mjs` (writes the MCP entries),
349
349
  `log-session.mjs` (the session hook), `count-behaviour.mjs` (the local counter) and `preserve.mjs`
350
350
  (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.
351
+ - **Bundled measurement modules.** The npm package includes its counter and readers. Interactive
352
+ commands can check the registry and relay through `npx` to a newer package; that can download code.
353
+ The standalone bootstrap can also download support modules. See SECURITY.md for the distinction.
354
+ - **Provenance.** The release workflow requests npm provenance from the public source repository.
355
+ Verify the actual version's attestation and contents before relying on that origin; the manifest
356
+ setting alone does not establish it. `npm audit signatures` checks an installed dependency tree.
356
357
  - **Read it before you run it:** `npm pack worktrust` downloads the package as a file without
357
358
  running anything.
358
359
  - **The key** never appears on a command line a process list could show: it is written to its file
@@ -376,14 +377,19 @@ which would delete every password on the computer, and many people rightly keep
376
377
  ## Undo
377
378
 
378
379
  `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.
380
+ Antigravity's `worktrust` hook when WorkTrust set them), the key file and installed bridge scripts.
381
+ A small note of the previous account (masked) remains so that a later coupling by another account
382
+ does not offer its earlier work. Other retained files and your local evidence archive are not an
383
+ automatic server or archive erasure.
382
384
  Then revoke the key in WorkTrust: Sources → Devices → this computer → Revoke.
383
385
 
384
386
  ## Requirements
385
387
 
386
- Node 18 or later. macOS, Linux or Windows.
388
+ Node 18 or later for the base CLI. SQLite session readers require Node 22.5 or later with `node:sqlite`;
389
+ without it, those clients are not read. macOS, Linux or Windows; available readers depend on the local client format.
390
+
391
+ See [SECURITY.md](SECURITY.md) for the credential-file threat model, network/update behaviour and known
392
+ trust limits. A local signature proves possession of a key, not independent observation of the work.
387
393
 
388
394
  Security reports: see [SECURITY.md](SECURITY.md).
389
395
 
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");
@@ -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.12",
4
4
  "description": "Couple this computer to WorkTrust: approve a code in your browser, and every AI app here reports what you built. Metadata only, no dependencies.",
5
5
  "type": "module",
6
6
  "bin": {
package/worktrust.mjs CHANGED
@@ -79,11 +79,11 @@ 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.12";
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");
@@ -346,8 +346,11 @@ function proof(device, url, body) {
346
346
  async function accepted(url, token, device) {
347
347
  try {
348
348
  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;
349
+ 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) });
350
+ if (response.status === 401 || response.status === 403) return false;
351
+ if (response.status !== 200) return null;
352
+ const answer = await response.json();
353
+ return answer?.jsonrpc === "2.0" && answer.id === 0 && !answer.error && Array.isArray(answer.result?.tools) ? true : null;
351
354
  } catch { return null; }
352
355
  }
353
356
 
@@ -402,6 +405,8 @@ async function freshKey() {
402
405
  const next = await accepted(value.url, value.pending, value.device);
403
406
  if (next === true) { const promoted = { ...value, token: value.pending, renewedAt: new Date().toISOString() }; delete promoted.pending; keyStore.save(promoted); return promoted; }
404
407
  if (next === false) { delete value.pending; keyStore.save(value); }
408
+ // Unknown means the pending token may already be the server's only accepted key. Never replace it on an outage.
409
+ if (next === null) return value;
405
410
  }
406
411
  if (value.identified && Date.now() - Date.parse(value.renewedAt ?? 0) < RENEW_EVERY_MS) return value;
407
412
  const pending = `wt_${randomBytes(32).toString("base64url")}`;
@@ -410,8 +415,13 @@ async function freshKey() {
410
415
  const renewUrl = `${new URL(value.url).origin}/api/cli/renew`;
411
416
  const ids = computerIds();
412
417
  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; }
418
+ 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) });
419
+ if (response.status === 200) {
420
+ const answer = await response.json();
421
+ if (typeof answer?.renewed_at === "string" && Number.isFinite(Date.parse(answer.renewed_at))) {
422
+ const renewed = { ...value, token: pending, renewedAt: new Date().toISOString(), identified: true, profile: value.profile ?? ids.profile_id }; keyStore.save(renewed); return renewed;
423
+ }
424
+ }
415
425
  // Refused: drop the pending key only if the file still holds the value this renewal read.
416
426
  if (response.status === 400 || response.status === 401) { const now = keyStore.load(); if (now?.token === value.token && now?.pending === pending) keyStore.save(value); }
417
427
  } catch { /* offline: the pending key is settled next time */ }
@@ -669,7 +679,15 @@ async function offerHistory(paths, token, devicePem, url = MCP, rebuild = false)
669
679
  historyDone(false);
670
680
  const sent = await run(paths["log-session.mjs"], ["--history", ...(rebuild ? ["--rebuild"] : [])], token, true, env);
671
681
  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.");
682
+ // WHAT ACTUALLY HAPPENED, FROM THE DOOR'S RECEIPTS (owner, 2026-10-10): a re-measure in which nothing changed must not say
683
+ // "replaced". The hook sums the receipts of every batch and prints one line; without it (an older hook) the sentence stays neutral.
684
+ const did = (() => { try { return JSON.parse(sent.out.trim().split("\n").reverse().find((line) => line.startsWith('{"history_sent"')) ?? "null"); } catch { return null; } })();
685
+ const n = (value) => Number(value) || 0;
686
+ const outcome = !did ? "The record shows what changed."
687
+ : 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` : ""}.`
688
+ : 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.`
689
+ : `${n(did.new)} new lines${n(did.filled) > 0 ? `, ${n(did.filled)} lines gained what was missing` : ""}; ${n(did.alreadyHeld)} already held.`;
690
+ 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
691
  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
692
  }
675
693
 
@@ -1090,11 +1108,11 @@ function help() {
1090
1108
  // before anything is read or written, --yes included. The hook and the MCP bridge are started by the agent's client
1091
1109
  // itself and stay as they are; `status` only reads.
1092
1110
  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"]);
1111
+ const PERSON_ONLY = new Set(["default", "connect", "update", "history", "disconnect", "preserve", "codex", "antigravity", "sources", "web", "import"]);
1094
1112
  const agentShell = AGENT_ENV.find((name) => process.env[name] && process.env[name] !== "0");
1095
1113
  if (agentShell && PERSON_ONLY.has(command)) {
1096
1114
  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}).`);
1115
+ 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
1116
  say(" Nothing was read, sent or changed. See AGENTS.md in the package: https://www.npmjs.com/package/worktrust");
1099
1117
  process.exit(3);
1100
1118
  }
@@ -1134,7 +1152,8 @@ async function relayToNewest() {
1134
1152
  }
1135
1153
  await relayToNewest();
1136
1154
 
1137
- if (command === "default") { if (keyStore.load()) await again(); else await connect(); }
1155
+ if (command === "version") say(CLI_VERSION);
1156
+ else if (command === "default") { if (keyStore.load()) await again(); else await connect(); }
1138
1157
  else if (command === "mcp") await bridge();
1139
1158
  else if (command === "hook") await hook();
1140
1159
  else if (command === "connect") await connect();