worktrust 0.10.18 → 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/README.md +20 -9
- package/count-behaviour.mjs +31 -32
- package/log-session.mjs +128 -178
- package/package.json +1 -1
- package/preserve-lines.mjs +5 -2
- package/preserve-summary.mjs +1 -1
- package/worktrust.mjs +39 -35
package/README.md
CHANGED
|
@@ -329,14 +329,17 @@ give `conversations.json`. Every 64 MB a line on stderr says how many megabytes
|
|
|
329
329
|
one question; Enter is No; `--dry-run` shows the plan and stops. On a coupled computer the bare `npx worktrust` looks
|
|
330
330
|
in your Downloads folder (its top level only) for such an export it has not sent, offers it the same way, once, and
|
|
331
331
|
remembers your answer by the file's digest, never by a conversation.
|
|
332
|
-
- **The export replaces.** On the days the export covers, its lines count and the earlier lines of that product
|
|
333
|
-
connector
|
|
334
|
-
correction row, so a day counts once; the command says how many. A connector line that arrives later
|
|
335
|
-
export covers is held. Lines
|
|
336
|
-
command says how many lie on those days and asks once, `Also withdraw N earlier lines
|
|
337
|
-
days?`; Enter is No, `--yes` keeps No, `--dry-run` sends nothing, and only a typed yes or
|
|
338
|
-
in advance withdraws exactly those lines on exactly those days, the same way, never deleting.
|
|
339
|
-
|
|
332
|
+
- **The export replaces.** On the days the export covers, its lines count and the earlier lines of that product your
|
|
333
|
+
connector of the same vendor reported (an AI signed in on the web, which selects what it reports) are withdrawn and
|
|
334
|
+
kept, each with a correction row, so a day counts once; the command says how many. A connector line that arrives later
|
|
335
|
+
for a day the export covers is held. Lines that connector reported earlier under no product may describe the same
|
|
336
|
+
conversations: the command says how many lie on those days and asks once, `Also withdraw N earlier lines your Claude
|
|
337
|
+
connector reported for these days?`; Enter is No, `--yes` keeps No, `--dry-run` sends nothing, and only a typed yes or
|
|
338
|
+
`--withdraw-unknown` said in advance withdraws exactly those lines on exactly those days, the same way, never deleting.
|
|
339
|
+
The count in the question is the door's own, and it is the count the yes withdraws. Never touched, whatever you answer
|
|
340
|
+
(0.10.19, held on the server): any line a computer of yours wrote (measured sessions, a rebuilt or archived history, an
|
|
341
|
+
earlier export send), a measured line, a connector of another vendor, another product, a private line, a day the export
|
|
342
|
+
does not cover.
|
|
340
343
|
|
|
341
344
|
## A copied session folder, and the local archive key
|
|
342
345
|
|
|
@@ -387,9 +390,17 @@ which would delete every password on the computer, and many people rightly keep
|
|
|
387
390
|
| **Reads** | Which AI apps are installed (the settings folders of Claude Code, Codex, Cursor, Gemini CLI, Antigravity, VS Code, Windsurf, Hermes Agent, Goose, OpenCode, OpenClaw), and the chats Cursor and Copilot keep (clocks, models and token counts only). Afterwards, the session hook reads Claude Code's, Codex's and Antigravity's session files, the session databases of Hermes, Goose, OpenCode and OpenClaw, and the chats Cursor and Copilot keep, on this computer to measure durations and token counts. |
|
|
388
391
|
| **Writes** | The key file (above). In each AI app's MCP settings (`~/.claude.json` through `claude mcp`, `~/.cursor/mcp.json`, `~/.codex/config.toml`, `~/.gemini/settings.json`, `~/.gemini/config/mcp_config.json` (Antigravity), VS Code's `mcp.json`, Windsurf's `mcp_config.json`, Hermes's and Goose's `config.yaml`, OpenCode's `opencode.json`, OpenClaw through `openclaw mcp set`) a WorkTrust entry that runs the local bridge, with no key in it; three hooks in `~/.claude/settings.json`; the bridge, the hook and the counter in `~/.worktrust/`. |
|
|
389
392
|
| **Sends, to pair** | This computer's system (macOS, Windows, Linux) and host name. WorkTrust also records the network address the request arrives from, as a security record kept 90 days and seen only by WorkTrust staff (to answer a theft or fraud report). |
|
|
390
|
-
| **Sends, afterwards** | Per measured stretch of work, and nothing else: its
|
|
393
|
+
| **Sends, afterwards** | Per measured stretch of work, and nothing else: its timeline and basis (`timeline`, `duration_basis`: since 0.10.20 the CLI sends no duration and no hours in layers of its own; WorkTrust computes them from the timeline), token counts (`tokens_in`, `tokens_out`, `tokens_cache_read`, `tokens_cache_write`, `token_basis`), the model's name (`model`), the kind of work and one layer keyword such as frontend or backend (`title`, `kind`, `layer`, `layers`), closed technology keys (`stack`) and separate display-only tool keys (`tools_seen`), how the turns are counted (`turn_basis`; the counts themselves WorkTrust reads from the timeline; the subagents' seconds wait for a timeline per run), when it began and ended and your computer's offset from UTC (`started_at`, `at`, `utc_offset`), what the CLI derived from the stretch as kinds and counts (`evidence`: checks run and failed, delivery steps and whether a check passed first, recoveries, delegation, context, routing, steering, refusals, planning, files and test files changed, the complexity class; with the WorkTrust mod on, its `live` counts from inside Claude Code: permission answers, effort levels, context and plan-limit peaks, subagents and setup; never a word, a command or a path; since 0.8.3, `live` since 0.10.15), a hash of the session and the day (`stretch_ref`), `steered_from` when it ran over SSH, the stretch's clock as step kinds and whole seconds so WorkTrust computes the figures itself (`timeline`, since 0.10.20: never a word, a tool name or a path), the CLI's version and a digest of its own files as signals (`cli_version`, `cli_digest`), and, so the work can be matched to GitHub, the repository as its remote's owner/name (`repo`, only for a repository on GitHub, GitLab or Bitbucket, the hosts WorkTrust can couple; never one on your own or a client's server) and the hashes of the commits made in the stretch (`commits`, never their messages). |
|
|
391
394
|
| **Never sends** | Prompts, answers, code, file names or paths, commit messages, branch names, or the name of your local folder (a repository is named only as its remote's owner/name, above). The door has no field for them and refuses a submission that carries them. |
|
|
392
395
|
|
|
396
|
+
**The clock is WorkTrust's, not this computer's (0.10.20).** A measured stretch travels as its timeline: one step per
|
|
397
|
+
transcript line, as a kind (your turn, the model's answer, a tool call, a tool's result, a question that waited for you, an
|
|
398
|
+
interruption) and the whole seconds since the previous step. Nothing of a message is in it: no word, no tool name, no path.
|
|
399
|
+
This CLI computes no duration and no hours of its own and carries no rule for doing so; WorkTrust computes the seconds, the
|
|
400
|
+
hours in layers and the turns from the timeline when it arrives, and the figures the terminal shows after a send are
|
|
401
|
+
WorkTrust's receipt. The line also names the CLI's version and a digest of its own files, as signals of which code ran,
|
|
402
|
+
never as proof.
|
|
403
|
+
|
|
393
404
|
## Why you can check it
|
|
394
405
|
|
|
395
406
|
- **No dependencies and no install scripts.** Plain files, readable
|
package/count-behaviour.mjs
CHANGED
|
@@ -1,24 +1,20 @@
|
|
|
1
1
|
/**
|
|
2
2
|
* THE LOCAL COUNTER — rubric v0.1 (`counter@0.1.0`).
|
|
3
|
-
*
|
|
4
3
|
* Reads this machine's own Claude Code transcripts, its Codex rollouts (2026-09-27), its Antigravity conversations (2026-10-04), its VS Code
|
|
5
4
|
* Copilot chat sessions (2026-09-08) and, when given, a claude.ai export (~/.claude/projects/**/*.jsonl — transcripts
|
|
6
5
|
* ONLY, never project files), classifies each of the person's OWN messages with the
|
|
7
6
|
* deterministic rules below, and reports COUNTS per month through the WorkTrust MCP door's
|
|
8
7
|
* `log_signals`. The same logs under the same rubric give the same numbers: every count is
|
|
9
8
|
* re-derivable, and a better rubric is a new version that writes beside this one.
|
|
10
|
-
*
|
|
11
9
|
* WHAT CANNOT LEAVE: the door's schema takes vocabulary keys and integers; it has no text
|
|
12
10
|
* field and refuses unknown keys by name. This script builds exactly that payload and nothing
|
|
13
11
|
* else — a password or a .env line has no channel to travel through. Run with --dry-run to see
|
|
14
12
|
* every number before anything is sent.
|
|
15
|
-
*
|
|
16
13
|
* node count-behaviour.mjs --dry-run
|
|
17
14
|
* node count-behaviour.mjs --url https://app.worktrust.io/api/mcp --token wt_...
|
|
18
15
|
* node count-behaviour.mjs --dry-run --exclude client-x --exclude secret
|
|
19
16
|
* node count-behaviour.mjs --dry-run --claude-export ~/Downloads/claude-export (a claude.ai data export beside the transcripts)
|
|
20
17
|
* node count-behaviour.mjs --dry-run --chatgpt-export ~/Downloads/chatgpt-export (a ChatGPT data export, the same way)
|
|
21
|
-
*
|
|
22
18
|
* CONFIDENTIAL PROJECTS stay out BEFORE anything is counted: `--exclude <text>` (repeatable)
|
|
23
19
|
* skips every project directory whose name contains that text, and `.worktrust-counter.json`
|
|
24
20
|
* in your home directory does the same permanently: { "exclude": ["client-x"] }. An excluded
|
|
@@ -55,7 +51,6 @@ export const encode = value => JSON.stringify(value, (_, v) => v instanceof Map
|
|
|
55
51
|
export const decode = value => JSON.parse(value, (_, v) => v?.$map ? new Map(v.$map) : v?.$set ? new Set(v.$set) : v);
|
|
56
52
|
export function checkpointStore(path, signature, manifest) {
|
|
57
53
|
mkdirSync(dirname(path), {recursive:true,mode:0o700});
|
|
58
|
-
// A process lock prevents two local runs from replacing each other's checkpoint.
|
|
59
54
|
const lock=path+'.lock';
|
|
60
55
|
try { const fd=openSync(lock,'wx',0o600);writeFileSync(fd,String(process.pid));closeSync(fd); }
|
|
61
56
|
catch(error) {
|
|
@@ -409,7 +404,25 @@ function gitCommitsOf(cwd, sinceIso) {
|
|
|
409
404
|
return commits;
|
|
410
405
|
}
|
|
411
406
|
|
|
407
|
+
export const isoWeek = (day) => {
|
|
408
|
+
const date = new Date(`${day}T00:00:00Z`);
|
|
409
|
+
const thursday = new Date(date); thursday.setUTCDate(date.getUTCDate() + 3 - ((date.getUTCDay() + 6) % 7));
|
|
410
|
+
const firstThursday = new Date(Date.UTC(thursday.getUTCFullYear(), 0, 4));
|
|
411
|
+
const week = 1 + Math.round(((thursday - firstThursday) / 86400000 - 3 + ((firstThursday.getUTCDay() + 6) % 7)) / 7);
|
|
412
|
+
return `${thursday.getUTCFullYear()}-W${String(week).padStart(2, "0")}`;
|
|
413
|
+
};
|
|
414
|
+
export function overlappingSessions(spans) {
|
|
415
|
+
const ordered=spans.map((span,index)=>({...span,index})).filter(s=>s.end>s.start).sort((a,b)=>a.start-b.start);
|
|
416
|
+
const found=new Set();let maximumEnd=-Infinity;
|
|
417
|
+
for(let i=0;i<ordered.length;i++){
|
|
418
|
+
const a=ordered[i];
|
|
419
|
+
if(maximumEnd>a.start || (ordered[i+1] && ordered[i+1].start<a.end))found.add(a.index);
|
|
420
|
+
maximumEnd=Math.max(maximumEnd,a.end);
|
|
421
|
+
}
|
|
422
|
+
return found;
|
|
423
|
+
}
|
|
412
424
|
|
|
425
|
+
async function main() {
|
|
413
426
|
const args = process.argv.slice(2);
|
|
414
427
|
const flag = (name) => args.includes(`--${name}`);
|
|
415
428
|
const value = (name) => { const i = args.indexOf(`--${name}`); return i >= 0 ? args[i + 1] : undefined; };
|
|
@@ -473,7 +486,7 @@ if (flag("classify")) {
|
|
|
473
486
|
const form = classifyOpening(row.text);
|
|
474
487
|
console.log(JSON.stringify({ form, kind: openingActKind(row.text, form), second: row.second === undefined ? null : classifySecondTurn(row.second), pasted: Math.round(pastedShare(row.text ?? "") * 100) / 100, restated: row.skill === undefined ? null : restatedSentences(row.text, row.skill), gitSide: row.commits === undefined ? null : gitSideCounts(row.commits), testRun: row.command === undefined ? null : { test: isTestCommand(row.command), outcome: row.result === undefined ? null : testOutcomeOf(row.result, row.isError) } }));
|
|
475
488
|
}
|
|
476
|
-
process.
|
|
489
|
+
return (process.exitCode = 0);
|
|
477
490
|
}
|
|
478
491
|
{
|
|
479
492
|
const i = args.indexOf("--agreement");
|
|
@@ -485,7 +498,7 @@ if (flag("classify")) {
|
|
|
485
498
|
const perLanguage = Object.fromEntries([...byLang.entries()].map(([lang, pairs]) => [lang, { n: pairs.length, kappa: cohenKappa(pairs) }]));
|
|
486
499
|
const passes = rows.length >= 100 && unclassified !== null && unclassified <= UNCLASSIFIED_CEILING && Object.values(perLanguage).every((entry) => entry.kappa !== null && entry.kappa >= KAPPA_FLOOR);
|
|
487
500
|
console.log(JSON.stringify({ n: rows.length, unclassified, perLanguage, floors: { kappa: KAPPA_FLOOR, unclassified: UNCLASSIFIED_CEILING, items: 100 }, counterGrade: passes }));
|
|
488
|
-
process.
|
|
501
|
+
return (process.exitCode = passes ? 0 : 1);
|
|
489
502
|
}
|
|
490
503
|
}
|
|
491
504
|
/**
|
|
@@ -788,13 +801,6 @@ const byMonthContext = new Map(); // month → Map("signal|context" → count)
|
|
|
788
801
|
* week never straddles two stored months: "2026-09|2026-W36". A count without a day (a
|
|
789
802
|
* month-level aggregate) lands in the month's "U" bucket.
|
|
790
803
|
*/
|
|
791
|
-
export const isoWeek = (day) => {
|
|
792
|
-
const date = new Date(`${day}T00:00:00Z`);
|
|
793
|
-
const thursday = new Date(date); thursday.setUTCDate(date.getUTCDate() + 3 - ((date.getUTCDay() + 6) % 7));
|
|
794
|
-
const firstThursday = new Date(Date.UTC(thursday.getUTCFullYear(), 0, 4));
|
|
795
|
-
const week = 1 + Math.round(((thursday - firstThursday) / 86400000 - 3 + ((firstThursday.getUTCDay() + 6) % 7)) / 7);
|
|
796
|
-
return `${thursday.getUTCFullYear()}-W${String(week).padStart(2, "0")}`;
|
|
797
|
-
};
|
|
798
804
|
const byWeek = new Map(); // "month|week" → Map(signal → count)
|
|
799
805
|
/**
|
|
800
806
|
* THE WORK STRETCH (0.7.0, the owner's capability framework v4 §13: "work_stretch_id, the stable unit joining AI
|
|
@@ -1175,7 +1181,7 @@ for await (const session of sessions()) {
|
|
|
1175
1181
|
checkpoint?.write(sessionIndex,{maps:checkpointMaps,sets:checkpointSets,sessionSpans,messages,files,currentContext,duplicateLines},checkpointDependencies);
|
|
1176
1182
|
if(++processed>=maxSessions && sessionIndex<manifest.length){
|
|
1177
1183
|
console.log(`Counter paused at ${sessionIndex}/${manifest.length} sessions; rerun the same command. Nothing sent.`);
|
|
1178
|
-
checkpoint?.close();process.
|
|
1184
|
+
checkpoint?.close();return (process.exitCode = 0);
|
|
1179
1185
|
}
|
|
1180
1186
|
}
|
|
1181
1187
|
currentUnit = null; currentDay = null; currentStretchBase = null; // month-level aggregates carry no unit, no day and no stretch
|
|
@@ -1198,16 +1204,6 @@ for (const [context, cwd] of contextCwds) {
|
|
|
1198
1204
|
}
|
|
1199
1205
|
currentUnit = null; currentDay = null; currentContext = null;
|
|
1200
1206
|
// The same strict overlap test in O(n log n), rather than comparing every pair.
|
|
1201
|
-
export function overlappingSessions(spans) {
|
|
1202
|
-
const ordered=spans.map((span,index)=>({...span,index})).filter(s=>s.end>s.start).sort((a,b)=>a.start-b.start);
|
|
1203
|
-
const found=new Set();let maximumEnd=-Infinity;
|
|
1204
|
-
for(let i=0;i<ordered.length;i++){
|
|
1205
|
-
const a=ordered[i];
|
|
1206
|
-
if(maximumEnd>a.start || (ordered[i+1] && ordered[i+1].start<a.end))found.add(a.index);
|
|
1207
|
-
maximumEnd=Math.max(maximumEnd,a.end);
|
|
1208
|
-
}
|
|
1209
|
-
return found;
|
|
1210
|
-
}
|
|
1211
1207
|
const overlapping=overlappingSessions(sessionSpans);
|
|
1212
1208
|
// Parallelism: a session that overlaps any other counted session, once per session.
|
|
1213
1209
|
for (let i = 0; i < sessionSpans.length; i += 1) {
|
|
@@ -1221,7 +1217,7 @@ for (let i = 0; i < sessionSpans.length; i += 1) {
|
|
|
1221
1217
|
if (flag("stretch-signals")) {
|
|
1222
1218
|
const rows = [...byStretch.entries()].sort(([, a], [, b]) => a.day.localeCompare(b.day)).map(([stretch_ref, entry]) => JSON.stringify({ stretch_ref, day: entry.day, analyzer_version: ANALYZER_VERSION, signals: Object.fromEntries(Object.entries(entry.signals).sort().map(([signal, count]) => [signal, Math.min(COUNT_CEILING, count)])) }));
|
|
1223
1219
|
await new Promise((resolve) => process.stdout.write(`${[...rows, JSON.stringify({ stretch_signals_end: rows.length })].join("\n")}\n`, resolve));
|
|
1224
|
-
process.
|
|
1220
|
+
return (process.exitCode = 0);
|
|
1225
1221
|
}
|
|
1226
1222
|
|
|
1227
1223
|
const months = [...byMonth.keys()].sort();
|
|
@@ -1281,10 +1277,10 @@ console.log("");
|
|
|
1281
1277
|
if (LABEL_OUT) { writeFileSync(LABEL_OUT, labelRows.map((row) => JSON.stringify(row)).join("\n") + "\n"); console.log(` openings written for labelling: ${labelRows.length} → ${LABEL_OUT} (local file; add "label" per line, then --agreement ${LABEL_OUT})`); }
|
|
1282
1278
|
if (DRY) {
|
|
1283
1279
|
console.log(`dry run — nothing sent. Next: run again with --stage — the reading then WAITS in the app (${appOrigin}/behaviour) until the person clicks Import; nothing is counted before that click. (Alternative without the app visit: approval code ${APPROVAL} at ${appOrigin}/behaviour?approve=${APPROVAL}, then --send.)${URL_ && TOKEN ? ` Coupling found (${new URL(URL_).host}).` : " Pass --url and --token (or couple this client) first."}`);
|
|
1284
|
-
process.
|
|
1280
|
+
return (process.exitCode = 0);
|
|
1285
1281
|
}
|
|
1286
1282
|
if (STAGE) {
|
|
1287
|
-
if (!URL_ || !TOKEN) { console.error("no coupling found: pass --url and --token, or set WORKTRUST_MCP_URL / WORKTRUST_MCP_TOKEN"); process.
|
|
1283
|
+
if (!URL_ || !TOKEN) { console.error("no coupling found: pass --url and --token, or set WORKTRUST_MCP_URL / WORKTRUST_MCP_TOKEN"); return (process.exitCode = 1); }
|
|
1288
1284
|
const readings = months.map((month) => ({ period: month, stretches: sessionsByMonth.get(month) ?? 0, signals: [...byMonth.get(month).entries()].map(([signal, count]) => ({ signal, count: clampCount(signal, count, month) })), contexts: cellsOf(month), context_names: contextNamesOf(), units: [...(unitsByMonth.get(month)?.values() ?? [])].map(({ unit, signal, induced, day, context }) => ({ unit, signal, induced, ...(day ? { day } : {}), ...(context ? { context } : {}) })) }));
|
|
1289
1285
|
if (!flag("legacy-stage")) {
|
|
1290
1286
|
// WHAT THIS MACHINE ALREADY DELIVERED, per month and ISO week, for this coupling and rubric
|
|
@@ -1326,7 +1322,7 @@ if (STAGE) {
|
|
|
1326
1322
|
const unchanged=new Set(readings.map(r=>r.period)).size-plan.length;
|
|
1327
1323
|
console.log(` ${plan.length} month(s) with new or changed weeks${unchanged>0?` · ${unchanged} unchanged, not sent`:""}`);
|
|
1328
1324
|
for(const {reading,changes} of plan)console.log(` ${reading.period}: ${changes.length?changes.map(c=>`${c.week} ${c.previous===null?"new":c.observations===0?"removed":`${c.previous}→${c.observations}`}`).join(" · "):"per-project cells changed"}`);
|
|
1329
|
-
if(plan.length===0){console.log("Nothing new since the last delivery from this machine. Nothing sent.");process.
|
|
1325
|
+
if(plan.length===0){console.log("Nothing new since the last delivery from this machine. Nothing sent.");return (process.exitCode = 0);}
|
|
1330
1326
|
// Persist the outbound revision BEFORE sending. A failed HTTP response replays safely.
|
|
1331
1327
|
let delivery=null;try{delivery=JSON.parse(readFileSync(deliveryPath,"utf8"));}catch{}
|
|
1332
1328
|
if(delivery?.scope!==scope)delivery=null;
|
|
@@ -1356,7 +1352,7 @@ if (STAGE) {
|
|
|
1356
1352
|
}
|
|
1357
1353
|
}
|
|
1358
1354
|
console.log("Complete months await the owner's Import in /behaviour. Imports replace this coupling's month, including corrections and removals.");
|
|
1359
|
-
process.
|
|
1355
|
+
return (process.exitCode = 0);
|
|
1360
1356
|
}
|
|
1361
1357
|
// UNDER THE HOST'S CEILING. A serverless request takes about 4.5 MB; a year of unit references
|
|
1362
1358
|
// does not fit in one. Months are staged in chunks that stay under the ceiling, each with its own
|
|
@@ -1378,9 +1374,9 @@ if (STAGE) {
|
|
|
1378
1374
|
console.log(` staged ${chunk[0].period}${chunk.length > 1 ? `–${chunk[chunk.length - 1].period}` : ""} → ${text}`);
|
|
1379
1375
|
}
|
|
1380
1376
|
console.log(` the person imports ${chunks.length === 1 ? "it" : `each of the ${chunks.length} readings`} at ${appOrigin}/behaviour — one click each; nothing is on the mirror before it.`);
|
|
1381
|
-
process.
|
|
1377
|
+
return (process.exitCode = 0);
|
|
1382
1378
|
}
|
|
1383
|
-
if (!URL_ || !TOKEN) { console.error("no coupling found: pass --url and --token, or set WORKTRUST_MCP_URL / WORKTRUST_MCP_TOKEN"); process.
|
|
1379
|
+
if (!URL_ || !TOKEN) { console.error("no coupling found: pass --url and --token, or set WORKTRUST_MCP_URL / WORKTRUST_MCP_TOKEN"); return (process.exitCode = 1); }
|
|
1384
1380
|
console.log(`sending to ${new URL(URL_).host} …`);
|
|
1385
1381
|
for (const month of months) {
|
|
1386
1382
|
const bucket = byMonth.get(month);
|
|
@@ -1392,3 +1388,6 @@ for (const month of months) {
|
|
|
1392
1388
|
const text = answer?.result?.content?.[0]?.text ?? answer?.error?.message ?? `http ${response.status}`;
|
|
1393
1389
|
console.log(` sent ${month} → ${text}`);
|
|
1394
1390
|
}
|
|
1391
|
+
|
|
1392
|
+
}
|
|
1393
|
+
await main();
|
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
|
|
55
|
-
*
|
|
56
|
-
*
|
|
57
|
-
*
|
|
58
|
-
*
|
|
59
|
-
*
|
|
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
|
-
|
|
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
|
-
//
|
|
75
|
-
const exitFlushed = (code) => new Promise((resolve) => process.stdout.write("", resolve)).then(() => process.
|
|
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
|
|
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
|
|
427
|
-
* before it, carrying no tokens, no model and no turn, so the gap that crosses midnight
|
|
428
|
-
* ends,
|
|
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 (
|
|
437
|
-
if (!byDay.has(day)) byDay.set(day, prev && message.at - prev.at <=
|
|
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.
|
|
479
|
-
*
|
|
480
|
-
*
|
|
481
|
-
*
|
|
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
|
|
488
|
+
// A run is counted on the day it started.
|
|
509
489
|
const day = new Date(stamps[0]).toISOString().slice(0, 10);
|
|
510
|
-
|
|
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.
|
|
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,
|
|
527
|
+
/** One day's messages → the stretch: its timeline, its tokens, its model. The server measures it. */
|
|
550
528
|
function measure(cwd, messages) {
|
|
551
|
-
//
|
|
552
|
-
//
|
|
553
|
-
|
|
554
|
-
|
|
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
|
-
|
|
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,
|
|
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
|
-
*
|
|
584
|
-
*
|
|
585
|
-
*
|
|
586
|
-
*
|
|
587
|
-
*
|
|
588
|
-
*
|
|
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
|
|
591
|
-
|
|
592
|
-
for (let i =
|
|
593
|
-
const
|
|
594
|
-
const
|
|
595
|
-
|
|
596
|
-
|
|
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
|
|
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:
|
|
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
|
-
//
|
|
680
|
-
//
|
|
681
|
-
...(stretch.
|
|
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,
|
|
685
|
-
// row that does not say reads as the old count, which included them.
|
|
686
|
-
...(stretch.
|
|
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
|
-
//
|
|
696
|
-
...(
|
|
697
|
-
|
|
698
|
-
// WHEN
|
|
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)
|
|
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.
|
|
867
|
-
* person's
|
|
868
|
-
* device key witnessed it. No tokens (the export carries none and none are estimated), no
|
|
869
|
-
*
|
|
870
|
-
*
|
|
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.
|
|
877
|
-
*
|
|
878
|
-
*
|
|
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.
|
|
888
|
-
if (!current) { current = { messages: [],
|
|
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;
|
|
@@ -898,7 +848,7 @@ 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 = {}, report = { days: new Set()
|
|
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)
|
|
902
852
|
for await (const { id, lines } of exportSessions(given, { excluded, report: read })) {
|
|
903
853
|
const messages = [];
|
|
904
854
|
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 +857,15 @@ async function exportEntries() {
|
|
|
907
857
|
if (ofDay.length === 0) continue;
|
|
908
858
|
// ONE STRETCH PER RUN OF ACTIVITY (0.10.17): the day's messages cut where the hook calls a stretch finished; one run
|
|
909
859
|
// is the day as before, under the name it always had; several name the one-envelope line they replace.
|
|
910
|
-
const runs = runsOf(ofDay),
|
|
911
|
-
runs.forEach(({ messages: run,
|
|
860
|
+
const runs = runsOf(ofDay), old = exportRef(read.vendor, id, day);
|
|
861
|
+
runs.forEach(({ messages: run, tail }, index) => {
|
|
912
862
|
const stretch = measure(null, run), ref = runs.length === 1 ? old : exportRunRef(read.vendor, id, day, index);
|
|
913
|
-
// The
|
|
914
|
-
//
|
|
915
|
-
const
|
|
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;
|
|
916
866
|
const entry = {
|
|
917
867
|
title: EXPORT_TITLES[read.vendor], kind: "researched",
|
|
918
|
-
...(
|
|
919
|
-
...(stretch.exchanges > 0 ? { exchanges: stretch.exchanges, turn_basis: "humanOnly" } : {}),
|
|
868
|
+
...(timeline ? { timeline, duration_basis: "reconstructed", turn_basis: "humanOnly" } : {}),
|
|
920
869
|
...(stretch.model ? { model: stretch.model } : {}),
|
|
921
870
|
stretch_ref: ref, source_event_id: `exp_${ref}`,
|
|
922
871
|
...(runs.length > 1 ? { supersedes_ref: old } : {}),
|
|
@@ -924,13 +873,13 @@ async function exportEntries() {
|
|
|
924
873
|
};
|
|
925
874
|
entrySource.set(entry, read.vendor);
|
|
926
875
|
entryFile.set(entry, { file: `${read.vendor}:${id}`, from: stretch.from, folder: null });
|
|
927
|
-
|
|
876
|
+
entries.push(entry);
|
|
928
877
|
});
|
|
929
878
|
report.days.add(day);
|
|
930
879
|
}
|
|
931
880
|
}
|
|
932
881
|
const days = [...report.days].sort();
|
|
933
|
-
reports.push({ path: read.path, vendor: read.vendor, digest: read.digest, conversations: read.conversations, days: days.length,
|
|
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
|
|
934
883
|
}
|
|
935
884
|
const seen = new Set();
|
|
936
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 };
|
|
@@ -942,8 +891,8 @@ async function exportEntries() {
|
|
|
942
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
|
|
943
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
|
|
944
893
|
* 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
|
|
946
|
-
*
|
|
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.
|
|
947
896
|
*/
|
|
948
897
|
function folderEntries(given) {
|
|
949
898
|
const dir = given.replace(/^~(?=\/|$)/, homedir());
|
|
@@ -964,7 +913,7 @@ function folderEntries(given) {
|
|
|
964
913
|
walk(here, 0);
|
|
965
914
|
if (files.length === 0) throw Error(`no session files under ${given} (Claude Code transcripts, Codex rollouts or Antigravity transcripts, as .jsonl)`);
|
|
966
915
|
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()
|
|
916
|
+
const entries = [], report = { stretches: 0, skipped: 0, days: new Set() };
|
|
968
917
|
for (const file of files) {
|
|
969
918
|
const client = CODEX_ROLLOUT.test(file) ? "codex" : ANTIGRAVITY_TRANSCRIPT.test(file) ? "antigravity" : "claude";
|
|
970
919
|
const lines = parsedLines(file);
|
|
@@ -984,17 +933,15 @@ function folderEntries(given) {
|
|
|
984
933
|
report.stretches += 1;
|
|
985
934
|
if (present.has(ref) || seen.has(ref)) { report.skipped += 1; continue; }
|
|
986
935
|
seen.add(ref);
|
|
987
|
-
const
|
|
988
|
-
const {
|
|
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" } : {}) };
|
|
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" } : {}) };
|
|
991
938
|
if (client !== "claude") entrySource.set(entry, client);
|
|
992
939
|
entryFile.set(entry, { file, from: firstOf(messages), folder: null });
|
|
993
|
-
report.days.add(day);
|
|
940
|
+
report.days.add(day); entries.push(entry);
|
|
994
941
|
}
|
|
995
942
|
}
|
|
996
943
|
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,
|
|
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 } };
|
|
998
945
|
}
|
|
999
946
|
|
|
1000
947
|
/** Every transcript this machine holds, excluded projects skipped before a file is opened. */
|
|
@@ -1076,7 +1023,7 @@ if (flag("uninstall")) {
|
|
|
1076
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 */ } }
|
|
1077
1024
|
console.log(`${removed ? "removed" : "nothing wired"}: ${file}${flag("purge") ? "\n purged ~/.worktrust" : ""}`);
|
|
1078
1025
|
console.log("the coupling itself still exists: end it in the app (Sources → the computer's row → end this coupling)");
|
|
1079
|
-
await exitFlushed(0);
|
|
1026
|
+
return await exitFlushed(0);
|
|
1080
1027
|
}
|
|
1081
1028
|
|
|
1082
1029
|
if (flag("install")) {
|
|
@@ -1155,7 +1102,7 @@ if (flag("install")) {
|
|
|
1155
1102
|
} catch (error) { console.log(`counter: could not fetch it (${error.message}) — the hook works without it; fetch /counter/count-behaviour.mjs later`); }
|
|
1156
1103
|
}
|
|
1157
1104
|
}
|
|
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); }
|
|
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); }
|
|
1159
1106
|
for (const event of added) settings.hooks[event].push({ hooks: [{ type: "command", command }] });
|
|
1160
1107
|
mkdirSync(dirname(file), { recursive: true });
|
|
1161
1108
|
writeFileSync(file, JSON.stringify(settings, null, 2));
|
|
@@ -1166,7 +1113,7 @@ if (flag("install")) {
|
|
|
1166
1113
|
// never rewrites: `npx worktrust` asks and writes it (WORKTRUST_CODEX_OFFER, so no hint twice), and
|
|
1167
1114
|
// without it Codex rollouts are still swept whenever the Claude Code hook runs.
|
|
1168
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)`);
|
|
1169
|
-
await exitFlushed(0);
|
|
1116
|
+
return await exitFlushed(0);
|
|
1170
1117
|
}
|
|
1171
1118
|
|
|
1172
1119
|
const door = coupling();
|
|
@@ -1189,7 +1136,7 @@ if (flag("evidence-summary")) {
|
|
|
1189
1136
|
const complexity = {};
|
|
1190
1137
|
for (const entry of rows) { const tier = DERIVED.get(entry)?.complexity?.class; if (tier) complexity[tier] = (complexity[tier] ?? 0) + 1; }
|
|
1191
1138
|
const summary = {
|
|
1192
|
-
stretches: rows.length,
|
|
1139
|
+
stretches: rows.length, // the hours are WorkTrust's (0.10.20): the app shows them
|
|
1193
1140
|
delivered: sum((d) => (d.delivery ? 1 : 0)), verified_first: sum((d) => (d.delivery?.verified_first ? 1 : 0)),
|
|
1194
1141
|
failures: sum((d) => d.recovery?.failures), recovered: sum((d) => d.recovery?.recovered), blind_retries: sum((d) => d.recovery?.blind_retries),
|
|
1195
1142
|
steers: sum((d) => d.steering?.moments), effective_steers: sum((d) => d.steering?.effective),
|
|
@@ -1197,14 +1144,14 @@ if (flag("evidence-summary")) {
|
|
|
1197
1144
|
planned: sum((d) => (d.planning ? 1 : 0)), files: sum((d) => d.changes?.files), test_files: sum((d) => d.changes?.test_files), complexity,
|
|
1198
1145
|
};
|
|
1199
1146
|
process.stdout.write(`${JSON.stringify(summary)}\n`);
|
|
1200
|
-
await exitFlushed(0);
|
|
1147
|
+
return await exitFlushed(0);
|
|
1201
1148
|
}
|
|
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
|
|
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
|
|
1203
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
|
|
1204
1151
|
// 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) {
|
|
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.
|
|
1208
1155
|
|
|
1209
1156
|
/**
|
|
1210
1157
|
* HISTORY FROM THE ARCHIVE (0.8.0; framework §22). When an AI app has deleted its sessions, the stretches this computer
|
|
@@ -1222,59 +1169,59 @@ if (flag("history") && flag("from-archive")) {
|
|
|
1222
1169
|
// archive must still verify whole, and only stretches no longer in any AI app here travel.
|
|
1223
1170
|
let ownKey = null;
|
|
1224
1171
|
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); }
|
|
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); }
|
|
1227
1174
|
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); }
|
|
1175
|
+
if (!archiveEntries) { say("preserve-lines.mjs is not beside this file. Nothing was sent."); return await exitFlushed(1); }
|
|
1229
1176
|
const present = new Set(historyEntries(null, true).map((entry) => entry.stretch_ref));
|
|
1230
1177
|
const all = archiveEntries(dir, ownKey), gone = all.filter(({ entry }) => !present.has(entry.stretch_ref));
|
|
1231
1178
|
const entries = gone.map(({ entry, client, signed }) => {
|
|
1232
1179
|
if (client !== "claude") entrySource.set(entry, client);
|
|
1233
|
-
if (!signed && typeof entry.seconds === "number"
|
|
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
|
|
1234
1181
|
return entry;
|
|
1235
1182
|
});
|
|
1236
1183
|
const signedCount = all.filter(({ signed }) => signed).length;
|
|
1237
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`);
|
|
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);
|
|
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);
|
|
1241
1188
|
}
|
|
1242
1189
|
|
|
1243
1190
|
if (flag("history")) {
|
|
1244
1191
|
const historyFloor = floorOf(readState(), "__historyFloor");
|
|
1245
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).
|
|
1246
1193
|
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); } }
|
|
1194
|
+
if (EXPORT_PATHS.length > 0) { try { fromExports = await exportEntries(); } catch (error) { console.log(`export: ${error.message}`); return await exitFlushed(1); } }
|
|
1248
1195
|
// A COPIED SESSION FOLDER (0.10.10): its own history, reconstructed, the live folders' stretches skipped; never a rebuild.
|
|
1249
1196
|
if (flag("from-folder")) {
|
|
1250
1197
|
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); }
|
|
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); }
|
|
1253
1200
|
}
|
|
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); }
|
|
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); }
|
|
1255
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
|
|
1256
1203
|
// 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); }
|
|
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); }
|
|
1258
1205
|
const entries = fromExports ? fromExports.entries : fromFolder ? fromFolder.entries : historyEntries(historyFloor);
|
|
1259
|
-
const hours = entries.reduce((sum, entry) => sum + (entry.seconds ?? 0), 0) / 3600;
|
|
1260
1206
|
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,
|
|
1262
|
-
|
|
1263
|
-
|
|
1264
|
-
console.log(
|
|
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" : ""}`);
|
|
1265
1212
|
if (DRY) {
|
|
1266
1213
|
// One example in full: the shape is the argument for trusting it, and a summary hides it.
|
|
1267
1214
|
if (entries[0]) console.log(`\nthe oldest of them, in full:\n${JSON.stringify(entries[0], null, 1)}`);
|
|
1268
1215
|
console.log(`\ndry run — nothing sent. Add --history${flag("rebuild") ? " --rebuild" : ""} without --dry-run to ${flag("rebuild") ? "rebuild" : "import"} them.`);
|
|
1269
|
-
await exitFlushed(0);
|
|
1216
|
+
return await exitFlushed(0);
|
|
1270
1217
|
}
|
|
1271
1218
|
// A batch the door refused is a failure the caller must see, not a quiet zero.
|
|
1272
1219
|
const accepted = await sendHistory(door, entries, true, flag("rebuild"), Boolean(fromFolder), fromExports ? { byDay: true, withdrawUnknown: flag("withdraw-unknown") } : {});
|
|
1273
1220
|
// An export that arrived whole is remembered by its digest (never by a conversation), so the bare command offers it no more.
|
|
1274
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 });
|
|
1275
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.
|
|
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);
|
|
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);
|
|
1278
1225
|
}
|
|
1279
1226
|
|
|
1280
1227
|
const input = hookInput();
|
|
@@ -1353,11 +1300,14 @@ if (!DRY && existsSync(COUNTER)) {
|
|
|
1353
1300
|
const last = state.__counter?.at ? Date.parse(state.__counter.at) : 0;
|
|
1354
1301
|
if (Date.now() - last > COUNTER_EVERY_MS) {
|
|
1355
1302
|
try {
|
|
1356
|
-
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" });
|
|
1357
1304
|
child.unref();
|
|
1358
1305
|
state.__counter = { at: new Date().toISOString() };
|
|
1359
1306
|
writeState(state);
|
|
1360
1307
|
} catch { /* the counter is a bonus; a hook that fails on it would cost the stretch it just logged */ }
|
|
1361
1308
|
}
|
|
1362
1309
|
}
|
|
1363
|
-
await exitFlushed(0);
|
|
1310
|
+
return await exitFlushed(0);
|
|
1311
|
+
|
|
1312
|
+
}
|
|
1313
|
+
await main();
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "worktrust",
|
|
3
|
-
"version": "0.10.
|
|
3
|
+
"version": "0.10.20",
|
|
4
4
|
"description": "Couple this computer to WorkTrust: approve a code in your browser, and every AI app here reports what you built. Metadata only, no dependencies.",
|
|
5
5
|
"type": "module",
|
|
6
6
|
"bin": {
|
package/preserve-lines.mjs
CHANGED
|
@@ -36,6 +36,8 @@ export function archiveLine(entry, behaviour = null, { ids = {}, collector, salt
|
|
|
36
36
|
if (typeof entry?.client !== "string" || !/^[a-z][a-z0-9-]{0,31}$/.test(entry.client) || !ISO.test(entry.started_at ?? "") || !ISO.test(entry.at ?? "") || !/^[A-Za-z0-9_-]{16,128}$/.test(entry.stretch_ref ?? "")) return null;
|
|
37
37
|
const line = { client: entry.client, day: entry.started_at.slice(0, 10), started_at: entry.started_at, ended_at: entry.at };
|
|
38
38
|
for (const key of COUNTS) if (typeof entry[key] === "number" && Number.isFinite(entry[key]) && entry[key] >= 0) line[key] = entry[key];
|
|
39
|
+
// THE TIMELINE (0.10.20): the stretch's clock as step kinds and gaps, the shape and nothing else; WorkTrust computes the figures from it when the archive is sent.
|
|
40
|
+
if (typeof entry.timeline === "string" && entry.timeline.length <= 200000 && /^(G?[HIURATWhiuratw][0-9]{1,6})+$/.test(entry.timeline)) line.timeline = entry.timeline;
|
|
39
41
|
if (typeof entry.model === "string" && /^[A-Za-z0-9][A-Za-z0-9._:/ -]{0,63}$/.test(entry.model)) line.model = entry.model;
|
|
40
42
|
for (const key of WORDS) if (typeof entry[key] === "string" && WORD.test(entry[key])) line[key] = entry[key];
|
|
41
43
|
if (Array.isArray(entry.layers) && entry.layers.length > 1 && entry.layers.every((word) => typeof word === "string" && WORD.test(word))) line.layers = entry.layers.slice(0, 8);
|
|
@@ -205,8 +207,9 @@ export function archiveEntries(dir, ownKey) {
|
|
|
205
207
|
const entry = {
|
|
206
208
|
title: line.layer ? `AI-assisted work · ${line.layer}` : "AI-assisted work",
|
|
207
209
|
...(line.kind ? { kind: line.kind } : {}), ...(line.layer ? { layer: line.layer } : {}), ...(line.layers ? { layers: line.layers } : {}),
|
|
208
|
-
|
|
209
|
-
...
|
|
210
|
+
// An older archive carries the figures it computed (sent as they are, marked client at the door); one since 0.10.20 carries the timeline, and the basis goes with either.
|
|
211
|
+
...(typeof line.seconds === "number" ? { seconds: line.seconds, duration_basis: line.duration_basis ?? "measured" } : typeof line.timeline === "string" ? { duration_basis: line.duration_basis ?? "measured" } : {}),
|
|
212
|
+
...Object.fromEntries(["timeline", "tokens_in", "tokens_out", "token_basis", "tokens_cache_read", "tokens_cache_write", "exchanges", "turn_basis", "model", "steered_from", "model_seconds", "tool_seconds", "human_seconds", "idle_seconds", "agent_runs", "agent_seconds", "agent_peak", "interrupts", "steers", "utc_offset"].filter((key) => line[key] !== undefined).map((key) => [key, line[key]])),
|
|
210
213
|
stretch_ref: line.stretch_ref, started_at: line.started_at, at: line.ended_at, from_archive: true,
|
|
211
214
|
};
|
|
212
215
|
out.push({ entry, client: line.client ?? "claude", signed });
|
package/preserve-summary.mjs
CHANGED
|
@@ -25,7 +25,7 @@ export function summaryLines(lines) {
|
|
|
25
25
|
}
|
|
26
26
|
const hours = (seconds) => (seconds / 3600).toFixed(1);
|
|
27
27
|
for (const [key, m] of [...months].sort()) {
|
|
28
|
-
out.push(` ${key} ${hours(m.seconds)} h measured`);
|
|
28
|
+
out.push(` ${key} ${m.seconds > 0 ? `${hours(m.seconds)} h measured` : "hours measured by WorkTrust on arrival"}`); // an archive since 0.10.20 carries timelines, not figures
|
|
29
29
|
for (const [model, tokens] of [...m.models].sort((a, b) => b[1] - a[1])) out.push(` ${model.padEnd(28)} ${tokens.toLocaleString("en")} tokens`);
|
|
30
30
|
if (m.input > 0) out.push(` cache share of input ${Math.round((m.cached / m.input) * 100)}%`);
|
|
31
31
|
if (m.delivered > 0) out.push(` verified before delivery ${m.verifiedFirst} of ${m.delivered} stretch${m.delivered === 1 ? "" : "es"} that delivered`);
|
package/worktrust.mjs
CHANGED
|
@@ -1,7 +1,6 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
2
|
/**
|
|
3
3
|
* WorkTrust on a computer, in one command — like `gh auth login` (2026-10-03).
|
|
4
|
-
*
|
|
5
4
|
* npx worktrust show the plan, ask, approve this computer in the app, couple (0.10.7: a person's
|
|
6
5
|
* command always runs the newest version, whatever npx had cached);
|
|
7
6
|
* on a computer already coupled: what is coupled here
|
|
@@ -30,27 +29,23 @@
|
|
|
30
29
|
* --archive [dir] a local metadata-only record, --verify [dir] checks it,
|
|
31
30
|
* --summary [dir] counts hours, tokens and parallel sessions from it);
|
|
32
31
|
* local only: no account, no key, no network (preserve.mjs)
|
|
33
|
-
*
|
|
34
32
|
* WHAT RUNS. From the npm package, everything that runs is in the package: this file,
|
|
35
33
|
* `setup-mcp.mjs` (gives every AI app here the WorkTrust door), `log-session.mjs` (the session hook)
|
|
36
34
|
* and `count-behaviour.mjs` (the local counter, pinned: never replaced from the network), with
|
|
37
35
|
* `transcript-readers.mjs` (how Codex and Antigravity logs are read, imported by the last two). Nothing
|
|
38
36
|
* is downloaded. Run as a single file from WorkTrust's site instead, it fetches those from that
|
|
39
37
|
* same site, and says so before it asks.
|
|
40
|
-
*
|
|
41
38
|
* HOW THE ACCOUNT IS DECIDED. By default this terminal listens on 127.0.0.1 for one answer and holds
|
|
42
39
|
* a PKCE secret. Your browser opens WorkTrust, you approve this computer there (signed in, second
|
|
43
40
|
* factor), and the browser is sent back to 127.0.0.1 with a one-time code that only this terminal,
|
|
44
41
|
* with its secret, can exchange for the key. Nothing is typed, and a link forwarded to someone else
|
|
45
42
|
* approves nothing they can collect. Without a browser (`--device`, or over SSH) the terminal shows
|
|
46
43
|
* a code that you type yourself at app.worktrust.io/connect/computer.
|
|
47
|
-
*
|
|
48
44
|
* WHERE THE KEY LIVES. In one file only you can read (~/.worktrust/key.json, mode 600, folder 700).
|
|
49
45
|
* No keychain is touched. The AI apps never hold it:
|
|
50
46
|
* each runs `worktrust.mjs mcp`, a small local bridge that reads the key and speaks to WorkTrust for
|
|
51
47
|
* them, and the session hook runs through `worktrust.mjs hook` the same way. `--direct` writes the
|
|
52
48
|
* key into each app's settings instead (for an app that cannot run a local command).
|
|
53
|
-
*
|
|
54
49
|
* THE KEY ONLY WORKS ON THIS COMPUTER. connect makes an Ed25519 key pair; the public half goes to
|
|
55
50
|
* WorkTrust, the private half stays in the key file. Every call the bridge, the hook and
|
|
56
51
|
* the counter make carries a fresh signature (`WorkTrust-Proof`), and WorkTrust refuses a call
|
|
@@ -83,7 +78,7 @@ const command = args.includes("--help") ? "help" : args.includes("--version") ?
|
|
|
83
78
|
const flag = (name) => { const at = args.indexOf(`--${name}`); return at >= 0 ? args[at + 1] : undefined; };
|
|
84
79
|
const has = (name) => args.includes(`--${name}`);
|
|
85
80
|
/** This CLI's version, said to the door so the app can tell which computer runs an old one (check-cli-package holds it equal to package.json). */
|
|
86
|
-
const CLI_VERSION = "0.10.
|
|
81
|
+
const CLI_VERSION = "0.10.20";
|
|
87
82
|
const ORIGIN = (flag("origin") ?? process.env.WORKTRUST_ORIGIN ?? "https://app.worktrust.io").replace(/\/$/, "");
|
|
88
83
|
const MCP = flag("url") ?? process.env.WORKTRUST_MCP_URL ?? `${ORIGIN}/api/mcp`;
|
|
89
84
|
const HOME_DIR = join(homedir(), ".worktrust");
|
|
@@ -97,7 +92,9 @@ const PLACEHOLDER = `wt_${"0".repeat(43)}`;
|
|
|
97
92
|
const say = (line = "") => process.stdout.write(`${line}\n`);
|
|
98
93
|
// A reader that closed the pipe (`worktrust status | head`) wants no more: stop quietly, never an EPIPE stack (0.6.16, audit L4).
|
|
99
94
|
process.stdout.on("error", (error) => { if (error?.code === "EPIPE") process.exit(0); throw error; });
|
|
100
|
-
|
|
95
|
+
class CliFailure extends Error {}
|
|
96
|
+
const fail = (line) => { process.stderr.write(`worktrust: ${line}\n`); throw new CliFailure(); };
|
|
97
|
+
const NODE_FLAGS = process.versions.node === "26.5.0" ? ["--no-concurrent-sparkplug"] : [];
|
|
101
98
|
const OS = { darwin: "macos", win32: "windows", linux: "linux" }[platform()] ?? "other";
|
|
102
99
|
const OS_NAME = { macos: "macOS", windows: "Windows", linux: "Linux", other: "this system" }[OS];
|
|
103
100
|
|
|
@@ -123,8 +120,6 @@ function computerIds() {
|
|
|
123
120
|
return { device_id: hash(`worktrust-machine|${machine.toLowerCase()}`), profile_id: hash(`worktrust-profile|${machine.toLowerCase()}|${homedir()}`) };
|
|
124
121
|
}
|
|
125
122
|
|
|
126
|
-
if (Number(process.versions.node.split(".")[0]) < 18) fail("needs Node 18 or later (fetch is built in from 18).");
|
|
127
|
-
|
|
128
123
|
async function post(path, body) {
|
|
129
124
|
const response = await fetch(`${ORIGIN}${path}`, { method: "POST", headers: { "content-type": "application/json" }, body: JSON.stringify(body) });
|
|
130
125
|
return { status: response.status, json: await response.json().catch(() => ({})) };
|
|
@@ -147,7 +142,7 @@ async function scripts() {
|
|
|
147
142
|
/** Run a script; its output is shown, or collected for the plan. The key travels in the environment only. */
|
|
148
143
|
function run(path, scriptArgs, token, collect = false, extraEnv = {}) {
|
|
149
144
|
return new Promise((resolve) => {
|
|
150
|
-
const child = spawn(process.execPath, [path, ...scriptArgs], { stdio: collect ? ["ignore", "pipe", "pipe"] : "inherit", env: { ...process.env, WORKTRUST_MCP_URL: MCP, WORKTRUST_MCP_TOKEN: token, WORKTRUST_NODE: NODE, ...extraEnv } });
|
|
145
|
+
const child = spawn(process.execPath, [...NODE_FLAGS, path, ...scriptArgs], { stdio: collect ? ["ignore", "pipe", "pipe"] : "inherit", env: { ...process.env, WORKTRUST_MCP_URL: MCP, WORKTRUST_MCP_TOKEN: token, WORKTRUST_NODE: NODE, WORKTRUST_CLI_VERSION: CLI_VERSION, ...extraEnv } });
|
|
151
146
|
let out = "";
|
|
152
147
|
child.stdout?.on("data", (chunk) => { out += chunk; });
|
|
153
148
|
child.stderr?.on("data", (chunk) => { out += chunk; });
|
|
@@ -463,7 +458,7 @@ function sweepAtMostHourly() {
|
|
|
463
458
|
const stamp = join(HOME_DIR, "bridge-swept-at");
|
|
464
459
|
try { if (Date.now() - Number(readFileSync(stamp, "utf8")) < 3_600_000) return; } catch { /* never swept here */ }
|
|
465
460
|
try { mkdirSync(HOME_DIR, { recursive: true }); writeFileSync(stamp, String(Date.now())); } catch { return; }
|
|
466
|
-
try { spawn(process.execPath, [fileURLToPath(import.meta.url), "hook"], { detached: true, stdio: "ignore" }).unref(); } catch { /* the next start sweeps */ }
|
|
461
|
+
try { spawn(process.execPath, [...NODE_FLAGS, fileURLToPath(import.meta.url), "hook"], { detached: true, stdio: "ignore" }).unref(); } catch { /* the next start sweeps */ }
|
|
467
462
|
}
|
|
468
463
|
|
|
469
464
|
async function bridge() {
|
|
@@ -505,9 +500,9 @@ async function hook() {
|
|
|
505
500
|
if (has("antigravity-stop")) return antigravityStop();
|
|
506
501
|
if (has("hermes") || has("goose")) return sessionEnd();
|
|
507
502
|
const key = await freshKey();
|
|
508
|
-
if (!key)
|
|
509
|
-
const child = spawn(process.execPath, [join(BUNDLED ? HERE : HOME_DIR, "log-session.mjs"), ...args.filter((arg) => arg !== "hook")], { stdio: "inherit", env: { ...process.env, WORKTRUST_MCP_URL: key.url, WORKTRUST_MCP_TOKEN: key.token, ...(key.device ? { WORKTRUST_DEVICE_KEY: key.device } : {}) } });
|
|
510
|
-
child.on("
|
|
503
|
+
if (!key) return;
|
|
504
|
+
const child = spawn(process.execPath, [...NODE_FLAGS, join(BUNDLED ? HERE : HOME_DIR, "log-session.mjs"), ...args.filter((arg) => arg !== "hook")], { stdio: "inherit", env: { ...process.env, WORKTRUST_MCP_URL: key.url, WORKTRUST_MCP_TOKEN: key.token, WORKTRUST_CLI_VERSION: CLI_VERSION, ...(key.device ? { WORKTRUST_DEVICE_KEY: key.device } : {}) } }); // 0.10.20: the hook names the version that started it, beside each line
|
|
505
|
+
process.exitCode = await new Promise((resolve, reject) => { child.on("error", reject); child.on("close", (code) => resolve(code ?? 1)); });
|
|
511
506
|
}
|
|
512
507
|
|
|
513
508
|
/**
|
|
@@ -529,8 +524,8 @@ async function antigravityStop() {
|
|
|
529
524
|
process.stdin.on("end", () => { clearTimeout(timer); resolve(text); });
|
|
530
525
|
process.stdin.on("error", () => { clearTimeout(timer); resolve(text); });
|
|
531
526
|
});
|
|
532
|
-
try { spawn(process.execPath, [fileURLToPath(import.meta.url), "hook", "--antigravity"], { detached: true, stdio: "ignore", env: { ...process.env, WORKTRUST_HOOK_INPUT: input.slice(0, 65536) } }).unref(); } catch { /* the next run sweeps it */ }
|
|
533
|
-
process.
|
|
527
|
+
try { spawn(process.execPath, [...NODE_FLAGS, fileURLToPath(import.meta.url), "hook", "--antigravity"], { detached: true, stdio: "ignore", env: { ...process.env, WORKTRUST_HOOK_INPUT: input.slice(0, 65536) } }).unref(); } catch { /* the next run sweeps it */ }
|
|
528
|
+
process.stdin.pause(); return;
|
|
534
529
|
}
|
|
535
530
|
|
|
536
531
|
/**
|
|
@@ -543,8 +538,8 @@ async function antigravityStop() {
|
|
|
543
538
|
async function sessionEnd() {
|
|
544
539
|
writeSync(1, "{}\n");
|
|
545
540
|
if (!process.stdin.isTTY) await new Promise((resolve) => { const timer = setTimeout(resolve, 2000); process.stdin.on("data", () => {}); process.stdin.on("end", () => { clearTimeout(timer); resolve(); }); process.stdin.on("error", () => { clearTimeout(timer); resolve(); }); });
|
|
546
|
-
try { spawn(process.execPath, [fileURLToPath(import.meta.url), "hook"], { detached: true, stdio: "ignore" }).unref(); } catch { /* the next run sweeps it */ }
|
|
547
|
-
process.
|
|
541
|
+
try { spawn(process.execPath, [...NODE_FLAGS, fileURLToPath(import.meta.url), "hook"], { detached: true, stdio: "ignore" }).unref(); } catch { /* the next run sweeps it */ }
|
|
542
|
+
process.stdin.pause(); return;
|
|
548
543
|
}
|
|
549
544
|
|
|
550
545
|
/**
|
|
@@ -683,10 +678,10 @@ async function offerHistory(paths, token, devicePem, url = MCP, rebuild = false)
|
|
|
683
678
|
try { found = JSON.parse(counted.out.trim().split("\n").pop()); } catch { /* no line: nothing to offer */ }
|
|
684
679
|
say();
|
|
685
680
|
if (!found?.sessions) { historyDone(true); say(rebuild ? " Your AI apps hold no earlier sessions on this computer to re-measure." : " Your AI apps hold no earlier sessions on this computer to send."); return; }
|
|
686
|
-
say(` This computer holds ${found.sessions} earlier sessions of your AI apps · ${found.
|
|
681
|
+
say(` This computer holds ${found.sessions} earlier sessions of your AI apps · ${found.days} days · ${found.first} … ${found.last}. WorkTrust measures the hours when they arrive.`);
|
|
687
682
|
// REBUILD (owner, 2026-10-07): the plan per AI app, in days and hours, and what it replaces, before the one question. Enter is No.
|
|
688
683
|
if (rebuild) {
|
|
689
|
-
for (const row of found.clients ?? []) say(` ${row.client.padEnd(12)} ${String(row.days).padStart(4)} days
|
|
684
|
+
for (const row of found.clients ?? []) say(` ${row.client.padEnd(12)} ${String(row.days).padStart(4)} days ${row.first} … ${row.last}`);
|
|
690
685
|
say(" Re-measured with the current rules (what the seconds were, your own turns, tokens with the cache, every AI app above).");
|
|
691
686
|
say(" WorkTrust REPLACES this computer's earlier lines for those days and apps: each earlier line is withdrawn and kept,");
|
|
692
687
|
say(" never deleted, so a day is counted once. Other computers, web sources and days not listed are not touched.");
|
|
@@ -707,6 +702,7 @@ async function offerHistory(paths, token, devicePem, url = MCP, rebuild = false)
|
|
|
707
702
|
: `${n(did.new)} new lines${n(did.filled) > 0 ? `, ${n(did.filled)} lines gained what was missing` : ""}; ${n(did.alreadyHeld)} already held.`;
|
|
708
703
|
if (rebuild) say(sent.code === 0 ? ` ✓ Re-measured. ${outcome}` : " Not all of it arrived. Run npx worktrust again: it finishes what did not arrive, a day already rebuilt is counted once.");
|
|
709
704
|
else say(sent.code === 0 ? " ✓ Sent as history. Measured sessions count toward your verified hours; a day WorkTrust already holds is kept once." : " Not all of it arrived. Run npx worktrust history again: a line already received is kept once.");
|
|
705
|
+
if (did && Number(did.measuredSeconds) > 0) say(` Measured by WorkTrust: ${(Number(did.measuredSeconds) / 3600).toFixed(1)} h for what this send stored${n(did.corrected) > 0 ? ` (${n(did.corrected)} lines corrected: a figure sent beside the timeline differed)` : ""}.`);
|
|
710
706
|
}
|
|
711
707
|
|
|
712
708
|
/** The version stamped in the stable copy in ~/.worktrust, the CLI this computer ran before an update; null without one. */
|
|
@@ -800,6 +796,8 @@ async function offerArchive(paths, key) {
|
|
|
800
796
|
* `--dry-run` stops before it; `--history` says yes in advance. Answers whether the export arrived whole.
|
|
801
797
|
*/
|
|
802
798
|
const EXPORT_PRODUCT = { chatgpt: "ChatGPT", "claude-web": "Claude on the web" };
|
|
799
|
+
/** The connector of the export's vendor (0.10.19): the only lines an export may withdraw are the ones this connector reported. */
|
|
800
|
+
const EXPORT_CONNECTOR = { chatgpt: "ChatGPT", "claude-web": "Claude" };
|
|
803
801
|
async function offerExport(paths, key, path) {
|
|
804
802
|
const env = { WORKTRUST_MCP_URL: key.url, ...(key.device ? { WORKTRUST_DEVICE_KEY: key.device } : {}) };
|
|
805
803
|
const counted = await run(paths["log-session.mjs"], ["--history", "--export", path, "--dry-run", "--summary"], key.token, true, env);
|
|
@@ -808,10 +806,10 @@ async function offerExport(paths, key, path) {
|
|
|
808
806
|
const report = found?.exports?.[0];
|
|
809
807
|
say();
|
|
810
808
|
if (counted.code !== 0 || !report) { say(` ${counted.out.trim().split("\n").filter(Boolean).pop() ?? "export: it could not be read"}. Nothing was sent.`); return false; }
|
|
811
|
-
const product = EXPORT_PRODUCT[report.vendor] ?? report.vendor;
|
|
809
|
+
const product = EXPORT_PRODUCT[report.vendor] ?? report.vendor, connector = EXPORT_CONNECTOR[report.vendor] ?? report.vendor;
|
|
812
810
|
if (!report.days) { say(` ${product} export · ${report.conversations} conversations, none with a clock to place: nothing to send.`); return true; }
|
|
813
|
-
say(` ${product} export · ${report.conversations} conversations · ${report.days} days · ${
|
|
814
|
-
say("
|
|
811
|
+
say(` ${product} export · ${report.conversations} conversations · ${report.days} days · ${String(report.first).slice(0, 7)} … ${String(report.last).slice(0, 7)}`);
|
|
812
|
+
say(" WorkTrust reconstructs the hours from the export's own clocks when they arrive: shown with their origin, never verified hours. Never a title or a message.");
|
|
815
813
|
// LEFT OUT AND COUNTED (0.10.18): a conversation whose kept fields outgrew the reader's budget is passed over, never the export.
|
|
816
814
|
if (report.oversized > 0) say(` ${report.oversized} conversation${report.oversized === 1 ? "" : "s"} too large to read ${report.oversized === 1 ? "is" : "are"} left out; the rest is read.`);
|
|
817
815
|
if (has("dry-run")) { say(" Dry run: nothing was sent."); return false; }
|
|
@@ -822,13 +820,15 @@ async function offerExport(paths, key, path) {
|
|
|
822
820
|
// THE EXPORT REPLACES (owner, 2026-10-10): the door withdrew the product's earlier connector lines on the export's days by itself and
|
|
823
821
|
// says so; the lines an AI app reported under no product on those days may describe the same conversations, and go only on a yes.
|
|
824
822
|
const counts = lastCounts(sent.out);
|
|
825
|
-
|
|
823
|
+
// WHAT AN EXPORT MAY WITHDRAW (0.10.19, after the incident of 2026-10-18): lines your connector of the same vendor reported, and nothing a computer of yours wrote;
|
|
824
|
+
// the door holds the rule, the counts here are the door's own, and the question names exactly what the second send will touch.
|
|
825
|
+
if (counts.superseded > 0) say(` ${counts.superseded} earlier line${counts.superseded === 1 ? "" : "s"} of ${product} your ${connector} connector reported for those days ${counts.superseded === 1 ? "is" : "are"} withdrawn and kept (each with a correction row): the export's lines count, a day counts once.`);
|
|
826
826
|
// ONE STRETCH PER RUN (0.10.17): a conversation-day sent before as one envelope is now its runs; the door withdrew the envelope.
|
|
827
827
|
if (counts.recut > 0) say(` ${counts.recut} earlier line${counts.recut === 1 ? "" : "s"} of this export, one per conversation and day, ${counts.recut === 1 ? "is" : "are"} replaced by one line per run of activity (withdrawn and kept, the same total).`);
|
|
828
828
|
if (counts.unknownOnDays > 0) {
|
|
829
829
|
const n = counts.unknownOnDays;
|
|
830
|
-
say(` ${n} earlier line${n === 1 ? "" : "s"}
|
|
831
|
-
if (has("withdraw-unknown") || (await ask(`Also withdraw ${n} earlier line${n === 1 ? "" : "s"}
|
|
830
|
+
say(` ${n} earlier line${n === 1 ? "" : "s"} your ${connector} connector reported for these days under no product may describe the same conversations. Your own computers' lines are never touched.`);
|
|
831
|
+
if (has("withdraw-unknown") || (await ask(`Also withdraw ${n} earlier line${n === 1 ? "" : "s"} your ${connector} connector reported for these days?`, false))) {
|
|
832
832
|
const again = await run(paths["log-session.mjs"], ["--history", "--export", path, "--withdraw-unknown"], key.token, true, env);
|
|
833
833
|
const done = lastCounts(again.out);
|
|
834
834
|
say(again.code === 0 ? ` ✓ Withdrawn and kept: ${done.unknownWithdrawn} earlier line${done.unknownWithdrawn === 1 ? "" : "s"}, each with a correction row; never deleted.` : ` Not withdrawn: ${again.out.trim().split("\n").pop()}`);
|
|
@@ -874,7 +874,7 @@ async function offerFolder(paths, key, dir) {
|
|
|
874
874
|
const report = found?.folder;
|
|
875
875
|
say();
|
|
876
876
|
if (counted.code !== 0 || !report) { say(` ${counted.out.trim().split("\n").filter(Boolean).pop() ?? "folder: it could not be read"}. Nothing was sent.`); return; }
|
|
877
|
-
say(` Copied session folder · ${report.stretches} stretch${report.stretches === 1 ? "" : "es"} (${report.skipped} already among this computer's own sessions, skipped) · ${report.days} day${report.days === 1 ? "" : "s"} ·
|
|
877
|
+
say(` Copied session folder · ${report.stretches} stretch${report.stretches === 1 ? "" : "es"} (${report.skipped} already among this computer's own sessions, skipped) · ${report.days} day${report.days === 1 ? "" : "s"} · measured by WorkTrust on arrival${report.first ? ` · ${report.first} … ${report.last}` : ""}`);
|
|
878
878
|
if (!report.days) { say(" Nothing to send: every day of the copy is already among this computer's own sessions."); return; }
|
|
879
879
|
say(" Hours reconstructed from the copy's own clocks: shown with their origin, never verified hours. Never text.");
|
|
880
880
|
if (has("dry-run")) { say(" Dry run: nothing was sent."); return; }
|
|
@@ -1106,7 +1106,7 @@ async function measuredHere() {
|
|
|
1106
1106
|
if (!m || !m.stretches) { say(" Measured here, last 30 days: no finished work stretch yet."); return; }
|
|
1107
1107
|
const of = (part, whole, one, many) => `${part} of ${whole} ${whole === 1 ? one : many}`;
|
|
1108
1108
|
say();
|
|
1109
|
-
say(` Measured here, last 30 days: ${m.stretches} work stretch${m.stretches === 1 ? "" : "es"}
|
|
1109
|
+
say(` Measured here, last 30 days: ${m.stretches} work stretch${m.stretches === 1 ? "" : "es"} (the hours are WorkTrust's: see the app)`);
|
|
1110
1110
|
if (m.delivered) say(` verified before delivery ${of(m.verified_first, m.delivered, "stretch that delivered", "stretches that delivered")}`);
|
|
1111
1111
|
if (m.failures) say(` recovered failures ${of(m.recovered, m.failures, "failed tool call", "failed tool calls")} (${m.blind_retries} retried unchanged)`);
|
|
1112
1112
|
if (m.steers) say(` steering that worked ${of(m.effective_steers, m.steers, "time you stepped in", "times you stepped in")}`);
|
|
@@ -1131,7 +1131,7 @@ function claudeKeepsDays() {
|
|
|
1131
1131
|
async function preserve() {
|
|
1132
1132
|
const script = join(HERE, "preserve.mjs");
|
|
1133
1133
|
if (!existsSync(script)) fail("preserve runs from the package: npx worktrust@latest preserve");
|
|
1134
|
-
const child = spawn(process.execPath, [script, ...args.filter((arg) => arg !== "preserve")], { stdio: "inherit", env: { ...process.env, WORKTRUST_COLLECTOR: `worktrust-cli/${CLI_VERSION}` } });
|
|
1134
|
+
const child = spawn(process.execPath, [...NODE_FLAGS, script, ...args.filter((arg) => arg !== "preserve")], { stdio: "inherit", env: { ...process.env, WORKTRUST_COLLECTOR: `worktrust-cli/${CLI_VERSION}` } });
|
|
1135
1135
|
process.exitCode = await new Promise((resolve) => child.on("exit", (code) => resolve(code ?? 1)));
|
|
1136
1136
|
}
|
|
1137
1137
|
|
|
@@ -1157,7 +1157,7 @@ function help() {
|
|
|
1157
1157
|
say(" --export <path> a ChatGPT or Claude data export (the zip, its folder, conversations.json, a conversations part or the manifest) as history:");
|
|
1158
1158
|
say(" hours reconstructed from its clocks, shown with their origin, never verified hours (asks first);");
|
|
1159
1159
|
say(" on its days the export replaces the product's earlier connector lines (withdrawn, kept)");
|
|
1160
|
-
say(" --withdraw-unknown with --export: yes in advance to withdrawing the earlier lines
|
|
1160
|
+
say(" --withdraw-unknown with --export: yes in advance to withdrawing the earlier lines your connector of that vendor reported for those days under no product");
|
|
1161
1161
|
say(" --from-folder <dir> your own copy of an AI app's session folder (a backed-up ~/.claude/projects, ~/.codex/sessions):");
|
|
1162
1162
|
say(" days this computer's own sessions lack, reconstructed, never verified hours (asks first)");
|
|
1163
1163
|
say(" worktrust disconnect take WorkTrust out of every AI app here (asks first)");
|
|
@@ -1174,12 +1174,13 @@ function help() {
|
|
|
1174
1174
|
}
|
|
1175
1175
|
|
|
1176
1176
|
// THE BARE COMMAND COUPLES (owner, 2026-10-03: "zo kort mogelijk"). `npx worktrust` on a computer
|
|
1177
|
-
//
|
|
1178
|
-
// coupled, so running it twice never re-pairs by surprise.
|
|
1177
|
+
// An existing key shows the current coupling; no key starts the pairing plan.
|
|
1179
1178
|
// AN AGENT DOES NOT RUN WORKTRUST FOR A PERSON (owner, 2026-10-08; AGENTS.md). The commands that change what this
|
|
1180
1179
|
// computer sends, couples or rebuilds are the person's to run in their own terminal: in an AI agent's shell they stop
|
|
1181
1180
|
// before anything is read or written, --yes included. The hook and the MCP bridge are started by the agent's client
|
|
1182
1181
|
// itself and stay as they are; `status` only reads.
|
|
1182
|
+
async function main() {
|
|
1183
|
+
if (Number(process.versions.node.split(".")[0]) < 18) fail("needs Node 18 or later (fetch is built in from 18).");
|
|
1183
1184
|
const AGENT_ENV = ["CLAUDECODE", "CLAUDE_CODE_ENTRYPOINT", "CODEX_SANDBOX", "CODEX_CI", "GEMINI_CLI", "CURSOR_AGENT", "OPENCODE", "CLINE_ACTIVE", "AIDER_CHAT", "ANTIGRAVITY_AGENT", "WINDSURF_AGENT"];
|
|
1184
1185
|
const PERSON_ONLY = new Set(["default", "connect", "update", "history", "disconnect", "preserve", "codex", "antigravity", "sources", "web", "import", "orchestration", "mod"]);
|
|
1185
1186
|
const agentShell = AGENT_ENV.find((name) => process.env[name] && process.env[name] !== "0");
|
|
@@ -1187,7 +1188,7 @@ if (agentShell && PERSON_ONLY.has(command)) {
|
|
|
1187
1188
|
say();
|
|
1188
1189
|
say(` worktrust${command === "default" ? "" : ` ${command}`} is run by the person, in their own terminal, never by an AI agent for them (this shell is an agent's: ${agentShell}).`);
|
|
1189
1190
|
say(" Nothing was read, sent or changed. See AGENTS.md in the package: https://www.npmjs.com/package/worktrust");
|
|
1190
|
-
process.
|
|
1191
|
+
return (process.exitCode = 3);
|
|
1191
1192
|
}
|
|
1192
1193
|
|
|
1193
1194
|
/**
|
|
@@ -1221,9 +1222,9 @@ async function relayToNewest() {
|
|
|
1221
1222
|
const child = platform() === "win32" ? spawn(["npx", ...argv].map(quote).join(" "), { stdio: "inherit", env, shell: true }) : spawn("npx", argv, { stdio: "inherit", env });
|
|
1222
1223
|
const code = await new Promise((done) => { child.on("error", () => done(null)); child.on("close", (exit) => done(exit)); });
|
|
1223
1224
|
if (code === null) { say(" The newest could not be started; this version runs instead."); return; }
|
|
1224
|
-
process.
|
|
1225
|
+
process.exitCode = code; return true;
|
|
1225
1226
|
}
|
|
1226
|
-
await relayToNewest();
|
|
1227
|
+
if (await relayToNewest()) return;
|
|
1227
1228
|
|
|
1228
1229
|
if (command === "version") say(CLI_VERSION);
|
|
1229
1230
|
else if (command === "default") { if (keyStore.load()) await again(); else await connect(); }
|
|
@@ -1250,3 +1251,6 @@ else if (command === "orchestration") {
|
|
|
1250
1251
|
const { reportFile } = await import("./orchestration-report.mjs"); reportFile(args.slice(1));
|
|
1251
1252
|
}
|
|
1252
1253
|
else help();
|
|
1254
|
+
|
|
1255
|
+
}
|
|
1256
|
+
try { await main(); } catch (error) { if (!(error instanceof CliFailure)) throw error; process.exitCode = 1; }
|