worktrust 0.10.17 → 0.10.20

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -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.exit(0);
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.exit(passes ? 0 : 1);
501
+ return (process.exitCode = passes ? 0 : 1);
489
502
  }
490
503
  }
491
504
  /**
@@ -622,16 +635,17 @@ const skippedConversations = [];
622
635
  * both; a vendor's zip is opened for its conversations.json alone. Without the module an export flag is refused by name.
623
636
  */
624
637
  const { exportSessions = null } = (await import("./chat-exports.mjs").catch(() => null)) ?? {};
625
- function* vendorExportSessions(paths, expect) {
638
+ // 0.10.18: the export streams, one conversation in memory at a time, with its text (`text: true`: this rubric reads it here).
639
+ async function* vendorExportSessions(paths, expect) {
626
640
  if (paths.length > 0 && !exportSessions) throw Error("chat-exports.mjs is not beside this file: a data export cannot be read");
627
- for (const given of paths) for (const session of exportSessions(given, { expect, excluded, skipped: skippedConversations })) {
641
+ for (const given of paths) for await (const session of exportSessions(given, { expect, excluded, skipped: skippedConversations, text: true })) {
628
642
  if (expect === "chatgpt") chatgptConversations += 1; else exportConversations += 1;
629
643
  yield session;
630
644
  }
631
645
  }
632
- function* claudeExportSessions() { yield* vendorExportSessions(EXPORTS, "claude-web"); }
646
+ async function* claudeExportSessions() { yield* vendorExportSessions(EXPORTS, "claude-web"); }
633
647
  let chatgptConversations = 0;
634
- function* chatgptExportSessions() { yield* vendorExportSessions(CHATGPT_EXPORTS, "chatgpt"); }
648
+ async function* chatgptExportSessions() { yield* vendorExportSessions(CHATGPT_EXPORTS, "chatgpt"); }
635
649
  /**
636
650
  * THE READERS FOR CODEX AND ANTIGRAVITY live in transcript-readers.mjs beside this file (2026-10-04;
637
651
  * the session hook imports the same file). Run alone, without it, the counter reads Claude Code,
@@ -709,7 +723,7 @@ const decodeLine = (buffer, start, end) => { try { return buffer.toString("utf8"
709
723
  /** The digest of a transcript file, streamed: its path and every byte. */
710
724
  function fileDigest(path) { const hash = createHash("sha256").update(`file:${path}\n`); for (const _ of fileLines(path, hash)) { /* the bytes are the input */ } return hash.digest("hex"); }
711
725
  const sessionDigest = (session) => session.path ? fileDigest(session.path) : fingerprint(session);
712
- function* sessions() {
726
+ async function* sessions() { // async since 0.10.18: an export streams through it
713
727
  for (const file of transcriptFiles()) {
714
728
  yield { key: file, projectDir: file.split("/").slice(-2, -1)[0] ?? "", basename: null, path: file };
715
729
  }
@@ -787,13 +801,6 @@ const byMonthContext = new Map(); // month → Map("signal|context" → count)
787
801
  * week never straddles two stored months: "2026-09|2026-W36". A count without a day (a
788
802
  * month-level aggregate) lands in the month's "U" bucket.
789
803
  */
790
- export const isoWeek = (day) => {
791
- const date = new Date(`${day}T00:00:00Z`);
792
- const thursday = new Date(date); thursday.setUTCDate(date.getUTCDate() + 3 - ((date.getUTCDay() + 6) % 7));
793
- const firstThursday = new Date(Date.UTC(thursday.getUTCFullYear(), 0, 4));
794
- const week = 1 + Math.round(((thursday - firstThursday) / 86400000 - 3 + ((firstThursday.getUTCDay() + 6) % 7)) / 7);
795
- return `${thursday.getUTCFullYear()}-W${String(week).padStart(2, "0")}`;
796
- };
797
804
  const byWeek = new Map(); // "month|week" → Map(signal → count)
798
805
  /**
799
806
  * THE WORK STRETCH (0.7.0, the owner's capability framework v4 §13: "work_stretch_id, the stable unit joining AI
@@ -849,7 +856,7 @@ const seenLines = new Set(); // v0.10: line identities already counted (a uuid o
849
856
  // Validate the processed prefix before reuse. Edited/truncated/deleted sessions restart the
850
857
  // scan; complete session boundaries preserve signals that depend on earlier turns.
851
858
  const manifest = [];
852
- for(const session of sessions())manifest.push(sessionDigest(session));
859
+ for await (const session of sessions())manifest.push(sessionDigest(session));
853
860
  exportConversations = 0; chatgptConversations = 0; copilotSessionCount = 0; codexRolloutCount = 0; antigravityCount = 0; skippedDirs.length = 0; countedDirs.length = 0; skippedConversations.length = 0;
854
861
  const checkpoint = flag("no-checkpoint") || flag("stretch-signals") || LABEL_OUT ? null : checkpointStore(
855
862
  value("checkpoint") ?? join(homedir(), ".worktrust", "counter-checkpoint.json"),
@@ -867,7 +874,7 @@ const resumeAt=checkpoint?.saved?.next??0;
867
874
  let sessionIndex=0, processed=0;
868
875
  const maxSessions=Number(value("batch-sessions")??Number.POSITIVE_INFINITY);
869
876
  if (value("batch-sessions") !== undefined && (!Number.isSafeInteger(maxSessions) || maxSessions < 1)) throw Error("batch-sessions must be a positive integer");
870
- for (const session of sessions()) {
877
+ for await (const session of sessions()) {
871
878
  // A file's digest is taken while its lines stream past and compared when the session ends.
872
879
  if(!session.path && fingerprint(session)!==manifest[sessionIndex]) throw Error("Source changed during counting; rerun to resume safely");
873
880
  if(sessionIndex++<resumeAt)continue;
@@ -1174,7 +1181,7 @@ for (const session of sessions()) {
1174
1181
  checkpoint?.write(sessionIndex,{maps:checkpointMaps,sets:checkpointSets,sessionSpans,messages,files,currentContext,duplicateLines},checkpointDependencies);
1175
1182
  if(++processed>=maxSessions && sessionIndex<manifest.length){
1176
1183
  console.log(`Counter paused at ${sessionIndex}/${manifest.length} sessions; rerun the same command. Nothing sent.`);
1177
- checkpoint?.close();process.exit(0);
1184
+ checkpoint?.close();return (process.exitCode = 0);
1178
1185
  }
1179
1186
  }
1180
1187
  currentUnit = null; currentDay = null; currentStretchBase = null; // month-level aggregates carry no unit, no day and no stretch
@@ -1197,16 +1204,6 @@ for (const [context, cwd] of contextCwds) {
1197
1204
  }
1198
1205
  currentUnit = null; currentDay = null; currentContext = null;
1199
1206
  // The same strict overlap test in O(n log n), rather than comparing every pair.
1200
- export function overlappingSessions(spans) {
1201
- const ordered=spans.map((span,index)=>({...span,index})).filter(s=>s.end>s.start).sort((a,b)=>a.start-b.start);
1202
- const found=new Set();let maximumEnd=-Infinity;
1203
- for(let i=0;i<ordered.length;i++){
1204
- const a=ordered[i];
1205
- if(maximumEnd>a.start || (ordered[i+1] && ordered[i+1].start<a.end))found.add(a.index);
1206
- maximumEnd=Math.max(maximumEnd,a.end);
1207
- }
1208
- return found;
1209
- }
1210
1207
  const overlapping=overlappingSessions(sessionSpans);
1211
1208
  // Parallelism: a session that overlaps any other counted session, once per session.
1212
1209
  for (let i = 0; i < sessionSpans.length; i += 1) {
@@ -1220,7 +1217,7 @@ for (let i = 0; i < sessionSpans.length; i += 1) {
1220
1217
  if (flag("stretch-signals")) {
1221
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)])) }));
1222
1219
  await new Promise((resolve) => process.stdout.write(`${[...rows, JSON.stringify({ stretch_signals_end: rows.length })].join("\n")}\n`, resolve));
1223
- process.exit(0);
1220
+ return (process.exitCode = 0);
1224
1221
  }
1225
1222
 
1226
1223
  const months = [...byMonth.keys()].sort();
@@ -1280,10 +1277,10 @@ console.log("");
1280
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})`); }
1281
1278
  if (DRY) {
1282
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."}`);
1283
- process.exit(0);
1280
+ return (process.exitCode = 0);
1284
1281
  }
1285
1282
  if (STAGE) {
1286
- if (!URL_ || !TOKEN) { console.error("no coupling found: pass --url and --token, or set WORKTRUST_MCP_URL / WORKTRUST_MCP_TOKEN"); process.exit(1); }
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); }
1287
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 } : {}) })) }));
1288
1285
  if (!flag("legacy-stage")) {
1289
1286
  // WHAT THIS MACHINE ALREADY DELIVERED, per month and ISO week, for this coupling and rubric
@@ -1325,7 +1322,7 @@ if (STAGE) {
1325
1322
  const unchanged=new Set(readings.map(r=>r.period)).size-plan.length;
1326
1323
  console.log(` ${plan.length} month(s) with new or changed weeks${unchanged>0?` · ${unchanged} unchanged, not sent`:""}`);
1327
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"}`);
1328
- if(plan.length===0){console.log("Nothing new since the last delivery from this machine. Nothing sent.");process.exit(0);}
1325
+ if(plan.length===0){console.log("Nothing new since the last delivery from this machine. Nothing sent.");return (process.exitCode = 0);}
1329
1326
  // Persist the outbound revision BEFORE sending. A failed HTTP response replays safely.
1330
1327
  let delivery=null;try{delivery=JSON.parse(readFileSync(deliveryPath,"utf8"));}catch{}
1331
1328
  if(delivery?.scope!==scope)delivery=null;
@@ -1355,7 +1352,7 @@ if (STAGE) {
1355
1352
  }
1356
1353
  }
1357
1354
  console.log("Complete months await the owner's Import in /behaviour. Imports replace this coupling's month, including corrections and removals.");
1358
- process.exit(0);
1355
+ return (process.exitCode = 0);
1359
1356
  }
1360
1357
  // UNDER THE HOST'S CEILING. A serverless request takes about 4.5 MB; a year of unit references
1361
1358
  // does not fit in one. Months are staged in chunks that stay under the ceiling, each with its own
@@ -1377,9 +1374,9 @@ if (STAGE) {
1377
1374
  console.log(` staged ${chunk[0].period}${chunk.length > 1 ? `–${chunk[chunk.length - 1].period}` : ""} → ${text}`);
1378
1375
  }
1379
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.`);
1380
- process.exit(0);
1377
+ return (process.exitCode = 0);
1381
1378
  }
1382
- if (!URL_ || !TOKEN) { console.error("no coupling found: pass --url and --token, or set WORKTRUST_MCP_URL / WORKTRUST_MCP_TOKEN"); process.exit(1); }
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); }
1383
1380
  console.log(`sending to ${new URL(URL_).host} …`);
1384
1381
  for (const month of months) {
1385
1382
  const bucket = byMonth.get(month);
@@ -1391,3 +1388,6 @@ for (const month of months) {
1391
1388
  const text = answer?.result?.content?.[0]?.text ?? answer?.error?.message ?? `http ${response.status}`;
1392
1389
  console.log(` sent ${month} → ${text}`);
1393
1390
  }
1391
+
1392
+ }
1393
+ await main();