worktrust 0.10.18 → 0.10.21

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,28 +47,30 @@
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.
64
61
  */
65
62
  import { execFileSync, spawn, spawnSync } from "node:child_process";
66
- import { copyFileSync, existsSync, mkdirSync, readFileSync, readdirSync, rmSync, statSync, writeFileSync } from "node:fs";
63
+ import { copyFileSync, existsSync, mkdirSync, readFileSync, readdirSync, rmSync, statSync, writeFileSync, lstatSync, openSync, closeSync, fsyncSync, linkSync, unlinkSync, constants } from "node:fs";
67
64
  import { homedir } from "node:os";
68
65
  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
@@ -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");
@@ -744,6 +698,43 @@ const noteReceipt = (answer) => {
744
698
  for (const key of Object.keys(RECEIPTS)) RECEIPTS[key] += Number(receipt[key]) || 0;
745
699
  } catch { /* a receipt unread leaves the counts short, never the send */ }
746
700
  };
701
+ /** Only explicit durable receipts authorize a checkpoint. HTTP 200 alone says nothing. */
702
+ function confirmedReceipt(answer, expectedCount = null) {
703
+ try {
704
+ const candidates = answer.trim().startsWith("{") ? [answer] : answer.split(/\r?\n/).filter(line => line.startsWith("data:")).map(line => line.slice(5).trim()).filter(line => line && line !== "[DONE]");
705
+ const replies = candidates.map(text => JSON.parse(text)).filter(reply => reply?.id === 1);
706
+ if (replies.length !== 1) throw Error();
707
+ const reply = replies[0];
708
+ if (reply.jsonrpc !== "2.0" || reply.error || !reply.result || reply.result.isError === true) throw Error();
709
+ const content = reply.result.content;
710
+ if (!Array.isArray(content) || content.length !== 1 || content[0].type !== "text") throw Error();
711
+ const receipt = JSON.parse(content[0].text);
712
+ if (expectedCount === null) {
713
+ if (!(receipt.receipt === "received" && ["accepted", "flagged", "pending"].includes(receipt.status)) && !(receipt.receipt === "unchanged" && receipt.reason === "duplicate")) throw Error();
714
+ } else if (receipt.receipt !== "received" || receipt.received !== expectedCount || receipt.refused !== 0
715
+ || !Number.isInteger(receipt.new) || receipt.new < 0 || !Number.isInteger(receipt.alreadyHeld) || receipt.alreadyHeld < 0
716
+ || receipt.new + receipt.alreadyHeld !== expectedCount) throw Error();
717
+ return receipt;
718
+ } catch { throw Error("WorkTrust did not confirm every line; progress was not advanced. Retained metadata and safe retries remain available."); }
719
+ }
720
+ /** A private metadata journal survives retries, an edited transcript and a later CLI update. */
721
+ function retainMeasurement(payload, source) {
722
+ const fields = ["stretch_ref", "at", "started_at", "timeline", "seconds", "client_seconds", "model_seconds", "tool_seconds", "human_seconds", "idle_seconds", "tokens_in", "tokens_out", "tokens_cache_read", "tokens_cache_write", "exchanges", "interrupts", "steers", "agent_runs", "agent_seconds", "agent_peak", "duration_basis", "token_basis", "turn_basis", "cli_version", "cli_digest"];
723
+ const metadata = Object.fromEntries(fields.filter(key => Object.hasOwn(payload, key)).map(key => [key, payload[key]]));
724
+ const body = JSON.stringify({ format: "worktrust-measurement/1", source: source ?? "claude", metadata }) + "\n";
725
+ const parent = join(homedir(), ".worktrust"), dir = join(parent, "measurements");
726
+ for (const path of [parent, dir]) { mkdirSync(path, { recursive: true, mode: 0o700 }); const st = lstatSync(path); if (!st.isDirectory() || st.isSymbolicLink()) throw Error("WorkTrust metadata directory is not a private directory"); }
727
+ const file = join(dir, createHash("sha256").update(body).digest("hex") + ".json");
728
+ if (existsSync(file)) { const st = lstatSync(file); if (!st.isFile() || st.isSymbolicLink() || readFileSync(file, "utf8") !== body) throw Error("WorkTrust retained metadata did not match its digest"); return; }
729
+ const temporary = join(dir, ".pending-" + randomBytes(18).toString("hex"));
730
+ const fd = openSync(temporary, constants.O_WRONLY | constants.O_CREAT | constants.O_EXCL | (constants.O_NOFOLLOW ?? 0), 0o600);
731
+ try {
732
+ writeFileSync(fd, body); fsyncSync(fd);
733
+ try { linkSync(temporary, file); } catch (error) {
734
+ if (error.code !== "EEXIST" || lstatSync(file).isSymbolicLink() || readFileSync(file, "utf8") !== body) throw error;
735
+ }
736
+ } finally { closeSync(fd); unlinkSync(temporary); }
737
+ }
747
738
  async function sendHistory(door, entries, announce = false, rebuild = false, named = false, { byDay = false, withdrawUnknown = false } = {}) {
748
739
  let accepted = 0;
749
740
  // A Codex entry goes through Codex's own coupling where one exists (see codexDoor), the rest
@@ -760,11 +751,13 @@ async function sendHistory(door, entries, announce = false, rebuild = false, nam
760
751
  // 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.
761
752
  // 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
753
  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; }) } } });
754
+ for (const entry of batch) retainMeasurement(entry, source);
763
755
  // `named` (0.10.10): a copied folder's lines name their client too, so the record says which app the copy came from.
764
756
  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 });
765
757
  const text = await response.text();
766
758
  if (announce) console.log(`batch ${number}: ${response.status} ${text.slice(0, 200).replace(/\\n/g, " ")}`);
767
759
  if (!response.ok) break;
760
+ try { confirmedReceipt(text, batch.length); } catch { break; }
768
761
  accepted += batch.length;
769
762
  noteReceipt(text);
770
763
  }
@@ -802,10 +795,13 @@ const proofFor = (url, body) => {
802
795
  const clientOf = (source, always = false) => (always || source === "antigravity" || DATABASE_CLIENTS.includes(source) || EXPORT_CLIENTS.includes(source) ? { "user-agent": `${source ?? "claude"}/hook (worktrust-hook)` } : {});
803
796
 
804
797
  async function send(door, payload) {
798
+ retainMeasurement(payload, entrySource.get(payload));
805
799
  const body = JSON.stringify({ jsonrpc: "2.0", id: 1, method: "tools/call", params: { name: "log_work", arguments: payload } });
806
800
  const response = await fetch(door.url, { method: "POST", headers: { "content-type": "application/json", accept: "application/json, text/event-stream", authorization: `Bearer ${door.token}`, ...clientOf(entrySource.get(payload)), ...proofFor(door.url, body) }, body });
807
801
  if (!response.ok) throw new Error(`door said ${response.status}`);
808
- return response.text();
802
+ const text = await response.text();
803
+ confirmedReceipt(text);
804
+ return text;
809
805
  }
810
806
 
811
807
  /**
@@ -863,20 +859,17 @@ function historyEntries(floor = null, all = false) {
863
859
  /**
864
860
  * A DATA EXPORT'S CONVERSATIONS AS HISTORY (0.10.10, owner 2026-10-10: "hours from an export count as reconstructed, shown,
865
861
  * 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.
862
+ * envelope per conversation and day. Each run travels as its TIMELINE (0.10.20) and WorkTrust computes its reconstructed
863
+ * seconds and the person's turns from it; the line says `reconstructed`: the file can be edited before it is read and no
864
+ * device key witnessed it. No tokens (the export carries none and none are estimated), no evidence; the title names the
865
+ * product and never the conversation; the stretch's name is the vendor, the conversation's id and the day, so the same
866
+ * export sent twice is each line once. The database keeps a reconstructed stretch inside eight hours (20261009170000).
872
867
  */
873
- const RECONSTRUCTED_MAX = 28800;
874
868
  /**
875
869
  * 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.
870
+ * (half an hour of quiet says a stretch is finished), never a new constant. The gap the cut falls in belongs to the run
871
+ * BEFORE it: that run's timeline ends with a closing step carrying the gap (kind U, the loop's own, never a turn), so
872
+ * WorkTrust counts the gap after the last message as it did when the day was one envelope, and only the windows sharpen.
880
873
  */
881
874
  const RUN_GAP = IDLE_BEFORE_SWEEP;
882
875
  function runsOf(messages) {
@@ -884,9 +877,8 @@ function runsOf(messages) {
884
877
  let current = null;
885
878
  for (let i = 0; i < messages.length; i += 1) {
886
879
  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));
880
+ if (current && gap > RUN_GAP) { current.tail = messages[i].at; current = null; }
881
+ if (!current) { current = { messages: [], tail: null }; runs.push(current); }
890
882
  current.messages.push(messages[i]);
891
883
  }
892
884
  return runs;
@@ -898,7 +890,7 @@ async function exportEntries() {
898
890
  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
891
  const entries = [], reports = [];
900
892
  for (const given of EXPORT_PATHS) {
901
- const read = {}, report = { days: new Set(), seconds: 0 }; // 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)
893
+ 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)
902
894
  for await (const { id, lines } of exportSessions(given, { excluded, report: read })) {
903
895
  const messages = [];
904
896
  for (const line of lines) { const at = line.timestamp ? Date.parse(line.timestamp) : NaN; if (Number.isFinite(at)) messages.push(messageOf(line, at)); }
@@ -907,16 +899,15 @@ async function exportEntries() {
907
899
  if (ofDay.length === 0) continue;
908
900
  // ONE STRETCH PER RUN OF ACTIVITY (0.10.17): the day's messages cut where the hook calls a stretch finished; one run
909
901
  // is the day as before, under the name it always had; several name the one-envelope line they replace.
910
- const runs = runsOf(ofDay), whole = measure(null, ofDay), old = exportRef(read.vendor, id, day);
911
- runs.forEach(({ messages: run, seconds }, index) => {
902
+ const runs = runsOf(ofDay), old = exportRef(read.vendor, id, day);
903
+ runs.forEach(({ messages: run, tail }, index) => {
912
904
  const stretch = measure(null, run), ref = runs.length === 1 ? old : exportRunRef(read.vendor, id, day, index);
913
- // The day as a whole decides whether there is a duration (under a minute is none, as before); a run then carries
914
- // its own share of the day's count, and a run with nothing to count carries none.
915
- const own = runs.length === 1 ? whole.seconds : whole.seconds !== null && seconds > 0 ? seconds : null;
905
+ // The run's timeline, with the gap to the next run as a closing step (the loop's own, never a turn), so WorkTrust
906
+ // counts it with this run as the one envelope did; the last run of the day closes where the day did.
907
+ const timeline = stretch.timeline ? `${stretch.timeline}${tail ? `U${Math.min(999999, Math.max(0, Math.round((tail - run[run.length - 1].at) / 1000)))}` : ""}` : null;
916
908
  const entry = {
917
909
  title: EXPORT_TITLES[read.vendor], kind: "researched",
918
- ...(own !== null ? { seconds: Math.min(RECONSTRUCTED_MAX, own), duration_basis: "reconstructed" } : {}),
919
- ...(stretch.exchanges > 0 ? { exchanges: stretch.exchanges, turn_basis: "humanOnly" } : {}),
910
+ ...(timeline ? { timeline, duration_basis: "reconstructed", turn_basis: "humanOnly" } : {}),
920
911
  ...(stretch.model ? { model: stretch.model } : {}),
921
912
  stretch_ref: ref, source_event_id: `exp_${ref}`,
922
913
  ...(runs.length > 1 ? { supersedes_ref: old } : {}),
@@ -924,13 +915,13 @@ async function exportEntries() {
924
915
  };
925
916
  entrySource.set(entry, read.vendor);
926
917
  entryFile.set(entry, { file: `${read.vendor}:${id}`, from: stretch.from, folder: null });
927
- report.seconds += entry.seconds ?? 0; entries.push(entry);
918
+ entries.push(entry);
928
919
  });
929
920
  report.days.add(day);
930
921
  }
931
922
  }
932
923
  const days = [...report.days].sort();
933
- reports.push({ path: read.path, vendor: read.vendor, digest: read.digest, conversations: read.conversations, days: days.length, seconds: report.seconds, hours: Math.round(report.seconds / 360) / 10, first: days[0] ?? null, last: days.at(-1) ?? null, oversized: read.oversized });
924
+ 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
934
925
  }
935
926
  const seen = new Set();
936
927
  return { entries: entries.filter((entry) => !seen.has(entry.stretch_ref) && seen.add(entry.stretch_ref)).sort((a, b) => a.at.localeCompare(b.at)), reports };
@@ -942,8 +933,8 @@ async function exportEntries() {
942
933
  * themselves (a copy of one of them, or one holding them, is refused by name). Each day is named exactly as the live folder
943
934
  * 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
944
935
  * same copy, is skipped: the live folders win. What travels is RECONSTRUCTED: no device key witnessed the copy, and a copy can
945
- * be edited. The counts a transcript carries (tokens, turns, the model, the evidence) travel; the hours in layers, which say
946
- * what a MEASURED day's seconds were, do not. The title says where the line came from.
936
+ * be edited. The timeline, the tokens, the model and the evidence travel as they do for a live day; WorkTrust computes the
937
+ * reconstructed seconds from the timeline. The title says where the line came from.
947
938
  */
948
939
  function folderEntries(given) {
949
940
  const dir = given.replace(/^~(?=\/|$)/, homedir());
@@ -964,7 +955,7 @@ function folderEntries(given) {
964
955
  walk(here, 0);
965
956
  if (files.length === 0) throw Error(`no session files under ${given} (Claude Code transcripts, Codex rollouts or Antigravity transcripts, as .jsonl)`);
966
957
  const present = new Set(historyEntries(null, true).map((entry) => entry.stretch_ref)), seen = new Set();
967
- const entries = [], report = { stretches: 0, skipped: 0, days: new Set(), seconds: 0 };
958
+ const entries = [], report = { stretches: 0, skipped: 0, days: new Set() };
968
959
  for (const file of files) {
969
960
  const client = CODEX_ROLLOUT.test(file) ? "codex" : ANTIGRAVITY_TRANSCRIPT.test(file) ? "antigravity" : "claude";
970
961
  const lines = parsedLines(file);
@@ -984,17 +975,15 @@ function folderEntries(given) {
984
975
  report.stretches += 1;
985
976
  if (present.has(ref) || seen.has(ref)) { report.skipped += 1; continue; }
986
977
  seen.add(ref);
987
- const measured = payloadFor({ ...measure(cwd, messages), ref, steered: null, agents: null });
988
- const { model_seconds, tool_seconds, human_seconds, idle_seconds, agent_runs, agent_seconds, agent_peak, ...rest } = measured;
989
- void model_seconds; void tool_seconds; void human_seconds; void idle_seconds; void agent_runs; void agent_seconds; void agent_peak;
990
- 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" } : {}) };
978
+ const rest = payloadFor({ ...measure(cwd, messages), ref, steered: null, agents: null });
979
+ 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" } : {}) };
991
980
  if (client !== "claude") entrySource.set(entry, client);
992
981
  entryFile.set(entry, { file, from: firstOf(messages), folder: null });
993
- report.days.add(day); report.seconds += entry.seconds ?? 0; entries.push(entry);
982
+ report.days.add(day); entries.push(entry);
994
983
  }
995
984
  }
996
985
  const days = [...report.days].sort();
997
- 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 } };
986
+ 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 } };
998
987
  }
999
988
 
1000
989
  /** Every transcript this machine holds, excluded projects skipped before a file is opened. */
@@ -1076,7 +1065,7 @@ if (flag("uninstall")) {
1076
1065
  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 */ } }
1077
1066
  console.log(`${removed ? "removed" : "nothing wired"}: ${file}${flag("purge") ? "\n purged ~/.worktrust" : ""}`);
1078
1067
  console.log("the coupling itself still exists: end it in the app (Sources → the computer's row → end this coupling)");
1079
- await exitFlushed(0);
1068
+ return await exitFlushed(0);
1080
1069
  }
1081
1070
 
1082
1071
  if (flag("install")) {
@@ -1155,7 +1144,7 @@ if (flag("install")) {
1155
1144
  } catch (error) { console.log(`counter: could not fetch it (${error.message}) — the hook works without it; fetch /counter/count-behaviour.mjs later`); }
1156
1145
  }
1157
1146
  }
1158
- 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); }
1147
+ 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); }
1159
1148
  for (const event of added) settings.hooks[event].push({ hooks: [{ type: "command", command }] });
1160
1149
  mkdirSync(dirname(file), { recursive: true });
1161
1150
  writeFileSync(file, JSON.stringify(settings, null, 2));
@@ -1166,7 +1155,7 @@ if (flag("install")) {
1166
1155
  // never rewrites: `npx worktrust` asks and writes it (WORKTRUST_CODEX_OFFER, so no hint twice), and
1167
1156
  // without it Codex rollouts are still swept whenever the Claude Code hook runs.
1168
1157
  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)`);
1169
- await exitFlushed(0);
1158
+ return await exitFlushed(0);
1170
1159
  }
1171
1160
 
1172
1161
  const door = coupling();
@@ -1189,7 +1178,7 @@ if (flag("evidence-summary")) {
1189
1178
  const complexity = {};
1190
1179
  for (const entry of rows) { const tier = DERIVED.get(entry)?.complexity?.class; if (tier) complexity[tier] = (complexity[tier] ?? 0) + 1; }
1191
1180
  const summary = {
1192
- stretches: rows.length, hours: Math.round(rows.reduce((total, entry) => total + (entry.seconds ?? 0), 0) / 360) / 10,
1181
+ stretches: rows.length, // the hours are WorkTrust's (0.10.20): the app shows them
1193
1182
  delivered: sum((d) => (d.delivery ? 1 : 0)), verified_first: sum((d) => (d.delivery?.verified_first ? 1 : 0)),
1194
1183
  failures: sum((d) => d.recovery?.failures), recovered: sum((d) => d.recovery?.recovered), blind_retries: sum((d) => d.recovery?.blind_retries),
1195
1184
  steers: sum((d) => d.steering?.moments), effective_steers: sum((d) => d.steering?.effective),
@@ -1197,14 +1186,14 @@ if (flag("evidence-summary")) {
1197
1186
  planned: sum((d) => (d.planning ? 1 : 0)), files: sum((d) => d.changes?.files), test_files: sum((d) => d.changes?.test_files), complexity,
1198
1187
  };
1199
1188
  process.stdout.write(`${JSON.stringify(summary)}\n`);
1200
- await exitFlushed(0);
1189
+ return await exitFlushed(0);
1201
1190
  }
1202
- 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
1191
+ 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
1203
1192
  // THE EXPORTS IN A FOLDER (0.10.10, for the bare `npx worktrust`): which lie there, by vendor and digest, and which this computer
1204
1193
  // already sent or was asked about; reads, prints one JSON line, sends nothing. `--export-offered <digest>` records a No.
1205
- 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`); await exitFlushed(0); }
1206
- if (value("export-offered")) { rememberExport(value("export-offered"), { offered: new Date().toISOString() }); await exitFlushed(0); }
1207
- if (!door && !codexDoor && !DRY) { process.exit(0); } // Not coupled on this machine: nothing to do, quietly.
1194
+ 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); }
1195
+ if (value("export-offered")) { rememberExport(value("export-offered"), { offered: new Date().toISOString() }); return await exitFlushed(0); }
1196
+ if (!door && !codexDoor && !DRY) { return await exitFlushed(0); } // Not coupled on this machine: nothing to do, quietly.
1208
1197
 
1209
1198
  /**
1210
1199
  * HISTORY FROM THE ARCHIVE (0.8.0; framework §22). When an AI app has deleted its sessions, the stretches this computer
@@ -1222,59 +1211,59 @@ if (flag("history") && flag("from-archive")) {
1222
1211
  // archive must still verify whole, and only stretches no longer in any AI app here travel.
1223
1212
  let ownKey = null;
1224
1213
  try { ownKey = pem ? createPublicKey(createPrivateKey(pem)).export({ format: "jwk" }).x : null; } catch { ownKey = null; }
1225
- const verified = spawnSync(process.execPath, [join(dirname(fileURLToPath(import.meta.url)), "preserve.mjs"), "--verify", dir], { encoding: "utf8" });
1226
- 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); }
1214
+ const verified = spawnSync(process.execPath, [...NODE_FLAGS, join(dirname(fileURLToPath(import.meta.url)), "preserve.mjs"), "--verify", dir], { encoding: "utf8" });
1215
+ 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); }
1227
1216
  const { archiveEntries = null } = (await import("./preserve-lines.mjs").catch(() => null)) ?? {};
1228
- if (!archiveEntries) { say("preserve-lines.mjs is not beside this file. Nothing was sent."); await exitFlushed(1); }
1217
+ if (!archiveEntries) { say("preserve-lines.mjs is not beside this file. Nothing was sent."); return await exitFlushed(1); }
1229
1218
  const present = new Set(historyEntries(null, true).map((entry) => entry.stretch_ref));
1230
1219
  const all = archiveEntries(dir, ownKey), gone = all.filter(({ entry }) => !present.has(entry.stretch_ref));
1231
1220
  const entries = gone.map(({ entry, client, signed }) => {
1232
1221
  if (client !== "claude") entrySource.set(entry, client);
1233
- if (!signed && typeof entry.seconds === "number") { entry.seconds = Math.min(RECONSTRUCTED_MAX, entry.seconds); entry.duration_basis = "reconstructed"; }
1222
+ if (!signed && (typeof entry.seconds === "number" || typeof entry.timeline === "string")) entry.duration_basis = "reconstructed"; // the door keeps an unmeasured stretch inside its own ceiling
1234
1223
  return entry;
1235
1224
  });
1236
1225
  const signedCount = all.filter(({ signed }) => signed).length;
1237
- 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`);
1238
- 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); }
1239
- 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); }
1240
- await exitFlushed((await sendHistory(door, entries, true)) === entries.length ? 0 : 1);
1226
+ say(`${all.length} stretches in the archive · ${signedCount} signed by this computer's key (signature checked) · ${all.length - signedCount} unsigned or signed by another key (reconstructed) · ${entries.length} of them no longer in any AI app here`);
1227
+ 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); }
1228
+ 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); }
1229
+ return await exitFlushed((await sendHistory(door, entries, true)) === entries.length ? 0 : 1);
1241
1230
  }
1242
1231
 
1243
1232
  if (flag("history")) {
1244
1233
  const historyFloor = floorOf(readState(), "__historyFloor");
1245
1234
  // 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).
1246
1235
  let fromExports = null, fromFolder = null;
1247
- if (EXPORT_PATHS.length > 0) { try { fromExports = await exportEntries(); } catch (error) { console.log(`export: ${error.message}`); await exitFlushed(1); } }
1236
+ if (EXPORT_PATHS.length > 0) { try { fromExports = await exportEntries(); } catch (error) { console.log(`export: ${error.message}`); return await exitFlushed(1); } }
1248
1237
  // A COPIED SESSION FOLDER (0.10.10): its own history, reconstructed, the live folders' stretches skipped; never a rebuild.
1249
1238
  if (flag("from-folder")) {
1250
1239
  const given = value("from-folder");
1251
- if (!given || given.startsWith("--")) { console.log("folder: --from-folder needs the copied folder's path"); await exitFlushed(1); }
1252
- try { fromFolder = folderEntries(given); } catch (error) { console.log(`folder: ${error.message}`); await exitFlushed(1); }
1240
+ if (!given || given.startsWith("--")) { console.log("folder: --from-folder needs the copied folder's path"); return await exitFlushed(1); }
1241
+ try { fromFolder = folderEntries(given); } catch (error) { console.log(`folder: ${error.message}`); return await exitFlushed(1); }
1253
1242
  }
1254
- 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); }
1243
+ 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); }
1255
1244
  // 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
1256
1245
  // lines under no product go only with `--withdraw-unknown`, which the command sends after the person's yes, with an export alone.
1257
- 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); }
1246
+ 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); }
1258
1247
  const entries = fromExports ? fromExports.entries : fromFolder ? fromFolder.entries : historyEntries(historyFloor);
1259
- const hours = entries.reduce((sum, entry) => sum + (entry.seconds ?? 0), 0) / 3600;
1260
1248
  const months = [...new Set(entries.map((entry) => entry.at.slice(0, 7)))].sort();
1261
- // 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.
1262
- 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) }));
1263
- 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); }
1264
- 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" : ""}`);
1249
+ // 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,
1250
+ // 2026-10-07); nothing sent. NO HOURS (0.10.20): the hours are WorkTrust's to compute; the receipt after the send carries them.
1251
+ 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) }));
1252
+ 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); }
1253
+ 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" : ""}`);
1265
1254
  if (DRY) {
1266
1255
  // One example in full: the shape is the argument for trusting it, and a summary hides it.
1267
1256
  if (entries[0]) console.log(`\nthe oldest of them, in full:\n${JSON.stringify(entries[0], null, 1)}`);
1268
1257
  console.log(`\ndry run — nothing sent. Add --history${flag("rebuild") ? " --rebuild" : ""} without --dry-run to ${flag("rebuild") ? "rebuild" : "import"} them.`);
1269
- await exitFlushed(0);
1258
+ return await exitFlushed(0);
1270
1259
  }
1271
1260
  // A batch the door refused is a failure the caller must see, not a quiet zero.
1272
1261
  const accepted = await sendHistory(door, entries, true, flag("rebuild"), Boolean(fromFolder), fromExports ? { byDay: true, withdrawUnknown: flag("withdraw-unknown") } : {});
1273
1262
  // An export that arrived whole is remembered by its digest (never by a conversation), so the bare command offers it no more.
1274
1263
  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 });
1275
1264
  // 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.
1276
- 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
1277
- await exitFlushed(accepted === entries.length ? 0 : 1);
1265
+ 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
1266
+ return await exitFlushed(accepted === entries.length ? 0 : 1);
1278
1267
  }
1279
1268
 
1280
1269
  const input = hookInput();
@@ -1353,11 +1342,14 @@ if (!DRY && existsSync(COUNTER)) {
1353
1342
  const last = state.__counter?.at ? Date.parse(state.__counter.at) : 0;
1354
1343
  if (Date.now() - last > COUNTER_EVERY_MS) {
1355
1344
  try {
1356
- const child = spawn(process.execPath, [COUNTER, "--stage"], { detached: true, stdio: "ignore" });
1345
+ const child = spawn(process.execPath, [...NODE_FLAGS, COUNTER, "--stage"], { detached: true, stdio: "ignore" });
1357
1346
  child.unref();
1358
1347
  state.__counter = { at: new Date().toISOString() };
1359
1348
  writeState(state);
1360
1349
  } catch { /* the counter is a bonus; a hook that fails on it would cost the stretch it just logged */ }
1361
1350
  }
1362
1351
  }
1363
- await exitFlushed(0);
1352
+ return await exitFlushed(0);
1353
+
1354
+ }
1355
+ await main();