tryharness 0.7.53 → 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 (69) hide show
  1. package/README.md +10 -5
  2. package/assets/dsh-plugin.mjs +72 -0
  3. package/assets/opencode-plugin.js +4 -3
  4. package/cli.mjs +115 -36
  5. package/lib/adapters.mjs +157 -222
  6. package/lib/agentRuntimes.mjs +26 -16
  7. package/lib/agentSignIn.mjs +226 -0
  8. package/lib/audit.mjs +643 -0
  9. package/lib/backupSetup.mjs +141 -0
  10. package/lib/boardAccess.mjs +8 -1
  11. package/lib/boardBackup.mjs +283 -0
  12. package/lib/boardMirror.mjs +71 -7
  13. package/lib/boardProtocol.json +59 -2
  14. package/lib/boardWaits.mjs +102 -0
  15. package/lib/book.mjs +659 -0
  16. package/lib/bridge.mjs +1 -1
  17. package/lib/cards.mjs +138 -28
  18. package/lib/cloudBoot.mjs +124 -0
  19. package/lib/commands.mjs +7 -2
  20. package/lib/context.mjs +18 -4
  21. package/lib/contractGate.mjs +377 -0
  22. package/lib/coordinator.mjs +149 -43
  23. package/lib/daemon.mjs +349 -28
  24. package/lib/desk.mjs +239 -0
  25. package/lib/desktop.mjs +106 -6
  26. package/lib/environments.mjs +237 -7
  27. package/lib/folders.mjs +2 -2
  28. package/lib/gitHost.mjs +174 -0
  29. package/lib/hookDialects.mjs +298 -0
  30. package/lib/landed.mjs +887 -0
  31. package/lib/live.mjs +284 -13
  32. package/lib/mcp-stdio.mjs +68 -2
  33. package/lib/members.json +16 -2
  34. package/lib/models.mjs +8 -8
  35. package/lib/museSession.mjs +16 -13
  36. package/lib/nativeHost.mjs +1 -1
  37. package/lib/neovim.mjs +126 -0
  38. package/lib/nudge.mjs +47 -16
  39. package/lib/ownMachines.mjs +343 -39
  40. package/lib/pairing.mjs +27 -10
  41. package/lib/paths.mjs +4 -0
  42. package/lib/personModel.mjs +89 -0
  43. package/lib/phones.mjs +66 -11
  44. package/lib/places.mjs +330 -10
  45. package/lib/readiness.mjs +135 -18
  46. package/lib/record.mjs +115 -0
  47. package/lib/runWorker.mjs +17 -2
  48. package/lib/runner.mjs +8 -4
  49. package/lib/sessionControl.mjs +377 -89
  50. package/lib/specialties.json +74 -0
  51. package/lib/specialties.mjs +477 -0
  52. package/lib/specialtyKeys.d.ts +3 -0
  53. package/lib/specialtyKeys.js +58 -0
  54. package/lib/specialtyNotice.mjs +147 -0
  55. package/lib/specialtySnapshot.mjs +138 -0
  56. package/lib/store.mjs +284 -1
  57. package/lib/swarm.mjs +137 -21
  58. package/lib/t3.mjs +13 -4
  59. package/lib/taskCommands.mjs +36 -9
  60. package/lib/taskRuns.mjs +9 -2
  61. package/lib/team.json +255 -148
  62. package/lib/team.mjs +529 -188
  63. package/lib/threadLine.mjs +116 -0
  64. package/lib/threadRuns.mjs +75 -11
  65. package/lib/threadView.mjs +15 -2
  66. package/lib/worktrees.mjs +51 -13
  67. package/package.json +4 -4
  68. package/lib/modelTiers.json +0 -1183
  69. package/lib/modelTiers.mjs +0 -133
package/lib/book.mjs ADDED
@@ -0,0 +1,659 @@
1
+ import { randomUUID } from "node:crypto";
2
+ import { MEMBERS, nameOf } from "./members.mjs";
3
+ import { agentModelInUse } from "./models.mjs";
4
+ import { offices, pinnedFor, specialtiesOf } from "./specialties.mjs";
5
+
6
+ // The onchain desk's book (docs/swarm-organization.md, "The onchain desk"): the lasting record a trader cannot keep in
7
+ // its sessions. Per strategy it keeps the grant it sits under and why it was opened, its entry and exit conditions,
8
+ // positions, each decision and who took it, the research behind it, and the receipts of what ran on chain.
9
+ //
10
+ // - The book is personal. Its tables are board tables, carried by the encrypted board backup and copied to the
11
+ // person's other computers like the rest of the board (boardMirror.mjs MIRRORED), and never sent to Harness's server
12
+ // in the clear.
13
+ // - Any agent reads it. The treasurer writes it, and so may the person. The agent that executes onchain never keeps
14
+ // its own book (Decision 28), so it is never the treasurer, whoever is appointed.
15
+ // - Receipts are filed by code, from what Harness read on chain when Bankr reported (cloud_job's chain_receipt), never
16
+ // from an agent's words.
17
+ // - Bankr never gets the book. A Bankr ask in a thread linked to a strategy carries the ask, the strategy's high-level
18
+ // instructions (bookSliceFor) and the newest of the thread's history, within Bankr's request limit.
19
+
20
+ /** The book's tables, made with the board's own (store.mjs) so every computer's copy and the backup carry them. */
21
+ export const BOOK_TABLES = `
22
+ create table if not exists book_strategies (
23
+ id text primary key,
24
+ title text not null,
25
+ objective text not null default '',
26
+ reasons text not null default '',
27
+ instructions text not null default '',
28
+ entry text not null default '',
29
+ exit text not null default '',
30
+ grant_ref text,
31
+ grant_classes text not null default '[]',
32
+ grant_set_by text,
33
+ status text not null default 'active',
34
+ written_by text not null,
35
+ version integer not null default 1,
36
+ created_at text not null,
37
+ updated_at text not null
38
+ );
39
+ create table if not exists book_positions (
40
+ id text primary key,
41
+ strategy_id text not null,
42
+ asset text not null,
43
+ chain text,
44
+ size text,
45
+ status text not null default 'open',
46
+ why text not null default '',
47
+ receipt_id text,
48
+ opened_at text,
49
+ closed_at text,
50
+ written_by text not null,
51
+ version integer not null default 1,
52
+ created_at text not null,
53
+ updated_at text not null
54
+ );
55
+ create table if not exists book_decisions (
56
+ id text primary key,
57
+ strategy_id text not null,
58
+ task_id text,
59
+ decision text not null,
60
+ taken_by text not null,
61
+ approved_by text,
62
+ written_by text not null,
63
+ created_at text not null
64
+ );
65
+ create table if not exists book_research (
66
+ id text primary key,
67
+ strategy_id text not null,
68
+ title text not null,
69
+ ref text not null,
70
+ written_by text not null,
71
+ created_at text not null
72
+ );
73
+ create table if not exists book_threads (
74
+ thread_id text primary key,
75
+ strategy_id text not null,
76
+ written_by text not null,
77
+ created_at text not null
78
+ );
79
+ create table if not exists book_receipts (
80
+ id text primary key,
81
+ strategy_id text,
82
+ thread_id text,
83
+ outcome text not null,
84
+ operations text not null default '[]',
85
+ settled_micro_usd integer,
86
+ observed_usd real,
87
+ filed_by text not null default 'code',
88
+ filed_at text not null
89
+ );
90
+ create table if not exists book_contracts (
91
+ id text primary key,
92
+ strategy_id text not null,
93
+ name text not null,
94
+ chain text not null,
95
+ one_go integer not null default 0,
96
+ build_chain text,
97
+ build_task text,
98
+ source text,
99
+ runtime_code text,
100
+ code_sha256 text,
101
+ code_bytes integer,
102
+ check_by text,
103
+ check_model text,
104
+ check_sha256 text,
105
+ check_passed integer,
106
+ judge_by text,
107
+ judge_model text,
108
+ judge_sha256 text,
109
+ judge_accepted integer,
110
+ approved_by text,
111
+ approved_sha256 text,
112
+ deploy_task text,
113
+ address text,
114
+ deployed_sha256 text,
115
+ status text not null,
116
+ written_by text not null,
117
+ version integer not null default 1,
118
+ created_at text not null,
119
+ updated_at text not null
120
+ );
121
+ `;
122
+
123
+ /** The book's tables by their primary key, for the board's copies and its backup (boardMirror.mjs MIRRORED). */
124
+ export const BOOK_MIRRORED = {
125
+ book_strategies: ["id"],
126
+ book_positions: ["id"],
127
+ book_decisions: ["id"],
128
+ book_research: ["id"],
129
+ book_threads: ["thread_id"],
130
+ book_receipts: ["id"],
131
+ book_contracts: ["id"],
132
+ };
133
+
134
+ // Bankr's edge refuses a request body over 8 KiB (src/server/bankr/client.ts). The relay's part of an ask (the ask, the
135
+ // strategy's instructions and the thread's history) stays well under it, so Harness's own protocol text still fits and
136
+ // its server never has to condense away the strategy's instructions.
137
+ export const BANKR_ASK_BYTES = 6_144;
138
+ const SLICE_BYTES = 1_536;
139
+ const TEXT_CHARS = 4_000;
140
+ const INSTRUCTION_CHARS = 1_200;
141
+ const PORTFOLIO_RISK = "portfolio-risk";
142
+
143
+ const bytes = (text) => Buffer.byteLength(String(text), "utf8");
144
+ const now = () => new Date().toISOString();
145
+ const text = (value, limit = TEXT_CHARS) =>
146
+ typeof value === "string" ? value.trim().slice(0, limit) : "";
147
+
148
+ /** The longest start of `words` within `room` bytes, marked as cut. */
149
+ function cutTo(words, room) {
150
+ if (bytes(words) <= room) return words;
151
+ const mark = " …";
152
+ let end = words.length;
153
+ while (end > 0 && bytes(words.slice(0, end)) > room - bytes(mark)) end--;
154
+ return end > 0 ? `${words.slice(0, end).trimEnd()}${mark}` : "";
155
+ }
156
+
157
+ /** A history's opening line and its newest lines within `room` bytes (the server's newestOf, specialistBrief.ts). */
158
+ function newestLines(history, room) {
159
+ if (room <= 0 || !history) return "";
160
+ const [head, ...lines] = String(history).split("\n");
161
+ if (bytes(head) > room) return cutTo(head, room);
162
+ const kept = [];
163
+ let used = bytes(head);
164
+ for (const line of [...lines].reverse()) {
165
+ if (used + 1 + bytes(line) > room) break;
166
+ kept.unshift(line);
167
+ used += 1 + bytes(line);
168
+ }
169
+ return [head, ...kept].join("\n");
170
+ }
171
+
172
+ // ── Who keeps the book ──
173
+
174
+ /**
175
+ * The agents that execute onchain: those whose fixed role is the executor (members.json), and Bankr until fixed roles
176
+ * are declared there, as the desk names it its only executor (Decision 26).
177
+ */
178
+ export function onchainExecutors() {
179
+ const declared = MEMBERS.filter(
180
+ (entry) => entry.fixedRole?.role === "executor"
181
+ ).map((entry) => entry.id);
182
+ return declared.length ? declared : ["bankr"];
183
+ }
184
+
185
+ /** Why an agent cannot be the treasurer, or null when it can. No appointment overrides it. */
186
+ export function treasurerRefusal(agentId) {
187
+ const id = String(agentId || "");
188
+ if (!id || id === "user")
189
+ return "the treasurer is one of the person's agents";
190
+ if (onchainExecutors().includes(id))
191
+ return `${nameOf(id)} executes onchain, so it never keeps the desk's book`;
192
+ return null;
193
+ }
194
+
195
+ // The agent the person appointed to an office (specialties.mjs offices), or null while it is not appointed.
196
+ function officeHolder(store, office) {
197
+ const entry = offices(store).find((one) => one.id === office);
198
+ return entry?.appointed ? entry.holder : null;
199
+ }
200
+
201
+ /**
202
+ * Who keeps the book now: the person's appointment, else the agent they pinned for portfolio and risk watching, else
203
+ * the first agent carrying it. Never the executor. `{ agent: null }` when no one does: then only the person writes.
204
+ */
205
+ export function treasurerOf(store) {
206
+ const appointed = officeHolder(store, "treasurer");
207
+ if (appointed && !treasurerRefusal(appointed))
208
+ return { agent: appointed, how: "appointed" };
209
+ const pinned = pinnedFor(store, PORTFOLIO_RISK);
210
+ if (pinned && !treasurerRefusal(pinned))
211
+ return { agent: pinned, how: "pinned" };
212
+ const carrier = MEMBERS.map((entry) => entry.id).find(
213
+ (id) =>
214
+ !treasurerRefusal(id) &&
215
+ specialtiesOf(store, id, agentModelInUse(store, id) ?? {}).some(
216
+ (view) => view?.id === PORTFOLIO_RISK
217
+ )
218
+ );
219
+ return carrier
220
+ ? { agent: carrier, how: "specialty" }
221
+ : { agent: null, how: null };
222
+ }
223
+
224
+ const mayWrite = (store, agent) =>
225
+ agent === "user" ||
226
+ (!treasurerRefusal(agent) && treasurerOf(store).agent === agent);
227
+
228
+ // ── Reading ──
229
+
230
+ const strategyRow = (store, id) =>
231
+ store.db.get("select * from book_strategies where id = ?", [String(id)]);
232
+
233
+ const strategyView = (row) => ({
234
+ id: row.id,
235
+ title: row.title,
236
+ objective: row.objective,
237
+ reasons: row.reasons,
238
+ instructions: row.instructions,
239
+ entry: row.entry,
240
+ exit: row.exit,
241
+ grant: row.grant_ref
242
+ ? {
243
+ ref: row.grant_ref,
244
+ classes: JSON.parse(row.grant_classes || "[]"),
245
+ recordedBy: row.grant_set_by,
246
+ }
247
+ : null,
248
+ status: row.status,
249
+ writtenBy: row.written_by,
250
+ createdAt: row.created_at,
251
+ updatedAt: row.updated_at,
252
+ });
253
+
254
+ const receiptView = (row) => ({
255
+ id: row.id,
256
+ strategy: row.strategy_id,
257
+ thread: row.thread_id,
258
+ outcome: row.outcome,
259
+ operations: JSON.parse(row.operations || "[]"),
260
+ settledMicroUsd:
261
+ row.settled_micro_usd == null ? null : Number(row.settled_micro_usd),
262
+ observedUsd: row.observed_usd == null ? null : Number(row.observed_usd),
263
+ filedBy: row.filed_by,
264
+ filedAt: row.filed_at,
265
+ });
266
+
267
+ /** The strategy a thread's work sits under, or null. */
268
+ export function strategyOfThread(store, threadId) {
269
+ if (!threadId) return null;
270
+ return (
271
+ store.db.get("select strategy_id from book_threads where thread_id = ?", [
272
+ String(threadId),
273
+ ])?.strategy_id ?? null
274
+ );
275
+ }
276
+
277
+ /** The book: every strategy in brief, or one strategy whole with what is filed under it. */
278
+ export function readBook(store, { strategy = null } = {}) {
279
+ if (!strategy) {
280
+ const strategies = store.db
281
+ .all("select * from book_strategies order by created_at desc")
282
+ .map((row) => ({
283
+ ...strategyView(row),
284
+ positions: Number(
285
+ store.db.get(
286
+ "select count(*) as n from book_positions where strategy_id = ? and status = 'open'",
287
+ [row.id]
288
+ ).n
289
+ ),
290
+ }));
291
+ return { ok: true, treasurer: treasurerOf(store), strategies };
292
+ }
293
+ const row = strategyRow(store, strategy);
294
+ if (!row) return { ok: false, error: "no strategy in the book has that id" };
295
+ const filed = (table, order = "created_at") =>
296
+ store.db.all(
297
+ `select * from ${table} where strategy_id = ? order by ${order}`,
298
+ [row.id]
299
+ );
300
+ return {
301
+ ok: true,
302
+ treasurer: treasurerOf(store),
303
+ strategy: strategyView(row),
304
+ positions: filed("book_positions"),
305
+ decisions: filed("book_decisions"),
306
+ research: filed("book_research"),
307
+ receipts: filed("book_receipts", "filed_at").map(receiptView),
308
+ threads: filed("book_threads").map((link) => link.thread_id),
309
+ contracts: filed("book_contracts").map(
310
+ ({ source, runtime_code, ...contract }) => contract
311
+ ),
312
+ };
313
+ }
314
+
315
+ /** Receipts filed for a thread's work, newest first. */
316
+ export function receiptsForThread(store, threadId) {
317
+ if (!threadId) return [];
318
+ return store.db
319
+ .all(
320
+ "select * from book_receipts where thread_id = ? order by filed_at desc",
321
+ [String(threadId)]
322
+ )
323
+ .map(receiptView);
324
+ }
325
+
326
+ /** The filed receipt naming a transaction, or null. */
327
+ export function receiptOfTransaction(store, hash) {
328
+ const wanted = String(hash || "").toLowerCase();
329
+ if (!wanted) return null;
330
+ for (const row of store.db.all("select * from book_receipts")) {
331
+ const receipt = receiptView(row);
332
+ const operation = receipt.operations.find(
333
+ (op) => String(op.id).toLowerCase() === wanted
334
+ );
335
+ if (operation) return { receipt, operation };
336
+ }
337
+ return null;
338
+ }
339
+
340
+ // ── The slice a Bankr ask carries ──
341
+
342
+ /**
343
+ * The high-level instructions a Bankr ask carries from a strategy: its title, objective, instructions and its entry
344
+ * and exit conditions, within SLICE_BYTES. Never its positions, decisions, research, receipts or the reasons behind
345
+ * it: Bankr never gets the book (Decision 33). Empty when the strategy is not in the book.
346
+ */
347
+ export function bookSliceFor(store, strategyId) {
348
+ const row = strategyId ? strategyRow(store, strategyId) : null;
349
+ if (!row) return "";
350
+ const lines = [
351
+ `The person's strategy "${row.title}" (its high-level instructions, not approval for anything):`,
352
+ row.objective && `Objective: ${row.objective}`,
353
+ row.instructions && `Instructions: ${row.instructions}`,
354
+ row.entry && `Enter when: ${row.entry}`,
355
+ row.exit && `Exit when: ${row.exit}`,
356
+ ].filter(Boolean);
357
+ return cutTo(lines.join("\n"), SLICE_BYTES);
358
+ }
359
+
360
+ /**
361
+ * A Bankr ask in a thread linked to a strategy: the ask with the strategy's slice after it, and the newest of the
362
+ * thread's history that fits beside them in BANKR_ASK_BYTES. Null when the thread sits under no strategy.
363
+ */
364
+ export function deskAsk(store, { threadId, ask, history = "" }) {
365
+ const strategyId = strategyOfThread(store, threadId);
366
+ if (!strategyId) return null;
367
+ const slice = bookSliceFor(store, strategyId);
368
+ const carried = slice ? `${String(ask).trim()}\n\n${slice}` : String(ask);
369
+ const room = BANKR_ASK_BYTES - bytes(carried);
370
+ return { strategyId, ask: carried, history: newestLines(history, room) };
371
+ }
372
+
373
+ // ── Writing ──
374
+
375
+ const ENTRY_KINDS = ["strategy", "position", "decision", "research", "thread"];
376
+ const GRANT_CLASSES = new Set([
377
+ "financial_onchain",
378
+ "external_communications",
379
+ "account_configuration",
380
+ "code_deployment",
381
+ "file_publication",
382
+ "persistent_delegation",
383
+ ]);
384
+
385
+ const needsStrategy = (store, entry) =>
386
+ strategyRow(store, entry.strategy)
387
+ ? null
388
+ : "name the strategy it belongs to (its id in the book)";
389
+
390
+ function writeStrategy(store, agent, entry) {
391
+ const existing = entry.id ? strategyRow(store, entry.id) : null;
392
+ if (entry.id && !existing)
393
+ return { ok: false, error: "no strategy in the book has that id" };
394
+ // The grant is the person's: only their record of it counts for a gate (the contract gate reads it).
395
+ if (entry.grant !== undefined && agent !== "user")
396
+ return {
397
+ ok: false,
398
+ error: "the grant a strategy sits under is the person's to record",
399
+ };
400
+ const classes = Array.isArray(entry.grant?.classes)
401
+ ? entry.grant.classes.map(String).filter((name) => GRANT_CLASSES.has(name))
402
+ : [];
403
+ const title = text(entry.title, 120) || existing?.title;
404
+ if (!title) return { ok: false, error: "a strategy needs a title" };
405
+ const at = now();
406
+ const id = existing?.id ?? randomUUID();
407
+ const value = (name, limit) =>
408
+ entry[name] !== undefined
409
+ ? text(entry[name], limit)
410
+ : (existing?.[name] ?? "");
411
+ const grantRef =
412
+ entry.grant !== undefined
413
+ ? text(entry.grant?.ref, 200) || null
414
+ : (existing?.grant_ref ?? null);
415
+ store.db.run(
416
+ `insert into book_strategies(id, title, objective, reasons, instructions, entry, exit, grant_ref, grant_classes,
417
+ grant_set_by, status, written_by, version, created_at, updated_at)
418
+ values(?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, 1, ?, ?)
419
+ on conflict(id) do update set title = excluded.title, objective = excluded.objective, reasons = excluded.reasons,
420
+ instructions = excluded.instructions, entry = excluded.entry, exit = excluded.exit, grant_ref = excluded.grant_ref,
421
+ grant_classes = excluded.grant_classes, grant_set_by = excluded.grant_set_by, status = excluded.status,
422
+ written_by = excluded.written_by, version = book_strategies.version + 1, updated_at = excluded.updated_at`,
423
+ [
424
+ id,
425
+ title,
426
+ value("objective"),
427
+ value("reasons"),
428
+ value("instructions", INSTRUCTION_CHARS),
429
+ value("entry"),
430
+ value("exit"),
431
+ grantRef,
432
+ entry.grant !== undefined
433
+ ? JSON.stringify(classes)
434
+ : (existing?.grant_classes ?? "[]"),
435
+ entry.grant !== undefined
436
+ ? grantRef
437
+ ? agent
438
+ : null
439
+ : (existing?.grant_set_by ?? null),
440
+ ["active", "paused", "closed"].includes(entry.status)
441
+ ? entry.status
442
+ : (existing?.status ?? "active"),
443
+ agent,
444
+ existing?.created_at ?? at,
445
+ at,
446
+ ]
447
+ );
448
+ return { ok: true, strategy: strategyView(strategyRow(store, id)) };
449
+ }
450
+
451
+ function writePosition(store, agent, entry) {
452
+ const refusal = needsStrategy(store, entry);
453
+ if (refusal) return { ok: false, error: refusal };
454
+ const existing = entry.id
455
+ ? store.db.get("select * from book_positions where id = ?", [
456
+ String(entry.id),
457
+ ])
458
+ : null;
459
+ if (entry.id && !existing)
460
+ return { ok: false, error: "no position in the book has that id" };
461
+ const asset = text(entry.asset, 120) || existing?.asset;
462
+ if (!asset) return { ok: false, error: "a position names its asset" };
463
+ const at = now();
464
+ const id = existing?.id ?? randomUUID();
465
+ const value = (name, limit = 200) =>
466
+ entry[name] !== undefined
467
+ ? text(entry[name], limit) || null
468
+ : (existing?.[name] ?? null);
469
+ store.db.run(
470
+ `insert into book_positions(id, strategy_id, asset, chain, size, status, why, receipt_id, opened_at, closed_at,
471
+ written_by, version, created_at, updated_at)
472
+ values(?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, 1, ?, ?)
473
+ on conflict(id) do update set asset = excluded.asset, chain = excluded.chain, size = excluded.size,
474
+ status = excluded.status, why = excluded.why, receipt_id = excluded.receipt_id, opened_at = excluded.opened_at,
475
+ closed_at = excluded.closed_at, written_by = excluded.written_by, version = book_positions.version + 1,
476
+ updated_at = excluded.updated_at`,
477
+ [
478
+ id,
479
+ String(entry.strategy),
480
+ asset,
481
+ value("chain", 40),
482
+ value("size", 80),
483
+ ["open", "closed"].includes(entry.status)
484
+ ? entry.status
485
+ : (existing?.status ?? "open"),
486
+ value("why", TEXT_CHARS) ?? "",
487
+ value("receipt", 120),
488
+ value("opened_at", 40),
489
+ value("closed_at", 40),
490
+ agent,
491
+ existing?.created_at ?? at,
492
+ at,
493
+ ]
494
+ );
495
+ return {
496
+ ok: true,
497
+ position: store.db.get("select * from book_positions where id = ?", [id]),
498
+ };
499
+ }
500
+
501
+ function writeDecision(store, agent, entry) {
502
+ const refusal = needsStrategy(store, entry);
503
+ if (refusal) return { ok: false, error: refusal };
504
+ const decision = text(entry.decision);
505
+ const takenBy = text(entry.taken_by, 80);
506
+ if (!decision || !takenBy)
507
+ return {
508
+ ok: false,
509
+ error: "a decision says what was decided and who took it",
510
+ };
511
+ const id = randomUUID();
512
+ store.db.run(
513
+ `insert into book_decisions(id, strategy_id, task_id, decision, taken_by, approved_by, written_by, created_at)
514
+ values(?, ?, ?, ?, ?, ?, ?, ?)`,
515
+ [
516
+ id,
517
+ String(entry.strategy),
518
+ text(entry.task, 120) || null,
519
+ decision,
520
+ takenBy,
521
+ ["grant", "user"].includes(entry.approved_by) ? entry.approved_by : null,
522
+ agent,
523
+ now(),
524
+ ]
525
+ );
526
+ return {
527
+ ok: true,
528
+ decision: store.db.get("select * from book_decisions where id = ?", [id]),
529
+ };
530
+ }
531
+
532
+ function writeResearch(store, agent, entry) {
533
+ const refusal = needsStrategy(store, entry);
534
+ if (refusal) return { ok: false, error: refusal };
535
+ const title = text(entry.title, 200);
536
+ const ref = text(entry.ref, 1_000);
537
+ if (!title || !ref)
538
+ return {
539
+ ok: false,
540
+ error:
541
+ "research is filed with a title and where it is (a link, a task or a file id)",
542
+ };
543
+ const id = randomUUID();
544
+ store.db.run(
545
+ "insert into book_research(id, strategy_id, title, ref, written_by, created_at) values(?, ?, ?, ?, ?, ?)",
546
+ [id, String(entry.strategy), title, ref, agent, now()]
547
+ );
548
+ return {
549
+ ok: true,
550
+ research: store.db.get("select * from book_research where id = ?", [id]),
551
+ };
552
+ }
553
+
554
+ function linkThread(store, agent, entry) {
555
+ const refusal = needsStrategy(store, entry);
556
+ if (refusal) return { ok: false, error: refusal };
557
+ const thread = store.getTask(String(entry.thread || ""));
558
+ if (thread?.kind !== "goal")
559
+ return {
560
+ ok: false,
561
+ error: "name a thread (its id) to put under the strategy",
562
+ };
563
+ store.db.run(
564
+ `insert into book_threads(thread_id, strategy_id, written_by, created_at) values(?, ?, ?, ?)
565
+ on conflict(thread_id) do update set strategy_id = excluded.strategy_id, written_by = excluded.written_by`,
566
+ [thread.id, String(entry.strategy), agent, now()]
567
+ );
568
+ return { ok: true, thread: thread.id, strategy: String(entry.strategy) };
569
+ }
570
+
571
+ /** One entry written to the book by the treasurer or the person: { kind, ... }. Receipts are code's alone. */
572
+ export function writeBook(store, agent, entry) {
573
+ if (!mayWrite(store, agent)) {
574
+ const treasurer = treasurerOf(store).agent;
575
+ return {
576
+ ok: false,
577
+ error:
578
+ treasurerRefusal(agent) && agent !== "user"
579
+ ? `${treasurerRefusal(agent)}; any agent reads it`
580
+ : treasurer
581
+ ? `only the treasurer (${nameOf(treasurer)}) and the person write the book; any agent reads it`
582
+ : "no one is the treasurer yet, so only the person writes the book; any agent reads it",
583
+ };
584
+ }
585
+ const kind = entry?.kind;
586
+ if (!ENTRY_KINDS.includes(kind))
587
+ return {
588
+ ok: false,
589
+ error: `an entry is one of ${ENTRY_KINDS.join(", ")}; receipts are filed by Harness from the chain`,
590
+ };
591
+ if (kind === "strategy") return writeStrategy(store, agent, entry);
592
+ if (kind === "position") return writePosition(store, agent, entry);
593
+ if (kind === "decision") return writeDecision(store, agent, entry);
594
+ if (kind === "research") return writeResearch(store, agent, entry);
595
+ return linkThread(store, agent, entry);
596
+ }
597
+
598
+ // ── Receipts, filed by code ──
599
+
600
+ const shortText = (value, limit) =>
601
+ typeof value === "string" ? value.slice(0, limit) : null;
602
+
603
+ /** The chain receipt Harness sent with a Bankr job, checked to the shape the book keeps, or null. */
604
+ function chainReceiptOf(job) {
605
+ const receipt = job?.chain_receipt;
606
+ if (!receipt || typeof receipt !== "object") return null;
607
+ const outcome = shortText(receipt.outcome, 40);
608
+ if (!outcome) return null;
609
+ const operations = (
610
+ Array.isArray(receipt.operations) ? receipt.operations : []
611
+ )
612
+ .slice(0, 50)
613
+ .filter((op) => typeof op?.id === "string" && op.id)
614
+ .map((op) => ({
615
+ id: op.id.slice(0, 120),
616
+ chain: shortText(op.chain, 40),
617
+ status: shortText(op.status, 20),
618
+ created: (Array.isArray(op.created) ? op.created : [])
619
+ .filter((address) => typeof address === "string")
620
+ .slice(0, 10)
621
+ .map((address) => address.toLowerCase().slice(0, 64)),
622
+ }));
623
+ const settled = Number(receipt.settled_micro_usd);
624
+ const observed = Number(receipt.observed_usd);
625
+ return {
626
+ outcome,
627
+ operations,
628
+ settledMicroUsd: Number.isFinite(settled) ? Math.round(settled) : null,
629
+ observedUsd: Number.isFinite(observed) ? observed : null,
630
+ };
631
+ }
632
+
633
+ /** Files the receipt of a Bankr job that finished in one of the person's threads. Null when it carried none. */
634
+ export function fileBankrReceipt(store, job) {
635
+ if (!onchainExecutors().includes(String(job?.target_agent || "")))
636
+ return null;
637
+ const receipt = chainReceiptOf(job);
638
+ if (!receipt) return null;
639
+ const threadId = typeof job.parent_id === "string" ? job.parent_id : null;
640
+ store.db.run(
641
+ `insert into book_receipts(id, strategy_id, thread_id, outcome, operations, settled_micro_usd, observed_usd, filed_by, filed_at)
642
+ values(?, ?, ?, ?, ?, ?, ?, 'code', ?)
643
+ on conflict(id) do update set outcome = excluded.outcome, operations = excluded.operations,
644
+ settled_micro_usd = excluded.settled_micro_usd, observed_usd = excluded.observed_usd, filed_at = excluded.filed_at`,
645
+ [
646
+ String(job.id).slice(0, 120),
647
+ strategyOfThread(store, threadId),
648
+ threadId,
649
+ receipt.outcome,
650
+ JSON.stringify(receipt.operations),
651
+ receipt.settledMicroUsd,
652
+ receipt.observedUsd,
653
+ now(),
654
+ ]
655
+ );
656
+ return receiptView(
657
+ store.db.get("select * from book_receipts where id = ?", [String(job.id)])
658
+ );
659
+ }
package/lib/bridge.mjs CHANGED
@@ -15,7 +15,7 @@ export const RECONNECT_JITTER = 0.2;
15
15
  const HELD_ELSEWHERE = {
16
16
  status: 409,
17
17
  code: 4409,
18
- text: "Another computer is connected to this Harness account and holds its board, so this one stays offline. Disconnect that computer (npx tryharness disconnect there), then run npx tryharness setup here.",
18
+ text: "Another computer is connected to this Harness account and holds its board, so this one stays offline. Uninstall Harness there (npx tryharness uninstall), then run npx tryharness setup here.",
19
19
  };
20
20
  // This machine's IPv4 addresses: they change when it moves between networks. IPv6 privacy addresses rotate on their own.
21
21
  const networkAddresses = () =>