worktrust 0.10.8 → 0.10.10
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +65 -6
- package/chat-exports.mjs +182 -0
- package/count-behaviour.mjs +13 -57
- package/log-session.mjs +202 -18
- package/package.json +2 -1
- package/preserve-lines.mjs +5 -2
- package/preserve.mjs +45 -11
- package/worktrust.mjs +146 -34
package/README.md
CHANGED
|
@@ -85,7 +85,12 @@ npx worktrust@latest history send this computer's earlier sessions later (
|
|
|
85
85
|
npx worktrust@latest history --rebuild re-measure them with the current rules; WorkTrust replaces this computer's
|
|
86
86
|
earlier lines day by day, never counting a day twice (shows the plan, asks first)
|
|
87
87
|
npx worktrust@latest history --from-archive [dir] send what your local archive holds of sessions your AI apps
|
|
88
|
-
already deleted, marked as from your archive
|
|
88
|
+
already deleted, marked as from your archive: a day this computer's key signed as
|
|
89
|
+
measured, every other day as reconstructed (shows the plan, asks first)
|
|
90
|
+
npx worktrust@latest history --export <path> a ChatGPT or Claude data export (the zip, its folder or conversations.json)
|
|
91
|
+
as history: hours reconstructed from its clocks, never verified (shows the plan, asks first)
|
|
92
|
+
npx worktrust@latest history --from-folder <dir> your own copy of an AI app's session folder (a backed-up ~/.claude/projects,
|
|
93
|
+
~/.codex/sessions): the days this computer's sessions lack, reconstructed (asks first)
|
|
89
94
|
npx worktrust codex let Codex wake the session hook (asks first)
|
|
90
95
|
npx worktrust antigravity let Antigravity wake the session hook (asks first)
|
|
91
96
|
npx worktrust@latest status what is coupled here
|
|
@@ -226,11 +231,12 @@ sent stand as they were measured then, and sending the sessions again would coun
|
|
|
226
231
|
does not name its stretch, so WorkTrust cannot tell it from the one that arrives.
|
|
227
232
|
|
|
228
233
|
`npx worktrust@latest history --from-archive` (0.8.0) is for the sessions an AI app has already deleted (Claude
|
|
229
|
-
Code's default is 30 days). It sends what your local archive (`preserve --archive`) holds of them, and only that:
|
|
230
|
-
|
|
231
|
-
|
|
232
|
-
|
|
233
|
-
|
|
234
|
+
Code's default is 30 days). It sends what your local archive (`preserve --archive`) holds of them, and only that:
|
|
235
|
+
days of sessions no longer on the computer, each line marked as coming from your archive. One rule (2026-10-10):
|
|
236
|
+
a day signed by this computer's device key goes as it was measured; every other day (unsigned, signed by the local
|
|
237
|
+
archive key, or by another computer's key) goes as **reconstructed**, and the plan says how many of each. It refuses,
|
|
238
|
+
and sends nothing, when the archive does not verify or when WorkTrust does not yet accept the mark. It shows the plan
|
|
239
|
+
first and asks once; Enter is No. Such lines are history, like any import: never verified hours.
|
|
234
240
|
|
|
235
241
|
`npx worktrust@latest history --rebuild` re-measures every session still on this computer with the current rules and
|
|
236
242
|
sends them with one difference: WorkTrust **replaces** this computer's earlier lines, day by day.
|
|
@@ -254,6 +260,59 @@ sends them with one difference: WorkTrust **replaces** this computer's earlier l
|
|
|
254
260
|
and the same version updated again offers nothing. The command cannot read your record, so it is an offer, not a
|
|
255
261
|
finding.
|
|
256
262
|
|
|
263
|
+
## A web chat's data export
|
|
264
|
+
|
|
265
|
+
`npx worktrust@latest history --export <path>` (0.10.10) brings a ChatGPT data export (Settings → Data controls →
|
|
266
|
+
Export data) or a Claude data export (Settings → Privacy → Export data) onto your record as history, so years of
|
|
267
|
+
browser chats appear with their months, days and rhythm. The path is the zip the vendor sent you, the folder it was
|
|
268
|
+
unpacked into, or `conversations.json` itself; the vendor is told by the file's shape. Of the zip only
|
|
269
|
+
`conversations.json` is opened: the profile, memories and files beside it are never inflated.
|
|
270
|
+
|
|
271
|
+
- **What goes.** Per conversation and day: a neutral line (`A conversation in ChatGPT`, `A conversation in Claude on
|
|
272
|
+
the web`), the seconds between the messages' clocks counted the way a measured day is (a pause over five minutes is
|
|
273
|
+
not work; a day is cut at eight hours), your own turns as a count, the model's name where the export carries one, when
|
|
274
|
+
it began and ended, and a stable name made of the conversation's id and the day, so the same export sent twice, or
|
|
275
|
+
from two computers, is each line once. Never a title, never a message, never tokens (the export carries none and none
|
|
276
|
+
are estimated).
|
|
277
|
+
- **What it counts as.** Hours **reconstructed**, shown on your record with their origin and never in your verified
|
|
278
|
+
hours: an export file can be edited before it is read, and no device key witnessed those hours. WorkTrust holds this
|
|
279
|
+
at the door and in the database, whatever the sender claims.
|
|
280
|
+
- **How it asks.** The plan first (the product, conversations, days, reconstructed hours, first and last month), then
|
|
281
|
+
one question; Enter is No; `--dry-run` shows the plan and stops. On a coupled computer the bare `npx worktrust` looks
|
|
282
|
+
in your Downloads folder (its top level only) for such an export it has not sent, offers it the same way, once, and
|
|
283
|
+
remembers your answer by the file's digest, never by a conversation.
|
|
284
|
+
- **The export replaces.** On the days the export covers, its lines count and the earlier lines of that product a
|
|
285
|
+
connector brought in (an AI signed in on the web, which selects what it reports) are withdrawn and kept, each with a
|
|
286
|
+
correction row, so a day counts once; the command says how many. A connector line that arrives later for a day the
|
|
287
|
+
export covers is held. Lines an AI app reported earlier under no product may describe the same conversations: the
|
|
288
|
+
command says how many lie on those days and asks once, `Also withdraw N earlier lines an AI app reported for these
|
|
289
|
+
days?`; Enter is No, `--yes` keeps No, `--dry-run` sends nothing, and only a typed yes or `--withdraw-unknown` said
|
|
290
|
+
in advance withdraws exactly those lines on exactly those days, the same way, never deleting. Never touched: another
|
|
291
|
+
product, your own measured sessions, a private line, a day the export does not cover.
|
|
292
|
+
|
|
293
|
+
## A copied session folder, and the local archive key
|
|
294
|
+
|
|
295
|
+
**One rule (2026-10-10).** Verified hours are what this computer's coupled key witnessed: the live session hook, the
|
|
296
|
+
AI apps' own folders read at history time, and an archive day signed by this computer's device key. Everything else
|
|
297
|
+
that carries clocks is **reconstructed**: shown on your record with its origin, never in your verified hours.
|
|
298
|
+
|
|
299
|
+
`npx worktrust@latest history --from-folder <dir>` brings in your own copy of an AI app's session folder: a backed-up
|
|
300
|
+
`~/.claude/projects`, `~/.codex/sessions`, or an Antigravity brain folder. It is read with the same readers and the
|
|
301
|
+
same clock as the live folders, never the live folders themselves (a path that is, or holds, one of them is refused).
|
|
302
|
+
Each day is named exactly as the live folder would name it, so a stretch this computer's own sessions already hold is
|
|
303
|
+
skipped (they win), and the same copy sent twice is each line once. What travels: the copy's own counts (tokens, your
|
|
304
|
+
turns, the model, the evidence kinds), as reconstructed hours, titled as from a copied session folder; not the hours in
|
|
305
|
+
layers, which say what a measured day's seconds were. The plan first, one question, Enter is No; `--dry-run` sends
|
|
306
|
+
nothing.
|
|
307
|
+
|
|
308
|
+
`preserve --archive` on a computer that is not coupled now signs each day's root with a **local archive key**
|
|
309
|
+
(`~/.worktrust/archive-key.json`, only you can read it), made once and said in one line. It needs no account and no
|
|
310
|
+
network and never leaves this computer. It is continuity, not proof of time: a day it signed can be told from an edit,
|
|
311
|
+
and the chain stays one computer's when you couple later (the device key then signs new days, and either key may seal
|
|
312
|
+
a day it sealed before), but such a day reaches WorkTrust as reconstructed. It is never offered as the device key at
|
|
313
|
+
pairing: `connect` always mints a fresh pair, because a private key that lived on disk before the pairing would weaken
|
|
314
|
+
the proof of possession the pairing binds, for nothing your record would gain.
|
|
315
|
+
|
|
257
316
|
## Where the key lives, and why it only works here
|
|
258
317
|
|
|
259
318
|
The key is kept in **one file only you can read**: `~/.worktrust/key.json` (mode 600, in a folder of
|
package/chat-exports.mjs
ADDED
|
@@ -0,0 +1,182 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* A WEB CHAT'S DATA EXPORT, READ ONCE FOR TWO READERS (CLI 0.10.10, owner 2026-10-10). ChatGPT (Settings → Data
|
|
3
|
+
* controls → Export data) and Claude on the web (Settings → Privacy → Export data) each hand a person a zip with a
|
|
4
|
+
* `conversations.json` in it. The counter reads it for signals; the session hook reads it as HISTORY, so a person's
|
|
5
|
+
* years of browser chats appear on their record. One reader here, imported by both, so the two cannot drift.
|
|
6
|
+
*
|
|
7
|
+
* WHAT IT NEVER DOES. It opens nothing of the zip but `conversations.json` (a vendor's export carries the account's
|
|
8
|
+
* profile, memories and files beside it: those are never inflated). It hands the text to the counter's rubric on this
|
|
9
|
+
* computer, as it always did, and to the hook it hands clocks, roles and a model name only: the conversation's title
|
|
10
|
+
* and every message stay here. Hours from an export are RECONSTRUCTED, never measured: the file can be edited before
|
|
11
|
+
* it is read and no device key witnessed it, so the record shows them with their origin and never in verified hours.
|
|
12
|
+
*
|
|
13
|
+
* readExport(path) { vendor, conversations, digest } a folder holding conversations.json, the file, or the zip
|
|
14
|
+
* exportSessions(path, …) one session per conversation, in the transcript's own shape (type, timestamp, message)
|
|
15
|
+
* exportRef(vendor, id, day) the stretch's stable name: the same on any computer, so a second send is the same line
|
|
16
|
+
* findExports(dir) the exports lying in one folder (its top level only), by path and vendor
|
|
17
|
+
*/
|
|
18
|
+
import { createHash } from "node:crypto";
|
|
19
|
+
import { existsSync, openSync, readSync, closeSync, readFileSync, readdirSync, statSync } from "node:fs";
|
|
20
|
+
import { homedir } from "node:os";
|
|
21
|
+
import { basename, join } from "node:path";
|
|
22
|
+
import { inflateRawSync } from "node:zlib";
|
|
23
|
+
|
|
24
|
+
/** The two vendors, by the client name the door reads as their product (chatgpt → chatgpt_web, claude-web → claude_web). */
|
|
25
|
+
export const EXPORT_CLIENTS = ["chatgpt", "claude-web"];
|
|
26
|
+
/** The neutral line each vendor's conversation is filed under: never the conversation's own title. */
|
|
27
|
+
export const EXPORT_TITLES = { chatgpt: "A conversation in ChatGPT", "claude-web": "A conversation in Claude on the web" };
|
|
28
|
+
const PRODUCT_NAMES = { chatgpt: "ChatGPT", "claude-web": "Claude on the web" };
|
|
29
|
+
export const exportProductName = (vendor) => PRODUCT_NAMES[vendor] ?? vendor;
|
|
30
|
+
const FILE = "conversations.json";
|
|
31
|
+
const expand = (path) => String(path).replace(/^~(?=\/|$)/, homedir());
|
|
32
|
+
|
|
33
|
+
/**
|
|
34
|
+
* A ZIP, READ FOR ONE ENTRY. No dependency: the end-of-central-directory record is found from the back, the central
|
|
35
|
+
* directory walked for the one name, and only that entry's bytes inflated (stored or deflated; anything else, and a
|
|
36
|
+
* zip64 archive, is refused by name). Nothing else in the archive is touched.
|
|
37
|
+
*/
|
|
38
|
+
function zipEntry(path, wanted) {
|
|
39
|
+
const size = statSync(path).size;
|
|
40
|
+
const fd = openSync(path, "r");
|
|
41
|
+
const readAt = (at, length) => { const buffer = Buffer.alloc(length); const got = readSync(fd, buffer, 0, length, at); return buffer.subarray(0, got); };
|
|
42
|
+
try {
|
|
43
|
+
const tailLength = Math.min(size, 65_557);
|
|
44
|
+
const tail = readAt(size - tailLength, tailLength);
|
|
45
|
+
let eocd = -1;
|
|
46
|
+
for (let at = tail.length - 22; at >= 0; at -= 1) if (tail.readUInt32LE(at) === 0x06054b50) { eocd = at; break; }
|
|
47
|
+
if (eocd < 0) throw Error(`not a zip archive: ${path}`);
|
|
48
|
+
const entries = tail.readUInt16LE(eocd + 10), directorySize = tail.readUInt32LE(eocd + 12), directoryAt = tail.readUInt32LE(eocd + 16);
|
|
49
|
+
if (entries === 0xffff || directorySize === 0xffffffff || directoryAt === 0xffffffff) throw Error(`a zip64 archive is not read: ${path}`);
|
|
50
|
+
const directory = readAt(directoryAt, directorySize);
|
|
51
|
+
let at = 0;
|
|
52
|
+
for (let index = 0; index < entries && at + 46 <= directory.length; index += 1) {
|
|
53
|
+
if (directory.readUInt32LE(at) !== 0x02014b50) throw Error(`a damaged zip archive: ${path}`);
|
|
54
|
+
const method = directory.readUInt16LE(at + 10), compressed = directory.readUInt32LE(at + 20), uncompressed = directory.readUInt32LE(at + 24);
|
|
55
|
+
const nameLength = directory.readUInt16LE(at + 28), extraLength = directory.readUInt16LE(at + 30), commentLength = directory.readUInt16LE(at + 32), localAt = directory.readUInt32LE(at + 42);
|
|
56
|
+
const name = directory.toString("utf8", at + 46, at + 46 + nameLength);
|
|
57
|
+
at += 46 + nameLength + extraLength + commentLength;
|
|
58
|
+
if (basename(name) !== wanted || name.endsWith("/")) continue;
|
|
59
|
+
if (compressed === 0xffffffff || uncompressed === 0xffffffff || localAt === 0xffffffff) throw Error(`a zip64 entry is not read: ${path}`);
|
|
60
|
+
const local = readAt(localAt, 30);
|
|
61
|
+
if (local.readUInt32LE(0) !== 0x04034b50) throw Error(`a damaged zip archive: ${path}`);
|
|
62
|
+
const dataAt = localAt + 30 + local.readUInt16LE(26) + local.readUInt16LE(28);
|
|
63
|
+
const bytes = readAt(dataAt, compressed);
|
|
64
|
+
if (method === 0) return bytes;
|
|
65
|
+
if (method === 8) return inflateRawSync(bytes);
|
|
66
|
+
throw Error(`${wanted} in ${path} is compressed in a way this reader does not open (method ${method})`);
|
|
67
|
+
}
|
|
68
|
+
return null;
|
|
69
|
+
} finally { closeSync(fd); }
|
|
70
|
+
}
|
|
71
|
+
|
|
72
|
+
/** The bytes of `conversations.json`, wherever the given path keeps them: a folder, the file itself, or the vendor's zip. */
|
|
73
|
+
function exportBytes(given) {
|
|
74
|
+
const path = expand(given);
|
|
75
|
+
let stat; try { stat = statSync(path); } catch { throw Error(`export not found: ${given}`); }
|
|
76
|
+
if (stat.isDirectory()) { const file = join(path, FILE); if (!existsSync(file)) throw Error(`no ${FILE} in ${given}`); return { bytes: readFileSync(file), path: file }; }
|
|
77
|
+
if (/\.zip$/i.test(path)) { const bytes = zipEntry(path, FILE); if (!bytes) throw Error(`no ${FILE} in ${given}`); return { bytes, path }; }
|
|
78
|
+
return { bytes: readFileSync(path), path };
|
|
79
|
+
}
|
|
80
|
+
|
|
81
|
+
/** Which vendor wrote these conversations, by their shape alone; mixed or unknown shapes are refused, never guessed. */
|
|
82
|
+
export function vendorOf(conversations) {
|
|
83
|
+
if (!Array.isArray(conversations) || conversations.length === 0) return null;
|
|
84
|
+
const shapes = new Set(conversations.map((c) => (c && typeof c === "object" && c.mapping && typeof c.mapping === "object" ? "chatgpt" : c && typeof c === "object" && Array.isArray(c.chat_messages) ? "claude-web" : "unknown")));
|
|
85
|
+
return shapes.size === 1 ? [...shapes][0] : null;
|
|
86
|
+
}
|
|
87
|
+
|
|
88
|
+
/** One export, read: its vendor by shape, its conversations, and the digest of its bytes (what `sent` is remembered by). */
|
|
89
|
+
export function readExport(given, expect = null) {
|
|
90
|
+
const { bytes, path } = exportBytes(given);
|
|
91
|
+
let conversations; try { conversations = JSON.parse(bytes.toString("utf8")); } catch { throw Error(`export unreadable: ${path}`); }
|
|
92
|
+
if (!Array.isArray(conversations)) throw Error(`${path} must contain an array of conversations`);
|
|
93
|
+
const vendor = vendorOf(conversations);
|
|
94
|
+
if (conversations.length > 0 && !vendor) throw Error(`${path} is neither a ChatGPT nor a Claude export (or mixes the two)`);
|
|
95
|
+
if (expect && vendor && vendor !== expect) throw Error(`${path} is a ${exportProductName(vendor)} export, not ${exportProductName(expect)}`);
|
|
96
|
+
return { vendor: vendor ?? expect, conversations, digest: createHash("sha256").update(bytes).digest("hex"), path };
|
|
97
|
+
}
|
|
98
|
+
|
|
99
|
+
/** The kept branch of one ChatGPT conversation, oldest first: from `current_node` up through the parents. */
|
|
100
|
+
function chatgptBranch(conversation) {
|
|
101
|
+
const mapping = conversation?.mapping && typeof conversation.mapping === "object" ? conversation.mapping : {};
|
|
102
|
+
const branch = [];
|
|
103
|
+
const seen = new Set();
|
|
104
|
+
for (let id = conversation?.current_node; id && mapping[id] && !seen.has(id); id = mapping[id].parent) { seen.add(id); branch.push(mapping[id]); }
|
|
105
|
+
return branch.reverse();
|
|
106
|
+
}
|
|
107
|
+
/** A ChatGPT conversation's lines: the person and the model only; system prompts, tools and what the app hides are neither. */
|
|
108
|
+
function chatgptLines(conversation) {
|
|
109
|
+
const lines = [];
|
|
110
|
+
for (const node of chatgptBranch(conversation)) {
|
|
111
|
+
const m = node?.message;
|
|
112
|
+
const role = m?.author?.role;
|
|
113
|
+
if ((role !== "user" && role !== "assistant") || m?.metadata?.is_visually_hidden_from_conversation) continue;
|
|
114
|
+
const parts = Array.isArray(m?.content?.parts) ? m.content.parts.filter((part) => typeof part === "string") : [];
|
|
115
|
+
const text = parts.join("\n");
|
|
116
|
+
if (text.length === 0) continue;
|
|
117
|
+
const seconds = Number(m?.create_time ?? conversation?.create_time);
|
|
118
|
+
const at = Number.isFinite(seconds) && seconds > 0 ? new Date(seconds * 1000).toISOString() : null;
|
|
119
|
+
const model = typeof m?.metadata?.model_slug === "string" ? m.metadata.model_slug : undefined;
|
|
120
|
+
lines.push({ type: role === "user" ? "user" : "assistant", timestamp: at, message: { ...(role === "assistant" && model ? { model } : {}), content: [{ type: "text", text }] } });
|
|
121
|
+
}
|
|
122
|
+
return lines;
|
|
123
|
+
}
|
|
124
|
+
/** A claude.ai conversation's messages in the transcript's own shape; the export names no model. */
|
|
125
|
+
function claudeLines(conversation) {
|
|
126
|
+
const messages = Array.isArray(conversation?.chat_messages) ? conversation.chat_messages : [];
|
|
127
|
+
return messages.map((m) => {
|
|
128
|
+
const text = typeof m?.text === "string" && m.text.length > 0 ? m.text : (Array.isArray(m?.content) ? m.content.filter((c) => c?.type === "text" && typeof c.text === "string").map((c) => c.text).join("\n") : "");
|
|
129
|
+
const at = m?.created_at ?? conversation?.created_at ?? null;
|
|
130
|
+
return { type: m?.sender === "human" ? "user" : "assistant", timestamp: at, message: { content: [{ type: "text", text }] } };
|
|
131
|
+
});
|
|
132
|
+
}
|
|
133
|
+
const titleOf = (vendor, conversation) => String((vendor === "chatgpt" ? conversation?.title : conversation?.name) ?? "");
|
|
134
|
+
const idOf = (vendor, conversation, index) => String((vendor === "chatgpt" ? conversation?.conversation_id ?? conversation?.id : conversation?.uuid) ?? `#${index}`);
|
|
135
|
+
|
|
136
|
+
/**
|
|
137
|
+
* Every conversation of an export as one session: `key` names the vendor and the conversation's id, `lines` carry
|
|
138
|
+
* the transcript shape both readers measure. `excluded(title)` skips a conversation by its title before anything of
|
|
139
|
+
* it is read (the same `--exclude` as a project directory); the title itself goes no further than that call.
|
|
140
|
+
* `given` is a path, or an export `readExport` already returned (so a zip is inflated once).
|
|
141
|
+
*/
|
|
142
|
+
export function* exportSessions(given, { expect = null, excluded = () => false, skipped = null } = {}) {
|
|
143
|
+
const { vendor, conversations } = typeof given === "string" ? readExport(given, expect) : given;
|
|
144
|
+
for (let index = 0; index < conversations.length; index += 1) {
|
|
145
|
+
const conversation = conversations[index];
|
|
146
|
+
const title = titleOf(vendor, conversation);
|
|
147
|
+
if (excluded(title)) { skipped?.push(title.slice(0, 40)); continue; }
|
|
148
|
+
const lines = vendor === "chatgpt" ? chatgptLines(conversation) : claudeLines(conversation);
|
|
149
|
+
if (lines.length === 0) continue;
|
|
150
|
+
const id = idOf(vendor, conversation, index);
|
|
151
|
+
yield { key: `${vendor === "chatgpt" ? "chatgpt" : "claude.ai"}:${id}`, projectDir: vendor === "chatgpt" ? "chatgpt" : "claude-ai", basename: vendor === "chatgpt" ? "chatgpt" : "claude.ai", vendor, id, lines };
|
|
152
|
+
}
|
|
153
|
+
}
|
|
154
|
+
|
|
155
|
+
/**
|
|
156
|
+
* THE STRETCH'S NAME (the hook's `stretch_ref`, 43 characters): a hash of the vendor, the conversation's id and the
|
|
157
|
+
* UTC day, the same on any computer and on any copy of the export, so the same export sent twice, or from two
|
|
158
|
+
* computers, is each line once. The conversation's id is a vendor's opaque id; the hash carries nothing readable.
|
|
159
|
+
*/
|
|
160
|
+
export const exportRef = (vendor, id, day) => createHash("sha256").update(`worktrust-export|${vendor}|${id}|${day}`).digest("base64url");
|
|
161
|
+
|
|
162
|
+
/**
|
|
163
|
+
* THE EXPORTS IN ONE FOLDER, its top level only (the Downloads folder, where a vendor's export lands): a zip holding
|
|
164
|
+
* `conversations.json`, a folder holding one, or the file itself. Each is read to tell its vendor and digest; a file
|
|
165
|
+
* that is none of these, or not an export, is passed over without a word.
|
|
166
|
+
*/
|
|
167
|
+
export function findExports(dir = join(homedir(), "Downloads")) {
|
|
168
|
+
const root = expand(dir);
|
|
169
|
+
let names = []; try { names = readdirSync(root); } catch { return []; }
|
|
170
|
+
const found = [];
|
|
171
|
+
for (const name of names.sort()) {
|
|
172
|
+
const path = join(root, name);
|
|
173
|
+
let stat; try { stat = statSync(path); } catch { continue; }
|
|
174
|
+
const candidate = stat.isDirectory() ? existsSync(join(path, FILE)) : /\.zip$/i.test(name) || name === FILE;
|
|
175
|
+
if (!candidate) continue;
|
|
176
|
+
try {
|
|
177
|
+
const { vendor, conversations, digest } = readExport(path);
|
|
178
|
+
if (vendor && conversations.length > 0) found.push({ path, vendor, digest, conversations: conversations.length });
|
|
179
|
+
} catch { /* not an export, or not one this reader opens */ }
|
|
180
|
+
}
|
|
181
|
+
return found;
|
|
182
|
+
}
|
package/count-behaviour.mjs
CHANGED
|
@@ -616,66 +616,22 @@ const skippedDirs = [];
|
|
|
616
616
|
const countedDirs = [];
|
|
617
617
|
let exportConversations = 0;
|
|
618
618
|
const skippedConversations = [];
|
|
619
|
-
|
|
620
|
-
|
|
621
|
-
|
|
622
|
-
|
|
623
|
-
|
|
624
|
-
|
|
625
|
-
|
|
626
|
-
|
|
627
|
-
|
|
628
|
-
|
|
629
|
-
|
|
630
|
-
exportConversations += 1;
|
|
631
|
-
// The export's messages in the transcript's own shape, so one rubric reads both.
|
|
632
|
-
const lines = messages.map((m) => {
|
|
633
|
-
const text = typeof m?.text === "string" && m.text.length > 0 ? m.text : (Array.isArray(m?.content) ? m.content.filter((c) => c?.type === "text" && typeof c.text === "string").map((c) => c.text).join("\n") : "");
|
|
634
|
-
const at = m?.created_at ?? conversation?.created_at ?? null;
|
|
635
|
-
return { type: m?.sender === "human" ? "user" : "assistant", timestamp: at, message: { content: [{ type: "text", text }] } };
|
|
636
|
-
});
|
|
637
|
-
yield { key: `claude.ai:${conversation?.uuid ?? title}`, projectDir: "claude-ai", basename: "claude.ai", lines };
|
|
638
|
-
}
|
|
619
|
+
/**
|
|
620
|
+
* THE EXPORT READERS LIVE IN chat-exports.mjs beside this file (0.10.10): the session hook reads the same exports as
|
|
621
|
+
* history, so one reader serves both. The export's messages arrive in the transcript's own shape, so one rubric reads
|
|
622
|
+
* both; a vendor's zip is opened for its conversations.json alone. Without the module an export flag is refused by name.
|
|
623
|
+
*/
|
|
624
|
+
const { exportSessions = null } = (await import("./chat-exports.mjs").catch(() => null)) ?? {};
|
|
625
|
+
function* vendorExportSessions(paths, expect) {
|
|
626
|
+
if (paths.length > 0 && !exportSessions) throw Error("chat-exports.mjs is not beside this file: a data export cannot be read");
|
|
627
|
+
for (const given of paths) for (const session of exportSessions(given, { expect, excluded, skipped: skippedConversations })) {
|
|
628
|
+
if (expect === "chatgpt") chatgptConversations += 1; else exportConversations += 1;
|
|
629
|
+
yield session;
|
|
639
630
|
}
|
|
640
631
|
}
|
|
632
|
+
function* claudeExportSessions() { yield* vendorExportSessions(EXPORTS, "claude-web"); }
|
|
641
633
|
let chatgptConversations = 0;
|
|
642
|
-
|
|
643
|
-
function chatgptBranch(conversation) {
|
|
644
|
-
const mapping = conversation?.mapping && typeof conversation.mapping === "object" ? conversation.mapping : {};
|
|
645
|
-
const branch = [];
|
|
646
|
-
const seen = new Set();
|
|
647
|
-
for (let id = conversation?.current_node; id && mapping[id] && !seen.has(id); id = mapping[id].parent) { seen.add(id); branch.push(mapping[id]); }
|
|
648
|
-
return branch.reverse();
|
|
649
|
-
}
|
|
650
|
-
function* chatgptExportSessions() {
|
|
651
|
-
for (const given of CHATGPT_EXPORTS) {
|
|
652
|
-
let path = given.replace(/^~(?=\/|$)/, homedir());
|
|
653
|
-
try { if (statSync(path).isDirectory()) path = join(path, "conversations.json"); } catch { throw Error(`chatgpt export not found: ${given}`); }
|
|
654
|
-
let conversations; try { conversations = JSON.parse(readFileSync(path, "utf8")); } catch { throw Error(`chatgpt export unreadable: ${path}`); }
|
|
655
|
-
if (!Array.isArray(conversations)) throw Error("chatgpt export must contain an array of conversations");
|
|
656
|
-
for (const conversation of conversations) {
|
|
657
|
-
const title = String(conversation?.title ?? "");
|
|
658
|
-
if (excluded(title)) { skippedConversations.push(title.slice(0, 40)); continue; }
|
|
659
|
-
const lines = [];
|
|
660
|
-
for (const node of chatgptBranch(conversation)) {
|
|
661
|
-
const m = node?.message;
|
|
662
|
-
const role = m?.author?.role;
|
|
663
|
-
// The person and the model only: system prompts, tools and what the app hides are neither.
|
|
664
|
-
if ((role !== "user" && role !== "assistant") || m?.metadata?.is_visually_hidden_from_conversation) continue;
|
|
665
|
-
const parts = Array.isArray(m?.content?.parts) ? m.content.parts.filter((part) => typeof part === "string") : [];
|
|
666
|
-
const text = parts.join("\n");
|
|
667
|
-
if (text.length === 0) continue;
|
|
668
|
-
const seconds = Number(m?.create_time ?? conversation?.create_time);
|
|
669
|
-
const at = Number.isFinite(seconds) && seconds > 0 ? new Date(seconds * 1000).toISOString() : null;
|
|
670
|
-
const model = typeof m?.metadata?.model_slug === "string" ? m.metadata.model_slug : undefined;
|
|
671
|
-
lines.push({ type: role === "user" ? "user" : "assistant", timestamp: at, message: { ...(role === "assistant" && model ? { model } : {}), content: [{ type: "text", text }] } });
|
|
672
|
-
}
|
|
673
|
-
if (lines.length === 0) continue;
|
|
674
|
-
chatgptConversations += 1;
|
|
675
|
-
yield { key: `chatgpt:${conversation?.conversation_id ?? conversation?.id ?? title}`, projectDir: "chatgpt", basename: "chatgpt", lines };
|
|
676
|
-
}
|
|
677
|
-
}
|
|
678
|
-
}
|
|
634
|
+
function* chatgptExportSessions() { yield* vendorExportSessions(CHATGPT_EXPORTS, "chatgpt"); }
|
|
679
635
|
/**
|
|
680
636
|
* THE READERS FOR CODEX AND ANTIGRAVITY live in transcript-readers.mjs beside this file (2026-10-04;
|
|
681
637
|
* the session hook imports the same file). Run alone, without it, the counter reads Claude Code,
|
package/log-session.mjs
CHANGED
|
@@ -25,6 +25,17 @@
|
|
|
25
25
|
* node log-session.mjs --history [--dry-run] send the months already on this machine, as HISTORY
|
|
26
26
|
* node log-session.mjs --history --rebuild the same, re-measured: the door REPLACES this computer's earlier lines, day by day
|
|
27
27
|
* node log-session.mjs --history --summary one JSON line: sessions, hours, first and last month, per client (sends nothing)
|
|
28
|
+
* node log-session.mjs --history --export <path> a ChatGPT or Claude data export (zip, folder or conversations.json) as
|
|
29
|
+
* HISTORY: hours RECONSTRUCTED from its clocks, never measured, never tokens;
|
|
30
|
+
* the door withdraws the product's earlier connector lines on its days (the
|
|
31
|
+
* export replaces, 2026-10-10); `--withdraw-unknown` (after the person's yes)
|
|
32
|
+
* also withdraws the AI-app lines under no product on exactly those days
|
|
33
|
+
* node log-session.mjs --find-exports [dir] the exports lying in a folder (default ~/Downloads), and which were sent
|
|
34
|
+
* node log-session.mjs --history --from-folder <dir> a person's own COPY of an AI app's session folder (a backed-up
|
|
35
|
+
* ~/.claude/projects or ~/.codex/sessions), read with the same readers and
|
|
36
|
+
* clock, never the live folders: days the live folders lack, RECONSTRUCTED
|
|
37
|
+
* node log-session.mjs --history --from-archive [dir] the archive's stretches no longer in any AI app here: a day this
|
|
38
|
+
* computer's device key signed as measured, every other day reconstructed
|
|
28
39
|
* (as a hook) reads the hook's JSON on stdin, logs, exits
|
|
29
40
|
* (from Codex) notify = ["node", "~/.worktrust/log-session.mjs", "--codex-notify"]
|
|
30
41
|
* in ~/.codex/config.toml: Codex calls it at every turn's end and
|
|
@@ -57,7 +68,7 @@
|
|
|
57
68
|
import { execFileSync, spawn, spawnSync } from "node:child_process";
|
|
58
69
|
import { copyFileSync, existsSync, mkdirSync, readFileSync, readdirSync, rmSync, statSync, writeFileSync } from "node:fs";
|
|
59
70
|
import { homedir } from "node:os";
|
|
60
|
-
import { dirname, join } from "node:path";
|
|
71
|
+
import { dirname, join, resolve, sep } from "node:path";
|
|
61
72
|
import { fileURLToPath } from "node:url";
|
|
62
73
|
import { createHash, createPrivateKey, createPublicKey, randomBytes, sign as cryptoSign } from "node:crypto";
|
|
63
74
|
|
|
@@ -260,9 +271,13 @@ const { CODEX_ROLLOUT = /(?!)/, codexIdOf = (file) => String(file).split(/[\\/]/
|
|
|
260
271
|
// context and routing, for the local archive only. A copy without the module still measures and sends exactly as before.
|
|
261
272
|
const { callOf = (block) => ({ id: block.id, kinds: [], family: String(block.name), digest: "" }), deriveStretch = () => ({}), complexityOf = null, resultOf = (block) => ({ id: block.tool_use_id, failed: block.is_error === true, refusal: null }) } = (await import("./stretch-evidence.mjs").catch(() => null)) ?? {};
|
|
262
273
|
const { DATABASE_SESSION = /(?!)/, databaseLines = () => null, databaseSessions = function* () {} } = (await import("./session-databases.mjs").catch(() => null)) ?? {};
|
|
274
|
+
// A WEB CHAT'S DATA EXPORT AS HISTORY (0.10.10, owner 2026-10-10): chat-exports.mjs reads a ChatGPT or Claude export (the counter
|
|
275
|
+
// imports the same reader); `--history --export <path>` sends its conversations as RECONSTRUCTED days, never measured, never tokens.
|
|
276
|
+
const { EXPORT_CLIENTS = [], EXPORT_TITLES = {}, exportSessions = null, exportRef = null, readExport = null, findExports = null } = (await import("./chat-exports.mjs").catch(() => null)) ?? {};
|
|
277
|
+
const EXPORT_PATHS = []; for (let i = 0; i < args.length; i += 1) if (args[i] === "--export" && args[i + 1]) EXPORT_PATHS.push(args[i + 1]);
|
|
263
278
|
const DATABASE_CLIENTS = ["hermes", "goose", "opencode", "openclaw", "cursor", "copilot"]; // the registry's keys, the name each line carries
|
|
264
279
|
const LIVE_SOURCE = new RegExp(`^(codex|antigravity|${DATABASE_CLIENTS.join("|")}):`); // a sweep entry's id → the client it names (every database client, 0.6.16)
|
|
265
|
-
const READER_FILES = ["transcript-readers.mjs", "session-databases.mjs", "stretch-evidence.mjs"]; // 0.7.4: the derived record travels with the hook
|
|
280
|
+
const READER_FILES = ["transcript-readers.mjs", "session-databases.mjs", "stretch-evidence.mjs", "chat-exports.mjs"]; // 0.7.4: the derived record travels with the hook; 0.10.10: the export reader
|
|
266
281
|
/** The readers go where the hook and the counter run: copied from beside this file, else (or for a newer counter) from the deployment. */
|
|
267
282
|
async function installReaders(origin, fromNetwork = false) {
|
|
268
283
|
let installed = true;
|
|
@@ -699,24 +714,56 @@ function payloadFor(stretch) {
|
|
|
699
714
|
* exactly what landed. `announce` because one caller is a person watching a terminal and the other
|
|
700
715
|
* is a hook holding a session's exit open.
|
|
701
716
|
*/
|
|
702
|
-
|
|
717
|
+
/**
|
|
718
|
+
* THE BATCHES: at most two hundred lines each. `byDay` (an export, 2026-10-10) never splits a UTC day across two batches unless
|
|
719
|
+
* 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
|
|
720
|
+
* day in two batches would be counted twice.
|
|
721
|
+
*/
|
|
722
|
+
function batchesOf(group, byDay) {
|
|
723
|
+
if (!byDay) { const out = []; for (let i = 0; i < group.length; i += 200) out.push(group.slice(i, i + 200)); return out; }
|
|
724
|
+
const days = new Map();
|
|
725
|
+
for (const entry of group) { const day = String(entry.at).slice(0, 10); days.set(day, [...(days.get(day) ?? []), entry]); }
|
|
726
|
+
const out = []; let current = [];
|
|
727
|
+
for (const ofDay of days.values()) {
|
|
728
|
+
if (ofDay.length > 200) { if (current.length) { out.push(current); current = []; } for (let i = 0; i < ofDay.length; i += 200) out.push(ofDay.slice(i, i + 200)); continue; }
|
|
729
|
+
if (current.length + ofDay.length > 200) { out.push(current); current = []; }
|
|
730
|
+
current.push(...ofDay);
|
|
731
|
+
}
|
|
732
|
+
if (current.length) out.push(current);
|
|
733
|
+
return out;
|
|
734
|
+
}
|
|
735
|
+
/** THE RECEIPTS' COUNTS (2026-10-10): what an export send replaced, how many AI-app lines lie on its days, how many were withdrawn; summed over the batches, read for the counts alone. */
|
|
736
|
+
const RECEIPTS = { superseded: 0, unknownOnDays: 0, unknownWithdrawn: 0 };
|
|
737
|
+
const noteReceipt = (answer) => {
|
|
738
|
+
try {
|
|
739
|
+
const json = JSON.parse(answer.trim().startsWith("{") ? answer : answer.split("\n").find((row) => row.startsWith("data:"))?.slice(5) ?? "null");
|
|
740
|
+
const receipt = JSON.parse(json?.result?.content?.[0]?.text ?? "{}");
|
|
741
|
+
for (const key of Object.keys(RECEIPTS)) RECEIPTS[key] += Number(receipt[key]) || 0;
|
|
742
|
+
} catch { /* a receipt unread leaves the counts short, never the send */ }
|
|
743
|
+
};
|
|
744
|
+
async function sendHistory(door, entries, announce = false, rebuild = false, named = false, { byDay = false, withdrawUnknown = false } = {}) {
|
|
703
745
|
let accepted = 0;
|
|
704
746
|
// A Codex entry goes through Codex's own coupling where one exists (see codexDoor), the rest
|
|
705
747
|
// through the door given: the record files a line under the coupling that sent it. Antigravity's
|
|
706
748
|
// go apart too, so their batch can name the client (clientOf).
|
|
707
|
-
|
|
749
|
+
// An export's lines go as their own group too (0.10.10), so the record names the product (ChatGPT, Claude on the web).
|
|
750
|
+
for (const [source, group] of [["claude", entries.filter((entry) => !entrySource.has(entry))], ["codex", entries.filter((entry) => entrySource.get(entry) === "codex")], ...["antigravity", ...DATABASE_CLIENTS, ...EXPORT_CLIENTS].map((client) => [client, entries.filter((entry) => entrySource.get(entry) === client)])]) {
|
|
708
751
|
const target = source === "codex" ? codexDoor ?? door : door;
|
|
709
752
|
if (group.length === 0 || !target) continue;
|
|
710
|
-
|
|
711
|
-
|
|
753
|
+
let number = 0;
|
|
754
|
+
for (const batch of batchesOf(group, byDay)) {
|
|
755
|
+
number += 1;
|
|
712
756
|
// History carries no shas: an imported line forms no session, and the join is the live route's. REBUILD (owner, 2026-10-07): `rebuild: true`
|
|
713
757
|
// tells the door to replace this computer's earlier lines on the days and for the client the batch carries, and every group names its client.
|
|
714
|
-
|
|
715
|
-
const
|
|
758
|
+
// WITHDRAW UNKNOWN (owner, 2026-10-10): with an export, after the person's yes, `withdraw_unknown: true` also withdraws the AI-app lines on its days.
|
|
759
|
+
const body = JSON.stringify({ jsonrpc: "2.0", id: 1, method: "tools/call", params: { name: "import_history", arguments: { ...(rebuild ? { rebuild: true } : {}), ...(withdrawUnknown ? { withdraw_unknown: true } : {}), entries: batch.map((entry) => { const { commits, ...rest } = entry; void commits; return rest; }) } } });
|
|
760
|
+
// `named` (0.10.10): a copied folder's lines name their client too, so the record says which app the copy came from.
|
|
761
|
+
const response = await fetch(target.url, { method: "POST", headers: { "content-type": "application/json", accept: "application/json, text/event-stream", authorization: `Bearer ${target.token}`, ...clientOf(source, rebuild || named), ...proofFor(target.url, body) }, body });
|
|
716
762
|
const text = await response.text();
|
|
717
|
-
if (announce) console.log(`batch ${
|
|
763
|
+
if (announce) console.log(`batch ${number}: ${response.status} ${text.slice(0, 200).replace(/\\n/g, " ")}`);
|
|
718
764
|
if (!response.ok) break;
|
|
719
765
|
accepted += batch.length;
|
|
766
|
+
noteReceipt(text);
|
|
720
767
|
}
|
|
721
768
|
}
|
|
722
769
|
return accepted;
|
|
@@ -749,7 +796,7 @@ const proofFor = (url, body) => {
|
|
|
749
796
|
* on this computer, and the door names a coupling's clients by the user-agent it hears (mcp_identify's
|
|
750
797
|
* agents_seen). An Antigravity line names Antigravity: the product name, nothing of the work.
|
|
751
798
|
*/
|
|
752
|
-
const clientOf = (source, always = false) => (always || source === "antigravity" || DATABASE_CLIENTS.includes(source) ? { "user-agent": `${source ?? "claude"}/hook (worktrust-hook)` } : {});
|
|
799
|
+
const clientOf = (source, always = false) => (always || source === "antigravity" || DATABASE_CLIENTS.includes(source) || EXPORT_CLIENTS.includes(source) ? { "user-agent": `${source ?? "claude"}/hook (worktrust-hook)` } : {});
|
|
753
800
|
|
|
754
801
|
async function send(door, payload) {
|
|
755
802
|
const body = JSON.stringify({ jsonrpc: "2.0", id: 1, method: "tools/call", params: { name: "log_work", arguments: payload } });
|
|
@@ -810,6 +857,113 @@ function historyEntries(floor = null, all = false) {
|
|
|
810
857
|
return entries.filter((entry) => !seen.has(entry.stretch_ref) && seen.add(entry.stretch_ref)).sort((a, b) => a.at.localeCompare(b.at));
|
|
811
858
|
}
|
|
812
859
|
|
|
860
|
+
/**
|
|
861
|
+
* A DATA EXPORT'S CONVERSATIONS AS HISTORY (0.10.10, owner 2026-10-10: "hours from an export count as reconstructed, shown,
|
|
862
|
+
* never in verified hours"). The same clock cuts them (a day, gaps capped at IDLE_CAP) and the same measure counts the
|
|
863
|
+
* person's own turns and the model, but the line says `reconstructed`: the file can be edited before it is read and no
|
|
864
|
+
* device key witnessed it. No tokens (the export carries none and none are estimated), no layers, no evidence; the
|
|
865
|
+
* title names the product and never the conversation; the stretch's name is the vendor, the conversation's id and the
|
|
866
|
+
* day, so the same export sent twice is each line once. The database keeps a reconstructed stretch inside eight hours
|
|
867
|
+
* (20261009170000), so the line is cut there before it leaves.
|
|
868
|
+
*/
|
|
869
|
+
const RECONSTRUCTED_MAX = 28800;
|
|
870
|
+
const EXPORTS_STATE = join(homedir(), ".worktrust", "exports.json"); // per export digest: sent, or offered and declined; nothing of a conversation
|
|
871
|
+
const readExportsState = () => { try { return JSON.parse(readFileSync(EXPORTS_STATE, "utf8")); } catch { return {}; } };
|
|
872
|
+
const rememberExport = (digest, note) => { const state = readExportsState(); state[digest] = { ...(state[digest] ?? {}), ...note }; mkdirSync(dirname(EXPORTS_STATE), { recursive: true }); writeFileSync(EXPORTS_STATE, JSON.stringify(state, null, 1)); };
|
|
873
|
+
function exportEntries() {
|
|
874
|
+
if (!exportSessions) throw Error("chat-exports.mjs is not beside this file: a data export cannot be read");
|
|
875
|
+
const entries = [], reports = [];
|
|
876
|
+
for (const given of EXPORT_PATHS) {
|
|
877
|
+
const read = readExport(given);
|
|
878
|
+
const report = { path: read.path, vendor: read.vendor, digest: read.digest, conversations: read.conversations.length, days: new Set(), seconds: 0 };
|
|
879
|
+
for (const { id, lines } of exportSessions(read, { excluded })) {
|
|
880
|
+
const messages = [];
|
|
881
|
+
for (const line of lines) { const at = line.timestamp ? Date.parse(line.timestamp) : NaN; if (Number.isFinite(at)) messages.push(messageOf(line, at)); }
|
|
882
|
+
messages.sort((a, b) => a.at - b.at);
|
|
883
|
+
for (const [day, ofDay] of byDayOf(messages)) {
|
|
884
|
+
if (ofDay.length === 0) continue;
|
|
885
|
+
const stretch = measure(null, ofDay), ref = exportRef(read.vendor, id, day);
|
|
886
|
+
const entry = {
|
|
887
|
+
title: EXPORT_TITLES[read.vendor], kind: "researched",
|
|
888
|
+
...(stretch.seconds !== null ? { seconds: Math.min(RECONSTRUCTED_MAX, stretch.seconds), duration_basis: "reconstructed" } : {}),
|
|
889
|
+
...(stretch.exchanges > 0 ? { exchanges: stretch.exchanges, turn_basis: "humanOnly" } : {}),
|
|
890
|
+
...(stretch.model ? { model: stretch.model } : {}),
|
|
891
|
+
stretch_ref: ref, source_event_id: `exp_${ref}`,
|
|
892
|
+
started_at: new Date(stretch.from).toISOString(), utc_offset: stretch.offset, at: new Date(stretch.to).toISOString(),
|
|
893
|
+
};
|
|
894
|
+
entrySource.set(entry, read.vendor);
|
|
895
|
+
entryFile.set(entry, { file: `${read.vendor}:${id}`, from: stretch.from, folder: null });
|
|
896
|
+
report.days.add(day); report.seconds += entry.seconds ?? 0; entries.push(entry);
|
|
897
|
+
}
|
|
898
|
+
}
|
|
899
|
+
const days = [...report.days].sort();
|
|
900
|
+
reports.push({ ...report, days: days.length, hours: Math.round(report.seconds / 360) / 10, first: days[0] ?? null, last: days.at(-1) ?? null });
|
|
901
|
+
}
|
|
902
|
+
const seen = new Set();
|
|
903
|
+
return { entries: entries.filter((entry) => !seen.has(entry.stretch_ref) && seen.add(entry.stretch_ref)).sort((a, b) => a.at.localeCompare(b.at)), reports };
|
|
904
|
+
}
|
|
905
|
+
|
|
906
|
+
/**
|
|
907
|
+
* A PERSON'S OWN COPY OF AN AI APP'S SESSION FOLDER (owner, 2026-10-10, one rule): a backed-up ~/.claude/projects, ~/.codex/sessions
|
|
908
|
+
* or an Antigravity brain folder, read with the same readers and the same clock as the live folders, never the live folders
|
|
909
|
+
* themselves (a copy of one of them, or one holding them, is refused by name). Each day is named exactly as the live folder
|
|
910
|
+
* would name it (the session file's name and the day), so a stretch the live folders already hold, or an earlier send of the
|
|
911
|
+
* same copy, is skipped: the live folders win. What travels is RECONSTRUCTED: no device key witnessed the copy, and a copy can
|
|
912
|
+
* be edited. The counts a transcript carries (tokens, turns, the model, the evidence) travel; the hours in layers, which say
|
|
913
|
+
* what a MEASURED day's seconds were, do not. The title says where the line came from.
|
|
914
|
+
*/
|
|
915
|
+
function folderEntries(given) {
|
|
916
|
+
const dir = given.replace(/^~(?=\/|$)/, homedir());
|
|
917
|
+
let stat; try { stat = statSync(dir); } catch { throw Error(`no session files: ${given} does not exist`); }
|
|
918
|
+
if (!stat.isDirectory()) throw Error(`no session files: ${given} is not a folder`);
|
|
919
|
+
const here = resolve(dir), live = [claudeRoot(), codexRoot(), ...antigravityRoots(value("antigravity-root"))].filter(Boolean).map((root) => resolve(root));
|
|
920
|
+
if (live.some((root) => here === root || here.startsWith(root + sep) || root.startsWith(here + sep))) throw Error(`${given} is an AI app's own session folder on this computer, or holds one: the hook measures those itself; a copy lives elsewhere`);
|
|
921
|
+
const files = [];
|
|
922
|
+
const walk = (at, depth) => {
|
|
923
|
+
if (depth > 12) return;
|
|
924
|
+
let names = []; try { names = readdirSync(at, { withFileTypes: true }); } catch { return; }
|
|
925
|
+
for (const entry of names.sort((a, b) => a.name.localeCompare(b.name))) {
|
|
926
|
+
const path = join(at, entry.name);
|
|
927
|
+
if (entry.isDirectory()) { if (entry.name !== "subagents" && !excluded(entry.name)) walk(path, depth + 1); }
|
|
928
|
+
else if (entry.name.endsWith(".jsonl")) files.push(path);
|
|
929
|
+
}
|
|
930
|
+
};
|
|
931
|
+
walk(here, 0);
|
|
932
|
+
if (files.length === 0) throw Error(`no session files under ${given} (Claude Code transcripts, Codex rollouts or Antigravity transcripts, as .jsonl)`);
|
|
933
|
+
const present = new Set(historyEntries(null, true).map((entry) => entry.stretch_ref)), seen = new Set();
|
|
934
|
+
const entries = [], report = { stretches: 0, skipped: 0, days: new Set(), seconds: 0 };
|
|
935
|
+
for (const file of files) {
|
|
936
|
+
const client = CODEX_ROLLOUT.test(file) ? "codex" : ANTIGRAVITY_TRANSCRIPT.test(file) ? "antigravity" : "claude";
|
|
937
|
+
const lines = parsedLines(file);
|
|
938
|
+
if (!lines) continue;
|
|
939
|
+
let cwd = null;
|
|
940
|
+
const read = [];
|
|
941
|
+
for (const line of lines) {
|
|
942
|
+
if (typeof line.cwd === "string") cwd = line.cwd;
|
|
943
|
+
if (!line.timestamp || (line.type !== "user" && line.type !== "assistant")) continue;
|
|
944
|
+
const at = Date.parse(line.timestamp);
|
|
945
|
+
if (Number.isFinite(at)) read.push(messageOf(line, at));
|
|
946
|
+
}
|
|
947
|
+
read.sort((a, b) => a.at - b.at);
|
|
948
|
+
for (const [day, messages] of byDayOf(read)) {
|
|
949
|
+
if (messages.length === 0) continue;
|
|
950
|
+
const ref = stretchRef(file, day);
|
|
951
|
+
report.stretches += 1;
|
|
952
|
+
if (present.has(ref) || seen.has(ref)) { report.skipped += 1; continue; }
|
|
953
|
+
seen.add(ref);
|
|
954
|
+
const measured = payloadFor({ ...measure(cwd, messages), ref, steered: null, agents: null });
|
|
955
|
+
const { model_seconds, tool_seconds, human_seconds, idle_seconds, agent_runs, agent_seconds, agent_peak, ...rest } = measured;
|
|
956
|
+
void model_seconds; void tool_seconds; void human_seconds; void idle_seconds; void agent_runs; void agent_seconds; void agent_peak;
|
|
957
|
+
const entry = { ...rest, title: rest.layer ? `AI-assisted work from a copied session folder · ${rest.layer}` : "AI-assisted work from a copied session folder", ...(typeof rest.seconds === "number" ? { seconds: Math.min(RECONSTRUCTED_MAX, rest.seconds), duration_basis: "reconstructed" } : {}) };
|
|
958
|
+
if (client !== "claude") entrySource.set(entry, client);
|
|
959
|
+
entryFile.set(entry, { file, from: firstOf(messages), folder: null });
|
|
960
|
+
report.days.add(day); report.seconds += entry.seconds ?? 0; entries.push(entry);
|
|
961
|
+
}
|
|
962
|
+
}
|
|
963
|
+
const days = [...report.days].sort();
|
|
964
|
+
return { entries: entries.sort((a, b) => a.at.localeCompare(b.at)), report: { stretches: report.stretches, skipped: report.skipped, days: days.length, hours: Math.round(report.seconds / 360) / 10, first: days[0] ?? null, last: days.at(-1) ?? null } };
|
|
965
|
+
}
|
|
966
|
+
|
|
813
967
|
/** Every transcript this machine holds, excluded projects skipped before a file is opened. */
|
|
814
968
|
function* allTranscripts() {
|
|
815
969
|
const root = claudeRoot();
|
|
@@ -1013,6 +1167,10 @@ if (flag("evidence-summary")) {
|
|
|
1013
1167
|
await exitFlushed(0);
|
|
1014
1168
|
}
|
|
1015
1169
|
if (flag("archive-lines")) { const lines = historyEntries(null, true).map((entry) => JSON.stringify({ ...entry, ...(DERIVED.get(entry) ?? {}), client: entrySource.get(entry) ?? "claude", started_at: new Date(entryFile.get(entry).from).toISOString(), folder: entryFile.get(entry).folder })); process.stdout.write(`${[...lines, JSON.stringify({ archive_end: lines.length })].join("\n")}\n`); await exitFlushed(0); } // one write and a count, so the reader tells a whole answer from a cut one
|
|
1170
|
+
// THE EXPORTS IN A FOLDER (0.10.10, for the bare `npx worktrust`): which lie there, by vendor and digest, and which this computer
|
|
1171
|
+
// already sent or was asked about; reads, prints one JSON line, sends nothing. `--export-offered <digest>` records a No.
|
|
1172
|
+
if (flag("find-exports")) { const named = value("find-exports"), state = readExportsState(); const found = (findExports ? findExports(named && !named.startsWith("--") ? named : undefined) : []).map((one) => ({ ...one, sent: state[one.digest]?.sent === true, offered: Boolean(state[one.digest]) })); process.stdout.write(`${JSON.stringify(found)}\n`); await exitFlushed(0); }
|
|
1173
|
+
if (value("export-offered")) { rememberExport(value("export-offered"), { offered: new Date().toISOString() }); await exitFlushed(0); }
|
|
1016
1174
|
if (!door && !codexDoor && !DRY) { process.exit(0); } // Not coupled on this machine: nothing to do, quietly.
|
|
1017
1175
|
|
|
1018
1176
|
/**
|
|
@@ -1025,17 +1183,25 @@ if (flag("history") && flag("from-archive")) {
|
|
|
1025
1183
|
const named = value("from-archive"), dir = named && !named.startsWith("--") ? named.replace(/^~(?=\/|$)/, homedir()) : join(homedir(), "AI-Evidence");
|
|
1026
1184
|
const say = (text) => console.log(text);
|
|
1027
1185
|
const pem = process.env.WORKTRUST_DEVICE_KEY;
|
|
1186
|
+
// ONE RULE (owner, 2026-10-10): VERIFIED is what this computer's coupled key witnessed. A day the device key signed goes as it was
|
|
1187
|
+
// measured; a day unsigned, signed by the local archive key, or by another computer's key goes too, as RECONSTRUCTED, inside the
|
|
1188
|
+
// database's ceiling for an unmeasured stretch. No device key is no longer a refusal: it means every day is reconstructed. The
|
|
1189
|
+
// archive must still verify whole, and only stretches no longer in any AI app here travel.
|
|
1028
1190
|
let ownKey = null;
|
|
1029
1191
|
try { ownKey = pem ? createPublicKey(createPrivateKey(pem)).export({ format: "jwk" }).x : null; } catch { ownKey = null; }
|
|
1030
|
-
if (!ownKey) { say("No device key on this computer: only lines this computer signed can be sent from its archive. Nothing was sent."); await exitFlushed(1); }
|
|
1031
1192
|
const verified = spawnSync(process.execPath, [join(dirname(fileURLToPath(import.meta.url)), "preserve.mjs"), "--verify", dir], { encoding: "utf8" });
|
|
1032
1193
|
if (verified.status !== 0) { say(`The archive in ${dir} does not verify, so nothing was sent: ${(verified.stdout || verified.stderr || "").trim().split("\n").pop()}`); await exitFlushed(1); }
|
|
1033
1194
|
const { archiveEntries = null } = (await import("./preserve-lines.mjs").catch(() => null)) ?? {};
|
|
1034
1195
|
if (!archiveEntries) { say("preserve-lines.mjs is not beside this file. Nothing was sent."); await exitFlushed(1); }
|
|
1035
1196
|
const present = new Set(historyEntries(null, true).map((entry) => entry.stretch_ref));
|
|
1036
|
-
const
|
|
1037
|
-
const entries = gone.map(({ entry, client }) => {
|
|
1038
|
-
|
|
1197
|
+
const all = archiveEntries(dir, ownKey), gone = all.filter(({ entry }) => !present.has(entry.stretch_ref));
|
|
1198
|
+
const entries = gone.map(({ entry, client, signed }) => {
|
|
1199
|
+
if (client !== "claude") entrySource.set(entry, client);
|
|
1200
|
+
if (!signed && typeof entry.seconds === "number") { entry.seconds = Math.min(RECONSTRUCTED_MAX, entry.seconds); entry.duration_basis = "reconstructed"; }
|
|
1201
|
+
return entry;
|
|
1202
|
+
});
|
|
1203
|
+
const signedCount = all.filter(({ signed }) => signed).length;
|
|
1204
|
+
say(`${all.length} stretches in the archive · ${signedCount} signed by this computer's key (verified) · ${all.length - signedCount} unsigned or signed by another key (reconstructed) · ${entries.length} of them no longer in any AI app here`);
|
|
1039
1205
|
if (DRY || entries.length === 0) { if (entries[0]) say(`\nthe oldest of them, in full:\n${JSON.stringify(entries[0], null, 1)}`); say(entries.length === 0 ? "Nothing to send." : "\ndry run — nothing sent."); await exitFlushed(0); }
|
|
1040
1206
|
if (!(await doorKnowsArchive(door))) { say("WorkTrust does not accept history from an archive yet (the door does not know the mark). Nothing was sent."); await exitFlushed(1); }
|
|
1041
1207
|
await exitFlushed((await sendHistory(door, entries, true)) === entries.length ? 0 : 1);
|
|
@@ -1043,13 +1209,26 @@ if (flag("history") && flag("from-archive")) {
|
|
|
1043
1209
|
|
|
1044
1210
|
if (flag("history")) {
|
|
1045
1211
|
const historyFloor = floorOf(readState(), "__historyFloor");
|
|
1046
|
-
|
|
1212
|
+
// AN EXPORT IS ITS OWN HISTORY (0.10.10): its lines alone, reconstructed, and never a rebuild (a rebuild replaces this computer's own measured days).
|
|
1213
|
+
let fromExports = null, fromFolder = null;
|
|
1214
|
+
if (EXPORT_PATHS.length > 0) { try { fromExports = exportEntries(); } catch (error) { console.log(`export: ${error.message}`); await exitFlushed(1); } }
|
|
1215
|
+
// A COPIED SESSION FOLDER (0.10.10): its own history, reconstructed, the live folders' stretches skipped; never a rebuild.
|
|
1216
|
+
if (flag("from-folder")) {
|
|
1217
|
+
const given = value("from-folder");
|
|
1218
|
+
if (!given || given.startsWith("--")) { console.log("folder: --from-folder needs the copied folder's path"); await exitFlushed(1); }
|
|
1219
|
+
try { fromFolder = folderEntries(given); } catch (error) { console.log(`folder: ${error.message}`); await exitFlushed(1); }
|
|
1220
|
+
}
|
|
1221
|
+
if ((fromExports || fromFolder) && flag("rebuild")) { console.log("An export or a copied folder is never a rebuild: its hours are reconstructed and replace nothing. Run it without --rebuild."); await exitFlushed(1); }
|
|
1222
|
+
// THE EXPORT REPLACES (owner, 2026-10-10): the door withdraws the product's earlier connector lines on the export's days by itself; the AI-app
|
|
1223
|
+
// lines under no product go only with `--withdraw-unknown`, which the command sends after the person's yes, with an export alone.
|
|
1224
|
+
if (flag("withdraw-unknown") && !fromExports) { console.log("--withdraw-unknown goes with --export alone: it withdraws, on the days an export covers, the earlier lines an AI app reported under no product."); await exitFlushed(1); }
|
|
1225
|
+
const entries = fromExports ? fromExports.entries : fromFolder ? fromFolder.entries : historyEntries(historyFloor);
|
|
1047
1226
|
const hours = entries.reduce((sum, entry) => sum + (entry.seconds ?? 0), 0) / 3600;
|
|
1048
1227
|
const months = [...new Set(entries.map((entry) => entry.at.slice(0, 7)))].sort();
|
|
1049
1228
|
// ONE LINE FOR `npx worktrust` TO ASK WITH (2026-10-03): sessions, hours, first and last month; per client its days and hours (the rebuild's plan, 2026-10-07); nothing sent.
|
|
1050
1229
|
const clients = [...entries.reduce((map, entry) => { const client = entrySource.get(entry) ?? "claude", row = map.get(client) ?? { client, days: new Set(), seconds: 0 }; row.days.add(entry.at.slice(0, 10)); row.seconds += entry.seconds ?? 0; return map.set(client, row); }, new Map()).values()].map((row) => ({ client: row.client, days: row.days.size, hours: Math.round(row.seconds / 360) / 10, first: [...row.days].sort()[0], last: [...row.days].sort().at(-1) }));
|
|
1051
|
-
if (flag("summary")) { console.log(JSON.stringify({ sessions: new Set(entries.map((entry) => entryFile.get(entry).file)).size, hours: Math.round(hours * 10) / 10, first: months[0] ?? null, last: months.at(-1) ?? null, clients })); await exitFlushed(0); }
|
|
1052
|
-
console.log(`${entries.length} day-stretches · ${hours.toFixed(1)} measured hours · ${months.join(", ")}${flag("rebuild") ? " · rebuild: this computer's earlier lines for these days and clients are replaced at the door" : ""}`);
|
|
1230
|
+
if (flag("summary")) { console.log(JSON.stringify({ sessions: new Set(entries.map((entry) => entryFile.get(entry).file)).size, hours: Math.round(hours * 10) / 10, first: months[0] ?? null, last: months.at(-1) ?? null, ...(fromExports ? { exports: fromExports.reports } : {}), ...(fromFolder ? { folder: fromFolder.report } : {}), clients })); await exitFlushed(0); }
|
|
1231
|
+
console.log(`${entries.length} day-stretches · ${hours.toFixed(1)} ${fromExports || fromFolder ? "reconstructed" : "measured"} hours · ${months.join(", ")}${flag("rebuild") ? " · rebuild: this computer's earlier lines for these days and clients are replaced at the door" : ""}`);
|
|
1053
1232
|
if (DRY) {
|
|
1054
1233
|
// One example in full: the shape is the argument for trusting it, and a summary hides it.
|
|
1055
1234
|
if (entries[0]) console.log(`\nthe oldest of them, in full:\n${JSON.stringify(entries[0], null, 1)}`);
|
|
@@ -1057,7 +1236,12 @@ if (flag("history")) {
|
|
|
1057
1236
|
await exitFlushed(0);
|
|
1058
1237
|
}
|
|
1059
1238
|
// A batch the door refused is a failure the caller must see, not a quiet zero.
|
|
1060
|
-
|
|
1239
|
+
const accepted = await sendHistory(door, entries, true, flag("rebuild"), Boolean(fromFolder), fromExports ? { byDay: true, withdrawUnknown: flag("withdraw-unknown") } : {});
|
|
1240
|
+
// An export that arrived whole is remembered by its digest (never by a conversation), so the bare command offers it no more.
|
|
1241
|
+
if (fromExports && accepted === entries.length) for (const report of fromExports.reports) rememberExport(report.digest, { vendor: report.vendor, sent: true, at: new Date().toISOString(), conversations: report.conversations });
|
|
1242
|
+
// ONE LINE FOR THE COMMAND TO ASK WITH (2026-10-10): what the door replaced, how many AI-app lines lie on the export's days, how many it withdrew.
|
|
1243
|
+
if (fromExports) console.log(JSON.stringify({ export_sent: accepted, of: entries.length, ...RECEIPTS }));
|
|
1244
|
+
await exitFlushed(accepted === entries.length ? 0 : 1);
|
|
1061
1245
|
}
|
|
1062
1246
|
|
|
1063
1247
|
const input = hookInput();
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "worktrust",
|
|
3
|
-
"version": "0.10.
|
|
3
|
+
"version": "0.10.10",
|
|
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": {
|
|
@@ -18,6 +18,7 @@
|
|
|
18
18
|
"preserve-summary.mjs",
|
|
19
19
|
"preserve-lines.mjs",
|
|
20
20
|
"stretch-evidence.mjs",
|
|
21
|
+
"chat-exports.mjs",
|
|
21
22
|
"README.md",
|
|
22
23
|
"SECURITY.md",
|
|
23
24
|
"LICENSE",
|
package/preserve-lines.mjs
CHANGED
|
@@ -198,7 +198,10 @@ export function archiveEntries(dir, ownKey) {
|
|
|
198
198
|
let line; try { line = JSON.parse(text); } catch { continue; }
|
|
199
199
|
if (line.supplements) continue; // a supplement adds fields to a stretch, it is no stretch of its own
|
|
200
200
|
const proof = read(join(dir, "proofs", `${line.day}.json`));
|
|
201
|
-
|
|
201
|
+
// SIGNED BY THIS COMPUTER'S KEY, OR NOT (owner, 2026-10-10, one rule): every stretch is answered, with whether the day's
|
|
202
|
+
// root carries this computer's device key's signature; the hook sends a signed day as it was measured and every other day
|
|
203
|
+
// (unsigned, a local archive key's, another computer's) as reconstructed. Before this, an unsigned day was not answered.
|
|
204
|
+
const signed = Boolean(ownKey && proof && typeof proof.signature === "string" && proof.public_key === ownKey);
|
|
202
205
|
const entry = {
|
|
203
206
|
title: line.layer ? `AI-assisted work · ${line.layer}` : "AI-assisted work",
|
|
204
207
|
...(line.kind ? { kind: line.kind } : {}), ...(line.layer ? { layer: line.layer } : {}), ...(line.layers ? { layers: line.layers } : {}),
|
|
@@ -206,7 +209,7 @@ export function archiveEntries(dir, ownKey) {
|
|
|
206
209
|
...Object.fromEntries(["tokens_in", "tokens_out", "token_basis", "tokens_cache_read", "tokens_cache_write", "exchanges", "turn_basis", "model", "steered_from", "model_seconds", "tool_seconds", "human_seconds", "idle_seconds", "agent_runs", "agent_seconds", "agent_peak", "interrupts", "steers", "utc_offset"].filter((key) => line[key] !== undefined).map((key) => [key, line[key]])),
|
|
207
210
|
stretch_ref: line.stretch_ref, started_at: line.started_at, at: line.ended_at, from_archive: true,
|
|
208
211
|
};
|
|
209
|
-
out.push({ entry, client: line.client ?? "claude" });
|
|
212
|
+
out.push({ entry, client: line.client ?? "claude", signed });
|
|
210
213
|
}
|
|
211
214
|
}
|
|
212
215
|
return out;
|
package/preserve.mjs
CHANGED
|
@@ -24,8 +24,8 @@
|
|
|
24
24
|
* (~/.worktrust/key.json) when there is one. Today waits for the next run. Nothing leaves this computer.
|
|
25
25
|
*/
|
|
26
26
|
import { execFileSync, spawnSync } from "node:child_process";
|
|
27
|
-
import { createHash, createPrivateKey, createPublicKey, randomBytes, sign, verify } from "node:crypto";
|
|
28
|
-
import { appendFileSync, copyFileSync, existsSync, mkdirSync, readFileSync, readdirSync, statSync, writeFileSync } from "node:fs";
|
|
27
|
+
import { createHash, createPrivateKey, createPublicKey, generateKeyPairSync, randomBytes, sign, verify } from "node:crypto";
|
|
28
|
+
import { appendFileSync, chmodSync, copyFileSync, existsSync, mkdirSync, readFileSync, readdirSync, statSync, writeFileSync } from "node:fs";
|
|
29
29
|
import { homedir, platform } from "node:os";
|
|
30
30
|
import { dirname, join, relative } from "node:path";
|
|
31
31
|
import { createInterface } from "node:readline/promises";
|
|
@@ -193,9 +193,37 @@ function deviceKey() {
|
|
|
193
193
|
try {
|
|
194
194
|
const key = JSON.parse(Buffer.from(readFileSync(home(".worktrust", "key.json"), "utf8"), "base64").toString("utf8"));
|
|
195
195
|
const privateKey = createPrivateKey(key.device);
|
|
196
|
-
return { privateKey, publicX: createPublicKey(privateKey).export({ format: "jwk" }).x };
|
|
196
|
+
return { privateKey, publicX: createPublicKey(privateKey).export({ format: "jwk" }).x, kind: "device" };
|
|
197
197
|
} catch { return null; }
|
|
198
198
|
}
|
|
199
|
+
/**
|
|
200
|
+
* THE LOCAL ARCHIVE KEY (owner, 2026-10-10): a computer that is not coupled still signs its archive, with an Ed25519 key made
|
|
201
|
+
* here (~/.worktrust/archive-key.json, mode 600, folder 700), so a day's root can be told from an edit and the chain stays one
|
|
202
|
+
* computer's when it is coupled later. It needs no account and no network and never leaves this computer. It is CONTINUITY,
|
|
203
|
+
* not proof of time: a day it signed is sent as reconstructed, never as measured; only the coupled device key's signature
|
|
204
|
+
* counts as this computer witnessing a day. It is never offered as the device key at pairing: a private key that lived on
|
|
205
|
+
* disk before the pairing would weaken the fresh proof of possession the pairing binds, for nothing the record would gain.
|
|
206
|
+
*/
|
|
207
|
+
const ARCHIVE_KEY_FILE = home(".worktrust", "archive-key.json");
|
|
208
|
+
function archiveKey(create = false) {
|
|
209
|
+
try {
|
|
210
|
+
const kept = JSON.parse(readFileSync(ARCHIVE_KEY_FILE, "utf8"));
|
|
211
|
+
const privateKey = createPrivateKey(kept.private);
|
|
212
|
+
return { privateKey, publicX: createPublicKey(privateKey).export({ format: "jwk" }).x, kind: "archive", made: false };
|
|
213
|
+
} catch { /* none yet, or unreadable */ }
|
|
214
|
+
if (!create) return null;
|
|
215
|
+
try {
|
|
216
|
+
const pair = generateKeyPairSync("ed25519");
|
|
217
|
+
const privatePem = pair.privateKey.export({ format: "pem", type: "pkcs8" }), publicX = pair.publicKey.export({ format: "jwk" }).x;
|
|
218
|
+
mkdirSync(home(".worktrust"), { recursive: true, mode: 0o700 });
|
|
219
|
+
try { chmodSync(home(".worktrust"), 0o700); } catch { /* Windows */ }
|
|
220
|
+
writeFileSync(ARCHIVE_KEY_FILE, `${JSON.stringify({ format: "worktrust-archive-key/1", public: publicX, private: privatePem, created: new Date().toISOString() }, null, 1)}\n`, { mode: 0o600, flag: "wx" });
|
|
221
|
+
try { chmodSync(ARCHIVE_KEY_FILE, 0o600); } catch { /* Windows */ }
|
|
222
|
+
return { privateKey: pair.privateKey, publicX, kind: "archive", made: true };
|
|
223
|
+
} catch { return archiveKey(false); }
|
|
224
|
+
}
|
|
225
|
+
/** This computer's keys for the archive: the device key when coupled, else the local archive key; both are "ours" for sealing. */
|
|
226
|
+
const ownKeys = () => [deviceKey(), archiveKey(false)].filter(Boolean);
|
|
199
227
|
|
|
200
228
|
/** Every line of an archive, where it lives, parsed or not. */
|
|
201
229
|
function readArchive(dir) {
|
|
@@ -233,8 +261,8 @@ function check(dir) {
|
|
|
233
261
|
if (manifest && typeof manifest.signature === "string" && !signedBy(manifest)) return broken("manifest.json", "its signature does not verify with the key named in it (the count or the last line was changed)");
|
|
234
262
|
const days = new Map();
|
|
235
263
|
for (const line of lines) days.set(line.day, [...(days.get(line.day) ?? []), line]);
|
|
236
|
-
const mine = deviceKey()?.publicX ?? null;
|
|
237
|
-
let signed = 0, ours = 0;
|
|
264
|
+
const mine = deviceKey()?.publicX ?? null, local = archiveKey(false)?.publicX ?? null;
|
|
265
|
+
let signed = 0, ours = 0, archived = 0;
|
|
238
266
|
for (const name of readdirSafe(join(dir, "proofs"))) if (!days.has(name.replace(/\.json$/, ""))) return broken(`proofs/${name}`, "a proof for a day with no lines");
|
|
239
267
|
for (const [day, ofDay] of days) {
|
|
240
268
|
const where = `proofs/${day}.json`;
|
|
@@ -245,8 +273,9 @@ function check(dir) {
|
|
|
245
273
|
if (!signedBy(proof)) return broken(where, "the signature does not verify with the key named in it");
|
|
246
274
|
signed += 1;
|
|
247
275
|
if (proof.public_key === mine) ours += 1;
|
|
276
|
+
else if (local && proof.public_key === local) archived += 1;
|
|
248
277
|
}
|
|
249
|
-
return { lines, days, signed, ours, manifest, proofs: new Map([...days.keys()].map((day) => [day, readJson(join(dir, "proofs", `${day}.json`)).value])) };
|
|
278
|
+
return { lines, days, signed, ours, archived, manifest, proofs: new Map([...days.keys()].map((day) => [day, readJson(join(dir, "proofs", `${day}.json`)).value])) };
|
|
250
279
|
}
|
|
251
280
|
/** Whether a signed body (a day's proof, the manifest) verifies under the key it names. */
|
|
252
281
|
function signedBy(document) {
|
|
@@ -295,8 +324,11 @@ function archive(dir) {
|
|
|
295
324
|
// A day that gained lines gets its root again over all of its lines; the lines themselves are never rewritten.
|
|
296
325
|
// THIS KEY SIGNS ONLY ITS OWN LINES (0.6.18, audit S7): a day is signed when every earlier line of it was already under
|
|
297
326
|
// this key's signature (or there were none); a day that came into the folder from elsewhere keeps an unsigned root.
|
|
298
|
-
|
|
299
|
-
|
|
327
|
+
// THE SIGNING KEY (owner, 2026-10-10): the device key when this computer is coupled, else the local archive key, made now when
|
|
328
|
+
// there is none. A day or a manifest either of this computer's keys sealed is this computer's to seal again.
|
|
329
|
+
const key = deviceKey() ?? archiveKey(true);
|
|
330
|
+
const mineX = new Set(ownKeys().map((own) => own.publicX));
|
|
331
|
+
const ours = (document) => !document || (key && typeof document.signature === "string" && mineX.has(document.public_key));
|
|
300
332
|
mkdirSync(join(dir, "proofs"), { recursive: true });
|
|
301
333
|
for (const day of new Set([...fresh, ...additions].map((line) => line.day))) {
|
|
302
334
|
const own = !existing.days?.has(day) || ours(existing.proofs?.get(day));
|
|
@@ -308,7 +340,8 @@ function archive(dir) {
|
|
|
308
340
|
if (fresh.length + additions.length > 0 || !existing.manifest) writeFileSync(join(dir, "manifest.json"), `${JSON.stringify(sealed({ format: "worktrust-ai-evidence/1", collector_version: COLLECTOR, created: existing.manifest?.created ?? new Date().toISOString(), updated: new Date().toISOString(), clients: [...new Set(all.map((line) => line.client))].sort(), ...IDS, count: all.length, head: prev, ...(manifestKey ? { public_key: manifestKey.publicX } : {}) }, manifestKey), null, 1)}\n`);
|
|
309
341
|
say();
|
|
310
342
|
const stretches = all.filter((line) => !line.supplements).length;
|
|
311
|
-
say(` ✓ ${fresh.length} new day-stretch${fresh.length === 1 ? "" : "es"} archived in ${dir}: it holds ${stretches}, the session hook measures ${measured.size} finished ones here now${key ? ", each day's root signed with this computer's device key" : ", unsigned (no
|
|
343
|
+
say(` ✓ ${fresh.length} new day-stretch${fresh.length === 1 ? "" : "es"} archived in ${dir}: it holds ${stretches}, the session hook measures ${measured.size} finished ones here now${key?.kind === "device" ? ", each day's root signed with this computer's device key" : key ? ", each day's root signed with this computer's local archive key" : ", unsigned (no key could be made on this computer)"}.`);
|
|
344
|
+
if (key?.kind === "archive") say(` ${key.made ? "A local archive key was made" : "The local archive key"} in ${ARCHIVE_KEY_FILE} (only you can read it): it signs this archive so a day can be told from an edit; it never leaves this computer, needs no account, and is no proof of time (such days reach WorkTrust as reconstructed, never as verified hours).`);
|
|
312
345
|
if (additions.length > 0) say(` ${additions.length} stretch${additions.length === 1 ? "" : "es"} already here gained the newer measurements, each in a supplement line; nothing earlier was rewritten.`);
|
|
313
346
|
if (waiting > 0) say(` ${waiting} of today wait for tomorrow's run: a day is archived once it is over.`);
|
|
314
347
|
say(" Metadata only: clocks, counts, model names, a hash of each project's name. Nothing was sent.");
|
|
@@ -318,8 +351,9 @@ function verifyArchive(dir) {
|
|
|
318
351
|
const result = check(dir);
|
|
319
352
|
if (result.broken) { say(` BROKEN ${result.broken}`); process.exit(1); }
|
|
320
353
|
if (result.lines.length === 0) { say(` Nothing to verify in ${dir}.`); return; }
|
|
321
|
-
const
|
|
322
|
-
const
|
|
354
|
+
const others = result.signed - result.ours - result.archived;
|
|
355
|
+
const daySeal = result.signed === 0 ? "no day signed" : result.ours === result.signed ? `${result.signed} signed by this computer's key` : result.archived === result.signed ? `${result.signed} signed by this computer's local archive key (continuity, no proof of time)` : `${result.signed} signed (${result.ours} by this computer's key, ${result.archived} by its local archive key, ${others} by another key named in them)`;
|
|
356
|
+
const seal = typeof result.manifest?.signature !== "string" ? "manifest unsigned" : result.manifest.public_key === deviceKey()?.publicX ? "manifest signed by this computer's key" : result.manifest.public_key === archiveKey(false)?.publicX ? "manifest signed by this computer's local archive key" : "manifest signed by another key named in it";
|
|
323
357
|
const added = result.lines.filter((line) => line.supplements).length;
|
|
324
358
|
say(` OK ${result.lines.length - added} stretches${added ? ` (and ${added} supplement${added === 1 ? "" : "s"})` : ""} · ${result.days.size} days · the chain is whole · every day's root matches · ${daySeal} · ${seal}`);
|
|
325
359
|
}
|
package/worktrust.mjs
CHANGED
|
@@ -8,15 +8,24 @@
|
|
|
8
8
|
* npx worktrust --dry-run show the plan only; nothing is written, nothing is sent
|
|
9
9
|
* npx worktrust --yes no question (for scripts); the computer is still approved in the app
|
|
10
10
|
* npx worktrust --device a computer without a browser (SSH): type a code on another device
|
|
11
|
-
* npx worktrust
|
|
12
|
-
* npx worktrust
|
|
13
|
-
* npx worktrust
|
|
14
|
-
* npx worktrust
|
|
11
|
+
* npx worktrust connect couple again, also on a computer already coupled
|
|
12
|
+
* npx worktrust update this computer onto the newest CLI, same key, no new pairing
|
|
13
|
+
* npx worktrust history send this computer's earlier sessions as history (asks first)
|
|
14
|
+
* npx worktrust history --rebuild the same as history (0.10.5: history always re-measures); WorkTrust replaces this computer's
|
|
15
15
|
* earlier lines day by day, never counting a day twice (shows the plan, asks first)
|
|
16
|
-
* npx worktrust
|
|
17
|
-
* already deleted, marked as from your archive (shows the plan, asks first)
|
|
18
|
-
*
|
|
19
|
-
*
|
|
16
|
+
* npx worktrust history --from-archive [dir] send what your local archive holds of sessions your AI apps have
|
|
17
|
+
* already deleted, marked as from your archive (shows the plan, asks first):
|
|
18
|
+
* a day this computer's device key signed as measured, every other day
|
|
19
|
+
* (unsigned, the local archive key's, another computer's) as reconstructed
|
|
20
|
+
* npx worktrust history --from-folder <dir> your own copy of an AI app's session folder (a backed-up ~/.claude/projects,
|
|
21
|
+
* ~/.codex/sessions): the days this computer's own sessions lack, reconstructed,
|
|
22
|
+
* never verified hours (shows the plan, asks first; 0.10.10)
|
|
23
|
+
* npx worktrust history --export <path> a ChatGPT or Claude data export (the zip, its folder or conversations.json)
|
|
24
|
+
* as history: hours RECONSTRUCTED from its clocks, shown with their origin,
|
|
25
|
+
* never verified hours (shows the plan, asks first; 0.10.10). The bare
|
|
26
|
+
* command on a coupled computer offers an export lying in ~/Downloads once.
|
|
27
|
+
* npx worktrust disconnect show what comes out, ask, take it out again
|
|
28
|
+
* npx worktrust status what is coupled here
|
|
20
29
|
* npx worktrust@latest preserve how long each AI app here keeps its sessions (--apply keeps them,
|
|
21
30
|
* --archive [dir] a local metadata-only record, --verify [dir] checks it,
|
|
22
31
|
* --summary [dir] counts hours, tokens and parallel sessions from it);
|
|
@@ -69,19 +78,19 @@ import { createInterface as lines } from "node:readline";
|
|
|
69
78
|
import { fileURLToPath } from "node:url";
|
|
70
79
|
|
|
71
80
|
const args = process.argv.slice(2);
|
|
72
|
-
const VALUED = ["--name", "--origin", "--url"];
|
|
81
|
+
const VALUED = ["--name", "--origin", "--url", "--export", "--from-folder"];
|
|
73
82
|
const command = args.find((arg, at) => !arg.startsWith("--") && !(at > 0 && VALUED.includes(args[at - 1]))) ?? (args.includes("--help") ? "help" : "default");
|
|
74
83
|
const flag = (name) => { const at = args.indexOf(`--${name}`); return at >= 0 ? args[at + 1] : undefined; };
|
|
75
84
|
const has = (name) => args.includes(`--${name}`);
|
|
76
85
|
/** This CLI's version, said to the door so the app can tell which computer runs an old one (check-cli-package holds it equal to package.json). */
|
|
77
|
-
const CLI_VERSION = "0.10.
|
|
86
|
+
const CLI_VERSION = "0.10.10";
|
|
78
87
|
const ORIGIN = (flag("origin") ?? process.env.WORKTRUST_ORIGIN ?? "https://app.worktrust.io").replace(/\/$/, "");
|
|
79
88
|
const MCP = flag("url") ?? process.env.WORKTRUST_MCP_URL ?? `${ORIGIN}/api/mcp`;
|
|
80
89
|
const HOME_DIR = join(homedir(), ".worktrust");
|
|
81
90
|
const HERE = dirname(fileURLToPath(import.meta.url));
|
|
82
|
-
const SCRIPTS = ["setup-mcp.mjs", "log-session.mjs", "count-behaviour.mjs", "transcript-readers.mjs", "session-databases.mjs", "config-edits.mjs", "stretch-evidence.mjs"];
|
|
91
|
+
const SCRIPTS = ["setup-mcp.mjs", "log-session.mjs", "count-behaviour.mjs", "transcript-readers.mjs", "session-databases.mjs", "config-edits.mjs", "stretch-evidence.mjs", "chat-exports.mjs"];
|
|
83
92
|
/** The modules the scripts import by name from beside them; a download keeps that name. */
|
|
84
|
-
const IMPORTED = new Set(["transcript-readers.mjs", "session-databases.mjs", "config-edits.mjs", "stretch-evidence.mjs"]);
|
|
93
|
+
const IMPORTED = new Set(["transcript-readers.mjs", "session-databases.mjs", "config-edits.mjs", "stretch-evidence.mjs", "chat-exports.mjs"]);
|
|
85
94
|
const downloaded = (name) => (IMPORTED.has(name) ? name : `${name}.download.mjs`);
|
|
86
95
|
const BUNDLED = SCRIPTS.every((name) => existsSync(join(HERE, name)));
|
|
87
96
|
const PLACEHOLDER = `wt_${"0".repeat(43)}`;
|
|
@@ -219,7 +228,7 @@ async function pairByBrowser(host, extra) {
|
|
|
219
228
|
const exchange = await post("/api/cli/token", { device_code: secret, code, code_verifier: verifier }).catch(() => null);
|
|
220
229
|
if (!exchange || exchange.status !== 200 || !exchange.json.token) fail(`the approval could not be exchanged (${exchange?.json?.error ?? "no answer"}). Run \`worktrust connect\` again.`);
|
|
221
230
|
say(` ✓ Approved as "${exchange.json.label}"${exchange.json.account ? ` for the WorkTrust account ${exchange.json.account}` : ""}`);
|
|
222
|
-
if (exchange.json.account) say(" Not your account? Run `npx worktrust
|
|
231
|
+
if (exchange.json.account) say(" Not your account? Run `npx worktrust disconnect` now and revoke it in WorkTrust.");
|
|
223
232
|
if (extraBound && exchange.json.bound === false) say(" ! WorkTrust did not bind the key to this computer; it works like a key made by hand.");
|
|
224
233
|
return paired(exchange.json);
|
|
225
234
|
}
|
|
@@ -248,7 +257,7 @@ async function pairByCode(host, extra) {
|
|
|
248
257
|
if (!answer) continue;
|
|
249
258
|
if (answer.status === 200 && answer.json.token) {
|
|
250
259
|
say(` ✓ Approved as "${answer.json.label}"${answer.json.account ? ` for the WorkTrust account ${answer.json.account}` : ""}`);
|
|
251
|
-
if (answer.json.account) say(" Not your account? Run `npx worktrust
|
|
260
|
+
if (answer.json.account) say(" Not your account? Run `npx worktrust disconnect` now and revoke it in WorkTrust.");
|
|
252
261
|
return paired(answer.json);
|
|
253
262
|
}
|
|
254
263
|
if (answer.json.error === "slow_down") wait += 2000;
|
|
@@ -375,7 +384,7 @@ async function copiedHere(key) {
|
|
|
375
384
|
const url = `${new URL(key.url).origin}/api/cli/moved`, body = JSON.stringify(computerIds());
|
|
376
385
|
await fetch(url, { method: "POST", headers: { "content-type": "application/json", authorization: `Bearer ${key.token}`, ...proof(key.device, url, body) }, body });
|
|
377
386
|
} catch { /* offline: it is told next time */ }
|
|
378
|
-
process.stderr.write("WorkTrust: this key was made on another computer (copied from a backup?). Nothing is sent from here; run `npx worktrust
|
|
387
|
+
process.stderr.write("WorkTrust: this key was made on another computer (copied from a backup?). Nothing is sent from here; run `npx worktrust connect` on this computer.\n");
|
|
379
388
|
return true;
|
|
380
389
|
}
|
|
381
390
|
|
|
@@ -442,7 +451,7 @@ async function bridge() {
|
|
|
442
451
|
let message;
|
|
443
452
|
try { message = JSON.parse(line); } catch { continue; }
|
|
444
453
|
if (message.method === "initialize" && message.params?.clientInfo?.name) agent = `${message.params.clientInfo.name}/${message.params.clientInfo.version ?? "0"} (worktrust-bridge) worktrust-cli/${CLI_VERSION}`;
|
|
445
|
-
if (!key) { if (message.id !== undefined) answer(message.id, "WorkTrust is not connected on this computer: run `npx worktrust
|
|
454
|
+
if (!key) { if (message.id !== undefined) answer(message.id, "WorkTrust is not connected on this computer: run `npx worktrust connect`."); continue; }
|
|
446
455
|
try {
|
|
447
456
|
const response = await fetch(key.url, { method: "POST", headers: { "content-type": "application/json", accept: "application/json, text/event-stream", authorization: `Bearer ${key.token}`, "user-agent": agent, ...(session ? { "mcp-session-id": session } : {}), ...proof(key.device, key.url, line) }, body: line });
|
|
448
457
|
session = response.headers.get("mcp-session-id") ?? session;
|
|
@@ -455,7 +464,7 @@ async function bridge() {
|
|
|
455
464
|
const again = await fetch(key.url, { method: "POST", headers: { "content-type": "application/json", accept: "application/json, text/event-stream", authorization: `Bearer ${key.token}`, "user-agent": agent, ...(session ? { "mcp-session-id": session } : {}), ...proof(key.device, key.url, line) }, body: line });
|
|
456
465
|
if (again.status !== 401) { const text = await again.text(); const parts = (again.headers.get("content-type") ?? "").includes("event-stream") ? text.split("\n").filter((part) => part.startsWith("data:")).map((part) => part.slice(5).trim()) : [text.trim()]; for (const part of parts.filter(Boolean)) process.stdout.write(`${part}\n`); continue; }
|
|
457
466
|
}
|
|
458
|
-
answer(message.id, "WorkTrust did not accept this computer's key: run `npx worktrust
|
|
467
|
+
answer(message.id, "WorkTrust did not accept this computer's key: run `npx worktrust connect` again.");
|
|
459
468
|
continue;
|
|
460
469
|
}
|
|
461
470
|
const text = await response.text();
|
|
@@ -521,7 +530,7 @@ async function sessionEnd() {
|
|
|
521
530
|
*/
|
|
522
531
|
async function update() {
|
|
523
532
|
const key = await freshKey();
|
|
524
|
-
if (!key) fail("this computer has no WorkTrust key file yet. Run npx worktrust
|
|
533
|
+
if (!key) fail("this computer has no WorkTrust key file yet. Run npx worktrust connect.");
|
|
525
534
|
say();
|
|
526
535
|
say(` WorkTrust · update ${hostname().replace(/\.local$/i, "")} to ${CLI_VERSION}`);
|
|
527
536
|
say();
|
|
@@ -655,11 +664,13 @@ async function offerHistory(paths, token, devicePem, url = MCP, rebuild = false)
|
|
|
655
664
|
say(" never deleted, so a day is counted once. Other computers, web sources and days not listed are not touched.");
|
|
656
665
|
}
|
|
657
666
|
if (has("dry-run")) { say(" Dry run: nothing was sent."); return; }
|
|
658
|
-
if (!has("history") && !(rebuild ? await ask("Send them (re-measured; this computer's earlier lines for these days are replaced, a day is counted once)?", false) : await ask("Send these as history (hours and tokens per day; never text)?", false))) { historyDone(false); say(" Not sent. Send them later with: npx worktrust
|
|
667
|
+
if (!has("history") && !(rebuild ? await ask("Send them (re-measured; this computer's earlier lines for these days are replaced, a day is counted once)?", false) : await ask("Send these as history (hours and tokens per day; never text)?", false))) { historyDone(false); say(" Not sent. Send them later with: npx worktrust"); return; }
|
|
668
|
+
// Marked unfinished before the first batch leaves (0.10.9): a send stopped halfway (Ctrl+C, a closed lid) is finished by the next run.
|
|
669
|
+
historyDone(false);
|
|
659
670
|
const sent = await run(paths["log-session.mjs"], ["--history", ...(rebuild ? ["--rebuild"] : [])], token, true, env);
|
|
660
671
|
historyDone(sent.code === 0);
|
|
661
|
-
if (rebuild) say(sent.code === 0 ? " ✓ Rebuilt. This computer's earlier lines for those days were replaced; the record shows each replacement." : " Not all of it arrived. Run npx worktrust
|
|
662
|
-
else say(sent.code === 0 ? " ✓ Sent as history. Measured sessions count toward your verified hours; a day WorkTrust already holds is kept once." : " Not all of it arrived. Run npx worktrust
|
|
672
|
+
if (rebuild) say(sent.code === 0 ? " ✓ Rebuilt. This computer's earlier lines for those days were replaced; the record shows each replacement." : " Not all of it arrived. Run npx worktrust again: it finishes what did not arrive, a day already rebuilt is counted once.");
|
|
673
|
+
else say(sent.code === 0 ? " ✓ Sent as history. Measured sessions count toward your verified hours; a day WorkTrust already holds is kept once." : " Not all of it arrived. Run npx worktrust history again: a line already received is kept once.");
|
|
663
674
|
}
|
|
664
675
|
|
|
665
676
|
/** The version stamped in the stable copy in ~/.worktrust, the CLI this computer ran before an update; null without one. */
|
|
@@ -678,7 +689,7 @@ async function offerRebuild(previousVersion, paths, key) {
|
|
|
678
689
|
say(" differently (each answer's tokens counted once, nothing lost at midnight, when each stretch began, how you steered");
|
|
679
690
|
say(" the agent, what the seconds were, more AI apps). You can re-measure the");
|
|
680
691
|
say(" sessions still on this computer and have WorkTrust replace this computer's earlier lines, day by day, never counting");
|
|
681
|
-
say(" a day twice. Later: npx worktrust
|
|
692
|
+
say(" a day twice. Later: npx worktrust");
|
|
682
693
|
if (!(await ask("Show the plan and rebuild now?", false))) { say(" Not now."); return; }
|
|
683
694
|
await offerHistory(paths, key.token, key.device ?? null, key.url, true);
|
|
684
695
|
}
|
|
@@ -691,7 +702,9 @@ const HISTORY_STATE = join(HOME_DIR, "history.json");
|
|
|
691
702
|
function historyDone(complete) {
|
|
692
703
|
try { ensureHome(); writeFileSync(HISTORY_STATE, JSON.stringify({ version: CLI_VERSION, at: new Date().toISOString(), complete }), { mode: 0o600 }); } catch { /* the next run asks again */ }
|
|
693
704
|
}
|
|
694
|
-
|
|
705
|
+
/** Complete AND measured by this very CLI (0.10.9): a run stopped after the update, before the history, leaves the history
|
|
706
|
+
* measured by an older version, and the next run must offer it again rather than read "complete" as done. */
|
|
707
|
+
const historyComplete = () => { try { const state = JSON.parse(readFileSync(HISTORY_STATE, "utf8")); return state.complete === true && state.version === CLI_VERSION; } catch { return false; } };
|
|
695
708
|
|
|
696
709
|
/**
|
|
697
710
|
* THE SAME COMMAND AGAIN DOES WHAT IS LEFT (0.10.5). On a computer already coupled, `npx worktrust@latest` brings it onto
|
|
@@ -704,18 +717,22 @@ async function again() {
|
|
|
704
717
|
if (before && before !== CLI_VERSION) { await update(); return; }
|
|
705
718
|
if (!historyComplete()) {
|
|
706
719
|
const key = await freshKey();
|
|
707
|
-
if (key) { say(); say(
|
|
720
|
+
if (key) { say(); say(` Your earlier sessions are not yet measured by worktrust ${CLI_VERSION} in WorkTrust, or did not all arrive. This finishes them.`); await offerHistory(await scripts(), key.token, key.device ?? null, key.url, true); }
|
|
708
721
|
}
|
|
722
|
+
// A WEB CHAT'S EXPORT LYING IN DOWNLOADS (0.10.10): offered once, Enter is No.
|
|
723
|
+
{ const key = await freshKey(); if (key) await offerDownloads(await scripts(), key); }
|
|
709
724
|
say();
|
|
710
725
|
await status();
|
|
711
726
|
say();
|
|
712
|
-
say(" This computer is coupled. `npx worktrust
|
|
727
|
+
say(" This computer is coupled. `npx worktrust connect` couples it again; `npx worktrust disconnect` takes it out.");
|
|
713
728
|
}
|
|
714
729
|
|
|
715
730
|
async function history() {
|
|
716
731
|
const key = await freshKey();
|
|
717
732
|
if (!key) fail("this computer is not coupled through the key file. Run npx worktrust first.");
|
|
718
733
|
if (has("from-archive")) return offerArchive(await scripts(), key);
|
|
734
|
+
if (has("export")) { if (!flag("export") || flag("export").startsWith("--")) fail("--export needs the export's path: the zip, its folder, or conversations.json"); await offerExport(await scripts(), key, flag("export")); return; }
|
|
735
|
+
if (has("from-folder")) { if (!flag("from-folder") || flag("from-folder").startsWith("--")) fail("--from-folder needs the copied folder's path"); await offerFolder(await scripts(), key, flag("from-folder")); return; }
|
|
719
736
|
// ONE PATH (0.10.5): sending is re-measuring. On a computer WorkTrust has never heard from nothing is replaced, so it is a
|
|
720
737
|
// plain send; after a failure, a merge or an older CLI, the same command replaces day by day. `--rebuild` still reads.
|
|
721
738
|
await offerHistory(await scripts(), key.token, key.device ?? null, key.url, true);
|
|
@@ -738,6 +755,94 @@ async function offerArchive(paths, key) {
|
|
|
738
755
|
say(sent.code === 0 ? " ✓ Sent as history from your archive. It shows in WorkTrust as earlier work, marked as such, never as verified hours." : ` Not sent: ${sent.out.trim().split("\n").pop()}`);
|
|
739
756
|
}
|
|
740
757
|
|
|
758
|
+
/**
|
|
759
|
+
* A WEB CHAT'S DATA EXPORT AS HISTORY (0.10.10, owner 2026-10-10). ChatGPT's and Claude's exports (the zip, its folder, or
|
|
760
|
+
* conversations.json) go through the history door as RECONSTRUCTED hours: shown with their origin, never verified
|
|
761
|
+
* hours, because the file can be edited before it is read and no device key witnessed it. Nothing of a conversation
|
|
762
|
+
* leaves: not its title, not a message; the hook reads the clocks, the person's own turns and the model's name. The
|
|
763
|
+
* plan first (the product, conversations, days, hours, first and last month), then one question; Enter is No;
|
|
764
|
+
* `--dry-run` stops before it; `--history` says yes in advance. Answers whether the export arrived whole.
|
|
765
|
+
*/
|
|
766
|
+
const EXPORT_PRODUCT = { chatgpt: "ChatGPT", "claude-web": "Claude on the web" };
|
|
767
|
+
async function offerExport(paths, key, path) {
|
|
768
|
+
const env = { WORKTRUST_MCP_URL: key.url, ...(key.device ? { WORKTRUST_DEVICE_KEY: key.device } : {}) };
|
|
769
|
+
const counted = await run(paths["log-session.mjs"], ["--history", "--export", path, "--dry-run", "--summary"], key.token, true, env);
|
|
770
|
+
let found = null;
|
|
771
|
+
try { found = JSON.parse(counted.out.trim().split("\n").pop()); } catch { /* no line: the export could not be read */ }
|
|
772
|
+
const report = found?.exports?.[0];
|
|
773
|
+
say();
|
|
774
|
+
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; }
|
|
775
|
+
const product = EXPORT_PRODUCT[report.vendor] ?? report.vendor;
|
|
776
|
+
if (!report.days) { say(` ${product} export · ${report.conversations} conversations, none with a clock to place: nothing to send.`); return true; }
|
|
777
|
+
say(` ${product} export · ${report.conversations} conversations · ${report.days} days · ${report.hours} reconstructed hours · ${String(report.first).slice(0, 7)} … ${String(report.last).slice(0, 7)}`);
|
|
778
|
+
say(" Hours reconstructed from the export's own clocks: shown with their origin, never verified hours. Never a title or a message.");
|
|
779
|
+
if (has("dry-run")) { say(" Dry run: nothing was sent."); return false; }
|
|
780
|
+
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; }
|
|
781
|
+
const sent = await run(paths["log-session.mjs"], ["--history", "--export", path], key.token, true, env);
|
|
782
|
+
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.`);
|
|
783
|
+
if (sent.code !== 0) return false;
|
|
784
|
+
// THE EXPORT REPLACES (owner, 2026-10-10): the door withdrew the product's earlier connector lines on the export's days by itself and
|
|
785
|
+
// says so; the lines an AI app reported under no product on those days may describe the same conversations, and go only on a yes.
|
|
786
|
+
const counts = lastCounts(sent.out);
|
|
787
|
+
if (counts.superseded > 0) say(` ${counts.superseded} earlier line${counts.superseded === 1 ? "" : "s"} of ${product} on those days, brought in by a connector, ${counts.superseded === 1 ? "is" : "are"} withdrawn and kept (each with a correction row): the export's lines count, a day counts once.`);
|
|
788
|
+
if (counts.unknownOnDays > 0) {
|
|
789
|
+
const n = counts.unknownOnDays;
|
|
790
|
+
say(` ${n} earlier line${n === 1 ? "" : "s"} an AI app reported for these days, under no product, may describe the same conversations.`);
|
|
791
|
+
if (has("withdraw-unknown") || (await ask(`Also withdraw ${n} earlier line${n === 1 ? "" : "s"} an AI app reported for these days?`, false))) {
|
|
792
|
+
const again = await run(paths["log-session.mjs"], ["--history", "--export", path, "--withdraw-unknown"], key.token, true, env);
|
|
793
|
+
const done = lastCounts(again.out);
|
|
794
|
+
say(again.code === 0 ? ` ✓ Withdrawn and kept: ${done.unknownWithdrawn} earlier line${done.unknownWithdrawn === 1 ? "" : "s"}, each with a correction row; never deleted.` : ` Not withdrawn: ${again.out.trim().split("\n").pop()}`);
|
|
795
|
+
} else say(` Kept. Later: npx worktrust history --export ${path} --withdraw-unknown`);
|
|
796
|
+
}
|
|
797
|
+
return true;
|
|
798
|
+
}
|
|
799
|
+
/** The hook's last line of counts after an export send (superseded, unknownOnDays, unknownWithdrawn); zeros when there is none. */
|
|
800
|
+
function lastCounts(out) {
|
|
801
|
+
try { const line = out.trim().split("\n").filter((text) => text.startsWith("{")).pop(); const json = JSON.parse(line ?? "{}"); return { superseded: Number(json.superseded) || 0, unknownOnDays: Number(json.unknownOnDays) || 0, unknownWithdrawn: Number(json.unknownWithdrawn) || 0 }; } catch { return { superseded: 0, unknownOnDays: 0, unknownWithdrawn: 0 }; }
|
|
802
|
+
}
|
|
803
|
+
|
|
804
|
+
/**
|
|
805
|
+
* THE EXPORT LYING IN DOWNLOADS (0.10.10): on a coupled computer the bare command looks in ~/Downloads, its top level
|
|
806
|
+
* only, for a ChatGPT or Claude export it has neither sent nor asked about, and offers each once by the same path as
|
|
807
|
+
* `history --export`; a No is remembered by the file's digest (never a conversation), and the command to send it later is
|
|
808
|
+
* said. A dry run remembers nothing.
|
|
809
|
+
*/
|
|
810
|
+
async function offerDownloads(paths, key) {
|
|
811
|
+
const found = await run(paths["log-session.mjs"], ["--find-exports"], "", true, { WORKTRUST_MCP_URL: "" });
|
|
812
|
+
let exports = [];
|
|
813
|
+
try { exports = JSON.parse(found.out.trim().split("\n").pop()); } catch { return; }
|
|
814
|
+
for (const one of Array.isArray(exports) ? exports : []) {
|
|
815
|
+
if (one.sent || one.offered) continue;
|
|
816
|
+
say();
|
|
817
|
+
say(` A ${EXPORT_PRODUCT[one.vendor] ?? one.vendor} export lies in your Downloads folder: ${one.path}`);
|
|
818
|
+
const sent = await offerExport(paths, key, one.path);
|
|
819
|
+
if (!sent && !has("dry-run")) await run(paths["log-session.mjs"], ["--export-offered", one.digest], "", true, { WORKTRUST_MCP_URL: "" });
|
|
820
|
+
}
|
|
821
|
+
}
|
|
822
|
+
|
|
823
|
+
/**
|
|
824
|
+
* A COPIED SESSION FOLDER AS HISTORY (owner, 2026-10-10, one rule): a person's own backup of ~/.claude/projects, ~/.codex/sessions
|
|
825
|
+
* or an Antigravity brain folder, read by the hook with the same readers and clock as the live folders (never those), its days
|
|
826
|
+
* RECONSTRUCTED and titled as from a copied folder; a stretch the live folders already hold is skipped (they win). The plan
|
|
827
|
+
* first, then one question; Enter is No; `--dry-run` stops before it; `--history` says yes in advance.
|
|
828
|
+
*/
|
|
829
|
+
async function offerFolder(paths, key, dir) {
|
|
830
|
+
const env = { WORKTRUST_MCP_URL: key.url, ...(key.device ? { WORKTRUST_DEVICE_KEY: key.device } : {}) };
|
|
831
|
+
const counted = await run(paths["log-session.mjs"], ["--history", "--from-folder", dir, "--dry-run", "--summary"], key.token, true, env);
|
|
832
|
+
let found = null;
|
|
833
|
+
try { found = JSON.parse(counted.out.trim().split("\n").pop()); } catch { /* no line: the folder could not be read */ }
|
|
834
|
+
const report = found?.folder;
|
|
835
|
+
say();
|
|
836
|
+
if (counted.code !== 0 || !report) { say(` ${counted.out.trim().split("\n").filter(Boolean).pop() ?? "folder: it could not be read"}. Nothing was sent.`); return; }
|
|
837
|
+
say(` Copied session folder · ${report.stretches} stretch${report.stretches === 1 ? "" : "es"} (${report.skipped} already among this computer's own sessions, skipped) · ${report.days} day${report.days === 1 ? "" : "s"} · ${report.hours} reconstructed hours${report.first ? ` · ${report.first} … ${report.last}` : ""}`);
|
|
838
|
+
if (!report.days) { say(" Nothing to send: every day of the copy is already among this computer's own sessions."); return; }
|
|
839
|
+
say(" Hours reconstructed from the copy's own clocks: shown with their origin, never verified hours. Never text.");
|
|
840
|
+
if (has("dry-run")) { say(" Dry run: nothing was sent."); return; }
|
|
841
|
+
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 --from-folder ${dir}`); return; }
|
|
842
|
+
const sent = await run(paths["log-session.mjs"], ["--history", "--from-folder", dir], key.token, true, env);
|
|
843
|
+
say(sent.code === 0 ? " ✓ Sent as history. It shows in WorkTrust as reconstructed, from a copied session folder, never as verified hours; a line already received is kept once." : ` Not all of it arrived. Run npx worktrust history --from-folder ${dir} again: a line already received is kept once.`);
|
|
844
|
+
}
|
|
845
|
+
|
|
741
846
|
/**
|
|
742
847
|
* CODEX WAKES THE HOOK ON A YES (owner, 2026-10-04). Codex has no hook settings: it runs ONE `notify`
|
|
743
848
|
* program at the end of every turn, named on a top-level line of ~/.codex/config.toml. Without it
|
|
@@ -787,7 +892,7 @@ async function offerCodex() {
|
|
|
787
892
|
say(" Codex can wake the session hook at the end of every turn, so Codex work arrives without Claude Code running:");
|
|
788
893
|
say(` ${found.text ? "↻" : "+"} ${CODEX_CONFIG} → ${want}`);
|
|
789
894
|
if (has("dry-run")) { say(" Dry run: nothing was written."); return; }
|
|
790
|
-
if (!has("codex") && !(await ask("Let Codex wake the session hook?", false))) { say(" Not set. npx worktrust
|
|
895
|
+
if (!has("codex") && !(await ask("Let Codex wake the session hook?", false))) { say(" Not set. npx worktrust update asks again."); return; }
|
|
791
896
|
const rows = [...found.rows];
|
|
792
897
|
if (found.text) rows.splice(found.at, found.end - found.at + 1, want);
|
|
793
898
|
else rows.splice(found.insert, 0, ...(found.insert < rows.length && rows[found.insert] !== "" ? [want, ""] : [want]));
|
|
@@ -828,7 +933,7 @@ async function offerAntigravity() {
|
|
|
828
933
|
say(" Antigravity can wake the session hook when its agent stops, so Antigravity work arrives without Claude Code running:");
|
|
829
934
|
say(` ${hooks.worktrust ? "↻" : "+"} ${AGY_HOOKS} → worktrust: Stop runs ${want.Stop[0].command}`);
|
|
830
935
|
if (has("dry-run")) { say(" Dry run: nothing was written."); return; }
|
|
831
|
-
if (!has("antigravity") && !(await ask("Let Antigravity wake the session hook?", false))) { say(" Not set. npx worktrust
|
|
936
|
+
if (!has("antigravity") && !(await ask("Let Antigravity wake the session hook?", false))) { say(" Not set. npx worktrust update asks again."); return; }
|
|
832
937
|
writeAgyHooks({ ...hooks, worktrust: want });
|
|
833
938
|
say(` ✓ Antigravity wakes the session hook. Restart Antigravity to pick it up${existsSync(`${AGY_HOOKS}.worktrust-backup`) ? "; the earlier file is kept as hooks.json.worktrust-backup" : ""}.`);
|
|
834
939
|
}
|
|
@@ -886,16 +991,16 @@ async function status() {
|
|
|
886
991
|
for (const project of Object.values(config.projects ?? {})) Object.assign(servers, project.mcpServers ?? {});
|
|
887
992
|
} catch { /* no Claude Code here */ }
|
|
888
993
|
const door = Object.entries(servers).find(([name, server]) => /worktrust/i.test(`${name} ${server?.url ?? ""} ${(server?.args ?? []).join(" ")}`));
|
|
889
|
-
say(door ? ` Claude Code: coupled (${door[1].url ?? "through the local bridge"})` : " Claude Code: not coupled. Run `npx worktrust
|
|
994
|
+
say(door ? ` Claude Code: coupled (${door[1].url ?? "through the local bridge"})` : " Claude Code: not coupled. Run `npx worktrust connect`.");
|
|
890
995
|
const key = keyStore.load();
|
|
891
996
|
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)");
|
|
892
|
-
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
|
|
997
|
+
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)");
|
|
893
998
|
let hook = false;
|
|
894
999
|
try { hook = /log-session|worktrust\.mjs\\?" hook/.test(readFileSync(join(homedir(), ".claude", "settings.json"), "utf8")); } catch { /* none */ }
|
|
895
1000
|
say(hook ? " Session hook: installed" : " Session hook: not installed");
|
|
896
|
-
if (existsSync(join(homedir(), ".codex"))) { const notify = codexNotify().text ?? ""; say(isOurNotify(notify) ? " Codex: wakes the session hook" : " Codex: does not wake the session hook (npx worktrust
|
|
897
|
-
if (existsSync(join(homedir(), ".hermes"))) { let text = ""; try { text = readFileSync(join(homedir(), ".hermes", "config.yaml"), "utf8"); } catch { /* none */ } say(/worktrust\.mjs\\?" hook --hermes/.test(text) ? " Hermes Agent: wakes the session hook" : " Hermes Agent: does not wake the session hook (npx worktrust
|
|
898
|
-
if (antigravityHere()) say(agyHooks()?.worktrust ? " Antigravity: wakes the session hook" : " Antigravity: does not wake the session hook (npx worktrust
|
|
1001
|
+
if (existsSync(join(homedir(), ".codex"))) { const notify = codexNotify().text ?? ""; say(isOurNotify(notify) ? " Codex: wakes the session hook" : " Codex: does not wake the session hook (npx worktrust update asks)"); }
|
|
1002
|
+
if (existsSync(join(homedir(), ".hermes"))) { let text = ""; try { text = readFileSync(join(homedir(), ".hermes", "config.yaml"), "utf8"); } catch { /* none */ } say(/worktrust\.mjs\\?" hook --hermes/.test(text) ? " Hermes Agent: wakes the session hook" : " Hermes Agent: does not wake the session hook (npx worktrust update writes it)"); }
|
|
1003
|
+
if (antigravityHere()) say(agyHooks()?.worktrust ? " Antigravity: wakes the session hook" : " Antigravity: does not wake the session hook (npx worktrust update asks)");
|
|
899
1004
|
say(existsSync(join(HOME_DIR, "pinned")) ? " Counter: from the package, pinned" : existsSync(join(HOME_DIR, "count-behaviour.mjs")) ? " Counter: follows the site" : " Counter: not installed");
|
|
900
1005
|
await measuredHere();
|
|
901
1006
|
}
|
|
@@ -914,7 +1019,7 @@ async function measuredHere() {
|
|
|
914
1019
|
if (!m || !m.stretches) { say(" Measured here, last 30 days: no finished work stretch yet."); return; }
|
|
915
1020
|
const of = (part, whole, unit) => `${part} of ${whole} ${unit}`;
|
|
916
1021
|
say();
|
|
917
|
-
say(` Measured here, last 30 days: ${m.stretches} work stretches · ${m.hours} h`);
|
|
1022
|
+
say(` Measured here, last 30 days: ${m.stretches} work stretch${m.stretches === 1 ? "" : "es"} · ${m.hours >= 1 ? `${m.hours} h` : "under 1 h"}`);
|
|
918
1023
|
if (m.delivered) say(` verified before delivery ${of(m.verified_first, m.delivered, "stretches that delivered")}`);
|
|
919
1024
|
if (m.failures) say(` recovered failures ${of(m.recovered, m.failures, "failed tool calls")} (${m.blind_retries} retried unchanged)`);
|
|
920
1025
|
if (m.steers) say(` steering that worked ${of(m.effective_steers, m.steers, "times you stepped in")}`);
|
|
@@ -960,7 +1065,14 @@ function help() {
|
|
|
960
1065
|
say(" --rebuild re-measure them with the current rules; WorkTrust replaces this computer's earlier lines,");
|
|
961
1066
|
say(" day by day, never counting a day twice (shows the plan per AI app, asks first; --dry-run: the plan only)");
|
|
962
1067
|
say(" --from-archive [dir] send what your archive (preserve --archive) holds of sessions your AI apps already deleted,");
|
|
963
|
-
say("
|
|
1068
|
+
say(" marked as from your archive: a day this computer's key signed as measured, every other day");
|
|
1069
|
+
say(" as reconstructed, never verified hours (shows the plan, asks first)");
|
|
1070
|
+
say(" --export <path> a ChatGPT or Claude data export (the zip, its folder or conversations.json) as history:");
|
|
1071
|
+
say(" hours reconstructed from its clocks, shown with their origin, never verified hours (asks first);");
|
|
1072
|
+
say(" on its days the export replaces the product's earlier connector lines (withdrawn, kept)");
|
|
1073
|
+
say(" --withdraw-unknown with --export: yes in advance to withdrawing the earlier lines an AI app reported for those days");
|
|
1074
|
+
say(" --from-folder <dir> your own copy of an AI app's session folder (a backed-up ~/.claude/projects, ~/.codex/sessions):");
|
|
1075
|
+
say(" days this computer's own sessions lack, reconstructed, never verified hours (asks first)");
|
|
964
1076
|
say(" worktrust disconnect take WorkTrust out of every AI app here (asks first)");
|
|
965
1077
|
say(" worktrust status what is coupled here");
|
|
966
1078
|
say(" worktrust preserve keep your AI history: the report, then the settings and a local archive, each on your yes");
|