worktrust 0.10.17 → 0.10.20

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
@@ -1,21 +1,17 @@
1
1
  #!/usr/bin/env node
2
2
  /**
3
3
  * THE MOMENT OF THE WORK, RECORDED — a Claude Code hook that logs a finished stretch.
4
- *
5
4
  * Session observations complement repository and CI evidence with locally recorded AI activity.
6
5
  * They do not establish independent verification or human presence by themselves.
7
- *
8
6
  * IT NEVER LOSES A MEASURED DAY. A session is reported day by day, on whichever run comes first,
9
7
  * so a session that stays open for a fortnight is not a fortnight of silence; a machine that was
10
8
  * closed for four months hands over its months when it comes back, through the history door; and
11
9
  * a day the network refused is sent again on the next run, because the watermark advances over
12
10
  * what was accepted and stops at the first refusal.
13
- *
14
11
  * This hook supplies exactly that half, and nothing else. It NEVER decides how good the work was:
15
12
  * scoring calls no model, and a stretch reported here is corroborated by the commit and the CI run
16
13
  * that land beside it or it counts for nothing. What it sends is what a clock and a token counter
17
14
  * recorded.
18
- *
19
15
  * node log-session.mjs --install wire it into Claude Code (SessionEnd, SessionStart, PreCompact)
20
16
  * node log-session.mjs --uninstall [--purge] take it out again (--purge also deletes the copies)
21
17
  * node log-session.mjs --dry-run show what the current transcripts would send
@@ -51,13 +47,14 @@
51
47
  * answer, no file path, no commit message, no branch, no folder name. File paths ARE read locally to decide one layer keyword,
52
48
  * the way the connector reads them to decide an activity class, and only the keyword travels.
53
49
  *
54
- * WHAT IS MEASURED, AND WHAT IS THEREFORE NOT SENT. A stretch's seconds are the sum of the gaps
55
- * between consecutive messages in the transcript, each gap counted only up to IDLE_CAP: two
56
- * recorded timestamps at both ends, and a pause longer than the cap is not work. That is what
57
- * `duration_basis: "measured"` means for local sessions; copied/exported history is reconstructed.
58
- * A local stretch without timestamps is skipped rather than estimated. Tokens are what each
59
- * request ADDED (input plus cache creation, cache reads excluded), which the door calls
60
- * `newInput`.
50
+ * WHAT IS MEASURED, AND BY WHOM (0.10.20, owner 2026-10-18: "the calculation must be done by our system; we only get
51
+ * metadata"). This hook sends a stretch's TIMELINE: one step per transcript line, as the kind of line it was and the whole
52
+ * seconds since the previous step, never a word. WorkTrust computes the seconds and the hours in layers from that timeline
53
+ * with its own rules; nothing here counts an hour, and no constant in this file decides a figure. `duration_basis:
54
+ * "measured"` says the timeline was read from the app's own folder on this computer; copied or exported history is
55
+ * reconstructed. A local stretch without timestamps is skipped rather than estimated. Tokens are what each request ADDED
56
+ * (input plus cache creation, cache reads excluded), which the door calls `newInput`. The figures the terminal shows come
57
+ * from WorkTrust's receipts.
61
58
  *
62
59
  * CONFIDENTIAL PROJECTS never open: `~/.worktrust-counter.json` { "exclude": ["client-x"] } is
63
60
  * honoured here too, matched against the transcript's project directory, before a file is read.
@@ -69,10 +66,11 @@ import { dirname, join, resolve, sep } from "node:path";
69
66
  import { fileURLToPath } from "node:url";
70
67
  import { createHash, createPrivateKey, createPublicKey, randomBytes, sign as cryptoSign } from "node:crypto";
71
68
 
72
- const args = process.argv.slice(2);
69
+ async function main() {
70
+ const args = process.argv.slice(2), NODE_FLAGS = process.versions.node === "26.5.0" ? ["--no-concurrent-sparkplug"] : [];
73
71
  const flag = (name) => args.includes(`--${name}`), value = (name) => { const i = args.indexOf(`--${name}`); return i >= 0 ? args[i + 1] : undefined; }, DRY = flag("dry-run");
74
- // Exit once stdout is written: to a pipe it is asynchronous and process.exit drops what is queued (0.6.13 cut --archive-lines).
75
- const exitFlushed = (code) => new Promise((resolve) => process.stdout.write("", resolve)).then(() => process.exit(code));
72
+ // Return from every terminal branch and drain naturally: forced exit can deadlock Node 26.5 while V8 compiles.
73
+ const exitFlushed = (code) => new Promise((resolve) => process.stdout.write("", resolve)).then(() => { process.exitCode = code; });
76
74
 
77
75
  /**
78
76
  * THE OTHER HALF OF A SESSION: HOW IT WAS ASKED.
@@ -116,32 +114,16 @@ async function refreshCounter(origin, announce) {
116
114
  } catch { return false; }
117
115
  }
118
116
 
119
- /** A pause longer than this is not work, so it is not counted. Five minutes. */
120
- const IDLE_CAP = 300;
121
117
  /**
122
- * The live door refuses a stretch older than two days, because it records work AS IT HAPPENS —
123
- * that rule is what stops a year of invented afternoons walking in through the same door.
118
+ * The live door refuses stretches older than two days; older work uses the history door.
124
119
  *
125
120
  * It is not a reason to lose the work. Past this line a measured day is filed through
126
121
  * `import_history` instead: the same counted seconds, marked as history, standing as history
127
122
  * stands (it corroborates, and it never lifts a level on its own). Late is not the same as untrue.
128
123
  */
129
124
  const WINDOW_HOURS = 48;
130
- /** A stretch still being worked in is not finished; half an hour of quiet says it is. */
125
+ /** A stretch still being worked in is not finished; half an hour of quiet says it is. The one timing rule this hook keeps: WHEN to sweep, never how long a stretch was. */
131
126
  const IDLE_BEFORE_SWEEP = 30 * 60 * 1000;
132
- /** Under a minute is not a piece of work. */
133
- const MIN_SECONDS = 60;
134
- /**
135
- * The door's own ceiling for one MEASURED stretch: sixteen hours since 0.10.6 (owner, 2026-10-09; it was eight). Every
136
- * second of it lies between two messages at most five minutes apart. A day past it is reported SHORT: under-reporting is the
137
- * safe direction. Stretches are split by DAY, which is a boundary the clock draws — never by
138
- * guessing where one piece of work ended and the next began.
139
- */
140
- const MAX_SECONDS = 57600;
141
- /** The door's ceilings for the layers (a day) and for a day's subagents: the same bounds its columns check. */
142
- const DAY_SECONDS = 86400;
143
- /** A tool gap is tool time up to thirty minutes (proposed, owner 2026-10-06); past that it is a wait, counted as idle. */
144
- const TOOL_CAP = 1800;
145
127
  /** Tools whose result waits for the person: the gap to it is the person's time. Names only; nothing of the call is read. */
146
128
  const WAITS_FOR_PERSON = new Set(["AskUserQuestion", "ExitPlanMode"]);
147
129
  /**
@@ -189,7 +171,6 @@ const gitRouteOf = (cwd, shas, paths) => {
189
171
  };
190
172
  /** The derived record of a stretch, kept for the local archive only (see payloadFor). */
191
173
  const DERIVED = new WeakMap();
192
- const AGENT_RUNS_MAX = 10000, AGENT_SECONDS_MAX = 2592000;
193
174
 
194
175
  /**
195
176
  * WHEN THE HOOK RUNS. SessionEnd alone was a bet that sessions end, and a session that stays open
@@ -270,7 +251,7 @@ const { callOf = (block) => ({ id: block.id, kinds: [], family: String(block.nam
270
251
  const { DATABASE_SESSION = /(?!)/, databaseLines = () => null, databaseSessions = function* () {} } = (await import("./session-databases.mjs").catch(() => null)) ?? {};
271
252
  // 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
272
253
  // imports the same reader); `--history --export <path>` sends its conversations as RECONSTRUCTED days, never measured, never tokens.
273
- const { EXPORT_CLIENTS = [], EXPORT_TITLES = {}, exportSessions = null, exportRef = null, exportRunRef = null, readExport = null, findExports = null } = (await import("./chat-exports.mjs").catch(() => null)) ?? {};
254
+ const { EXPORT_CLIENTS = [], EXPORT_TITLES = {}, exportSessions = null, exportRef = null, exportRunRef = null, findExports = null } = (await import("./chat-exports.mjs").catch(() => null)) ?? {};
274
255
  const { modCounts = () => null } = (await import("./claude-mod.mjs").catch(() => null)) ?? {}; // 0.10.15: the WorkTrust mod's live counts per Claude Code session and day; absent → no `live` group, never zeros
275
256
  const liveOf = (file, day) => modCounts(String(file).split(/[\\/]/).pop().replace(/\.jsonl$/, ""), day) ?? codexLive(file, day); // 0.10.16: a Codex rollout's own
276
257
  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
@@ -423,9 +404,9 @@ function stretchesOf(file, since) {
423
404
  /**
424
405
  * DAYS SPLIT ON THE CLOCK, NOTHING LOST AT MIDNIGHT (0.6.18, audit C14). A stretch is one session's UTC day, and the gap
425
406
  * between a day's last message and the next day's first belonged to neither, so a run through the night lost one gap
426
- * per midnight. A day whose first message follows the last one within the tool cap now opens with a BRIDGE: the message
427
- * before it, carrying no tokens, no model and no turn, so the gap that crosses midnight is counted once, on the day it
428
- * ends, under the same caps as any other.
407
+ * per midnight. A day whose first message follows the last one within the sweep's half hour (the session never went quiet)
408
+ * now opens with a BRIDGE: the message before it, carrying no tokens, no model and no turn, so the gap that crosses midnight
409
+ * is in the day's timeline once, on the day it ends, for the server to count as it counts any other gap.
429
410
  * Messages must arrive sorted.
430
411
  */
431
412
  function byDayOf(messages) {
@@ -433,8 +414,8 @@ function byDayOf(messages) {
433
414
  let prev = null;
434
415
  for (const message of messages) {
435
416
  const day = new Date(message.at).toISOString().slice(0, 10);
436
- // Only a gap the work could have run through (within the tool cap): a session resumed the next morning opens its day as it always did.
437
- if (!byDay.has(day)) byDay.set(day, prev && message.at - prev.at <= TOOL_CAP * 1000 ? [{ ...prev, usage: null, model: null, cumulative: false, bridge: true }] : []);
417
+ // Only a gap the work could have run through (no half hour of quiet): a session resumed the next morning opens its day as it always did.
418
+ if (!byDay.has(day)) byDay.set(day, prev && message.at - prev.at <= IDLE_BEFORE_SWEEP ? [{ ...prev, usage: null, model: null, cumulative: false, bridge: true }] : []);
438
419
  byDay.get(day).push(message);
439
420
  prev = message;
440
421
  }
@@ -475,11 +456,10 @@ const messageOf = (line, at) => {
475
456
  /**
476
457
  * SUBAGENTS AS AGENT TIME, NEVER AS HOURS (owner, 2026-10-06). Claude Code writes each subagent's transcript beside its
477
458
  * session (`<session>/subagents/*.jsonl`: 279 of them beside 48 sessions on the computer this was built on), and the
478
- * sweep read only the sessions, so delegated work was invisible. Now each run is read for its clocks and sent as
479
- * METADATA beside the parent's day: how many runs started that day, their own measured seconds (the same gap rule, the
480
- * same cap), and how many were open at once at the busiest moment. None of it enters `seconds`: four agents working an
481
- * hour are four agent-hours and one hour of the person's, and the record says which is which. Only Claude Code keeps
482
- * subagents this way; every other client answers an empty map.
459
+ * sweep read only the sessions, so delegated work was invisible. Each run is read for its clocks: how many runs started
460
+ * that day and how many were open at once at the busiest moment (read here for the complexity class). Their SECONDS are
461
+ * not computed here since 0.10.20 (no counting rule ships in this file); until a timeline per run travels, the agent
462
+ * group is not sent. Only Claude Code keeps subagents this way; every other client answers an empty map.
483
463
  */
484
464
  function subagentFiles(file) {
485
465
  if (!/\.jsonl$/.test(String(file)) || CODEX_ROLLOUT.test(file) || ANTIGRAVITY_TRANSCRIPT.test(file) || DATABASE_SESSION.test(file)) return [];
@@ -505,13 +485,11 @@ function agentsByDay(file, since) {
505
485
  // watermark stays unsent, which is the safe direction.
506
486
  if (stamps.length === 0 || (since && started <= since)) continue;
507
487
  stamps.sort((a, b) => a - b);
508
- // A run is counted on the day it started; its seconds go with it, the same rule as the parent's.
488
+ // A run is counted on the day it started.
509
489
  const day = new Date(stamps[0]).toISOString().slice(0, 10);
510
- let seconds = 0;
511
- for (let i = 1; i < stamps.length; i += 1) seconds += Math.min(IDLE_CAP, Math.round((stamps[i] - stamps[i - 1]) / 1000));
512
- if (!byDay.has(day)) byDay.set(day, { runs: 0, seconds: 0, spans: [] });
490
+ if (!byDay.has(day)) byDay.set(day, { runs: 0, spans: [] });
513
491
  const entry = byDay.get(day);
514
- entry.runs += 1; entry.seconds += seconds; entry.spans.push([stamps[0], stamps[stamps.length - 1]]);
492
+ entry.runs += 1; entry.spans.push([stamps[0], stamps[stamps.length - 1]]);
515
493
  }
516
494
  for (const entry of byDay.values()) entry.peak = peakOf(entry.spans);
517
495
  return byDay;
@@ -546,66 +524,41 @@ function isHumanTurn(content) {
546
524
  return types.has("text") || types.has("image");
547
525
  }
548
526
 
549
- /** One day's messages → the stretch, measured. Null when there is nothing honest to send. */
527
+ /** One day's messages → the stretch: its timeline, its tokens, its model. The server measures it. */
550
528
  function measure(cwd, messages) {
551
- // MEASURED, AND ONLY MEASURED: every second counted lies between two recorded timestamps, and a
552
- // gap longer than the cap is a pause rather than work. No stretch is ever inferred from a count.
553
- let seconds = 0;
554
- for (let i = 1; i < messages.length; i += 1) seconds += Math.min(IDLE_CAP, Math.round((messages[i].at - messages[i - 1].at) / 1000));
555
- // A DURATION MAY BE ABSENT; THE STRETCH MAY NOT. What corroborates a commit is that a person and
556
- // an agent were there at that moment, not how long they stayed — so a stretch too short to time,
557
- // or one whose clocks give nothing, is still reported, WITHOUT seconds and without a basis. The
558
- // alternative is a hook that goes quiet exactly where the record is thinnest, or one that fills
559
- // the gap with a guess: the same fabrication in a smaller jacket.
560
- const measured = seconds >= MIN_SECONDS ? Math.min(MAX_SECONDS, seconds) : null;
529
+ // THE CLOCK IS THE SERVER'S (0.10.20). This hook sends the stretch's timeline and never a duration of its own: every
530
+ // second WorkTrust counts lies between two recorded timestamps in that timeline, under WorkTrust's rules, and a stretch
531
+ // too short to time is a stretch WorkTrust answers without a duration. A stretch whose clocks give nothing is still
532
+ // reported, so a commit beside it can be joined to a moment somebody was there.
561
533
  const models = new Map();
562
- let exchanges = 0;
563
- for (const message of messages) {
564
- if (message.type === "user" && !message.meta && !message.bridge && isHumanTurn(message.content)) exchanges += 1;
565
- if (message.model) models.set(message.model, (models.get(message.model) ?? 0) + 1);
566
- }
534
+ for (const message of messages) if (message.model) models.set(message.model, (models.get(message.model) ?? 0) + 1);
567
535
  const model = [...models.entries()].sort((a, b) => b[1] - a[1])[0]?.[0] ?? null;
568
536
  const tokens = tokensOf(messages);
569
- // HOW THE PERSON STEERED (owner, 2026-10-08): how often they stopped the agent (Claude Code's interruption line), and how
570
- // often their next turn arrived while the agent was still mid-task (right after a tool call or its result). Counts only.
571
- let interrupts = 0, steers = 0;
572
- for (let i = 1; i < messages.length; i += 1) {
573
- const message = messages[i], prev = messages[i - 1];
574
- if (message.bridge || message.type !== "user" || message.meta || message.kind === "tool_result") continue;
575
- if (INTERRUPTED.test(textOf(message.content).trim())) interrupts += 1;
576
- else if (isHumanTurn(message.content) && (prev.kind === "tool_result" || prev.toolUse)) steers += 1;
577
- }
578
537
  const from = firstOf(messages);
579
- return { cwd, seconds: measured, derived: deriveStretch(messages, { isHumanTurn, INTERRUPTED, textOf }), layers: measured !== null ? timeLayers(messages) : null, ...tokens, cumulative: messages.some((message) => message.cumulative), exchanges, interrupts, steers, model, from, to: messages[messages.length - 1].at, offset: offsetAt(from) };
538
+ return { cwd, derived: deriveStretch(messages, { isHumanTurn, INTERRUPTED, textOf }), timeline: messages.length > 0 ? timelineOf(messages) : null, ...tokens, cumulative: messages.some((message) => message.cumulative), model, from, to: messages[messages.length - 1].at, offset: offsetAt(from) };
580
539
  }
581
540
 
582
541
  /**
583
- * HOW THE SECONDS WERE SPENT (owner, 2026-10-06: "observed time → AI active → agent-directed → verified work activity").
584
- * `seconds` keeps its exact meaning above; this reads the same gaps a second time and says what each one WAS, by the
585
- * message that ends it: the model's message (model time, capped as before), a tool's result or an agent run (tool time,
586
- * NOT capped at five minutes, because a test suite that ran twenty minutes was twenty minutes of the agent's work; bounded
587
- * by the stretch's own ceiling), or the person's next turn (human time, capped). What a cap cut off is idle, counted as
588
- * idle and never as work. The four sum to the stretch's span, so nothing is hidden and nothing is double-counted.
542
+ * THE TIMELINE, FOR THE SERVER'S OWN CLOCK (0.10.20, owner 2026-10-18: "the calculation must be done by our system; we only get
543
+ * metadata"). One step per message, as the KIND the measure read it as and the whole seconds since the previous step; the
544
+ * first step carries 0, a bridge is lowercase, an agent run is marked G. Nothing of a message travels: not a word, not a
545
+ * tool's name, not a path. WorkTrust computes `seconds`, the hours in layers, the turns, the interruptions and the mid-task
546
+ * turns from this with its own rules (private to the server); this file sends no figure of its own, so nothing in it can
547
+ * move the passport.
589
548
  */
590
- function timeLayers(messages) {
591
- const split = { model: 0, tool: 0, human: 0, idle: 0 };
592
- for (let i = 1; i < messages.length; i += 1) {
593
- const gap = Math.max(0, Math.round((messages[i].at - messages[i - 1].at) / 1000));
594
- const next = messages[i], prev = messages[i - 1];
595
- // WAITS FOR THE PERSON ARE NOT TOOL TIME (review, 2026-10-06). A tool's result arrives when the tool is done, or when the
596
- // person answered a question, approved a plan, or sat on a permission prompt. The first two are named by the tool and
597
- // counted as human time; the third is invisible in the transcript, so a tool gap is counted as tool time only up to
598
- // TOOL_CAP, and the rest as idle: a tool runs minutes, a person away from the keyboard does not.
599
- const tool = (next.kind === "tool_result" || next.agentic || (prev.toolUse && next.kind === "assistant")) && !prev.waitsForPerson;
600
- // ONE DEFINITION OF A HUMAN TURN (review, 2026-10-06): the same `isHumanTurn` that counts `exchanges`; a user line that
601
- // is not one (a meta line the client injected, a textless line) is the loop's own and counts as model time.
602
- const human = !tool && ((prev.waitsForPerson && next.kind === "tool_result") || (next.kind === "user" && !next.meta && isHumanTurn(next.content)));
603
- const counted = Math.min(tool ? TOOL_CAP : IDLE_CAP, gap);
604
- split[tool ? "tool" : human ? "human" : "model"] += counted;
605
- split.idle += gap - counted;
549
+ function timelineOf(messages) {
550
+ let out = "";
551
+ for (let i = 0; i < messages.length; i += 1) {
552
+ const message = messages[i];
553
+ const gap = i === 0 ? 0 : Math.max(0, Math.round((message.at - messages[i - 1].at) / 1000));
554
+ const kind = message.kind === "assistant" ? (message.waitsForPerson ? "W" : message.toolUse ? "T" : "A") : message.kind === "tool_result" ? "R" : INTERRUPTED.test(textOf(message.content).trim()) && !message.meta ? "I" : !message.meta && isHumanTurn(message.content) ? "H" : "U";
555
+ out += `${message.agentic ? "G" : ""}${message.bridge ? kind.toLowerCase() : kind}${Math.min(999999, gap)}`;
606
556
  }
607
- return split;
557
+ return out;
608
558
  }
559
+ /** A digest of this hook and the readers beside it, as installed: the door records it beside each line as a signal of which code ran, never as proof. */
560
+ const selfDigest = (() => { try { const here = dirname(fileURLToPath(import.meta.url)); const hash = createHash("sha256"); for (const name of ["log-session.mjs", ...READER_FILES].sort()) { try { hash.update(`${name}\0`).update(readFileSync(join(here, name))).update("\0"); } catch { hash.update(`${name}\0missing\0`); } } return hash.digest("hex"); } catch { return null; } })();
561
+ const CLI_VERSION_SENT = /^[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,4}$/.test(process.env.WORKTRUST_CLI_VERSION ?? "") ? process.env.WORKTRUST_CLI_VERSION : null; // `worktrust.mjs` hands its own version to the hook it starts
609
562
 
610
563
  /**
611
564
  * THE TOKENS, AND THE CACHE HALVES APART (roadmap 16). Claude Code's usage block carries input_tokens, output_tokens,
@@ -667,7 +620,7 @@ function payloadFor(stretch) {
667
620
  // 0.8.7: of the stretch's commits, how many name an AI as co-author (the Co-authored-by trailer, read here, never kept).
668
621
  const coauthored = cwd && touched.shas.length > 0 ? git(cwd, "log", "--no-walk", "--format=%(trailers:key=Co-authored-by,valueonly,separator=%x01)%x00", ...touched.shas.slice(0, 50)).split("\0").filter((entry, index) => index < Math.min(50, touched.shas.length) && AI_COAUTHOR.test(entry)).length : 0;
669
622
  const route = { ...(stretch.derived?.route ?? {}), ...(touched.committed ? gitRouteOf(cwd, touched.shas, changed) : {}) };
670
- const derived = stretch.derived ? { ...stretch.derived, ...(Object.keys(route).length > 0 ? { route } : {}), ...(changed.length > 0 ? { changes: { files: changed.length, test_files: tests } } : {}), ...(touched.shas.length > 0 ? { authorship: { commits: Math.min(50, touched.shas.length), ai_coauthored: coauthored } } : {}), ...(contextFilesOf(changed) ? { context_files: contextFilesOf(changed) } : {}), ...(complexityOf ? { complexity: complexityOf(stretch.derived, { layers: Math.max(layers.length, layer ? 1 : 0), agentRuns: stretch.agents?.runs ?? 0, agentPeak: stretch.agents?.peak ?? 0, seconds: stretch.seconds }) } : {}) } : null;
623
+ const derived = stretch.derived ? { ...stretch.derived, ...(Object.keys(route).length > 0 ? { route } : {}), ...(changed.length > 0 ? { changes: { files: changed.length, test_files: tests } } : {}), ...(touched.shas.length > 0 ? { authorship: { commits: Math.min(50, touched.shas.length), ai_coauthored: coauthored } } : {}), ...(contextFilesOf(changed) ? { context_files: contextFilesOf(changed) } : {}), ...(complexityOf ? { complexity: complexityOf(stretch.derived, { layers: Math.max(layers.length, layer ? 1 : 0), agentRuns: stretch.agents?.runs ?? 0, agentPeak: stretch.agents?.peak ?? 0, seconds: null }) } : {}) } : null;
671
624
  const evidence = derived || stretch.live ? { ...(derived ?? {}), ...(stretch.live ? { live: stretch.live } : {}) } : null; // 0.10.15: the mod's counts ride as their own group
672
625
  const payload = {
673
626
  title: layer ? `AI-assisted work · ${layer}` : "AI-assisted work",
@@ -676,30 +629,27 @@ function payloadFor(stretch) {
676
629
  ...(layers.length > 1 ? { layers } : {}),
677
630
  ...(stack.length > 0 ? { stack } : {}),
678
631
  ...(toolsSeen.length > 0 ? { tools_seen: toolsSeen } : {}), // its own line: the payload allowlist (hook-presence) reads the key here
679
- // Both, or neither: seconds without a basis is exactly the ambiguity the record is trying to
680
- // lose, and a basis without seconds says nothing.
681
- ...(stretch.seconds !== null ? { seconds: stretch.seconds, duration_basis: "measured" } : {}),
632
+ // THE TIMELINE AND ITS BASIS, both or neither (0.10.20): the basis says the timeline was read from the app's own folder
633
+ // on this computer; WorkTrust computes the duration from the timeline, and a timeline too short to time gets none.
634
+ ...(stretch.timeline ? { timeline: stretch.timeline, duration_basis: "measured" } : {}),
682
635
  // Tokens only when the usage block's shape is the one this script knows — otherwise nothing, never a guess.
683
636
  ...(stretch.shapeKnown && stretch.tokensIn + stretch.tokensOut > 0 ? { tokens_in: stretch.tokensIn, tokens_out: stretch.tokensOut, token_basis: "newInput" } : {}),
684
- // The turns are the person's own messages, tool results excluded — said explicitly, because a
685
- // row that does not say reads as the old count, which included them.
686
- ...(stretch.exchanges > 0 ? { turn_basis: "humanOnly" } : {}),
637
+ // The turns WorkTrust counts from the timeline are the person's own messages, tool results excluded — said explicitly,
638
+ // because a row that does not say reads as the old count, which included them.
639
+ ...(stretch.timeline ? { turn_basis: "humanOnly" } : {}),
687
640
  // The cache halves, as counts, beside the tokens (roadmap 16): read from a cache, written into one.
688
641
  ...(stretch.shapeKnown && stretch.cacheRead > 0 ? { tokens_cache_read: stretch.cacheRead } : {}),
689
642
  ...(stretch.shapeKnown && stretch.cacheWrite > 0 ? { tokens_cache_write: stretch.cacheWrite } : {}),
690
- ...(stretch.exchanges > 0 ? { exchanges: stretch.exchanges } : {}),
691
643
  ...(stretch.model ? { model: stretch.model } : {}),
692
644
  ...(repo ? { repo } : {}),
693
645
  ...(touched.shas.length > 0 ? { commits: touched.shas.slice(0, 50) } : {}),
694
646
  ...(stretch.ref ? { stretch_ref: stretch.ref } : {}), ...(stretch.steered ? { steered_from: stretch.steered } : {}),
695
- // THE LAYERS (2026-10-06), only on a measured stretch, each bounded by a day: what the seconds were. `seconds` above is untouched.
696
- ...(stretch.seconds !== null && stretch.layers ? { model_seconds: Math.min(DAY_SECONDS, stretch.layers.model), tool_seconds: Math.min(DAY_SECONDS, stretch.layers.tool), human_seconds: Math.min(DAY_SECONDS, stretch.layers.human), idle_seconds: Math.min(DAY_SECONDS, stretch.layers.idle) } : {}),
697
- // THE SUBAGENTS, as agent metadata beside the day: runs, their own seconds, the peak open at once. Never in `seconds`.
698
- // WHEN AND HOW (0.6.18): the stretch's first moment and the computer's UTC offset then; the person's interruptions and mid-task turns, counts only.
647
+ // WHICH CODE SENT IT (0.10.20): a version and a digest of this hook's own files, signals never proof.
648
+ ...(CLI_VERSION_SENT ? { cli_version: CLI_VERSION_SENT } : {}),
649
+ ...(selfDigest ? { cli_digest: selfDigest } : {}),
650
+ // WHEN (0.6.18): the stretch's first moment and the computer's UTC offset then. The interruptions and the mid-task turns are
651
+ // read by WorkTrust from the timeline; the subagents' seconds wait for a timeline per run (0.10.20).
699
652
  started_at: new Date(stretch.from).toISOString(), utc_offset: stretch.offset,
700
- ...(stretch.interrupts > 0 ? { interrupts: Math.min(10000, stretch.interrupts) } : {}),
701
- ...(stretch.steers > 0 ? { steers: Math.min(10000, stretch.steers) } : {}),
702
- ...(stretch.agents && stretch.agents.runs > 0 ? { agent_runs: Math.min(AGENT_RUNS_MAX, stretch.agents.runs), agent_seconds: Math.min(AGENT_SECONDS_MAX, stretch.agents.seconds), agent_peak: Math.min(AGENT_RUNS_MAX, stretch.agents.peak) } : {}),
703
653
  // THE STRETCH'S EVIDENCE (0.8.3): what the CLI derived from it here, kinds and counts only (stretch-evidence.mjs); the door keeps it from a CLI key alone.
704
654
  ...(evidence ? { evidence } : {}),
705
655
  at: new Date(stretch.to).toISOString(),
@@ -722,8 +672,12 @@ function payloadFor(stretch) {
722
672
  * 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
673
  * day in two batches would be counted twice.
724
674
  */
675
+ /** A batch stays under the door's body ceiling (4.5 MB) with room for the envelope: a timeline (0.10.20) is up to 200 KB a line, so a batch is cut by bytes as well as by count. */
676
+ const BATCH_BYTES = 3_500_000;
677
+ const bytesOf = (entry) => Buffer.byteLength(JSON.stringify(entry), "utf8");
678
+ const byBytes = (entries) => { const out = []; let current = [], size = 0; for (const entry of entries) { const bytes = bytesOf(entry); if (current.length > 0 && (current.length >= 200 || size + bytes > BATCH_BYTES)) { out.push(current); current = []; size = 0; } current.push(entry); size += bytes; } if (current.length) out.push(current); return out; };
725
679
  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; }
680
+ if (!byDay) return byBytes(group);
727
681
  const days = new Map();
728
682
  for (const entry of group) { const day = String(entry.at).slice(0, 10); days.set(day, [...(days.get(day) ?? []), entry]); }
729
683
  const out = []; let current = [];
@@ -736,7 +690,7 @@ function batchesOf(group, byDay) {
736
690
  return out;
737
691
  }
738
692
  /** 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 = { new: 0, alreadyHeld: 0, filled: 0, replaced: 0, superseded: 0, recut: 0, unknownOnDays: 0, unknownWithdrawn: 0 }; // 0.10.17: recut, the one-envelope export lines its runs replaced // 2026-10-10: and what a re-measure did (new, held, filled, replaced), so the command can say it
693
+ const RECEIPTS = { new: 0, alreadyHeld: 0, filled: 0, replaced: 0, superseded: 0, recut: 0, unknownOnDays: 0, unknownWithdrawn: 0, corrected: 0, measuredSeconds: 0 }; // 0.10.20: measuredSeconds is WorkTrust's own figure for what the batch stored, the one the terminal shows // 0.10.17: recut, the one-envelope export lines its runs replaced // 2026-10-10: and what a re-measure did (new, held, filled, replaced), so the command can say it
740
694
  const noteReceipt = (answer) => {
741
695
  try {
742
696
  const json = JSON.parse(answer.trim().startsWith("{") ? answer : answer.split("\n").find((row) => row.startsWith("data:"))?.slice(5) ?? "null");
@@ -863,20 +817,17 @@ function historyEntries(floor = null, all = false) {
863
817
  /**
864
818
  * A DATA EXPORT'S CONVERSATIONS AS HISTORY (0.10.10, owner 2026-10-10: "hours from an export count as reconstructed, shown,
865
819
  * never in verified hours"). Since 0.10.17 one line per RUN of activity in a conversation-day (runsOf, below), no longer one
866
- * envelope per conversation and day. The same clock cuts them (a day, gaps capped at IDLE_CAP) and the same measure counts the
867
- * person's own turns and the model, but the line says `reconstructed`: the file can be edited before it is read and no
868
- * device key witnessed it. No tokens (the export carries none and none are estimated), no layers, no evidence; the
869
- * title names the product and never the conversation; the stretch's name is the vendor, the conversation's id and the
870
- * day, so the same export sent twice is each line once. The database keeps a reconstructed stretch inside eight hours
871
- * (20261009170000), so the line is cut there before it leaves.
820
+ * envelope per conversation and day. Each run travels as its TIMELINE (0.10.20) and WorkTrust computes its reconstructed
821
+ * seconds and the person's turns from it; the line says `reconstructed`: the file can be edited before it is read and no
822
+ * device key witnessed it. No tokens (the export carries none and none are estimated), no evidence; the title names the
823
+ * product and never the conversation; the stretch's name is the vendor, the conversation's id and the day, so the same
824
+ * export sent twice is each line once. The database keeps a reconstructed stretch inside eight hours (20261009170000).
872
825
  */
873
- const RECONSTRUCTED_MAX = 28800;
874
826
  /**
875
827
  * WHERE A CONVERSATION-DAY IS CUT (CLI 0.10.17, owner 2026-10-17): the hook's own stretch-finished gap, IDLE_BEFORE_SWEEP
876
- * (half an hour of quiet says a stretch is finished), never a new constant. Counting is unchanged: every gap between two
877
- * messages, the person's or the model's, counts up to IDLE_CAP, and a gap the cut falls in is counted, as it always was,
878
- * with the run BEFORE it (the five minutes the clock credits after a message). So the runs' seconds sum to exactly what
879
- * the one envelope carried, and only the windows sharpen: a long-idle conversation no longer spans its own gap.
828
+ * (half an hour of quiet says a stretch is finished), never a new constant. The gap the cut falls in belongs to the run
829
+ * BEFORE it: that run's timeline ends with a closing step carrying the gap (kind U, the loop's own, never a turn), so
830
+ * WorkTrust counts the gap after the last message as it did when the day was one envelope, and only the windows sharpen.
880
831
  */
881
832
  const RUN_GAP = IDLE_BEFORE_SWEEP;
882
833
  function runsOf(messages) {
@@ -884,9 +835,8 @@ function runsOf(messages) {
884
835
  let current = null;
885
836
  for (let i = 0; i < messages.length; i += 1) {
886
837
  const gap = i === 0 ? null : messages[i].at - messages[i - 1].at;
887
- if (current && gap > RUN_GAP) { current.seconds += Math.min(IDLE_CAP, Math.round(gap / 1000)); current = null; }
888
- if (!current) { current = { messages: [], seconds: 0 }; runs.push(current); }
889
- else current.seconds += Math.min(IDLE_CAP, Math.round(gap / 1000));
838
+ if (current && gap > RUN_GAP) { current.tail = messages[i].at; current = null; }
839
+ if (!current) { current = { messages: [], tail: null }; runs.push(current); }
890
840
  current.messages.push(messages[i]);
891
841
  }
892
842
  return runs;
@@ -894,13 +844,12 @@ function runsOf(messages) {
894
844
  const EXPORTS_STATE = join(homedir(), ".worktrust", "exports.json"); // per export digest: sent, or offered and declined; nothing of a conversation
895
845
  const readExportsState = () => { try { return JSON.parse(readFileSync(EXPORTS_STATE, "utf8")); } catch { return {}; } };
896
846
  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)); };
897
- function exportEntries() {
847
+ async function exportEntries() {
898
848
  if (!exportSessions || !exportRunRef) throw Error("chat-exports.mjs is not beside this file, or is older than this hook: a data export cannot be read");
899
849
  const entries = [], reports = [];
900
850
  for (const given of EXPORT_PATHS) {
901
- const read = readExport(given);
902
- const report = { path: read.path, vendor: read.vendor, digest: read.digest, conversations: read.conversations.length, days: new Set(), seconds: 0 };
903
- for (const { id, lines } of exportSessions(read, { excluded })) {
851
+ const read = {}, report = { days: new Set() }; // 0.10.18: the reader streams the export and fills `read` as it goes (path and vendor first; digest, count and the conversations left out as too large at the end)
852
+ for await (const { id, lines } of exportSessions(given, { excluded, report: read })) {
904
853
  const messages = [];
905
854
  for (const line of lines) { const at = line.timestamp ? Date.parse(line.timestamp) : NaN; if (Number.isFinite(at)) messages.push(messageOf(line, at)); }
906
855
  messages.sort((a, b) => a.at - b.at);
@@ -908,16 +857,15 @@ function exportEntries() {
908
857
  if (ofDay.length === 0) continue;
909
858
  // ONE STRETCH PER RUN OF ACTIVITY (0.10.17): the day's messages cut where the hook calls a stretch finished; one run
910
859
  // is the day as before, under the name it always had; several name the one-envelope line they replace.
911
- const runs = runsOf(ofDay), whole = measure(null, ofDay), old = exportRef(read.vendor, id, day);
912
- runs.forEach(({ messages: run, seconds }, index) => {
860
+ const runs = runsOf(ofDay), old = exportRef(read.vendor, id, day);
861
+ runs.forEach(({ messages: run, tail }, index) => {
913
862
  const stretch = measure(null, run), ref = runs.length === 1 ? old : exportRunRef(read.vendor, id, day, index);
914
- // The day as a whole decides whether there is a duration (under a minute is none, as before); a run then carries
915
- // its own share of the day's count, and a run with nothing to count carries none.
916
- const own = runs.length === 1 ? whole.seconds : whole.seconds !== null && seconds > 0 ? seconds : null;
863
+ // The run's timeline, with the gap to the next run as a closing step (the loop's own, never a turn), so WorkTrust
864
+ // counts it with this run as the one envelope did; the last run of the day closes where the day did.
865
+ const timeline = stretch.timeline ? `${stretch.timeline}${tail ? `U${Math.min(999999, Math.max(0, Math.round((tail - run[run.length - 1].at) / 1000)))}` : ""}` : null;
917
866
  const entry = {
918
867
  title: EXPORT_TITLES[read.vendor], kind: "researched",
919
- ...(own !== null ? { seconds: Math.min(RECONSTRUCTED_MAX, own), duration_basis: "reconstructed" } : {}),
920
- ...(stretch.exchanges > 0 ? { exchanges: stretch.exchanges, turn_basis: "humanOnly" } : {}),
868
+ ...(timeline ? { timeline, duration_basis: "reconstructed", turn_basis: "humanOnly" } : {}),
921
869
  ...(stretch.model ? { model: stretch.model } : {}),
922
870
  stretch_ref: ref, source_event_id: `exp_${ref}`,
923
871
  ...(runs.length > 1 ? { supersedes_ref: old } : {}),
@@ -925,13 +873,13 @@ function exportEntries() {
925
873
  };
926
874
  entrySource.set(entry, read.vendor);
927
875
  entryFile.set(entry, { file: `${read.vendor}:${id}`, from: stretch.from, folder: null });
928
- report.seconds += entry.seconds ?? 0; entries.push(entry);
876
+ entries.push(entry);
929
877
  });
930
878
  report.days.add(day);
931
879
  }
932
880
  }
933
881
  const days = [...report.days].sort();
934
- reports.push({ ...report, days: days.length, hours: Math.round(report.seconds / 360) / 10, first: days[0] ?? null, last: days.at(-1) ?? null });
882
+ reports.push({ path: read.path, vendor: read.vendor, digest: read.digest, conversations: read.conversations, days: days.length, first: days[0] ?? null, last: days.at(-1) ?? null, oversized: read.oversized }); // no hours (0.10.20): WorkTrust computes them on arrival and the receipt says
935
883
  }
936
884
  const seen = new Set();
937
885
  return { entries: entries.filter((entry) => !seen.has(entry.stretch_ref) && seen.add(entry.stretch_ref)).sort((a, b) => a.at.localeCompare(b.at)), reports };
@@ -943,8 +891,8 @@ function exportEntries() {
943
891
  * themselves (a copy of one of them, or one holding them, is refused by name). Each day is named exactly as the live folder
944
892
  * 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
945
893
  * same copy, is skipped: the live folders win. What travels is RECONSTRUCTED: no device key witnessed the copy, and a copy can
946
- * be edited. The counts a transcript carries (tokens, turns, the model, the evidence) travel; the hours in layers, which say
947
- * what a MEASURED day's seconds were, do not. The title says where the line came from.
894
+ * be edited. The timeline, the tokens, the model and the evidence travel as they do for a live day; WorkTrust computes the
895
+ * reconstructed seconds from the timeline. The title says where the line came from.
948
896
  */
949
897
  function folderEntries(given) {
950
898
  const dir = given.replace(/^~(?=\/|$)/, homedir());
@@ -965,7 +913,7 @@ function folderEntries(given) {
965
913
  walk(here, 0);
966
914
  if (files.length === 0) throw Error(`no session files under ${given} (Claude Code transcripts, Codex rollouts or Antigravity transcripts, as .jsonl)`);
967
915
  const present = new Set(historyEntries(null, true).map((entry) => entry.stretch_ref)), seen = new Set();
968
- const entries = [], report = { stretches: 0, skipped: 0, days: new Set(), seconds: 0 };
916
+ const entries = [], report = { stretches: 0, skipped: 0, days: new Set() };
969
917
  for (const file of files) {
970
918
  const client = CODEX_ROLLOUT.test(file) ? "codex" : ANTIGRAVITY_TRANSCRIPT.test(file) ? "antigravity" : "claude";
971
919
  const lines = parsedLines(file);
@@ -985,17 +933,15 @@ function folderEntries(given) {
985
933
  report.stretches += 1;
986
934
  if (present.has(ref) || seen.has(ref)) { report.skipped += 1; continue; }
987
935
  seen.add(ref);
988
- const measured = payloadFor({ ...measure(cwd, messages), ref, steered: null, agents: null });
989
- const { model_seconds, tool_seconds, human_seconds, idle_seconds, agent_runs, agent_seconds, agent_peak, ...rest } = measured;
990
- void model_seconds; void tool_seconds; void human_seconds; void idle_seconds; void agent_runs; void agent_seconds; void agent_peak;
991
- 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" } : {}) };
936
+ const rest = payloadFor({ ...measure(cwd, messages), ref, steered: null, agents: null });
937
+ const entry = { ...rest, title: rest.layer ? `AI-assisted work from a copied session folder · ${rest.layer}` : "AI-assisted work from a copied session folder", ...(rest.timeline ? { duration_basis: "reconstructed" } : {}) };
992
938
  if (client !== "claude") entrySource.set(entry, client);
993
939
  entryFile.set(entry, { file, from: firstOf(messages), folder: null });
994
- report.days.add(day); report.seconds += entry.seconds ?? 0; entries.push(entry);
940
+ report.days.add(day); entries.push(entry);
995
941
  }
996
942
  }
997
943
  const days = [...report.days].sort();
998
- 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 } };
944
+ return { entries: entries.sort((a, b) => a.at.localeCompare(b.at)), report: { stretches: report.stretches, skipped: report.skipped, days: days.length, first: days[0] ?? null, last: days.at(-1) ?? null } };
999
945
  }
1000
946
 
1001
947
  /** Every transcript this machine holds, excluded projects skipped before a file is opened. */
@@ -1077,7 +1023,7 @@ if (flag("uninstall")) {
1077
1023
  if (flag("purge")) for (const path of [COUNTER, PINNED, join(homedir(), ".worktrust", "log-session.mjs"), STATE, ...READER_FILES.map((name) => join(homedir(), ".worktrust", name)), join(homedir(), ".worktrust", "antigravity.json")]) { try { rmSync(path); } catch { /* already gone */ } }
1078
1024
  console.log(`${removed ? "removed" : "nothing wired"}: ${file}${flag("purge") ? "\n purged ~/.worktrust" : ""}`);
1079
1025
  console.log("the coupling itself still exists: end it in the app (Sources → the computer's row → end this coupling)");
1080
- await exitFlushed(0);
1026
+ return await exitFlushed(0);
1081
1027
  }
1082
1028
 
1083
1029
  if (flag("install")) {
@@ -1156,7 +1102,7 @@ if (flag("install")) {
1156
1102
  } catch (error) { console.log(`counter: could not fetch it (${error.message}) — the hook works without it; fetch /counter/count-behaviour.mjs later`); }
1157
1103
  }
1158
1104
  }
1159
- if (already && !repaired) { console.log(hookRefreshed ? `hook updated: ${home} now runs the version you downloaded; the wiring was already right (${command})` : `already installed — nothing changed (${command})`); await exitFlushed(0); }
1105
+ if (already && !repaired) { console.log(hookRefreshed ? `hook updated: ${home} now runs the version you downloaded; the wiring was already right (${command})` : `already installed — nothing changed (${command})`); return await exitFlushed(0); }
1160
1106
  for (const event of added) settings.hooks[event].push({ hooks: [{ type: "command", command }] });
1161
1107
  mkdirSync(dirname(file), { recursive: true });
1162
1108
  writeFileSync(file, JSON.stringify(settings, null, 2));
@@ -1167,7 +1113,7 @@ if (flag("install")) {
1167
1113
  // never rewrites: `npx worktrust` asks and writes it (WORKTRUST_CODEX_OFFER, so no hint twice), and
1168
1114
  // without it Codex rollouts are still swept whenever the Claude Code hook runs.
1169
1115
  if (existsSync(join(homedir(), ".codex")) && !process.env.WORKTRUST_CODEX_OFFER) console.log(`codex: to have Codex wake this hook too, add to ~/.codex/config.toml:\n notify = ${via ? `["${process.env.WORKTRUST_NODE || process.execPath}", "${via}", "hook", "--codex-notify"]` : `["node", "${home}", "--codex-notify"]`}\n (its rollouts are swept on every run either way)`);
1170
- await exitFlushed(0);
1116
+ return await exitFlushed(0);
1171
1117
  }
1172
1118
 
1173
1119
  const door = coupling();
@@ -1190,7 +1136,7 @@ if (flag("evidence-summary")) {
1190
1136
  const complexity = {};
1191
1137
  for (const entry of rows) { const tier = DERIVED.get(entry)?.complexity?.class; if (tier) complexity[tier] = (complexity[tier] ?? 0) + 1; }
1192
1138
  const summary = {
1193
- stretches: rows.length, hours: Math.round(rows.reduce((total, entry) => total + (entry.seconds ?? 0), 0) / 360) / 10,
1139
+ stretches: rows.length, // the hours are WorkTrust's (0.10.20): the app shows them
1194
1140
  delivered: sum((d) => (d.delivery ? 1 : 0)), verified_first: sum((d) => (d.delivery?.verified_first ? 1 : 0)),
1195
1141
  failures: sum((d) => d.recovery?.failures), recovered: sum((d) => d.recovery?.recovered), blind_retries: sum((d) => d.recovery?.blind_retries),
1196
1142
  steers: sum((d) => d.steering?.moments), effective_steers: sum((d) => d.steering?.effective),
@@ -1198,14 +1144,14 @@ if (flag("evidence-summary")) {
1198
1144
  planned: sum((d) => (d.planning ? 1 : 0)), files: sum((d) => d.changes?.files), test_files: sum((d) => d.changes?.test_files), complexity,
1199
1145
  };
1200
1146
  process.stdout.write(`${JSON.stringify(summary)}\n`);
1201
- await exitFlushed(0);
1147
+ return await exitFlushed(0);
1202
1148
  }
1203
- 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
1149
+ 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`); return await exitFlushed(0); } // one write and a count, so the reader tells a whole answer from a cut one
1204
1150
  // THE EXPORTS IN A FOLDER (0.10.10, for the bare `npx worktrust`): which lie there, by vendor and digest, and which this computer
1205
1151
  // already sent or was asked about; reads, prints one JSON line, sends nothing. `--export-offered <digest>` records a No.
1206
- 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); }
1207
- if (value("export-offered")) { rememberExport(value("export-offered"), { offered: new Date().toISOString() }); await exitFlushed(0); }
1208
- if (!door && !codexDoor && !DRY) { process.exit(0); } // Not coupled on this machine: nothing to do, quietly.
1152
+ if (flag("find-exports")) { const named = value("find-exports"), state = readExportsState(); const found = (findExports ? await 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`); return await exitFlushed(0); }
1153
+ if (value("export-offered")) { rememberExport(value("export-offered"), { offered: new Date().toISOString() }); return await exitFlushed(0); }
1154
+ if (!door && !codexDoor && !DRY) { return await exitFlushed(0); } // Not coupled on this machine: nothing to do, quietly.
1209
1155
 
1210
1156
  /**
1211
1157
  * HISTORY FROM THE ARCHIVE (0.8.0; framework §22). When an AI app has deleted its sessions, the stretches this computer
@@ -1223,59 +1169,59 @@ if (flag("history") && flag("from-archive")) {
1223
1169
  // archive must still verify whole, and only stretches no longer in any AI app here travel.
1224
1170
  let ownKey = null;
1225
1171
  try { ownKey = pem ? createPublicKey(createPrivateKey(pem)).export({ format: "jwk" }).x : null; } catch { ownKey = null; }
1226
- const verified = spawnSync(process.execPath, [join(dirname(fileURLToPath(import.meta.url)), "preserve.mjs"), "--verify", dir], { encoding: "utf8" });
1227
- 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); }
1172
+ const verified = spawnSync(process.execPath, [...NODE_FLAGS, join(dirname(fileURLToPath(import.meta.url)), "preserve.mjs"), "--verify", dir], { encoding: "utf8" });
1173
+ if (verified.status !== 0) { say(`The archive in ${dir} does not verify, so nothing was sent: ${(verified.stdout || verified.stderr || "").trim().split("\n").pop()}`); return await exitFlushed(1); }
1228
1174
  const { archiveEntries = null } = (await import("./preserve-lines.mjs").catch(() => null)) ?? {};
1229
- if (!archiveEntries) { say("preserve-lines.mjs is not beside this file. Nothing was sent."); await exitFlushed(1); }
1175
+ if (!archiveEntries) { say("preserve-lines.mjs is not beside this file. Nothing was sent."); return await exitFlushed(1); }
1230
1176
  const present = new Set(historyEntries(null, true).map((entry) => entry.stretch_ref));
1231
1177
  const all = archiveEntries(dir, ownKey), gone = all.filter(({ entry }) => !present.has(entry.stretch_ref));
1232
1178
  const entries = gone.map(({ entry, client, signed }) => {
1233
1179
  if (client !== "claude") entrySource.set(entry, client);
1234
- if (!signed && typeof entry.seconds === "number") { entry.seconds = Math.min(RECONSTRUCTED_MAX, entry.seconds); entry.duration_basis = "reconstructed"; }
1180
+ if (!signed && (typeof entry.seconds === "number" || typeof entry.timeline === "string")) entry.duration_basis = "reconstructed"; // the door keeps an unmeasured stretch inside its own ceiling
1235
1181
  return entry;
1236
1182
  });
1237
1183
  const signedCount = all.filter(({ signed }) => signed).length;
1238
1184
  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`);
1239
- 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); }
1240
- 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); }
1241
- await exitFlushed((await sendHistory(door, entries, true)) === entries.length ? 0 : 1);
1185
+ 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."); return await exitFlushed(0); }
1186
+ if (!(await doorKnowsArchive(door))) { say("WorkTrust does not accept history from an archive yet (the door does not know the mark). Nothing was sent."); return await exitFlushed(1); }
1187
+ return await exitFlushed((await sendHistory(door, entries, true)) === entries.length ? 0 : 1);
1242
1188
  }
1243
1189
 
1244
1190
  if (flag("history")) {
1245
1191
  const historyFloor = floorOf(readState(), "__historyFloor");
1246
1192
  // 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).
1247
1193
  let fromExports = null, fromFolder = null;
1248
- if (EXPORT_PATHS.length > 0) { try { fromExports = exportEntries(); } catch (error) { console.log(`export: ${error.message}`); await exitFlushed(1); } }
1194
+ if (EXPORT_PATHS.length > 0) { try { fromExports = await exportEntries(); } catch (error) { console.log(`export: ${error.message}`); return await exitFlushed(1); } }
1249
1195
  // A COPIED SESSION FOLDER (0.10.10): its own history, reconstructed, the live folders' stretches skipped; never a rebuild.
1250
1196
  if (flag("from-folder")) {
1251
1197
  const given = value("from-folder");
1252
- if (!given || given.startsWith("--")) { console.log("folder: --from-folder needs the copied folder's path"); await exitFlushed(1); }
1253
- try { fromFolder = folderEntries(given); } catch (error) { console.log(`folder: ${error.message}`); await exitFlushed(1); }
1198
+ if (!given || given.startsWith("--")) { console.log("folder: --from-folder needs the copied folder's path"); return await exitFlushed(1); }
1199
+ try { fromFolder = folderEntries(given); } catch (error) { console.log(`folder: ${error.message}`); return await exitFlushed(1); }
1254
1200
  }
1255
- 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); }
1201
+ 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."); return await exitFlushed(1); }
1256
1202
  // 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
1257
1203
  // lines under no product go only with `--withdraw-unknown`, which the command sends after the person's yes, with an export alone.
1258
- 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); }
1204
+ 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."); return await exitFlushed(1); }
1259
1205
  const entries = fromExports ? fromExports.entries : fromFolder ? fromFolder.entries : historyEntries(historyFloor);
1260
- const hours = entries.reduce((sum, entry) => sum + (entry.seconds ?? 0), 0) / 3600;
1261
1206
  const months = [...new Set(entries.map((entry) => entry.at.slice(0, 7)))].sort();
1262
- // 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.
1263
- 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) }));
1264
- 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); }
1265
- 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" : ""}`);
1207
+ // ONE LINE FOR `npx worktrust` TO ASK WITH (2026-10-03): sessions, days, first and last month; per client its days (the rebuild's plan,
1208
+ // 2026-10-07); nothing sent. NO HOURS (0.10.20): the hours are WorkTrust's to compute; the receipt after the send carries them.
1209
+ const clients = [...entries.reduce((map, entry) => { const client = entrySource.get(entry) ?? "claude", row = map.get(client) ?? { client, days: new Set() }; row.days.add(entry.at.slice(0, 10)); return map.set(client, row); }, new Map()).values()].map((row) => ({ client: row.client, days: row.days.size, first: [...row.days].sort()[0], last: [...row.days].sort().at(-1) }));
1210
+ if (flag("summary")) { console.log(JSON.stringify({ sessions: new Set(entries.map((entry) => entryFile.get(entry).file)).size, days: new Set(entries.map((entry) => entry.at.slice(0, 10))).size, first: months[0] ?? null, last: months.at(-1) ?? null, ...(fromExports ? { exports: fromExports.reports } : {}), ...(fromFolder ? { folder: fromFolder.report } : {}), clients })); return await exitFlushed(0); }
1211
+ console.log(`${entries.length} day-stretches · ${fromExports || fromFolder ? "reconstructed" : "measured"} by WorkTrust on arrival · ${months.join(", ")}${flag("rebuild") ? " · rebuild: this computer's earlier lines for these days and clients are replaced at the door" : ""}`);
1266
1212
  if (DRY) {
1267
1213
  // One example in full: the shape is the argument for trusting it, and a summary hides it.
1268
1214
  if (entries[0]) console.log(`\nthe oldest of them, in full:\n${JSON.stringify(entries[0], null, 1)}`);
1269
1215
  console.log(`\ndry run — nothing sent. Add --history${flag("rebuild") ? " --rebuild" : ""} without --dry-run to ${flag("rebuild") ? "rebuild" : "import"} them.`);
1270
- await exitFlushed(0);
1216
+ return await exitFlushed(0);
1271
1217
  }
1272
1218
  // A batch the door refused is a failure the caller must see, not a quiet zero.
1273
1219
  const accepted = await sendHistory(door, entries, true, flag("rebuild"), Boolean(fromFolder), fromExports ? { byDay: true, withdrawUnknown: flag("withdraw-unknown") } : {});
1274
1220
  // An export that arrived whole is remembered by its digest (never by a conversation), so the bare command offers it no more.
1275
1221
  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 });
1276
1222
  // 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.
1277
- if (fromExports) console.log(JSON.stringify({ export_sent: accepted, of: entries.length, ...RECEIPTS })); else console.log(JSON.stringify({ history_sent: accepted, of: entries.length, ...RECEIPTS })); // the same line for a history send: what the door did with it
1278
- await exitFlushed(accepted === entries.length ? 0 : 1);
1223
+ if (fromExports) console.log(JSON.stringify({ export_sent: accepted, of: entries.length, ...RECEIPTS })); else console.log(JSON.stringify({ history_sent: accepted, of: entries.length, ...RECEIPTS })); // the same line for a history send: what the door did with it, and WorkTrust's measuredSeconds for what it stored
1224
+ return await exitFlushed(accepted === entries.length ? 0 : 1);
1279
1225
  }
1280
1226
 
1281
1227
  const input = hookInput();
@@ -1354,11 +1300,14 @@ if (!DRY && existsSync(COUNTER)) {
1354
1300
  const last = state.__counter?.at ? Date.parse(state.__counter.at) : 0;
1355
1301
  if (Date.now() - last > COUNTER_EVERY_MS) {
1356
1302
  try {
1357
- const child = spawn(process.execPath, [COUNTER, "--stage"], { detached: true, stdio: "ignore" });
1303
+ const child = spawn(process.execPath, [...NODE_FLAGS, COUNTER, "--stage"], { detached: true, stdio: "ignore" });
1358
1304
  child.unref();
1359
1305
  state.__counter = { at: new Date().toISOString() };
1360
1306
  writeState(state);
1361
1307
  } catch { /* the counter is a bonus; a hook that fails on it would cost the stretch it just logged */ }
1362
1308
  }
1363
1309
  }
1364
- await exitFlushed(0);
1310
+ return await exitFlushed(0);
1311
+
1312
+ }
1313
+ await main();