tryharness 0.7.54 → 0.7.58

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 (156) hide show
  1. package/README.md +15 -16
  2. package/cli.mjs +384 -62
  3. package/lib/activity.mjs +10 -10
  4. package/lib/adapters.mjs +16 -0
  5. package/lib/agentBinaries.mjs +71 -0
  6. package/lib/agentRuntimeConfig.mjs +1 -1
  7. package/lib/agentRuntimes.mjs +9 -3
  8. package/lib/agentSignIn.mjs +271 -41
  9. package/lib/answers.mjs +5 -5
  10. package/lib/archetypes.d.ts +64 -0
  11. package/lib/archetypes.js +989 -0
  12. package/lib/asks.mjs +4 -4
  13. package/lib/audit.mjs +36 -13
  14. package/lib/backupSetup.mjs +4 -2
  15. package/lib/boardAccess.mjs +17 -11
  16. package/lib/boardBackup.mjs +6 -6
  17. package/lib/boardFileCommands.mjs +6 -6
  18. package/lib/boardFiles.mjs +13 -12
  19. package/lib/boardMirror.mjs +82 -47
  20. package/lib/boardProtocol.json +30 -1
  21. package/lib/boardWaits.mjs +2 -3
  22. package/lib/book.mjs +6 -6
  23. package/lib/bridge.mjs +5 -5
  24. package/lib/cards.mjs +2 -2
  25. package/lib/cloudAgents.mjs +216 -0
  26. package/lib/cloudAi.mjs +1312 -0
  27. package/lib/cloudAssistants.mjs +242 -0
  28. package/lib/cloudBoot.mjs +81 -86
  29. package/lib/cloudSave.mjs +197 -0
  30. package/lib/cloudSsh.mjs +178 -0
  31. package/lib/context.mjs +3 -3
  32. package/lib/contractGate.mjs +34 -12
  33. package/lib/control-client.mjs +9 -1
  34. package/lib/controlSocket.mjs +86 -0
  35. package/lib/coordinator.mjs +103 -101
  36. package/lib/daemon.mjs +1128 -2865
  37. package/lib/desk.mjs +7 -6
  38. package/lib/desktop.mjs +72 -68
  39. package/lib/directLink.mjs +16 -5
  40. package/lib/environment.mjs +2 -1
  41. package/lib/environments.mjs +14 -6
  42. package/lib/firewall.mjs +9 -9
  43. package/lib/folders.mjs +18 -14
  44. package/lib/frames.mjs +2 -3
  45. package/lib/gitHost.mjs +3 -3
  46. package/lib/goalCommands.mjs +25 -7
  47. package/lib/goals.mjs +7 -7
  48. package/lib/guestRequests.mjs +94 -0
  49. package/lib/handoffs.mjs +8 -7
  50. package/lib/handover.mjs +4 -4
  51. package/lib/harnessModel.mjs +6 -6
  52. package/lib/harnessOffers.mjs +266 -0
  53. package/lib/inference.mjs +26 -8
  54. package/lib/jobAnswers.mjs +190 -0
  55. package/lib/landed.mjs +1 -1
  56. package/lib/lane.mjs +42 -11
  57. package/lib/lessons.mjs +16 -16
  58. package/lib/library.mjs +3 -3
  59. package/lib/lineup.mjs +3 -0
  60. package/lib/linkRelay.mjs +574 -0
  61. package/lib/localAgentAsk.mjs +74 -0
  62. package/lib/localStack.mjs +536 -0
  63. package/lib/localmodels.mjs +6 -4
  64. package/lib/loopBackstop.mjs +4 -4
  65. package/lib/machineIdentity.mjs +9 -1
  66. package/lib/machineRoutes.mjs +181 -2
  67. package/lib/machineRuns.mjs +76 -1
  68. package/lib/machineSeal.mjs +39 -12
  69. package/lib/mcp-stdio.mjs +96 -26
  70. package/lib/mcpRelay.mjs +1 -1
  71. package/lib/members.json +13 -0
  72. package/lib/members.mjs +1 -1
  73. package/lib/models.mjs +77 -23
  74. package/lib/museSession.mjs +6 -1
  75. package/lib/nativeHost.mjs +35 -7
  76. package/lib/network.mjs +50 -5
  77. package/lib/notify.mjs +7 -5
  78. package/lib/nudge.mjs +3 -3
  79. package/lib/ocr.mjs +9 -9
  80. package/lib/onboard.mjs +141 -50
  81. package/lib/oneLine.mjs +7 -7
  82. package/lib/ownMachines.mjs +928 -149
  83. package/lib/pairing.mjs +39 -8
  84. package/lib/paths.mjs +15 -1
  85. package/lib/peerProcess.mjs +124 -0
  86. package/lib/personModel.mjs +3 -3
  87. package/lib/personNotices.mjs +151 -0
  88. package/lib/phones.mjs +490 -38
  89. package/lib/placeCommands.mjs +4 -4
  90. package/lib/places.mjs +70 -2
  91. package/lib/profile.mjs +67 -14
  92. package/lib/projectGit.mjs +158 -14
  93. package/lib/projectPieces.mjs +902 -0
  94. package/lib/projectSettings.mjs +7 -4
  95. package/lib/projects.mjs +384 -62
  96. package/lib/provenance.mjs +5 -1
  97. package/lib/proxyLinks.mjs +267 -0
  98. package/lib/reactions.mjs +7 -5
  99. package/lib/readiness.mjs +12 -7
  100. package/lib/record.mjs +19 -6
  101. package/lib/redact.mjs +4 -4
  102. package/lib/relayLimits.mjs +62 -0
  103. package/lib/release.mjs +170 -0
  104. package/lib/releaseKeys.json +6 -0
  105. package/lib/repoLinks.mjs +4 -4
  106. package/lib/roomChannels.mjs +24 -0
  107. package/lib/roomPage.mjs +1 -1
  108. package/lib/runAuthority.mjs +101 -0
  109. package/lib/runBrief.mjs +19 -8
  110. package/lib/runWorker.mjs +14 -5
  111. package/lib/runner.mjs +215 -25
  112. package/lib/runtime-install.mjs +143 -9
  113. package/lib/schedules.mjs +2 -2
  114. package/lib/screens.mjs +1 -1
  115. package/lib/sealed.mjs +11 -2
  116. package/lib/sealedThreads.mjs +671 -0
  117. package/lib/secretPatterns.json +1 -1
  118. package/lib/secrets.mjs +4 -4
  119. package/lib/seen.mjs +6 -6
  120. package/lib/serverWords.mjs +175 -0
  121. package/lib/service.mjs +22 -12
  122. package/lib/sessionControl.mjs +6 -6
  123. package/lib/specialties.mjs +6 -6
  124. package/lib/specialtyKeys.js +4 -5
  125. package/lib/specialtyNotice.mjs +7 -7
  126. package/lib/specialtySnapshot.mjs +5 -5
  127. package/lib/speech.mjs +5 -5
  128. package/lib/store.mjs +140 -39
  129. package/lib/stuck.mjs +1 -1
  130. package/lib/swarm.mjs +167 -16
  131. package/lib/swarmDevices.mjs +319 -0
  132. package/lib/swarmMemory.mjs +27 -25
  133. package/lib/t3.mjs +13 -13
  134. package/lib/taskCommands.mjs +44 -11
  135. package/lib/taskRooms.mjs +125 -0
  136. package/lib/taskRuns.mjs +36 -1
  137. package/lib/team.mjs +41 -18
  138. package/lib/threadActions.mjs +315 -0
  139. package/lib/threadAuthority.mjs +101 -0
  140. package/lib/threadBriefs.mjs +178 -0
  141. package/lib/threadLine.mjs +2 -2
  142. package/lib/threadRuns.mjs +138 -43
  143. package/lib/threadView.mjs +5 -5
  144. package/lib/usageTotals.mjs +2 -3
  145. package/lib/vault.mjs +101 -10
  146. package/lib/vaultCloud.mjs +2 -2
  147. package/lib/vaultCommands.mjs +15 -6
  148. package/lib/vaultTools.js +2 -2
  149. package/lib/verdicts.mjs +328 -0
  150. package/lib/wakes.mjs +1 -1
  151. package/lib/watches.mjs +2 -2
  152. package/lib/windowAsks.mjs +13 -5
  153. package/lib/worktrees.mjs +112 -18
  154. package/npm-shrinkwrap.json +1093 -0
  155. package/package.json +11 -10
  156. package/release.json +220 -0
@@ -0,0 +1,902 @@
1
+ import { nameOf } from "./members.mjs";
2
+ import { secretReason } from "./secrets.mjs";
3
+ import { agentModelInUse } from "./models.mjs";
4
+ import { stopAgentTask } from "./runner.mjs";
5
+ import { auditReport } from "./audit.mjs";
6
+ import {
7
+ SPECIALTIES,
8
+ headingOf,
9
+ pinnedFor,
10
+ specialtiesOf,
11
+ specialtyName,
12
+ } from "./specialties.mjs";
13
+
14
+ // Working with other people's swarms (docs/swarm-organization.md, "Working with other people's swarms"; the words are
15
+ // GLOSSARY.md's): open pieces, claims, handoffs and each person's strengths in a shared room, on top of the project's
16
+ // record (projects.mjs).
17
+ //
18
+ // - An open piece is a record entry (`piece`) with the specialty it needs and no owner. Any swarm in the room may claim
19
+ // it: each computer's own dispatcher, here in code, looks among its own agents in the room for a free one that carries
20
+ // the specialty (the person's pin first), and claims with no one's OK. No computer routes another side's agents.
21
+ // - Ownership is never an edited field, because each side changes only its own entries: it is worked out the same way on
22
+ // every computer from the entries both keep, in the order they were made. A claim takes an open piece; a handoff
23
+ // passes it on from its owner (at most HANDOFFS deep, never back to the agent it came from); a release by the owner's
24
+ // side puts it back up open. Two claims made at nearly the same moment: the first one made holds, and the computer
25
+ // whose claim lost stops its run.
26
+ // - Secrets, spending and onchain actions never go agent to agent across swarms, even in a claim: a guarded piece is
27
+ // claimed only once the person of the swarm that would take it says OK, and a guarded handoff to the other side
28
+ // waits for its receiving person. Both are proposals waiting on that one person, so they reach every surface as the
29
+ // project's own `agree` needs-you card. Words that look like a secret never leave this computer.
30
+
31
+ export const HANDOFFS = 3;
32
+ // Kinds of record entry this module adds to a project's record.
33
+ export const PIECE_KINDS = ["piece", "claim", "handoff", "accept", "release"];
34
+ const STRENGTHS = "strengths";
35
+ export const RECORD_KINDS = [...PIECE_KINDS, STRENGTHS];
36
+ // Declared side effects, as an outside agent's mandate names them (src/schemas/externalAgent.ts SIDE_EFFECT_CLASSES).
37
+ const EFFECTS = [
38
+ "financial_onchain",
39
+ "external_communications",
40
+ "account_configuration",
41
+ "code_deployment",
42
+ "file_publication",
43
+ "persistent_delegation",
44
+ ];
45
+ // What a guarded piece needs, by the effect it declares: money moving, or an account's credentials.
46
+ const GUARDED_EFFECTS = {
47
+ financial_onchain: "spending",
48
+ account_configuration: "secret",
49
+ };
50
+ const DONE = ["review", "merged"];
51
+ const OPEN_WORK = ["checking", "clear", "overlap", "clash", "unchecked"];
52
+ const SUMMARY_CHARS = 600;
53
+ // Entries that arrive together (a piece and the claim made right after it) are read before the dispatcher looks.
54
+ const SWEEP_MS = 1_500;
55
+
56
+ const sideOf = (address) => String(address).split("/")[0];
57
+ const agentOf = (address) => String(address).split("/")[1] ?? "";
58
+ const known = new Set(SPECIALTIES.map((specialty) => specialty.id));
59
+ const lineOf = (text, limit) => {
60
+ const clean = String(text || "")
61
+ .replace(/\s+/g, " ")
62
+ .trim();
63
+ return clean.length > limit ? `${clean.slice(0, limit - 1)}…` : clean;
64
+ };
65
+
66
+ /**
67
+ * Why a piece needs a person before any agent of another swarm takes it, or null when it may cross: "onchain" for a
68
+ * specialty under the onchain heading, "spending" or "secret" by the effects it declares.
69
+ */
70
+ export function guardOf(body) {
71
+ if (headingOf(body?.specialty)?.id === "onchain") return "onchain";
72
+ for (const effect of body?.effects ?? [])
73
+ if (GUARDED_EFFECTS[effect]) return GUARDED_EFFECTS[effect];
74
+ return null;
75
+ }
76
+
77
+ /**
78
+ * Who owns a piece now, worked out from the entries about it in the order they were made (ties by side, then id), so
79
+ * every computer holding the same entries agrees: `{ owner, from, depth, chain, offered, released, claimedBy }`.
80
+ */
81
+ export function ownershipOf(entries) {
82
+ const ordered = [...entries].sort(
83
+ (a, b) =>
84
+ String(a.at).localeCompare(String(b.at)) ||
85
+ a.side.localeCompare(b.side) ||
86
+ a.id.localeCompare(b.id)
87
+ );
88
+ let state = {
89
+ owner: null,
90
+ from: null,
91
+ depth: 0,
92
+ chain: [],
93
+ offered: null,
94
+ released: [],
95
+ claimedBy: null,
96
+ release: null,
97
+ };
98
+ const pass = (hop) => ({
99
+ ...state,
100
+ owner: hop.to,
101
+ from: hop.from,
102
+ depth: hop.byPerson ? 0 : state.depth + 1,
103
+ chain: [...state.chain, hop],
104
+ offered: null,
105
+ });
106
+ for (const entry of ordered) {
107
+ const body = entry.body;
108
+ if (entry.kind === "claim") {
109
+ if (state.owner || sideOf(body.agent) !== entry.side) continue;
110
+ state = {
111
+ ...state,
112
+ owner: body.agent,
113
+ from: null,
114
+ depth: 0,
115
+ chain: [],
116
+ claimedBy: entry.side,
117
+ release: null,
118
+ };
119
+ } else if (entry.kind === "handoff") {
120
+ if (
121
+ !state.owner ||
122
+ state.offered ||
123
+ body.from !== state.owner ||
124
+ sideOf(body.from) !== entry.side
125
+ )
126
+ continue;
127
+ const allowed =
128
+ body.byPerson ||
129
+ (state.depth < HANDOFFS &&
130
+ body.to !== state.from &&
131
+ body.to !== body.from);
132
+ if (!allowed) continue;
133
+ const hop = {
134
+ id: entry.id,
135
+ from: body.from,
136
+ to: body.to,
137
+ at: entry.at,
138
+ byPerson: Boolean(body.byPerson),
139
+ };
140
+ state = body.offered ? { ...state, offered: hop } : pass(hop);
141
+ } else if (entry.kind === "accept") {
142
+ if (
143
+ state.offered?.id !== body.handoff ||
144
+ sideOf(state.offered.to) !== entry.side
145
+ )
146
+ continue;
147
+ state = body.yes ? pass(state.offered) : { ...state, offered: null };
148
+ } else if (entry.kind === "release") {
149
+ if (!state.owner || sideOf(state.owner) !== entry.side) continue;
150
+ state = {
151
+ ...state,
152
+ owner: null,
153
+ from: null,
154
+ depth: 0,
155
+ offered: null,
156
+ released: [...state.released, entry.side],
157
+ release: { side: entry.side, ...body, at: entry.at },
158
+ };
159
+ }
160
+ }
161
+ return state;
162
+ }
163
+
164
+ /**
165
+ * The pieces of one shared project. Made by createProjects, which hands it the project's record (`items`, `item`,
166
+ * `write`), its names (`display`, `shared`, `local`), the room's agents (`ownAgents`, `remoteAgents`, `peopleOf`) and
167
+ * the run seams (`wakeRun`, `stopRun`, `laneOf`, `commitLane`, `changedFiles`).
168
+ */
169
+ export function createPieces({
170
+ store,
171
+ log = () => {},
172
+ project,
173
+ items,
174
+ item,
175
+ write,
176
+ propose,
177
+ note,
178
+ display,
179
+ shared,
180
+ local,
181
+ ownAgents,
182
+ remoteAgents,
183
+ peopleOf,
184
+ wakeRun,
185
+ stopRun = () => {},
186
+ laneOf,
187
+ commitLane,
188
+ changedFiles,
189
+ branchSlug,
190
+ }) {
191
+ const pieceIn = (p, id) => {
192
+ const entry = item(id);
193
+ return entry?.kind === "piece" && entry.projectId === p.id ? entry : null;
194
+ };
195
+ const eventsOf = (p, pieceId) =>
196
+ PIECE_KINDS.slice(1)
197
+ .flatMap((kind) => items(p.id, kind))
198
+ .filter((entry) => entry.body.piece === pieceId);
199
+ const stateOf = (p, pieceId) => ownershipOf(eventsOf(p, pieceId));
200
+ const workOn = (p, pieceId) =>
201
+ items(p.id, "work").filter((entry) => entry.body.piece === pieceId);
202
+ const doneOf = (p, pieceId) =>
203
+ workOn(p, pieceId).find((entry) => DONE.includes(entry.body.status)) ??
204
+ null;
205
+ const openWorkOf = (p, side, agent) =>
206
+ items(p.id, "work").find(
207
+ (entry) =>
208
+ entry.side === side &&
209
+ entry.body.agent === agent &&
210
+ OPEN_WORK.includes(entry.body.status)
211
+ ) ?? null;
212
+
213
+ // ---- this side's dispatcher ----
214
+
215
+ // Whether an agent is at work anywhere on this computer now, or on a piece of work in this project.
216
+ const busy = (p, agent) =>
217
+ Boolean(openWorkOf(p, p.me, agent)) ||
218
+ store.db.all(
219
+ "select 1 from board_tasks where target_agent = ? and status in ('claimed', 'running') limit 1",
220
+ [agent]
221
+ ).length > 0;
222
+ const carries = (agent, specialty) =>
223
+ specialtiesOf(store, agent, agentModelInUse(store, agent) ?? {}).some(
224
+ (view) => view.id === specialty
225
+ );
226
+ const primaryFor = (agent, specialty) =>
227
+ specialtiesOf(store, agent, agentModelInUse(store, agent) ?? {})[0]?.id ===
228
+ specialty;
229
+ /**
230
+ * The free agent of this side's room that fits a specialty: the person's pin for it, else one whose primary it is,
231
+ * else any that carries it. Harness answers in the person's window and holds no piece. Null when none fits now.
232
+ */
233
+ const dispatch = (p, specialty, taken) => {
234
+ const room = ownAgents(p).filter(
235
+ (agent) => agent !== "harness" && !taken.has(agent)
236
+ );
237
+ const free = room.filter((agent) => !busy(p, agent));
238
+ const pin = pinnedFor(store, specialty);
239
+ if (pin && free.includes(pin)) return pin;
240
+ const fit = free.filter((agent) => carries(agent, specialty));
241
+ return fit.find((agent) => primaryFor(agent, specialty)) ?? fit[0] ?? null;
242
+ };
243
+
244
+ const asked = (pieceId, p) => `piece-asked:${pieceId}:${p.me}`;
245
+ // Open pieces this side may take: not ours to give back (a person released it here), not already asked about.
246
+ const sweep = (p) => {
247
+ const fresh = project(p.id);
248
+ if (!fresh || fresh.status !== "open") return;
249
+ const taken = new Set();
250
+ for (const piece of items(fresh.id, "piece")) {
251
+ if (piece.body.withdrawn) continue;
252
+ const state = stateOf(fresh, piece.id);
253
+ if (state.owner || state.offered || doneOf(fresh, piece.id)) continue;
254
+ if (state.released.includes(fresh.me)) continue;
255
+ if (store.meta(asked(piece.id, fresh))) continue;
256
+ const agent = dispatch(fresh, piece.body.specialty, taken);
257
+ if (!agent) continue;
258
+ taken.add(agent);
259
+ const guard = guardOf(piece.body);
260
+ if (guard) {
261
+ store.meta(asked(piece.id, fresh), "1");
262
+ propose(
263
+ fresh,
264
+ {
265
+ type: "claim",
266
+ piece: piece.id,
267
+ agent,
268
+ guard,
269
+ needs: [fresh.me],
270
+ text: `${nameOf(agent)} would take the open piece "${lineOf(piece.body.summary, 160)}" (${specialtyName(piece.body.specialty)}). ${GUARD_WORDS[guard]} never goes from agent to agent between swarms, so it waits for you.`,
271
+ },
272
+ agent
273
+ );
274
+ continue;
275
+ }
276
+ write(fresh, "claim", {
277
+ piece: piece.id,
278
+ agent: shared(fresh, agent),
279
+ });
280
+ log(`project ${fresh.id}: ${agent} claimed piece ${piece.id}`);
281
+ }
282
+ };
283
+ const timers = new Map();
284
+ const sweepSoon = (p) => {
285
+ if (timers.has(p.id)) return;
286
+ const timer = setTimeout(() => {
287
+ timers.delete(p.id);
288
+ try {
289
+ sweep(p);
290
+ } catch (error) {
291
+ log(`project pieces: ${error.message}`);
292
+ }
293
+ }, SWEEP_MS);
294
+ timer.unref?.();
295
+ timers.set(p.id, timer);
296
+ };
297
+
298
+ // ---- runs on a piece ----
299
+
300
+ const reasonFor = (p, piece, state) => {
301
+ const what = `"${lineOf(piece.body.summary, 300)}" (${specialtyName(piece.body.specialty)})`;
302
+ const before = state.release?.branch
303
+ ? ` Work done on it before is on branch ${state.release.branch}.`
304
+ : "";
305
+ const hop = state.chain.at(-1);
306
+ if (!hop)
307
+ return `Your swarm claimed the open piece ${what} in this shared room. You own it now: build it on your own branch and call plan_work with done when it is ready.${before}`;
308
+ const left = HANDOFFS - state.depth;
309
+ return `${display(p, hop.from)} handed you the piece ${what}. You own it now; ${display(p, hop.from)} stays accountable until you report it done with plan_work.${before} ${left > 0 ? `You may hand it on with plan_work hand_to (${left} more time${left === 1 ? "" : "s"} at most, never back to ${display(p, hop.from)}).` : "It has been handed on as often as it may be; past this a person decides."}`;
310
+ };
311
+ // The owning agent on this side starts on the piece: its own piece of work, checked like any other, then its run.
312
+ const begin = (p, piece, state) => {
313
+ const agent = agentOf(state.owner);
314
+ // Taken up by other work since it was chosen: the piece goes back up rather than sit held with nobody on it.
315
+ if (openWorkOf(p, p.me, agent)) {
316
+ write(p, "release", { piece: piece.id });
317
+ note(
318
+ p,
319
+ `${nameOf(agent)} was busy by the time "${lineOf(piece.body.summary, 90)}" reached it, so the piece is open again.`
320
+ );
321
+ return;
322
+ }
323
+ const hop = state.chain.at(-1);
324
+ const accepted = state.acceptedBy === p.me;
325
+ const asker = hop?.from ?? piece.body.by ?? `${piece.side}/person`;
326
+ // A claim needs no OK; nor does what this side's person said yes to. A handoff from another swarm is work the
327
+ // other side pushed at a named agent, which `start` governs (projects.mjs gate).
328
+ const go =
329
+ !hop ||
330
+ accepted ||
331
+ (hop.byPerson && sideOf(hop.from) === p.me) ||
332
+ Boolean(state.claimByPerson);
333
+ write(p, "work", {
334
+ agent,
335
+ piece: piece.id,
336
+ summary: String(piece.body.summary).slice(0, SUMMARY_CHARS),
337
+ touches: [],
338
+ files: [],
339
+ status: "checking",
340
+ base: p.repo.head,
341
+ branch: `${p.me}/${agent}/${branchSlug(piece.body.summary)}`,
342
+ startedFor: asker,
343
+ });
344
+ if (!p.roomId) return;
345
+ wakeRun(p.roomId, agent, reasonFor(p, piece, state), {
346
+ go,
347
+ asker: local(p, asker),
348
+ words: String(piece.body.summary).slice(0, SUMMARY_CHARS),
349
+ });
350
+ };
351
+ /** This side's run on a piece ends where it is: stopped, its changes committed on its branch. */
352
+ const halted = (p, agent) => `piece-halted:${p.id}:${agent}`;
353
+ const halt = (p, work, fields) => {
354
+ // A run still going commits as it ends, into this piece's branch (projects.mjs committed, stoppedWork).
355
+ if (
356
+ p.roomId &&
357
+ store
358
+ .threadRuns(p.roomId)
359
+ .some(
360
+ (run) =>
361
+ run.target_agent === work.body.agent && run.status === "running"
362
+ )
363
+ )
364
+ store.meta(halted(p, work.body.agent), work.id);
365
+ if (p.roomId) stopRun(p.roomId, work.body.agent);
366
+ const where = p.folder ? laneOf(p, work) : null;
367
+ const sha = where
368
+ ? commitLane(
369
+ where,
370
+ `${work.body.agent}: ${lineOf(work.body.summary, 150)} (stopped)`
371
+ )
372
+ : null;
373
+ write(
374
+ p,
375
+ "work",
376
+ {
377
+ status: "stopped",
378
+ ...(sha
379
+ ? { head: sha, files: changedFiles(where, work.body.base) }
380
+ : {}),
381
+ ...fields,
382
+ },
383
+ work.id
384
+ );
385
+ };
386
+
387
+ // ---- accountability ----
388
+
389
+ // The sender's run that handed the piece on stays accountable until the receiver reports: its report is audited
390
+ // with the handoff still open (audit.mjs piece_open), and again once the receiver reports.
391
+ const accountKey = (taskId) => `handoffs-open:${taskId}`;
392
+ const openOf = (taskId) => {
393
+ try {
394
+ return JSON.parse(store.meta(accountKey(taskId)) || "[]");
395
+ } catch {
396
+ return [];
397
+ }
398
+ };
399
+ const holdAccountable = (p, agent, hop, to) => {
400
+ const run = store
401
+ .threadRuns(p.roomId)
402
+ .filter((entry) => entry.target_agent === agent)
403
+ .at(-1);
404
+ if (!run) return;
405
+ store.meta(`handoff-run:${hop}`, run.id);
406
+ store.meta(
407
+ accountKey(run.id),
408
+ JSON.stringify([...openOf(run.id), { handoff: hop, to }])
409
+ );
410
+ auditReport(store, run.id);
411
+ };
412
+ const settleAccounts = (p, state, pieceId) => {
413
+ const done = doneOf(p, pieceId);
414
+ for (const hop of state.chain) {
415
+ if (sideOf(hop.from) !== p.me) continue;
416
+ const runId = store.meta(`handoff-run:${hop.id}`);
417
+ if (!runId) continue;
418
+ const reported = done && String(done.updatedAt) >= String(hop.at);
419
+ if (!reported) continue;
420
+ const left = openOf(runId).filter((entry) => entry.handoff !== hop.id);
421
+ if (left.length === openOf(runId).length) continue;
422
+ store.meta(accountKey(runId), JSON.stringify(left));
423
+ auditReport(store, runId);
424
+ }
425
+ };
426
+
427
+ // ---- what changed in the record ----
428
+
429
+ const settle = (p, pieceId) => {
430
+ const piece = pieceIn(p, pieceId);
431
+ if (!piece) return;
432
+ const raw = stateOf(p, pieceId);
433
+ const acceptedHop = raw.chain
434
+ .map((hop) =>
435
+ items(p.id, "accept").find(
436
+ (entry) => entry.body.handoff === hop.id && entry.side === p.me
437
+ )
438
+ )
439
+ .filter(Boolean)
440
+ .at(-1);
441
+ const claim = items(p.id, "claim")
442
+ .filter(
443
+ (entry) =>
444
+ entry.body.piece === pieceId &&
445
+ entry.body.agent === raw.owner &&
446
+ !raw.chain.length
447
+ )
448
+ .at(-1);
449
+ const state = {
450
+ ...raw,
451
+ acceptedBy:
452
+ acceptedHop?.body.handoff === raw.chain.at(-1)?.id ? p.me : null,
453
+ claimByPerson: Boolean(claim?.body.byPerson),
454
+ };
455
+ // This side's runs on the piece that no longer own it stop: a claim that lost, a piece handed on or released.
456
+ for (const work of workOn(p, pieceId).filter(
457
+ (entry) => entry.side === p.me && OPEN_WORK.includes(entry.body.status)
458
+ )) {
459
+ // A run stopped by a settle this one set off is not stopped twice.
460
+ if (!OPEN_WORK.includes(item(work.id)?.body.status)) continue;
461
+ if (state.owner !== `${p.me}/${work.body.agent}`) {
462
+ const handed = state.chain.find(
463
+ (hop) => hop.from === `${p.me}/${work.body.agent}`
464
+ );
465
+ const released = !state.owner && state.release?.side === p.me;
466
+ halt(
467
+ p,
468
+ work,
469
+ handed
470
+ ? { handedTo: handed.to }
471
+ : released
472
+ ? { released: true }
473
+ : { lost: true }
474
+ );
475
+ if (!handed && !released)
476
+ note(
477
+ p,
478
+ `${nameOf(work.body.agent)} stopped on "${lineOf(piece.body.summary, 90)}": another claim on it was made first. Its work so far stays on ${work.body.branch}.`
479
+ );
480
+ }
481
+ }
482
+ if (
483
+ state.owner &&
484
+ sideOf(state.owner) === p.me &&
485
+ !doneOf(p, pieceId) &&
486
+ !workOn(p, pieceId).some(
487
+ (entry) =>
488
+ entry.side === p.me &&
489
+ entry.body.agent === agentOf(state.owner) &&
490
+ String(entry.at) >= String(state.chain.at(-1)?.at ?? claim?.at ?? "")
491
+ )
492
+ )
493
+ begin(p, piece, state);
494
+ // A guarded handoff from another swarm to an agent here waits for this person.
495
+ const offered = state.offered;
496
+ if (
497
+ offered &&
498
+ sideOf(offered.to) === p.me &&
499
+ sideOf(offered.from) !== p.me &&
500
+ !store.meta(`handoff-asked:${offered.id}`)
501
+ ) {
502
+ store.meta(`handoff-asked:${offered.id}`, "1");
503
+ propose(
504
+ p,
505
+ {
506
+ type: "handoff",
507
+ piece: pieceId,
508
+ handoff: offered.id,
509
+ needs: [p.me],
510
+ text: `${display(p, offered.from)} hands ${nameOf(agentOf(offered.to))} the piece "${lineOf(piece.body.summary, 160)}" (${specialtyName(piece.body.specialty)}). ${GUARD_WORDS[guardOf(piece.body)]} never goes from agent to agent between swarms, so it waits for you.`,
511
+ },
512
+ agentOf(offered.to)
513
+ );
514
+ }
515
+ settleAccounts(p, state, pieceId);
516
+ sweepSoon(p);
517
+ };
518
+
519
+ /** An entry of the project's record was made here or arrived: the pieces it touches settle, and the dispatcher looks. */
520
+ const changed = (p, entry) => {
521
+ if (!p || !entry || p.status !== "open") return;
522
+ if (entry.kind === "piece") return sweepSoon(p);
523
+ if (PIECE_KINDS.includes(entry.kind)) return settle(p, entry.body.piece);
524
+ if (entry.kind !== "work") return;
525
+ if (entry.body.piece) settle(p, entry.body.piece);
526
+ // An agent here came free: an open piece may fit it now.
527
+ else if (entry.side === p.me && !OPEN_WORK.includes(entry.body.status))
528
+ sweepSoon(p);
529
+ };
530
+
531
+ /** A person said yes to a claim or a handoff that waited for them. */
532
+ const accepted = (p, proposal) => {
533
+ if (proposal.side !== p.me) return;
534
+ const body = proposal.body;
535
+ if (body.type === "claim") {
536
+ const state = stateOf(p, body.piece);
537
+ if (state.owner || !pieceIn(p, body.piece)) {
538
+ note(p, "That piece was taken before your OK: nothing changed.");
539
+ return;
540
+ }
541
+ write(p, "claim", {
542
+ piece: body.piece,
543
+ agent: shared(p, body.agent),
544
+ byPerson: true,
545
+ });
546
+ return;
547
+ }
548
+ if (body.type === "handoff" && body.handoff) {
549
+ write(p, "accept", {
550
+ piece: body.piece,
551
+ handoff: body.handoff,
552
+ yes: true,
553
+ });
554
+ return;
555
+ }
556
+ if (body.type === "handoff" && body.from) {
557
+ // Past the limit, the person passes it on themselves: a fresh start for its chain.
558
+ const state = stateOf(p, body.piece);
559
+ if (state.owner !== body.from) {
560
+ note(p, "That piece moved before your OK: nothing changed.");
561
+ return;
562
+ }
563
+ handOn(p, body.piece, body.from, body.to, { byPerson: true });
564
+ }
565
+ };
566
+ /** A person said no: a guarded handoff from another swarm goes back to its sender. */
567
+ const declined = (p, proposal) => {
568
+ if (proposal.side !== p.me) return;
569
+ if (proposal.body.type === "handoff" && proposal.body.handoff)
570
+ write(p, "accept", {
571
+ piece: proposal.body.piece,
572
+ handoff: proposal.body.handoff,
573
+ yes: false,
574
+ });
575
+ };
576
+
577
+ // ---- commands ----
578
+
579
+ const post = (p, by, { summary, specialty, effects }) => {
580
+ const text = String(summary || "").trim();
581
+ if (!text) throw new Error("say what the piece is (summary)");
582
+ if (!known.has(String(specialty)))
583
+ throw new Error(
584
+ `name the specialty it needs, one of: ${SPECIALTIES.map((entry) => entry.id).join(", ")}`
585
+ );
586
+ const secret = secretReason(text);
587
+ if (secret)
588
+ throw new Error(
589
+ `It looks like it holds ${secret}, which never goes to another swarm. Put the piece up without it.`
590
+ );
591
+ const declared = (Array.isArray(effects) ? effects : [])
592
+ .map(String)
593
+ .filter((effect) => EFFECTS.includes(effect));
594
+ const piece = write(p, "piece", {
595
+ summary: text.slice(0, SUMMARY_CHARS),
596
+ specialty: String(specialty),
597
+ effects: [...new Set(declared)],
598
+ by: shared(p, by),
599
+ });
600
+ return { ok: true, piece: piece.id, guard: guardOf(piece.body) };
601
+ };
602
+
603
+ // A handoff from the piece's owner on this side; `offered` when it waits for the receiving person.
604
+ const handOn = (p, pieceId, from, to, { byPerson = false } = {}) => {
605
+ const piece = pieceIn(p, pieceId);
606
+ const across = sideOf(to) !== p.me;
607
+ const offered = across && Boolean(guardOf(piece.body));
608
+ const hop = write(p, "handoff", {
609
+ piece: pieceId,
610
+ from,
611
+ to,
612
+ ...(byPerson ? { byPerson: true } : {}),
613
+ ...(offered ? { offered: true } : {}),
614
+ });
615
+ holdAccountable(p, agentOf(from), hop.id, display(p, to));
616
+ return { hop, offered };
617
+ };
618
+
619
+ const handoff = (p, agent, { to }) => {
620
+ const from = `${p.me}/${agent}`;
621
+ const piece = items(p.id, "piece").find(
622
+ (entry) => stateOf(p, entry.id).owner === from && !doneOf(p, entry.id)
623
+ );
624
+ if (!piece)
625
+ throw new Error("You hold no piece in this project to hand on.");
626
+ const state = stateOf(p, piece.id);
627
+ const named = String(to || "")
628
+ .trim()
629
+ .replace(/^@/, "");
630
+ const target = named.includes("/")
631
+ ? remoteAgents(p).find((entry) => entry.address === named)?.address
632
+ : ownAgents(p).includes(named)
633
+ ? `${p.me}/${named}`
634
+ : null;
635
+ if (!target || agentOf(target) === "harness")
636
+ throw new Error(
637
+ `Hand it to an agent in this room: one of yours by name, or the other side's by its full name (${remoteAgents(
638
+ p
639
+ )
640
+ .map((entry) => `@${entry.address}`)
641
+ .join(", ")}).`
642
+ );
643
+ if (target === from) throw new Error("You already hold it.");
644
+ if (state.offered)
645
+ throw new Error("Its last handoff still waits for the receiving person.");
646
+ if (target === state.from)
647
+ throw new Error(
648
+ `It came from ${display(p, target)}; a piece never goes back to the agent it came from.`
649
+ );
650
+ if (openWorkOf(p, sideOf(target), agentOf(target)))
651
+ throw new Error(`${display(p, target)} is busy with another piece.`);
652
+ if (state.depth >= HANDOFFS) {
653
+ const waiting = items(p.id, "proposal").some(
654
+ (entry) =>
655
+ entry.body.type === "handoff" &&
656
+ entry.body.piece === piece.id &&
657
+ !entry.body.withdrawn &&
658
+ !store.meta(`project-accepted:${entry.id}`)
659
+ );
660
+ if (!waiting)
661
+ propose(
662
+ p,
663
+ {
664
+ type: "handoff",
665
+ piece: piece.id,
666
+ from,
667
+ to: target,
668
+ needs: [p.me],
669
+ text: `${nameOf(agent)} wants to pass "${lineOf(piece.body.summary, 160)}" to ${display(p, target)}. It has been handed on ${HANDOFFS} times, so a person decides who takes it next.`,
670
+ },
671
+ agent
672
+ );
673
+ return {
674
+ ok: true,
675
+ waiting: "person",
676
+ note: `It has been handed on ${HANDOFFS} times, so your person decides. Keep it until they do.`,
677
+ };
678
+ }
679
+ const { offered } = handOn(p, piece.id, from, target);
680
+ return {
681
+ ok: true,
682
+ handedTo: display(p, target),
683
+ ...(offered
684
+ ? {
685
+ waiting: "person",
686
+ note: `${GUARD_WORDS[guardOf(piece.body)]} never goes from agent to agent between swarms: it waits for ${sideOf(target)} to OK it. Keep it until then.`,
687
+ }
688
+ : {
689
+ note: "You stay accountable for it until the receiver reports it done.",
690
+ }),
691
+ };
692
+ };
693
+
694
+ /** The person whose swarm holds a piece gives it back: its run stops, its work stays on its branch, it is open again. */
695
+ const release = (p, pieceId) => {
696
+ const piece = pieceIn(p, pieceId);
697
+ if (!piece) throw new Error("That piece isn't here.");
698
+ const state = stateOf(p, pieceId);
699
+ if (!state.owner || sideOf(state.owner) !== p.me)
700
+ throw new Error("Only a piece your swarm holds can be released.");
701
+ const work = workOn(p, pieceId)
702
+ .filter((entry) => entry.side === p.me)
703
+ .at(-1);
704
+ write(p, "release", {
705
+ piece: pieceId,
706
+ ...(work ? { branch: work.body.branch } : {}),
707
+ });
708
+ note(
709
+ project(p.id),
710
+ `You released "${lineOf(piece.body.summary, 90)}". It is open again${work ? `; the work so far stays on ${work.body.branch}` : ""}.`
711
+ );
712
+ return { ok: true };
713
+ };
714
+
715
+ /** The person's and agents' piece commands; null for a command that isn't one. */
716
+ const command = (p, name, request, agent) => {
717
+ if (name === "board.project.piece")
718
+ return post(p, agent === "user" ? "user" : agent, request);
719
+ if (name === "board.project.release" && agent === "user")
720
+ return release(p, String(request.piece || ""));
721
+ if (name === "board.project.handoff" && agent !== "user")
722
+ return handoff(p, agent, request);
723
+ return null;
724
+ };
725
+
726
+ // ---- strengths ----
727
+
728
+ /** This side's strengths in the room: the headings of the specialties its agents here carry, never their record. */
729
+ const headingsHere = (p) =>
730
+ [
731
+ ...new Set(
732
+ ownAgents(p).flatMap((agent) =>
733
+ specialtiesOf(store, agent, agentModelInUse(store, agent) ?? {})
734
+ .map((view) => headingOf(view.id)?.id)
735
+ .filter(Boolean)
736
+ )
737
+ ),
738
+ ].sort();
739
+ const strengthsId = (p) => `${STRENGTHS}:${p.id}:${p.me}`;
740
+ const shareStrengths = (p) => {
741
+ const headings = headingsHere(p);
742
+ const current = item(strengthsId(p));
743
+ if (
744
+ JSON.stringify(current?.body.headings ?? null) ===
745
+ JSON.stringify(headings)
746
+ )
747
+ return;
748
+ write(p, STRENGTHS, { headings }, strengthsId(p));
749
+ };
750
+ const strengthsOf = (p) =>
751
+ Object.fromEntries(
752
+ items(p.id, STRENGTHS).map((entry) => [
753
+ entry.side,
754
+ (entry.body.headings ?? [])
755
+ .map((id) => HEADING_NAMES[id])
756
+ .filter(Boolean),
757
+ ])
758
+ );
759
+
760
+ // ---- what the person reads ----
761
+
762
+ const view = (p) => {
763
+ // A person reading the room keeps it current: their strengths shared once they change (a specialty added), and
764
+ // open pieces looked at again for an agent that fits now.
765
+ if (p.status === "open") {
766
+ shareStrengths(p);
767
+ sweepSoon(p);
768
+ }
769
+ const strengths = strengthsOf(p);
770
+ const people = peopleOf(p);
771
+ return items(p.id, "piece")
772
+ .filter((piece) => !piece.body.withdrawn)
773
+ .map((piece) => {
774
+ const state = stateOf(p, piece.id);
775
+ const heading = headingOf(piece.body.specialty);
776
+ const waiting = items(p.id, "proposal").some(
777
+ (entry) =>
778
+ ["claim", "handoff"].includes(entry.body.type) &&
779
+ entry.body.piece === piece.id &&
780
+ entry.side === p.me &&
781
+ !entry.body.withdrawn &&
782
+ !store.meta(`project-accepted:${entry.id}`) &&
783
+ !items(p.id, "answer").some(
784
+ (answer) =>
785
+ answer.body.proposal === entry.id && answer.body.yes === false
786
+ )
787
+ );
788
+ const done = doneOf(p, piece.id);
789
+ const hop = state.chain.at(-1);
790
+ return {
791
+ id: piece.id,
792
+ summary: piece.body.summary,
793
+ specialty: piece.body.specialty,
794
+ specialtyName: specialtyName(piece.body.specialty),
795
+ guard: guardOf(piece.body),
796
+ by: display(p, piece.body.by ?? `${piece.side}/person`),
797
+ state: done
798
+ ? "done"
799
+ : waiting || state.offered
800
+ ? "waiting"
801
+ : state.owner
802
+ ? "held"
803
+ : "open",
804
+ owner: state.owner
805
+ ? {
806
+ who: display(p, state.owner),
807
+ you: sideOf(state.owner) === p.me,
808
+ agent: agentOf(state.owner),
809
+ }
810
+ : null,
811
+ // Whose swarm a piece fits, from the strengths each side shares; a suggestion that never assigns.
812
+ fits: people.filter((handle) =>
813
+ heading
814
+ ? (strengths[handle] ?? []).includes(HEADING_NAMES[heading.id])
815
+ : false
816
+ ),
817
+ handoffs: state.chain.map((entry) => ({
818
+ from: display(p, entry.from),
819
+ to: display(p, entry.to),
820
+ reported: Boolean(
821
+ done && String(done.updatedAt) >= String(entry.at)
822
+ ),
823
+ })),
824
+ accountable:
825
+ hop && !(done && String(done.updatedAt) >= String(hop.at))
826
+ ? display(p, hop.from)
827
+ : null,
828
+ mayRelease: Boolean(state.owner) && sideOf(state.owner) === p.me,
829
+ at: piece.at,
830
+ };
831
+ });
832
+ };
833
+
834
+ /** What an agent in the room is told of the pieces, beside the rest of the project's record. */
835
+ const brief = (p, agent) => {
836
+ const pieces = view(p).filter((piece) => piece.state !== "done");
837
+ const own = pieces.find(
838
+ (piece) => piece.owner?.you && piece.owner.agent === agent
839
+ );
840
+ const state = own ? stateOf(p, own.id) : null;
841
+ return [
842
+ pieces.length
843
+ ? `Open pieces of this project (a swarm's dispatcher claims one for a free agent that fits; nobody routes another swarm's agents):\n${pieces
844
+ .map(
845
+ (piece) =>
846
+ `- "${lineOf(piece.summary, 160)}" needs ${piece.specialtyName}${piece.owner ? `, held by ${piece.owner.who}` : piece.state === "waiting" ? ", waiting for a person" : ", open"}`
847
+ )
848
+ .join("\n")}`
849
+ : "",
850
+ own
851
+ ? `You hold the piece "${lineOf(own.summary, 160)}". To pass it to another agent here, call plan_work with hand_to (one of your swarm's agents by name, or the other side's by its full name); you stay accountable until it reports. A piece is handed on at most ${HANDOFFS} times (${HANDOFFS - state.depth} left) and never back to the agent it came from.`
852
+ : "",
853
+ "To put up a piece any swarm in the room may claim, call plan_work with open and the specialty it needs. Secrets, spending and onchain actions never go from agent to agent between swarms: such a piece waits for a person.",
854
+ ]
855
+ .filter(Boolean)
856
+ .join("\n");
857
+ };
858
+
859
+ /** Keeping up: this side's strengths shared when they change, and open pieces looked at again. */
860
+ const refresh = (p) => {
861
+ if (p.status !== "open") return;
862
+ shareStrengths(p);
863
+ sweepSoon(p);
864
+ };
865
+
866
+ /** The work entry of this side's run stopped on a piece, once, for that run's end to commit into its branch. */
867
+ const stoppedWork = (p, agent) => {
868
+ const id = store.meta(halted(p, agent));
869
+ if (!id) return null;
870
+ store.meta(halted(p, agent), "");
871
+ return item(id);
872
+ };
873
+
874
+ return {
875
+ changed,
876
+ accepted,
877
+ declined,
878
+ command,
879
+ view,
880
+ strengthsOf,
881
+ brief,
882
+ refresh,
883
+ stoppedWork,
884
+ stop: () => {
885
+ for (const timer of timers.values()) clearTimeout(timer);
886
+ timers.clear();
887
+ },
888
+ };
889
+ }
890
+
891
+ const GUARD_WORDS = {
892
+ onchain: "Onchain work",
893
+ spending: "Spending",
894
+ secret: "Anything that needs a secret",
895
+ };
896
+ // Headings as a room's People block says them: "onchain, research".
897
+ const HEADING_NAMES = Object.fromEntries(
898
+ SPECIALTIES.map((specialty) => [
899
+ specialty.heading,
900
+ headingOf(specialty.id).name.toLowerCase(),
901
+ ])
902
+ );