tryharness 0.7.53 → 0.7.57

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 (167) hide show
  1. package/README.md +23 -19
  2. package/assets/dsh-plugin.mjs +72 -0
  3. package/assets/opencode-plugin.js +4 -3
  4. package/cli.mjs +484 -90
  5. package/lib/activity.mjs +10 -10
  6. package/lib/adapters.mjs +173 -222
  7. package/lib/agentBinaries.mjs +71 -0
  8. package/lib/agentRuntimeConfig.mjs +1 -1
  9. package/lib/agentRuntimes.mjs +34 -18
  10. package/lib/agentSignIn.mjs +456 -0
  11. package/lib/answers.mjs +5 -5
  12. package/lib/archetypes.d.ts +64 -0
  13. package/lib/archetypes.js +989 -0
  14. package/lib/asks.mjs +4 -4
  15. package/lib/audit.mjs +666 -0
  16. package/lib/backupSetup.mjs +143 -0
  17. package/lib/boardAccess.mjs +24 -11
  18. package/lib/boardBackup.mjs +283 -0
  19. package/lib/boardFileCommands.mjs +6 -6
  20. package/lib/boardFiles.mjs +13 -12
  21. package/lib/boardMirror.mjs +124 -25
  22. package/lib/boardProtocol.json +88 -2
  23. package/lib/boardWaits.mjs +101 -0
  24. package/lib/book.mjs +659 -0
  25. package/lib/bridge.mjs +6 -6
  26. package/lib/cards.mjs +138 -28
  27. package/lib/cloudAgents.mjs +216 -0
  28. package/lib/cloudAi.mjs +1312 -0
  29. package/lib/cloudAssistants.mjs +242 -0
  30. package/lib/cloudBoot.mjs +119 -0
  31. package/lib/cloudSave.mjs +197 -0
  32. package/lib/cloudSsh.mjs +178 -0
  33. package/lib/commands.mjs +7 -2
  34. package/lib/context.mjs +19 -5
  35. package/lib/contractGate.mjs +399 -0
  36. package/lib/control-client.mjs +9 -1
  37. package/lib/controlSocket.mjs +86 -0
  38. package/lib/coordinator.mjs +252 -144
  39. package/lib/daemon.mjs +1351 -2767
  40. package/lib/desk.mjs +240 -0
  41. package/lib/desktop.mjs +178 -74
  42. package/lib/directLink.mjs +16 -5
  43. package/lib/environment.mjs +2 -1
  44. package/lib/environments.mjs +247 -9
  45. package/lib/firewall.mjs +9 -9
  46. package/lib/folders.mjs +20 -16
  47. package/lib/frames.mjs +2 -3
  48. package/lib/gitHost.mjs +174 -0
  49. package/lib/goalCommands.mjs +25 -7
  50. package/lib/goals.mjs +7 -7
  51. package/lib/guestRequests.mjs +94 -0
  52. package/lib/handoffs.mjs +8 -7
  53. package/lib/handover.mjs +4 -4
  54. package/lib/harnessModel.mjs +6 -6
  55. package/lib/harnessOffers.mjs +266 -0
  56. package/lib/hookDialects.mjs +298 -0
  57. package/lib/inference.mjs +26 -8
  58. package/lib/jobAnswers.mjs +190 -0
  59. package/lib/landed.mjs +887 -0
  60. package/lib/lane.mjs +42 -11
  61. package/lib/lessons.mjs +16 -16
  62. package/lib/library.mjs +3 -3
  63. package/lib/lineup.mjs +3 -0
  64. package/lib/linkRelay.mjs +574 -0
  65. package/lib/live.mjs +284 -13
  66. package/lib/localAgentAsk.mjs +74 -0
  67. package/lib/localStack.mjs +536 -0
  68. package/lib/localmodels.mjs +6 -4
  69. package/lib/loopBackstop.mjs +4 -4
  70. package/lib/machineIdentity.mjs +9 -1
  71. package/lib/machineRoutes.mjs +181 -2
  72. package/lib/machineRuns.mjs +76 -1
  73. package/lib/machineSeal.mjs +39 -12
  74. package/lib/mcp-stdio.mjs +163 -27
  75. package/lib/mcpRelay.mjs +1 -1
  76. package/lib/members.json +29 -2
  77. package/lib/members.mjs +1 -1
  78. package/lib/models.mjs +85 -31
  79. package/lib/museSession.mjs +21 -13
  80. package/lib/nativeHost.mjs +36 -8
  81. package/lib/neovim.mjs +126 -0
  82. package/lib/network.mjs +50 -5
  83. package/lib/notify.mjs +7 -5
  84. package/lib/nudge.mjs +50 -19
  85. package/lib/ocr.mjs +9 -9
  86. package/lib/onboard.mjs +26 -20
  87. package/lib/oneLine.mjs +7 -7
  88. package/lib/ownMachines.mjs +1223 -140
  89. package/lib/pairing.mjs +60 -16
  90. package/lib/paths.mjs +19 -1
  91. package/lib/peerProcess.mjs +124 -0
  92. package/lib/personModel.mjs +89 -0
  93. package/lib/personNotices.mjs +151 -0
  94. package/lib/phones.mjs +538 -31
  95. package/lib/placeCommands.mjs +4 -4
  96. package/lib/places.mjs +400 -12
  97. package/lib/profile.mjs +67 -14
  98. package/lib/projectGit.mjs +158 -14
  99. package/lib/projectPieces.mjs +902 -0
  100. package/lib/projectSettings.mjs +7 -4
  101. package/lib/projects.mjs +384 -62
  102. package/lib/provenance.mjs +5 -1
  103. package/lib/proxyLinks.mjs +267 -0
  104. package/lib/reactions.mjs +7 -5
  105. package/lib/readiness.mjs +145 -23
  106. package/lib/record.mjs +128 -0
  107. package/lib/redact.mjs +4 -4
  108. package/lib/relayLimits.mjs +62 -0
  109. package/lib/release.mjs +170 -0
  110. package/lib/releaseKeys.json +6 -0
  111. package/lib/repoLinks.mjs +4 -4
  112. package/lib/roomChannels.mjs +24 -0
  113. package/lib/roomPage.mjs +1 -1
  114. package/lib/runAuthority.mjs +101 -0
  115. package/lib/runBrief.mjs +19 -8
  116. package/lib/runWorker.mjs +31 -7
  117. package/lib/runner.mjs +223 -29
  118. package/lib/runtime-install.mjs +143 -9
  119. package/lib/schedules.mjs +2 -2
  120. package/lib/screens.mjs +1 -1
  121. package/lib/sealed.mjs +11 -2
  122. package/lib/sealedThreads.mjs +671 -0
  123. package/lib/secretPatterns.json +1 -1
  124. package/lib/secrets.mjs +4 -4
  125. package/lib/seen.mjs +6 -6
  126. package/lib/serverWords.mjs +175 -0
  127. package/lib/service.mjs +22 -12
  128. package/lib/sessionControl.mjs +378 -90
  129. package/lib/specialties.json +74 -0
  130. package/lib/specialties.mjs +477 -0
  131. package/lib/specialtyKeys.d.ts +3 -0
  132. package/lib/specialtyKeys.js +57 -0
  133. package/lib/specialtyNotice.mjs +147 -0
  134. package/lib/specialtySnapshot.mjs +138 -0
  135. package/lib/speech.mjs +5 -5
  136. package/lib/store.mjs +420 -36
  137. package/lib/stuck.mjs +1 -1
  138. package/lib/swarm.mjs +304 -37
  139. package/lib/swarmDevices.mjs +319 -0
  140. package/lib/swarmMemory.mjs +27 -25
  141. package/lib/t3.mjs +24 -15
  142. package/lib/taskCommands.mjs +80 -20
  143. package/lib/taskRooms.mjs +125 -0
  144. package/lib/taskRuns.mjs +45 -3
  145. package/lib/team.json +255 -148
  146. package/lib/team.mjs +554 -190
  147. package/lib/threadActions.mjs +315 -0
  148. package/lib/threadAuthority.mjs +101 -0
  149. package/lib/threadBriefs.mjs +178 -0
  150. package/lib/threadLine.mjs +116 -0
  151. package/lib/threadRuns.mjs +209 -50
  152. package/lib/threadView.mjs +20 -7
  153. package/lib/usageTotals.mjs +2 -3
  154. package/lib/vault.mjs +101 -10
  155. package/lib/vaultCloud.mjs +2 -2
  156. package/lib/vaultCommands.mjs +15 -6
  157. package/lib/vaultTools.js +2 -2
  158. package/lib/verdicts.mjs +328 -0
  159. package/lib/wakes.mjs +1 -1
  160. package/lib/watches.mjs +2 -2
  161. package/lib/windowAsks.mjs +13 -5
  162. package/lib/worktrees.mjs +157 -25
  163. package/npm-shrinkwrap.json +1093 -0
  164. package/package.json +12 -11
  165. package/release.json +220 -0
  166. package/lib/modelTiers.json +0 -1183
  167. package/lib/modelTiers.mjs +0 -133
@@ -0,0 +1,178 @@
1
+ import fs from "node:fs";
2
+ import os from "node:os";
3
+ import path from "node:path";
4
+ import { createHash } from "node:crypto";
5
+
6
+ // SSH into a cloud computer (docs/cloud-swarm.md §7), both ends of it.
7
+ //
8
+ // On the box: the keys the person's own devices allowed (createCloudSsh). Boat puts a key on a sandbox for its own
9
+ // account when Harness's server asks, so Harness's server could put one there on its own word. The box's sshd
10
+ // therefore reads, for that account, only the file kept here (bootScript.ts sshGate), and this file is written only
11
+ // when one of the person's registered devices asks: their own computer over the sealed line between their computers
12
+ // (ownMachines.mjs), or a window linked to this computer (phones.mjs). Never on a call from Harness's server.
13
+ //
14
+ // On the person's computer: the key to send (their own, never made here), and the ssh command that pins the host key
15
+ // the box has now, which changes with every resume.
16
+
17
+ const KEY_TYPES = new Set([
18
+ "ssh-ed25519",
19
+ "ecdsa-sha2-nistp256",
20
+ "ecdsa-sha2-nistp384",
21
+ "ecdsa-sha2-nistp521",
22
+ "ssh-rsa",
23
+ "sk-ssh-ed25519@openssh.com",
24
+ "sk-ecdsa-sha2-nistp256@openssh.com",
25
+ ]);
26
+ // More than this many keys is not one person's computers: the oldest goes.
27
+ const MAX_KEYS = 20;
28
+ const MAX_KEY_CHARS = 16_384;
29
+ // The key files a person's computer most likely has, in the order ssh itself tries them.
30
+ const OWN_KEYS = [
31
+ "id_ed25519",
32
+ "id_ecdsa",
33
+ "id_ed25519_sk",
34
+ "id_ecdsa_sk",
35
+ "id_rsa",
36
+ ];
37
+
38
+ /** An OpenSSH public key line as { type, blob }, or null. The key must name its own type inside it. */
39
+ export function parsePublicKey(text) {
40
+ const line = String(text ?? "").trim();
41
+ if (!line || line.length > MAX_KEY_CHARS || /[\r\n]/.test(line)) return null;
42
+ const [type, blob] = line.split(/\s+/);
43
+ if (!KEY_TYPES.has(type) || !/^[A-Za-z0-9+/]+={0,3}$/.test(blob ?? ""))
44
+ return null;
45
+ const bytes = Buffer.from(blob, "base64");
46
+ if (bytes.length < 4) return null;
47
+ const named = bytes.readUInt32BE(0);
48
+ if (bytes.subarray(4, 4 + named).toString("latin1") !== type) return null;
49
+ return { type, blob };
50
+ }
51
+
52
+ /** A key's fingerprint as `ssh-keygen -l` shows it. */
53
+ export const fingerprintOf = (blob) =>
54
+ `SHA256:${createHash("sha256")
55
+ .update(Buffer.from(blob, "base64"))
56
+ .digest("base64")
57
+ .replace(/=+$/, "")}`;
58
+
59
+ // Who allowed a key, kept as its comment: printable and short, as sshd's own line takes it.
60
+ const byLine = (by) =>
61
+ String(by || "your device")
62
+ .replace(/[^A-Za-z0-9 ._()-]/g, "")
63
+ .trim()
64
+ .slice(0, 60) || "your device";
65
+
66
+ /**
67
+ * The box's side. `keysFile`: what sshd reads for the provider's account; `gateFile`: sshd's drop-in that makes it read
68
+ * only that, without which no key is taken (bootScript.ts).
69
+ */
70
+ export function createCloudSsh({ keysFile, gateFile, log = () => {} }) {
71
+ const ready = () => {
72
+ try {
73
+ return fs
74
+ .readFileSync(gateFile, "utf8")
75
+ .includes("AuthorizedKeysCommand");
76
+ } catch {
77
+ return false;
78
+ }
79
+ };
80
+ const read = () => {
81
+ let text = "";
82
+ try {
83
+ text = fs.readFileSync(keysFile, "utf8");
84
+ } catch {}
85
+ return text
86
+ .split("\n")
87
+ .map((line) => {
88
+ const parsed = parsePublicKey(line);
89
+ return parsed
90
+ ? { ...parsed, by: line.trim().split(/\s+/).slice(2).join(" ") }
91
+ : null;
92
+ })
93
+ .filter(Boolean);
94
+ };
95
+ const write = (keys) => {
96
+ const next = `${keysFile}.${process.pid}.tmp`;
97
+ fs.writeFileSync(
98
+ next,
99
+ keys.map((key) => `${key.type} ${key.blob} ${key.by}\n`).join(""),
100
+ { mode: 0o644 }
101
+ );
102
+ fs.renameSync(next, keysFile);
103
+ };
104
+
105
+ /** One of the person's devices lets this key in. `by`: which device, as the person named it. */
106
+ const allow = ({ key, by }) => {
107
+ if (!ready())
108
+ return {
109
+ ok: false,
110
+ error:
111
+ "This cloud computer takes no SSH keys: its SSH gate is not in place. Remove it and add a new one.",
112
+ };
113
+ const parsed = parsePublicKey(key);
114
+ if (!parsed) return { ok: false, error: "That is not an SSH public key." };
115
+ const others = read().filter((kept) => kept.blob !== parsed.blob);
116
+ const keys = [...others, { ...parsed, by: byLine(by) }].slice(-MAX_KEYS);
117
+ write(keys);
118
+ const fingerprint = fingerprintOf(parsed.blob);
119
+ log(`SSH key ${fingerprint} allowed by ${byLine(by)}`);
120
+ return { ok: true, fingerprint };
121
+ };
122
+
123
+ const list = () =>
124
+ read().map((key) => ({ fingerprint: fingerprintOf(key.blob), by: key.by }));
125
+
126
+ return { ready, allow, list };
127
+ }
128
+
129
+ /** The person's own public key: the file named, else the first of ssh's usual ones; null when there is none. */
130
+ export function ownPublicKey(named = null, home = os.homedir()) {
131
+ const files = named
132
+ ? [path.resolve(named.endsWith(".pub") ? named : `${named}.pub`)]
133
+ : OWN_KEYS.map((name) => path.join(home, ".ssh", `${name}.pub`));
134
+ for (const file of files) {
135
+ try {
136
+ const text = fs.readFileSync(file, "utf8").trim();
137
+ if (parsePublicKey(text))
138
+ return { file, privateFile: file.replace(/\.pub$/, ""), text };
139
+ } catch {}
140
+ }
141
+ return null;
142
+ }
143
+
144
+ /**
145
+ * The ssh command for one cloud computer as it is now: its host key pinned under a name of its own in a known_hosts
146
+ * file kept for it, so a resume's new host key replaces the old one and nothing in the person's own known_hosts changes.
147
+ */
148
+ export function sshCommand({
149
+ access,
150
+ computer,
151
+ keyFile,
152
+ knownHostsDir,
153
+ command = [],
154
+ }) {
155
+ const alias = `harness-cloud-${String(computer.id).slice(0, 8)}`;
156
+ fs.mkdirSync(knownHostsDir, { recursive: true, mode: 0o700 });
157
+ const knownHosts = path.join(knownHostsDir, `${alias}.known_hosts`);
158
+ if (access.hostKey)
159
+ fs.writeFileSync(knownHosts, `${alias} ${access.hostKey}\n`, {
160
+ mode: 0o600,
161
+ });
162
+ return [
163
+ "-i",
164
+ keyFile,
165
+ "-o",
166
+ "IdentitiesOnly=yes",
167
+ "-o",
168
+ `HostKeyAlias=${alias}`,
169
+ "-o",
170
+ `UserKnownHostsFile=${knownHosts}`,
171
+ "-o",
172
+ `StrictHostKeyChecking=${access.hostKey ? "yes" : "ask"}`,
173
+ "-p",
174
+ String(access.port),
175
+ `${access.user}@${access.host}`,
176
+ ...(command.length ? ["--", ...command] : []),
177
+ ];
178
+ }
package/lib/commands.mjs CHANGED
@@ -1,7 +1,7 @@
1
1
  import fs from "node:fs";
2
2
  import path from "node:path";
3
3
  import { spawnSync } from "node:child_process";
4
- import { MEMBERS } from "./members.mjs";
4
+ import { MEMBERS, member } from "./members.mjs";
5
5
  import { runtimeOf } from "./agentRuntimeConfig.mjs";
6
6
 
7
7
  export function resolveCommand(command, env = process.env) {
@@ -72,9 +72,14 @@ export const AGENT_COMMANDS = {
72
72
  ),
73
73
  };
74
74
 
75
+ // An agent whose protocol server is a download of its own (Antigravity's ACP server) is still found by the command the
76
+ // person runs (its member's `cli`), so setup connects their own sessions.
75
77
  export function detectAgents() {
76
78
  return Object.entries(AGENT_COMMANDS).map(([agent, defaultCommand]) => {
77
79
  const command = runtimeOf(agent)?.command || defaultCommand;
78
- return { agent, command, path: resolveCommand(command) };
80
+ const found = resolveCommand(command);
81
+ const cli = member(agent)?.cli;
82
+ if (found || !cli) return { agent, command, path: found };
83
+ return { agent, command: cli, path: resolveCommand(cli) };
79
84
  });
80
85
  }
package/lib/context.mjs CHANGED
@@ -35,6 +35,8 @@ const PACK_FILES = 8;
35
35
  const POOL = 60;
36
36
  const HISTORY_DAYS = 60;
37
37
  const REFRESH_MS = 15 * 60_000;
38
+ // How long the background pass trusts which repository a folder is in; a new repository joins on the next asking.
39
+ const PLACE_KEPT_MS = 60 * 60_000;
38
40
  const LEARN_EVERY_MS = 20 * 3_600_000;
39
41
  // Vectors of the pieces packs search stay in memory while packs are being made, and go after this long without one.
40
42
  const VECTORS_IDLE_MS = 5 * 60_000;
@@ -118,7 +120,7 @@ export async function rankFiles({
118
120
  const hybrid = (c) => c.dense + 0.25 * (c.lexical / topWords) + 0.2 * c.named;
119
121
  const byHybrid = [...candidates].sort((a, b) => hybrid(b) - hybrid(a));
120
122
  const prior = swarmPrior(history, at);
121
- // No cross-encoder pass: on the owner's own sessions it moved recall by under one point (context-recall v3).
123
+ // No cross-encoder pass: on real sessions it moved recall by under one point.
122
124
  const byDense = [...candidates]
123
125
  .sort((a, b) => b.dense - a.dense)
124
126
  .slice(0, POOL)
@@ -212,11 +214,22 @@ export function createContextEngine({
212
214
  : repo.root;
213
215
  return { root, top: repo.root };
214
216
  };
217
+ // The background pass keeps each folder's place for a while: asking git blocks the daemon, and the pass asked three
218
+ // times for each of 683 sessions every 15 minutes, holding everything else (T3, the buddy, hooks) for up to 11 s.
219
+ // A brief's pack still asks fresh.
220
+ const keptPlaces = new Map();
221
+ const keptPlaceOf = (folder) => {
222
+ const kept = keptPlaces.get(folder);
223
+ if (kept && Date.now() - kept.at < PLACE_KEPT_MS) return kept.place;
224
+ const place = placeOf(folder);
225
+ keptPlaces.set(folder, { place, at: Date.now() });
226
+ return place;
227
+ };
215
228
 
216
229
  const roots = () => [
217
230
  ...new Set(
218
231
  known()
219
- .map((place) => placeOf(place.path)?.root)
232
+ .map((place) => keptPlaceOf(place.path)?.root)
220
233
  .filter(Boolean)
221
234
  ),
222
235
  ];
@@ -237,14 +250,15 @@ export function createContextEngine({
237
250
  const trees = new Map();
238
251
  let added = 0;
239
252
  for (const session of store.sessionSources({ since })) {
240
- const place = placeOf(session.cwd);
241
- if (!place || !rootList.includes(place.root)) continue;
242
253
  // A session whose source file the agent has since deleted is read from the relay's own copy, once.
243
254
  let mtime = 0;
244
255
  try {
245
256
  mtime = fs.statSync(session.source).mtimeMs;
246
257
  } catch {}
258
+ // Seen as it is now: nothing to read, and no need to ask git where it ran.
247
259
  if (atlas.runSeen(session.agent, session.session_id) === mtime) continue;
260
+ const place = keptPlaceOf(session.cwd);
261
+ if (!place || !rootList.includes(place.root)) continue;
248
262
  const trail = mtime
249
263
  ? await readTrail(session.agent, session.source)
250
264
  : trailFromTranscript(
@@ -267,7 +281,7 @@ export function createContextEngine({
267
281
  {
268
282
  ...trail,
269
283
  cwd:
270
- trail.cwd && placeOf(trail.cwd)?.top === place.top
284
+ trail.cwd && keptPlaceOf(trail.cwd)?.top === place.top
271
285
  ? path.join(place.root, path.relative(place.top, trail.cwd))
272
286
  : trail.cwd,
273
287
  },
@@ -0,0 +1,399 @@
1
+ import { createHash, randomUUID } from "node:crypto";
2
+ import { MACHINE_RUNNERS, nameOf } from "./members.mjs";
3
+ import { onchainExecutors, treasurerOf } from "./book.mjs";
4
+
5
+ // The gate between building a contract and deploying it. Bankr builds and deploys as two asks, so its maker is not its
6
+ // only check:
7
+ //
8
+ // 1. Build: Bankr returns the source and the compiled code; the treasurer (or the person) files them in the book and
9
+ // code hashes the runtime code. Every verdict below is bound to that hash, so code filed again after a review is
10
+ // reviewed again.
11
+ // 2. Check: a coding agent tests it on a fork with no real funds.
12
+ // 3. Judge: a reviewer on a model other than the checker's; then the grant or the person approves.
13
+ // 4. Deploy: Bankr is asked to deploy exactly that code, and code reads what the chain holds at the address it reports
14
+ // and compares it with the code reviewed.
15
+ //
16
+ // Deploying needs the grant's code_deployment and financial_onchain classes, both off by default, as the person
17
+ // recorded them in the book. The gate before the action itself stays the mandate's reservation on Harness's server:
18
+ // nothing here moves money or widens what Harness's server allows. If Bankr can only build and deploy in one go, the
19
+ // first deploy goes to a testnet (`oneGo`), and the testnet's code is what is reviewed.
20
+
21
+ export const DEPLOY_CLASSES = ["code_deployment", "financial_onchain"];
22
+ // Test networks a one-go build may deploy to. Harness's server reads code on the ones it knows (chainReceipts.ts).
23
+ export const TESTNETS = ["base-sepolia", "sepolia"];
24
+
25
+ const now = () => new Date().toISOString();
26
+ const short = (value, limit) =>
27
+ typeof value === "string" ? value.trim().slice(0, limit) : "";
28
+
29
+ /** Runtime code as hex (with or without 0x), normalized, or null when it is not hex. */
30
+ function hexOf(code) {
31
+ const hex = short(code, 200_000).toLowerCase().replace(/^0x/, "");
32
+ return hex && hex.length % 2 === 0 && /^[0-9a-f]+$/.test(hex) ? hex : null;
33
+ }
34
+
35
+ /** The SHA-256 of runtime code's bytes, as Harness's server hashes the code it reads at an address. */
36
+ export const codeSha256 = (hex) =>
37
+ createHash("sha256").update(Buffer.from(hex, "hex")).digest("hex");
38
+
39
+ const contractRow = (store, id) =>
40
+ store.db.get("select * from book_contracts where id = ?", [String(id || "")]);
41
+
42
+ const strategyOf = (store, id) =>
43
+ store.db.get("select * from book_strategies where id = ?", [
44
+ String(id || ""),
45
+ ]);
46
+
47
+ // The classes the person recorded for the strategy's grant; an agent's record of a grant counts for nothing here.
48
+ const grantClasses = (strategy) =>
49
+ strategy?.grant_set_by === "user"
50
+ ? JSON.parse(strategy.grant_classes || "[]")
51
+ : [];
52
+
53
+ const keeps = (store, agent) =>
54
+ agent === "user" || treasurerOf(store).agent === agent;
55
+
56
+ const update = (store, id, fields) => {
57
+ const names = Object.keys(fields);
58
+ store.db.run(
59
+ `update book_contracts set ${names.map((name) => `${name} = ?`).join(", ")}, version = version + 1, updated_at = ?
60
+ where id = ?`,
61
+ [...names.map((name) => fields[name]), now(), id]
62
+ );
63
+ return view(contractRow(store, id));
64
+ };
65
+
66
+ /** A contract as agents and the person read it, without its source and code. */
67
+ export const view = (row) =>
68
+ row && {
69
+ id: row.id,
70
+ strategy: row.strategy_id,
71
+ name: row.name,
72
+ chain: row.chain,
73
+ oneGo: Boolean(row.one_go),
74
+ buildChain: row.build_chain,
75
+ status: row.status,
76
+ codeSha256: row.code_sha256,
77
+ codeBytes: row.code_bytes == null ? null : Number(row.code_bytes),
78
+ check: row.check_by
79
+ ? {
80
+ by: row.check_by,
81
+ model: row.check_model,
82
+ sha256: row.check_sha256,
83
+ passed: Boolean(row.check_passed),
84
+ }
85
+ : null,
86
+ judge: row.judge_by
87
+ ? {
88
+ by: row.judge_by,
89
+ model: row.judge_model,
90
+ sha256: row.judge_sha256,
91
+ accepted: Boolean(row.judge_accepted),
92
+ }
93
+ : null,
94
+ approvedBy: row.approved_by,
95
+ deployTask: row.deploy_task,
96
+ address: row.address,
97
+ deployedSha256: row.deployed_sha256,
98
+ };
99
+
100
+ /** A contract the desk will build: under a strategy in the book, for one chain. The treasurer or the person. */
101
+ export function startContract(
102
+ store,
103
+ agent,
104
+ { strategy, name, chain, oneGo = false, buildChain = null }
105
+ ) {
106
+ if (!keeps(store, agent))
107
+ return {
108
+ ok: false,
109
+ error: "the treasurer or the person starts a contract",
110
+ };
111
+ if (!strategyOf(store, strategy))
112
+ return { ok: false, error: "name the strategy in the book it is for" };
113
+ const title = short(name, 120);
114
+ const target = short(chain, 40).toLowerCase();
115
+ if (!title || !target)
116
+ return {
117
+ ok: false,
118
+ error: "a contract has a name and the chain it is for",
119
+ };
120
+ const testnet = short(buildChain, 40).toLowerCase() || null;
121
+ if (oneGo && !TESTNETS.includes(testnet))
122
+ return {
123
+ ok: false,
124
+ error: `Bankr builds and deploys in one go here, so its first deploy goes to a testnet: one of ${TESTNETS.join(", ")}`,
125
+ };
126
+ const id = randomUUID();
127
+ const at = now();
128
+ store.db.run(
129
+ `insert into book_contracts(id, strategy_id, name, chain, one_go, build_chain, status, written_by, version, created_at, updated_at)
130
+ values(?, ?, ?, ?, ?, ?, 'drafting', ?, 1, ?, ?)`,
131
+ [
132
+ id,
133
+ String(strategy),
134
+ title,
135
+ target,
136
+ oneGo ? 1 : 0,
137
+ oneGo ? testnet : null,
138
+ agent,
139
+ at,
140
+ at,
141
+ ]
142
+ );
143
+ return { ok: true, contract: view(contractRow(store, id)) };
144
+ }
145
+
146
+ /** The words of Bankr's build ask: source and compiled code back, and no deploy except to a testnet in one go. */
147
+ export function buildAsk(store, id) {
148
+ const row = contractRow(store, id);
149
+ if (!row) return null;
150
+ return row.one_go
151
+ ? `Build the contract "${row.name}" and deploy it to ${row.build_chain} only, never to a main network. Return the full source, the compiled runtime bytecode as hex, the testnet address and the deploy transaction hash.`
152
+ : `Build the contract "${row.name}" for ${row.chain}. Do not deploy it. Return the full source and the compiled runtime bytecode as hex.`;
153
+ }
154
+
155
+ /**
156
+ * Bankr's build, filed by the treasurer or the person: the source and runtime code it returned. Code hashes the code;
157
+ * code filed again under a different hash clears every verdict given for the old one.
158
+ */
159
+ export function fileBuild(
160
+ store,
161
+ agent,
162
+ { contract, source, runtimeCode, buildTask = null, address = null }
163
+ ) {
164
+ const row = contractRow(store, contract);
165
+ if (!row) return { ok: false, error: "no contract in the book has that id" };
166
+ if (!keeps(store, agent))
167
+ return {
168
+ ok: false,
169
+ error: "the treasurer or the person files Bankr's build",
170
+ };
171
+ if (row.deploy_task)
172
+ return {
173
+ ok: false,
174
+ error: "this contract was already asked to deploy; start a new one",
175
+ };
176
+ const hex = hexOf(runtimeCode);
177
+ if (!hex)
178
+ return {
179
+ ok: false,
180
+ error: "the runtime code is hex, as the compiler gives it",
181
+ };
182
+ const sha256 = codeSha256(hex);
183
+ const same = sha256 === row.code_sha256;
184
+ return {
185
+ ok: true,
186
+ contract: update(store, row.id, {
187
+ source: short(source, 200_000),
188
+ runtime_code: hex,
189
+ code_sha256: sha256,
190
+ code_bytes: hex.length / 2,
191
+ build_task: short(buildTask, 120) || row.build_task,
192
+ ...(row.one_go && address
193
+ ? { address: short(address, 64).toLowerCase() }
194
+ : {}),
195
+ ...(same
196
+ ? {}
197
+ : {
198
+ check_by: null,
199
+ check_model: null,
200
+ check_sha256: null,
201
+ check_passed: null,
202
+ judge_by: null,
203
+ judge_model: null,
204
+ judge_sha256: null,
205
+ judge_accepted: null,
206
+ approved_by: null,
207
+ approved_sha256: null,
208
+ }),
209
+ status: "built",
210
+ }),
211
+ };
212
+ }
213
+
214
+ // Who may give a verdict on a contract: never the agent that executes onchain, and a verdict names the code it is for.
215
+ function verdictRefusal(row, agent, sha256) {
216
+ if (!row) return "no contract in the book has that id";
217
+ if (!row.code_sha256)
218
+ return "nothing is built yet; Bankr's build is filed first";
219
+ if (onchainExecutors().includes(agent))
220
+ return `${nameOf(agent)} built it, so it does not check or judge it`;
221
+ if (short(sha256, 64).toLowerCase() !== row.code_sha256)
222
+ return `that verdict is for other code: the code filed now has SHA-256 ${row.code_sha256}`;
223
+ return null;
224
+ }
225
+
226
+ // A verdict is a run's: filed from inside a run the daemon started (its capability, runner.mjs), on the model Harness
227
+ // chose for that run. Neither the agent nor the model is a name the caller writes, so "another reviewer on another
228
+ // model" is a fact about two runs, not two claims.
229
+ function verdictRun(store, agent, run) {
230
+ if (!run || run.agent !== agent)
231
+ return {
232
+ error:
233
+ "a check or a judgment is filed from inside the run that made it, by its Harness tools",
234
+ };
235
+ const model = store.db.get(
236
+ "select json_extract(run_model, '$.model') as model from board_tasks where id = ?",
237
+ [run.id]
238
+ )?.model;
239
+ if (!model)
240
+ return {
241
+ error:
242
+ "Harness did not choose this run's model, so its verdict cannot be told apart from another model's: give the run a model",
243
+ };
244
+ return { id: run.id, model: short(model, 100) };
245
+ }
246
+
247
+ /** The Check: a coding agent tested exactly this code on a fork with no real funds. */
248
+ export function fileCheck(store, agent, { contract, run, sha256, passed }) {
249
+ const row = contractRow(store, contract);
250
+ const refusal = verdictRefusal(row, agent, sha256);
251
+ if (refusal) return { ok: false, error: refusal };
252
+ if (!MACHINE_RUNNERS.includes(agent))
253
+ return {
254
+ ok: false,
255
+ error: "a coding agent on the person's computers checks a contract",
256
+ };
257
+ const checker = verdictRun(store, agent, run);
258
+ if (checker.error) return { ok: false, error: checker.error };
259
+ store.meta(`contract-check-run:${row.id}`, checker.id);
260
+ return {
261
+ ok: true,
262
+ contract: update(store, row.id, {
263
+ check_by: agent,
264
+ check_model: checker.model,
265
+ check_sha256: row.code_sha256,
266
+ check_passed: passed === true ? 1 : 0,
267
+ judge_by: null,
268
+ judge_model: null,
269
+ judge_sha256: null,
270
+ judge_accepted: null,
271
+ status: passed === true ? "checked" : "sent_back",
272
+ }),
273
+ };
274
+ }
275
+
276
+ /** The Judge: a reviewer on a model other than the checker's accepted exactly this code, or sent it back. */
277
+ export function fileJudge(store, agent, { contract, run, sha256, accepted }) {
278
+ const row = contractRow(store, contract);
279
+ const refusal = verdictRefusal(row, agent, sha256);
280
+ if (refusal) return { ok: false, error: refusal };
281
+ if (!row.check_passed || row.check_sha256 !== row.code_sha256)
282
+ return {
283
+ ok: false,
284
+ error: "it is judged after a check passes on this code",
285
+ };
286
+ if (agent === row.check_by)
287
+ return { ok: false, error: "the checker does not judge its own check" };
288
+ const judge = verdictRun(store, agent, run);
289
+ if (judge.error) return { ok: false, error: judge.error };
290
+ const judgeModel = judge.model;
291
+ if (judgeModel.toLowerCase() === String(row.check_model).toLowerCase())
292
+ return {
293
+ ok: false,
294
+ error: `the judge runs on a model other than the checker's (${row.check_model})`,
295
+ };
296
+ store.meta(`contract-judge-run:${row.id}`, judge.id);
297
+ return {
298
+ ok: true,
299
+ contract: update(store, row.id, {
300
+ judge_by: agent,
301
+ judge_model: judgeModel,
302
+ judge_sha256: row.code_sha256,
303
+ judge_accepted: accepted === true ? 1 : 0,
304
+ status: accepted === true ? "judged" : "sent_back",
305
+ }),
306
+ };
307
+ }
308
+
309
+ /** The person's own approval of deploying exactly this code, kept with the contract as who approved it. */
310
+ export function approveDeploy(store, agent, { contract, sha256 }) {
311
+ const row = contractRow(store, contract);
312
+ if (!row) return { ok: false, error: "no contract in the book has that id" };
313
+ if (agent !== "user")
314
+ return { ok: false, error: "only the person approves a deploy" };
315
+ if (short(sha256, 64).toLowerCase() !== row.code_sha256)
316
+ return {
317
+ ok: false,
318
+ error: `that approval is for other code: the code filed now has SHA-256 ${row.code_sha256}`,
319
+ };
320
+ return {
321
+ ok: true,
322
+ contract: update(store, row.id, {
323
+ approved_by: "user",
324
+ approved_sha256: row.code_sha256,
325
+ }),
326
+ };
327
+ }
328
+
329
+ /**
330
+ * Whether the reviewed code may be deployed now, and Bankr's deploy ask when it may: every step passed on the code
331
+ * filed now, approved by the grant or the person, under a grant the person recorded with both deploy classes.
332
+ */
333
+ export function deployRequest(store, { contract }) {
334
+ const row = contractRow(store, contract);
335
+ if (!row)
336
+ return { ok: false, refusals: ["no contract in the book has that id"] };
337
+ const strategy = strategyOf(store, row.strategy_id);
338
+ const classes = grantClasses(strategy);
339
+ const hash = row.code_sha256;
340
+ const refusals = [
341
+ !hash && "nothing is built yet",
342
+ hash &&
343
+ !(row.check_passed && row.check_sha256 === hash) &&
344
+ "no check passed on the code filed now",
345
+ hash &&
346
+ !(row.judge_accepted && row.judge_sha256 === hash) &&
347
+ "no judge accepted the code filed now",
348
+ // The grant approves within its classes; Harness's server still asks the person when the grant says to.
349
+ !DEPLOY_CLASSES.every((name) => classes.includes(name)) &&
350
+ `the person's grant for this strategy does not allow ${DEPLOY_CLASSES.join(" and ")}`,
351
+ row.deploy_task && "it was already asked to deploy",
352
+ ].filter(Boolean);
353
+ if (refusals.length) return { ok: false, refusals };
354
+ const from = row.build_task
355
+ ? ` from your build in task ${row.build_task}`
356
+ : "";
357
+ return {
358
+ ok: true,
359
+ chain: row.chain,
360
+ sha256: hash,
361
+ ask: `Deploy the contract "${row.name}" on ${row.chain}: exactly the compiled runtime code${from}, ${row.code_bytes} bytes with SHA-256 ${hash}, as reviewed. Do not rebuild or change it. Report the deployed address and the transaction hash.`,
362
+ };
363
+ }
364
+
365
+ /** The deploy ask went to Bankr as this task. */
366
+ export const markDeployAsked = (store, contract, taskId) =>
367
+ update(store, contract, { deploy_task: String(taskId), status: "deploying" });
368
+
369
+ /** The contract Bankr's deploy task was for, or null. */
370
+ export const contractOfDeploy = (store, taskId) =>
371
+ view(
372
+ store.db.get("select * from book_contracts where deploy_task = ?", [
373
+ String(taskId || ""),
374
+ ])
375
+ );
376
+
377
+ /**
378
+ * What the chain holds at the deployed address against the code reviewed: `deployed` when its SHA-256 is the reviewed
379
+ * code's, `mismatch` otherwise, and `unread` while the chain cannot be read.
380
+ */
381
+ export function verifyDeployment(store, { contract, address, deployedSha256 }) {
382
+ const row = contractRow(store, contract);
383
+ if (!row) return { ok: false, error: "no contract in the book has that id" };
384
+ const read = short(deployedSha256, 64).toLowerCase() || null;
385
+ const status = !read
386
+ ? "unread"
387
+ : read === row.code_sha256
388
+ ? "deployed"
389
+ : "mismatch";
390
+ return {
391
+ ok: status === "deployed",
392
+ status,
393
+ contract: update(store, row.id, {
394
+ address: short(address, 64).toLowerCase() || row.address,
395
+ deployed_sha256: read,
396
+ status: status === "unread" ? row.status : status,
397
+ }),
398
+ };
399
+ }
@@ -1,6 +1,10 @@
1
1
  import net from "node:net";
2
2
  import { paths } from "./paths.mjs";
3
3
 
4
+ // Inside a run Harness started, every call carries that run's capability (runner.mjs): the daemon takes it as the run's
5
+ // agent under the run's limits, whatever agent the call names. The person's own terminal and sessions have none.
6
+ const runToken = process.env.HARNESS_RUN_TOKEN;
7
+
4
8
  export function daemonRequest(message, timeoutMs = 5_000) {
5
9
  return new Promise((resolve, reject) => {
6
10
  let settled = false;
@@ -14,7 +18,11 @@ export function daemonRequest(message, timeoutMs = 5_000) {
14
18
  };
15
19
  socket.setEncoding("utf8");
16
20
  socket.setTimeout(timeoutMs);
17
- socket.on("connect", () => socket.write(JSON.stringify(message) + "\n"));
21
+ socket.on("connect", () =>
22
+ socket.write(
23
+ JSON.stringify(runToken ? { ...message, runToken } : message) + "\n"
24
+ )
25
+ );
18
26
  socket.on("data", (chunk) => {
19
27
  buffer += chunk;
20
28
  const newline = buffer.indexOf("\n");