worktrust 0.10.36 → 0.10.37

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/log-session.mjs CHANGED
@@ -954,7 +954,7 @@ function batchesOf(group, byDay, limit = BATCH_LIMIT) {
954
954
  return out;
955
955
  }
956
956
  /** 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. */
957
- const RECEIPTS = { new: 0, alreadyHeld: 0, filled: 0, replaced: 0, superseded: 0, recut: 0, unknownOnDays: 0, unknownWithdrawn: 0, corrected: 0, measuredSeconds: 0, staged: 0, kept: 0, restored: 0, untimed: 0 }; // 0.10.27: staged, the batches WorkTrust keeps on its server, and kept, their lines // 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
957
+ const RECEIPTS = { new: 0, alreadyHeld: 0, filled: 0, replaced: 0, superseded: 0, recut: 0, unknownOnDays: 0, unknownWithdrawn: 0, corrected: 0, measuredSeconds: 0, reconstructedSeconds: 0, staged: 0, kept: 0, restored: 0, untimed: 0 }; // 0.10.27: staged, the batches WorkTrust keeps on its server, and kept, their lines // 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
958
958
  const noteReceipt = (answer, run = null) => {
959
959
  try {
960
960
  const json = JSON.parse(answer.trim().startsWith("{") ? answer : answer.split("\n").find((row) => row.startsWith("data:"))?.slice(5) ?? "null");
@@ -1142,8 +1142,9 @@ const outboxCut = {
1142
1142
  };
1143
1143
  async function sendHistory(door, entries, announce = false, rebuild = false, named = false, { byDay = false, withdrawUnknown = false } = {}) {
1144
1144
  let accepted = 0;
1145
- const { queuedHistory, historyRefusal, historyIdOf, resumeHistory } = await import("./history-outbox.mjs");
1145
+ const { queuedHistory, historyIdOf, resumeHistory, deliverHistory } = await import("./history-outbox.mjs");
1146
1146
  const plan = historyPlan(door, entries, rebuild, { byDay, withdrawUnknown });
1147
+ const shown = announce ? historyProgressOut : null, STOP = announce && PROGRESS.stopSignals ? (STOPPING ??= PROGRESS.stopSignals()) : null; shown?.({ phase: "plan", batches: plan.length, lines: plan.reduce((n, item) => n + item.batch.length, 0) }); // THE SEND, AS IT GOES (2026-11-05)
1147
1148
  // Persist the approved plan before sending, so later batches survive removed source files too.
1148
1149
  try { for (const item of plan) queuedHistory(item.target, item.body, item.source); }
1149
1150
  catch { console.error("History queue is full, busy or unavailable. Resume the saved batches before retrying this import; nothing was marked complete."); HISTORY_DELIVERY.waiting += entries.length; return 0; }
@@ -1157,7 +1158,7 @@ async function sendHistory(door, entries, announce = false, rebuild = false, nam
1157
1158
  const handLater = (item) => { const row = later.get(item.target.token) ?? { target: item.target, ids: [] }; row.ids.push(historyIdOf(item.target, item.body, item.source)); later.set(item.target.token, row); };
1158
1159
  for (const item of plan) {
1159
1160
  const { source, target, batch, body } = item;
1160
- if (stopped.has(source)) { HISTORY_DELIVERY.waiting += batch.length; continue; } // 2026-10-31: held back behind its AI app's failed batch, waiting in the outbox, and said
1161
+ if (stopped.has(source) || STOP?.asked) { HISTORY_DELIVERY.waiting += batch.length; continue; } // 2026-10-31: held back behind its AI app's failed batch, waiting in the outbox, and said
1161
1162
  if (item.run && stoppedRuns.has(item.run.id)) { handLater(item); continue; }
1162
1163
  const number = (numbers.get(source) ?? 0) + 1; numbers.set(source, number);
1163
1164
  for (const entry of batch) retainMeasurement(entry, source);
@@ -1166,32 +1167,30 @@ async function sendHistory(door, entries, announce = false, rebuild = false, nam
1166
1167
  try { queued = queuedHistory(target, body, source); }
1167
1168
  catch { console.error("Pending history could not be stored safely. Nothing was marked complete; keep the local WorkTrust folder for recovery."); HISTORY_DELIVERY.waiting += batch.length; stopped.add(source); continue; }
1168
1169
  if (queued.status === "closed") { HISTORY_DELIVERY.refused += batch.length; RUNS.refused(item.run); continue; } // 2026-10-31: let go on an earlier send is refused, never "already held"
1169
- if (queued.status === "acknowledged" && !byDay) { accepted += batch.length; RECEIPTS.alreadyHeld += batch.length; RUNS.held(item.run); continue; }
1170
+ if (queued.status === "acknowledged" && !byDay) { accepted += batch.length; RECEIPTS.alreadyHeld += batch.length; RUNS.held(item.run); shown?.({ phase: "batch", lines: batch.length, landed: true }); continue; }
1170
1171
  if (queued.status === "replaced" || queued.status === "oversize") { handLater(item); if (item.run) stoppedRuns.add(item.run.id); continue; }
1171
1172
  if (queued.status === "review" && !flag("retry-review")) { HISTORY_DELIVERY.review += batch.length; continue; }
1172
1173
  if (queued.status === "waiting") { HISTORY_DELIVERY.waiting += batch.length; continue; }
1173
1174
  try {
1174
- const response = await fetch(target.url, { method: "POST", headers: { "content-type": "application/json", accept: "application/json, text/event-stream", authorization: `Bearer ${target.token}`, ...clientOf(source, rebuild || named), ...proofFor(target.url, body) }, body, redirect: "error", signal: AbortSignal.timeout(65_000) });
1175
- const text = await response.text();
1176
- try { if (!response.ok) throw Error(); confirmedReceipt(text, batch.length); }
1177
- catch {
1178
- const refusal = historyRefusal(text, response);
1175
+ const delivered = await deliverHistory(() => fetch(target.url, { method: "POST", headers: { "content-type": "application/json", accept: "application/json, text/event-stream", authorization: `Bearer ${target.token}`, ...clientOf(source, rebuild || named), ...proofFor(target.url, body) }, body, redirect: "error", signal: callSignal(65_000) }), (text) => confirmedReceipt(text, batch.length), { patient: announce, lines: batch.length, progress: shown, halt: () => STOP?.asked, sleep: pause });
1176
+ const { text, refusal } = delivered; // A BATCH LANDED IN PART GOES AGAIN AT ONCE (2026-11-05): the person's send (`announce`) resends it while each resend lands more and waits out a minute's budget; a hook's send answers as before
1177
+ if (!delivered.ok) { if (refusal.reason !== "oversize") shown?.({ phase: "batch", lines: batch.length, landed: false }); if (STOP?.asked) { HISTORY_DELIVERY.waiting += batch.length; stopped.add(source); continue; } // stopped: it stays pending, never deferred
1179
1178
  // A run WorkTrust closed (seven days without its last batch, another computer's key) is final: kept here it would wait forever.
1180
1179
  if (refusal.reason === "closed") { queued.close(); HISTORY_DELIVERY.refused += batch.length; if (refusal.said) HISTORY_DELIVERY.said = refusal.said; RUNS.refused(item.run); continue; }
1181
1180
  if (refusal.reason === "oversize") { queued.oversize(); handLater(item); if (item.run) stoppedRuns.add(item.run.id); continue; }
1182
- queued.defer(refusal.reason, refusal.seconds);
1181
+ queued.defer(refusal.reason, refusal.seconds); if (refusal.said) HISTORY_DELIVERY.reason = refusal.said; // why it waits, in WorkTrust's words (0.10.37, incident 2026-11-05)
1183
1182
  if (refusal.reason === "review") { HISTORY_DELIVERY.review += batch.length; continue; }
1184
1183
  HISTORY_DELIVERY.waiting += batch.length; stopped.add(source); continue;
1185
1184
  }
1186
- queued.confirm(batch.length); accepted += batch.length; noteReceipt(text, item.run);
1185
+ queued.confirm(batch.length); accepted += batch.length; noteReceipt(text, item.run); shown?.({ phase: "batch", lines: batch.length, landed: true });
1187
1186
  if (announce) console.log(`batch ${number}: received ${batch.length}`);
1188
- } catch { queued.defer("unconfirmed"); HISTORY_DELIVERY.waiting += batch.length; stopped.add(source); }
1187
+ } catch { queued.defer("unconfirmed"); HISTORY_DELIVERY.waiting += batch.length; stopped.add(source); shown?.({ phase: "batch", lines: batch.length, landed: false }); }
1189
1188
  }
1190
- for (const { target, ids } of later.values()) {
1189
+ for (const { target, ids } of later.values()) { // `pause`: a minute's wait that a stop cuts short (below)
1191
1190
  try {
1192
- const totals = await resumeHistory(target, { only: ids, cutter: outboxCut, retryReview: flag("retry-review"), confirmed: confirmedReceipt, note: noteReceipt, closed: RUNS.refused, send: sendQueued(target) });
1191
+ const totals = await resumeHistory(target, { only: ids, cutter: outboxCut, retryReview: flag("retry-review"), confirmed: confirmedReceipt, note: noteReceipt, closed: RUNS.refused, send: sendQueued(target), patient: announce, progress: shown, halt: () => STOP?.asked, sleep: pause });
1193
1192
  accepted += totals.received + totals.held; RECEIPTS.alreadyHeld += totals.held;
1194
- HISTORY_DELIVERY.waiting += totals.waiting; HISTORY_DELIVERY.review += totals.review; HISTORY_DELIVERY.refused += totals.refused; if (totals.said) HISTORY_DELIVERY.said = totals.said;
1193
+ HISTORY_DELIVERY.waiting += totals.waiting; HISTORY_DELIVERY.review += totals.review; HISTORY_DELIVERY.refused += totals.refused; if (totals.said) HISTORY_DELIVERY.said = totals.said; if (totals.reason) HISTORY_DELIVERY.reason = totals.reason;
1195
1194
  if (announce && totals.split) console.log(`${totals.split} batch${totals.split === 1 ? "" : "es"} too large for one call: cut smaller and sent again in pieces`);
1196
1195
  if (announce && totals.refused) console.log(`${totals.refused} line${totals.refused === 1 ? "" : "s"} could not be sent in a call WorkTrust takes; the earlier lines keep counting. Run npx worktrust@latest history again to measure them anew.`);
1197
1196
  } catch { console.error("Pending history could not be read safely. Nothing was marked complete; keep the local WorkTrust folder for recovery."); }
@@ -1199,8 +1198,9 @@ async function sendHistory(door, entries, announce = false, rebuild = false, nam
1199
1198
  return accepted;
1200
1199
  }
1201
1200
 
1201
+ const PROGRESS = await import("./history-progress.mjs").then((m) => ({ sink: m.progressSink(), stopSignals: m.stopSignals }), () => ({ sink: null, stopSignals: null })); let STOPPING = null; const historyProgressOut = PROGRESS.sink?.event ?? null, pause = (ms) => new Promise((done) => { const at = setTimeout(done, ms); STOPPING?.signal.addEventListener("abort", () => { clearTimeout(at); done(); }, { once: true }); }), callSignal = (ms) => (STOPPING && AbortSignal.any ? AbortSignal.any([AbortSignal.timeout(ms), STOPPING.signal]) : AbortSignal.timeout(ms)), readTick = (index, total) => { if (historyProgressOut && (!(Date.now() < readTick.at) || index + 1 === total)) { readTick.at = Date.now() + 250; historyProgressOut({ phase: "read", unit: "sessions", part: index + 1, parts: total }); } }; // THE LONG STEPS, AS THEY GO, AND A SAFE STOP (2026-11-05): history-progress.mjs; `pause` is a minute's wait a stop cuts short
1202
1202
  /** The outbox's batches for one coupling, sent as `--resume` and the hook send them: signed, named, bounded in time. */
1203
- const sendQueued = (target, ms = 65_000) => (body, source) => fetch(target.url, { method: "POST", headers: { "content-type": "application/json", accept: "application/json, text/event-stream", authorization: `Bearer ${target.token}`, ...clientOf(source, true), ...proofFor(target.url, body) }, body, redirect: "error", signal: AbortSignal.timeout(ms) });
1203
+ const sendQueued = (target, ms = 65_000) => (body, source) => fetch(target.url, { method: "POST", headers: { "content-type": "application/json", accept: "application/json, text/event-stream", authorization: `Bearer ${target.token}`, ...clientOf(source, true), ...proofFor(target.url, body) }, body, redirect: "error", signal: callSignal(ms) });
1204
1204
  /**
1205
1205
  * PENDING HISTORY GOES BY ITSELF (0.10.27; owner, 2026-10-21). A batch the server did not receive (no network, a closed lid,
1206
1206
  * the upload limit) stays in ~/.worktrust/history-outbox and is sent again by the next hook run, a few at a time, without a
@@ -1310,7 +1310,7 @@ async function sendProcessDays() {
1310
1310
  */
1311
1311
  function historyEntries(floor = null, all = false) {
1312
1312
  const entries = [], processGroups = new Map();
1313
- for (const { file } of allTranscripts()) {
1313
+ const transcripts = [...allTranscripts()]; for (const [index, { file }] of transcripts.entries()) { readTick(index, transcripts.length);
1314
1314
  const lines = parsedLines(file);
1315
1315
  if (!lines) continue;
1316
1316
  let cwd = null, steered = null;
@@ -1390,7 +1390,7 @@ async function exportEntries() {
1390
1390
  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");
1391
1391
  const entries = [], reports = [];
1392
1392
  for (const given of EXPORT_PATHS) {
1393
- 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)
1393
+ const read = { onProgress: (counts) => historyProgressOut?.({ phase: "read", unit: "parts", ...counts }) }, 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)
1394
1394
  for await (const { id, lines } of exportSessions(given, { excluded, report: read })) {
1395
1395
  const messages = [];
1396
1396
  for (const line of lines) { const at = line.timestamp ? Date.parse(line.timestamp) : NaN; if (Number.isFinite(at)) messages.push(messageOf(line, at)); }
@@ -1424,7 +1424,7 @@ async function exportEntries() {
1424
1424
  // A DOWNLOAD CUT OFF (2026-10-31): the reader read the conversations parts the archive held whole before the cut, and says
1425
1425
  // where it stopped; the person is told every time, so a partial export is never shown as the whole (counts and part names only).
1426
1426
  for (const cut of read.cut ?? []) process.stderr.write(`export: the archive is cut off (${cut.where}) after ${cut.last}: ${cut.parts} conversations part${cut.parts === 1 ? "" : "s"} read whole, ${read.conversations} conversations; nothing past the cut is read, so this is not the whole export\n`);
1427
- 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, ...(read.empty ? { empty: read.empty } : {}), ...(read.cut ? { parts: read.parts, cut: read.cut } : {}) }); // no hours (0.10.20): WorkTrust computes them on arrival and the receipt says
1427
+ 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, ...(read.empty ? { empty: read.empty } : {}), ...(Number.isInteger(read.parts) ? { parts: read.parts } : {}), ...(read.cut ? { cut: read.cut } : {}) }); // no hours (0.10.20): WorkTrust computes them on arrival and the receipt says
1428
1428
  }
1429
1429
  const seen = new Set();
1430
1430
  return { entries: entries.filter((entry) => !seen.has(entry.stretch_ref) && seen.add(entry.stretch_ref)).sort((a, b) => a.at.localeCompare(b.at)), reports };
@@ -1459,7 +1459,7 @@ function folderEntries(given) {
1459
1459
  if (files.length === 0) throw Error(`no session files under ${given} (Claude Code transcripts, Codex rollouts or Antigravity transcripts, as .jsonl)`);
1460
1460
  const present = new Set(historyEntries(null, true).map((entry) => entry.stretch_ref)), seen = new Set();
1461
1461
  const entries = [], report = { stretches: 0, skipped: 0, days: new Set() };
1462
- for (const file of files) {
1462
+ for (const [index, file] of files.entries()) { readTick(index, files.length);
1463
1463
  const client = CODEX_ROLLOUT.test(file) ? "codex" : ANTIGRAVITY_TRANSCRIPT.test(file) ? "antigravity" : "claude";
1464
1464
  const lines = parsedLines(file);
1465
1465
  if (!lines) continue;
@@ -1659,7 +1659,7 @@ if (flag("evidence-summary")) {
1659
1659
  process.stdout.write(`${JSON.stringify(summary)}\n`);
1660
1660
  return await exitFlushed(0);
1661
1661
  }
1662
- 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
1662
+ 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 })); PROGRESS.sink?.end(); 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
1663
1663
  // THE EXPORTS IN A FOLDER (0.10.10, for the bare `npx worktrust`): which lie there, by vendor and digest, and which this computer
1664
1664
  // already sent or was asked about; reads, prints one JSON line, sends nothing. `--export-offered <digest>` records a No.
1665
1665
  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); }
@@ -1677,7 +1677,7 @@ if (flag("history") && flag("resume")) {
1677
1677
  const totals = { received: 0, review: 0, waiting: 0, batches: 0, refused: 0, split: 0 };
1678
1678
  try {
1679
1679
  for (const target of [door, ...(codexDoor && codexDoor.token !== door?.token ? [codexDoor] : [])].filter(Boolean)) {
1680
- const result = await resumeHistory(target, { dry: DRY, retryReview: flag("retry-review"), cutter: outboxCut, confirmed: confirmedReceipt, note: noteReceipt, send: sendQueued(target) });
1680
+ const result = await resumeHistory(target, { dry: DRY, retryReview: flag("retry-review"), cutter: outboxCut, confirmed: confirmedReceipt, note: noteReceipt, send: sendQueued(target), patient: true }); // the person's own resume resends a batch landed in part (2026-11-05)
1681
1681
  for (const key of Object.keys(totals)) totals[key] += result[key];
1682
1682
  }
1683
1683
  console.log(JSON.stringify({ resumed: totals.received, ...totals, ...RECEIPTS }));
@@ -1710,7 +1710,7 @@ if (flag("history") && flag("from-archive")) {
1710
1710
  say(`${all.length} stretches in the archive · ${signedCount} signed by this computer's key (signature checked) · ${all.length - signedCount} unsigned or signed by another key (reconstructed) · ${entries.length} of them no longer in any AI app here`);
1711
1711
  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); }
1712
1712
  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); }
1713
- return await exitFlushed((await sendHistory(door, entries, true)) === entries.length ? 0 : 1);
1713
+ return await exitFlushed((await sendHistory(door, entries, true)) === entries.length ? 0 : STOPPING?.asked ? 130 : 1);
1714
1714
  }
1715
1715
 
1716
1716
  if (flag("history")) {
@@ -1762,8 +1762,8 @@ if (flag("history")) {
1762
1762
  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 });
1763
1763
  // 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.
1764
1764
  if (!fromExports && !fromFolder) await settleReadFailures(door ?? codexDoor); // 0.10.32: a transcript that could not be read is counted and told
1765
- if (fromExports) console.log(JSON.stringify({ export_sent: accepted, of: entries.length, ...RECEIPTS })); else console.log(JSON.stringify({ history_sent: accepted, of: sending.length, unreadable: READ_FAILURES.n, ...RECEIPTS, delivery: HISTORY_DELIVERY, ...(staged ? { days: { compared: COMPARED.asked ? COMPARED.days : null, changed: COMPARED.asked ? COMPARED.changed : null }, queued: QUEUED.at, run: RUNS.state() } : {}) })); // the same line for a history send: what the door did with it, and WorkTrust's measuredSeconds for what it stored
1766
- return await exitFlushed(accepted === sending.length && RUNS.state()?.whole !== false ? 0 : 1); // 2026-10-31: a run WorkTrust does not hold whole fails too
1765
+ if (fromExports) console.log(JSON.stringify({ export_sent: accepted, of: entries.length, ...RECEIPTS, delivery: HISTORY_DELIVERY })); else console.log(JSON.stringify({ history_sent: accepted, of: sending.length, unreadable: READ_FAILURES.n, ...RECEIPTS, delivery: HISTORY_DELIVERY, ...(staged ? { days: { compared: COMPARED.asked ? COMPARED.days : null, changed: COMPARED.asked ? COMPARED.changed : null }, queued: QUEUED.at, run: RUNS.state() } : {}) })); // the same line for a history send: what the door did with it, and WorkTrust's measuredSeconds for what it stored
1766
+ return await exitFlushed(STOPPING?.asked ? 130 : accepted === sending.length && RUNS.state()?.whole !== false ? 0 : 1); // 2026-10-31: a run WorkTrust does not hold whole fails too
1767
1767
  }
1768
1768
 
1769
1769
  const input = hookInput();
@@ -1 +1 @@
1
- {"keyId":"608168ccdef72562fc91f9c0f9f2c2d6876bece7f7362cb545b818f7947da6b5","payload":{"files":{"AGENTS.md":"c6f5280c5bf81a14db4bdc282218fb005706e92dd9a9170c0e727716ee91685a","CLAUDE.md":"5933504f93e5a40369a4790e96dd5dad791d849d3178b1833eb64088e456aaeb","LICENSE":"3096ed1693974a90e1f4f59bf01c9559d94a7941d933e36fb81d3995a97f25c1","README.md":"65f5597520d3add8f021ee68f39cbc29bae59744da46e89d641cf7fb4474f541","SECURITY.md":"b672649c7c7bf18538dd4560d7b533498721e0be765a000796d7d18390b5cbb6","chat-exports.mjs":"bda43095a62bab608fc9309f9e7a2232dc10b29c514fb34e1aae357daa132737","claude-mod.mjs":"02d86b0cdddf39879efc5194c0a5be6b41456faedec28963dc123a4e88dc3942","commit-rules.mjs":"e94cc32a5415f6d9e978145ab9505ac4ae0bac9431e6e9104b9b37155260b51f","config-edits.mjs":"0eba2f176ef6f7afba071d6e00de0ff19ba2b283180a801dfd957aa38c1edd94","count-behaviour.mjs":"179baf829eda488bab3f17ae6917473ec01d0d6346f47de7bc144351274f19c8","credential-store.mjs":"a4b3540a61f4ce19e535c7f1d260c0d817686cd066d559a76db2ab108144abba","credential-vault-scripts.mjs":"7e42fe1db3885c2dec6f1de87bebfbefe2292d29179a68f3da87d19eb6c7704b","credential-vault.mjs":"279baabb217e2a3f170e8d7f2b271a88484531f9031c441360ea91561a70da99","engine-release.json":"5d0bc51d24750c8ea15423f5625a8e27cfe352c88fe17c623ef0fc5f59bca2da","git-commits.mjs":"f9c084c54937a86df8fe30a0db2a58e04eeef0dbae69c54b8e368efc9964d6d8","history-outbox.mjs":"31609392f4e13dd37678ab3154bd2896cce1a8cca4903b78dd2d96da82b1f406","log-session.mjs":"9c78cadbc469f273367a438721fcc47ce101dc230b6c9a18fe0923960f471bc9","orchestration-contract.mjs":"ec08f303a166365b99e70b675de4cfe76c6156c2567e14b5569f6d992f0231b7","orchestration-evidence.mjs":"d0d06cecf0eb08e5c6e653c62a4f45b1eddf2119c2acb8341056b34f488d214a","orchestration-report.mjs":"d4e0a9ad8e4a01b462d22c6b1866aac291565c533ff476085d3367cb6d59bc1b","package-integrity.mjs":"a8210c9494a56bfb9a5ea3d10064c7a269f0b6330c0af7c0700e706c3c0224e3","package.json":"bb2bac211ec7f12913d860beb8a7b7733f926a361d575733951b0140f0409dec","preserve-lines.mjs":"2df64a69687aa51219bf7b86b88d175cc50990fa29574b31897e41a9ebeecf43","preserve-summary.mjs":"137f781ed7021596a3f0ea67afcf2ab8616ac293f833dbb8f176e838e0ed8321","preserve.mjs":"3e369083ba43bcda2fa0622fd526aa64fcf8ad66e7b6e8f23821752c4d47ad27","runtime-install.mjs":"aab47b52c79d726ef428a24f982c648fa3f1c2dc2b574f633611d02924864e5f","session-databases.mjs":"b9fe20d7445205bdbf4cf2eaaf9cc770dad01e23d41e644b04930ca34e10426d","setup-mcp.mjs":"dcaa912b0e15a74ab3365aa62f345ba436510b958e9f5cdceddd57ffb99ef4b7","stack-rules.mjs":"b23c56e72ec56ba02b17ed895f869172d988c468a697e8d6026b0e268f61e489","stretch-evidence.mjs":"5f5667b92adf11b1a5a6330a0f26dd6db73d56fe60823d9a5246dab71d27d380","transcript-readers.mjs":"e9f20415c2b5d62a09f35a63075002ebd1da56edb32f242d52822d58ecbd8ac3","worktrust-launch.mjs":"84801bd29d472d48188c126b9ebe3989a3132b54e13cc4fe534ff7c383a294ee","worktrust.mjs":"ff83a783504950cba6f62cb14786e504db701be6c324a44c3fefac26628f516d"},"format":"worktrust-package/1","kind":"npm","version":"0.10.36"},"signature":"t6KO1vCVVWp2XvOnCv6p7PTsCXQIrf3TeOComgkM9ePryMwd0NoNjNfrLY0PrF0-8zG7DxnUdGsqpeIW4mxKAg"}
1
+ {"keyId":"608168ccdef72562fc91f9c0f9f2c2d6876bece7f7362cb545b818f7947da6b5","payload":{"files":{"AGENTS.md":"e8abb38c293b57b71d3a6163d6242d1f375e773372b91b6d8ce39c584c51262a","CLAUDE.md":"5933504f93e5a40369a4790e96dd5dad791d849d3178b1833eb64088e456aaeb","LICENSE":"3096ed1693974a90e1f4f59bf01c9559d94a7941d933e36fb81d3995a97f25c1","README.md":"f603caa93e074200d8ebde79cfed1c6b884ac6a3079926a94536c71d21a3b538","SECURITY.md":"4f2b644d8a7ff87bd87d593f2bdff3f1149454151559f633fc16801cedff7dbe","chat-exports.mjs":"1dc109a971f88605ee3fa3a7564bcd57bce2047b86bfcd92eb3e5acf865d8f11","claude-mod.mjs":"02d86b0cdddf39879efc5194c0a5be6b41456faedec28963dc123a4e88dc3942","commit-rules.mjs":"e94cc32a5415f6d9e978145ab9505ac4ae0bac9431e6e9104b9b37155260b51f","config-edits.mjs":"527a7674f9d52b284bfda3b8089eb4b930a709bf14aedbec7f6eef1e59ef52ee","count-behaviour.mjs":"179baf829eda488bab3f17ae6917473ec01d0d6346f47de7bc144351274f19c8","credential-store.mjs":"a4b3540a61f4ce19e535c7f1d260c0d817686cd066d559a76db2ab108144abba","credential-vault-scripts.mjs":"7e42fe1db3885c2dec6f1de87bebfbefe2292d29179a68f3da87d19eb6c7704b","credential-vault.mjs":"279baabb217e2a3f170e8d7f2b271a88484531f9031c441360ea91561a70da99","engine-release.json":"0e766c012881c228e0472ec3426620e0d1e4e01d5668f6f33d3c60e4a0e0ed1b","git-commits.mjs":"f9c084c54937a86df8fe30a0db2a58e04eeef0dbae69c54b8e368efc9964d6d8","history-outbox.mjs":"85c70389effc5b4ec9d9b33af9192314e67f47af2752515b42a7959344ce2354","history-progress.mjs":"dcc25ee94b727f2605a763349a4d8764640335d6cf0043fb6108cebeed16dcb9","log-session.mjs":"f7e8f247edcc5a3ad17c2c05b83452a938d0e9e20cde5f806a54c1fb04f28958","orchestration-contract.mjs":"ec08f303a166365b99e70b675de4cfe76c6156c2567e14b5569f6d992f0231b7","orchestration-evidence.mjs":"d0d06cecf0eb08e5c6e653c62a4f45b1eddf2119c2acb8341056b34f488d214a","orchestration-report.mjs":"d4e0a9ad8e4a01b462d22c6b1866aac291565c533ff476085d3367cb6d59bc1b","package-integrity.mjs":"a8210c9494a56bfb9a5ea3d10064c7a269f0b6330c0af7c0700e706c3c0224e3","package.json":"fb98ed631188c3ffe3d516646056408556899c74368e1d7d517c68837b79b84a","preserve-lines.mjs":"2df64a69687aa51219bf7b86b88d175cc50990fa29574b31897e41a9ebeecf43","preserve-summary.mjs":"137f781ed7021596a3f0ea67afcf2ab8616ac293f833dbb8f176e838e0ed8321","preserve.mjs":"cd111cae0f53a25a2d878a158479abfb1ace353361454843f91a16d241101d46","runtime-install.mjs":"aab47b52c79d726ef428a24f982c648fa3f1c2dc2b574f633611d02924864e5f","self-update.mjs":"378e3620d48c72cf0bf812be408883b995cdb2223de34a20f762dd73eeffb258","session-databases.mjs":"b9fe20d7445205bdbf4cf2eaaf9cc770dad01e23d41e644b04930ca34e10426d","setup-mcp.mjs":"b732e3dd9b3e522b7cc8acf167ce28ba8f1a8dee797ee15bd7c3b02919b13e6f","stack-rules.mjs":"b23c56e72ec56ba02b17ed895f869172d988c468a697e8d6026b0e268f61e489","stretch-evidence.mjs":"5f5667b92adf11b1a5a6330a0f26dd6db73d56fe60823d9a5246dab71d27d380","transcript-readers.mjs":"e9f20415c2b5d62a09f35a63075002ebd1da56edb32f242d52822d58ecbd8ac3","worktrust-launch.mjs":"84801bd29d472d48188c126b9ebe3989a3132b54e13cc4fe534ff7c383a294ee","worktrust.mjs":"c417a0cabf02318cb3200bda514a3d4ca39dc95f5528d36ff59307f2f045b839"},"format":"worktrust-package/1","kind":"npm","version":"0.10.37"},"signature":"XHc9pXa0YEZrsLz9bB4Zy9AMprpIipFsGNpGUbefQwzJpqPHhqOjN4ch5rXJcGb1JZBxIiqq_FMKGK25EZQZBA"}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "worktrust",
3
- "version": "0.10.36",
3
+ "version": "0.10.37",
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": {
@@ -39,7 +39,9 @@
39
39
  "history-outbox.mjs",
40
40
  "credential-store.mjs",
41
41
  "credential-vault.mjs",
42
- "credential-vault-scripts.mjs"
42
+ "credential-vault-scripts.mjs",
43
+ "self-update.mjs",
44
+ "history-progress.mjs"
43
45
  ],
44
46
  "engines": {
45
47
  "node": ">=18"
package/preserve.mjs CHANGED
@@ -287,8 +287,8 @@ function archive(dir) {
287
287
  IDS = computerIds();
288
288
  const existing = existsSync(join(dir, "manifest.json")) || readArchive(dir).length > 0 ? check(dir) : { lines: [], manifest: null };
289
289
  if (existing.broken) { say(` The archive in ${dir} does not verify, so nothing was added: ${existing.broken}`); process.exit(1); }
290
- const hook = spawnSync(moduleExecutable(HERE), moduleArgs(HERE, "log-session.mjs", ["--archive-lines"]), { encoding: "utf8", maxBuffer: 1 << 29, env: { ...process.env, WORKTRUST_MCP_URL: "", WORKTRUST_MCP_TOKEN: "", WORKTRUST_HOOK_INPUT: "" } });
291
- if (hook.status !== 0) { say(` The session hook could not read this computer's sessions: ${(hook.stderr || "").trim().split("\n").pop()}`); process.exit(1); }
290
+ const hook = spawnSync(moduleExecutable(HERE), moduleArgs(HERE, "log-session.mjs", ["--archive-lines"]), { encoding: "utf8", maxBuffer: 1 << 29, stdio: ["ignore", "pipe", "inherit"], env: { ...process.env, WORKTRUST_MCP_URL: "", WORKTRUST_MCP_TOKEN: "", WORKTRUST_HOOK_INPUT: "", WORKTRUST_HISTORY_PROGRESS: "stderr" } });
291
+ if (hook.status !== 0) { if (hook.signal) { say(" Stopped while reading this computer's sessions: nothing was added. Run the same command again to keep them."); process.exit(130); } say(" The session hook could not read this computer's sessions; nothing was added."); process.exit(1); }
292
292
  // A WHOLE ANSWER OR NOTHING: the hook ends with its own count; one line missing or cut is a read to refuse, never part of an archive.
293
293
  const rows = hook.stdout.split("\n").filter(Boolean), end = (() => { try { return JSON.parse(rows.at(-1) ?? "").archive_end; } catch { return undefined; } })();
294
294
  if (!Number.isInteger(end) || end !== rows.length - 1) { say(` The session hook's answer came back incomplete (${rows.length - 1} of ${end ?? "an unknown number of"} lines), so nothing was added. Run it again.`); process.exit(1); }
@@ -381,7 +381,8 @@ async function guided() {
381
381
  else if (!kept) say(write === null ? " Not a terminal: no archive written. Add --yes to agree in advance." : " No archive written.");
382
382
  if (existsSync(join(dir, "manifest.json"))) { say(); verifyArchive(dir); summary(dir); }
383
383
  }
384
-
384
+ process.on("SIGINT", stopped); process.on("SIGTERM", stopped); function stopped() { // STOPPING SAFELY (2026-11-05): the archive is written in one synchronous pass, so a Ctrl+C is handled after it, never inside it
385
+ say(" Stopped. What was kept so far stays in the archive, whole; run the same command again to keep the rest."); process.exit(130); }
385
386
  if (has("summary")) summary(folderAfter("summary"));
386
387
  else if (has("verify")) verifyArchive(folderAfter("verify"));
387
388
  else if (has("archive")) archive(folderAfter("archive"));
@@ -0,0 +1,274 @@
1
+ /**
2
+ * UPDATING ITSELF WHEN THE PERSON TURNS IT ON (owner, 2026-11-05; CLI 0.10.37). The ONE place this CLI installs code
3
+ * without a person typing a command, and only on that person's own act: turning CLI active back on for this computer in
4
+ * Sources (set_my_computer_measure, a resume from a pause this computer had confirmed). WorkTrust's door answer
5
+ * (api/cli/door) then carries a one-shot instruction `{ version, at }`: the version WorkTrust names from the published
6
+ * npm release, `at` the moment of that resume, which is the instruction's id. A version string alone never starts it:
7
+ * no instruction, no install, and the same id is never handled twice.
8
+ *
9
+ * WHAT RUNS, AND ONLY WHEN EVERYTHING HOLDS (SECURITY.md "Updating itself when you turn it on"):
10
+ * 1. the method: this CLI runs from the verified npm copy in ~/.worktrust/verified (the launcher checked it); Python
11
+ * installations and anything else update by the person's own command and report `python` / `unsupported`;
12
+ * 2. the version is NEWER than this CLI (never equal, never a downgrade: `current`);
13
+ * 3. npm beside the running Node (else the first on PATH) is 11.12.0 or later, the first that lists the attestations it
14
+ * verified (`audit signatures --include-attestations`); an older one is `unsupported` before anything is fetched;
15
+ * 4. THE COMPUTER'S OWN POLICY, not the server's (review M1): npm's registry record names <version> as `latest` and does
16
+ * not deprecate it (a version the console classes critical is deprecated on npm too: tools/worktrust-release/README);
17
+ * 5. `npm install --ignore-scripts` of exactly worktrust@<version> from registry.npmjs.org into a fresh staging folder
18
+ * (nothing of the package runs during install);
19
+ * 6. `npm audit signatures` there: the registry signature and the Sigstore attestations, verified BY NPM against its own
20
+ * trust roots and relayed here; the SLSA provenance's certificate must name
21
+ * github.com/fhomey/worktrust-cli/.github/workflows/publish.yml at tag v<version> and carry GitHub Actions' OIDC
22
+ * issuer in Fulcio's extension 1.3.6.1.4.1.57264.1.8, its DSSE signature verify under it, its subject be this exact
23
+ * tarball (sha512 of the lockfile);
24
+ * 7. WorkTrust's own release signature (package-release.json) under the key pinned in THIS CLI, naming <version>: the
25
+ * binding root, which needs neither npm's word nor WorkTrust's server;
26
+ * 8. only then: the verified copy is installed beside the current one, and the NEW launcher (which verifies itself
27
+ * again) runs `update --yes`: what was agreed before is refreshed, nothing new is coupled, no history is sent.
28
+ * A failed check leaves the running CLI as it is and reports a code (`unverified` or `failed`), never content, on the
29
+ * next door call. It runs detached from the hook, under a lock, and logs to ~/.worktrust/update.log on this computer only.
30
+ */
31
+ import { spawn } from "node:child_process";
32
+ import { X509Certificate, verify as verifySignature } from "node:crypto";
33
+ import { appendFileSync, closeSync, existsSync, mkdirSync, mkdtempSync, openSync, readFileSync, rmSync, statSync, writeFileSync } from "node:fs";
34
+ import { delimiter, dirname, isAbsolute, join } from "node:path";
35
+
36
+ /** The closed list of outcomes reported back as `worktrust-update/<code>.<id>` (mcp_identify knows the same list). */
37
+ export const UPDATE_RESULTS = ["installed", "current", "python", "unsupported", "unverified", "failed"];
38
+ export const REGISTRY = "https://registry.npmjs.org/";
39
+ export const REPOSITORY = "https://github.com/fhomey/worktrust-cli";
40
+ export const WORKFLOW = ".github/workflows/publish.yml";
41
+ export const OIDC_ISSUER = "https://token.actions.githubusercontent.com";
42
+ const SLSA = "https://slsa.dev/provenance/v1";
43
+ const VERSION = /^\d{1,4}\.\d{1,4}\.\d{1,4}$/;
44
+ /** An attempt that has not finished in half an hour died (a closed lid, a killed process): it counts as failed, once. */
45
+ const STALE_MS = 30 * 60_000;
46
+ /** The first npm whose `audit signatures --include-attestations` lists the bundles it verified (review M2). */
47
+ export const NPM_SINCE = "11.12.0";
48
+
49
+ /** Fulcio's OIDC issuer extension, 1.3.6.1.4.1.57264.1.8, as its DER OID bytes. */
50
+ const FULCIO_ISSUER_OID = Buffer.from([0x2b, 0x06, 0x01, 0x04, 0x01, 0x83, 0xbf, 0x30, 0x01, 0x08]);
51
+ /** One DER element at `at`: its tag, where its content starts and ends. Null when it does not fit. */
52
+ function der(bytes, at) {
53
+ if (at + 2 > bytes.length) return null;
54
+ const tag = bytes[at]; let length = bytes[at + 1], start = at + 2;
55
+ if (length & 0x80) { const count = length & 0x7f; if (count === 0 || count > 4 || start + count > bytes.length) return null; length = 0; for (let i = 0; i < count; i += 1) length = length * 256 + bytes[start + i]; start += count; }
56
+ return start + length > bytes.length ? null : { tag, start, end: start + length };
57
+ }
58
+ function children(bytes, item) { const out = []; for (let at = item.start; at < item.end;) { const child = der(bytes, at); if (!child) return null; out.push(child); at = child.end; } return out; }
59
+ /** The issuer Fulcio wrote into the certificate's own extension (a DER UTF8String), or null: never a byte string elsewhere. */
60
+ export function fulcioIssuer(raw) {
61
+ const certificate = der(raw, 0), tbs = certificate && children(raw, certificate)?.[0];
62
+ const holder = tbs && children(raw, tbs)?.find((item) => item.tag === 0xa3);
63
+ const list = holder && children(raw, holder)?.[0];
64
+ const found = [];
65
+ for (const extension of (list && children(raw, list)) ?? []) {
66
+ const parts = children(raw, extension);
67
+ if (!parts || parts[0]?.tag !== 0x06 || !raw.subarray(parts[0].start, parts[0].end).equals(FULCIO_ISSUER_OID)) continue;
68
+ const octets = parts.at(-1), value = octets?.tag === 0x04 ? der(raw, octets.start) : null;
69
+ found.push(value?.tag === 0x0c && value.end === octets.end ? raw.subarray(value.start, value.end).toString("utf8") : null);
70
+ }
71
+ return found.length === 1 ? found[0] : null;
72
+ }
73
+
74
+ export function newerThan(a, b) {
75
+ const x = a.split(".").map(Number), y = b.split(".").map(Number);
76
+ for (let i = 0; i < 3; i += 1) if (x[i] !== y[i]) return x[i] > y[i];
77
+ return false;
78
+ }
79
+
80
+ /** The instruction in a door answer, `{ id, version }`, or null: an id is the resume moment in whole seconds. */
81
+ export function updateOffer(update) {
82
+ if (!update || typeof update !== "object" || typeof update.version !== "string" || !VERSION.test(update.version) || typeof update.at !== "string") return null;
83
+ const id = Math.floor(Date.parse(update.at) / 1000);
84
+ return Number.isSafeInteger(id) && id > 0 ? { id, version: update.version } : null;
85
+ }
86
+
87
+ /**
88
+ * THE ONE DECISION, given an instruction (tools/worktrust-release/update-policy.mjs `resumePolicy` says the same;
89
+ * scripts/test-cli-self-update.mjs holds them equal). Only the verified npm copy installs, and only a newer version.
90
+ */
91
+ export function resumeDecision({ method, current, version }) {
92
+ if (!VERSION.test(version ?? "") || !VERSION.test(current ?? "")) return { install: false, outcome: "failed" };
93
+ if (!newerThan(version, current)) return { install: false, outcome: "current" };
94
+ if (method === "npm") return { install: true, outcome: null };
95
+ if (method === "python") return { install: false, outcome: "python" };
96
+ return { install: false, outcome: "unsupported" };
97
+ }
98
+
99
+ /** The outcome to report for the state kept in update.json; null while an attempt waits or runs. */
100
+ export function updateResult(state, now = Date.now()) {
101
+ if (!state || !Number.isSafeInteger(state.id)) return null;
102
+ if (UPDATE_RESULTS.includes(state.state)) return state.state;
103
+ if (["pending", "running"].includes(state.state) && !(now - Date.parse(state.at ?? "") <= STALE_MS)) return "failed";
104
+ return null;
105
+ }
106
+
107
+ /**
108
+ * WHAT NPM VERIFIED, BOUND TO OUR PUBLISHER. npm has already checked the registry signature and the attestation bundles
109
+ * (certificate chain to Sigstore's root, transparency log, signatures); this names whose they are. Null when everything
110
+ * holds, else a short reason for the local log (never sent).
111
+ */
112
+ export function provenanceProblem({ audit, auditCode, lock, version }) {
113
+ if (auditCode !== 0) return "audit-exit";
114
+ if (!audit || !Array.isArray(audit.invalid) || !Array.isArray(audit.missing) || audit.invalid.length > 0 || audit.missing.length > 0) return "audit-invalid";
115
+ const packages = lock?.packages;
116
+ if (!packages || typeof packages !== "object" || Object.keys(packages).sort().join(",") !== ",node_modules/worktrust") return "lock-shape";
117
+ const entry = packages["node_modules/worktrust"];
118
+ if (entry?.version !== version || entry.resolved !== `${REGISTRY}worktrust/-/worktrust-${version}.tgz` || !/^sha512-[A-Za-z0-9+/]{86}==$/.test(entry.integrity ?? "")) return "lock-entry";
119
+ const digest = Buffer.from(entry.integrity.slice(7), "base64").toString("hex");
120
+ const verified = (Array.isArray(audit.verified) ? audit.verified : []).filter((one) => one?.name === "worktrust" && one.version === version && one.location === "node_modules/worktrust");
121
+ if (verified.length !== 1) return "not-verified";
122
+ const bundles = (Array.isArray(verified[0].attestationBundles) ? verified[0].attestationBundles : []).filter((one) => one?.predicateType === SLSA);
123
+ if (bundles.length !== 1) return "no-provenance";
124
+ const bundle = bundles[0].bundle;
125
+ const raw = bundle?.verificationMaterial?.certificate?.rawBytes ?? bundle?.verificationMaterial?.x509CertificateChain?.certificates?.[0]?.rawBytes;
126
+ let certificate;
127
+ try { certificate = new X509Certificate(Buffer.from(String(raw), "base64")); } catch { return "certificate"; }
128
+ if (certificate.subjectAltName !== `URI:${REPOSITORY}/${WORKFLOW}@refs/tags/v${version}`) return "identity";
129
+ if (fulcioIssuer(certificate.raw) !== OIDC_ISSUER) return "issuer";
130
+ const envelope = bundle.dsseEnvelope;
131
+ if (envelope?.payloadType !== "application/vnd.in-toto+json" || typeof envelope.payload !== "string" || !Array.isArray(envelope.signatures) || envelope.signatures.length !== 1) return "envelope";
132
+ const body = Buffer.from(envelope.payload, "base64");
133
+ const signedBytes = Buffer.concat([Buffer.from(`DSSEv1 ${Buffer.byteLength(envelope.payloadType)} ${envelope.payloadType} ${body.length} `), body]);
134
+ let signed = false;
135
+ try { signed = verifySignature("sha256", signedBytes, certificate.publicKey, Buffer.from(String(envelope.signatures[0].sig), "base64")); } catch { signed = false; }
136
+ if (!signed) return "signature";
137
+ let statement;
138
+ try { statement = JSON.parse(body.toString("utf8")); } catch { return "statement"; }
139
+ if (statement?.predicateType !== SLSA || !Array.isArray(statement.subject) || statement.subject.length !== 1) return "statement";
140
+ const [subject] = statement.subject;
141
+ if (subject?.name !== `pkg:npm/worktrust@${version}` || subject.digest?.sha512 !== digest) return "subject";
142
+ const workflow = statement.predicate?.buildDefinition?.externalParameters?.workflow;
143
+ if (workflow?.repository !== REPOSITORY || workflow.path !== WORKFLOW || workflow.ref !== `refs/tags/v${version}`) return "workflow";
144
+ return null;
145
+ }
146
+
147
+ /**
148
+ * npm: the one beside the running Node first (its own installation: <prefix>/lib/node_modules/npm, or on Windows
149
+ * <dir>/node_modules/npm), run under this Node; else the first on PATH (absolute directories only). On Windows the
150
+ * npm-cli.js runs under this Node: a .cmd needs a shell.
151
+ */
152
+ export function findNpm(env = process.env, platform = process.platform, node = process.execPath) {
153
+ const beside = platform === "win32" ? join(dirname(node), "node_modules", "npm", "bin", "npm-cli.js") : join(dirname(node), "..", "lib", "node_modules", "npm", "bin", "npm-cli.js");
154
+ if (existsSync(beside)) return { command: node, prefix: [beside] };
155
+ for (const dir of String(env.PATH ?? env.Path ?? "").split(delimiter).filter((one) => one && isAbsolute(one))) {
156
+ if (platform === "win32") {
157
+ const cli = join(dir, "node_modules", "npm", "bin", "npm-cli.js");
158
+ if (existsSync(join(dir, "npm.cmd")) && existsSync(cli)) return { command: process.execPath, prefix: [cli] };
159
+ } else if (existsSync(join(dir, "npm"))) return { command: join(dir, "npm"), prefix: [] };
160
+ }
161
+ return null;
162
+ }
163
+
164
+ function runProcess(command, args, { env, cwd, timeout }) {
165
+ return new Promise((resolve) => {
166
+ let out = "", err = "", settled = false;
167
+ const finish = (code) => { if (!settled) { settled = true; clearTimeout(timer); resolve({ code, out, err }); } };
168
+ let child;
169
+ try { child = spawn(command, args, { cwd, env, stdio: ["ignore", "pipe", "pipe"], windowsHide: true }); } catch { resolve({ code: -1, out, err }); return; }
170
+ const timer = setTimeout(() => { try { child.kill("SIGKILL"); } catch { /* gone */ } }, timeout);
171
+ child.stdout.on("data", (chunk) => { if (out.length < 8 << 20) out += chunk; });
172
+ child.stderr.on("data", (chunk) => { if (err.length < 65536) err += chunk; });
173
+ child.on("error", () => finish(-1));
174
+ child.on("close", (code) => finish(code ?? -1));
175
+ });
176
+ }
177
+
178
+ /** One line per event, on this computer only: versions, codes and a short reason; never a key or a path of the person's. */
179
+ function logger(home) {
180
+ const file = join(home, "update.log");
181
+ return (...words) => {
182
+ try {
183
+ if (existsSync(file) && statSync(file).size > 256 * 1024) writeFileSync(file, readFileSync(file, "utf8").slice(-64 * 1024), { mode: 0o600 });
184
+ appendFileSync(file, `${new Date().toISOString()} ${words.join(" ").replace(/[\u0000-\u001f\u007f]/g, " ").slice(0, 600)}\n`, { mode: 0o600 });
185
+ } catch { /* a log that cannot be written changes nothing */ }
186
+ };
187
+ }
188
+
189
+ function takeLock(path) {
190
+ for (let tries = 0; tries < 2; tries += 1) {
191
+ try { closeSync(openSync(path, "wx", 0o600)); return () => rmSync(path, { force: true }); }
192
+ catch (error) {
193
+ if (error?.code !== "EEXIST") return null;
194
+ try { if (Date.now() - statSync(path).mtimeMs > STALE_MS) { rmSync(path, { force: true }); continue; } } catch { continue; }
195
+ return null;
196
+ }
197
+ }
198
+ return null;
199
+ }
200
+
201
+ /**
202
+ * The detached run the hook starts (`worktrust self-update`). `options`: home (~/.worktrust), method ("npm" | "python" |
203
+ * "unknown"), current (this CLI's version), readState / saveState (update.json), verifyPackage / installSignedPackage
204
+ * (this CLI's package-integrity, its pinned release key), nodeArgs (Node flags for the new launcher), agentEnv (the agent
205
+ * markers left out of the update's environment), env.
206
+ */
207
+ export async function runSelfUpdate(options) {
208
+ const { home } = options;
209
+ const release = takeLock(join(home, "update.lock"));
210
+ if (!release) return null;
211
+ const log = logger(home);
212
+ try {
213
+ const state = options.readState();
214
+ if (state?.state !== "pending" || !Number.isSafeInteger(state.id)) return null;
215
+ // COMPARE AND SET (review L4): an outcome is written only while the stored instruction is still the one that started.
216
+ const save = (next) => { if (options.readState()?.id === state.id) options.saveState(next); };
217
+ // CONSUMED BEFORE ANYTHING RUNS: whatever happens next, this instruction is never taken again.
218
+ save({ state: "running", at: new Date().toISOString() });
219
+ log("start", `id=${state.id}`, `from=${options.current}`, `to=${state.version}`, `method=${options.method}`);
220
+ let outcome;
221
+ try { outcome = await attempt(options, state.version, log); } catch (error) { log("error", String(error?.message ?? error).slice(0, 200)); outcome = "failed"; }
222
+ save({ state: outcome, at: new Date().toISOString() });
223
+ log("result", outcome);
224
+ return outcome;
225
+ } finally { release(); }
226
+ }
227
+
228
+ async function attempt(options, version, log) {
229
+ const decision = resumeDecision({ method: options.method, current: options.current, version });
230
+ if (!decision.install) return decision.outcome;
231
+ const env = options.env ?? process.env;
232
+ const npm = findNpm(env);
233
+ if (!npm) { log("no-npm"); return "unsupported"; }
234
+ const quiet = Object.fromEntries(Object.entries(env).filter(([name]) => !(options.agentEnv ?? []).includes(name)));
235
+ const said = await runProcess(npm.command, [...npm.prefix, "--version"], { env: quiet, cwd: options.home, timeout: 30_000 });
236
+ const npmVersion = /^(\d{1,4}\.\d{1,4}\.\d{1,4})/.exec(said.out.trim())?.[1] ?? null;
237
+ if (said.code !== 0 || !npmVersion || newerThan(NPM_SINCE, npmVersion)) { log("unsupported", "npm-old", `npm=${npmVersion ?? "unknown"}`, `needs=${NPM_SINCE}`); return "unsupported"; }
238
+ // THE COMPUTER'S OWN POLICY (review M1): whatever the door names, only npm's `latest`, and never a deprecated version.
239
+ const viewed = await runProcess(npm.command, [...npm.prefix, "view", `worktrust@${version}`, "--json", `--registry=${REGISTRY}`], { env: quiet, cwd: options.home, timeout: 60_000 });
240
+ if (viewed.code !== 0) { log("view", `exit=${viewed.code}`, viewed.err.slice(-200)); return "failed"; }
241
+ let record = null;
242
+ try { record = JSON.parse(viewed.out); } catch { record = null; }
243
+ if (record?.version !== version || record?.["dist-tags"]?.latest !== version) { log("unverified", "not-latest", `latest=${String(record?.["dist-tags"]?.latest ?? "unknown").slice(0, 20)}`); return "unverified"; }
244
+ if (record.deprecated) { log("unverified", "deprecated"); return "unverified"; }
245
+ const stages = join(options.home, "update-stage");
246
+ mkdirSync(stages, { recursive: true, mode: 0o700 });
247
+ const stage = mkdtempSync(join(stages, "run-"));
248
+ try {
249
+ writeFileSync(join(stage, "package.json"), `${JSON.stringify({ name: "worktrust-update-stage", version: "0.0.0", private: true })}\n`, { mode: 0o600 });
250
+ const common = ["--prefix", stage, `--registry=${REGISTRY}`];
251
+ const installed = await runProcess(npm.command, [...npm.prefix, "install", ...common, "--ignore-scripts", "--no-audit", "--no-fund", "--save-exact", `worktrust@${version}`], { env: quiet, cwd: stage, timeout: 180_000 });
252
+ if (installed.code !== 0) { log("install", `exit=${installed.code}`, installed.err.slice(-300)); return "failed"; }
253
+ const audited = await runProcess(npm.command, [...npm.prefix, "audit", "signatures", ...common, "--json", "--include-attestations"], { env: quiet, cwd: stage, timeout: 120_000 });
254
+ let audit = null, lock = null;
255
+ try { audit = JSON.parse(audited.out); } catch { audit = null; }
256
+ try { lock = JSON.parse(readFileSync(join(stage, "package-lock.json"), "utf8")); } catch { lock = null; }
257
+ const problem = provenanceProblem({ audit, auditCode: audited.code, lock, version });
258
+ if (problem) { log("unverified", problem); return "unverified"; }
259
+ const unpacked = join(stage, "node_modules", "worktrust");
260
+ let launcher;
261
+ try {
262
+ const checked = options.verifyPackage(unpacked);
263
+ if (checked?.manifest?.version !== version) { log("unverified", "release-version"); return "unverified"; }
264
+ launcher = options.installSignedPackage(unpacked, options.home);
265
+ } catch (error) { log("unverified", String(error?.message ?? "release-signature").slice(0, 80)); return "unverified"; }
266
+ // THE NEW CLI DOES THE SWITCH, as `npx worktrust update --yes` would: agreed entries refreshed, nothing new coupled.
267
+ const switched = await runProcess(process.execPath, [...(options.nodeArgs ?? []), launcher, "update", "--yes"], { env: { ...quiet, WORKTRUST_RELAYED: "1" }, cwd: options.home, timeout: 600_000 });
268
+ if (switched.code !== 0) { log("switch", `exit=${switched.code}`, switched.err.slice(-300)); return "failed"; }
269
+ return "installed";
270
+ } finally {
271
+ // A folder that cannot be removed now (Windows: a file still open, EBUSY) changes no outcome (review L5).
272
+ try { rmSync(stage, { recursive: true, force: true }); } catch (error) { log("cleanup", String(error?.code ?? "error")); }
273
+ }
274
+ }
package/setup-mcp.mjs CHANGED
@@ -19,7 +19,7 @@ import { existsSync, mkdirSync, readFileSync, readdirSync, rmSync, writeFileSync
19
19
  import { spawnSync } from "node:child_process";
20
20
  import { homedir, platform } from "node:os";
21
21
  import { dirname, join } from "node:path";
22
- import { isWorkTrustDoor, placeUnder, takeOut } from "./config-edits.mjs";
22
+ import { doorSnapshot, isWorkTrustDoor, placeUnder, putDoorsBack, takeOut } from "./config-edits.mjs";
23
23
 
24
24
  const args = process.argv.slice(2);
25
25
  const value = (name) => { const i = args.indexOf(`--${name}`); return i >= 0 ? args[i + 1] : undefined; };
@@ -214,9 +214,9 @@ const CLIENTS = [
214
214
  { key: "claude", label: "Claude Code", present: () => existsSync(join(home, ".claude.json")), file: join(home, ".claude.json"), shape: "claude" },
215
215
  ];
216
216
 
217
+ if (args.includes("--snapshot") || args.includes("--restore")) { if (args.includes("--snapshot")) console.log(JSON.stringify(doorSnapshot([...CLIENTS.filter((client) => !["claude", "openclaw"].includes(client.shape) && client.present()).map((client) => client.file), OPENCODE_PLUGIN], join(home, ".claude.json"), NAME))); else putDoorsBack(readFileSync(0, "utf8"), NAME, claudeOnPath() ? (verb) => runCommand("claude", verb).status === 0 : null); process.exit(0); } // a failed run's doors put back (security review L3; config-edits.mjs)
217
218
  console.log(`WorkTrust MCP ${REMOVE ? "removal" : "setup"} · door ${new URL(URL_).host} · token ${masked} · ${WRITE ? "WRITING" : "dry run — add --write to write"}`);
218
- let touched = 0;
219
- let standing = 0;
219
+ let touched = 0, standing = 0;
220
220
  for (const client of CLIENTS) {
221
221
  if (!client.present()) { console.log(` – ${client.label}: not on this machine`); continue; }
222
222
  if (SKIP.has(client.label)) { console.log(` · ${client.label}: left as it is (not agreed yet)`); continue; }