worktrust 0.11.8 → 0.11.10

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.
@@ -18,6 +18,7 @@ import { createHash, randomBytes } from "node:crypto";
18
18
  import { createServer } from "node:http";
19
19
  import { createInterface } from "node:readline/promises";
20
20
  import * as P from "./remote-protocol.mjs";
21
+ import { PRODUCTION_GATEWAY } from "./remote-store.mjs";
21
22
 
22
23
  const PROOF = P.utf8Encode("worktrust-remote/v1/pair-request\n");
23
24
  const RENEW = P.utf8Encode("worktrust-remote/v1/renew\n");
@@ -36,6 +37,40 @@ async function post(origin, path, body) {
36
37
  return { status: response.status, json: await response.json().catch(() => ({})) };
37
38
  }
38
39
 
40
+ /**
41
+ * ONE SCAN (CLI 0.11.10, owner 2026-11-14: "once you have done that, do you still have to pair? Otherwise you go through the
42
+ * same step twice"). `remote app` draws the approval link with the PAIRING material in its fragment, which no browser sends
43
+ * to a server: `<authorize_url>#v=1&g=<gateway>&k=<Ed25519 pub>&x=<X25519 pub>&s=<32-byte secret>&e=<expiry>`, the pairing
44
+ * invite of PROTOCOL.md §Pairing without `d` (the issuer names this computer's device id only when it approves). The
45
+ * WorkTrust app's own scanner approves with the authenticator, finds this computer in the account's device list by the
46
+ * fingerprint of `k` and `x`, and makes the invite whole with its device id; the daemon then confirms the phone by the
47
+ * secret's proof, exactly as a scanned `remote pair` QR. The camera app or a browser opens the approve link and ignores the
48
+ * fragment: pairing a phone is then the second step it always was (`linkPhone` shows the QR after its wait).
49
+ */
50
+ export const ONE_SCAN_KEYS = Object.freeze(["v", "g", "k", "x", "s", "e"]);
51
+ export function oneScan({ gateway, publicKeys, nowMs, random }) {
52
+ if (!gateway || !P.isGatewayOrigin(gateway)) return null;
53
+ const fields = { v: 1, g: gateway, k: publicKeys.ed25519_pub, x: publicKeys.x25519_pub, s: P.toBase64Url(random(32)), e: Math.floor(nowMs / 1000) + P.PAIRING_INVITE_LIFETIME_S };
54
+ return { ...fields, fragment: ONE_SCAN_KEYS.map((key) => `${key}=${encodeURIComponent(String(fields[key]))}`).join("&") };
55
+ }
56
+ /**
57
+ * THE QR'S OWN, SHORTER FORM OF A LINK (owner, 2026-11-14: "make the QR more compact"): `g` is left out when it names
58
+ * WorkTrust's production relay, the one the phone assumes when `g` is missing (CLI 0.11.10 with the app's 2026-11-14
59
+ * JavaScript, which reads both forms). `d`, `k`, `x`, `s` and `e` are never left out; another gateway (the dev relay) stays
60
+ * named. Only the drawn code is shortened: the printed link and invite.json keep `g`, for a browser it is pasted into and
61
+ * for the daemon. 36 characters fewer: the pairing QR goes from version 12 to 9 with level L.
62
+ */
63
+ const DEFAULT_G = `&g=${encodeURIComponent(PRODUCTION_GATEWAY)}`;
64
+ export const compactForQr = (link) => link.replace(DEFAULT_G, "");
65
+ /** The approval link with the pairing material in its fragment, or the link as it was (no gateway, the browser's road). */
66
+ export const withPairing = (url, once) => (once ? `${url}#${once.fragment}` : url);
67
+ /** The invite the daemon reads (invite.json) once the issuer named this computer: the one-scan secret, now with its `d`; checked by the protocol's own encoder. */
68
+ export function oneScanInvite(once, deviceId, code, nowMs) {
69
+ const invite = { v: once.v, g: once.g, d: deviceId, k: once.k, x: once.x, s: once.s, e: once.e };
70
+ P.encodePairingInvite(invite);
71
+ return { ...invite, code, used: false, created_at: nowMs };
72
+ }
73
+
39
74
  /** Which road, the app's QR here (Enter) or the browser; not a terminal, or --yes: the browser. Since 0.11.7 the person names the road (`remote app` | `remote web`, or the menu); kept for a caller that asks. */
40
75
  export async function chooseRoad({ interactive = Boolean(process.stdin.isTTY), yes = false, prompt = null } = {}) {
41
76
  if (!interactive || yes) return "web";
@@ -49,7 +84,7 @@ export async function chooseRoad({ interactive = Boolean(process.stdin.isTTY), y
49
84
  * Pair, and return the verified binding. `keys` holds the secret pair (never sent), `issuerKeys` the pinned keys. `road`:
50
85
  * "web" opens the approval page in the browser; "app" draws its link with `showQr` for the WorkTrust app and opens nothing.
51
86
  */
52
- export async function pairComputer({ origin, secret, publicKeys, host, os, device = false, road = "web", showQr = () => {}, issuerKeys, say, openBrowser, now = Date.now, countdown = null }) {
87
+ export async function pairComputer({ origin, secret, publicKeys, host, os, device = false, road = "web", showQr = () => {}, issuerKeys, say, openBrowser, now = Date.now, countdown = null, once = null, showLink = false }) {
53
88
  const verifier = randomBytes(32).toString("base64url");
54
89
  const code_challenge = createHash("sha256").update(verifier).digest("base64url");
55
90
  const state = randomBytes(24).toString("base64url");
@@ -83,9 +118,12 @@ export async function pairComputer({ origin, secret, publicKeys, host, os, devic
83
118
  let exchanged = null;
84
119
  if (!device) {
85
120
  if (road === "app") {
86
- say(" Scan this with the WorkTrust app (or the phone's camera) and approve with your authenticator code:");
87
- showQr(authorize_url);
88
- say(` Link: ${authorize_url}`);
121
+ // One scan (0.11.10): the app's scanner approves AND links this phone; the camera app only approves.
122
+ say(once ? " Scan this in the WorkTrust app (Scan › Connect agent): approve with your authenticator code, and the phone links too." : " Scan this with the WorkTrust app (or the phone's camera) and approve with your authenticator code:");
123
+ showQr(withPairing(authorize_url, once));
124
+ // The printed link leaves the pairing secret out (scrollback, a shared screen; review 2026-11-14, P3-7): the QR carries
125
+ // it, and --show-link prints it whole for a phone that cannot scan.
126
+ say(` Link: ${showLink ? withPairing(authorize_url, once) : authorize_url}`);
89
127
  } else {
90
128
  say(` Approve in your browser (opening it). If it does not open: ${authorize_url}`);
91
129
  openBrowser(authorize_url);
package/remote-qr.mjs CHANGED
@@ -1,6 +1,6 @@
1
1
  /**
2
2
  * A QR CODE FOR THE TERMINAL, WITHOUT A DEPENDENCY (2026-11-07; owner: pairing by scanning the computer's screen with the
3
- * WorkTrust app). ISO/IEC 18004: byte mode, error correction level M, the smallest version 1 to 40 that holds the data,
3
+ * WorkTrust app). ISO/IEC 18004: byte mode, error correction level M (or L), the smallest version 1 to 40 that holds the data,
4
4
  * the mask with the lowest penalty, format and version information. `qrMatrix(text)` gives the modules (true = dark);
5
5
  * `renderQr(matrix)` draws them with half-block characters, two module rows per line, black on an explicitly white
6
6
  * background with a four-module white quiet zone, so it scans in a light or a dark terminal.
@@ -16,8 +16,20 @@ const EC_M = [null,
16
16
  [26, 17, 42], [28, 17, 46], [28, 4, 47, 14, 48], [28, 6, 45, 14, 46], [28, 8, 47, 13, 48], [28, 19, 46, 4, 47], [28, 22, 45, 3, 46], [28, 3, 45, 23, 46], [28, 21, 45, 7, 46], [28, 19, 47, 10, 48],
17
17
  [28, 2, 46, 29, 47], [28, 10, 46, 23, 47], [28, 14, 46, 21, 47], [28, 14, 46, 23, 47], [28, 12, 47, 26, 48], [28, 6, 47, 34, 48], [28, 29, 46, 14, 47], [28, 13, 46, 32, 47], [28, 40, 47, 7, 48], [28, 18, 47, 31, 48]];
18
18
 
19
- const blocksOf = (v) => { const [ec, n1, d1, n2 = 0, d2 = 0] = EC_M[v]; return { ec, groups: [[n1, d1], [n2, d2]].filter(([n]) => n > 0) }; };
20
- const dataCodewords = (v) => blocksOf(v).groups.reduce((s, [n, d]) => s + n * d, 0);
19
+ // Level L, the same shape (ISO/IEC 18004 table 9). A code on a screen is not scuffed like a print: L (7% recovery, M is 15%)
20
+ // holds the same link in fewer modules (owner, 2026-11-14: "make the QR more compact"). Every version's total of codewords
21
+ // is the same as M's; scripts/test-remote-claude-events.mjs holds that for all forty.
22
+ const EC_L = [null,
23
+ [7, 1, 19], [10, 1, 34], [15, 1, 55], [20, 1, 80], [26, 1, 108], [18, 2, 68], [20, 2, 78], [24, 2, 97], [30, 2, 116], [18, 2, 68, 2, 69],
24
+ [20, 4, 81], [24, 2, 92, 2, 93], [26, 4, 107], [30, 3, 115, 1, 116], [22, 5, 87, 1, 88], [24, 5, 98, 1, 99], [28, 1, 107, 5, 108], [30, 5, 120, 1, 121], [28, 3, 113, 4, 114], [28, 3, 107, 5, 108],
25
+ [28, 4, 116, 4, 117], [28, 2, 111, 7, 112], [30, 4, 121, 5, 122], [30, 6, 117, 4, 118], [26, 8, 106, 4, 107], [28, 10, 114, 2, 115], [30, 8, 122, 4, 123], [30, 3, 117, 10, 118], [30, 7, 116, 7, 117], [30, 5, 115, 10, 116],
26
+ [30, 13, 115, 3, 116], [30, 17, 115], [30, 17, 115, 1, 116], [30, 13, 115, 6, 116], [30, 12, 121, 7, 122], [30, 6, 121, 14, 122], [30, 17, 122, 4, 123], [30, 4, 122, 18, 123], [30, 20, 117, 4, 118], [30, 19, 118, 6, 119]];
27
+ const TABLES = { L: EC_L, M: EC_M };
28
+ /** The format information's two level bits (L 01, M 00). */
29
+ const LEVEL_BITS = { L: 0b01, M: 0b00 };
30
+
31
+ export const blocksOf = (v, level = "M") => { const [ec, n1, d1, n2 = 0, d2 = 0] = TABLES[level][v]; return { ec, groups: [[n1, d1], [n2, d2]].filter(([n]) => n > 0) }; };
32
+ const dataCodewords = (v, level = "M") => blocksOf(v, level).groups.reduce((s, [n, d]) => s + n * d, 0);
21
33
 
22
34
  // GF(256) with the QR polynomial x^8 + x^4 + x^3 + x^2 + 1.
23
35
  const EXP = new Uint8Array(512), LOG = new Uint8Array(256);
@@ -44,12 +56,12 @@ export function reedSolomon(data, degree) {
44
56
  return rem;
45
57
  }
46
58
 
47
- function codewords(bytes) {
59
+ function codewords(bytes, level = "M") {
48
60
  let version = 1;
49
61
  const need = (v) => 4 + (v < 10 ? 8 : 16) + bytes.length * 8;
50
- while (version <= 40 && need(version) > dataCodewords(version) * 8) version += 1;
62
+ while (version <= 40 && need(version) > dataCodewords(version, level) * 8) version += 1;
51
63
  if (version > 40) throw new RangeError("too much data for one QR code");
52
- const capacity = dataCodewords(version) * 8, bits = [];
64
+ const capacity = dataCodewords(version, level) * 8, bits = [];
53
65
  const put = (value, length) => { for (let i = length - 1; i >= 0; i -= 1) bits.push((value >>> i) & 1); };
54
66
  put(0b0100, 4);
55
67
  put(bytes.length, version < 10 ? 8 : 16);
@@ -59,7 +71,7 @@ function codewords(bytes) {
59
71
  for (let pad = 0; bits.length < capacity; pad += 1) put(pad % 2 ? 0x11 : 0xec, 8);
60
72
  const data = [];
61
73
  for (let i = 0; i < bits.length; i += 8) data.push(bits.slice(i, i + 8).reduce((a, b) => (a << 1) | b, 0));
62
- const { ec, groups } = blocksOf(version), blocks = [];
74
+ const { ec, groups } = blocksOf(version, level), blocks = [];
63
75
  let at = 0;
64
76
  for (const [n, d] of groups) for (let i = 0; i < n; i += 1) { const block = data.slice(at, at + d); at += d; blocks.push({ data: block, ec: reedSolomon(block, ec) }); }
65
77
  const out = [], longest = Math.max(...blocks.map((b) => b.data.length));
@@ -79,7 +91,7 @@ export function alignmentCenters(version) {
79
91
  }
80
92
 
81
93
  const bch = (value, poly, bitsOfPoly) => { let v = value << (bitsOfPoly - 1); while (31 - Math.clz32(v) >= bitsOfPoly - 1) v ^= poly << (31 - Math.clz32(v) - (bitsOfPoly - 1)); return v; };
82
- export const formatBits = (mask) => { const data = (0b00 << 3) | mask; return ((data << 10) | bch(data, 0x537, 11)) ^ 0x5412; };
94
+ export const formatBits = (mask, level = "M") => { const data = (LEVEL_BITS[level] << 3) | mask; return ((data << 10) | bch(data, 0x537, 11)) ^ 0x5412; };
83
95
  export const versionBits = (version) => (version << 12) | bch(version, 0x1f25, 13);
84
96
 
85
97
  export const MASKS = [(r, c) => (r + c) % 2 === 0, (r) => r % 2 === 0, (r, c) => c % 3 === 0, (r, c) => (r + c) % 3 === 0,
@@ -110,7 +122,7 @@ function base(version) {
110
122
  return { size, m, fixed };
111
123
  }
112
124
 
113
- function place(version, words, mask) {
125
+ function place(version, words, mask, level = "M") {
114
126
  const { size, m, fixed } = base(version);
115
127
  let bit = 0;
116
128
  const total = words.length * 8, take = () => (bit < total ? (words[bit >> 3] >>> (7 - (bit++ & 7))) & 1 : 0);
@@ -121,7 +133,7 @@ function place(version, words, mask) {
121
133
  for (const c of [col, col - 1]) if (!fixed[r][c]) m[r][c] = (take() === 1) !== MASKS[mask](r, c);
122
134
  }
123
135
  }
124
- const f = formatBits(mask);
136
+ const f = formatBits(mask, level);
125
137
  for (let i = 0; i < 15; i += 1) {
126
138
  const dark = ((f >> i) & 1) === 1;
127
139
  if (i < 6) m[i][8] = dark; else if (i < 8) m[i + 1][8] = dark; else m[size - 15 + i][8] = dark;
@@ -153,17 +165,19 @@ export function penalty(m) {
153
165
  }
154
166
 
155
167
  /** The modules of the QR code for `text` (UTF-8 bytes), `mask` chosen by penalty unless given. */
156
- export function qrMatrix(text, forcedMask = null) {
157
- const { version, out } = codewords(new TextEncoder().encode(text));
158
- if (forcedMask !== null) return { version, mask: forcedMask, modules: place(version, out, forcedMask) };
168
+ export function qrMatrix(text, forcedMask = null, level = "M") {
169
+ const { version, out } = codewords(new TextEncoder().encode(text), level);
170
+ if (forcedMask !== null) return { version, mask: forcedMask, modules: place(version, out, forcedMask, level) };
159
171
  let best = null;
160
- for (let mask = 0; mask < 8; mask += 1) { const modules = place(version, out, mask), score = penalty(modules); if (!best || score < best.score) best = { version, mask, modules, score }; }
172
+ for (let mask = 0; mask < 8; mask += 1) { const modules = place(version, out, mask, level), score = penalty(modules); if (!best || score < best.score) best = { version, mask, modules, score }; }
161
173
  return { version: best.version, mask: best.mask, modules: best.modules };
162
174
  }
163
175
 
176
+ /** The quiet zone, in modules, around every code the CLI draws (the standard's four; its ground is drawn white). */
177
+ export const QUIET = 4;
164
178
  /** Half blocks, black on white, a four-module quiet zone. `color` false gives the plain characters (dark = block). */
165
179
  export function renderQr(modules, { color = true } = {}) {
166
- const quiet = 4, size = modules.length + quiet * 2;
180
+ const quiet = QUIET, size = modules.length + quiet * 2;
167
181
  const dark = (r, c) => { const rr = r - quiet, cc = c - quiet; return rr >= 0 && cc >= 0 && rr < modules.length && cc < modules.length && modules[rr][cc]; };
168
182
  const lines = [];
169
183
  for (let r = 0; r < size; r += 2) {
@@ -173,3 +187,14 @@ export function renderQr(modules, { color = true } = {}) {
173
187
  }
174
188
  return lines.join("\n");
175
189
  }
190
+
191
+ /**
192
+ * EVERY QR THE CLI DRAWS GOES THROUGH HERE (owner, 2026-11-14: "make the QR more compact"): the approval, the pairing and the
193
+ * one-scan code alike, level L, half blocks (two module rows per terminal line), the white quiet zone, so a version-10 code
194
+ * is 33 lines by 65 columns and fits an 80-column terminal. `color` as renderQr: the ground drawn white on a terminal with
195
+ * colours, the plain characters otherwise (a pipe, NO_COLOR). check-remote-cli and cli-01110-cases hold that no other path
196
+ * draws one.
197
+ */
198
+ export function terminalQr(text, { color = true } = {}) {
199
+ return renderQr(qrMatrix(text, null, "L").modules, { color });
200
+ }
package/remote-run.mjs CHANGED
@@ -15,7 +15,7 @@ import { fileURLToPath } from "node:url";
15
15
  import * as P from "./remote-protocol.mjs";
16
16
  import { loadPreviewGrants, loadRoots } from "./remote-store.mjs";
17
17
  import { sessionProjects } from "./remote-projects.mjs";
18
- import { ensureRemoteDir, issuerKeys, loadDeskMarks, loadIdentity, loadKeys, loadPipelineReviews, loadProjects, loadSettings, readJson, remotePath, random, saveIdentity } from "./remote-store.mjs";
18
+ import { ensureRemoteDir, gatewayOf, issuerKeys, loadDeskMarks, loadIdentity, loadKeys, loadPipelineReviews, loadProjects, loadSettings, readJson, remotePath, random, saveIdentity } from "./remote-store.mjs";
19
19
  import { openJournal } from "./remote-journal.mjs";
20
20
  import { inventory as listAgents, offered } from "./remote-inventory.mjs";
21
21
 
@@ -105,9 +105,11 @@ export async function runDaemon({ say = (l) => process.stdout.write(`${l}\n`) }
105
105
  const settings = loadSettings(), identity = loadIdentity(), keys = loadKeys();
106
106
  if (!settings.enabled) throw new Error("remote is off on this computer: run `worktrust remote app` (or `remote web`)");
107
107
  if (!identity || !keys) throw new Error("this computer is not paired for remote: run `worktrust remote app` (or `remote web`)");
108
- if (!settings.gateway) throw new Error("no gateway is set: the production gateway is not live yet; for local tests pass --gateway ws://127.0.0.1:<port> to `worktrust remote app` (or `remote web`)");
108
+ // A computer saved with `gateway: null` (0.11.8 and 0.11.9 saved that when none was given) uses WorkTrust's relay: no new
109
+ // approval is needed (owner, 2026-11-14: on by default).
110
+ const gateway = gatewayOf(settings);
109
111
  if (!webSocketAvailable()) throw new Error(`remote needs Node 22.4 or later (this is ${process.versions.node})`);
110
- const keysOf = issuerKeys(settings.gateway);
112
+ const keysOf = issuerKeys(gateway);
111
113
  const claims = P.verifyBinding(identity.binding, { issuerKeys: keysOf, now: Date.now(), kind: "computer", deviceId: identity.device_id });
112
114
  if (!claims.ok) throw new Error(`this computer's binding does not verify (${claims.code}): run \`worktrust remote app\` (or \`remote web\`) again`);
113
115
  if (claims.value.exp * 1000 - Date.now() < 7 * 86400_000 && identity.origin) {
@@ -176,9 +178,9 @@ export async function runDaemon({ say = (l) => process.stdout.write(`${l}\n`) }
176
178
  // The production gateway admits a computer on a five-minute assertion from the issuer, asked fresh for every challenge.
177
179
  const { requestAssertion } = await import("./remote-pairing.mjs");
178
180
  const authorize = () => (identity.origin ? requestAssertion({ origin: identity.origin, deviceId: identity.device_id, secret: keys.secret }) : Promise.resolve(null));
179
- transport = connectGateway({ url: settings.gateway, identity, signingSecret: keys.secret.ed25519, log, authorize, onFrame: (f) => { dispatchFrame(f).catch((e) => log("frame_failed", { name: e?.name ?? "Error" })); },
181
+ transport = connectGateway({ url: gateway, identity, signingSecret: keys.secret.ed25519, log, authorize, onFrame: (f) => { dispatchFrame(f).catch((e) => log("frame_failed", { name: e?.name ?? "Error" })); },
180
182
  onState: (state, info) => { log("gateway", { state, ...info }); if (state === "ready") registerCode(true); } });
181
- say(` WorkTrust remote is running for ${identity.device_id} (gateway ${new URL(settings.gateway).host}). Ctrl+C stops it.`);
183
+ say(` WorkTrust remote is running for ${identity.device_id} (gateway ${new URL(gateway).host}). Ctrl+C stops it.`);
182
184
  let stopping = false;
183
185
  const stop = async (code = 0) => {
184
186
  if (stopping) return;
package/remote-store.mjs CHANGED
@@ -72,6 +72,16 @@ export const saveIdentity = (identity) => writeJson("identity.json", identity);
72
72
  // modes_allowed (0.11.7, owner 2026-11-12): the CEILING of agent modes a phone may start, set here only (`worktrust remote
73
73
  // modes allow|deny edit|auto`); manual and plan always. admin (0.11.7): RESERVED for managing this computer from the app or
74
74
  // the web with a server-signed proof (part B); on by default, honoured by nothing yet (remote-settings.mjs).
75
+ /**
76
+ * WORKTRUST'S PRODUCTION RELAY, ON BY DEFAULT FOR EVERYONE (owner, 2026-11-14: "it must be ON by default for everyone, also
77
+ * without Premium; the subscription comes later"; CLI 0.11.10). A computer's saved `gateway: null` means THIS default, read
78
+ * where it is used, so a later change of the default moves every computer that never chose one; `--gateway` and
79
+ * WORKTRUST_REMOTE_GATEWAY at `remote app` still choose another (the dev relay, tests), and that choice is saved.
80
+ * GATEWAY.md step 9 (a crypto review and a penetration test) is still open: the owner chose the default before it.
81
+ */
82
+ export const PRODUCTION_GATEWAY = "wss://remote.worktrust.io";
83
+ /** The relay this computer uses: its own saved choice, else WorkTrust's. */
84
+ export const gatewayOf = (settings) => settings?.gateway ?? PRODUCTION_GATEWAY;
75
85
  export const DEFAULT_SETTINGS = Object.freeze({ v: 1, enabled: false, paused: null, gateway: null, default_adapter: "claude-code", default_model: null, agent_path: null, codex: false, opencode: false, terminal: false, allow_endorse: false, modes_allowed: Object.freeze(["manual", "plan"]), admin: true });
76
86
  export const loadSettings = () => ({ ...DEFAULT_SETTINGS, ...(readJson("settings.json") ?? {}) });
77
87
  export const saveSettings = (settings) => writeJson("settings.json", { ...DEFAULT_SETTINGS, ...settings });
@@ -0,0 +1,202 @@
1
+ /**
2
+ * THE SESSION READERS: where each AI app keeps its sessions on this computer, and how a session file is read (CLI 0.11.10,
3
+ * split from log-session.mjs unchanged, so the hook and `npx worktrust look` find and read sessions by ONE set of rules).
4
+ *
5
+ * Two halves. READING: a transcript read in 8 MB chunks, line by line, never whole; a read that fails is counted
6
+ * (READ_FAILURES), never silent; a resumed read checks the file is still the one it read (edgesOf). FINDING: every session
7
+ * of every AI app the readers know (Claude Code transcripts, Codex rollouts, Antigravity conversations and the database
8
+ * clients of session-databases.mjs), an excluded project skipped before a file is opened.
9
+ *
10
+ * The per-app parsing stays in transcript-readers.mjs and session-databases.mjs; this module takes their functions as
11
+ * arguments (transcriptLines, sessionFinders), so a copy without one of them still reads Claude Code, as before. Nothing
12
+ * here writes a file or opens a connection: it reads, counts and yields.
13
+ */
14
+ import { closeSync, existsSync, fstatSync, openSync, readdirSync, readSync, statSync } from "node:fs";
15
+ import { createHash } from "node:crypto";
16
+ import { homedir } from "node:os";
17
+ import { join } from "node:path";
18
+
19
+ // ── reading a session file ──
20
+ /**
21
+ * A FILE'S LINES, READ IN CHUNKS (0.10.32). A whole-file `readFileSync(file, "utf8")` throws past the longest string Node
22
+ * makes (about 512 MB), and that throw was read as "this file cannot be read": the owner's VS Code session passed it on
23
+ * 2026-10-18 (797 MB by 10-28) and from then on measured no day at all, live or re-measured. Read 8 MB at a time, one
24
+ * line at a time; re-iterable (each pass opens the file again); null only when the file cannot be opened.
25
+ */
26
+ const CHUNK_BYTES = 8 << 20;
27
+ /**
28
+ * A READ THAT FAILS IS COUNTED, NEVER SILENT (0.10.32): a transcript that exists and cannot be opened or read to its end
29
+ * is one failure. The run keeps the count in sessions.json (`npx worktrust status` says it) and tells WorkTrust the
30
+ * count alone, never which file or what was in it (reportUnreadable).
31
+ */
32
+ const READ_FAILURES = { n: 0 };
33
+ /** The bytes this run read from transcripts (the resume's own measure, below): said on stderr under WORKTRUST_HOOK_DEBUG, never sent. */
34
+ const READ_BYTES = { n: 0 };
35
+ /**
36
+ * What a resume trusts of the bytes it does not read again: eight 4 KB samples before the offset, the first and the last of
37
+ * them at its edges and six spread evenly between, hashed with the offset (32 KB read, whatever the file's length).
38
+ */
39
+ const EDGE_BYTES = 4096, EDGE_SAMPLES = 8;
40
+ const edgesOf = (fd, end) => {
41
+ const hash = createHash("sha256").update(`worktrust-read-position|${end}|`), buffer = Buffer.allocUnsafe(EDGE_BYTES);
42
+ const starts = end <= EDGE_BYTES ? [0] : [...new Set(Array.from({ length: EDGE_SAMPLES }, (_, k) => Math.floor((k * (end - EDGE_BYTES)) / (EDGE_SAMPLES - 1))))];
43
+ for (const from of starts) {
44
+ const want = Math.min(EDGE_BYTES, end - from);
45
+ let got = 0;
46
+ while (got < want) { const n = readSync(fd, buffer, got, want - got, from + got); if (n <= 0) break; got += n; }
47
+ READ_BYTES.n += got;
48
+ hash.update(buffer.subarray(0, got));
49
+ }
50
+ return hash.digest("base64url").slice(0, 22);
51
+ };
52
+ /**
53
+ * The lines from byte `from` (a line boundary), split on the newline BYTE, which no UTF-8 sequence holds, and decoded line by
54
+ * line. `at`, when given, says where each yielded line starts (`at.line`) and, read through the same descriptor the lines came
55
+ * from: the file's identity (`at.dev`, `at.ino`), the offset after its last newline (`at.end`, set before an unterminated last
56
+ * line is yielded) and the hash of its edges before that offset (`at.hash`). `at.failed` is a read that failed (counted, as
57
+ * always); `at.moved` a file that is not the one `expect` names (another identity, shorter than its offset, other bytes at its
58
+ * edges): nothing is yielded and nothing counted, and the caller reads it whole.
59
+ */
60
+ function* chunkedLines(file, from = 0, at = null, expect = null) {
61
+ let fd;
62
+ try { fd = openSync(file, "r"); } catch { READ_FAILURES.n += 1; if (at) at.failed = true; return; }
63
+ try {
64
+ if (at || expect) {
65
+ let stat; try { stat = fstatSync(fd); } catch { READ_FAILURES.n += 1; if (at) at.failed = true; return; }
66
+ if (at) { at.dev = String(stat.dev); at.ino = String(stat.ino); }
67
+ if (expect) {
68
+ let same = false;
69
+ try { same = String(stat.dev) === expect.dev && String(stat.ino) === expect.ino && stat.size >= expect.end && expect.end >= from && (expect.end === 0 ? expect.hash === null : edgesOf(fd, expect.end) === expect.hash); } catch { same = false; }
70
+ if (!same) { if (at) at.moved = true; return; }
71
+ }
72
+ }
73
+ const buffer = Buffer.allocUnsafe(CHUNK_BYTES);
74
+ let pending = [], position = from, lineStart = from;
75
+ for (;;) {
76
+ let n;
77
+ try { n = readSync(fd, buffer, 0, CHUNK_BYTES, position); } catch { READ_FAILURES.n += 1; if (at) at.failed = true; return; }
78
+ if (n <= 0) break;
79
+ READ_BYTES.n += n;
80
+ const chunk = buffer.subarray(0, n);
81
+ let start = 0;
82
+ for (let nl = chunk.indexOf(10); nl !== -1; nl = chunk.indexOf(10, start)) {
83
+ const text = pending.length > 0 ? Buffer.concat([...pending, chunk.subarray(start, nl)]).toString("utf8") : chunk.toString("utf8", start, nl);
84
+ pending = [];
85
+ if (at) at.line = lineStart;
86
+ lineStart = position + nl + 1; start = nl + 1;
87
+ yield text;
88
+ }
89
+ if (start < n) pending.push(Buffer.from(chunk.subarray(start)));
90
+ position += n;
91
+ }
92
+ if (at) { at.end = lineStart; try { at.hash = lineStart > 0 ? edgesOf(fd, lineStart) : null; } catch { READ_FAILURES.n += 1; at.failed = true; } }
93
+ const rest = pending.length > 0 ? Buffer.concat(pending).toString("utf8") : "";
94
+ if (rest) { if (at) at.line = lineStart; yield rest; }
95
+ } finally { closeSync(fd); }
96
+ }
97
+ /** A Claude Code transcript's lines as objects from byte `from`, `at` and `expect` as chunkedLines takes them. */
98
+ function* claudeLinesFrom(file, from, at, expect) { for (const raw of chunkedLines(file, from, at, expect)) { if (!raw.trim()) continue; let line; try { line = JSON.parse(raw); } catch { continue; } yield line; } }
99
+ const fileLines = (file) => {
100
+ try { closeSync(openSync(file, "r")); } catch (error) { if (error?.code !== "ENOENT") READ_FAILURES.n += 1; return null; }
101
+ return { [Symbol.iterator]: () => chunkedLines(file) };
102
+ };
103
+ export { READ_FAILURES, READ_BYTES, chunkedLines, claudeLinesFrom, fileLines };
104
+
105
+ /** The line reader for any client's session, given the per-client readers (transcript-readers.mjs, session-databases.mjs). */
106
+ export function transcriptLines({ DATABASE_SESSION, databaseLines, CODEX_ROLLOUT, codexLines, ANTIGRAVITY_TRANSCRIPT, antigravityIdOf, antigravityLines, antigravityContext }) {
107
+ /** A transcript's lines as objects, whichever client wrote it; null when the file cannot be read. A Claude Code transcript is parsed lazily, as it is read. */
108
+ const parsedLines = (file) => {
109
+ if (DATABASE_SESSION.test(file)) return databaseLines(file);
110
+ const lines = fileLines(file);
111
+ if (!lines) return null;
112
+ if (CODEX_ROLLOUT.test(file)) return [...codexLines(lines)];
113
+ if (ANTIGRAVITY_TRANSCRIPT.test(file)) { const id = antigravityIdOf(file); return [...antigravityLines(lines, { id, ...antigravityContext(id) })]; }
114
+ return { *[Symbol.iterator]() { for (const raw of lines) { if (!raw.trim()) continue; try { yield JSON.parse(raw); } catch { /* a torn line */ } } } };
115
+ };
116
+ return parsedLines;
117
+ }
118
+
119
+ // ── finding each AI app's sessions ──
120
+ /**
121
+ * The finders, given the hook's arguments (`value`: a test names its own roots), its project modes (`excluded`) and the
122
+ * per-client readers. Returns the roots and the walks the hook and `look` share.
123
+ */
124
+ export function sessionFinders({ value, excluded, DATABASE_CLIENTS, codexRolloutFiles, codexCwd, codexIdOf, antigravityRoots, antigravityTranscripts, antigravityContext, databaseSessions }) {
125
+ /** The roots this machine's transcripts live under; a test names its own. */
126
+ const claudeRoot = () => value("transcript-root") ?? join(homedir(), ".claude", "projects");
127
+ const codexRoot = () => { const given = value("codex-root"); if (given) return given.replace(/^~(?=\/|$)/, homedir()); return value("transcript-root") ? null : join(homedir(), ".codex", "sessions"); };
128
+ /** Every Codex rollout and Antigravity conversation on this machine, an excluded project's threads skipped by their working directory. */
129
+ function* codexRollouts() {
130
+ const root = codexRoot();
131
+ for (const file of root ? codexRolloutFiles(root) : []) {
132
+ const cwd = codexCwd(file);
133
+ if (cwd && excluded(cwd)) continue;
134
+ yield { id: `codex:${codexIdOf(file)}`, file };
135
+ }
136
+ yield* antigravityConversations();
137
+ yield* databaseConversations();
138
+ }
139
+ /** The attended sessions of the clients that keep a database (session-databases.mjs); an excluded folder skipped. */
140
+ function* databaseConversations() {
141
+ const given = Object.fromEntries(DATABASE_CLIENTS.map((client) => [client, value(`${client}-root`)]).filter(([, root]) => root));
142
+ for (const { client, sessionId, file, cwd, writtenAt } of databaseSessions(given, Boolean(value("transcript-root")))) {
143
+ if (!(cwd && excluded(cwd))) yield { id: `${client}:${sessionId}`, file, writtenAt };
144
+ }
145
+ }
146
+ /** Antigravity beside Codex: one transcript per conversation, its folder known only from the Stop hook. */
147
+ function* antigravityConversations() {
148
+ const given = value("antigravity-root");
149
+ for (const { conversationId, file } of antigravityTranscripts(given || !value("transcript-root") ? antigravityRoots(given) : [])) {
150
+ const { cwd } = antigravityContext(conversationId);
151
+ if (!(cwd && excluded(cwd))) yield { id: `antigravity:${conversationId}`, file };
152
+ }
153
+ }
154
+
155
+ /** Every transcript this machine holds, excluded projects skipped before a file is opened. */
156
+ function* allTranscripts() {
157
+ const root = claudeRoot();
158
+ if (existsSync(root)) for (const dir of readdirSync(root)) {
159
+ if (excluded(dir)) continue;
160
+ let files;
161
+ try { files = readdirSync(join(root, dir)); } catch { continue; }
162
+ for (const file of files) if (file.endsWith(".jsonl")) yield { id: file.replace(/\.jsonl$/, ""), file: join(root, dir, file) };
163
+ }
164
+ yield* codexRollouts();
165
+ }
166
+
167
+ /**
168
+ * EVERY TRANSCRIPT, with what it was last written. The two filters that used to live here decided
169
+ * the wrong thing at the wrong level:
170
+ *
171
+ * - "idle 30 minutes" skipped the file being typed into, and with it every earlier day of a
172
+ * session that has been open for a fortnight. Whether a DAY is finished is a fact about the day.
173
+ * - "not older than 48 hours" skipped the machine that was closed for four months, which is
174
+ * exactly the person whose work needs collecting when they come back.
175
+ *
176
+ * The caller opens a file only when it has been written since the watermark says we last read it,
177
+ * so a sweep over a hundred transcripts costs a hundred `stat` calls and nothing more.
178
+ */
179
+ function* candidates() {
180
+ for (const rollout of codexRollouts()) {
181
+ if (rollout.writtenAt) { yield rollout; continue; } // a database session knows its own last moment
182
+ let stat; try { stat = statSync(rollout.file); } catch { continue; }
183
+ yield { ...rollout, writtenAt: stat.mtimeMs };
184
+ }
185
+ const root = claudeRoot();
186
+ if (!existsSync(root)) return;
187
+ for (const dir of readdirSync(root)) {
188
+ if (excluded(dir)) continue;
189
+ const path = join(root, dir);
190
+ let files;
191
+ try { files = readdirSync(path); } catch { continue; }
192
+ for (const file of files) {
193
+ if (!file.endsWith(".jsonl")) continue;
194
+ const full = join(path, file);
195
+ let stat;
196
+ try { stat = statSync(full); } catch { continue; }
197
+ yield { id: file.replace(/\.jsonl$/, ""), file: full, writtenAt: stat.mtimeMs };
198
+ }
199
+ }
200
+ }
201
+ return { claudeRoot, codexRoot, codexRollouts, databaseConversations, antigravityConversations, allTranscripts, candidates };
202
+ }