worktrust 0.10.35 → 0.10.36

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -1,5 +1,24 @@
1
1
  # worktrust
2
2
 
3
+ ## 0.10.36: large and cut-off ChatGPT exports; hours only with `mcp off`; a re-measure reported whole or not at all
4
+
5
+ `npx worktrust history --export` now reads a ChatGPT export of any size: a zip64 archive (an export over 4 GB), and a
6
+ download that stopped part way, which is read up to the last whole `conversations-NNN.json` part and said as such ("The
7
+ archive was cut off after conversations-NNN.json; this is not the whole export"), so you decide whether to send what was
8
+ read before the cut. ChatGPT's loose `conversations-NNN.json` parts, a folder of them or one part beside its siblings, are
9
+ read as one export in part order; a missing part is refused by its name. An empty element in an export is counted and
10
+ left out instead of refusing the whole export. What is sent from an export is unchanged: hours and tokens per day, never
11
+ text. (The reader can also count an export's file kinds, searches and model switches between model families, but nothing
12
+ asks for them and nothing of them is sent.)
13
+
14
+ `npx worktrust mcp off` keeps the hours and takes the WorkTrust door out of every AI app here; `mcp on` puts it back (see
15
+ "Hours only, or also work lines" below). A choice made for this computer in Sources › Devices is done by the computer
16
+ at its next session. `update` no longer takes Codex's door out on every second run at the same version.
17
+
18
+ A re-measure says "Re-measured" only when WorkTrust holds every batch of the run; otherwise it says how many it holds and
19
+ gives WorkTrust's own reason for a refused batch, and the session hook exits with an error. What is measured is
20
+ unchanged, so the measure rules stay 3 and no re-measure is offered.
21
+
3
22
  ## 0.10.35: Gemini CLI read; every earlier line can name its AI app
4
23
 
5
24
  Gemini CLI's sessions are read in place, as Copilot's are: the files Gemini CLI records itself under
@@ -287,9 +306,23 @@ npx worktrust@latest history --from-folder <dir> your own copy of an AI app's
287
306
  npx worktrust codex let Codex wake the session hook (asks first)
288
307
  npx worktrust antigravity let Antigravity wake the session hook (asks first)
289
308
  npx worktrust@latest status what is coupled here
309
+ npx worktrust mcp off hours only: the WorkTrust door out of every AI app here, so nothing of WorkTrust loads into
310
+ your sessions; the session hook keeps measuring your hours, and update leaves the door out
311
+ npx worktrust mcp on the door back in: your AI may also log finished work (about 40 tokens per session); nothing
312
+ from the time it was off is sent
313
+ npx worktrust mcp which of the two this computer is in (and whether a claude.ai WorkTrust connector also loads)
290
314
  npx worktrust@latest disconnect take it out again (shows the plan, asks first)
291
315
  ```
292
316
 
317
+ **Hours only, or also work lines.** Your passport's hours come from the session hook, which reads your AI apps' own
318
+ session files; it needs no WorkTrust door in the apps. The door adds one thing: your AI's own `log_work` line at the end
319
+ of a piece of work, and for that its short instruction (and, in apps that load every tool up front, its tool
320
+ definitions) is loaded into every session. `connect` asks which you want (Enter keeps the door, as before); an update
321
+ asks once on a computer coupled before. The choice lives in `~/.worktrust/door.json` (0600). The hook tells WorkTrust
322
+ the mode beside the CLI version, one word, so Sources › Devices can show "work lines off" instead of an unexplained gap.
323
+ If Claude Code has also been connected to a WorkTrust connector of your claude.ai account, the CLI says so once: keep
324
+ the local door (it carries this computer's key) and remove the other at claude.ai/customize/connectors.
325
+
293
326
  ## Keep your history
294
327
 
295
328
  **Why.** Your AI apps decide how long your history lives, and several delete it on their own schedule:
package/chat-exports.mjs CHANGED
@@ -49,7 +49,7 @@ const expand = (path) => String(path).replace(/^~(?=\/|$)/, homedir());
49
49
  // held whole (readExport) stops at 512 MB of kept fields. A zip64 archive (one over 4 GB) is refused by name: unpack it
50
50
  // and give conversations.json itself. No limit override.
51
51
  export const EXPORT_LIMITS = Object.freeze({ fileBytes: 64 * 1024 ** 3, directoryBytes: 8 * 1024 ** 2, depth: 64, conversations: 2_000_000,
52
- conversationBytes: 8 * 1024 ** 2, conversationTextBytes: 64 * 1024 ** 2, keptBytes: 512 * 1024 ** 2, keyBytes: 256, parts: 64, manifestBytes: 1024 ** 2 });
52
+ conversationBytes: 8 * 1024 ** 2, conversationTextBytes: 64 * 1024 ** 2, keptBytes: 512 * 1024 ** 2, keyBytes: 256, parts: 64, manifestBytes: 1024 ** 2, zipEntries: 1_000_000 });
53
53
  const PROGRESS_BYTES = 64 * 1024 ** 2, CHUNK_BYTES = 1024 ** 2;
54
54
  const limit = (condition, label) => { if (!condition) throw Error(`export limit exceeded: ${label}`); };
55
55
  const damaged = (condition) => { if (!condition) throw Error("a damaged zip archive"); };
@@ -96,11 +96,12 @@ async function* inflated(chunks, uncompressed) {
96
96
  }
97
97
 
98
98
  /**
99
- * A ZIP, READ FOR ITS CONVERSATIONS ENTRIES. No dependency: the end-of-central-directory record is found from the back, the
100
- * central directory walked for the names `accept` takes, and only those entries' bytes read (stored or deflated, as a
101
- * stream; anything else, and a zip64 archive, is refused by name), in part order. Nothing else in the archive is touched.
102
- * Two entries of one name are ambiguous and refused. The descriptor stays open until `close`, so the bytes read are the
103
- * bytes the directory described.
99
+ * A ZIP, READ FOR ITS CONVERSATIONS ENTRIES. No dependency: the end-of-central-directory record is found from the back (and,
100
+ * for an archive past 4 GB, the zip64 record its locator names), the central directory walked for the names `accept` takes,
101
+ * and only those entries' bytes read (stored or deflated, as a stream; anything else is refused by name), in part order.
102
+ * Nothing else in the archive is touched. Two entries of one name, or a numbered part missing from the run, are refused. The
103
+ * descriptor stays open until `close`, so the bytes read are the bytes the directory described. An archive with no end
104
+ * record that begins with an entry is a download CUT OFF (2026-10-31): its local headers are walked instead (`walkLocal`).
104
105
  */
105
106
  function zipEntries(path, accept) {
106
107
  const { size, readAt, chunksOf, close } = openExport(path, EXPORT_LIMITS.fileBytes);
@@ -109,47 +110,146 @@ function zipEntries(path, accept) {
109
110
  const tail = readAt(size - tailLength, tailLength);
110
111
  let eocd = -1;
111
112
  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; }
112
- if (eocd < 0) throw Error(`not a zip archive: ${path}`);
113
- const entries = tail.readUInt16LE(eocd + 10), directorySize = tail.readUInt32LE(eocd + 12), directoryAt = tail.readUInt32LE(eocd + 16);
114
- if (entries === 0xffff || directorySize === 0xffffffff || directoryAt === 0xffffffff) throw Error(`a zip64 archive is not read: ${path} (unpack it and give its ${FILE})`);
115
- if (tail.readUInt16LE(eocd + 4) !== 0 || tail.readUInt16LE(eocd + 6) !== 0) throw Error("unsupported zip: multiple disks");
116
- damaged(tail.readUInt16LE(eocd + 8) === entries);
113
+ if (eocd < 0) {
114
+ if (size < 30 || readAt(0, 4).readUInt32LE(0) !== LOCAL) throw Error(`not a zip archive: ${path}`);
115
+ const { selected, cut } = walkLocal(path, size, readAt, accept);
116
+ return { parts: entryParts(path, selected, size, readAt, chunksOf, true), close, cut };
117
+ }
118
+ const endAt = size - tailLength + eocd;
119
+ let entries = tail.readUInt16LE(eocd + 10), directorySize = tail.readUInt32LE(eocd + 12), directoryAt = tail.readUInt32LE(eocd + 16), directoryEnd = endAt;
120
+ if (entries === 0xffff || directorySize === U32 || directoryAt === U32) {
121
+ // ZIP64 (an archive past 4 GB or 65,535 entries): the locator lies just before the end record and names the zip64 end record, which holds the true counts.
122
+ damaged(endAt >= 20);
123
+ const locator = readAt(endAt - 20, 20);
124
+ damaged(locator.readUInt32LE(0) === 0x07064b50);
125
+ if (locator.readUInt32LE(4) !== 0 || locator.readUInt32LE(16) !== 1) throw Error("unsupported zip: multiple disks");
126
+ const recordAt = big(locator, 8), record = readAt(recordAt, 56, endAt - 20);
127
+ damaged(record.readUInt32LE(0) === 0x06064b50 && recordAt + 12 + big(record, 4) === endAt - 20);
128
+ if (record.readUInt32LE(16) !== 0 || record.readUInt32LE(20) !== 0) throw Error("unsupported zip: multiple disks");
129
+ entries = big(record, 32); damaged(big(record, 24) === entries);
130
+ directorySize = big(record, 40); directoryAt = big(record, 48); directoryEnd = recordAt;
131
+ } else {
132
+ if (tail.readUInt16LE(eocd + 4) !== 0 || tail.readUInt16LE(eocd + 6) !== 0) throw Error("unsupported zip: multiple disks");
133
+ damaged(tail.readUInt16LE(eocd + 8) === entries);
134
+ }
117
135
  limit(directorySize <= EXPORT_LIMITS.directoryBytes, "zip directory bytes");
118
- damaged(directoryAt + directorySize === size - tailLength + eocd);
136
+ damaged(directoryAt + directorySize === directoryEnd);
119
137
  const directory = readAt(directoryAt, directorySize);
120
138
  let at = 0;
121
139
  const selected = new Map();
122
140
  for (let index = 0; index < entries; index += 1) {
123
141
  damaged(at + 46 <= directory.length && directory.readUInt32LE(at) === 0x02014b50);
124
- const method = directory.readUInt16LE(at + 10), compressed = directory.readUInt32LE(at + 20), uncompressed = directory.readUInt32LE(at + 24);
125
- const nameLength = directory.readUInt16LE(at + 28), extraLength = directory.readUInt16LE(at + 30), commentLength = directory.readUInt16LE(at + 32), localAt = directory.readUInt32LE(at + 42);
142
+ const method = directory.readUInt16LE(at + 10);
143
+ let compressed = directory.readUInt32LE(at + 20), uncompressed = directory.readUInt32LE(at + 24), localAt = directory.readUInt32LE(at + 42);
144
+ const nameLength = directory.readUInt16LE(at + 28), extraLength = directory.readUInt16LE(at + 30), commentLength = directory.readUInt16LE(at + 32);
126
145
  const flags = directory.readUInt16LE(at + 8), disk = directory.readUInt16LE(at + 34);
127
146
  damaged(at + 46 + nameLength + extraLength + commentLength <= directory.length);
128
- const name = directory.toString("utf8", at + 46, at + 46 + nameLength);
147
+ const name = directory.toString("utf8", at + 46, at + 46 + nameLength), extra = directory.subarray(at + 46 + nameLength, at + 46 + nameLength + extraLength);
129
148
  at += 46 + nameLength + extraLength + commentLength;
130
149
  if (!accept(basename(name)) || name.endsWith("/")) continue;
131
- if (compressed === 0xffffffff || uncompressed === 0xffffffff || localAt === 0xffffffff) throw Error(`a zip64 entry is not read: ${path} (unpack it and give its ${FILE})`);
150
+ if (compressed === U32 || uncompressed === U32 || localAt === U32) [uncompressed, compressed, localAt] = zip64Extra(extra, [uncompressed, compressed, localAt]);
132
151
  if ((flags & (1 | 64)) !== 0 || disk !== 0) throw Error("unsupported zip: encrypted or multi-disk entry");
133
152
  damaged(!selected.has(basename(name)));
134
153
  selected.set(basename(name), { name, method, flags, compressed, uncompressed, localAt });
135
154
  }
136
155
  damaged(at === directory.length);
137
- limit(selected.size <= EXPORT_LIMITS.parts, "conversations parts");
138
- const parts = [...selected.keys()].sort(byPart).map((key) => {
139
- const { name, method, flags, compressed, uncompressed, localAt } = selected.get(key);
140
- const local = readAt(localAt, 30, directoryAt);
141
- damaged(local.readUInt32LE(0) === 0x04034b50 && local.readUInt16LE(8) === method && local.readUInt16LE(6) === flags);
142
- const nameLength = local.readUInt16LE(26), dataAt = localAt + 30 + nameLength + local.readUInt16LE(28);
143
- damaged(readAt(localAt + 30, nameLength, directoryAt).toString("utf8") === name);
144
- if (!(flags & 8)) damaged(local.readUInt32LE(18) === compressed && local.readUInt32LE(22) === uncompressed);
145
- damaged(dataAt + compressed <= directoryAt);
146
- if (method === 0) damaged(compressed === uncompressed);
147
- else if (method !== 8) throw Error(`${basename(name)} in ${path} is compressed in a way this reader does not open (method ${method})`);
148
- return { path, bytes: uncompressed, chunks: () => (method === 0 ? chunksOf(dataAt, compressed, directoryAt) : inflated(chunksOf(dataAt, compressed, directoryAt), uncompressed)) };
149
- });
150
- return { parts, close };
156
+ return { parts: entryParts(path, selected, directoryAt, readAt, chunksOf, false), close, cut: null };
151
157
  } catch (error) { close(); throw error; }
152
158
  }
159
+ const LOCAL = 0x04034b50, U32 = 0xffffffff;
160
+ /** An eight-byte length or offset, held to what a number can say exactly. */
161
+ const big = (buffer, at) => { const value = buffer.readBigUInt64LE(at); damaged(value <= BigInt(Number.MAX_SAFE_INTEGER)); return Number(value); };
162
+ /** The zip64 extended-information field (id 0x0001): an eight-byte value for each of `words` that reads 0xffffffff, in the spec's order; the others as they are. */
163
+ function zip64Extra(extra, words) {
164
+ for (let at = 0; at + 4 <= extra.length; at += 4 + extra.readUInt16LE(at + 2)) {
165
+ const end = at + 4 + extra.readUInt16LE(at + 2);
166
+ damaged(end <= extra.length);
167
+ if (extra.readUInt16LE(at) !== 1) continue;
168
+ let next = at + 4;
169
+ return words.map((word) => { if (word !== U32) return word; damaged(next + 8 <= end); const value = big(extra, next); next += 8; return value; });
170
+ }
171
+ return damaged(false);
172
+ }
173
+ /** The selected entries as parts in part order, each held to its local header (method, flags, name and lengths) and its bytes before `end`. */
174
+ function entryParts(path, selected, end, readAt, chunksOf, walked) {
175
+ limit(selected.size <= EXPORT_LIMITS.parts, "conversations parts");
176
+ contiguous([...selected.keys()], path);
177
+ return [...selected.keys()].sort(byPart).map((key) => {
178
+ const { name, method, flags, compressed, uncompressed, localAt } = selected.get(key);
179
+ const local = readAt(localAt, 30, end);
180
+ damaged(local.readUInt32LE(0) === LOCAL && local.readUInt16LE(8) === method && local.readUInt16LE(6) === flags);
181
+ const nameLength = local.readUInt16LE(26), extraLength = local.readUInt16LE(28), dataAt = localAt + 30 + nameLength + extraLength;
182
+ damaged(readAt(localAt + 30, nameLength, end).toString("utf8") === name);
183
+ if (!walked && !(flags & 8)) {
184
+ let sizes = [local.readUInt32LE(22), local.readUInt32LE(18)];
185
+ if (sizes.includes(U32)) sizes = zip64Extra(readAt(localAt + 30 + nameLength, extraLength, end), [U32, U32]);
186
+ damaged(sizes[1] === compressed && sizes[0] === uncompressed);
187
+ }
188
+ damaged(dataAt + compressed <= end);
189
+ if (method === 0) damaged(compressed === uncompressed);
190
+ else if (method !== 8) throw Error(`${basename(name)} in ${path} is compressed in a way this reader does not open (method ${method})`);
191
+ return { path, bytes: uncompressed, chunks: () => (method === 0 ? chunksOf(dataAt, compressed, end) : inflated(chunksOf(dataAt, compressed, end), uncompressed)) };
192
+ });
193
+ }
194
+ /**
195
+ * A ZIP CUT OFF (2026-10-31: the owner's 4 GB ChatGPT export, downloaded, stopped inside an attachment; it has no central
196
+ * directory and no end record). Its LOCAL headers are walked from the front, each passed by the lengths it carries, its data
197
+ * never read: only an entry `accept` takes is kept, and only one whose header carries its real lengths (an entry that defers
198
+ * them to a data descriptor cannot be passed without inflating it, so the walk stops there and says so). The walk ends at the
199
+ * first entry the file does not hold whole, or at the directory if the cut came later. A cut inside a conversations entry
200
+ * refuses the export by that entry's name; otherwise what was read is handed over WITH the cut (`cut`), never as the whole.
201
+ */
202
+ function walkLocal(path, size, readAt, accept) {
203
+ const selected = new Map();
204
+ let at = 0, walked = 0, where = null;
205
+ for (;;) {
206
+ if (at === size) { where = "at the end of an entry"; break; }
207
+ if (at + 30 > size) { where = "inside an entry's header"; break; }
208
+ const local = readAt(at, 30), signature = local.readUInt32LE(0);
209
+ if (signature === 0x02014b50 || signature === 0x06064b50) { where = "inside its directory"; break; }
210
+ damaged(signature === LOCAL);
211
+ limit((walked += 1) <= EXPORT_LIMITS.zipEntries, "zip entries");
212
+ const flags = local.readUInt16LE(6), method = local.readUInt16LE(8), nameLength = local.readUInt16LE(26), extraLength = local.readUInt16LE(28);
213
+ if (at + 30 + nameLength + extraLength > size) { where = "inside an entry's header"; break; }
214
+ const name = readAt(at + 30, nameLength).toString("utf8"), extra = readAt(at + 30 + nameLength, extraLength);
215
+ let compressed = local.readUInt32LE(18), uncompressed = local.readUInt32LE(22);
216
+ const wide = compressed === U32 || uncompressed === U32;
217
+ if (wide) [uncompressed, compressed] = zip64Extra(extra, [U32, U32]);
218
+ const wanted = accept(basename(name)) && !name.endsWith("/"), dataAt = at + 30 + nameLength + extraLength;
219
+ if ((flags & 8) && compressed === 0 && uncompressed === 0) {
220
+ if (wanted) throw Error(`${basename(name)} in ${path} carries no length in its header and the archive has no directory: it cannot be read without one`);
221
+ where = "at an entry whose header carries no length"; break;
222
+ }
223
+ if (dataAt + compressed > size) {
224
+ if (wanted) throw Error(`${path} is cut off inside ${basename(name)} (the file ends at byte ${size}; the entry needs ${dataAt + compressed}): download the export again`);
225
+ where = "inside an entry that is not a conversations part"; break;
226
+ }
227
+ if (wanted) {
228
+ if ((flags & (1 | 64)) !== 0) throw Error("unsupported zip: encrypted or multi-disk entry");
229
+ damaged(!selected.has(basename(name)));
230
+ selected.set(basename(name), { name, method, flags, compressed, uncompressed, localAt: at });
231
+ }
232
+ at = dataAt + compressed;
233
+ if (flags & 8) { // the data descriptor after the data: an optional signature, the crc and two lengths (eight bytes each in zip64)
234
+ const length = (at + 4 <= size && readAt(at, 4).readUInt32LE(0) === 0x08074b50 ? 4 : 0) + 4 + (wide ? 16 : 8);
235
+ if (at + length > size) { where = "at the end of an entry"; break; }
236
+ at += length;
237
+ }
238
+ }
239
+ if (selected.size === 0) throw Error(`${path} is cut off (no directory at its end) and holds no whole conversations part before the cut: download the export again`);
240
+ const names = [...selected.keys()].sort(byPart);
241
+ return { selected, cut: { size, at, where, entries: walked, parts: names.length, first: names[0], last: names.at(-1) } };
242
+ }
243
+ /** Numbered parts run without a gap: a part missing from the middle of the run is a partial export, never read as the whole. */
244
+ function contiguous(names, where, fromZero = false) {
245
+ const numbers = names.map(partOf).filter((n) => n >= 0).sort((a, b) => a - b), missing = [];
246
+ if (fromZero) for (let n = 0; n < (numbers[0] ?? 0) && missing.length < 8; n += 1) missing.push(`conversations-${String(n).padStart(3, "0")}`);
247
+ for (let i = 1; i < numbers.length; i += 1) {
248
+ damaged(numbers[i] !== numbers[i - 1]);
249
+ for (let n = numbers[i - 1] + 1; n < numbers[i] && missing.length < 8; n += 1) missing.push(`conversations-${String(n).padStart(3, "0")}`);
250
+ }
251
+ if (missing.length > 0) throw Error(`${where} is missing conversations part${missing.length === 1 ? "" : "s"} ${missing.join(", ")}: a partial export is never read as the whole`);
252
+ }
153
253
 
154
254
  /**
155
255
  * THE CONVERSATIONS, AND ONLY THEM (owner, 2026-10-17). Inside a zip: `conversations.json`, or a part-numbered
@@ -166,9 +266,9 @@ const refuseOther = (path) => { const other = OTHER_PART.exec(basename(path)); i
166
266
  /** One conversations zip: its conversations entries, or a refusal that names the zip. */
167
267
  function zipParts(path, given) {
168
268
  refuseOther(path);
169
- const { parts, close } = zipEntries(path, (name) => CONVERSATIONS_ENTRY.test(name));
269
+ const { parts, close, cut } = zipEntries(path, (name) => CONVERSATIONS_ENTRY.test(name));
170
270
  if (parts.length === 0) { close(); throw Error(`no ${FILE} in ${given}`); }
171
- return { parts, close };
271
+ return { parts, close, cuts: cut ? [cut] : [] };
172
272
  }
173
273
  /** A folder's conversations zips (conversations-000.zip, -001.zip …), in part order; nothing else of the folder is read. */
174
274
  const folderParts = (dir) => { let names = []; try { names = readdirSync(dir); } catch { return []; } return names.filter((name) => CONVERSATIONS_PART.test(name)).sort(byPart).map((name) => join(dir, name)); };
@@ -200,9 +300,29 @@ function zipsParts(zips, given) {
200
300
  for (const zip of zips) opened.push(zipParts(zip, given));
201
301
  const parts = opened.flatMap((one) => one.parts);
202
302
  limit(parts.length <= EXPORT_LIMITS.parts && parts.reduce((sum, part) => sum + part.bytes, 0) <= EXPORT_LIMITS.fileBytes, "conversations parts");
203
- return { parts, close: () => { for (const one of opened) one.close(); } };
303
+ return { parts, close: () => { for (const one of opened) one.close(); }, cuts: opened.flatMap((one) => one.cuts) };
204
304
  } catch (error) { for (const one of opened) one.close(); throw error; }
205
305
  }
306
+ /**
307
+ * CHATGPT'S OWN SPLIT, UNPACKED (2026-10-31): conversations-000.json … -050.json loose in a folder. The folder, or any one of
308
+ * its parts given, is ONE export: every sibling part, in part order, the digest of their bytes in that order (as the same
309
+ * parts inside a zip). The run starts at 000 and has no gap, or the export is refused by the missing part's name; a folder
310
+ * holding loose parts AND conversations zips is ambiguous and refused. Nothing else of the folder is opened.
311
+ */
312
+ const LOOSE_PART = /^conversations[-_](\d{1,6})\.json$/i;
313
+ const looseOf = (dir) => { let names = []; try { names = readdirSync(dir); } catch { return []; } return names.filter((name) => LOOSE_PART.test(name)).sort(byPart); };
314
+ function looseParts(dir, given) {
315
+ if (folderParts(dir).length > 0) throw Error(`${given} holds both loose conversations parts and conversations zips: give the one or the other`);
316
+ const names = looseOf(dir);
317
+ limit(names.length <= EXPORT_LIMITS.parts, "conversations parts");
318
+ contiguous(names, dir, true);
319
+ const opened = [];
320
+ try {
321
+ for (const name of names) { const path = join(dir, name); opened.push({ path, file: openExport(path, EXPORT_LIMITS.fileBytes) }); }
322
+ limit(opened.reduce((sum, one) => sum + one.file.size, 0) <= EXPORT_LIMITS.fileBytes, "conversations parts");
323
+ return { parts: opened.map(({ path, file }) => ({ path, bytes: file.size, chunks: () => file.chunksOf(0, file.size, file.size) })), close: () => { for (const one of opened) one.file.close(); }, cuts: [] };
324
+ } catch (error) { for (const one of opened) one.file.close(); throw error; }
325
+ }
206
326
 
207
327
  /** Every conversations part, wherever the given path keeps them (a folder, the file itself, a zip, a part, or the manifest), each a source of chunks. */
208
328
  function exportParts(given) {
@@ -210,6 +330,7 @@ function exportParts(given) {
210
330
  let stat; try { stat = statSync(path); } catch { throw Error(`export not found: ${given}`); }
211
331
  if (stat.isDirectory()) {
212
332
  if (existsSync(join(path, FILE))) path = join(path, FILE);
333
+ else if (looseOf(path).length > 0) return looseParts(path, given);
213
334
  else {
214
335
  const zips = folderParts(path);
215
336
  if (zips.length === 0) throw Error(`no ${FILE} in ${given}`);
@@ -217,6 +338,7 @@ function exportParts(given) {
217
338
  }
218
339
  }
219
340
  if (/\.zip$/i.test(path)) return zipParts(path, given);
341
+ if (LOOSE_PART.test(basename(path)) && stat.isFile()) return looseParts(dirname(path), given); // one loose part given: the export is it and its siblings
220
342
  const file = openExport(path, EXPORT_LIMITS.fileBytes);
221
343
  let manifest;
222
344
  try {
@@ -234,9 +356,103 @@ const NONSCALAR = Object.freeze({});
234
356
  /** An element whose kept fields outgrew their budget: handed over as this, counted, never built. */
235
357
  const OVERSIZED = Symbol("oversized");
236
358
  const S = "scalar", T = "text"; // a scalar kept as it is; a text kept as a string for the counter, as its byte length for the hook
359
+ const P = "presence"; // a string that is never kept: only that it was there (`true`); any other value as a scalar would be
360
+ /** The leaf a plan gives a string: the plan itself, or the `leaf` of a plan that also keeps an object's keys (a list of strings and objects). A function maps the string as it ends, and only what it returns is kept. */
361
+ const leafOf = (plan) => (plan !== null && typeof plan === "object" ? plan.leaf ?? null : plan);
237
362
  const NODE = { keys: { parent: S, message: { keys: { author: { keys: { role: S } }, create_time: S, content: { keys: { parts: { items: T } } }, metadata: { keys: { model_slug: S, is_visually_hidden_from_conversation: S } } } } } };
238
363
  const CONVERSATION = { keys: { title: S, name: S, conversation_id: S, id: S, uuid: S, create_time: S, created_at: S, current_node: S, mapping: { any: NODE },
239
364
  chat_messages: { items: { keys: { sender: S, created_at: S, text: T, content: { items: { keys: { type: S, text: T } } } } } } } };
365
+ /**
366
+ * AN EXPORT'S METADATA, COUNTS ONLY (owner, 2026-10-31). Asked for (`metadata: true`, the hook's way: never with the text),
367
+ * the walk keeps a few more fields of a ChatGPT message, each MAPPED as it is read to a word of a closed list or to nothing, so
368
+ * the export's own string (a favicon URL, a file's name or type, a quoted reply, a task's title, a GPT's id) is never kept:
369
+ * the person's attachments by category; the answer's searches, source references, reasoning and tool icons (only the fixed
370
+ * names globe, code, thoughts, run-command and api_tool, and an app's icon path, which says an app was used, never which);
371
+ * a deep-research task, a quote reply and voice by their presence. The field names are the ones the owner's own export
372
+ * carries (2026-10-31, read by key name only). conversation_asset_file_names.json, ads.json and chat.html are never opened.
373
+ */
374
+ const ICONS = Object.freeze({ globe: "web_search", code: "code", thoughts: "reasoning", "run-command": "run_command", api_tool: "connected_app" });
375
+ const iconOf = (name) => (Object.hasOwn(ICONS, name) ? ICONS[name] : /^\/(?:[\w-]{1,64}\/){1,8}[\w.-]{1,128}$/.test(name) ? "connected_app" : null); // a URL, a path with "//" or anything else: nothing
376
+ const SOURCE_REFERENCES = new Set(["grouped_webpages", "grouped_webpages_model_predicted_fallback", "webpage", "webpage_extended", "sources_footnote"]);
377
+ const FILE_TYPES = [["pdf", /^application\/pdf$/], ["image", /^image\//], ["audio", /^audio\//], ["video", /^video\//], ["spreadsheet", /^text\/(?:csv|tab-separated-values)$|spreadsheet|excel|\.sheet$|numbers$/], ["presentation", /presentation|powerpoint|keynote/],
378
+ ["document", /msword|wordprocessing|opendocument\.text|rtf|epub|pages$/], ["archive", /zip|tar|gzip|7z|rar|compressed/], ["data", /json|xml|yaml|toml|x-ndjson|sqlite/], ["code", /javascript|typescript|jsx|tsx|python|x-sh|x-sql|x-c|java|ruby|php|golang|x-go|rust|swift|kotlin|css|x-shellscript/], ["text", /^text\//]];
379
+ const fileOf = (mime) => FILE_TYPES.find(([, test]) => test.test(String(mime).toLowerCase().slice(0, 128)))?.[0] ?? "other";
380
+ const META_NODE = { keys: { parent: S, message: { keys: { author: { keys: { role: S } }, create_time: S,
381
+ content: { keys: { content_type: (type) => (type === "thoughts" || type === "reasoning_recap" ? "reasoning" : null), parts: { items: { keys: { content_type: (type) => (/^(?:audio_transcription|audio_asset_pointer|real_time_user_audio_video_asset_pointer)$/.test(type) ? "voice" : null) }, leaf: T } } } },
382
+ metadata: { keys: { model_slug: S, is_visually_hidden_from_conversation: S, attachments: { items: { keys: { mime_type: fileOf, mimeType: fileOf, is_big_paste: S } } }, search_result_groups: { items: P }, content_references: { items: { keys: { type: (type) => SOURCE_REFERENCES.has(type) || null } } },
383
+ tool_icons: { items: iconOf }, async_task_title: P, is_async_task_result_message: S, targeted_reply_label: P, targeted_reply_source_message_id: P, bidi_voice_mode_message: S } } } } } };
384
+ const META_CONVERSATION = { keys: { ...CONVERSATION.keys, mapping: { any: META_NODE }, conversation_template_id: (id) => (/^g-p-/.test(id) ? "project" : /^g-/.test(id) ? "gpt" : null) } };
385
+ /** The closed list (owner, 2026-10-31): what a conversation-day's counts may name, and nothing else. `files` and `depth` count by category. */
386
+ export const EXPORT_METADATA = Object.freeze(["files", "web_search", "sources_cited", "reasoning", "model_switch", "code", "run_command", "connected_app", "custom_gpt_or_project", "deep_research_agent", "voice", "quote_reply", "depth"]);
387
+ /**
388
+ * A MODEL'S FAMILY (owner, 2026-11-03): a switch counts between families, never ChatGPT's own routing inside one. The closed table names
389
+ * the slugs that carry no family in their shape; every other slug is normalised by one documented rule, never guessed: lower case;
390
+ * `gpt-N` or `gpt-No` (omni) is the generation, whatever follows (a point version such as -2 or .6, thinking, auto, instant, mini,
391
+ * a codename); `oN` is that o-series generation; anything else drops its routing suffixes (thinking, auto, instant, mini, t-mini,
392
+ * high, medium, low, pro, mobile, a bare number) and is its own family. A slug that names no model (auto, empty) has none.
393
+ */
394
+ const FAMILY_TABLE = Object.freeze({ "text-davinci-002-render": "gpt-3.5", "text-davinci-002-render-sha": "gpt-3.5", "text-davinci-002-render-sha-mobile": "gpt-3.5", "text-davinci-002-render-paid": "gpt-3.5", auto: null });
395
+ export function modelFamily(slug) {
396
+ const name = String(slug ?? "").trim().toLowerCase().slice(0, 64);
397
+ if (name === "") return null;
398
+ if (Object.hasOwn(FAMILY_TABLE, name)) return FAMILY_TABLE[name];
399
+ const gpt = /^gpt-(\d+)(o)?(?=$|[.-])/.exec(name);
400
+ if (gpt) return `gpt-${gpt[1]}${gpt[2] ?? ""}`;
401
+ const o = /^o(\d+)(?=$|-)/.exec(name);
402
+ if (o) return `o${o[1]}`;
403
+ let family = name, before;
404
+ do { before = family; family = family.replace(/-(?:thinking|auto|instant|t-mini|mini|high|medium|low|pro|mobile|\d+)$/, ""); } while (family !== before);
405
+ return family || null;
406
+ }
407
+ const DEPTH = (bytes) => (bytes < 200 ? "short" : bytes < 1000 ? "medium" : "long"); // PROPOSED bounds (bytes of the person's text as the export writes it), uncalibrated
408
+ const list = (value) => (Array.isArray(value) ? value : []);
409
+ /**
410
+ * One ChatGPT conversation's counts per UTC day, on its kept branch: an EXCHANGE is a person's turn and the answers to it, and
411
+ * each kind is counted once per exchange (a search run twice for one question is one); files, a model switch between answers,
412
+ * the person's prompts by depth and a day inside a custom GPT or a project are counted as they are. Integers, never a string.
413
+ */
414
+ function chatgptMetadata(kept) {
415
+ const days = {}, template = kept.conversation_template_id === "gpt" || kept.conversation_template_id === "project";
416
+ let seen = new Set(), model = null;
417
+ const day = (m) => { const seconds = Number(m?.create_time ?? kept.create_time); return Number.isFinite(seconds) && seconds > 0 ? new Date(seconds * 1000).toISOString().slice(0, 10) : null; };
418
+ const add = (counts, key, sub = null) => { if (sub) { counts[key] ??= {}; counts[key][sub] = (counts[key][sub] ?? 0) + 1; } else counts[key] = (counts[key] ?? 0) + 1; };
419
+ const once = (counts, key) => { if (!seen.has(key)) { seen.add(key); add(counts, key); } };
420
+ for (const node of chatgptBranch(kept)) {
421
+ const m = node?.message, role = m?.author?.role, meta = m?.metadata && typeof m.metadata === "object" ? m.metadata : {}, at = day(m);
422
+ if ((role !== "user" && role !== "assistant") || meta.is_visually_hidden_from_conversation || at === null) continue;
423
+ const counts = (days[at] ??= {});
424
+ if (template) counts.custom_gpt_or_project = 1;
425
+ const parts = list(m.content?.parts);
426
+ if (role === "user") {
427
+ seen = new Set();
428
+ for (const file of list(meta.attachments)) if (file && typeof file === "object" && file !== NONSCALAR && file.is_big_paste !== true) add(counts, "files", file.mime_type ?? file.mimeType ?? "other");
429
+ if (meta.bidi_voice_mode_message === true || parts.some((part) => part?.content_type === "voice")) once(counts, "voice");
430
+ if (meta.targeted_reply_label === true || meta.targeted_reply_source_message_id === true) once(counts, "quote_reply");
431
+ const bytes = parts.reduce((sum, part) => sum + (typeof part === "number" ? part : 0), 0);
432
+ if (bytes > 0) add(counts, "depth", DEPTH(bytes));
433
+ continue;
434
+ }
435
+ const family = typeof meta.model_slug === "string" ? modelFamily(meta.model_slug) : null; // a switch between families, never routing inside one
436
+ if (family !== null) { if (model !== null && family !== model) add(counts, "model_switch"); model = family; }
437
+ const icons = new Set(list(meta.tool_icons).filter((icon) => typeof icon === "string"));
438
+ if (list(meta.search_result_groups).length > 0 || icons.has("web_search")) once(counts, "web_search");
439
+ if (list(meta.content_references).some((reference) => reference?.type === true)) once(counts, "sources_cited");
440
+ if (m.content?.content_type === "reasoning" || icons.has("reasoning")) once(counts, "reasoning");
441
+ for (const kind of ["code", "run_command", "connected_app"]) if (icons.has(kind)) once(counts, kind);
442
+ if (meta.async_task_title === true || meta.is_async_task_result_message === true) once(counts, "deep_research_agent");
443
+ if (meta.bidi_voice_mode_message === true) once(counts, "voice");
444
+ }
445
+ for (const [at, counts] of Object.entries(days)) if (Object.keys(counts).length === 0) delete days[at];
446
+ return days;
447
+ }
448
+ /** Counts added into totals, category by category. */
449
+ function addCounts(totals, counts) {
450
+ for (const [key, value] of Object.entries(counts)) {
451
+ if (typeof value === "number") totals[key] = (totals[key] ?? 0) + value;
452
+ else { totals[key] ??= {}; for (const [sub, n] of Object.entries(value)) totals[key][sub] = (totals[key][sub] ?? 0) + n; }
453
+ }
454
+ return totals;
455
+ }
240
456
  const malformed = () => { throw Object.assign(Error("malformed"), { malformed: true }); };
241
457
  const NUMBER = /^-?(?:0|[1-9]\d*)(?:\.\d+)?(?:[eE][+-]?\d+)?$/;
242
458
  const VALUE = 0, KEY = 1, COLON = 2, AFTER = 3, STRING = 4, TOKEN = 5, DONE = 6;
@@ -272,7 +488,7 @@ function walker(plan, { text, budget, onElement }) {
272
488
  vPlan = kind === "[" ? top().plan?.items ?? null : null; state = kind === "{" ? KEY : VALUE;
273
489
  };
274
490
  const close = (kind) => { const frame = stack.pop(); if (frame.kind !== kind) malformed(); if (frame.root) state = DONE; else store(frame.out ?? NONSCALAR, 0); };
275
- const beginString = (key) => { state = STRING; sKey = key; sKeep = key ? top().out !== null : vPlan === S || (vPlan === T && text); sRaw = sKeep ? [] : null; sLen = 0; sEsc = 0; sEscaped = false; };
491
+ const beginString = (key) => { const leaf = key ? null : leafOf(vPlan); state = STRING; sKey = key; sKeep = key ? top().out !== null : leaf === S || (leaf === T && text) || typeof leaf === "function"; sRaw = sKeep ? [] : null; sLen = 0; sEsc = 0; sEscaped = false; };
276
492
  /** Kept bytes of the string in flight: a key past its bound stops being one; a value past the budget takes the element with it. */
277
493
  const take = (chunk, from, to) => {
278
494
  sLen += to - from;
@@ -290,8 +506,11 @@ function walker(plan, { text, budget, onElement }) {
290
506
  else if (frame.plan?.keys && key !== null && Object.hasOwn(frame.plan.keys, key)) { frame.key = key; vPlan = frame.plan.keys[key]; }
291
507
  else { frame.key = null; vPlan = null; }
292
508
  state = COLON;
293
- } else if (sKeep) store(decode(), 0);
294
- else store(vPlan === T ? sLen : NONSCALAR, 8); // a text the hook never reads: its byte length says whether there was one
509
+ } else {
510
+ const leaf = leafOf(vPlan);
511
+ if (sKeep) store(typeof leaf === "function" ? leaf(decode()) : decode(), 0); // a mapped string: only the mapper's answer is kept
512
+ else store(leaf === T ? sLen : leaf === P ? true : NONSCALAR, 8); // a text the hook never reads: its byte length says whether there was one
513
+ }
295
514
  };
296
515
  const finishToken = () => {
297
516
  let value;
@@ -396,15 +615,20 @@ const transcriptLine = ({ type, timestamp, model, text }) => ({ type, timestamp,
396
615
  * one without an id, marked); `report` receives the path and vendor before the first conversation, the digest, the counts
397
616
  * and the number of parts when the stream ends. Counts only on stderr.
398
617
  */
399
- async function* exportRecords(given, { expect = null, excluded = () => false, skipped = null, text = false, report = null } = {}) {
400
- const { parts, close } = exportParts(given);
618
+ async function* exportRecords(given, { expect = null, excluded = () => false, skipped = null, text = false, report = null, metadata = false } = {}) {
619
+ if (metadata && text) throw Error("an export's metadata is counted without the text, never with it");
620
+ const totals = {};
621
+ const { parts, close, cuts = [] } = exportParts(given);
401
622
  const path = parts[0].path, digest = createHash("sha256");
402
- let vendor = null, count = 0, oversized = 0, bytes = 0, next = PROGRESS_BYTES, offset = 0;
403
- if (report) { report.path = path; report.vendor = expect; report.digest = null; report.conversations = 0; report.oversized = 0; report.parts = parts.length; }
623
+ let vendor = null, count = 0, oversized = 0, empty = 0, bytes = 0, next = PROGRESS_BYTES, offset = 0;
624
+ if (report) { report.path = path; report.vendor = expect; report.digest = null; report.conversations = 0; report.oversized = 0; report.empty = 0; report.parts = parts.length; report.cut = cuts.length > 0 ? cuts : null; }
404
625
  const one = (kept, index) => {
405
626
  limit(count < EXPORT_LIMITS.conversations, "conversation count");
406
627
  count += 1;
407
628
  if (kept === OVERSIZED) { oversized += 1; return { vendor, oversized: true, lines: [] }; }
629
+ // AN EMPTY ELEMENT (2026-10-31: one `{}` in the owner's conversations-043.json refused the whole export): none of the fields read, so
630
+ // it is counted and left out and decides no vendor; an export of nothing else is refused below as no export at all.
631
+ if (kept && typeof kept === "object" && kept.constructor === Object && kept !== NONSCALAR && Object.keys(kept).length === 0) { empty += 1; return { vendor, empty: true, lines: [] }; }
408
632
  const shape = kept && typeof kept === "object" && kept !== NONSCALAR ? (kept.mapping instanceof Map || kept.mapping === NONSCALAR ? "chatgpt" : Array.isArray(kept.chat_messages) ? "claude-web" : "unknown") : "unknown";
409
633
  if (vendor === null) vendor = shape;
410
634
  if (shape === "unknown" || shape !== vendor) throw Error(`${path} is neither a ChatGPT nor a Claude export (or mixes the two)`);
@@ -412,12 +636,14 @@ async function* exportRecords(given, { expect = null, excluded = () => false, sk
412
636
  if (report) report.vendor = vendor;
413
637
  const title = String((vendor === "chatgpt" ? kept.title : kept.name) ?? "");
414
638
  if (excluded(title)) { skipped?.push(title.slice(0, 40)); return { vendor, excluded: true, lines: [] }; }
415
- return { vendor, id: String((vendor === "chatgpt" ? kept.conversation_id ?? kept.id : kept.uuid) ?? `#${index}`), lines: vendor === "chatgpt" ? chatgptLines(kept, text) : claudeLines(kept, text) };
639
+ const record = { vendor, id: String((vendor === "chatgpt" ? kept.conversation_id ?? kept.id : kept.uuid) ?? `#${index}`), lines: vendor === "chatgpt" ? chatgptLines(kept, text) : claudeLines(kept, text) };
640
+ if (metadata) { record.metadata = vendor === "chatgpt" ? chatgptMetadata(kept) : null; for (const counts of Object.values(record.metadata ?? {})) addCounts(totals, counts); } // a Claude export carries no such fields: null, never zeros
641
+ return record;
416
642
  };
417
643
  try {
418
644
  for (const part of parts) {
419
645
  let queue = [], seen = 0;
420
- const walk = walker(CONVERSATION, { text, budget: text ? EXPORT_LIMITS.conversationTextBytes : EXPORT_LIMITS.conversationBytes, onElement: (kept, index) => queue.push([kept, offset + index]) });
646
+ const walk = walker(metadata ? META_CONVERSATION : CONVERSATION, { text, budget: text ? EXPORT_LIMITS.conversationTextBytes : EXPORT_LIMITS.conversationBytes, onElement: (kept, index) => queue.push([kept, offset + index]) });
421
647
  const drain = function* () { const due = queue; queue = []; for (const [kept, index] of due) { seen = index + 1 - offset; yield one(kept, index); } };
422
648
  try {
423
649
  for await (const chunk of part.chunks()) {
@@ -435,19 +661,20 @@ async function* exportRecords(given, { expect = null, excluded = () => false, sk
435
661
  offset += seen;
436
662
  }
437
663
  } finally { close(); }
438
- if (report) { report.vendor = vendor ?? expect; report.digest = digest.digest("hex"); report.conversations = count; report.oversized = oversized; }
664
+ if (vendor === null && empty > 0) throw Error(`${path} is neither a ChatGPT nor a Claude export (or mixes the two)`);
665
+ if (report) { report.vendor = vendor ?? expect; report.digest = digest.digest("hex"); report.conversations = count; report.oversized = oversized; report.empty = empty; if (metadata) report.metadata = vendor === "chatgpt" ? totals : null; }
439
666
  }
440
667
 
441
668
  /** One export, read whole but compact: its vendor by shape, one record per conversation (its kept lines; none for an excluded or oversized one), and the digest of its bytes (what `sent` is remembered by). */
442
- export async function readExport(given, expect = null, { excluded = () => false, skipped = null, text = false } = {}) {
669
+ export async function readExport(given, expect = null, { excluded = () => false, skipped = null, text = false, metadata = false } = {}) {
443
670
  const report = {}, conversations = [];
444
671
  let kept = 0;
445
- for await (const record of exportRecords(given, { expect, excluded, skipped, text, report })) {
446
- kept += 64 + (record.id?.length ?? 0) + record.lines.reduce((sum, line) => sum + 64 + (line.model?.length ?? 0) + (line.text?.length ?? 0), 0);
672
+ for await (const record of exportRecords(given, { expect, excluded, skipped, text, report, metadata })) {
673
+ kept += 64 + (record.id?.length ?? 0) + Object.keys(record.metadata ?? {}).length * 256 + record.lines.reduce((sum, line) => sum + 64 + (line.model?.length ?? 0) + (line.text?.length ?? 0), 0);
447
674
  limit(kept <= EXPORT_LIMITS.keptBytes, "kept bytes");
448
675
  conversations.push(record);
449
676
  }
450
- return { vendor: report.vendor, conversations, digest: report.digest, path: report.path, parts: report.parts, oversized: report.oversized };
677
+ return { vendor: report.vendor, conversations, digest: report.digest, path: report.path, parts: report.parts, oversized: report.oversized, empty: report.empty, cut: report.cut, ...(metadata ? { metadata: report.metadata } : {}) };
451
678
  }
452
679
 
453
680
  /**
@@ -457,11 +684,11 @@ export async function readExport(given, expect = null, { excluded = () => false,
457
684
  * call. `text` hands the counter the messages' text (read here, for its rubric); the hook leaves it out and gets clocks,
458
685
  * roles and a model name. `given` is a path, or an export `readExport` already returned; `report` is filled as above.
459
686
  */
460
- export async function* exportSessions(given, { expect = null, excluded = () => false, skipped = null, text = false, report = null } = {}) {
461
- const records = typeof given === "string" ? exportRecords(given, { expect, excluded, skipped, text, report }) : given.conversations;
462
- for await (const { vendor, id, lines } of records) {
687
+ export async function* exportSessions(given, { expect = null, excluded = () => false, skipped = null, text = false, report = null, metadata = false } = {}) {
688
+ const records = typeof given === "string" ? exportRecords(given, { expect, excluded, skipped, text, report, metadata }) : given.conversations;
689
+ for await (const { vendor, id, lines, metadata: counts = null } of records) {
463
690
  if (lines.length === 0) continue; // excluded, left out as too large, or without a message
464
- yield { key: `${vendor === "chatgpt" ? "chatgpt" : "claude.ai"}:${id}`, projectDir: vendor === "chatgpt" ? "chatgpt" : "claude-ai", basename: vendor === "chatgpt" ? "chatgpt" : "claude.ai", vendor, id, lines: lines.map(transcriptLine) };
691
+ yield { key: `${vendor === "chatgpt" ? "chatgpt" : "claude.ai"}:${id}`, projectDir: vendor === "chatgpt" ? "chatgpt" : "claude-ai", basename: vendor === "chatgpt" ? "chatgpt" : "claude.ai", vendor, id, lines: lines.map(transcriptLine), ...(metadata ? { metadata: counts } : {}) };
465
692
  }
466
693
  }
467
694
 
@@ -491,7 +718,7 @@ export async function findExports(dir = join(homedir(), "Downloads")) {
491
718
  for (const name of names.sort()) {
492
719
  const path = join(root, name);
493
720
  let stat; try { stat = statSync(path); } catch { continue; }
494
- const candidate = stat.isDirectory() ? existsSync(join(path, FILE)) || folderParts(path).length > 0 : (/\.zip$/i.test(name) && !OTHER_PART.test(name)) || name === FILE;
721
+ const candidate = stat.isDirectory() ? existsSync(join(path, FILE)) || folderParts(path).length > 0 || looseOf(path).length > 0 : (/\.zip$/i.test(name) && !OTHER_PART.test(name)) || name === FILE;
495
722
  if (!candidate) continue;
496
723
  try {
497
724
  const { vendor, conversations, digest } = await readExport(path);
@@ -638,9 +638,14 @@ const { exportSessions = null } = (await import("./chat-exports.mjs").catch(() =
638
638
  // 0.10.18: the export streams, one conversation in memory at a time, with its text (`text: true`: this rubric reads it here).
639
639
  async function* vendorExportSessions(paths, expect) {
640
640
  if (paths.length > 0 && !exportSessions) throw Error("chat-exports.mjs is not beside this file: a data export cannot be read");
641
- for (const given of paths) for await (const session of exportSessions(given, { expect, excluded, skipped: skippedConversations, text: true })) {
642
- if (expect === "chatgpt") chatgptConversations += 1; else exportConversations += 1;
643
- yield session;
641
+ for (const given of paths) {
642
+ const report = {};
643
+ for await (const session of exportSessions(given, { expect, excluded, skipped: skippedConversations, text: true, report })) {
644
+ if (expect === "chatgpt") chatgptConversations += 1; else exportConversations += 1;
645
+ yield session;
646
+ }
647
+ // A DOWNLOAD CUT OFF (2026-10-31): the parts before the cut are counted, and the person is told it is not the whole export.
648
+ for (const cut of report.cut ?? []) process.stderr.write(`export: the archive is cut off (${cut.where}) after ${cut.last}: ${cut.parts} conversations part${cut.parts === 1 ? "" : "s"} read whole, ${report.conversations} conversations; nothing past the cut is read, so this is not the whole export\n`);
644
649
  }
645
650
  }
646
651
  async function* claudeExportSessions() { yield* vendorExportSessions(EXPORTS, "claude-web"); }
@@ -1 +1 @@
1
- {"keyId":"608168ccdef72562fc91f9c0f9f2c2d6876bece7f7362cb545b818f7947da6b5","payload":{"files":{"chat-exports.mjs":"04eafe333940ec03d5058d8d51062124aa12ab882bf04db03bcda5613ec69298","claude-mod.mjs":"02d86b0cdddf39879efc5194c0a5be6b41456faedec28963dc123a4e88dc3942","commit-rules.mjs":"e94cc32a5415f6d9e978145ab9505ac4ae0bac9431e6e9104b9b37155260b51f","config-edits.mjs":"0eba2f176ef6f7afba071d6e00de0ff19ba2b283180a801dfd957aa38c1edd94","count-behaviour.mjs":"1beaec2a4d0aead76d166f89cc52441a9cf48f2e69da9888ca2091dd3a10a37b","credential-store.mjs":"a4b3540a61f4ce19e535c7f1d260c0d817686cd066d559a76db2ab108144abba","credential-vault-scripts.mjs":"7e42fe1db3885c2dec6f1de87bebfbefe2292d29179a68f3da87d19eb6c7704b","credential-vault.mjs":"279baabb217e2a3f170e8d7f2b271a88484531f9031c441360ea91561a70da99","git-commits.mjs":"f9c084c54937a86df8fe30a0db2a58e04eeef0dbae69c54b8e368efc9964d6d8","history-outbox.mjs":"10cdcdcc595fbc3222e39b3d845a2ff16c0e7ae20eb43a2d2794e8c4d3a7353e","log-session.mjs":"378a2fd38f4eafd8820a85e4bc4490929ceed59c2711e5cfef6e01e2e195ad3d","orchestration-contract.mjs":"ec08f303a166365b99e70b675de4cfe76c6156c2567e14b5569f6d992f0231b7","orchestration-evidence.mjs":"d0d06cecf0eb08e5c6e653c62a4f45b1eddf2119c2acb8341056b34f488d214a","orchestration-report.mjs":"d4e0a9ad8e4a01b462d22c6b1866aac291565c533ff476085d3367cb6d59bc1b","package-integrity.mjs":"a8210c9494a56bfb9a5ea3d10064c7a269f0b6330c0af7c0700e706c3c0224e3","preserve-lines.mjs":"2df64a69687aa51219bf7b86b88d175cc50990fa29574b31897e41a9ebeecf43","preserve-summary.mjs":"137f781ed7021596a3f0ea67afcf2ab8616ac293f833dbb8f176e838e0ed8321","preserve.mjs":"3e369083ba43bcda2fa0622fd526aa64fcf8ad66e7b6e8f23821752c4d47ad27","runtime-install.mjs":"aab47b52c79d726ef428a24f982c648fa3f1c2dc2b574f633611d02924864e5f","session-databases.mjs":"b9fe20d7445205bdbf4cf2eaaf9cc770dad01e23d41e644b04930ca34e10426d","setup-mcp.mjs":"0c29113179561af1c1e9ff8b7a786e7240edf48a2244993e12335e5ee362c812","stack-rules.mjs":"b23c56e72ec56ba02b17ed895f869172d988c468a697e8d6026b0e268f61e489","stretch-evidence.mjs":"5f5667b92adf11b1a5a6330a0f26dd6db73d56fe60823d9a5246dab71d27d380","transcript-readers.mjs":"e9f20415c2b5d62a09f35a63075002ebd1da56edb32f242d52822d58ecbd8ac3","worktrust-launch.mjs":"84801bd29d472d48188c126b9ebe3989a3132b54e13cc4fe534ff7c383a294ee","worktrust.mjs":"2a3ea97efabb582ebdc78bcb772e78a5aae06c243a5092563c88904df93003b9"},"format":"worktrust-package/1","kind":"engine","version":"0.10.35"},"signature":"tLkEDhYff_g15GrDNcNOzZDW3Y4b0pKv4HAkh8GM59E5IitPsz0eCU-244_mTKubaLILtdTcp85ZU1k_VAeUAQ"}
1
+ {"keyId":"608168ccdef72562fc91f9c0f9f2c2d6876bece7f7362cb545b818f7947da6b5","payload":{"files":{"chat-exports.mjs":"bda43095a62bab608fc9309f9e7a2232dc10b29c514fb34e1aae357daa132737","claude-mod.mjs":"02d86b0cdddf39879efc5194c0a5be6b41456faedec28963dc123a4e88dc3942","commit-rules.mjs":"e94cc32a5415f6d9e978145ab9505ac4ae0bac9431e6e9104b9b37155260b51f","config-edits.mjs":"0eba2f176ef6f7afba071d6e00de0ff19ba2b283180a801dfd957aa38c1edd94","count-behaviour.mjs":"179baf829eda488bab3f17ae6917473ec01d0d6346f47de7bc144351274f19c8","credential-store.mjs":"a4b3540a61f4ce19e535c7f1d260c0d817686cd066d559a76db2ab108144abba","credential-vault-scripts.mjs":"7e42fe1db3885c2dec6f1de87bebfbefe2292d29179a68f3da87d19eb6c7704b","credential-vault.mjs":"279baabb217e2a3f170e8d7f2b271a88484531f9031c441360ea91561a70da99","git-commits.mjs":"f9c084c54937a86df8fe30a0db2a58e04eeef0dbae69c54b8e368efc9964d6d8","history-outbox.mjs":"31609392f4e13dd37678ab3154bd2896cce1a8cca4903b78dd2d96da82b1f406","log-session.mjs":"9c78cadbc469f273367a438721fcc47ce101dc230b6c9a18fe0923960f471bc9","orchestration-contract.mjs":"ec08f303a166365b99e70b675de4cfe76c6156c2567e14b5569f6d992f0231b7","orchestration-evidence.mjs":"d0d06cecf0eb08e5c6e653c62a4f45b1eddf2119c2acb8341056b34f488d214a","orchestration-report.mjs":"d4e0a9ad8e4a01b462d22c6b1866aac291565c533ff476085d3367cb6d59bc1b","package-integrity.mjs":"a8210c9494a56bfb9a5ea3d10064c7a269f0b6330c0af7c0700e706c3c0224e3","preserve-lines.mjs":"2df64a69687aa51219bf7b86b88d175cc50990fa29574b31897e41a9ebeecf43","preserve-summary.mjs":"137f781ed7021596a3f0ea67afcf2ab8616ac293f833dbb8f176e838e0ed8321","preserve.mjs":"3e369083ba43bcda2fa0622fd526aa64fcf8ad66e7b6e8f23821752c4d47ad27","runtime-install.mjs":"aab47b52c79d726ef428a24f982c648fa3f1c2dc2b574f633611d02924864e5f","session-databases.mjs":"b9fe20d7445205bdbf4cf2eaaf9cc770dad01e23d41e644b04930ca34e10426d","setup-mcp.mjs":"dcaa912b0e15a74ab3365aa62f345ba436510b958e9f5cdceddd57ffb99ef4b7","stack-rules.mjs":"b23c56e72ec56ba02b17ed895f869172d988c468a697e8d6026b0e268f61e489","stretch-evidence.mjs":"5f5667b92adf11b1a5a6330a0f26dd6db73d56fe60823d9a5246dab71d27d380","transcript-readers.mjs":"e9f20415c2b5d62a09f35a63075002ebd1da56edb32f242d52822d58ecbd8ac3","worktrust-launch.mjs":"84801bd29d472d48188c126b9ebe3989a3132b54e13cc4fe534ff7c383a294ee","worktrust.mjs":"ff83a783504950cba6f62cb14786e504db701be6c324a44c3fefac26628f516d"},"format":"worktrust-package/1","kind":"engine","version":"0.10.36"},"signature":"1NYMJNm65pMSGf0JL43MaL9XjIWMwu_VBnL1kmdjXh61jjXeXX-RtT7Hb28yXdXM_69et0oAenpizRvOxjuiBg"}
@@ -39,7 +39,9 @@ export function queuedHistory(target,body,source) {
39
39
  const request=join(root,id+'.request.json'),ack=join(root,id+'.ack.json'),state=join(root,id+'.state.json');
40
40
  const acknowledged=read(ack);
41
41
  // REPLACED (0.10.29): a batch cut into smaller ones is acknowledged by its pieces; the caller follows them.
42
- if(acknowledged?.id===id)return {id,status:Array.isArray(acknowledged.replacedBy)?'replaced':'acknowledged',replacedBy:Array.isArray(acknowledged.replacedBy)?acknowledged.replacedBy.filter(child=>/^[a-f0-9]{64}$/.test(child)):[],lines:Number.isInteger(acknowledged.lines)?acknowledged.lines:null,confirm(){},close(){},defer(){},oversize(){},replace(){return [];}};
42
+ // CLOSED (2026-10-31): a batch WorkTrust refused for good is let go here, never "acknowledged": WorkTrust holds nothing of it,
43
+ // so a send that finds it says it was refused, never "already held" (CLI 0.10.35 counted it held and reported a run whole).
44
+ if(acknowledged?.id===id)return {id,status:Array.isArray(acknowledged.replacedBy)?'replaced':acknowledged.closedAt?'closed':'acknowledged',replacedBy:Array.isArray(acknowledged.replacedBy)?acknowledged.replacedBy.filter(child=>/^[a-f0-9]{64}$/.test(child)):[],lines:Number.isInteger(acknowledged.lines)?acknowledged.lines:null,confirm(){},close(){},defer(){},oversize(){},replace(){return [];}};
43
45
  const current=read(state);
44
46
  reservation(root,()=>{
45
47
  if(!existsSync(request)) {
@@ -73,9 +75,10 @@ export function historyRefusal(text,response) {
73
75
  // A staged run WorkTrust closed or refused (0.10.27: another computer's key, seven days without its last batch) is final.
74
76
  const closed=rpc?.id===1 && String(rpc?.error?.message??'').startsWith('history run refused:');
75
77
  // A 413 (0.10.29) is the batch, not the queue: it is cut smaller, never sent again as it was, and nothing else waits for it.
76
- // THE SERVER'S OWN SENTENCE (0.10.35): a re-measure refused for older measure rules says why and the one command that helps;
77
- // the CLI prints it instead of guessing (one line, control characters taken out, at most 400 characters).
78
- const said=closed&&rpc?.error?.data?.reason==='measure_rules'?String(rpc.error.message).replace(/[\u0000-\u001f\u007f-\u009f]/g,' ').slice(0,400):null;
78
+ // THE SERVER'S OWN SENTENCE (0.10.35; every final refusal since 2026-10-31): why WorkTrust refused the batch, printed instead of
79
+ // a guess (0.10.35 said "it missed a batch for seven days" of a batch refused for its lines). One line, control characters
80
+ // taken out, at most 400 characters.
81
+ const said=closed?String(rpc.error.message).replace(/[\u0000-\u001f\u007f-\u009f]/g,' ').slice(0,400):null;
79
82
  return {reason:review?'review':closed?'closed':response.status===413?'oversize':response.status===429?'capacity':'unconfirmed',seconds:Number.isFinite(raw)&&raw>0?Math.min(MAX_RETRY_SECONDS,raw):0,...(said?{said}:{})};
80
83
  }
81
84
 
@@ -90,7 +93,7 @@ export function historyRefusal(text,response) {
90
93
  * (`refused`: WorkTrust keeps the earlier lines counting, and `npx worktrust@latest history` measures again). A single line too
91
94
  * large for a call is let go the same way. `only` limits a pass to those batches (and their pieces): the send that just queued them.
92
95
  */
93
- export async function resumeHistory(target, {send, confirmed, note, retryReview=false, dry=false, limit=Infinity, cutter=null, only=null}) {
96
+ export async function resumeHistory(target, {send, confirmed, note, closed=null, retryReview=false, dry=false, limit=Infinity, cutter=null, only=null}) {
94
97
  const root=join(homedir(),'.worktrust','history-outbox'),scope=scopeOf(target);
95
98
  const totals={received:0,review:0,waiting:0,batches:0,refused:0,held:0,split:0};let paused=null,sent=0;
96
99
  if(!existsSync(root))return totals;
@@ -113,7 +116,8 @@ export async function resumeHistory(target, {send, confirmed, note, retryReview=
113
116
  const marked=(id)=>read(join(root,id+'.state.json'))?.status==='oversize';
114
117
  const whole=(batches)=>batches.length>0&&batches.length===batches[0].run.count&&batches.every((item,index)=>item.run.index===index&&item.run.count===batches[0].run.count);
115
118
  const queue=only?[...only]:[...ids],seen=new Set();
116
- const letGo=(batches)=>{for(const batch of batches){queuedHistory(target,batch.body,batch.source).close('oversize');items.set(batch.id,null);seen.add(batch.id);totals.refused+=batch.entries.length;}return null;};
119
+ // `closed` (2026-10-31): told which run lost a batch for good, so the send never reports that run whole.
120
+ const letGo=(batches)=>{for(const batch of batches){queuedHistory(target,batch.body,batch.source).close('oversize');items.set(batch.id,null);seen.add(batch.id);totals.refused+=batch.entries.length;closed?.(batch.run,batch.entries.length);}return null;};
117
121
  // Cut smaller: answers the pieces' ids, or null when the batch (or its run) can never fit and was let go.
118
122
  const resplit=(item,queued,tighter)=>{
119
123
  if(item.run){
@@ -134,7 +138,7 @@ export async function resumeHistory(target, {send, confirmed, note, retryReview=
134
138
  if(ack?.id===id){if(Array.isArray(ack.replacedBy))queue.unshift(...ack.replacedBy.filter(child=>/^[a-f0-9]{64}$/.test(child)));else if(only&&Number.isInteger(ack.lines))totals.held+=ack.lines;continue;}
135
139
  const item=load(id);if(!item)continue;
136
140
  const queued=queuedHistory(target,item.body,item.source);totals.batches++;
137
- if(queued.status==='acknowledged')continue;
141
+ if(queued.status==='acknowledged'||queued.status==='closed')continue;
138
142
  if(queued.status==='replaced'){queue.unshift(...queued.replacedBy);continue;}
139
143
  // `limit` (0.10.27): the hook sends a few a run by itself; the rest wait, untouched, for the next run.
140
144
  if(sent>=limit){totals.waiting+=item.entries.length;continue;}
@@ -154,16 +158,38 @@ export async function resumeHistory(target, {send, confirmed, note, retryReview=
154
158
  try{if(!response.ok)throw Error();confirmed(text,item.entries.length);}
155
159
  catch{
156
160
  const refusal=historyRefusal(text,response);
157
- if(refusal.reason==='closed'){queued.close();totals.refused+=item.entries.length;if(refusal.said)totals.said=refusal.said;continue;}
161
+ if(refusal.reason==='closed'){queued.close();totals.refused+=item.entries.length;if(refusal.said)totals.said=refusal.said;closed?.(item.run,item.entries.length);continue;}
158
162
  // Too large (0.10.29): marked and taken again at once, by the cut, never resent as it was. Without a cutter it waits.
159
163
  if(refusal.reason==='oversize'){queued.oversize();if(cutter){seen.delete(id);queue.unshift(id);}else totals.waiting+=item.entries.length;continue;}
160
164
  if(refusal.reason!=='review')paused={reason:refusal.reason,seconds:refusal.seconds>0?refusal.seconds:5};queued.defer(refusal.reason,paused?.seconds??refusal.seconds);totals[refusal.reason==='review'?'review':'waiting']+=item.entries.length;continue;
161
165
  }
162
- queued.confirm(item.entries.length);totals.received+=item.entries.length;note(text);
166
+ queued.confirm(item.entries.length);totals.received+=item.entries.length;note(text,item.run);
163
167
  }catch{paused={reason:'unconfirmed',seconds:5};queued.defer(paused.reason,paused.seconds);totals.waiting+=item.entries.length;}
164
168
  }
165
169
  return totals;
166
170
  }
171
+ /**
172
+ * A RUN IS DONE WHEN WORKTRUST HOLDS ALL OF IT (2026-10-31). On 2026-10-30 a re-measure of four batches lost one to a final
173
+ * refusal and the command said "✓ Re-measured. WorkTrust holds all 3 batches": the receipts it had were read as the run. Per run
174
+ * a send touches: its declared count, the batches WorkTrust confirmed (a receipt now, or an acknowledgement an earlier send kept
175
+ * here), the most the door said had arrived, whether a receipt said the run is complete, and the batches refused for good.
176
+ * `state()` is what the command reads: whole only when every run is; null when the send touched none.
177
+ */
178
+ export function runLedger() {
179
+ const runs=new Map();
180
+ const of=(run)=>{if(!run||typeof run.id!=='string'||!Number.isInteger(run.count)||!Number.isInteger(run.index))return null;const known=runs.get(run.id)??{count:run.count,confirmed:new Set(),arrived:0,complete:false,refused:new Set()};runs.set(run.id,known);return known;};
181
+ const kept=(run)=>Math.min(run.count,Math.max(run.arrived,run.confirmed.size));
182
+ return {
183
+ heard(run,receipt){const known=of(run);if(!known)return;known.confirmed.add(run.index);if(Number.isInteger(receipt?.arrived))known.arrived=Math.max(known.arrived,receipt.arrived);if(receipt?.complete===true||(Number.isInteger(receipt?.of)&&receipt.arrived===receipt.of))known.complete=true;},
184
+ held(run){of(run)?.confirmed.add(run.index);},
185
+ refused(run){of(run)?.refused.add(run.index);},
186
+ state(){
187
+ const all=[...runs.values()];if(!all.length)return null;
188
+ return {batches:all.reduce((n,run)=>n+run.count,0),arrived:all.reduce((n,run)=>n+kept(run),0),refused:all.reduce((n,run)=>n+run.refused.size,0),
189
+ whole:all.every(run=>run.refused.size===0&&(run.complete||kept(run)===run.count))};
190
+ },
191
+ };
192
+ }
167
193
  /** A queued batch's id, as queuedHistory names it, so a send can hand its own batches to resumeHistory (`only`). */
168
194
  export const historyIdOf=(target,body,source)=>digest(scopeOf(target)+'\0'+source+'\0'+body);
169
195
 
package/log-session.mjs CHANGED
@@ -802,7 +802,7 @@ function callOutcomesOf(messages) {
802
802
  /** A digest of this hook and the readers beside it, as installed: the door records it beside each line as a signal of which code ran, never as proof. */
803
803
  const selfDigest = (() => { try { const here = dirname(fileURLToPath(import.meta.url)); const hash = createHash("sha256"); for (const name of ["log-session.mjs", ...READER_FILES].sort()) { try { hash.update(`${name}\0`).update(readFileSync(join(here, name))).update("\0"); } catch { hash.update(`${name}\0missing\0`); } } return hash.digest("hex"); } catch { return null; } })();
804
804
  const CLI_VERSION_SENT = /^[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,4}$/.test(process.env.WORKTRUST_CLI_VERSION ?? "") ? process.env.WORKTRUST_CLI_VERSION : null; // `worktrust.mjs` hands its own version to the hook it starts
805
-
805
+ const DOOR_MODE_SENT = CLI_VERSION_SENT && /^(hours_only|work_lines)(\.[0-9]{9,11})?$/.test(process.env.WORKTRUST_DOOR_MODE ?? "") ? process.env.WORKTRUST_DOOR_MODE : null; // 0.10.37: `mcp off|on`, a closed word and its moment beside the version
806
806
  /**
807
807
  * THE TOKENS, AND THE CACHE HALVES APART (roadmap 16). Claude Code's usage block carries input_tokens, output_tokens,
808
808
  * cache_creation_input_tokens and cache_read_input_tokens. `tokensIn` stays what it was — new input plus what was written
@@ -919,13 +919,11 @@ function payloadFor(stretch) {
919
919
  * adding a twin. Returns how many entries were accepted, so a caller can advance a watermark over
920
920
  * exactly what landed. `announce` because one caller is a person watching a terminal and the other
921
921
  * is a hook holding a session's exit open.
922
- */
923
- /**
922
+ *
924
923
  * THE BATCHES: at most two hundred lines each. `byDay` (an export, 2026-10-10) never splits a UTC day across two batches unless
925
924
  * one day alone exceeds the cap: the door's receipt counts per day what it replaced and how many AI-app lines lie there, and a
926
925
  * day in two batches would be counted twice.
927
- */
928
- /**
926
+ *
929
927
  * A batch stays under the door's ceilings for one history call (2026-10-23, docs/INTAKE-HARDENING.md): 2 MB a call and 1.5 MB of
930
928
  * timelines a call, each with room for the envelope. A timeline (0.10.20) is up to 200 KB a line, so a batch is cut by bytes
931
929
  * and by timeline bytes as well as by count. Until 0.10.28 the cut was 3.5 MB, under the door's 4.5 MB outer bound only.
@@ -957,11 +955,11 @@ function batchesOf(group, byDay, limit = BATCH_LIMIT) {
957
955
  }
958
956
  /** 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. */
959
957
  const RECEIPTS = { new: 0, alreadyHeld: 0, filled: 0, replaced: 0, superseded: 0, recut: 0, unknownOnDays: 0, unknownWithdrawn: 0, corrected: 0, measuredSeconds: 0, staged: 0, kept: 0, restored: 0, untimed: 0 }; // 0.10.27: staged, the batches WorkTrust keeps on its server, and kept, their lines // 0.10.20: measuredSeconds is WorkTrust's own figure for what the batch stored, the one the terminal shows // 0.10.17: recut, the one-envelope export lines its runs replaced // 2026-10-10: and what a re-measure did (new, held, filled, replaced), so the command can say it
960
- const noteReceipt = (answer) => {
958
+ const noteReceipt = (answer, run = null) => {
961
959
  try {
962
960
  const json = JSON.parse(answer.trim().startsWith("{") ? answer : answer.split("\n").find((row) => row.startsWith("data:"))?.slice(5) ?? "null");
963
961
  const receipt = JSON.parse(json?.result?.content?.[0]?.text ?? "{}");
964
- for (const key of Object.keys(RECEIPTS)) RECEIPTS[key] += Number(receipt[key]) || 0;
962
+ for (const key of Object.keys(RECEIPTS)) RECEIPTS[key] += Number(receipt[key]) || 0; if (receipt.staged === true) RUNS.heard(run, receipt);
965
963
  // THE QUEUE (0.10.32): the receipt of the batch that completes a run says where the run waits; the last one seen is kept.
966
964
  const queued = receipt.queued;
967
965
  if (queued && Number.isInteger(queued.position) && queued.position >= 1 && Number.isFinite(Number(queued.eta_minutes)) && Number(queued.eta_minutes) >= 0) QUEUED.at = { position: queued.position, eta_minutes: Math.max(1, Math.ceil(Number(queued.eta_minutes))) };
@@ -969,6 +967,7 @@ const noteReceipt = (answer) => {
969
967
  };
970
968
  /** Where the last completed run waits in WorkTrust's queue (0.10.32): null when no receipt said so (an older server, or not complete yet). */
971
969
  const QUEUED = { at: null };
970
+ const RUNS = (await import("./history-outbox.mjs").then((m) => m.runLedger?.(), () => null)) ?? { heard() {}, held() {}, refused() {}, state: () => null }; // A RUN IS DONE WHEN WORKTRUST HOLDS ALL OF IT (2026-10-31): each run's declared batches against the receipts; a copy without the outbox (preserve) sends no run
972
971
  /** Only explicit durable receipts authorize a checkpoint. HTTP 200 alone says nothing. */
973
972
  function confirmedReceipt(answer, expectedCount = null) {
974
973
  try {
@@ -1158,7 +1157,7 @@ async function sendHistory(door, entries, announce = false, rebuild = false, nam
1158
1157
  const handLater = (item) => { const row = later.get(item.target.token) ?? { target: item.target, ids: [] }; row.ids.push(historyIdOf(item.target, item.body, item.source)); later.set(item.target.token, row); };
1159
1158
  for (const item of plan) {
1160
1159
  const { source, target, batch, body } = item;
1161
- if (stopped.has(source)) continue;
1160
+ if (stopped.has(source)) { HISTORY_DELIVERY.waiting += batch.length; continue; } // 2026-10-31: held back behind its AI app's failed batch, waiting in the outbox, and said
1162
1161
  if (item.run && stoppedRuns.has(item.run.id)) { handLater(item); continue; }
1163
1162
  const number = (numbers.get(source) ?? 0) + 1; numbers.set(source, number);
1164
1163
  for (const entry of batch) retainMeasurement(entry, source);
@@ -1166,7 +1165,8 @@ async function sendHistory(door, entries, announce = false, rebuild = false, nam
1166
1165
  let queued;
1167
1166
  try { queued = queuedHistory(target, body, source); }
1168
1167
  catch { console.error("Pending history could not be stored safely. Nothing was marked complete; keep the local WorkTrust folder for recovery."); HISTORY_DELIVERY.waiting += batch.length; stopped.add(source); continue; }
1169
- if (queued.status === "acknowledged" && !byDay) { accepted += batch.length; RECEIPTS.alreadyHeld += batch.length; continue; }
1168
+ if (queued.status === "closed") { HISTORY_DELIVERY.refused += batch.length; RUNS.refused(item.run); continue; } // 2026-10-31: let go on an earlier send is refused, never "already held"
1169
+ if (queued.status === "acknowledged" && !byDay) { accepted += batch.length; RECEIPTS.alreadyHeld += batch.length; RUNS.held(item.run); continue; }
1170
1170
  if (queued.status === "replaced" || queued.status === "oversize") { handLater(item); if (item.run) stoppedRuns.add(item.run.id); continue; }
1171
1171
  if (queued.status === "review" && !flag("retry-review")) { HISTORY_DELIVERY.review += batch.length; continue; }
1172
1172
  if (queued.status === "waiting") { HISTORY_DELIVERY.waiting += batch.length; continue; }
@@ -1177,19 +1177,19 @@ async function sendHistory(door, entries, announce = false, rebuild = false, nam
1177
1177
  catch {
1178
1178
  const refusal = historyRefusal(text, response);
1179
1179
  // A run WorkTrust closed (seven days without its last batch, another computer's key) is final: kept here it would wait forever.
1180
- if (refusal.reason === "closed") { queued.close(); HISTORY_DELIVERY.refused += batch.length; if (refusal.said) HISTORY_DELIVERY.said = refusal.said; continue; }
1180
+ if (refusal.reason === "closed") { queued.close(); HISTORY_DELIVERY.refused += batch.length; if (refusal.said) HISTORY_DELIVERY.said = refusal.said; RUNS.refused(item.run); continue; }
1181
1181
  if (refusal.reason === "oversize") { queued.oversize(); handLater(item); if (item.run) stoppedRuns.add(item.run.id); continue; }
1182
1182
  queued.defer(refusal.reason, refusal.seconds);
1183
1183
  if (refusal.reason === "review") { HISTORY_DELIVERY.review += batch.length; continue; }
1184
1184
  HISTORY_DELIVERY.waiting += batch.length; stopped.add(source); continue;
1185
1185
  }
1186
- queued.confirm(batch.length); accepted += batch.length; noteReceipt(text);
1186
+ queued.confirm(batch.length); accepted += batch.length; noteReceipt(text, item.run);
1187
1187
  if (announce) console.log(`batch ${number}: received ${batch.length}`);
1188
1188
  } catch { queued.defer("unconfirmed"); HISTORY_DELIVERY.waiting += batch.length; stopped.add(source); }
1189
1189
  }
1190
1190
  for (const { target, ids } of later.values()) {
1191
1191
  try {
1192
- const totals = await resumeHistory(target, { only: ids, cutter: outboxCut, retryReview: flag("retry-review"), confirmed: confirmedReceipt, note: noteReceipt, send: sendQueued(target) });
1192
+ const totals = await resumeHistory(target, { only: ids, cutter: outboxCut, retryReview: flag("retry-review"), confirmed: confirmedReceipt, note: noteReceipt, closed: RUNS.refused, send: sendQueued(target) });
1193
1193
  accepted += totals.received + totals.held; RECEIPTS.alreadyHeld += totals.held;
1194
1194
  HISTORY_DELIVERY.waiting += totals.waiting; HISTORY_DELIVERY.review += totals.review; HISTORY_DELIVERY.refused += totals.refused; if (totals.said) HISTORY_DELIVERY.said = totals.said;
1195
1195
  if (announce && totals.split) console.log(`${totals.split} batch${totals.split === 1 ? "" : "es"} too large for one call: cut smaller and sent again in pieces`);
@@ -1215,7 +1215,7 @@ async function resendPending(limit) {
1215
1215
  } catch (error) { if (process.env.WORKTRUST_HOOK_DEBUG) console.error(`worktrust: ${error.message}`); }
1216
1216
  }
1217
1217
 
1218
- /** Whether the door's import_history takes `from_archive` (0.8.0): asked with tools/list, never assumed. */
1218
+ /** Whether the door's import_history takes `from_archive` (0.8.0), asked with tools/list; a door that no longer LISTS import_history to a computer's key (2026-10-31) is one that takes it. */
1219
1219
  async function doorKnowsArchive(target) {
1220
1220
  if (!target) return false;
1221
1221
  try {
@@ -1224,7 +1224,7 @@ async function doorKnowsArchive(target) {
1224
1224
  const text = await response.text();
1225
1225
  const json = JSON.parse(text.trim().startsWith("{") ? text : text.split("\n").find((row) => row.startsWith("data:"))?.slice(5) ?? "null");
1226
1226
  const tool = json?.result?.tools?.find((one) => one.name === "import_history");
1227
- return Boolean(tool?.inputSchema?.properties?.entries?.items?.properties?.from_archive);
1227
+ return tool ? Boolean(tool.inputSchema?.properties?.entries?.items?.properties?.from_archive) : Array.isArray(json?.result?.tools) && json.result.tools.some((one) => one.name === "log_work");
1228
1228
  } catch { return false; }
1229
1229
  }
1230
1230
 
@@ -1242,7 +1242,7 @@ const proofFor = (url, body) => {
1242
1242
  * on this computer, and the door names a coupling's clients by the user-agent it hears (mcp_identify's
1243
1243
  * agents_seen). An Antigravity line names Antigravity: the product name, nothing of the work.
1244
1244
  */
1245
- const clientOf = (source, always = false) => (CLI_VERSION_SENT || always || source === "antigravity" || DATABASE_CLIENTS.includes(source) || EXPORT_CLIENTS.includes(source) ? { "user-agent": `${source ?? "claude"}/hook (worktrust-hook)${CLI_VERSION_SENT ? ` worktrust-cli/${CLI_VERSION_SENT}` : ""}` } : {});
1245
+ const clientOf = (source, always = false) => (CLI_VERSION_SENT || always || source === "antigravity" || DATABASE_CLIENTS.includes(source) || EXPORT_CLIENTS.includes(source) ? { "user-agent": `${source ?? "claude"}/hook (worktrust-hook)${CLI_VERSION_SENT ? ` worktrust-cli/${CLI_VERSION_SENT}` : ""}${DOOR_MODE_SENT ? ` worktrust-mode/${DOOR_MODE_SENT}` : ""}` } : {});
1246
1246
 
1247
1247
  async function send(door, payload) {
1248
1248
  retainMeasurement(payload, entrySource.get(payload));
@@ -1421,7 +1421,10 @@ async function exportEntries() {
1421
1421
  }
1422
1422
  }
1423
1423
  const days = [...report.days].sort();
1424
- reports.push({ path: read.path, vendor: read.vendor, digest: read.digest, conversations: read.conversations, days: days.length, first: days[0] ?? null, last: days.at(-1) ?? null, oversized: read.oversized }); // no hours (0.10.20): WorkTrust computes them on arrival and the receipt says
1424
+ // A DOWNLOAD CUT OFF (2026-10-31): the reader read the conversations parts the archive held whole before the cut, and says
1425
+ // where it stopped; the person is told every time, so a partial export is never shown as the whole (counts and part names only).
1426
+ for (const cut of read.cut ?? []) process.stderr.write(`export: the archive is cut off (${cut.where}) after ${cut.last}: ${cut.parts} conversations part${cut.parts === 1 ? "" : "s"} read whole, ${read.conversations} conversations; nothing past the cut is read, so this is not the whole export\n`);
1427
+ reports.push({ path: read.path, vendor: read.vendor, digest: read.digest, conversations: read.conversations, days: days.length, first: days[0] ?? null, last: days.at(-1) ?? null, oversized: read.oversized, ...(read.empty ? { empty: read.empty } : {}), ...(read.cut ? { parts: read.parts, cut: read.cut } : {}) }); // no hours (0.10.20): WorkTrust computes them on arrival and the receipt says
1425
1428
  }
1426
1429
  const seen = new Set();
1427
1430
  return { entries: entries.filter((entry) => !seen.has(entry.stretch_ref) && seen.add(entry.stretch_ref)).sort((a, b) => a.at.localeCompare(b.at)), reports };
@@ -1759,8 +1762,8 @@ if (flag("history")) {
1759
1762
  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 });
1760
1763
  // 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.
1761
1764
  if (!fromExports && !fromFolder) await settleReadFailures(door ?? codexDoor); // 0.10.32: a transcript that could not be read is counted and told
1762
- if (fromExports) console.log(JSON.stringify({ export_sent: accepted, of: entries.length, ...RECEIPTS })); else console.log(JSON.stringify({ history_sent: accepted, of: sending.length, unreadable: READ_FAILURES.n, ...RECEIPTS, delivery: HISTORY_DELIVERY, ...(staged ? { days: { compared: COMPARED.asked ? COMPARED.days : null, changed: COMPARED.asked ? COMPARED.changed : null }, queued: QUEUED.at } : {}) })); // the same line for a history send: what the door did with it, and WorkTrust's measuredSeconds for what it stored
1763
- return await exitFlushed(accepted === sending.length ? 0 : 1);
1765
+ if (fromExports) console.log(JSON.stringify({ export_sent: accepted, of: entries.length, ...RECEIPTS })); else console.log(JSON.stringify({ history_sent: accepted, of: sending.length, unreadable: READ_FAILURES.n, ...RECEIPTS, delivery: HISTORY_DELIVERY, ...(staged ? { days: { compared: COMPARED.asked ? COMPARED.days : null, changed: COMPARED.asked ? COMPARED.changed : null }, queued: QUEUED.at, run: RUNS.state() } : {}) })); // the same line for a history send: what the door did with it, and WorkTrust's measuredSeconds for what it stored
1766
+ return await exitFlushed(accepted === sending.length && RUNS.state()?.whole !== false ? 0 : 1); // 2026-10-31: a run WorkTrust does not hold whole fails too
1764
1767
  }
1765
1768
 
1766
1769
  const input = hookInput();
@@ -1 +1 @@
1
- {"keyId":"608168ccdef72562fc91f9c0f9f2c2d6876bece7f7362cb545b818f7947da6b5","payload":{"files":{"AGENTS.md":"c6f5280c5bf81a14db4bdc282218fb005706e92dd9a9170c0e727716ee91685a","CLAUDE.md":"5933504f93e5a40369a4790e96dd5dad791d849d3178b1833eb64088e456aaeb","LICENSE":"3096ed1693974a90e1f4f59bf01c9559d94a7941d933e36fb81d3995a97f25c1","README.md":"9774f45499ba5fd3db19135ddd3c9606f0744db11556acf7a41100bd2c0bd9d4","SECURITY.md":"b672649c7c7bf18538dd4560d7b533498721e0be765a000796d7d18390b5cbb6","chat-exports.mjs":"04eafe333940ec03d5058d8d51062124aa12ab882bf04db03bcda5613ec69298","claude-mod.mjs":"02d86b0cdddf39879efc5194c0a5be6b41456faedec28963dc123a4e88dc3942","commit-rules.mjs":"e94cc32a5415f6d9e978145ab9505ac4ae0bac9431e6e9104b9b37155260b51f","config-edits.mjs":"0eba2f176ef6f7afba071d6e00de0ff19ba2b283180a801dfd957aa38c1edd94","count-behaviour.mjs":"1beaec2a4d0aead76d166f89cc52441a9cf48f2e69da9888ca2091dd3a10a37b","credential-store.mjs":"a4b3540a61f4ce19e535c7f1d260c0d817686cd066d559a76db2ab108144abba","credential-vault-scripts.mjs":"7e42fe1db3885c2dec6f1de87bebfbefe2292d29179a68f3da87d19eb6c7704b","credential-vault.mjs":"279baabb217e2a3f170e8d7f2b271a88484531f9031c441360ea91561a70da99","engine-release.json":"982e696f36761c655ab7696cf920bafac1ebe0c59d040b7219d510523fc346eb","git-commits.mjs":"f9c084c54937a86df8fe30a0db2a58e04eeef0dbae69c54b8e368efc9964d6d8","history-outbox.mjs":"10cdcdcc595fbc3222e39b3d845a2ff16c0e7ae20eb43a2d2794e8c4d3a7353e","log-session.mjs":"378a2fd38f4eafd8820a85e4bc4490929ceed59c2711e5cfef6e01e2e195ad3d","orchestration-contract.mjs":"ec08f303a166365b99e70b675de4cfe76c6156c2567e14b5569f6d992f0231b7","orchestration-evidence.mjs":"d0d06cecf0eb08e5c6e653c62a4f45b1eddf2119c2acb8341056b34f488d214a","orchestration-report.mjs":"d4e0a9ad8e4a01b462d22c6b1866aac291565c533ff476085d3367cb6d59bc1b","package-integrity.mjs":"a8210c9494a56bfb9a5ea3d10064c7a269f0b6330c0af7c0700e706c3c0224e3","package.json":"f357f15ad0a9bf85b82371dabccc20a15a38c040cc7cd1aad60e58fd7edfdca6","preserve-lines.mjs":"2df64a69687aa51219bf7b86b88d175cc50990fa29574b31897e41a9ebeecf43","preserve-summary.mjs":"137f781ed7021596a3f0ea67afcf2ab8616ac293f833dbb8f176e838e0ed8321","preserve.mjs":"3e369083ba43bcda2fa0622fd526aa64fcf8ad66e7b6e8f23821752c4d47ad27","runtime-install.mjs":"aab47b52c79d726ef428a24f982c648fa3f1c2dc2b574f633611d02924864e5f","session-databases.mjs":"b9fe20d7445205bdbf4cf2eaaf9cc770dad01e23d41e644b04930ca34e10426d","setup-mcp.mjs":"0c29113179561af1c1e9ff8b7a786e7240edf48a2244993e12335e5ee362c812","stack-rules.mjs":"b23c56e72ec56ba02b17ed895f869172d988c468a697e8d6026b0e268f61e489","stretch-evidence.mjs":"5f5667b92adf11b1a5a6330a0f26dd6db73d56fe60823d9a5246dab71d27d380","transcript-readers.mjs":"e9f20415c2b5d62a09f35a63075002ebd1da56edb32f242d52822d58ecbd8ac3","worktrust-launch.mjs":"84801bd29d472d48188c126b9ebe3989a3132b54e13cc4fe534ff7c383a294ee","worktrust.mjs":"2a3ea97efabb582ebdc78bcb772e78a5aae06c243a5092563c88904df93003b9"},"format":"worktrust-package/1","kind":"npm","version":"0.10.35"},"signature":"zBGC2wIWsTuBDq7bcmDRreaEYyxq59m78Cd8yfiLHx_s4gMOqj2ZMeXON5ePQgB_OhsB1Esf2JWLpR_xrGJyCQ"}
1
+ {"keyId":"608168ccdef72562fc91f9c0f9f2c2d6876bece7f7362cb545b818f7947da6b5","payload":{"files":{"AGENTS.md":"c6f5280c5bf81a14db4bdc282218fb005706e92dd9a9170c0e727716ee91685a","CLAUDE.md":"5933504f93e5a40369a4790e96dd5dad791d849d3178b1833eb64088e456aaeb","LICENSE":"3096ed1693974a90e1f4f59bf01c9559d94a7941d933e36fb81d3995a97f25c1","README.md":"65f5597520d3add8f021ee68f39cbc29bae59744da46e89d641cf7fb4474f541","SECURITY.md":"b672649c7c7bf18538dd4560d7b533498721e0be765a000796d7d18390b5cbb6","chat-exports.mjs":"bda43095a62bab608fc9309f9e7a2232dc10b29c514fb34e1aae357daa132737","claude-mod.mjs":"02d86b0cdddf39879efc5194c0a5be6b41456faedec28963dc123a4e88dc3942","commit-rules.mjs":"e94cc32a5415f6d9e978145ab9505ac4ae0bac9431e6e9104b9b37155260b51f","config-edits.mjs":"0eba2f176ef6f7afba071d6e00de0ff19ba2b283180a801dfd957aa38c1edd94","count-behaviour.mjs":"179baf829eda488bab3f17ae6917473ec01d0d6346f47de7bc144351274f19c8","credential-store.mjs":"a4b3540a61f4ce19e535c7f1d260c0d817686cd066d559a76db2ab108144abba","credential-vault-scripts.mjs":"7e42fe1db3885c2dec6f1de87bebfbefe2292d29179a68f3da87d19eb6c7704b","credential-vault.mjs":"279baabb217e2a3f170e8d7f2b271a88484531f9031c441360ea91561a70da99","engine-release.json":"5d0bc51d24750c8ea15423f5625a8e27cfe352c88fe17c623ef0fc5f59bca2da","git-commits.mjs":"f9c084c54937a86df8fe30a0db2a58e04eeef0dbae69c54b8e368efc9964d6d8","history-outbox.mjs":"31609392f4e13dd37678ab3154bd2896cce1a8cca4903b78dd2d96da82b1f406","log-session.mjs":"9c78cadbc469f273367a438721fcc47ce101dc230b6c9a18fe0923960f471bc9","orchestration-contract.mjs":"ec08f303a166365b99e70b675de4cfe76c6156c2567e14b5569f6d992f0231b7","orchestration-evidence.mjs":"d0d06cecf0eb08e5c6e653c62a4f45b1eddf2119c2acb8341056b34f488d214a","orchestration-report.mjs":"d4e0a9ad8e4a01b462d22c6b1866aac291565c533ff476085d3367cb6d59bc1b","package-integrity.mjs":"a8210c9494a56bfb9a5ea3d10064c7a269f0b6330c0af7c0700e706c3c0224e3","package.json":"bb2bac211ec7f12913d860beb8a7b7733f926a361d575733951b0140f0409dec","preserve-lines.mjs":"2df64a69687aa51219bf7b86b88d175cc50990fa29574b31897e41a9ebeecf43","preserve-summary.mjs":"137f781ed7021596a3f0ea67afcf2ab8616ac293f833dbb8f176e838e0ed8321","preserve.mjs":"3e369083ba43bcda2fa0622fd526aa64fcf8ad66e7b6e8f23821752c4d47ad27","runtime-install.mjs":"aab47b52c79d726ef428a24f982c648fa3f1c2dc2b574f633611d02924864e5f","session-databases.mjs":"b9fe20d7445205bdbf4cf2eaaf9cc770dad01e23d41e644b04930ca34e10426d","setup-mcp.mjs":"dcaa912b0e15a74ab3365aa62f345ba436510b958e9f5cdceddd57ffb99ef4b7","stack-rules.mjs":"b23c56e72ec56ba02b17ed895f869172d988c468a697e8d6026b0e268f61e489","stretch-evidence.mjs":"5f5667b92adf11b1a5a6330a0f26dd6db73d56fe60823d9a5246dab71d27d380","transcript-readers.mjs":"e9f20415c2b5d62a09f35a63075002ebd1da56edb32f242d52822d58ecbd8ac3","worktrust-launch.mjs":"84801bd29d472d48188c126b9ebe3989a3132b54e13cc4fe534ff7c383a294ee","worktrust.mjs":"ff83a783504950cba6f62cb14786e504db701be6c324a44c3fefac26628f516d"},"format":"worktrust-package/1","kind":"npm","version":"0.10.36"},"signature":"t6KO1vCVVWp2XvOnCv6p7PTsCXQIrf3TeOComgkM9ePryMwd0NoNjNfrLY0PrF0-8zG7DxnUdGsqpeIW4mxKAg"}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "worktrust",
3
- "version": "0.10.35",
3
+ "version": "0.10.36",
4
4
  "description": "Couple this computer to WorkTrust: approve a code in your browser, and every AI app here reports what you built. Metadata only, no dependencies.",
5
5
  "type": "module",
6
6
  "bin": {
package/setup-mcp.mjs CHANGED
@@ -260,7 +260,9 @@ for (const client of CLIENTS) {
260
260
  }
261
261
  const text = existsSync(client.file) ? readFileSync(client.file, "utf8") : "";
262
262
  // With the bridge, coupled means the bridge is in AND no entry with a key in it is left beside it.
263
- const already = client.shape === "yaml" && !REMOVE ? (BRIDGE !== undefined ? text.includes(JSON.stringify(BRIDGE)) && (!client.plugin || goosePluginStands()) : text.includes(URL_)) && yamlConfig(client, text, false) === text : REMOVE ? text.includes(URL_) || /worktrust(?:-launch)?\.(?:mjs|py)/.test(text) : BRIDGE !== undefined ? text.includes(JSON.stringify(BRIDGE).slice(1, -1)) && !text.includes(URL_) : text.includes(URL_);
263
+ // A TOML'S SERVER TABLES ONLY (2026-10-31): Codex's `notify` names the same launcher, and read as "already there" it left Codex doorless.
264
+ const doorText = client.shape === "toml" ? (text.match(/\n?\[mcp_servers\.[^\n]*\][\s\S]*?(?=\n\[|$)/g) ?? []).join("\n") : text;
265
+ const already = client.shape === "yaml" && !REMOVE ? (BRIDGE !== undefined ? text.includes(JSON.stringify(BRIDGE)) && (!client.plugin || goosePluginStands()) : text.includes(URL_)) && yamlConfig(client, text, false) === text : REMOVE ? doorText.includes(URL_) || /worktrust(?:-launch)?\.(?:mjs|py)/.test(doorText) : BRIDGE !== undefined ? doorText.includes(JSON.stringify(BRIDGE).slice(1, -1)) && !doorText.includes(URL_) : doorText.includes(URL_);
264
266
  // THE WAY OUT, ON THE MACHINE. Uncoupling in the app ends the TOKEN; the config that names the
265
267
  // door stays behind on every client here, so the next person to read this file believes the
266
268
  // machine is coupled. `--remove` takes the entry out; the account side is a separate act and
package/worktrust.mjs CHANGED
@@ -76,7 +76,7 @@ const command = args.includes("--help") ? "help" : args.includes("--version") ?
76
76
  const flag = (name) => { const at = args.indexOf(`--${name}`); return at >= 0 ? args[at + 1] : undefined; };
77
77
  const has = (name) => args.includes(`--${name}`);
78
78
  /** This CLI's version, said to the door so the app can tell which computer runs an old one (check-cli-package holds it equal to package.json). */
79
- const CLI_VERSION = "0.10.35";
79
+ const CLI_VERSION = "0.10.36";
80
80
  /**
81
81
  * HOW THIS CLI MEASURES, AS A NUMBER OF ITS OWN (0.10.31; owner, 2026-10-28: 0.10.30 offered a re-measure it had no reason
82
82
  * to offer). Raised ONLY when what is measured changes: the timeline, the seconds, the tokens, the steering, the session
@@ -445,10 +445,10 @@ function proof(device, url, body) {
445
445
  }
446
446
 
447
447
  /** Whether the door accepts a key: one call that reads nothing back. */
448
- async function accepted(url, token, device) {
448
+ async function accepted(url, token, device, agentTail = "") {
449
449
  try {
450
450
  const body = JSON.stringify({ jsonrpc: "2.0", id: 0, method: "tools/list" });
451
- const response = await fetch(url, { method: "POST", headers: { "content-type": "application/json", accept: "application/json", authorization: `Bearer ${token}`, "user-agent": `worktrust-bridge worktrust-cli/${CLI_VERSION}`, ...proof(device, url, body) }, body, redirect: "error", signal: AbortSignal.timeout(5000) });
451
+ const response = await fetch(url, { method: "POST", headers: { "content-type": "application/json", accept: "application/json", authorization: `Bearer ${token}`, "user-agent": `worktrust-bridge worktrust-cli/${CLI_VERSION}${agentTail}`, ...proof(device, url, body) }, body, redirect: "error", signal: AbortSignal.timeout(5000) });
452
452
  if (response.status === 401 || response.status === 403) return false;
453
453
  if (response.status !== 200) return null;
454
454
  const answer = await response.json();
@@ -595,7 +595,8 @@ async function hook() {
595
595
  if (has("hermes") || has("goose")) return sessionEnd();
596
596
  const key = await freshKey();
597
597
  if (!key) return;
598
- const child = spawn(moduleExecutable(HERE), [...moduleArgs(HERE, "log-session.mjs", args.filter((arg) => arg !== "hook"))], { stdio: "inherit", env: { ...process.env, WORKTRUST_MCP_URL: key.url, WORKTRUST_MCP_TOKEN: key.token, WORKTRUST_CLI_VERSION: CLI_VERSION, WORKTRUST_MEASURE_RULES: String(MEASURE_RULES), WORKTRUST_HISTORY_SCOPE: historyQueueScope(key.token), ...(key.device ? { WORKTRUST_DEVICE_KEY: key.device } : {}) } }); // 0.10.20: the hook names the version that started it, beside each line
598
+ await followDoorWish(key);
599
+ const child = spawn(moduleExecutable(HERE), [...moduleArgs(HERE, "log-session.mjs", args.filter((arg) => arg !== "hook"))], { stdio: "inherit", env: { ...process.env, WORKTRUST_MCP_URL: key.url, WORKTRUST_MCP_TOKEN: key.token, WORKTRUST_CLI_VERSION: CLI_VERSION, ...doorModeEnv(), WORKTRUST_MEASURE_RULES: String(MEASURE_RULES), WORKTRUST_HISTORY_SCOPE: historyQueueScope(key.token), ...(key.device ? { WORKTRUST_DEVICE_KEY: key.device } : {}) } }); // 0.10.20: the hook names the version that started it, beside each line
599
600
  process.exitCode = await new Promise((resolve, reject) => { child.on("error", reject); child.on("close", (code) => resolve(code ?? 1)); });
600
601
  }
601
602
 
@@ -650,16 +651,19 @@ async function update() {
650
651
  say(` WorkTrust · update ${hostname().replace(/\.local$/i, "")} to ${CLI_VERSION}`);
651
652
  say();
652
653
  const paths = await scripts();
654
+ if (!doorState() && !has("dry-run")) saveDoorState({ mode: await chooseDoor(), asked: new Date().toISOString() }); // once, for a computer coupled before 0.10.37
655
+ const doorIsOff = doorOff();
653
656
  const plan = await run(paths["setup-mcp.mjs"], ["--bridge", STABLE], PLACEHOLDER, true);
654
657
  // AGREED BEFORE, REFRESHED WITHOUT A QUESTION (0.10.30): an app or hook the person said yes to is brought onto this
655
658
  // version's launcher; only what is NEW here is shown in full and asked about, and --yes leaves the new ones as they are.
656
659
  const agreed = await consent();
657
660
  say(" Every AI app found here gets the WorkTrust door, the local command that reads the key:");
658
- const found = planLines(plan.out, true).filter((line) => !line.includes("not on this machine"));
661
+ const found = doorIsOff ? [] : planLines(plan.out, true).filter((line) => !line.includes("not on this machine"));
662
+ if (doorIsOff) say(` the door stays off here (hours only, ${DOOR_SWITCH})`);
659
663
  const apps = [...new Set(found.map(labelOf).filter(Boolean))], fresh = apps.filter((app) => !agreed.has(`door:${app}`));
660
664
  for (const app of apps) if (!fresh.includes(app)) say(` ✓ ${app}: refreshed (${agreed.said(`door:${app}`)})`);
661
665
  for (const line of found) if (fresh.includes(labelOf(line))) say(`${line} · new`);
662
- if (found.length === 0) say(" (no AI app found here)");
666
+ if (found.length === 0 && !doorIsOff) say(" (no AI app found here)");
663
667
  const hookFresh = !agreed.has("session-hook");
664
668
  say(` The session hook and ${STABLE} are brought to ${CLI_VERSION}.`);
665
669
  say(hookFresh ? ` + Session hook: ${join(homedir(), ".claude", "settings.json")} → SessionStart, SessionEnd, PreCompact and (at most once an hour) Stop run it · new` : ` ✓ Session hook: refreshed (${agreed.said("session-hook")}; since 0.10.32 it also runs after an answer, at most once an hour, so a long session's finished days arrive the same day)`);
@@ -679,8 +683,8 @@ async function update() {
679
683
  say(` ✓ ${STABLE} is now ${CLI_VERSION}`);
680
684
  // Out first, then in: an app that held a key of its own (a hand-made entry) moves onto the bridge. An app not agreed to is not touched.
681
685
  const skipArgs = skip.length > 0 ? ["--skip", skip.join(",")] : [];
682
- await run(paths["setup-mcp.mjs"], ["--remove", "--write", ...skipArgs], key.token, true);
683
- if ((await run(paths["setup-mcp.mjs"], ["--write", "--bridge", STABLE, ...skipArgs], key.token)).code !== 0) fail("coupling the AI apps failed; the output above says where.");
686
+ await run(paths["setup-mcp.mjs"], ["--remove", "--write", ...skipArgs], key.token, true); // hours only: nothing is skipped (no app was offered), so every door comes out
687
+ if (!doorIsOff && (await run(paths["setup-mcp.mjs"], ["--write", "--bridge", STABLE, ...skipArgs], key.token)).code !== 0) fail("coupling the AI apps failed; the output above says where.");
684
688
  const hookArgs = ["--install", "--via", STABLE];
685
689
  if (hookOn && (await run(paths["log-session.mjs"], hookArgs, key.token, false)).code !== 0) fail("installing the session hook failed; the output above says where.");
686
690
  for (const name of [...apps.filter((app) => !skip.includes(app)).map((app) => `door:${app}`), ...(hookOn ? ["session-hook"] : [])]) agreed.agree(name, "typed");
@@ -688,9 +692,10 @@ async function update() {
688
692
  // Codex installed since, or a No said at connect: the one question, asked again (or "already set").
689
693
  await offerCodex();
690
694
  await offerAntigravity();
691
- const reported = await accepted(key.url, key.token, key.device);
695
+ const reported = await accepted(key.url, key.token, key.device, doorModeAgent());
692
696
  say(reported === true ? ` ✓ WorkTrust received CLI version ${CLI_VERSION}.` : " ! Installed locally. WorkTrust could not confirm the version yet; it will be reported on the next connection.");
693
697
  await offerRebuild(previous, paths, key);
698
+ doubleDoorNotice();
694
699
  say();
695
700
  say(" Done. Quit your AI apps completely and open them again to use the updated CLI.");
696
701
  }
@@ -732,6 +737,7 @@ async function connect() {
732
737
  say();
733
738
  if (has("dry-run")) { say(" Dry run: nothing was written and nothing was sent."); return; }
734
739
  if (!(await ask("Continue?"))) { say(" Stopped. Nothing was written and nothing was sent."); return; }
740
+ const doorChoice = await chooseDoor();
735
741
  await prepareBundledRuntime();
736
742
  const agreed = await consent(); // read before anything is written, so what this run writes is not taken for an earlier yes
737
743
 
@@ -755,7 +761,9 @@ async function connect() {
755
761
  saveStableEntry();
756
762
  say(` ✓ Key kept in ${KEY_PLACE}`);
757
763
  }
758
- 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.");
764
+ saveDoorState({ mode: doorChoice, asked: new Date().toISOString() });
765
+ if (doorChoice === "hours_only") say(` ✓ Hours only: no AI app gets the WorkTrust door (${DOOR_SWITCH})`);
766
+ else 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.");
759
767
  say();
760
768
  // The old key ends now that the new one is in place (never before: a failed pairing must not leave the computer uncoupled).
761
769
  if (previous?.token) await releasePrevious(previous, pairing.prefix);
@@ -766,7 +774,7 @@ async function connect() {
766
774
  if ((await run(paths["log-session.mjs"], hookArgs, token, false, { WORKTRUST_CODEX_OFFER: "1" })).code !== 0) fail("installing the session hook failed; the output above says where.");
767
775
  // WHAT WAS AGREED HERE (0.10.30): the apps and the hook this "Continue?" covered; another account starts with none from before.
768
776
  if (switched) agreed.reset();
769
- for (const name of [...new Set(foundApps.map(labelOf).filter(Boolean))].map((app) => `door:${app}`).concat("session-hook")) agreed.agree(name, has("yes") ? "flag" : "typed");
777
+ for (const name of (doorChoice === "hours_only" ? [] : [...new Set(foundApps.map(labelOf).filter(Boolean))].map((app) => `door:${app}`)).concat("session-hook")) agreed.agree(name, has("yes") ? "flag" : "typed");
770
778
  await offerCodex();
771
779
  await offerAntigravity();
772
780
  if (switched) { say(); say(" Earlier work on this computer is not offered: it was coupled to another account before. Only work from now on goes to this account."); }
@@ -775,6 +783,7 @@ async function connect() {
775
783
  // ONE LINE, NO CHANGE (2026-10-06): Claude Code deletes what the hook measures from; `preserve --apply` keeps it, on a yes.
776
784
  const keeps = claudeKeepsDays();
777
785
  if (keeps !== null && keeps < 90) say(` Claude Code deletes sessions after ${keeps} days. Keep them: npx worktrust@latest preserve --apply`);
786
+ doubleDoorNotice();
778
787
  say(" Done. Quit your AI apps completely and open them again. This computer appears in WorkTrust");
779
788
  say(" under Sources → CLI once one of them has spoken.");
780
789
  }
@@ -830,16 +839,24 @@ async function offerHistory(paths, token, devicePem, url = MCP, rebuild = false,
830
839
  if (Number(did?.delivery?.review) > 0) say(` ${did.delivery.review} lines are waiting for review. Earlier measurements remain unchanged. Reconnecting or repeating the import does not approve them.`);
831
840
  // KEPT ON THE SERVER (0.10.27; owner, 2026-10-21): what did not arrive stays here and goes again by itself; nothing to resume by hand.
832
841
  if (Number(did?.delivery?.waiting) > 0) say(" Some batches did not reach WorkTrust yet. They stay on this computer and are sent again by themselves the next time npx worktrust or your AI app's hook runs.");
833
- // 0.10.35: a re-measure refused for older measure rules is told in WorkTrust's own words (the hook passes them on, cleaned).
834
- if (Number(did?.delivery?.refused) > 0) say(typeof did.delivery.said === "string" ? ` ${did.delivery.said.replace(/[\u0000-\u001f\u007f-\u009f]/g, " ").slice(0, 400)}` : ` WorkTrust closed an earlier run of ${did.delivery.refused} lines (it missed a batch for seven days): run npx worktrust@latest history again to send them as a new run.`);
842
+ // A REFUSAL IN WORKTRUST'S OWN WORDS (0.10.35 for older measure rules; every final refusal since 2026-10-31): the hook passes
843
+ // the door's sentence on, cleaned. Without one (a batch let go on an earlier send, or one too large for any call) the count
844
+ // alone, never a guessed reason: 0.10.35 said "it missed a batch for seven days" of a batch refused for its lines.
845
+ if (Number(did?.delivery?.refused) > 0) say(typeof did.delivery.said === "string" ? ` WorkTrust refused ${did.delivery.refused} lines for good: ${did.delivery.said.replace(/[\u0000-\u001f\u007f-\u009f]/g, " ").replace(/^history run refused:\s*/, "").slice(0, 400)}` : ` WorkTrust refused ${did.delivery.refused} lines for good; nothing of them was stored and they are not sent again.`);
846
+ // THE RUN, AS WORKTRUST HOLDS IT (2026-10-31): the hook counts each run's batches against the receipts. A run missing a batch
847
+ // is never "re-measured" (on 2026-10-30 three receipts of a run of four printed "holds all 3 batches"): WorkTrust rebuilds
848
+ // a run's days only once every batch has arrived. A batch still on its way is said above, and goes again by itself.
849
+ const staging = rebuild && did?.run && Number.isInteger(did.run.batches) && Number.isInteger(did.run.arrived) ? did.run : null;
850
+ const notWhole = staging?.whole === false;
851
+ if (notWhole && (!Number(did?.delivery?.waiting) || n(staging.refused) > 0)) say(` ✗ Not re-measured: WorkTrust holds ${staging.arrived} of ${staging.batches} batches of this run and rebuilds nothing until all of them have arrived. Nothing was replaced; your earlier lines keep counting.`);
835
852
  // A STAGED RUN (0.10.27): WorkTrust holds every batch and rebuilds the days itself once the run is whole; the receipts say what it kept.
836
- if (rebuild && n(did?.staged) > 0 && !Number(did?.delivery?.review) && !Number(did?.delivery?.waiting)) {
837
- say(` ✓ Re-measured. WorkTrust holds all ${n(did.staged)} batches (${n(did.kept)} lines) and rebuilds these days itself, every AI app together, a day counted once. Sources › Logs shows it while it works.`);
853
+ if (rebuild && staging?.whole === true && n(did?.staged) > 0 && sent.code === 0 && !Number(did?.delivery?.review) && !Number(did?.delivery?.waiting)) {
854
+ say(` ✓ Re-measured. WorkTrust holds all ${staging.batches} batches (${n(did.kept)} lines) and rebuilds these days itself, every AI app together, a day counted once. Sources › Logs shows it while it works.`);
838
855
  // WHERE IT WAITS (0.10.32): the receipt of the run's last batch names its place in WorkTrust's queue and a time; absent, nothing is guessed.
839
856
  const queued = did?.queued;
840
857
  if (queued && Number.isInteger(queued.position) && queued.position >= 1 && Number.isFinite(Number(queued.eta_minutes))) say(` queued, position ${queued.position}, about ${Math.max(1, Math.ceil(Number(queued.eta_minutes)))} min`);
841
858
  }
842
- else if (rebuild && !Number(did?.delivery?.review) && !Number(did?.delivery?.waiting)) say(sent.code === 0 ? ` ✓ Re-measured. ${outcome}` : " Not all of it arrived. Run npx worktrust again: it finishes what did not arrive, a day already rebuilt is counted once.");
859
+ else if (rebuild && !notWhole && !Number(did?.delivery?.review) && !Number(did?.delivery?.waiting)) say(sent.code === 0 ? ` ✓ Re-measured. ${outcome}` : " Not all of it arrived. Run npx worktrust again: it finishes what did not arrive, a day already rebuilt is counted once.");
843
860
  else if (!rebuild) say(sent.code === 0 ? " ✓ Sent as history. Activity is recorded with its origin; independent verification and passport publication are separate. A day WorkTrust already holds is kept once." : " Not all of it arrived. Run npx worktrust history again: a line already received is kept once.");
844
861
  if (did && Number(did.measuredSeconds) > 0) say(` Measured by WorkTrust: ${(Number(did.measuredSeconds) / 3600).toFixed(1)} h for what this send stored${n(did.corrected) > 0 ? ` (${n(did.corrected)} lines corrected: a figure sent beside the timeline differed)` : ""}.`);
845
862
  }
@@ -988,12 +1005,15 @@ async function offerExport(paths, key, path) {
988
1005
  if (counted.code !== 0 || !report) { say(` ${counted.out.trim().split("\n").filter(Boolean).pop() ?? "export: it could not be read"}. Nothing was sent.`); return false; }
989
1006
  const product = EXPORT_PRODUCT[report.vendor] ?? report.vendor, connector = EXPORT_CONNECTOR[report.vendor] ?? report.vendor;
990
1007
  if (!report.days) { say(` ${product} export · ${report.conversations} conversations, none with a clock to place: nothing to send.`); return true; }
991
- say(` ${product} export · ${report.conversations} conversations · ${report.days} days · ${String(report.first).slice(0, 7)} … ${String(report.last).slice(0, 7)}`);
1008
+ const cuts = Array.isArray(report.cut) ? report.cut : [];
1009
+ say(` ${product} export${cuts.length > 0 ? ", cut off" : ""} · ${report.conversations} conversations · ${report.days} days · ${String(report.first).slice(0, 7)} … ${String(report.last).slice(0, 7)}`);
1010
+ // A DOWNLOAD CUT OFF (2026-10-31): what the archive held whole before the cut is read, and the person is told it is not the whole export.
1011
+ for (const cut of cuts) say(` The archive was cut off after ${cut.last} (part ${cut.parts}); ${report.conversations} conversations read. Nothing past the cut is read: this is not the whole export. Download it again for the rest; a line already received is kept once.`);
992
1012
  say(" WorkTrust reconstructs the hours from the export's own clocks when they arrive: shown with their origin, never verified hours. Never a title or a message.");
993
1013
  // LEFT OUT AND COUNTED (0.10.18): a conversation whose kept fields outgrew the reader's budget is passed over, never the export.
994
1014
  if (report.oversized > 0) say(` ${report.oversized} conversation${report.oversized === 1 ? "" : "s"} too large to read ${report.oversized === 1 ? "is" : "are"} left out; the rest is read.`);
995
1015
  if (has("dry-run")) { say(" Dry run: nothing was sent."); return false; }
996
- if (!has("history") && !(await ask("Send it as history (reconstructed hours per day; never text)?", false))) { say(` Not sent. Send it later with: npx worktrust history --export ${path}`); return false; }
1016
+ if (!has("history") && !(await ask(cuts.length > 0 ? "Send what was read before the cut as history (reconstructed hours per day; never text)?" : "Send it as history (reconstructed hours per day; never text)?", false))) { say(` Not sent. Send it later with: npx worktrust history --export ${path}`); return false; }
997
1017
  const sent = await run(paths["log-session.mjs"], ["--history", "--export", path], key.token, true, env);
998
1018
  say(sent.code === 0 ? ` ✓ Sent as history. It shows in WorkTrust as ${product}, reconstructed, never as verified hours; a line already received is kept once.` : ` Not all of it arrived. Run npx worktrust history --export ${path} again: a line already received is kept once.`);
999
1019
  if (sent.code !== 0) return false;
@@ -1274,6 +1294,7 @@ async function status() {
1274
1294
  say(key ? ` Key: in ${KEY_PLACE}, ${key.device ? "bound to this computer, " : ""}last renewed ${String(key.renewedAt ?? "").slice(0, 10) || "never"}` : " Key: not on this computer (or written into the apps' settings with --direct)");
1275
1295
  if (key) say(key.account ? ` Account: ${key.account}${key.coupledAt ? `, coupled ${String(key.coupledAt).slice(0, 10)}` : ""}` : " Account: not recorded (coupled by an older version; `npx worktrust connect` records it)");
1276
1296
  say(sessionHookHere() ? " Session hook: installed" : " Session hook: not installed");
1297
+ say(` AI work lines: ${doorLine()}`);
1277
1298
  // A TRANSCRIPT THE HOOK COULD NOT READ (0.10.32): the count of its last run that had any, never which file; WorkTrust has the count too.
1278
1299
  { let unread = null; try { unread = JSON.parse(readFileSync(join(HOME_DIR, "sessions.json"), "utf8")).__unreadable ?? null; } catch { /* no state yet */ }
1279
1300
  if (Number(unread?.count) > 0) say(` Transcripts: ${unread.count} could not be read on ${String(unread.at).slice(0, 10)}; their days are not measured until they can be (WorkTrust was told the count, nothing else)`); }
@@ -1362,6 +1383,107 @@ async function gitCommits() {
1362
1383
  process.exitCode = await gitMain(sub, { say, ask, send, consent: await consent(), salt: archiveSalt(), dryRun: has("dry-run") });
1363
1384
  }
1364
1385
 
1386
+ /**
1387
+ * HOURS ONLY, OR ALSO WORK LINES (owner, 2026-10-31, after an engineer: "every session loads ~600 tokens from the WorkTrust
1388
+ * MCP"). The passport's hours come from the session hook, which reads the AI apps' own transcripts and needs no door; the
1389
+ * door adds only the AI's own `log_work` lines, and loads its instruction (and, in clients that load every tool, its tool
1390
+ * definitions) into every session. So the person chooses, here, and the choice is kept in ~/.worktrust/door.json (600):
1391
+ * `mcp off` takes the door out of every app and `update` leaves it out; `mcp on` puts it back. The hook runs in both, and
1392
+ * names the mode to WorkTrust beside the CLI version (a closed word in its user-agent), so a pause in work lines reads as
1393
+ * the person's choice. Turning the door on sends nothing from the off period: work lines are live only, and earlier work
1394
+ * goes only through `history`, on the person's yes.
1395
+ */
1396
+ const DOOR_FILE = join(HOME_DIR, "door.json");
1397
+ const DOOR_MODES = ["hours_only", "work_lines"];
1398
+ const DOOR_SWITCH = "npx worktrust mcp on / mcp off";
1399
+ function doorState() { try { const state = JSON.parse(readPrivateFile(DOOR_FILE) ?? "null"); return DOOR_MODES.includes(state?.mode) ? state : null; } catch { return null; } }
1400
+ function saveDoorState(next) { if (has("dry-run")) return; try { ensureHome(); writePrivateFile(DOOR_FILE, `${JSON.stringify({ ...(doorState() ?? {}), ...next, ...(next.mode && next.mode !== doorState()?.mode ? { since: new Date().toISOString() } : {}) })}\n`); } catch { /* not kept: asked again next time */ } }
1401
+ const doorOff = () => doorState()?.mode === "hours_only";
1402
+ /** The mode and the moment it last changed here (whole seconds), so the last change wins against a wish from Sources. */
1403
+ const doorSaid = () => { const state = doorState(); if (!state) return null; const at = Math.floor(Date.parse(state.since ?? state.asked ?? "") / 1000); return Number.isFinite(at) && at > 0 ? `${state.mode}.${at}` : state.mode; };
1404
+ const doorModeEnv = () => (doorSaid() ? { WORKTRUST_DOOR_MODE: doorSaid() } : {});
1405
+ const doorModeAgent = () => (doorSaid() ? ` worktrust-mode/${doorSaid()}` : "");
1406
+ const doorLine = () => { const state = doorState(); return state ? `${state.mode === "hours_only" ? "off (hours only)" : "on"}${state.since ? ` since ${String(state.since).slice(0, 10)}` : ""}` : "on (not chosen yet: npx worktrust update asks once)"; };
1407
+ /** The first question: Enter, --yes and a closed terminal keep the door, as before; --hours-only and --work-lines say it in advance. */
1408
+ async function chooseDoor() {
1409
+ if (has("hours-only")) return "hours_only";
1410
+ if (has("work-lines")) return "work_lines";
1411
+ say();
1412
+ say(" How should your AI apps work with WorkTrust?");
1413
+ say(" 1 Hours only: the session hook measures your hours; nothing of WorkTrust loads into your sessions");
1414
+ say(" 2 Also let your AI log finished work: the WorkTrust door in each app, about 40 tokens per session");
1415
+ if (has("yes") || has("dry-run") || !process.stdin.isTTY) { say(` Kept: 2, the door, as before. Switch any time: ${DOOR_SWITCH}`); return "work_lines"; }
1416
+ const prompt = createInterface({ input: process.stdin, output: process.stdout });
1417
+ const answer = (await prompt.question(" Which one? [1/2, Enter = 2] ")).trim();
1418
+ prompt.close();
1419
+ return answer === "1" ? "hours_only" : "work_lines";
1420
+ }
1421
+ /**
1422
+ * TWO DOORS IN ONE CLAUDE CODE (owner, 2026-10-31). Claude Code also loads the connectors of the person's claude.ai account,
1423
+ * so a WorkTrust connector added there arrives beside the local door and its instruction loads twice. The local door is the
1424
+ * one to keep (it carries this computer's device key); a claude.ai connector is managed only at claude.ai, so the CLI says
1425
+ * where, once. Claude Code records the connectors it has EVER connected (`claudeAiMcpEverConnected`), not the ones on now,
1426
+ * and asking `claude mcp list` would start every server; so this is a notice, never a removal and never a claim.
1427
+ */
1428
+ function claudeAiDoor() { try { return (JSON.parse(readFileSync(join(homedir(), ".claude.json"), "utf8")).claudeAiMcpEverConnected ?? []).find((name) => typeof name === "string" && /^claude\.ai .*worktrust/i.test(name)) ?? null; } catch { return null; } }
1429
+ function doubleDoorNotice(always = false) {
1430
+ const connector = claudeAiDoor();
1431
+ if (!connector || (!always && doorState()?.noticed)) return;
1432
+ say();
1433
+ say(doorOff() ? ` ! Claude Code has also been connected to your claude.ai WorkTrust connector ("${connector}"): while it is on there, it still loads in your sessions.`
1434
+ : ` ! Claude Code has also been connected to your claude.ai WorkTrust connector ("${connector}"): with the local door, WorkTrust may load twice. Keep the local one (it carries this computer's key).`);
1435
+ say(" Remove the other at https://claude.ai/customize/connectors (the CLI cannot change your claude.ai account).");
1436
+ if (!always) saveDoorState({ noticed: new Date().toISOString() });
1437
+ }
1438
+ /**
1439
+ * THE OWNER'S SWITCH IN SOURCES, DONE HERE (owner, 2026-10-31). At a session's start or end the hook asks WorkTrust, with
1440
+ * this computer's signed key, whether the owner asked for a mode (at most every ten minutes, three seconds at most, silent
1441
+ * on any failure). A wish newer than the last choice made on this computer is done on WorkTrust's own entries in the AI
1442
+ * apps, recorded in door.json and reported back beside the version, which settles it; a choice made here later wins.
1443
+ * Nothing is printed: the hook's output belongs to the AI app.
1444
+ */
1445
+ async function followDoorWish(key) {
1446
+ const state = doorState();
1447
+ if (!key.device || (state?.checkedAt && Date.now() - Date.parse(state.checkedAt) < 10 * 60_000)) return;
1448
+ let wish = null;
1449
+ try {
1450
+ const url = new URL("/api/cli/door", key.url).href, body = "{}";
1451
+ const response = await fetch(url, { method: "POST", headers: { "content-type": "application/json", authorization: `Bearer ${key.token}`, "user-agent": `worktrust-cli/${CLI_VERSION}`, ...proof(key.device, url, body) }, body, redirect: "error", signal: AbortSignal.timeout(3000) });
1452
+ if (response.ok) wish = await response.json();
1453
+ } catch { /* offline: asked again next time */ }
1454
+ saveDoorState({ checkedAt: new Date().toISOString() });
1455
+ if (!DOOR_MODES.includes(wish?.mode) || wish.mode === state?.mode || !(Date.parse(wish.at) > Date.parse(state?.since ?? state?.asked ?? 0))) return;
1456
+ const paths = await scripts();
1457
+ if (wish.mode === "work_lines") { await prepareBundledRuntime(); await run(paths["setup-mcp.mjs"], ["--remove", "--write"], key.token, true); }
1458
+ const done = await run(paths["setup-mcp.mjs"], wish.mode === "hours_only" ? ["--remove", "--write"] : ["--write", "--bridge", STABLE], key.token, true);
1459
+ if (done.code !== 0) return;
1460
+ saveDoorState({ mode: wish.mode, asked: state?.asked ?? new Date().toISOString() });
1461
+ await accepted(key.url, key.token, key.device, doorModeAgent());
1462
+ }
1463
+ async function doorCommand(sub) {
1464
+ say();
1465
+ if (sub !== "off" && sub !== "on") { say(` AI work lines on this computer: ${doorLine()}`); say(" Your hours are measured by the session hook either way."); say(` ${DOOR_SWITCH}`); doubleDoorNotice(true); return; }
1466
+ const key = await freshKey();
1467
+ if (!key) fail("this computer has no WorkTrust key file yet. Run npx worktrust connect.");
1468
+ const paths = await scripts();
1469
+ if (sub === "off") {
1470
+ if ((await run(paths["setup-mcp.mjs"], ["--remove", "--write"], key.token)).code !== 0) fail("taking the door out failed; the output above says where. Nothing was recorded.");
1471
+ saveDoorState({ mode: "hours_only", asked: doorState()?.asked ?? new Date().toISOString() });
1472
+ say(" ✓ Hours only: the WorkTrust door is out of every AI app here, and update leaves it out.");
1473
+ say(" The session hook keeps measuring your hours. npx worktrust mcp on brings the door back.");
1474
+ } else {
1475
+ await prepareBundledRuntime(); ensureHome(); saveStableEntry();
1476
+ await run(paths["setup-mcp.mjs"], ["--remove", "--write"], key.token, true);
1477
+ if ((await run(paths["setup-mcp.mjs"], ["--write", "--bridge", STABLE], key.token)).code !== 0) fail("coupling the AI apps failed; the output above says where. Nothing was recorded.");
1478
+ saveDoorState({ mode: "work_lines", asked: doorState()?.asked ?? new Date().toISOString() });
1479
+ say(" ✓ The WorkTrust door is back: your AI can log finished work from now on. Nothing from the time it was off is sent.");
1480
+ }
1481
+ const reported = await accepted(key.url, key.token, key.device, doorModeAgent());
1482
+ say(reported === true ? " ✓ WorkTrust was told the mode (shown under Sources, Devices)." : " ! Kept here; WorkTrust is told on the next connection.");
1483
+ doubleDoorNotice();
1484
+ say(" Quit your AI apps completely and open them again.");
1485
+ }
1486
+
1365
1487
  function help() {
1366
1488
  say("WorkTrust: couple this computer to your record. Metadata only.");
1367
1489
  say();
@@ -1397,6 +1519,10 @@ function help() {
1397
1519
  say(" days this computer's own sessions lack, reconstructed, never verified hours (asks first)");
1398
1520
  say(" worktrust disconnect take WorkTrust out of every AI app here (asks first)");
1399
1521
  say(" worktrust status what is coupled here");
1522
+ say(" worktrust mcp off hours only: the WorkTrust door out of every AI app here, nothing of it in your sessions;");
1523
+ say(" the session hook keeps measuring your hours, and update leaves the door out");
1524
+ say(" worktrust mcp on the door back in, so your AI can log finished work (about 40 tokens per session)");
1525
+ say(" worktrust mcp which of the two this computer is in");
1400
1526
  say(" worktrust protect-key after update: move credential protection into the OS vault (asks first)");
1401
1527
  say(" worktrust orchestration report --file recording.jsonl inspect local agent metadata; sends nothing");
1402
1528
  say(" worktrust mod the WorkTrust mod for Claude Code: what it counts, and whether it is on");
@@ -1425,7 +1551,9 @@ if (Number(process.versions.node.split(".")[0]) < 18) fail("needs Node 18 or lat
1425
1551
  const AGENT_ENV = ["CLAUDECODE", "CLAUDE_CODE_ENTRYPOINT", "CODEX_SANDBOX", "CODEX_CI", "GEMINI_CLI", "CURSOR_AGENT", "OPENCODE", "CLINE_ACTIVE", "AIDER_CHAT", "ANTIGRAVITY_AGENT", "WINDSURF_AGENT"];
1426
1552
  const PERSON_ONLY = new Set(["default", "connect", "update", "history", "disconnect", "preserve", "codex", "antigravity", "sources", "web", "import", "orchestration", "mod", "protect-key", "git"]);
1427
1553
  const agentShell = AGENT_ENV.find((name) => process.env[name] && process.env[name] !== "0");
1428
- if (agentShell && PERSON_ONLY.has(command)) {
1554
+ // `mcp off` and `mcp on` change what this computer's AI apps load: the person's. Bare `mcp` stays the bridge the apps start.
1555
+ const doorSwitch = command === "mcp" && ["off", "on"].includes(args[args.indexOf("mcp") + 1]);
1556
+ if (agentShell && (PERSON_ONLY.has(command) || doorSwitch)) {
1429
1557
  say();
1430
1558
  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}).`);
1431
1559
  say(" Nothing was read, sent or changed. See AGENTS.md in the package: https://www.npmjs.com/package/worktrust");
@@ -1461,6 +1589,7 @@ if (!["version", "help", "preserve"].includes(command)) {
1461
1589
  }
1462
1590
  if (command === "version") say(CLI_VERSION);
1463
1591
  else if (command === "default") { if (keyStore.load()) await again(); else await connect(); }
1592
+ else if (command === "mcp" && (doorSwitch || args[args.indexOf("mcp") + 1] === "status" || (process.stdin.isTTY && process.stdout.isTTY))) await doorCommand(args[args.indexOf("mcp") + 1]);
1464
1593
  else if (command === "mcp") await bridge();
1465
1594
  else if (command === "hook") await hook();
1466
1595
  else if (command === "connect") await connect();