worktrust 0.10.9 → 0.10.11

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/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,14 @@ 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 { stackOfFiles = () => [], displayStackOfFiles = () => [] } = (await import("./stack-rules.mjs").catch(() => null)) ?? {}; // 0.10.11: core's stack rules and the display-only keys (tools_seen), generated (build-stack-rules --check); absent → nothing named, never a guess
278
+ 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
279
  const DATABASE_CLIENTS = ["hermes", "goose", "opencode", "openclaw", "cursor", "copilot"]; // the registry's keys, the name each line carries
264
280
  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
281
+ const READER_FILES = ["transcript-readers.mjs", "session-databases.mjs", "stretch-evidence.mjs", "chat-exports.mjs", "stack-rules.mjs"]; // 0.7.4: the derived record travels with the hook; 0.10.10: the export reader; 0.10.11: the stack rules
266
282
  /** 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
283
  async function installReaders(origin, fromNetwork = false) {
268
284
  let installed = true;
@@ -642,7 +658,7 @@ function payloadFor(stretch) {
642
658
  const cwd = stretch.cwd && existsSync(stretch.cwd) ? stretch.cwd : null;
643
659
  const repo = cwd ? repoOf(cwd) : null;
644
660
  const touched = cwd ? pathsTouched(cwd, new Date(stretch.from).toISOString(), new Date(stretch.to).toISOString()) : { paths: [], committed: false, shas: [] };
645
- const { layer, layers } = layersOf(touched.paths);
661
+ const { layer, layers } = layersOf(touched.paths), stack = stackOfFiles(touched.paths), toolsSeen = displayStackOfFiles(touched.paths); // 0.10.11: the stack and the tools seen, from the same paths, keys only, two fields
646
662
  // The seventh kind, used as it is defined: a stretch that changed no artefact is knowing
647
663
  // something, not building something, and it earns neither an artefact's nor a validation's credit.
648
664
  const kind = touched.paths.length === 0 ? "researched" : touched.committed ? "changed" : "built";
@@ -658,6 +674,8 @@ function payloadFor(stretch) {
658
674
  kind,
659
675
  ...(layer ? { layer } : {}),
660
676
  ...(layers.length > 1 ? { layers } : {}),
677
+ ...(stack.length > 0 ? { stack } : {}),
678
+ ...(toolsSeen.length > 0 ? { tools_seen: toolsSeen } : {}), // its own line: the payload allowlist (hook-presence) reads the key here
661
679
  // Both, or neither: seconds without a basis is exactly the ambiguity the record is trying to
662
680
  // lose, and a basis without seconds says nothing.
663
681
  ...(stretch.seconds !== null ? { seconds: stretch.seconds, duration_basis: "measured" } : {}),
@@ -699,24 +717,56 @@ function payloadFor(stretch) {
699
717
  * exactly what landed. `announce` because one caller is a person watching a terminal and the other
700
718
  * is a hook holding a session's exit open.
701
719
  */
702
- async function sendHistory(door, entries, announce = false, rebuild = false) {
720
+ /**
721
+ * THE BATCHES: at most two hundred lines each. `byDay` (an export, 2026-10-10) never splits a UTC day across two batches unless
722
+ * 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
723
+ * day in two batches would be counted twice.
724
+ */
725
+ function batchesOf(group, byDay) {
726
+ if (!byDay) { const out = []; for (let i = 0; i < group.length; i += 200) out.push(group.slice(i, i + 200)); return out; }
727
+ const days = new Map();
728
+ for (const entry of group) { const day = String(entry.at).slice(0, 10); days.set(day, [...(days.get(day) ?? []), entry]); }
729
+ const out = []; let current = [];
730
+ for (const ofDay of days.values()) {
731
+ 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; }
732
+ if (current.length + ofDay.length > 200) { out.push(current); current = []; }
733
+ current.push(...ofDay);
734
+ }
735
+ if (current.length) out.push(current);
736
+ return out;
737
+ }
738
+ /** THE RECEIPTS' COUNTS (2026-10-10): what an export send replaced, how many AI-app lines lie on its days, how many were withdrawn; summed over the batches, read for the counts alone. */
739
+ const RECEIPTS = { superseded: 0, unknownOnDays: 0, unknownWithdrawn: 0 };
740
+ const noteReceipt = (answer) => {
741
+ try {
742
+ const json = JSON.parse(answer.trim().startsWith("{") ? answer : answer.split("\n").find((row) => row.startsWith("data:"))?.slice(5) ?? "null");
743
+ const receipt = JSON.parse(json?.result?.content?.[0]?.text ?? "{}");
744
+ for (const key of Object.keys(RECEIPTS)) RECEIPTS[key] += Number(receipt[key]) || 0;
745
+ } catch { /* a receipt unread leaves the counts short, never the send */ }
746
+ };
747
+ async function sendHistory(door, entries, announce = false, rebuild = false, named = false, { byDay = false, withdrawUnknown = false } = {}) {
703
748
  let accepted = 0;
704
749
  // A Codex entry goes through Codex's own coupling where one exists (see codexDoor), the rest
705
750
  // through the door given: the record files a line under the coupling that sent it. Antigravity's
706
751
  // go apart too, so their batch can name the client (clientOf).
707
- for (const [source, group] of [["claude", entries.filter((entry) => !entrySource.has(entry))], ["codex", entries.filter((entry) => entrySource.get(entry) === "codex")], ...["antigravity", ...DATABASE_CLIENTS].map((client) => [client, entries.filter((entry) => entrySource.get(entry) === client)])]) {
752
+ // An export's lines go as their own group too (0.10.10), so the record names the product (ChatGPT, Claude on the web).
753
+ 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
754
  const target = source === "codex" ? codexDoor ?? door : door;
709
755
  if (group.length === 0 || !target) continue;
710
- for (let i = 0; i < group.length; i += 200) {
711
- const batch = group.slice(i, i + 200);
756
+ let number = 0;
757
+ for (const batch of batchesOf(group, byDay)) {
758
+ number += 1;
712
759
  // 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
760
  // 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
- const body = JSON.stringify({ jsonrpc: "2.0", id: 1, method: "tools/call", params: { name: "import_history", arguments: { ...(rebuild ? { rebuild: true } : {}), entries: batch.map((entry) => { const { commits, ...rest } = entry; void commits; return rest; }) } } });
715
- 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), ...proofFor(target.url, body) }, body });
761
+ // 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.
762
+ 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; }) } } });
763
+ // `named` (0.10.10): a copied folder's lines name their client too, so the record says which app the copy came from.
764
+ 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
765
  const text = await response.text();
717
- if (announce) console.log(`batch ${Math.floor(i / 200) + 1}: ${response.status} ${text.slice(0, 200).replace(/\\n/g, " ")}`);
766
+ if (announce) console.log(`batch ${number}: ${response.status} ${text.slice(0, 200).replace(/\\n/g, " ")}`);
718
767
  if (!response.ok) break;
719
768
  accepted += batch.length;
769
+ noteReceipt(text);
720
770
  }
721
771
  }
722
772
  return accepted;
@@ -749,7 +799,7 @@ const proofFor = (url, body) => {
749
799
  * on this computer, and the door names a coupling's clients by the user-agent it hears (mcp_identify's
750
800
  * agents_seen). An Antigravity line names Antigravity: the product name, nothing of the work.
751
801
  */
752
- const clientOf = (source, always = false) => (always || source === "antigravity" || DATABASE_CLIENTS.includes(source) ? { "user-agent": `${source ?? "claude"}/hook (worktrust-hook)` } : {});
802
+ const clientOf = (source, always = false) => (always || source === "antigravity" || DATABASE_CLIENTS.includes(source) || EXPORT_CLIENTS.includes(source) ? { "user-agent": `${source ?? "claude"}/hook (worktrust-hook)` } : {});
753
803
 
754
804
  async function send(door, payload) {
755
805
  const body = JSON.stringify({ jsonrpc: "2.0", id: 1, method: "tools/call", params: { name: "log_work", arguments: payload } });
@@ -810,6 +860,113 @@ function historyEntries(floor = null, all = false) {
810
860
  return entries.filter((entry) => !seen.has(entry.stretch_ref) && seen.add(entry.stretch_ref)).sort((a, b) => a.at.localeCompare(b.at));
811
861
  }
812
862
 
863
+ /**
864
+ * A DATA EXPORT'S CONVERSATIONS AS HISTORY (0.10.10, owner 2026-10-10: "hours from an export count as reconstructed, shown,
865
+ * never in verified hours"). The same clock cuts them (a day, gaps capped at IDLE_CAP) and the same measure counts the
866
+ * person's own turns and the model, but the line says `reconstructed`: the file can be edited before it is read and no
867
+ * device key witnessed it. No tokens (the export carries none and none are estimated), no layers, no evidence; the
868
+ * title names the product and never the conversation; the stretch's name is the vendor, the conversation's id and the
869
+ * day, so the same export sent twice is each line once. The database keeps a reconstructed stretch inside eight hours
870
+ * (20261009170000), so the line is cut there before it leaves.
871
+ */
872
+ const RECONSTRUCTED_MAX = 28800;
873
+ const EXPORTS_STATE = join(homedir(), ".worktrust", "exports.json"); // per export digest: sent, or offered and declined; nothing of a conversation
874
+ const readExportsState = () => { try { return JSON.parse(readFileSync(EXPORTS_STATE, "utf8")); } catch { return {}; } };
875
+ 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)); };
876
+ function exportEntries() {
877
+ if (!exportSessions) throw Error("chat-exports.mjs is not beside this file: a data export cannot be read");
878
+ const entries = [], reports = [];
879
+ for (const given of EXPORT_PATHS) {
880
+ const read = readExport(given);
881
+ const report = { path: read.path, vendor: read.vendor, digest: read.digest, conversations: read.conversations.length, days: new Set(), seconds: 0 };
882
+ for (const { id, lines } of exportSessions(read, { excluded })) {
883
+ const messages = [];
884
+ for (const line of lines) { const at = line.timestamp ? Date.parse(line.timestamp) : NaN; if (Number.isFinite(at)) messages.push(messageOf(line, at)); }
885
+ messages.sort((a, b) => a.at - b.at);
886
+ for (const [day, ofDay] of byDayOf(messages)) {
887
+ if (ofDay.length === 0) continue;
888
+ const stretch = measure(null, ofDay), ref = exportRef(read.vendor, id, day);
889
+ const entry = {
890
+ title: EXPORT_TITLES[read.vendor], kind: "researched",
891
+ ...(stretch.seconds !== null ? { seconds: Math.min(RECONSTRUCTED_MAX, stretch.seconds), duration_basis: "reconstructed" } : {}),
892
+ ...(stretch.exchanges > 0 ? { exchanges: stretch.exchanges, turn_basis: "humanOnly" } : {}),
893
+ ...(stretch.model ? { model: stretch.model } : {}),
894
+ stretch_ref: ref, source_event_id: `exp_${ref}`,
895
+ started_at: new Date(stretch.from).toISOString(), utc_offset: stretch.offset, at: new Date(stretch.to).toISOString(),
896
+ };
897
+ entrySource.set(entry, read.vendor);
898
+ entryFile.set(entry, { file: `${read.vendor}:${id}`, from: stretch.from, folder: null });
899
+ report.days.add(day); report.seconds += entry.seconds ?? 0; entries.push(entry);
900
+ }
901
+ }
902
+ const days = [...report.days].sort();
903
+ reports.push({ ...report, days: days.length, hours: Math.round(report.seconds / 360) / 10, first: days[0] ?? null, last: days.at(-1) ?? null });
904
+ }
905
+ const seen = new Set();
906
+ return { entries: entries.filter((entry) => !seen.has(entry.stretch_ref) && seen.add(entry.stretch_ref)).sort((a, b) => a.at.localeCompare(b.at)), reports };
907
+ }
908
+
909
+ /**
910
+ * 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
911
+ * or an Antigravity brain folder, read with the same readers and the same clock as the live folders, never the live folders
912
+ * themselves (a copy of one of them, or one holding them, is refused by name). Each day is named exactly as the live folder
913
+ * 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
914
+ * same copy, is skipped: the live folders win. What travels is RECONSTRUCTED: no device key witnessed the copy, and a copy can
915
+ * be edited. The counts a transcript carries (tokens, turns, the model, the evidence) travel; the hours in layers, which say
916
+ * what a MEASURED day's seconds were, do not. The title says where the line came from.
917
+ */
918
+ function folderEntries(given) {
919
+ const dir = given.replace(/^~(?=\/|$)/, homedir());
920
+ let stat; try { stat = statSync(dir); } catch { throw Error(`no session files: ${given} does not exist`); }
921
+ if (!stat.isDirectory()) throw Error(`no session files: ${given} is not a folder`);
922
+ const here = resolve(dir), live = [claudeRoot(), codexRoot(), ...antigravityRoots(value("antigravity-root"))].filter(Boolean).map((root) => resolve(root));
923
+ 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`);
924
+ const files = [];
925
+ const walk = (at, depth) => {
926
+ if (depth > 12) return;
927
+ let names = []; try { names = readdirSync(at, { withFileTypes: true }); } catch { return; }
928
+ for (const entry of names.sort((a, b) => a.name.localeCompare(b.name))) {
929
+ const path = join(at, entry.name);
930
+ if (entry.isDirectory()) { if (entry.name !== "subagents" && !excluded(entry.name)) walk(path, depth + 1); }
931
+ else if (entry.name.endsWith(".jsonl")) files.push(path);
932
+ }
933
+ };
934
+ walk(here, 0);
935
+ if (files.length === 0) throw Error(`no session files under ${given} (Claude Code transcripts, Codex rollouts or Antigravity transcripts, as .jsonl)`);
936
+ const present = new Set(historyEntries(null, true).map((entry) => entry.stretch_ref)), seen = new Set();
937
+ const entries = [], report = { stretches: 0, skipped: 0, days: new Set(), seconds: 0 };
938
+ for (const file of files) {
939
+ const client = CODEX_ROLLOUT.test(file) ? "codex" : ANTIGRAVITY_TRANSCRIPT.test(file) ? "antigravity" : "claude";
940
+ const lines = parsedLines(file);
941
+ if (!lines) continue;
942
+ let cwd = null;
943
+ const read = [];
944
+ for (const line of lines) {
945
+ if (typeof line.cwd === "string") cwd = line.cwd;
946
+ if (!line.timestamp || (line.type !== "user" && line.type !== "assistant")) continue;
947
+ const at = Date.parse(line.timestamp);
948
+ if (Number.isFinite(at)) read.push(messageOf(line, at));
949
+ }
950
+ read.sort((a, b) => a.at - b.at);
951
+ for (const [day, messages] of byDayOf(read)) {
952
+ if (messages.length === 0) continue;
953
+ const ref = stretchRef(file, day);
954
+ report.stretches += 1;
955
+ if (present.has(ref) || seen.has(ref)) { report.skipped += 1; continue; }
956
+ seen.add(ref);
957
+ const measured = payloadFor({ ...measure(cwd, messages), ref, steered: null, agents: null });
958
+ const { model_seconds, tool_seconds, human_seconds, idle_seconds, agent_runs, agent_seconds, agent_peak, ...rest } = measured;
959
+ void model_seconds; void tool_seconds; void human_seconds; void idle_seconds; void agent_runs; void agent_seconds; void agent_peak;
960
+ 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" } : {}) };
961
+ if (client !== "claude") entrySource.set(entry, client);
962
+ entryFile.set(entry, { file, from: firstOf(messages), folder: null });
963
+ report.days.add(day); report.seconds += entry.seconds ?? 0; entries.push(entry);
964
+ }
965
+ }
966
+ const days = [...report.days].sort();
967
+ 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 } };
968
+ }
969
+
813
970
  /** Every transcript this machine holds, excluded projects skipped before a file is opened. */
814
971
  function* allTranscripts() {
815
972
  const root = claudeRoot();
@@ -1013,6 +1170,10 @@ if (flag("evidence-summary")) {
1013
1170
  await exitFlushed(0);
1014
1171
  }
1015
1172
  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
1173
+ // THE EXPORTS IN A FOLDER (0.10.10, for the bare `npx worktrust`): which lie there, by vendor and digest, and which this computer
1174
+ // already sent or was asked about; reads, prints one JSON line, sends nothing. `--export-offered <digest>` records a No.
1175
+ 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); }
1176
+ if (value("export-offered")) { rememberExport(value("export-offered"), { offered: new Date().toISOString() }); await exitFlushed(0); }
1016
1177
  if (!door && !codexDoor && !DRY) { process.exit(0); } // Not coupled on this machine: nothing to do, quietly.
1017
1178
 
1018
1179
  /**
@@ -1025,17 +1186,25 @@ if (flag("history") && flag("from-archive")) {
1025
1186
  const named = value("from-archive"), dir = named && !named.startsWith("--") ? named.replace(/^~(?=\/|$)/, homedir()) : join(homedir(), "AI-Evidence");
1026
1187
  const say = (text) => console.log(text);
1027
1188
  const pem = process.env.WORKTRUST_DEVICE_KEY;
1189
+ // 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
1190
+ // measured; a day unsigned, signed by the local archive key, or by another computer's key goes too, as RECONSTRUCTED, inside the
1191
+ // database's ceiling for an unmeasured stretch. No device key is no longer a refusal: it means every day is reconstructed. The
1192
+ // archive must still verify whole, and only stretches no longer in any AI app here travel.
1028
1193
  let ownKey = null;
1029
1194
  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
1195
  const verified = spawnSync(process.execPath, [join(dirname(fileURLToPath(import.meta.url)), "preserve.mjs"), "--verify", dir], { encoding: "utf8" });
1032
1196
  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
1197
  const { archiveEntries = null } = (await import("./preserve-lines.mjs").catch(() => null)) ?? {};
1034
1198
  if (!archiveEntries) { say("preserve-lines.mjs is not beside this file. Nothing was sent."); await exitFlushed(1); }
1035
1199
  const present = new Set(historyEntries(null, true).map((entry) => entry.stretch_ref));
1036
- const signed = archiveEntries(dir, ownKey), gone = signed.filter(({ entry }) => !present.has(entry.stretch_ref));
1037
- const entries = gone.map(({ entry, client }) => { if (client !== "claude") entrySource.set(entry, client); return entry; });
1038
- say(`${signed.length} stretches in the archive signed by this computer · ${entries.length} of them no longer in any AI app here`);
1200
+ const all = archiveEntries(dir, ownKey), gone = all.filter(({ entry }) => !present.has(entry.stretch_ref));
1201
+ const entries = gone.map(({ entry, client, signed }) => {
1202
+ if (client !== "claude") entrySource.set(entry, client);
1203
+ if (!signed && typeof entry.seconds === "number") { entry.seconds = Math.min(RECONSTRUCTED_MAX, entry.seconds); entry.duration_basis = "reconstructed"; }
1204
+ return entry;
1205
+ });
1206
+ const signedCount = all.filter(({ signed }) => signed).length;
1207
+ 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
1208
  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
1209
  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
1210
  await exitFlushed((await sendHistory(door, entries, true)) === entries.length ? 0 : 1);
@@ -1043,13 +1212,26 @@ if (flag("history") && flag("from-archive")) {
1043
1212
 
1044
1213
  if (flag("history")) {
1045
1214
  const historyFloor = floorOf(readState(), "__historyFloor");
1046
- const entries = historyEntries(historyFloor);
1215
+ // 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).
1216
+ let fromExports = null, fromFolder = null;
1217
+ if (EXPORT_PATHS.length > 0) { try { fromExports = exportEntries(); } catch (error) { console.log(`export: ${error.message}`); await exitFlushed(1); } }
1218
+ // A COPIED SESSION FOLDER (0.10.10): its own history, reconstructed, the live folders' stretches skipped; never a rebuild.
1219
+ if (flag("from-folder")) {
1220
+ const given = value("from-folder");
1221
+ if (!given || given.startsWith("--")) { console.log("folder: --from-folder needs the copied folder's path"); await exitFlushed(1); }
1222
+ try { fromFolder = folderEntries(given); } catch (error) { console.log(`folder: ${error.message}`); await exitFlushed(1); }
1223
+ }
1224
+ 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); }
1225
+ // 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
1226
+ // lines under no product go only with `--withdraw-unknown`, which the command sends after the person's yes, with an export alone.
1227
+ 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); }
1228
+ const entries = fromExports ? fromExports.entries : fromFolder ? fromFolder.entries : historyEntries(historyFloor);
1047
1229
  const hours = entries.reduce((sum, entry) => sum + (entry.seconds ?? 0), 0) / 3600;
1048
1230
  const months = [...new Set(entries.map((entry) => entry.at.slice(0, 7)))].sort();
1049
1231
  // 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
1232
  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" : ""}`);
1233
+ 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); }
1234
+ 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
1235
  if (DRY) {
1054
1236
  // One example in full: the shape is the argument for trusting it, and a summary hides it.
1055
1237
  if (entries[0]) console.log(`\nthe oldest of them, in full:\n${JSON.stringify(entries[0], null, 1)}`);
@@ -1057,7 +1239,12 @@ if (flag("history")) {
1057
1239
  await exitFlushed(0);
1058
1240
  }
1059
1241
  // A batch the door refused is a failure the caller must see, not a quiet zero.
1060
- await exitFlushed((await sendHistory(door, entries, true, flag("rebuild"))) === entries.length ? 0 : 1);
1242
+ const accepted = await sendHistory(door, entries, true, flag("rebuild"), Boolean(fromFolder), fromExports ? { byDay: true, withdrawUnknown: flag("withdraw-unknown") } : {});
1243
+ // An export that arrived whole is remembered by its digest (never by a conversation), so the bare command offers it no more.
1244
+ if (fromExports && accepted === entries.length) for (const report of fromExports.reports) rememberExport(report.digest, { vendor: report.vendor, sent: true, at: new Date().toISOString(), conversations: report.conversations });
1245
+ // ONE LINE FOR THE COMMAND TO ASK WITH (2026-10-10): what the door replaced, how many AI-app lines lie on the export's days, how many it withdrew.
1246
+ if (fromExports) console.log(JSON.stringify({ export_sent: accepted, of: entries.length, ...RECEIPTS }));
1247
+ await exitFlushed(accepted === entries.length ? 0 : 1);
1061
1248
  }
1062
1249
 
1063
1250
  const input = hookInput();
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "worktrust",
3
- "version": "0.10.9",
3
+ "version": "0.10.11",
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,8 @@
18
18
  "preserve-summary.mjs",
19
19
  "preserve-lines.mjs",
20
20
  "stretch-evidence.mjs",
21
+ "chat-exports.mjs",
22
+ "stack-rules.mjs",
21
23
  "README.md",
22
24
  "SECURITY.md",
23
25
  "LICENSE",
@@ -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
- if (!ownKey || !proof || typeof proof.signature !== "string" || proof.public_key !== ownKey) continue;
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
- const key = deviceKey();
299
- const ours = (document) => !document || (key && typeof document.signature === "string" && document.public_key === key.publicX);
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 device key on this computer)"}.`);
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 daySeal = result.signed === 0 ? "no day signed" : result.ours === result.signed ? `${result.signed} signed by this computer's key` : `${result.signed} signed (${result.ours} by this computer's key, ${result.signed - result.ours} by another key named in them)`;
322
- const seal = typeof result.manifest?.signature !== "string" ? "manifest unsigned" : result.manifest.public_key === deviceKey()?.publicX ? "manifest signed by this computer's key" : "manifest signed by another key named in it";
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
  }