tryharness 0.7.45 → 0.7.54

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.
Files changed (125) hide show
  1. package/README.md +239 -14
  2. package/assets/dsh-plugin.mjs +72 -0
  3. package/assets/opencode-plugin.js +4 -3
  4. package/cli.mjs +497 -196
  5. package/lib/actorRoster.mjs +28 -5
  6. package/lib/adapters.mjs +165 -222
  7. package/lib/agentRuntimeConfig.mjs +36 -0
  8. package/lib/agentRuntimes.mjs +570 -0
  9. package/lib/agentSignIn.mjs +226 -0
  10. package/lib/atlas.mjs +7 -2
  11. package/lib/audit.mjs +643 -0
  12. package/lib/backupSetup.mjs +141 -0
  13. package/lib/boardAccess.mjs +8 -1
  14. package/lib/boardBackup.mjs +283 -0
  15. package/lib/boardCommands.mjs +5 -10
  16. package/lib/boardFileCommands.mjs +2 -1
  17. package/lib/boardMirror.mjs +523 -0
  18. package/lib/boardProtocol.json +263 -6
  19. package/lib/boardTools.mjs +2 -6
  20. package/lib/boardWaits.mjs +102 -0
  21. package/lib/book.mjs +659 -0
  22. package/lib/bridge.mjs +26 -4
  23. package/lib/browserWake.mjs +60 -0
  24. package/lib/cards.mjs +159 -16
  25. package/lib/cloudBoot.mjs +124 -0
  26. package/lib/commands.mjs +25 -5
  27. package/lib/connectionTools.d.ts +13 -0
  28. package/lib/connectionTools.js +45 -0
  29. package/lib/connectorAuth.mjs +309 -0
  30. package/lib/connectorCatalog.json +41 -0
  31. package/lib/connectorCommands.mjs +121 -0
  32. package/lib/connectorGoogle.mjs +513 -0
  33. package/lib/connectors.mjs +805 -0
  34. package/lib/context.mjs +18 -4
  35. package/lib/contractGate.mjs +377 -0
  36. package/lib/coordinator.mjs +152 -39
  37. package/lib/coreModels.mjs +78 -0
  38. package/lib/daemon.mjs +973 -54
  39. package/lib/desk.mjs +239 -0
  40. package/lib/desktop.mjs +113 -8
  41. package/lib/digest.mjs +32 -0
  42. package/lib/directLink.mjs +283 -0
  43. package/lib/environments.mjs +825 -0
  44. package/lib/folders.mjs +4 -4
  45. package/lib/gitHost.mjs +174 -0
  46. package/lib/goalCommands.mjs +58 -14
  47. package/lib/hookDialects.mjs +298 -0
  48. package/lib/inference.mjs +263 -152
  49. package/lib/landed.mjs +887 -0
  50. package/lib/lessons.mjs +6 -0
  51. package/lib/lineup.mjs +324 -0
  52. package/lib/live.mjs +284 -13
  53. package/lib/localmodels.mjs +10 -0
  54. package/lib/machineIdentity.mjs +3 -0
  55. package/lib/machineRoutes.mjs +40 -2
  56. package/lib/machineRuns.mjs +30 -3
  57. package/lib/machineSeal.mjs +69 -10
  58. package/lib/mcp-stdio.mjs +189 -120
  59. package/lib/mcpRelay.mjs +119 -0
  60. package/lib/members.json +26 -0
  61. package/lib/members.mjs +33 -0
  62. package/lib/modelMemory.mjs +100 -0
  63. package/lib/models.mjs +48 -15
  64. package/lib/museSession.mjs +122 -0
  65. package/lib/nativeHost.mjs +203 -0
  66. package/lib/neovim.mjs +126 -0
  67. package/lib/network.mjs +7 -2
  68. package/lib/nudge.mjs +57 -18
  69. package/lib/onboard.mjs +430 -1
  70. package/lib/oneclawLocal.mjs +150 -0
  71. package/lib/ownMachines.mjs +828 -39
  72. package/lib/pairing.mjs +182 -0
  73. package/lib/paths.mjs +8 -0
  74. package/lib/personModel.mjs +89 -0
  75. package/lib/phones.mjs +119 -3
  76. package/lib/placeCommands.mjs +27 -0
  77. package/lib/places.mjs +337 -9
  78. package/lib/plans.mjs +151 -27
  79. package/lib/profile.mjs +152 -0
  80. package/lib/projects.mjs +624 -137
  81. package/lib/readiness.mjs +400 -0
  82. package/lib/record.mjs +115 -0
  83. package/lib/repoLinks.mjs +354 -0
  84. package/lib/roomChannels.mjs +641 -0
  85. package/lib/runBrief.mjs +32 -2
  86. package/lib/runRequests.mjs +157 -0
  87. package/lib/runWorker.mjs +37 -9
  88. package/lib/runner.mjs +74 -11
  89. package/lib/secretPatterns.json +55 -0
  90. package/lib/secrets.mjs +10 -27
  91. package/lib/seen.mjs +102 -0
  92. package/lib/service.mjs +11 -6
  93. package/lib/sessionControl.mjs +386 -96
  94. package/lib/sessionIndex.mjs +5 -3
  95. package/lib/specialties.json +74 -0
  96. package/lib/specialties.mjs +477 -0
  97. package/lib/specialtyKeys.d.ts +3 -0
  98. package/lib/specialtyKeys.js +58 -0
  99. package/lib/specialtyNotice.mjs +147 -0
  100. package/lib/specialtySnapshot.mjs +138 -0
  101. package/lib/store.mjs +829 -29
  102. package/lib/subagents.mjs +8 -4
  103. package/lib/swarm.mjs +483 -37
  104. package/lib/swarmMemory.mjs +947 -0
  105. package/lib/t3.mjs +56 -17
  106. package/lib/taskCommands.mjs +91 -13
  107. package/lib/taskRuns.mjs +68 -11
  108. package/lib/team.json +253 -144
  109. package/lib/team.mjs +538 -147
  110. package/lib/threadLine.mjs +116 -0
  111. package/lib/threadRuns.mjs +78 -12
  112. package/lib/threadView.mjs +66 -16
  113. package/lib/tokenizer.mjs +405 -0
  114. package/lib/ui.mjs +16 -2
  115. package/lib/usageTotals.mjs +148 -0
  116. package/lib/vault.mjs +1144 -0
  117. package/lib/vaultCloud.mjs +117 -0
  118. package/lib/vaultCommands.mjs +201 -0
  119. package/lib/vaultTools.d.ts +12 -0
  120. package/lib/vaultTools.js +42 -0
  121. package/lib/windowAsks.mjs +42 -0
  122. package/lib/workFocus.mjs +59 -0
  123. package/lib/workLinks.mjs +90 -0
  124. package/lib/worktrees.mjs +51 -13
  125. package/package.json +10 -5
package/lib/audit.mjs ADDED
@@ -0,0 +1,643 @@
1
+ import fs from "node:fs";
2
+ import { CLOUD_HOMED, MACHINE_RUNNERS, nameOf } from "./members.mjs";
3
+ import { receiptOfTransaction, receiptsForThread } from "./book.mjs";
4
+ import { offices } from "./specialties.mjs";
5
+ import { underperforming } from "./record.mjs";
6
+ import { namedFiles } from "./worktrees.mjs";
7
+
8
+ // The auditor (docs/swarm-organization.md, "The auditor"): whether work said to be done was done, after the fact.
9
+ //
10
+ // - Code, on every report, no model: each claim a report makes in its structured fields (report_task's `claims`) is
11
+ // compared with what the board recorded: the run's receipt (receipts.mjs), the sub-pieces still open, the chain
12
+ // receipts filed in the book, whether its change is committed on its thread's branch, and whether the agent was
13
+ // answering when the work was assigned. A claim made only in the report's words is not audited: code never reads
14
+ // intent from prose (owner's rule). The result goes in board_tasks.audit, and the record (record.mjs) reads a report
15
+ // whose claims its receipts do not bear out as rejected.
16
+ // A mismatch is against the agent, or against the dispatcher when the dispatcher routed work to an agent that was
17
+ // not answering; only the agent's count toward `ok`.
18
+ // - An agent, weekly: a read-only task for the appointed auditor with the week's record and Harness's routing. Its one
19
+ // short report goes straight to the person (board.audit.week), never through the liaison and never as a notice: the
20
+ // liaison is Jev, and the auditor audits Jev.
21
+
22
+ export const CLAIM_TESTS = ["passed", "failed", "not_run"];
23
+ // How long a finished run's receipt may take to be read from its session file (runWorker.mjs receiptFor) before a
24
+ // claim that needs it is audited without it.
25
+ const RECEIPT_WAIT_MS = 15 * 60_000;
26
+ // Spend reported within a cent and a percent of what was settled is the same spend.
27
+ const SPEND_SLACK = (settledUsd) => 0.01 + settledUsd * 0.01;
28
+ const WEEK_MS = 7 * 24 * 60 * 60_000;
29
+ // Node's timers stop while the Mac sleeps, so the wall clock is read on a short poll (schedules.mjs does the same).
30
+ const POLL_MS = 30 * 60_000;
31
+ const SWEEP_MS = 60_000;
32
+ const REPORTED = ["done", "failed"];
33
+ const NOT_RUNS = ["goal", "group"];
34
+ const WEEK_LAST = "audit-week-last";
35
+ const WEEK_REPORT = "audit-week-report";
36
+ const BRIEF_LINES = 40;
37
+
38
+ const usd = (value) => `$${Number(value).toFixed(2)}`;
39
+ const plural = (count, word) => `${count} ${word}${count === 1 ? "" : "s"}`;
40
+
41
+ /** A report's structured claims, checked to the shape the audit reads, or null when it makes none. */
42
+ export function claimsOf(raw) {
43
+ if (!raw || typeof raw !== "object") return null;
44
+ const claims = {};
45
+ if (CLAIM_TESTS.includes(raw.tests)) claims.tests = raw.tests;
46
+ if (Array.isArray(raw.files_changed))
47
+ claims.files_changed = raw.files_changed
48
+ .filter((file) => typeof file === "string" && file.trim())
49
+ .slice(0, 100)
50
+ .map((file) => file.slice(0, 500));
51
+ if (Array.isArray(raw.sent))
52
+ claims.sent = raw.sent
53
+ .filter((sent) => sent && typeof sent === "object")
54
+ .slice(0, 20)
55
+ .map((sent) => ({
56
+ hash:
57
+ typeof sent.hash === "string" ? sent.hash.trim().slice(0, 120) : null,
58
+ chain: typeof sent.chain === "string" ? sent.chain.slice(0, 40) : null,
59
+ what: typeof sent.what === "string" ? sent.what.slice(0, 200) : null,
60
+ }));
61
+ const spent = Number(raw.spent_usd);
62
+ if (raw.spent_usd != null && Number.isFinite(spent) && spent >= 0)
63
+ claims.spent_usd = spent;
64
+ return Object.keys(claims).length ? claims : null;
65
+ }
66
+
67
+ const auditOf = (task) => {
68
+ if (!task?.audit) return null;
69
+ if (typeof task.audit === "object") return task.audit;
70
+ try {
71
+ return JSON.parse(task.audit);
72
+ } catch {
73
+ return null;
74
+ }
75
+ };
76
+
77
+ const writeAudit = (store, taskId, audit) =>
78
+ store.db.run("update board_tasks set audit = ? where id = ?", [
79
+ JSON.stringify(audit),
80
+ String(taskId),
81
+ ]);
82
+
83
+ /** Keeps a report's claims with its task, for the audit that follows the report. */
84
+ export function recordClaims(store, taskId, raw) {
85
+ const claims = claimsOf(raw);
86
+ if (!claims) return null;
87
+ const kept = auditOf(store.getTask(taskId));
88
+ writeAudit(store, taskId, { ...kept, claims });
89
+ return claims;
90
+ }
91
+
92
+ const receiptOf = (store, taskId) => {
93
+ try {
94
+ return JSON.parse(store.meta(`receipt:${taskId}`) || "null");
95
+ } catch {
96
+ return null;
97
+ }
98
+ };
99
+
100
+ const mismatch = (kind, detail, against = "agent") => ({
101
+ kind,
102
+ against,
103
+ detail,
104
+ });
105
+
106
+ // "Tests pass": a run whose receipt shows a passing test after its last change (or a passing test with nothing changed).
107
+ function auditTests(claims, receipt, waits) {
108
+ if (claims.tests !== "passed") return [];
109
+ if (!receipt)
110
+ return waits
111
+ ? "tests"
112
+ : [
113
+ mismatch(
114
+ "tests_not_recorded",
115
+ "Said the tests pass, but no test run is recorded for this work."
116
+ ),
117
+ ];
118
+ if (receipt.verdict === "tested") return [];
119
+ if (receipt.verdict === "no changes" && receipt.testOk === true) return [];
120
+ if (receipt.verdict === "tests failing")
121
+ return [
122
+ mismatch(
123
+ "tests_failing",
124
+ `Said the tests pass, but its last test after its last change, \`${receipt.test}\`, failed.`
125
+ ),
126
+ ];
127
+ return [
128
+ mismatch(
129
+ "tests_not_recorded",
130
+ "Said the tests pass, but no passing test after its last change is recorded."
131
+ ),
132
+ ];
133
+ }
134
+
135
+ // "Changed these files": a run whose receipt shows files changed.
136
+ function auditFiles(claims, receipt, waits) {
137
+ if (!claims.files_changed?.length) return [];
138
+ if (!receipt)
139
+ return waits
140
+ ? "files"
141
+ : [
142
+ mismatch(
143
+ "files_not_recorded",
144
+ `Said it changed ${plural(claims.files_changed.length, "file")}, but no run of it is recorded to show the change.`
145
+ ),
146
+ ];
147
+ return receipt.verdict === "no changes"
148
+ ? [
149
+ mismatch(
150
+ "no_files_changed",
151
+ `Said it changed ${plural(claims.files_changed.length, "file")}, but its run changed none.`
152
+ ),
153
+ ]
154
+ : [];
155
+ }
156
+
157
+ // "Sent": each send names its transaction, and a transaction Harness read on chain landed.
158
+ function auditSent(store, claims) {
159
+ return (claims.sent ?? []).flatMap((sent) => {
160
+ const what = sent.what ? ` ${sent.what}` : "";
161
+ if (!sent.hash)
162
+ return [
163
+ mismatch(
164
+ "sent_without_hash",
165
+ `Said it sent${what}, with no transaction hash.`
166
+ ),
167
+ ];
168
+ const filed = receiptOfTransaction(store, sent.hash);
169
+ if (filed && filed.operation.status !== "succeeded")
170
+ return [
171
+ mismatch(
172
+ "sent_not_confirmed",
173
+ `Said it sent${what} in ${sent.hash}, but Harness's read of the chain shows it ${String(filed.operation.status).replace(/_/g, " ")}.`
174
+ ),
175
+ ];
176
+ return [];
177
+ });
178
+ }
179
+
180
+ // Spend reported against what Harness settled against the person's limits for the thread's onchain work.
181
+ function auditSpend(store, task, claims) {
182
+ if (!(claims.spent_usd > 0)) return [];
183
+ const thread = task.parent_id ?? task.id;
184
+ const settledUsd =
185
+ receiptsForThread(store, thread).reduce(
186
+ (sum, receipt) => sum + (receipt.settledMicroUsd ?? 0),
187
+ 0
188
+ ) / 1_000_000;
189
+ if (!settledUsd)
190
+ return [
191
+ mismatch(
192
+ "spend_unreserved",
193
+ `Reported spending ${usd(claims.spent_usd)}, but nothing is recorded as settled against the person's limits for this work.`
194
+ ),
195
+ ];
196
+ return claims.spent_usd > settledUsd + SPEND_SLACK(settledUsd)
197
+ ? [
198
+ mismatch(
199
+ "spend_over_reserved",
200
+ `Reported spending ${usd(claims.spent_usd)}, more than the ${usd(settledUsd)} settled against the person's limits for this work.`
201
+ ),
202
+ ]
203
+ : [];
204
+ }
205
+
206
+ // "Made", for code: a run whose change git would not commit on its thread's branch (threadRuns.mjs) did not make it.
207
+ function auditCommitted(store, task) {
208
+ let left = null;
209
+ try {
210
+ left = JSON.parse(store.meta(`uncommitted:${task.id}`) || "null");
211
+ } catch {}
212
+ if (!left?.files?.length) return [];
213
+ return [
214
+ mismatch(
215
+ "not_committed",
216
+ `Its change is not committed on the thread's branch: ${namedFiles(left.files)}.`
217
+ ),
218
+ ];
219
+ }
220
+
221
+ function auditPieces(store, task) {
222
+ if (task.status !== "done") return [];
223
+ const open = store
224
+ .children(task.id)
225
+ .filter((child) => !["done", "failed", "unknown"].includes(child.status));
226
+ return open.length
227
+ ? [
228
+ mismatch(
229
+ "piece_open",
230
+ `Reported done while ${plural(open.length, "sub-piece")} ${open.length === 1 ? "is" : "are"} still open.`
231
+ ),
232
+ ]
233
+ : [];
234
+ }
235
+
236
+ /**
237
+ * Compares a reported task's claims with its receipts and writes the result to board_tasks.audit:
238
+ * `{ ok, mismatches: [{ kind, against: "agent" | "dispatcher", detail }], waiting, claims, at }`. `waiting` names claims
239
+ * whose receipt has not been read yet; they are audited again when it is. Null for a task that has not reported.
240
+ */
241
+ export function auditReport(store, taskId, { at = Date.now() } = {}) {
242
+ const task = store.getTask(taskId);
243
+ if (!task || !REPORTED.includes(task.status) || NOT_RUNS.includes(task.kind))
244
+ return null;
245
+ const kept = auditOf(task) ?? {};
246
+ const claims = kept.claims ?? {};
247
+ const receipt = receiptOf(store, task.id);
248
+ const reportedAt = Date.parse(task.reported_at || task.updated_at) || at;
249
+ // Only a run this computer started reads a receipt, and only for work that finished.
250
+ const receiptComing =
251
+ !receipt &&
252
+ task.status === "done" &&
253
+ MACHINE_RUNNERS.includes(task.target_agent) &&
254
+ Boolean(task.session_id && task.run_workspace) &&
255
+ at - reportedAt < RECEIPT_WAIT_MS;
256
+ const waiting = [];
257
+ const fromReceipt = [auditTests, auditFiles].flatMap((check) => {
258
+ const found = check(claims, receipt, receiptComing);
259
+ if (typeof found === "string") {
260
+ waiting.push(found);
261
+ return [];
262
+ }
263
+ return found;
264
+ });
265
+ const offline = store.meta(`assigned-offline:${task.id}`);
266
+ const mismatches = [
267
+ ...fromReceipt,
268
+ ...auditSent(store, claims),
269
+ ...auditSpend(store, task, claims),
270
+ ...auditCommitted(store, task),
271
+ ...auditPieces(store, task),
272
+ ...(offline
273
+ ? [
274
+ mismatch(
275
+ "assigned_offline",
276
+ `Assigned to ${nameOf(task.target_agent)} while ${offline}.`,
277
+ "dispatcher"
278
+ ),
279
+ ]
280
+ : []),
281
+ ];
282
+ const audit = {
283
+ ok: !mismatches.some((found) => found.against === "agent"),
284
+ mismatches,
285
+ waiting,
286
+ ...(Object.keys(claims).length ? { claims } : {}),
287
+ at: new Date(at).toISOString(),
288
+ };
289
+ writeAudit(store, task.id, audit);
290
+ return audit;
291
+ }
292
+
293
+ // ── Who audits weekly ──
294
+
295
+ /** Why an agent cannot hold the auditor office, or null. The dispatcher is never the auditor. */
296
+ export function auditorRefusal(
297
+ agentId,
298
+ { privacy = false, onMachine = () => false } = {}
299
+ ) {
300
+ const id = String(agentId || "");
301
+ if (!id || id === "user") return "the auditor is one of the person's agents";
302
+ if (id === "harness")
303
+ return "Harness is the dispatcher, and the auditor audits the dispatcher";
304
+ if (CLOUD_HOMED.includes(id))
305
+ return `${nameOf(id)} works on Harness's server and cannot read the board`;
306
+ if (privacy && !onMachine(id))
307
+ return `on the privacy setting only an agent on this computer audits, and ${nameOf(id)} is not one`;
308
+ return null;
309
+ }
310
+
311
+ // The agent the person appointed auditor (specialties.mjs offices), or null.
312
+ const appointedAuditor = (store) => {
313
+ const entry = offices(store).find((one) => one.id === "auditor");
314
+ return entry?.appointed ? entry.holder : null;
315
+ };
316
+
317
+ // The week's main makers: the agents with the most finished work, and the models it ran on.
318
+ function makersOf(store, since) {
319
+ const rows = store.db.all(
320
+ `select coalesce(claimed_by, target_agent) as agent, run_model, count(*) as n from board_tasks
321
+ where kind not in ('goal', 'group') and status = 'done' and reported_at >= ? group by 1, 2 order by n desc`,
322
+ [since]
323
+ );
324
+ const counts = new Map();
325
+ const models = new Set();
326
+ for (const row of rows) {
327
+ if (!row.agent) continue;
328
+ counts.set(row.agent, (counts.get(row.agent) ?? 0) + Number(row.n));
329
+ try {
330
+ const model = JSON.parse(row.run_model || "null")?.model;
331
+ if (model) models.add(String(model).toLowerCase());
332
+ } catch {}
333
+ }
334
+ const ranked = [...counts].sort((a, b) => b[1] - a[1]);
335
+ return {
336
+ agents: new Set(ranked.slice(0, 2).map(([agent]) => agent)),
337
+ models,
338
+ };
339
+ }
340
+
341
+ // ── The week's record, as the weekly auditor reads it ──
342
+
343
+ function weekRecord(store, since) {
344
+ const work = store.db.all(
345
+ `select coalesce(claimed_by, target_agent) as agent, status, count(*) as n from board_tasks
346
+ where kind not in ('goal', 'group') and status in ('done', 'failed') and reported_at >= ? group by 1, 2`,
347
+ [since]
348
+ );
349
+ const byAgent = new Map();
350
+ for (const row of work) {
351
+ if (!row.agent) continue;
352
+ const entry = byAgent.get(row.agent) ?? { done: 0, failed: 0 };
353
+ entry[row.status] += Number(row.n);
354
+ byAgent.set(row.agent, entry);
355
+ }
356
+ const marks = store.db
357
+ .all(
358
+ `select id, coalesce(claimed_by, target_agent) as agent, objective, audit from board_tasks
359
+ where audit is not null and reported_at >= ? order by reported_at`,
360
+ [since]
361
+ )
362
+ .flatMap((row) => {
363
+ const audit = auditOf(row);
364
+ return (audit?.mismatches ?? []).map(
365
+ (found) =>
366
+ `- ${row.id} (${nameOf(row.agent)}, ${found.against === "dispatcher" ? "the dispatcher's routing" : "its report"}): ${found.detail}`
367
+ );
368
+ });
369
+ const routing = store.db.all(
370
+ `select agent, action, count(*) as n from swarm_rounds where at >= ? group by agent, action order by n desc`,
371
+ [since]
372
+ );
373
+ const handedOn = routing
374
+ .filter((row) => row.action === "hand_on" && row.agent)
375
+ .map((row) => `${nameOf(row.agent)} ${row.n}`);
376
+ const undecided = routing
377
+ .filter((row) => row.action == null)
378
+ .reduce((sum, row) => sum + Number(row.n), 0);
379
+ const verdicts = store.db.all(
380
+ `select agent, verdict, count(*) as n from board_reactions where verdict != 'neither' and at >= ? group by agent, verdict`,
381
+ [since]
382
+ );
383
+ const receipts = store.db.all(
384
+ "select outcome, count(*) as n from book_receipts where filed_at >= ? group by outcome",
385
+ [since]
386
+ );
387
+ return {
388
+ work: [...byAgent].map(
389
+ ([agent, counts]) =>
390
+ `${nameOf(agent)} ${counts.done} done, ${counts.failed} failed`
391
+ ),
392
+ marks,
393
+ handedOn,
394
+ undecided,
395
+ verdicts: verdicts.map(
396
+ (row) => `${nameOf(row.agent)} ${row.verdict} ${row.n}`
397
+ ),
398
+ receipts: receipts.map((row) => `${row.outcome} ${row.n}`),
399
+ underperforming: underperforming(store).map(
400
+ (entry) =>
401
+ `${nameOf(entry.agent)} on ${entry.model}: ${entry.accepted} of ${entry.judged} ${entry.specialty} runs accepted`
402
+ ),
403
+ };
404
+ }
405
+
406
+ function weekBrief(record, from, to) {
407
+ const listed = (title, lines, none) => [
408
+ title,
409
+ ...(lines.length ? lines.slice(0, BRIEF_LINES) : [none]),
410
+ ...(lines.length > BRIEF_LINES
411
+ ? [`(and ${lines.length - BRIEF_LINES} more)`]
412
+ : []),
413
+ ];
414
+ return [
415
+ `The swarm's week from ${from.slice(0, 10)} to ${to.slice(0, 10)}, as the board recorded it. You are its auditor this week: read it for what code cannot see, such as work funnelled to one agent, checkers that never send anything back, the same reason for sending work back again and again (a rule the person might set), or specialties at odds with verdicts. Write one short report for the person, at most ten lines, each fact with the task or round it comes from. This is read-only: do not post work, change files or act on anything.`,
416
+ "",
417
+ ...listed("Work reported, by agent:", record.work, "No work was reported."),
418
+ "",
419
+ ...listed(
420
+ "Audit marks (code compared each report's claims with its receipts):",
421
+ record.marks,
422
+ "No marks."
423
+ ),
424
+ "",
425
+ ...listed(
426
+ "Harness's routing, work handed on by agent:",
427
+ record.handedOn,
428
+ "Harness handed nothing on."
429
+ ),
430
+ `Rounds no one decided: ${record.undecided}.`,
431
+ "",
432
+ ...listed(
433
+ "The person's verdicts, by agent:",
434
+ record.verdicts,
435
+ "No verdicts."
436
+ ),
437
+ "",
438
+ ...listed(
439
+ "Onchain receipts filed in the book, by outcome:",
440
+ record.receipts,
441
+ "No onchain work."
442
+ ),
443
+ "",
444
+ ...listed(
445
+ "Agents not living up to a specialty:",
446
+ record.underperforming,
447
+ "None."
448
+ ),
449
+ ].join("\n");
450
+ }
451
+
452
+ /**
453
+ * The auditor on this computer: every report audited as it lands (`changed`), receipts read late audited again, and
454
+ * the weekly task for the appointed auditor, whose report the person reads with board.audit.week.
455
+ */
456
+ export function createAuditor({
457
+ store,
458
+ log = () => {},
459
+ notifyBoard = () => {},
460
+ // Why an agent would not pick up work now ("it was not answering"), or null when it would.
461
+ offline = () => null,
462
+ privacy = () => false,
463
+ onMachine = () => false,
464
+ // Agents on this computer the daemon runs (installed and in the lineup), in the order to prefer.
465
+ runners = () => [],
466
+ // The model an agent runs on now, when known, so the default auditor is on a model other than the week's makers'.
467
+ modelOf = () => null,
468
+ // Only the computer that holds the board audits it.
469
+ holdsBoard = () => true,
470
+ folder,
471
+ now = Date.now,
472
+ }) {
473
+ /** Who audits this week: the person's appointment, else an agent off the week's main makers and their models. */
474
+ const auditor = () => {
475
+ const rules = { privacy: privacy(), onMachine };
476
+ const appointed = appointedAuditor(store);
477
+ if (appointed && !auditorRefusal(appointed, rules))
478
+ return { agent: appointed, how: "appointed" };
479
+ const since = new Date(now() - WEEK_MS).toISOString();
480
+ const makers = makersOf(store, since);
481
+ const candidates = runners().filter(
482
+ (agent) => !auditorRefusal(agent, rules)
483
+ );
484
+ const otherModel = (agent) =>
485
+ !makers.models.has(String(modelOf(agent) ?? "").toLowerCase());
486
+ const notMaker = candidates.filter((agent) => !makers.agents.has(agent));
487
+ const agent =
488
+ notMaker.find(otherModel) ?? notMaker[0] ?? candidates[0] ?? null;
489
+ return agent ? { agent, how: "default" } : { agent: null, how: null };
490
+ };
491
+
492
+ const weekTask = (task) => {
493
+ try {
494
+ return JSON.parse(store.meta(`audit-week:${task.id}`) || "null");
495
+ } catch {
496
+ return null;
497
+ }
498
+ };
499
+
500
+ /** Posts the week's audit task for the auditor, now. */
501
+ const postWeek = () => {
502
+ const holder = auditor();
503
+ if (!holder.agent)
504
+ return {
505
+ ok: false,
506
+ error: "no agent here can audit: appoint an auditor in the Swarm map",
507
+ };
508
+ const to = new Date(now()).toISOString();
509
+ const from = new Date(now() - WEEK_MS).toISOString();
510
+ const runs = runners().includes(holder.agent);
511
+ if (runs) fs.mkdirSync(folder, { recursive: true });
512
+ const task = store.postTask({
513
+ objective: `Weekly audit, ${from.slice(0, 10)} to ${to.slice(0, 10)}`,
514
+ brief: weekBrief(weekRecord(store, from), from, to),
515
+ originAgent: "harness",
516
+ targetAgent: holder.agent,
517
+ // The person's appointment is their go for this one read-only run; an agent that runs itself picks it up.
518
+ runWorkspace: runs ? folder : null,
519
+ runAuthorizedBy: runs ? "appointment" : null,
520
+ });
521
+ store.meta(`review:${task.id}`, "1");
522
+ store.meta(
523
+ `audit-week:${task.id}`,
524
+ JSON.stringify({ from, to, how: holder.how })
525
+ );
526
+ store.meta(WEEK_LAST, to);
527
+ log(`weekly audit posted for ${holder.agent} (${holder.how})`);
528
+ notifyBoard(store.getTask(task.id));
529
+ return { ok: true, task: store.getTask(task.id) };
530
+ };
531
+
532
+ // The auditor's report, kept for the person exactly as written.
533
+ const keepReport = (task, week) => {
534
+ const report = {
535
+ task: task.id,
536
+ from: week.from,
537
+ to: week.to,
538
+ agent: task.claimed_by ?? task.target_agent,
539
+ status: task.status,
540
+ text: String(task.result || ""),
541
+ at: task.reported_at,
542
+ };
543
+ store.meta(WEEK_REPORT, JSON.stringify(report));
544
+ return report;
545
+ };
546
+
547
+ /** A task changed (notifyBoard): its assignment noted, its report audited, the week's report kept. */
548
+ const changed = (task, previous) => {
549
+ if (!task || NOT_RUNS.includes(task.kind) || !holdsBoard()) return;
550
+ // Assigned now, to an agent that would not pick it up: the dispatcher's routing, audited with the report.
551
+ if (
552
+ !previous &&
553
+ task.status === "open" &&
554
+ task.target_agent &&
555
+ task.origin_agent !== "user" &&
556
+ now() - Date.parse(task.created_at) < 120_000 &&
557
+ !store.meta(`assigned-offline:${task.id}`)
558
+ ) {
559
+ const why = offline(task.target_agent);
560
+ if (why) store.meta(`assigned-offline:${task.id}`, why);
561
+ }
562
+ if (!REPORTED.includes(task.status)) return;
563
+ if (previous?.status === task.status && auditOf(task)?.at) return;
564
+ const audit = auditReport(store, task.id, { at: now() });
565
+ if (audit && !audit.ok)
566
+ log(
567
+ `audit of ${task.id}: ${audit.mismatches.map((found) => found.kind).join(", ")}`
568
+ );
569
+ const week = weekTask(task);
570
+ if (week) keepReport(store.getTask(task.id), week);
571
+ };
572
+
573
+ // Reports whose receipt was still being read are audited again once it is, or once it is too late to come.
574
+ const sweep = () => {
575
+ if (!holdsBoard()) return;
576
+ for (const row of store.db.all(
577
+ "select id from board_tasks where audit is not null and instr(audit, '\"waiting\":[]') = 0 and instr(audit, '\"waiting\":[') > 0"
578
+ ))
579
+ auditReport(store, row.id, { at: now() });
580
+ };
581
+
582
+ const due = () => {
583
+ const last = store.meta(WEEK_LAST);
584
+ // The first week counts from when the auditor first ran here.
585
+ if (!last) {
586
+ store.meta(WEEK_LAST, new Date(now()).toISOString());
587
+ return false;
588
+ }
589
+ return now() - Date.parse(last) >= WEEK_MS;
590
+ };
591
+ const tick = () => {
592
+ if (!holdsBoard() || !due()) return;
593
+ const posted = postWeek();
594
+ if (!posted.ok) log(`weekly audit: ${posted.error}`);
595
+ };
596
+ const weekTimer = setInterval(tick, POLL_MS);
597
+ weekTimer.unref?.();
598
+ const sweepTimer = setInterval(sweep, SWEEP_MS);
599
+ sweepTimer.unref?.();
600
+ setImmediate(tick);
601
+
602
+ /** The person's and agents' audit commands (board.audit.*). */
603
+ const command = (request, agent) => {
604
+ if (request.command === "board.audit.task") {
605
+ const task = store.getTask(String(request.id || ""));
606
+ if (!task) return { ok: false, error: "task not found" };
607
+ return { ok: true, audit: auditOf(task) };
608
+ }
609
+ if (request.command === "board.audit.week") {
610
+ // The weekly report is the person's, and reaches them without the liaison.
611
+ if (agent !== "user" || request.hostedCaller)
612
+ return { ok: false, error: "the weekly audit goes to the person" };
613
+ if (request.run === true) return postWeek();
614
+ let report = null;
615
+ try {
616
+ report = JSON.parse(store.meta(WEEK_REPORT) || "null");
617
+ } catch {}
618
+ return {
619
+ ok: true,
620
+ auditor: auditor(),
621
+ report,
622
+ last: store.meta(WEEK_LAST),
623
+ };
624
+ }
625
+ return { ok: false, error: `unknown audit command ${request.command}` };
626
+ };
627
+
628
+ return {
629
+ changed,
630
+ // A run's receipt was read after its report: the claims that waited for it are audited now.
631
+ receiptRead: (taskId) => {
632
+ if (holdsBoard()) auditReport(store, taskId, { at: now() });
633
+ },
634
+ command,
635
+ auditor,
636
+ postWeek,
637
+ sweep,
638
+ stop: () => {
639
+ clearInterval(weekTimer);
640
+ clearInterval(sweepTimer);
641
+ },
642
+ };
643
+ }