tryharness 0.7.82 → 0.7.86

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 (216) hide show
  1. package/README.md +21 -19
  2. package/assets/dsh-plugin.mjs +75 -4
  3. package/assets/herdr-mod/harness/main.js +367 -0
  4. package/assets/herdr-mod/harness/mod.json +6 -0
  5. package/assets/opencode-plugin.js +87 -22
  6. package/assets/pi-extension.ts +81 -2
  7. package/cli.mjs +544 -208
  8. package/lib/adapters.mjs +62 -27
  9. package/lib/agentBinaries.mjs +6 -8
  10. package/lib/agentClaims.mjs +168 -0
  11. package/lib/agentReadTools.json +415 -0
  12. package/lib/agentSignIn.mjs +17 -18
  13. package/lib/agentWiring.mjs +114 -0
  14. package/lib/archetypes.js +10 -11
  15. package/lib/attention.mjs +100 -0
  16. package/lib/audit.mjs +1 -1
  17. package/lib/backupSetup.mjs +6 -28
  18. package/lib/bankrApprovals.mjs +86 -0
  19. package/lib/boardAccess.mjs +40 -66
  20. package/lib/boardBackup.mjs +86 -85
  21. package/lib/boardCommands.mjs +28 -0
  22. package/lib/boardFileCommands.mjs +29 -36
  23. package/lib/boardFiles.mjs +83 -15
  24. package/lib/boardMirror.mjs +78 -11
  25. package/lib/boardProtocol.json +193 -123
  26. package/lib/boardThreads.mjs +19 -37
  27. package/lib/boardTools.mjs +22 -15
  28. package/lib/boardWatches.mjs +43 -15
  29. package/lib/bridge.mjs +7 -3
  30. package/lib/browserAgentTools.mjs +59 -0
  31. package/lib/browserWake.mjs +0 -6
  32. package/lib/cards.mjs +57 -2
  33. package/lib/circling.mjs +189 -0
  34. package/lib/cleanup.mjs +234 -0
  35. package/lib/cloudBoot.mjs +21 -4
  36. package/lib/cloudSave.mjs +46 -5
  37. package/lib/compaction.mjs +8 -1
  38. package/lib/completion.mjs +358 -0
  39. package/lib/computerDevices.mjs +853 -0
  40. package/lib/connectionStatus.mjs +34 -0
  41. package/lib/connectors.mjs +139 -1
  42. package/lib/coordinator.mjs +108 -14
  43. package/lib/coreModels.mjs +36 -12
  44. package/lib/daemon.mjs +2435 -333
  45. package/lib/daemonLock.mjs +103 -0
  46. package/lib/deviceDoor.mjs +308 -0
  47. package/lib/deviceIdentity.mjs +114 -0
  48. package/lib/deviceList.mjs +172 -0
  49. package/lib/deviceSeal.mjs +74 -0
  50. package/lib/dispatcher.mjs +497 -26
  51. package/lib/dispatches.mjs +3 -3
  52. package/lib/environment.mjs +2 -1
  53. package/lib/environments.mjs +67 -41
  54. package/lib/events.mjs +318 -0
  55. package/lib/facts.mjs +170 -0
  56. package/lib/fileSource.mjs +540 -0
  57. package/lib/files.mjs +47 -2
  58. package/lib/gitHost.mjs +39 -1
  59. package/lib/goalCommands.mjs +12 -80
  60. package/lib/handover.mjs +21 -16
  61. package/lib/harnessOffers.mjs +140 -15
  62. package/lib/herdr.mjs +100 -15
  63. package/lib/herdrAppCall.mjs +19 -0
  64. package/lib/herdrCore.mjs +59 -0
  65. package/lib/herdrRuns.mjs +1126 -0
  66. package/lib/hookDialects.mjs +235 -50
  67. package/lib/identityLink.mjs +81 -0
  68. package/lib/inference.mjs +31 -2
  69. package/lib/jamAccess.mjs +82 -0
  70. package/lib/{projectBoard.mjs → jamBoard.mjs} +5 -4
  71. package/lib/{projectGit.mjs → jamGit.mjs} +53 -15
  72. package/lib/jamKey.mjs +274 -0
  73. package/lib/{projectPieces.mjs → jamPieces.mjs} +35 -29
  74. package/lib/{projectSettings.mjs → jamSettings.mjs} +12 -22
  75. package/lib/jamStore.mjs +973 -0
  76. package/lib/jamUpgrade.mjs +112 -0
  77. package/lib/jams.mjs +3079 -0
  78. package/lib/kanban.mjs +13 -7
  79. package/lib/landed.mjs +5 -1
  80. package/lib/library.mjs +41 -22
  81. package/lib/limits.mjs +91 -0
  82. package/lib/lineDiff.mjs +97 -0
  83. package/lib/lineup.mjs +18 -13
  84. package/lib/link.mjs +584 -0
  85. package/lib/localStack.mjs +75 -16
  86. package/lib/localmodels.mjs +58 -78
  87. package/lib/loopBackstop.mjs +2 -1
  88. package/lib/machine.mjs +544 -0
  89. package/lib/machineLink.mjs +446 -0
  90. package/lib/machineRoutes.mjs +68 -19
  91. package/lib/machineRuns.mjs +85 -4
  92. package/lib/machineSeal.mjs +6 -31
  93. package/lib/manager.mjs +134 -12
  94. package/lib/mcp-stdio.mjs +492 -215
  95. package/lib/mcpRelay.mjs +34 -35
  96. package/lib/members.json +2 -2
  97. package/lib/modelRoute.mjs +162 -0
  98. package/lib/nativeHost.mjs +81 -90
  99. package/lib/nativeSenses.mjs +258 -0
  100. package/lib/nerves.mjs +523 -0
  101. package/lib/network.mjs +117 -278
  102. package/lib/networkPlaces.mjs +578 -0
  103. package/lib/nextStep.mjs +95 -0
  104. package/lib/notify.mjs +2 -2
  105. package/lib/nudge.mjs +116 -10
  106. package/lib/onboard.mjs +6 -6
  107. package/lib/originals.mjs +216 -0
  108. package/lib/outsideEvents.mjs +383 -0
  109. package/lib/outsideRuns.mjs +230 -0
  110. package/lib/ownMachines.mjs +674 -256
  111. package/lib/pain.mjs +215 -0
  112. package/lib/pairing.mjs +91 -11
  113. package/lib/paths.mjs +42 -3
  114. package/lib/peerProcess.mjs +21 -7
  115. package/lib/peopleLink.mjs +268 -0
  116. package/lib/personNotices.mjs +3 -2
  117. package/lib/phones.mjs +252 -542
  118. package/lib/placeCards.mjs +282 -0
  119. package/lib/placeChecks.mjs +95 -0
  120. package/lib/placeCommands.mjs +8 -17
  121. package/lib/placeRequests.mjs +152 -0
  122. package/lib/placeStore.mjs +295 -0
  123. package/lib/placeTool.d.ts +12 -0
  124. package/lib/placeTool.js +40 -0
  125. package/lib/places.mjs +63 -14
  126. package/lib/plans.mjs +53 -8
  127. package/lib/presence.mjs +270 -0
  128. package/lib/privateNetwork.d.ts +2 -0
  129. package/lib/privateNetwork.js +93 -0
  130. package/lib/proposals.mjs +300 -0
  131. package/lib/publicFetch.d.ts +32 -0
  132. package/lib/publicFetch.js +248 -0
  133. package/lib/reach.mjs +128 -0
  134. package/lib/rebuildable.mjs +72 -0
  135. package/lib/recall.mjs +216 -0
  136. package/lib/record.mjs +13 -0
  137. package/lib/reflexes.mjs +392 -0
  138. package/lib/relayLimits.mjs +31 -2
  139. package/lib/releaseNotice.mjs +198 -0
  140. package/lib/removeHarness.mjs +15 -4
  141. package/lib/repoLinks.mjs +204 -35
  142. package/lib/runAuthority.mjs +102 -39
  143. package/lib/runBrief.mjs +93 -40
  144. package/lib/runRequests.mjs +52 -14
  145. package/lib/runUsage.mjs +31 -0
  146. package/lib/runWorker.mjs +74 -25
  147. package/lib/runner.mjs +289 -45
  148. package/lib/runtime-install.mjs +37 -8
  149. package/lib/schedules.mjs +171 -47
  150. package/lib/screenWatches.mjs +221 -0
  151. package/lib/sealed.mjs +12 -30
  152. package/lib/sealedThreads.mjs +198 -392
  153. package/lib/secretStore.mjs +178 -0
  154. package/lib/secrets.mjs +11 -0
  155. package/lib/seen.mjs +3 -9
  156. package/lib/selfUpdate.mjs +51 -15
  157. package/lib/senseCall.mjs +1514 -0
  158. package/lib/senseHook.mjs +114 -0
  159. package/lib/senseTools.mjs +1298 -0
  160. package/lib/sessionBriefs.mjs +87 -0
  161. package/lib/sessionControl.mjs +63 -13
  162. package/lib/sessionFiles.mjs +85 -0
  163. package/lib/setupChoices.mjs +12 -3
  164. package/lib/setupMode.mjs +70 -25
  165. package/lib/sharedKeys.mjs +166 -0
  166. package/lib/sleep.mjs +396 -0
  167. package/lib/sources.mjs +306 -0
  168. package/lib/speech.mjs +166 -411
  169. package/lib/spoken.mjs +210 -0
  170. package/lib/steerHook.mjs +3 -1
  171. package/lib/steerQueue.mjs +40 -11
  172. package/lib/store.mjs +323 -130
  173. package/lib/stuck.mjs +85 -7
  174. package/lib/swarm.mjs +157 -49
  175. package/lib/swarmDevices.mjs +25 -85
  176. package/lib/swarmMemory.mjs +93 -9
  177. package/lib/t3.mjs +73 -3
  178. package/lib/taskCommands.mjs +51 -60
  179. package/lib/taskRooms.mjs +30 -4
  180. package/lib/taskRules.json +29 -0
  181. package/lib/taskRules.mjs +21 -0
  182. package/lib/taskRuns.mjs +74 -11
  183. package/lib/team.mjs +2 -1
  184. package/lib/threadActions.mjs +37 -9
  185. package/lib/threadAuthority.mjs +4 -4
  186. package/lib/threadBriefs.mjs +173 -43
  187. package/lib/threadNotes.mjs +320 -0
  188. package/lib/threadRecord.mjs +491 -0
  189. package/lib/threadRuns.mjs +216 -108
  190. package/lib/threadView.mjs +27 -30
  191. package/lib/threadWatches.mjs +1962 -0
  192. package/lib/timeSense.mjs +839 -0
  193. package/lib/tripwires.mjs +454 -0
  194. package/lib/ui.mjs +1 -1
  195. package/lib/vault.mjs +560 -45
  196. package/lib/vaultCommands.mjs +5 -3
  197. package/lib/vaultPeers.mjs +165 -0
  198. package/lib/vaultTools.d.ts +4 -1
  199. package/lib/vaultTools.js +22 -1
  200. package/lib/verdicts.mjs +12 -26
  201. package/lib/versions.mjs +117 -0
  202. package/lib/waitTool.mjs +278 -0
  203. package/lib/wakePicture.mjs +268 -0
  204. package/lib/wakeQueue.mjs +108 -0
  205. package/lib/watchResponses.mjs +533 -0
  206. package/lib/watches.mjs +290 -145
  207. package/lib/windowAsks.mjs +80 -17
  208. package/lib/worktrees.mjs +159 -9
  209. package/npm-shrinkwrap.json +138 -631
  210. package/package.json +7 -6
  211. package/release.json +212 -130
  212. package/lib/callSessions.mjs +0 -51
  213. package/lib/directLink.mjs +0 -349
  214. package/lib/peopleBoard.mjs +0 -131
  215. package/lib/projects.mjs +0 -2917
  216. package/lib/roomChannels.mjs +0 -667
package/lib/projects.mjs DELETED
@@ -1,2917 +0,0 @@
1
- import fs from "node:fs";
2
- import path from "node:path";
3
- import { randomUUID } from "node:crypto";
4
- import { DISPATCHER, nameOf } from "./members.mjs";
5
- import { secretReason } from "./secrets.mjs";
6
- import { createRoomChannels, agreementHash } from "./roomChannels.mjs";
7
- import { createPieces, RECORD_KINDS } from "./projectPieces.mjs";
8
- import { BOARD_KINDS, createProjectBoard, editIdOf } from "./projectBoard.mjs";
9
- import {
10
- SETTINGS,
11
- SETTING_KEYS,
12
- effectiveSettings,
13
- initialSettings,
14
- proposalState,
15
- validSetting,
16
- widens,
17
- } from "./projectSettings.mjs";
18
- import {
19
- anchorOf,
20
- behind,
21
- branchSlug,
22
- changedFiles,
23
- cloneInto,
24
- commitLane,
25
- fetchCanon,
26
- findCheckout,
27
- holds,
28
- laneFor,
29
- laneHead,
30
- openPullRequest,
31
- pullRequestState,
32
- pushLane,
33
- removeLane,
34
- validBranch,
35
- validRemote,
36
- validSha,
37
- } from "./projectGit.mjs";
38
-
39
- // A project two people's swarms share. One room both swarms read and write, mirrored on each computer; a record both
40
- // keep (who is building what, what the two people decided, notes, the settings they agreed); and a check before any
41
- // agent starts work, so the two sides never build two systems that later have to be made one.
42
- //
43
- // Everything crosses sealed, on a thread between the two people (the relay's person thread): an event per post or
44
- // record change, each carried until the other computer has it. Harness's server carries ciphertext and never learns
45
- // what a project is. Every record entry belongs to the side that made it and only that side changes it, so the two
46
- // copies never conflict: an answer to a proposal is the answerer's own entry, not an edit of the proposal.
47
- //
48
- // The repository is named by hashes: its first commit finds the person's checkout among the folders they work in, and
49
- // each piece of work records the canon commit it started from. Each agent works on its own branch in its own worktree;
50
- // code reaches the other side only through the shared remote.
51
-
52
- const NEXT_SEQ = 1_000_000;
53
- const OPEN_ONLY = new Set([
54
- "board.project.answer",
55
- "board.project.withdraw",
56
- "board.project.setting",
57
- "board.project.decide",
58
- "board.project.note",
59
- "board.project.goal",
60
- "board.project.piece",
61
- "board.project.release",
62
- ]);
63
- // Room posts both sides see; notes, held posts and the coordinator's bookkeeping stay on the computer that made them.
64
- const SHARED_KINDS = new Set([
65
- "post",
66
- "result",
67
- "answer",
68
- "question",
69
- "job",
70
- "failed",
71
- ]);
72
- const OPEN_WORK = ["checking", "clear", "overlap", "clash", "unchecked"];
73
- const REFRESH_MS = 5 * 60_000;
74
- const SUMMARY_CHARS = 600;
75
- const PROPOSAL_CHARS = 4_000;
76
- // What one other person's computer may put in a project on this one (security audit, October 25: nothing bounded it).
77
- // Past a limit an entry or post is refused, and Harness keeps it for a few tries then sets it aside. The largest honest
78
- // entry is a work entry naming 200 changed files (about 15,000 characters); a long project with active agents makes a
79
- // few hundred entries and posts. For owner review.
80
- const PEER_LIMITS = {
81
- // Characters of one record entry's body, as JSON.
82
- entryChars: 32_000,
83
- // Record entries (work, proposals, answers, notes, settings) one person's side keeps in one project.
84
- entries: 2_000,
85
- // Posts from one person into one project's room.
86
- posts: 2_000,
87
- // Characters of everything one person sent into one project: entries and posts together.
88
- totalChars: 20_000_000,
89
- };
90
-
91
- const now = () => new Date().toISOString();
92
- const json = (value, fallback) => {
93
- try {
94
- return value == null ? fallback : JSON.parse(value);
95
- } catch {
96
- return fallback;
97
- }
98
- };
99
- const oneLine = (text, limit = 120) => {
100
- const clean = String(text || "")
101
- .replace(/\s+/g, " ")
102
- .trim();
103
- return clean.length > limit ? `${clean.slice(0, limit - 1)}…` : clean;
104
- };
105
- const HANDLE = /^[a-z0-9][a-z0-9-]{2,19}$/;
106
-
107
- export function createProjects({
108
- store,
109
- log = () => {},
110
- // The person's handle on Harness (their swarm's name), or null when they have not claimed one.
111
- myHandle,
112
- relayRequest,
113
- decideRequest,
114
- invites: listInvites = async () => [],
115
- // Where each invitation this person sent stands at Harness: { id, status }.
116
- sentInvites = async () => [],
117
- sendEvent,
118
- endChannel = () => {},
119
- stopRoom = () => {},
120
- // Stops one agent's run in a room (a piece released or lost), leaving the rest of the room's work going.
121
- stopRun = () => {},
122
- wake,
123
- wakeRun,
124
- notifyBoard = () => {},
125
- notifyDesktop = () => {},
126
- // Harness's judgment of planned work against the record; null when Harness cannot judge now.
127
- checkWork = async () => null,
128
- // The injection guard's reading of another person's words (firewall.mjs), so a run's brief can say they were flagged.
129
- guard = async () => ({ verdict: "clean", unavailable: true }),
130
- knownFolders = () => [],
131
- agents = () => [],
132
- worktreeRoot,
133
- maxPosts = 500,
134
- maxWakes = 50,
135
- verdicts = null,
136
- }) {
137
- const db = store.db;
138
- db.exec(`
139
- create table if not exists projects (
140
- id text primary key,
141
- room_id text,
142
- title text not null,
143
- me text not null,
144
- partner text not null,
145
- role text not null,
146
- status text not null,
147
- repo text not null,
148
- folder text,
149
- agreed text not null,
150
- roster text not null default '[]',
151
- next_seq integer not null,
152
- created_at text not null,
153
- updated_at text not null
154
- );
155
- create table if not exists project_items (
156
- id text primary key,
157
- project_id text not null,
158
- kind text not null,
159
- side text not null,
160
- rev integer not null,
161
- body text not null,
162
- at text not null,
163
- updated_at text not null
164
- );
165
- create index if not exists project_items_idx on project_items(project_id, kind);
166
- create table if not exists project_outbox (
167
- message_id text primary key,
168
- project_id text not null,
169
- seq integer not null,
170
- body text not null,
171
- created_at text not null,
172
- delivered_at text
173
- );
174
- create table if not exists project_posts (
175
- post_id text primary key,
176
- project_id text not null,
177
- shared_id text not null,
178
- state text not null
179
- );
180
- create table if not exists project_receipts (
181
- channel_id text not null,
182
- message_id text not null,
183
- primary key(channel_id, message_id)
184
- );
185
- `);
186
- // Open pieces, claims and handoffs (projectPieces.mjs), made once the record below is.
187
- let pieces = null;
188
- const all = (sql, ...values) =>
189
- db.all(sql, values.length ? values : undefined);
190
- const run = (sql, ...values) =>
191
- db.run(sql, values.length ? values : undefined);
192
- const outboxColumns = all("pragma table_info(project_outbox)").map(
193
- (column) => column.name
194
- );
195
- for (const column of ["channel_id", "peer"])
196
- if (!outboxColumns.includes(column))
197
- db.exec(`alter table project_outbox add column ${column} text`);
198
- const channels = createRoomChannels({
199
- store,
200
- request: relayRequest,
201
- decide: decideRequest,
202
- invites: listInvites,
203
- sentInvites,
204
- ownAgents: agents,
205
- details: (id) => {
206
- const p = project(id);
207
- return {
208
- settings: settingsOf(p),
209
- agreements: items(id, "proposal")
210
- .filter((entry) => stateOf(p, entry).state === "accepted")
211
- .map(({ id, body }) => ({ id, body })),
212
- };
213
- },
214
- end: endChannel,
215
- log,
216
- send: (id, event, peers) => send(project(id), event, peers),
217
- onEvent: (id, event, peer) => receiveEvent(id, event, peer),
218
- onOpen: (id, peer) => {
219
- const p = project(id);
220
- if (!p || p.status === "left") return;
221
- const opened = makeRoom(save(id, { status: "open" }));
222
- hello(opened, true, peer);
223
- replay(opened, peer);
224
- resend();
225
- pieces.refresh(opened);
226
- notifyBoard(store.getTask(opened.roomId));
227
- },
228
- onChange: (id, before, after) => {
229
- const p = project(id);
230
- if (!p) return;
231
- const mine = after.members.find((member) => member.handle === p.me);
232
- if (["left", "removed"].includes(mine?.status)) {
233
- save(id, { status: "left" });
234
- store.meta(`project-ended:${id}`, "you_left");
235
- if (p.roomId) stopRoom(p.roomId);
236
- run(
237
- "delete from project_outbox where project_id = ? and delivered_at is null",
238
- id
239
- );
240
- }
241
- if (before) {
242
- for (const member of after.members) {
243
- const previous = before.members.find(
244
- (entry) => entry.handle === member.handle
245
- );
246
- if (previous?.status === member.status) continue;
247
- note(
248
- p,
249
- `${member.handle} ${member.status === "joined" ? "joined the room" : member.status === "invited" ? "was invited" : member.status === "removed" ? "was removed from the room" : "left the room"}.`
250
- );
251
- }
252
- }
253
- if (p.roomId) notifyBoard(store.getTask(p.roomId));
254
- },
255
- });
256
- const groupOf = (p) => channels.read(p.id);
257
- const peopleOf = (p) =>
258
- groupOf(p)
259
- ?.members.filter((member) => member.status === "joined")
260
- .map((member) => member.handle) ?? [p.me, p.partner];
261
- const peersOf = (p) => peopleOf(p).filter((handle) => handle !== p.me);
262
- const ownAgents = (p) => (groupOf(p) ? channels.agents(p.id) : agents());
263
- const remoteAgents = (p) => {
264
- const group = groupOf(p);
265
- return group
266
- ? peersOf(p).flatMap((peer) =>
267
- (group.rosters[peer] ?? []).map((id) => ({
268
- id,
269
- handle: peer,
270
- address: `${peer}/${id}`,
271
- }))
272
- )
273
- : p.roster.map((entry) => ({
274
- ...entry,
275
- handle: p.partner,
276
- address: `${p.partner}/${entry.id}`,
277
- }));
278
- };
279
- const isPeer = (p, identity) =>
280
- peersOf(p).includes(String(identity).split("/")[0]);
281
-
282
- // ---- the project rows ----
283
-
284
- const rowOf = (row) =>
285
- row && {
286
- id: row.id,
287
- roomId: row.room_id,
288
- title: row.title,
289
- me: row.me,
290
- partner: row.partner,
291
- role: row.role,
292
- status: row.status,
293
- repo: json(row.repo, {}),
294
- folder: row.folder,
295
- agreed: json(row.agreed, initialSettings()),
296
- roster: json(row.roster, []),
297
- nextSeq: Number(row.next_seq),
298
- createdAt: row.created_at,
299
- updatedAt: row.updated_at,
300
- };
301
- const project = (id) =>
302
- rowOf(all("select * from projects where id = ?", String(id))[0]);
303
- const projectOfRoom = (roomId) =>
304
- rowOf(all("select * from projects where room_id = ?", String(roomId))[0]);
305
- const projects = () =>
306
- all("select * from projects order by updated_at desc").map(rowOf);
307
- const save = (id, fields) => {
308
- const current = project(id);
309
- const next = { ...current, ...fields };
310
- run(
311
- "update projects set room_id = ?, title = ?, status = ?, repo = ?, folder = ?, agreed = ?, roster = ?, next_seq = ?, updated_at = ? where id = ?",
312
- next.roomId ?? null,
313
- next.title,
314
- next.status,
315
- JSON.stringify(next.repo),
316
- next.folder ?? null,
317
- JSON.stringify(next.agreed),
318
- JSON.stringify(next.roster ?? []),
319
- next.nextSeq,
320
- now(),
321
- id
322
- );
323
- return project(id);
324
- };
325
- const insertProject = (fields) => {
326
- const at = now();
327
- run(
328
- "insert into projects(id, room_id, title, me, partner, role, status, repo, folder, agreed, roster, next_seq, created_at, updated_at) values(?, ?, ?, ?, ?, ?, ?, ?, ?, ?, '[]', ?, ?, ?)",
329
- fields.id,
330
- fields.roomId ?? null,
331
- fields.title,
332
- fields.me,
333
- fields.partner,
334
- fields.role,
335
- fields.status,
336
- JSON.stringify(fields.repo),
337
- fields.folder ?? null,
338
- JSON.stringify(fields.agreed),
339
- NEXT_SEQ,
340
- at,
341
- at
342
- );
343
- return project(fields.id);
344
- };
345
-
346
- // ---- the record: entries each side makes and alone changes ----
347
-
348
- const itemOf = (row) =>
349
- row && {
350
- id: row.id,
351
- projectId: row.project_id,
352
- kind: row.kind,
353
- side: row.side,
354
- rev: Number(row.rev),
355
- body: json(row.body, {}),
356
- at: row.at,
357
- updatedAt: row.updated_at,
358
- };
359
- const item = (id) =>
360
- itemOf(all("select * from project_items where id = ?", String(id))[0]);
361
- const items = (projectId, kind = null) =>
362
- all(
363
- `select * from project_items where project_id = ?${kind ? " and kind = ?" : ""} order by at asc`,
364
- ...(kind ? [projectId, kind] : [projectId])
365
- ).map(itemOf);
366
- // Keeps an entry if it is newer than what this computer has; true when it changed anything.
367
- const keep = (entry) => {
368
- const current = item(entry.id);
369
- if (current && current.rev >= entry.rev) return false;
370
- if (
371
- current &&
372
- (current.side !== entry.side ||
373
- current.projectId !== entry.projectId ||
374
- current.kind !== entry.kind)
375
- )
376
- return false;
377
- run(
378
- "insert into project_items(id, project_id, kind, side, rev, body, at, updated_at) values(?, ?, ?, ?, ?, ?, ?, ?) on conflict(id) do update set rev = excluded.rev, body = excluded.body, updated_at = excluded.updated_at",
379
- entry.id,
380
- entry.projectId,
381
- entry.kind,
382
- entry.side,
383
- entry.rev,
384
- JSON.stringify(entry.body),
385
- entry.at,
386
- entry.updatedAt
387
- );
388
- return true;
389
- };
390
- // This side's own entry, new or changed, kept here and sent across.
391
- const write = (p, kind, body, id = randomUUID()) => {
392
- const current = item(id);
393
- const at = now();
394
- const entry = {
395
- id,
396
- projectId: p.id,
397
- kind,
398
- side: p.me,
399
- rev: (current?.rev ?? 0) + 1,
400
- body: current ? { ...current.body, ...body } : body,
401
- at: current?.at ?? at,
402
- updatedAt: at,
403
- };
404
- keep(entry);
405
- send(p, { type: "item", item: entry });
406
- pieces?.changed(project(p.id), item(id));
407
- // Every screen open on the room follows a change made here, as it does one from the other side.
408
- if (p.roomId) notifyBoard(store.getTask(p.roomId));
409
- return item(id);
410
- };
411
-
412
- // ---- the channel between the two computers ----
413
-
414
- const send = (p, body, peers = null) => {
415
- if (!p) return;
416
- if (!["open", "invited", "joining"].includes(p.status)) return;
417
- const routes = groupOf(p)
418
- ? peers
419
- ? channels
420
- .routes(p.id)
421
- .filter(
422
- (route) => peers.includes(route.peer) && route.state === "open"
423
- )
424
- : channels.recipients(p.id)
425
- : [{ id: p.id, peer: p.partner }];
426
- for (const route of routes) {
427
- const seq = project(p.id).nextSeq;
428
- run("update projects set next_seq = ? where id = ?", seq + 1, p.id);
429
- const messageId = `p:${p.id.slice(0, 8)}:${p.me}:${seq}`;
430
- run(
431
- "insert into project_outbox(message_id, project_id, channel_id, peer, seq, body, created_at) values(?, ?, ?, ?, ?, ?, ?)",
432
- messageId,
433
- p.id,
434
- route.id,
435
- route.peer,
436
- seq,
437
- JSON.stringify(body),
438
- now()
439
- );
440
- if (project(p.id).status === "open") deliver(messageId);
441
- }
442
- };
443
- const deliver = (messageId) => {
444
- const row = all(
445
- "select * from project_outbox where message_id = ? and delivered_at is null",
446
- messageId
447
- )[0];
448
- const p = row && project(row.project_id);
449
- if (!row || p?.status !== "open") return;
450
- sendEvent({
451
- projectId: row.channel_id ?? p.id,
452
- to: `${row.peer ?? p.partner}/person`,
453
- messageId,
454
- seq: Number(row.seq),
455
- body: json(row.body, {}),
456
- });
457
- };
458
- /** Harness has the event; it waits there sealed for the other computer. */
459
- const delivered = (messageId) =>
460
- run(
461
- "update project_outbox set delivered_at = ? where message_id = ?",
462
- now(),
463
- String(messageId)
464
- );
465
- /** Everything not yet delivered goes again, as when the connection comes back. */
466
- const resend = () => {
467
- for (const row of all(
468
- "select message_id from project_outbox where delivered_at is null order by seq asc"
469
- ))
470
- deliver(row.message_id);
471
- };
472
-
473
- // ---- names across the two sides ----
474
-
475
- // A name on this computer as the other side knows it: the person is handle/person, an agent handle/agent.
476
- const shared = (p, name) =>
477
- String(name).includes("/")
478
- ? String(name)
479
- : `${p.me}/${name === "user" ? "person" : name}`;
480
- // A name from the other side as this computer knows it.
481
- const local = (p, name) => {
482
- const [handle, who] = String(name).split("/");
483
- if (handle !== p.me || !who) return String(name);
484
- return who === "person" ? "user" : who;
485
- };
486
- /** How a name reads to the person: their own agents by name, the other side's as "maya's Codex". */
487
- const display = (p, name) => {
488
- const [handle, who] = String(name).split("/");
489
- if (!who) return name === "user" ? "You" : nameOf(name);
490
- if (handle === p.me) return who === "person" ? "You" : nameOf(who);
491
- return who === "person" ? handle : `${handle}'s ${nameOf(who)}`;
492
- };
493
- // The other side's agents a post names, by their address: "@maya/codex".
494
- const partnerMentions = (p, text) =>
495
- [
496
- ...remoteAgents(p).map((entry) => entry.address),
497
- ...peersOf(p).map((peer) => `${peer}/person`),
498
- ].filter((address) =>
499
- new RegExp(
500
- `(^|\\s)@${address.replace(/[.*+?^${}()|[\]\\/]/g, "\\$&")}\\b`,
501
- "i"
502
- ).test(String(text))
503
- );
504
-
505
- // ---- settings ----
506
-
507
- const settingsOf = (p) => {
508
- const changes = [];
509
- for (const entry of items(p.id, "setting"))
510
- changes.push({ ...entry.body, at: entry.updatedAt });
511
- for (const proposal of items(p.id, "proposal")) {
512
- if (proposal.body.type !== "setting") continue;
513
- const standing = stateOf(p, proposal);
514
- if (standing.state === "accepted")
515
- changes.push({
516
- key: proposal.body.key,
517
- value: proposal.body.value,
518
- at: standing.at,
519
- });
520
- }
521
- return effectiveSettings(p.agreed, changes);
522
- };
523
- const answersTo = (p, proposalId) =>
524
- items(p.id, "answer")
525
- .filter((answer) => answer.body.proposal === proposalId)
526
- .map((answer) => ({
527
- side: answer.side,
528
- yes: answer.body.yes,
529
- at: answer.updatedAt,
530
- }));
531
- // The work a fix changes: what it names as changing, else what it is about. Only that work is released by it.
532
- const changedBy = (body) =>
533
- (Array.isArray(body.changes) ? body.changes : (body.about ?? [])).map(
534
- String
535
- );
536
- // A fix that changes only pieces of work: the people whose work it changes. Anything else (a decision, a setting, the
537
- // goal, or a fix naming no work known here) needs everyone in the project.
538
- const isFix = (body) =>
539
- body.type === "fix" && !body.decision && !body.goal && !body.key;
540
- /**
541
- * Who a proposal needs, worked out on this computer from the record it holds, never taken from the proposal: a
542
- * proposal from the other side that said it needed only them could otherwise release this person's held work or
543
- * replace the goal (security audit P1/P10, October 25).
544
- */
545
- // `side`: whose record entry the proposal is, as the record holds it (never what the proposal says of itself).
546
- const needsOf = (p, body, side = null) => {
547
- // A handoff waits on one person, worked out from the record, never from who the proposal says it needs: past the
548
- // handoff limit, the person whose agent hands the piece on; a guarded piece offered across, the person whose agent
549
- // would take it (projectPieces.mjs). Either way that person's own agent's work is what moves.
550
- if (body.type === "handoff") {
551
- const offered = body.handoff ? item(body.handoff) : null;
552
- const decider = offered
553
- ? offered.projectId === p.id &&
554
- String(offered.body?.to ?? "").split("/")[0]
555
- : String(body.from ?? "").split("/")[0];
556
- if (decider && peopleOf(p).includes(decider)) return [decider];
557
- }
558
- // A claim of a guarded piece waits on the person whose swarm would take it: the side that proposed it.
559
- if (body.type === "claim" && side && peopleOf(p).includes(side))
560
- return [side];
561
- if (isFix(body)) {
562
- const owners = new Set(
563
- changedBy(body)
564
- .map((id) => item(id))
565
- .filter((entry) => entry?.projectId === p.id && entry.kind === "work")
566
- .map((entry) => entry.side)
567
- );
568
- if (owners.size) return [...owners].sort();
569
- }
570
- return peopleOf(p);
571
- };
572
- const stateOf = (p, proposal) => {
573
- const body = proposal.body;
574
- const group = groupOf(p);
575
- // An agreement the invitation carried counts as agreed by whoever joined with it; a fix to work is never one.
576
- const implicit =
577
- group && !isFix(body)
578
- ? Object.entries(group.consents ?? {})
579
- .filter(
580
- ([, consent]) => consent[proposal.id] === agreementHash(body)
581
- )
582
- .map(([side]) => ({ side, yes: true, at: proposal.at }))
583
- : [];
584
- const answers = answersTo(p, proposal.id);
585
- // An agreement this person joined with was accepted when they joined, though an answer to it from someone away
586
- // since never reached this computer: once, a room's agreed setting read as still pending on the fourth person's,
587
- // and an older narrowing won over it. It keeps its own time, so a narrowing after it still wins.
588
- if (
589
- !isFix(body) &&
590
- group?.consents?.[p.me]?.[proposal.id] === agreementHash(body)
591
- )
592
- return {
593
- state: "accepted",
594
- waitingOn: [],
595
- at: [proposal.at, ...answers.map((answer) => answer.at)]
596
- .map(String)
597
- .sort()
598
- .at(-1),
599
- };
600
- return proposalState(
601
- { ...body, needs: needsOf(p, body, proposal.side), at: proposal.at },
602
- [...implicit, ...answers]
603
- );
604
- };
605
-
606
- // ---- the room ----
607
-
608
- const roomOf = (p) => (p.roomId ? store.getTask(p.roomId) : null);
609
- const makeRoom = (p) => {
610
- if (p.roomId && store.getTask(p.roomId)) return p;
611
- const workspace =
612
- p.folder ?? path.join(worktreeRoot, p.id.slice(0, 8), "workspace");
613
- if (!p.folder) fs.mkdirSync(workspace, { recursive: true });
614
- const room = store.createGoal({
615
- objective: p.title,
616
- brief: "",
617
- originAgent: "user",
618
- provenance: { trust: "user", chain: [] },
619
- // The dispatcher facilitates (owner, November 1: "facilitator is dispatcher"); agents join as they are named or
620
- // handed work, Harness like any other. Rooms made before keep their team; the store relabels their facilitator.
621
- team: [],
622
- facilitator: DISPATCHER,
623
- workspace,
624
- maxPosts,
625
- maxWakes,
626
- });
627
- store.meta(`project-room:${room.id}`, p.id);
628
- return save(p.id, { roomId: room.id });
629
- };
630
- const note = (p, text) => {
631
- if (!p.roomId) return;
632
- store.roomPost({
633
- goalId: p.roomId,
634
- author: DISPATCHER,
635
- kind: "note",
636
- text,
637
- });
638
- notifyBoard(store.getTask(p.roomId));
639
- };
640
-
641
- let nextClash = null;
642
- // The dispatcher's own posts about the project (a clash, a heads up) go across whatever agents may say.
643
- let saying = false;
644
- /** A post made in a project's room on this computer: it goes to the other side, unless it must wait for the person. */
645
- const posted = (goalId, post) => {
646
- if (!post || String(post.author).includes("/")) return;
647
- const p = projectOfRoom(goalId);
648
- if (!p || !SHARED_KINDS.has(post.kind)) return;
649
- if (nextClash && post.author === DISPATCHER)
650
- store.meta(`project-clash-post:${post.id}`, JSON.stringify(nextClash));
651
- if (all("select 1 from project_posts where post_id = ?", post.id).length)
652
- return;
653
- const secret = secretReason(post.text);
654
- const waits =
655
- secret ||
656
- (post.author !== "user" &&
657
- !saying &&
658
- (!settingsOf(p).talk || !ownAgents(p).includes(post.author)));
659
- run(
660
- "insert into project_posts(post_id, project_id, shared_id, state) values(?, ?, ?, ?)",
661
- post.id,
662
- p.id,
663
- post.id,
664
- waits ? "held" : "sent"
665
- );
666
- if (secret) {
667
- note(
668
- p,
669
- `Kept on this computer: ${display(p, post.author)}'s post looks like it holds ${secret}. Share it from here if it is safe.`
670
- );
671
- return;
672
- }
673
- if (waits) return;
674
- sharePost(p, post);
675
- };
676
- const sharePost = (p, post, peers = null) =>
677
- send(
678
- p,
679
- {
680
- type: "post",
681
- ...clashOf(post),
682
- id: post.id,
683
- author: shared(p, post.author),
684
- kind: post.kind,
685
- text: post.text,
686
- mentions: [
687
- ...new Set([
688
- ...(post.mentions ?? []).map((name) => shared(p, name)),
689
- ...partnerMentions(p, post.text),
690
- ]),
691
- ],
692
- at: post.created_at ?? now(),
693
- },
694
- peers
695
- );
696
-
697
- // A post that names a clash carries the work it is about, so the other side's agents in it may talk it out.
698
- const clashOf = (post) => {
699
- const work = json(store.meta(`project-clash-post:${post.id}`), null);
700
- return Array.isArray(work) ? { clash: work } : {};
701
- };
702
- const settleKey = (p, agent) => `project-settle:${p.id}:${agent}`;
703
- /**
704
- * The other side's words with their names as they read here: their "@codex" is "@maya/codex" on this computer, and
705
- * their "@sig/codex" is this person's own "@codex".
706
- */
707
- const addressedHere = (p, text) => {
708
- const escape = (value) => value.replace(/[.*+?^${}()|[\]\\/]/g, "\\$&");
709
- const MINE = "\u0000";
710
- let words = text.replace(
711
- new RegExp(`(^|\\s)@${escape(p.me)}/([a-z0-9][a-z0-9._-]*)`, "gi"),
712
- `$1@${MINE}$2`
713
- );
714
- const senderAgents =
715
- groupOf(p)?.rosters[p.partner]?.map((id) => ({ id })) ?? p.roster;
716
- for (const entry of senderAgents)
717
- words = words.replace(
718
- new RegExp(`(^|\\s)@${escape(entry.id)}(?![\\w/-])`, "gi"),
719
- `$1@${p.partner}/${entry.id}`
720
- );
721
- return words.replaceAll(`@${MINE}`, "@");
722
- };
723
-
724
- // ---- what arrives from the other computer ----
725
-
726
- // Relay delivery can overlap or repeat after a lost acknowledgement. Record
727
- // the transport receipt so a repeated hello cannot replay history again.
728
- const receive = (channelId, event, messageId = null) => {
729
- if (
730
- messageId &&
731
- all(
732
- "select 1 from project_receipts where channel_id = ? and message_id = ?",
733
- channelId,
734
- messageId
735
- ).length
736
- )
737
- return { ok: true, duplicate: true };
738
- const result = receiveEvent(channelId, event);
739
- if (messageId && result.ok)
740
- run(
741
- "insert or ignore into project_receipts(channel_id, message_id) values(?, ?)",
742
- channelId,
743
- messageId
744
- );
745
- return result;
746
- };
747
- const receiveEvent = (projectId, event, source = null) => {
748
- if (!source) {
749
- const handled = channels.receive(projectId, event);
750
- if (handled) return handled;
751
- }
752
- const stored = project(projectId);
753
- const p = stored && source ? { ...stored, partner: source } : stored;
754
- if (!p) return { ok: false, error: "no project on this thread" };
755
- if (!event || typeof event !== "object")
756
- return { ok: false, error: "an empty project event" };
757
- // Until the thread under it opens here, Harness keeps what arrives and brings it again.
758
- if (p.status !== "open" && event.type !== "left")
759
- return p.status === "left"
760
- ? { ok: true, ignored: true }
761
- : { ok: false, error: "the project is not open on this computer yet" };
762
- if (event.type === "hello") {
763
- // The other side is in: everything this side has made goes to it, and its agents are known here.
764
- if (!groupOf(p) && Array.isArray(event.agents))
765
- setRoster(p, event.agents);
766
- if (event.reply !== false) {
767
- hello(p, false, source);
768
- replay(p, source);
769
- }
770
- return { ok: true };
771
- }
772
- if (event.type === "roster") {
773
- if (!groupOf(p) && Array.isArray(event.agents))
774
- setRoster(p, event.agents);
775
- return { ok: true };
776
- }
777
- if (event.type === "left") {
778
- if (p.status === "open") {
779
- save(p.id, { status: "left" });
780
- store.meta(`project-ended:${p.id}`, "they_left");
781
- note(
782
- p,
783
- `${p.partner} left the project. This room stays here; nothing more goes between you.`
784
- );
785
- notifyDesktop(
786
- `${p.partner} left the project "${oneLine(p.title, 60)}".`,
787
- { thread: p.roomId }
788
- );
789
- }
790
- return { ok: true };
791
- }
792
- if (event.type === "post") return receivePost(p, event);
793
- if (event.type === "item") return receiveItem(p, event.item);
794
- return { ok: true };
795
- };
796
- const setRoster = (p, agents) =>
797
- save(p.id, {
798
- roster: agents
799
- .filter(
800
- (entry) =>
801
- entry && /^[a-z0-9][a-z0-9._-]{0,63}$/.test(String(entry.id))
802
- )
803
- .slice(0, 20)
804
- .map((entry) => ({ id: String(entry.id) })),
805
- });
806
- // What one person sent into a project so far: their record entries, and their posts as counted when they came.
807
- const postsIn = (p, peer) =>
808
- json(store.meta(`project-intake:${p.id}:${peer}`), { posts: 0, chars: 0 });
809
- const intakeOf = (p, peer) => {
810
- const entries = all(
811
- "select count(*) as n, coalesce(sum(length(body)), 0) as chars from project_items where project_id = ? and side = ?",
812
- p.id,
813
- peer
814
- )[0];
815
- const posts = postsIn(p, peer);
816
- return {
817
- entries: Number(entries.n),
818
- posts: posts.posts,
819
- chars: Number(entries.chars) + posts.chars,
820
- };
821
- };
822
- const overLimit = (p, peer, { entry = 0, post = 0 }) => {
823
- const intake = intakeOf(p, peer);
824
- if (entry > PEER_LIMITS.entryChars)
825
- return "a record entry larger than a project takes";
826
- if (entry && intake.entries >= PEER_LIMITS.entries)
827
- return "more record entries than a project takes from one person";
828
- if (post && intake.posts >= PEER_LIMITS.posts)
829
- return "more posts than a project takes from one person";
830
- if (intake.chars + entry + post > PEER_LIMITS.totalChars)
831
- return "more than a project takes from one person";
832
- return null;
833
- };
834
- const receivePost = (p, event) => {
835
- if (!String(event.author || "").startsWith(`${p.partner}/`))
836
- return {
837
- ok: false,
838
- error: "a post in the other side's name only comes from them",
839
- };
840
- if (
841
- all("select 1 from project_posts where shared_id = ?", String(event.id))
842
- .length
843
- )
844
- return { ok: true, duplicate: true };
845
- const room = roomOf(p);
846
- if (!room) return { ok: false, error: "the project has no room here yet" };
847
- const words = addressedHere(p, String(event.text || "")).slice(0, 20_000);
848
- const over = overLimit(p, p.partner, { post: words.length || 1 });
849
- if (over) {
850
- log(`project ${p.id}: refused ${p.partner}'s post: ${over}`);
851
- return { ok: false, error: `Refused: ${over}.` };
852
- }
853
- const counted = postsIn(p, p.partner);
854
- store.meta(
855
- `project-intake:${p.id}:${p.partner}`,
856
- JSON.stringify({
857
- posts: counted.posts + 1,
858
- chars: counted.chars + words.length,
859
- })
860
- );
861
- const mentions = (Array.isArray(event.mentions) ? event.mentions : [])
862
- .map(String)
863
- .map((name) => local(p, name));
864
- const post = store.roomPost({
865
- goalId: room.id,
866
- author: String(event.author),
867
- kind: SHARED_KINDS.has(event.kind) ? event.kind : "post",
868
- text: words,
869
- mentions,
870
- });
871
- run(
872
- "insert into project_posts(post_id, project_id, shared_id, state) values(?, ?, ?, 'in')",
873
- post.id,
874
- p.id,
875
- String(event.id)
876
- );
877
- // The other side's words wake only the agents here they name; their unaddressed words are their own swarm's to sort.
878
- // Harness works on this person's credits, so the other side reaches it only when both let Harness answer them.
879
- const named = mentions.filter(
880
- (name) =>
881
- !name.includes("/") &&
882
- name !== "user" &&
883
- ownAgents(p).includes(name) &&
884
- (name !== "harness" || settingsOf(p).harness)
885
- );
886
- if (mentions.includes("harness") && !named.includes("harness"))
887
- note(
888
- p,
889
- `${display(p, event.author)} asked Harness. Harness answers the other side only once you both let it, since it works on your Harness credits.`
890
- );
891
- // A clash the other side found with one of this side's pieces of work: the agent on it talks it out, read-only.
892
- const clash = Array.isArray(event.clash) ? event.clash.map(String) : [];
893
- const settling = named.filter((agent) =>
894
- items(p.id, "work").some(
895
- (entry) =>
896
- entry.side === p.me &&
897
- entry.body.agent === agent &&
898
- clash.includes(entry.id)
899
- )
900
- );
901
- for (const agent of settling) store.meta(settleKey(p, agent), "1");
902
- const joining = named.filter((agent) => !room.goal.team.includes(agent));
903
- if (joining.length)
904
- store.setGoalTeam(room.id, [...room.goal.team, ...joining]);
905
- // Another person's words are read by the guard like any words from outside, before an agent here is told of them;
906
- // their ask never carries this person's go (the project's gate decides whether it waits for the Start).
907
- void guard(post.text)
908
- .catch(() => null)
909
- .then((reading) => {
910
- if (reading?.verdict === "flag" || reading?.verdict === "hold")
911
- store.meta(`flagged:${post.id}`, String(reading.score));
912
- const fresh = roomOf(p);
913
- if (named.length && fresh?.status === "open")
914
- wake(room.id, post, String(event.author), named, {
915
- go: false,
916
- partner: true,
917
- });
918
- notifyBoard(store.getTask(room.id));
919
- });
920
- notifyBoard(store.getTask(room.id));
921
- return { ok: true };
922
- };
923
- const receiveItem = (p, entry) => {
924
- if (!entry || entry.side !== p.partner || entry.projectId !== p.id)
925
- return {
926
- ok: false,
927
- error: "a record entry in the other side's name only comes from them",
928
- };
929
- if (
930
- ![
931
- "work",
932
- "proposal",
933
- "answer",
934
- "setting",
935
- "note",
936
- ...RECORD_KINDS,
937
- ...BOARD_KINDS,
938
- ].includes(entry.kind)
939
- )
940
- return { ok: true };
941
- // A side's changes to a card are its one entry for that card; under another id it could stand in for another's.
942
- if (
943
- entry.kind === "card-edit" &&
944
- entry.id !== editIdOf(entry.body?.card, entry.side)
945
- )
946
- return { ok: false, error: "a card's changes in the wrong place" };
947
- // An answer is its side's own entry for one proposal; one under another id could stand in for this person's.
948
- if (
949
- entry.kind === "answer" &&
950
- entry.id !== `${entry.body?.proposal}:${entry.side}`
951
- )
952
- return { ok: false, error: "an answer in the wrong place" };
953
- const before = settingsOf(p);
954
- // On every project, shared room or two-person: one side alone only narrows what agents may do.
955
- if (
956
- entry.kind === "setting" &&
957
- (!validSetting(entry.body?.key, entry.body?.value) ||
958
- widens(entry.body.key, before[entry.body.key], entry.body.value))
959
- )
960
- return {
961
- ok: false,
962
- error: "Giving agents more reach requires everyone's agreement.",
963
- };
964
- const chars = JSON.stringify(entry.body ?? {}).length;
965
- const over = item(entry.id)
966
- ? chars > PEER_LIMITS.entryChars
967
- ? "a record entry larger than a project takes"
968
- : null
969
- : overLimit(p, p.partner, { entry: chars });
970
- if (over) {
971
- log(`project ${p.id}: refused ${p.partner}'s entry: ${over}`);
972
- return { ok: false, error: `Refused: ${over}.` };
973
- }
974
- const previous = item(entry.id);
975
- const kept = keep({
976
- ...entry,
977
- rev: Number(entry.rev) || 1,
978
- body: entry.body && typeof entry.body === "object" ? entry.body : {},
979
- });
980
- if (!kept) return { ok: true, duplicate: true };
981
- const fresh = project(p.id);
982
- if (entry.kind === "proposal") proposed(fresh, item(entry.id));
983
- if (entry.kind === "answer") answered(fresh, item(entry.body.proposal));
984
- if (entry.kind === "setting") settingChanged(fresh, before);
985
- if (entry.kind === "work") workChanged(fresh, item(entry.id), previous);
986
- pieces.changed(fresh, item(entry.id));
987
- if (fresh.roomId) notifyBoard(store.getTask(fresh.roomId));
988
- return { ok: true };
989
- };
990
- const hello = (p, reply = true, peer = null) =>
991
- send(
992
- p,
993
- {
994
- type: "hello",
995
- agents: ownAgents(p).map((id) => ({ id })),
996
- agreements: groupOf(p)?.consents?.[p.me] ?? {},
997
- reply,
998
- },
999
- peer ? [peer] : null
1000
- );
1001
- const replay = (p, peer = null) => {
1002
- for (const entry of items(p.id).filter((own) => own.side === p.me))
1003
- send(p, { type: "item", item: entry }, peer ? [peer] : null);
1004
- if (!p.roomId) return;
1005
- for (const post of store.roomPosts(p.roomId, 0, 500)) {
1006
- const sent = all(
1007
- "select state from project_posts where post_id = ?",
1008
- post.id
1009
- )[0];
1010
- if (sent?.state === "sent") sharePost(p, post, peer ? [peer] : null);
1011
- }
1012
- };
1013
-
1014
- // ---- people's decisions: proposals and answers ----
1015
-
1016
- const proposed = (p, proposal) => {
1017
- const standing = stateOf(p, proposal);
1018
- // What waits on the person is told by the room's needs-you items (needsOf), once each, on every surface.
1019
- if (standing.waitingOn.includes(p.me) && p.roomId)
1020
- notifyBoard(store.getTask(p.roomId));
1021
- if (standing.state === "accepted") accepted(p, proposal);
1022
- };
1023
- const answered = (p, proposal) => {
1024
- if (!proposal) return;
1025
- const standing = stateOf(p, proposal);
1026
- if (standing.state === "accepted") accepted(p, proposal);
1027
- if (standing.state === "declined" && proposal.side === p.me)
1028
- note(p, `Not agreed: ${oneLine(proposal.body.text, 200)}`);
1029
- if (standing.state === "declined") pieces.declined(p, proposal);
1030
- };
1031
- // An agreed proposal takes effect on each computer for what that computer owns: a fix releases this side's work.
1032
- const accepted = (p, proposal) => {
1033
- const done = `project-accepted:${proposal.id}`;
1034
- if (store.meta(done)) return;
1035
- store.meta(done, "1");
1036
- if (proposal.body.type === "setting") {
1037
- note(
1038
- p,
1039
- `Agreed: ${settingLine(proposal.body.key, proposal.body.value)}.`
1040
- );
1041
- return;
1042
- }
1043
- if (proposal.body.type === "decision" || proposal.body.decision)
1044
- note(
1045
- p,
1046
- `Decided: ${oneLine(proposal.body.decision || proposal.body.text, 300)}`
1047
- );
1048
- if (isFix(proposal.body))
1049
- for (const id of changedBy(proposal.body)) release(p, item(id), proposal);
1050
- if (["claim", "handoff"].includes(proposal.body.type))
1051
- pieces.accepted(p, proposal);
1052
- };
1053
- const settingLine = (key, value) =>
1054
- SETTINGS[key].choices
1055
- ? `${SETTINGS[key].label}: ${SETTINGS[key].choices[value].toLowerCase()}`
1056
- : `${SETTINGS[key].label}: ${value ? "yes" : "no"}`;
1057
- const settingChanged = (p, before) => {
1058
- const after = settingsOf(p);
1059
- for (const key of SETTING_KEYS)
1060
- if (before[key] !== after[key])
1061
- note(p, `${p.partner} changed it: ${settingLine(key, after[key])}.`);
1062
- };
1063
- /**
1064
- * The people a proposal needs: a change to what both decided, or to a setting, needs both; a fix that reshapes only
1065
- * one side's work needs that side's person (agents settle it first, a person OKs it).
1066
- */
1067
- const needsFor = (p, { decision, changes }) => {
1068
- if (decision) return peopleOf(p);
1069
- const owners = new Set(
1070
- (changes ?? []).map((id) => item(id)?.side).filter(Boolean)
1071
- );
1072
- return owners.size ? [...owners].sort() : [p.me];
1073
- };
1074
- const propose = (p, body, by) => {
1075
- const proposal = write(p, "proposal", {
1076
- ...body,
1077
- by: shared(p, by),
1078
- text: String(body.text).slice(0, PROPOSAL_CHARS),
1079
- });
1080
- // A person's own proposal carries their yes.
1081
- if (by === "user")
1082
- write(
1083
- p,
1084
- "answer",
1085
- { proposal: proposal.id, yes: true },
1086
- `${proposal.id}:${p.me}`
1087
- );
1088
- proposed(project(p.id), proposal);
1089
- return proposal;
1090
- };
1091
-
1092
- // ---- work and the check before it ----
1093
-
1094
- const openWork = (p, agent) =>
1095
- items(p.id, "work").find(
1096
- (entry) =>
1097
- entry.side === p.me &&
1098
- entry.body.agent === agent &&
1099
- OPEN_WORK.includes(entry.body.status)
1100
- ) ?? null;
1101
- const laneOf = (p, work) =>
1102
- path.join(worktreeRoot, p.id.slice(0, 8), branchSlug(work.body.branch));
1103
- const describe = (p, work) => ({
1104
- id: work.id,
1105
- who: display(p, `${work.side}/${work.body.agent}`),
1106
- side: work.side === p.me ? "this person" : work.side,
1107
- summary: work.body.summary,
1108
- ...(work.body.touches?.length ? { touches: work.body.touches } : {}),
1109
- ...(work.body.files?.length ? { files: work.body.files } : {}),
1110
- status: work.body.status,
1111
- });
1112
- // An invitation explicitly carries the current agreements. Keep that accepted
1113
- // baseline available even when an original author's computer is unavailable.
1114
- // It is attributed to the invitation, not forged as an original author's row.
1115
- const joinedAgreements = (p) => groupOf(p)?.agreements ?? [];
1116
- const decisionsOf = (p) => {
1117
- const proposals = items(p.id, "proposal");
1118
- const originals = proposals
1119
- .filter(
1120
- (proposal) =>
1121
- (proposal.body.type === "decision" || proposal.body.decision) &&
1122
- stateOf(p, proposal).state === "accepted"
1123
- )
1124
- .map((proposal) => ({
1125
- id: proposal.id,
1126
- text: proposal.body.decision || proposal.body.text,
1127
- by: proposal.body.by,
1128
- at: stateOf(p, proposal).at,
1129
- }));
1130
- const baseline = joinedAgreements(p)
1131
- .filter(
1132
- (entry) =>
1133
- !proposals.some((proposal) => proposal.id === entry.id) &&
1134
- (entry.body.type === "decision" || entry.body.decision)
1135
- )
1136
- .map((entry) => ({
1137
- id: entry.id,
1138
- text: entry.body.decision || entry.body.text,
1139
- by: `Accepted on joining from ${groupOf(p).owner}`,
1140
- at: p.createdAt,
1141
- }));
1142
- return [...baseline, ...originals];
1143
- };
1144
- const goalOf = (p) => {
1145
- const agreed = items(p.id, "proposal")
1146
- .filter(
1147
- (entry) => entry.body.goal && stateOf(p, entry).state === "accepted"
1148
- )
1149
- .at(-1);
1150
- const baseline = joinedAgreements(p)
1151
- .filter((entry) => entry.body.goal)
1152
- .at(-1);
1153
- return (
1154
- agreed?.body.goal ??
1155
- baseline?.body.goal ?? { statement: p.title, criteria: [] }
1156
- );
1157
- };
1158
-
1159
- /**
1160
- * Compares one piece of planned work with what both sides agreed and with every other open piece, and keeps the answer
1161
- * on the work: clear, overlap (the same area, compatible), or clash (incompatible, or against a decision). Files both
1162
- * change make it at least an overlap. A check Harness cannot make leaves it unchecked, and the room says so.
1163
- */
1164
- const check = async (p, work, phase = "start") => {
1165
- const others = items(p.id, "work").filter(
1166
- (entry) => entry.id !== work.id && OPEN_WORK.includes(entry.body.status)
1167
- );
1168
- const decisions = decisionsOf(p);
1169
- const mine = new Set(work.body.files ?? []);
1170
- const sharedFiles = others
1171
- .map((entry) => ({
1172
- id: entry.id,
1173
- files: (entry.body.files ?? []).filter((file) => mine.has(file)),
1174
- }))
1175
- .filter((entry) => entry.files.length);
1176
- let judged = null;
1177
- if (others.length || decisions.length)
1178
- judged = await checkWork({
1179
- project: p.title,
1180
- repository: p.repo.name,
1181
- phase,
1182
- work: describe(p, work),
1183
- others: others.slice(0, 12).map((entry) => describe(p, entry)),
1184
- decisions: decisions.slice(0, 12).map(({ id, text }) => ({ id, text })),
1185
- }).catch((error) => {
1186
- log(`project check for ${work.id}: ${error.message}`);
1187
- return null;
1188
- });
1189
- const unchecked = (others.length || decisions.length) && !judged;
1190
- const verdict =
1191
- judged?.verdict === "clash"
1192
- ? "clash"
1193
- : judged?.verdict === "overlap" || sharedFiles.length
1194
- ? "overlap"
1195
- : unchecked
1196
- ? "unchecked"
1197
- : "clear";
1198
- return {
1199
- verdict,
1200
- with: [
1201
- ...new Set([
1202
- ...(judged?.with ?? []).filter((id) =>
1203
- others.some((entry) => entry.id === id)
1204
- ),
1205
- ...sharedFiles.map((entry) => entry.id),
1206
- ]),
1207
- ],
1208
- decision: decisions.some((entry) => entry.id === judged?.decision)
1209
- ? judged.decision
1210
- : null,
1211
- reason: judged?.reason ? String(judged.reason).slice(0, 600) : null,
1212
- files: sharedFiles.flatMap((entry) => entry.files).slice(0, 10),
1213
- at: now(),
1214
- };
1215
- };
1216
- // One piece of work can be checked twice at once (a new ask while the agent states its plan): only the newest check's
1217
- // answer stands, and anyone waiting on an older one gets the newest's.
1218
- const newestCheck = new Map();
1219
- const checkNewest = async (p, work, phase = "start") => {
1220
- const mine = check(p, work, phase);
1221
- newestCheck.set(work.id, mine);
1222
- let current = mine;
1223
- let result = await mine;
1224
- while (newestCheck.get(work.id) !== current) {
1225
- current = newestCheck.get(work.id);
1226
- result = await current;
1227
- }
1228
- return result;
1229
- };
1230
- const clashWords = (p, work, result) => {
1231
- const against = result.with.map((id) => item(id)).filter(Boolean);
1232
- const decision = decisionsOf(p).find(
1233
- (entry) => entry.id === result.decision
1234
- );
1235
- const parts = [
1236
- ...against.map(
1237
- (entry) =>
1238
- `${display(p, `${entry.side}/${entry.body.agent}`)}'s "${oneLine(entry.body.summary, 90)}"`
1239
- ),
1240
- ...(decision
1241
- ? [`what you decided: "${oneLine(decision.text, 120)}"`]
1242
- : []),
1243
- ];
1244
- return parts.join(" and ") || "other work here";
1245
- };
1246
- /**
1247
- * The run an agent is woken for in a project's room. The agent's open piece of work goes on as it is; new work is
1248
- * checked first, and starts once it is clear (or only overlaps, or the person set the project to warn). A clash
1249
- * holds that piece alone: the agents talk it out read-only, and it starts once a person OKs their fix.
1250
- */
1251
- const gate = ({ task, agent, reason, asker, go, mode, words }, start) => {
1252
- const p = projectOfRoom(task.id);
1253
- if (!p) return start(mode);
1254
- if (p.status !== "open")
1255
- return { ok: false, error: "This shared room is not open." };
1256
- if (!ownAgents(p).includes(agent))
1257
- return {
1258
- ok: false,
1259
- error: "This agent has not been selected for the shared room.",
1260
- };
1261
- const settings = settingsOf(p);
1262
- // The other side asking: it waits for the person's Start, talking out a clash included (security audit P2, October
1263
- // 25: a clash post started a review run on its own). Where both people let agents start work the other side asks
1264
- // for, it goes without the person's go, so only an agent that can run restricted in a copy here starts; the rest
1265
- // wait. Tier 4 hardens that restricted mode; this is where a partner's run would take it.
1266
- const fromPartner = isPeer(p, asker);
1267
- // A piece this side's own swarm claimed or accepted carries this side's go (projectPieces.mjs): the decision to take
1268
- // it was made here, though its words are the other side's, so its run still loads only this person's settings.
1269
- const needsStart = fromPartner && !settings.start && go !== true;
1270
- if (fromPartner && store.meta(settleKey(p, agent))) {
1271
- store.meta(settleKey(p, agent), "");
1272
- return start("review", null, needsStart);
1273
- }
1274
- // Checked like any work, so the person sees whether it clashes before they press Start.
1275
- if (needsStart && !store.meta(`project-asked-note:${p.id}:${agent}`)) {
1276
- store.meta(`project-asked-note:${p.id}:${agent}`, "1");
1277
- note(
1278
- p,
1279
- `${display(p, asker)} asked ${nameOf(agent)} for work. It waits for your Start: agents here don't start work the other side asks for on their own.`
1280
- );
1281
- }
1282
- const begin = () => {
1283
- const fresh = project(p.id);
1284
- if (
1285
- fresh?.status !== "open" ||
1286
- !ownAgents(fresh).includes(agent) ||
1287
- (fromPartner && !isPeer(fresh, asker))
1288
- )
1289
- return {
1290
- ok: false,
1291
- error:
1292
- "The room or this task's participation changed before it could start.",
1293
- };
1294
- return start(needsStart ? "wait" : mode);
1295
- };
1296
- let current = openWork(p, agent);
1297
- if (current?.body.status === "clash") {
1298
- write(p, "work", { waiting: { reason, asker, go } }, current.id);
1299
- return start("review", null, needsStart);
1300
- }
1301
- // The asker's own words when the wake carries them, else the wake's reason without its "… asked you:" lead.
1302
- const summary = String(
1303
- words ??
1304
- String(reason).replace(/^[^:]{0,80}(?:mentioned|asked) you: /, "")
1305
- )
1306
- .replace(/(^|\s)@[a-z0-9][a-z0-9./-]*/gi, "$1")
1307
- .replace(/\s+/g, " ")
1308
- .trim()
1309
- .slice(0, SUMMARY_CHARS);
1310
- // A person's new ask is what the agent builds next: its piece of work takes those words and is checked again; its
1311
- // branch takes the new name while nothing is on it yet. An agent's follow-up goes on with the piece as it is.
1312
- const person = asker === "user" || String(asker).endsWith("/person");
1313
- // A claimed piece keeps its own words: a new ask goes on beside it.
1314
- if (
1315
- current &&
1316
- person &&
1317
- !current.body.piece &&
1318
- summary !== current.body.summary
1319
- )
1320
- current = write(
1321
- p,
1322
- "work",
1323
- {
1324
- summary,
1325
- status: "checking",
1326
- ...(current.body.head || fs.existsSync(laneOf(p, current))
1327
- ? {}
1328
- : { branch: `${p.me}/${agent}/${branchSlug(summary)}` }),
1329
- },
1330
- current.id
1331
- );
1332
- else if (current && current.body.status !== "checking") return begin();
1333
- const work =
1334
- current ??
1335
- write(p, "work", {
1336
- agent,
1337
- summary,
1338
- touches: [],
1339
- files: [],
1340
- status: "checking",
1341
- base: p.repo.head,
1342
- branch: `${p.me}/${agent}/${branchSlug(summary)}`,
1343
- startedFor: shared(p, asker),
1344
- });
1345
- void (async () => {
1346
- const result = await checkNewest(project(p.id), work);
1347
- const fresh = project(p.id);
1348
- const holdsBack =
1349
- result.verdict === "clash" && settingsOf(fresh).check === "stop";
1350
- write(
1351
- fresh,
1352
- "work",
1353
- {
1354
- status: result.verdict,
1355
- check: result,
1356
- ...(holdsBack ? { waiting: { reason, asker, go } } : {}),
1357
- },
1358
- work.id
1359
- );
1360
- if (result.verdict === "unchecked")
1361
- note(
1362
- fresh,
1363
- `${nameOf(agent)} starts without a check against ${p.partner}'s work: Harness could not check it just now.`
1364
- );
1365
- if (
1366
- result.verdict === "overlap" ||
1367
- (result.verdict === "clash" && !holdsBack)
1368
- )
1369
- say(
1370
- fresh,
1371
- `Heads up: ${nameOf(agent)}'s "${oneLine(work.body.summary, 90)}" ${result.verdict === "clash" ? "clashes" : "overlaps"} with ${clashWords(fresh, work, result)}${result.files.length ? `, in ${result.files.join(", ")}` : ""}.${result.reason ? ` ${result.reason}` : ""}`,
1372
- []
1373
- );
1374
- if (!holdsBack) return begin();
1375
- // Each agent in the clash hears it; the other side's agents through the shared post.
1376
- const against = result.with.map((id) => item(id)).filter(Boolean);
1377
- const theirs = against
1378
- .filter((entry) => entry.side !== p.me)
1379
- .map((entry) => `${entry.side}/${entry.body.agent}`);
1380
- const ours = against
1381
- .filter((entry) => entry.side === p.me)
1382
- .map((entry) => entry.body.agent);
1383
- say(
1384
- fresh,
1385
- `Before ${nameOf(agent)} starts "${oneLine(work.body.summary, 90)}": it clashes with ${clashWords(fresh, work, result)}.${result.reason ? ` ${result.reason}` : ""} ${[agent, ...ours, ...theirs].map((name) => `@${name}`).join(" ")}, agree how these fit together, then one of you proposes it with propose (work ${work.id}). The work starts once a person OKs it.`,
1386
- [agent, ...ours, ...theirs],
1387
- [work.id, ...result.with]
1388
- );
1389
- notifyDesktop(
1390
- `Work clashes in "${oneLine(p.title, 60)}": ${nameOf(agent)} waits while the agents settle it.`,
1391
- { thread: p.roomId }
1392
- );
1393
- start(
1394
- "review",
1395
- `Your planned work clashes, so it waits. ${result.reason ?? ""} Read the thread, agree with the other agent how the two pieces fit, and propose it (propose, about work ${work.id}). Do not change files until it is agreed.`,
1396
- needsStart
1397
- );
1398
- })();
1399
- };
1400
- // The dispatcher's post in the room, shared with the other side; `clash` names the work a clash post is about.
1401
- const say = (p, text, mentions, clash = null) => {
1402
- if (!p.roomId) return null;
1403
- // The room's listener shares the post as it is made (posted), so the clash it names is set first.
1404
- nextClash = clash;
1405
- saying = true;
1406
- const post = store.roomPost({
1407
- goalId: p.roomId,
1408
- author: DISPATCHER,
1409
- kind: "post",
1410
- text,
1411
- mentions,
1412
- });
1413
- nextClash = null;
1414
- saying = false;
1415
- notifyBoard(store.getTask(p.roomId));
1416
- return post;
1417
- };
1418
- // A fix both sides agreed: this side's work held by the clash starts, only on this person's own yes here, and with the
1419
- // go its ask had: work the other side asked for still waits for the Start (or runs restricted where both let it).
1420
- const release = (p, work, proposal) => {
1421
- if (!work || work.side !== p.me || work.body.status !== "clash") return;
1422
- const mine = answersTo(p, proposal.id).some(
1423
- (answer) => answer.side === p.me && answer.yes === true
1424
- );
1425
- if (!mine) return;
1426
- const waiting = work.body.waiting;
1427
- write(
1428
- p,
1429
- "work",
1430
- { status: "clear", fix: proposal.id, waiting: null },
1431
- work.id
1432
- );
1433
- if (!waiting || !p.roomId) return;
1434
- const asker = String(waiting.asker || DISPATCHER);
1435
- const fromPartner = isPeer(p, asker);
1436
- wakeRun(
1437
- p.roomId,
1438
- work.body.agent,
1439
- `The fix is agreed: ${oneLine(proposal.body.text, 400)}. Go ahead with your work in that light.`,
1440
- {
1441
- go: !fromPartner && waiting.go === true,
1442
- asker,
1443
- checked: true,
1444
- wait: fromPartner && !settingsOf(p).start,
1445
- }
1446
- );
1447
- };
1448
- /**
1449
- * The other side's work, new or with a new plan, arrived here. Each side's check sees only what has reached it, so two
1450
- * pieces planned at nearly the same moment can each pass: this side checks its own open work planned since then
1451
- * again. Of the two, the newer piece is the one held, so only one side holds and says so.
1452
- */
1453
- const workChanged = (p, theirs, previous) => {
1454
- if (!theirs || theirs.side === p.me) return;
1455
- if (!OPEN_WORK.includes(theirs.body.status)) return;
1456
- if (previous && previous.body.summary === theirs.body.summary) return;
1457
- const mine = items(p.id, "work").filter(
1458
- (entry) =>
1459
- entry.side === p.me &&
1460
- ["clear", "overlap", "unchecked"].includes(entry.body.status) &&
1461
- entry.at >= theirs.at
1462
- );
1463
- for (const work of mine)
1464
- void (async () => {
1465
- const result = await checkNewest(project(p.id), item(work.id));
1466
- const fresh = project(p.id);
1467
- const now = item(work.id);
1468
- if (
1469
- !result.with.includes(theirs.id) ||
1470
- result.verdict === now.body.status
1471
- )
1472
- return;
1473
- const holdsBack =
1474
- result.verdict === "clash" && settingsOf(fresh).check === "stop";
1475
- write(
1476
- fresh,
1477
- "work",
1478
- { status: result.verdict, check: result },
1479
- work.id
1480
- );
1481
- const started = now.body.head
1482
- ? ` It has already changed ${now.body.files?.length ?? 0} file(s) on ${now.body.branch}.`
1483
- : "";
1484
- if (holdsBack)
1485
- say(
1486
- fresh,
1487
- `${nameOf(now.body.agent)}'s "${oneLine(now.body.summary, 90)}" clashes with ${clashWords(fresh, now, result)}, planned at nearly the same moment.${started} @${now.body.agent} @${theirs.side}/${theirs.body.agent}, agree how these fit together, then one of you proposes it with propose (work ${now.id}). Its next turn waits until a person OKs it.`,
1488
- [now.body.agent, `${theirs.side}/${theirs.body.agent}`],
1489
- [now.id, theirs.id]
1490
- );
1491
- else
1492
- say(
1493
- fresh,
1494
- `Heads up: ${nameOf(now.body.agent)}'s "${oneLine(now.body.summary, 90)}" ${result.verdict === "clash" ? "clashes" : "overlaps"} with ${clashWords(fresh, now, result)}.`,
1495
- []
1496
- );
1497
- })().catch((error) => log(`project late check: ${error.message}`));
1498
- };
1499
-
1500
- /** Where an agent's run in a project's room works: its own branch for its open piece of work. */
1501
- const folderFor = (task, agent, { review = false } = {}) => {
1502
- const p = projectOfRoom(task.id);
1503
- if (!p) return null;
1504
- if (!p.repo.first) return task.goal.workspace;
1505
- if (review || !p.folder) return null;
1506
- const work = openWork(p, agent);
1507
- if (!work) return null;
1508
- const where = laneOf(p, work);
1509
- // Canon's commit the work started from, when this computer has it; else canon as this computer last fetched it.
1510
- const base = holds(p.folder, work.body.base)
1511
- ? work.body.base
1512
- : `origin/${p.repo.canon}`;
1513
- const made = laneFor({
1514
- checkout: p.folder,
1515
- where,
1516
- branch: work.body.branch,
1517
- base,
1518
- });
1519
- if (!made.ok) throw new Error(made.error);
1520
- return where;
1521
- };
1522
- /** A finished turn's changes, committed on the agent's own branch; pushed when both people let agents push. */
1523
- const committed = (task) => {
1524
- const p = projectOfRoom(task.parent_id);
1525
- if (!p || !p.folder) return undefined;
1526
- const work =
1527
- verdictContext({
1528
- id: p.id,
1529
- work: store.getTask(task.id)?.returned?.work,
1530
- agent: task.target_agent,
1531
- run: task.id,
1532
- before: task.claimed_at,
1533
- })?.work ?? pieces.stoppedWork(p, task.target_agent);
1534
- // A run with no piece of work of its own (a review) worked in the thread's copy, which commits as any thread's does.
1535
- if (!work) return undefined;
1536
- const where = laneOf(p, work);
1537
- if (
1538
- !task.run_workspace ||
1539
- path.resolve(task.run_workspace) !== path.resolve(where)
1540
- )
1541
- return undefined;
1542
- const sha = commitLane(
1543
- where,
1544
- `${task.target_agent}: ${oneLine(work.body.summary, 150)}`
1545
- );
1546
- const head = sha ?? laneHead(where);
1547
- if (!head) return null;
1548
- const files = changedFiles(where, work.body.base);
1549
- write(p, "work", { head, files }, work.id);
1550
- if (settingsOf(p).push) void push(p, item(work.id));
1551
- return sha;
1552
- };
1553
- const push = async (p, work) => {
1554
- if (!p.folder) return { ok: false, error: "This room has no repository." };
1555
- const pushed = await pushLane(laneOf(p, work), work.body.branch);
1556
- if (pushed.ok)
1557
- write(project(p.id), "work", { pushed: work.body.head ?? null }, work.id);
1558
- else
1559
- note(
1560
- p,
1561
- `${nameOf(work.body.agent)}'s branch did not reach the remote: ${pushed.error}`
1562
- );
1563
- return pushed;
1564
- };
1565
- const pullRequest = async (p, work) => {
1566
- if (!p.folder) return { ok: false, error: "This room has no repository." };
1567
- if (work.body.pr?.number) return { ok: true };
1568
- if (work.body.pushed !== work.body.head) {
1569
- const pushed = await push(p, work);
1570
- if (!pushed.ok) return pushed;
1571
- }
1572
- const made = await openPullRequest(laneOf(p, work), {
1573
- branch: work.body.branch,
1574
- canon: p.repo.canon,
1575
- title: oneLine(work.body.summary, 120),
1576
- body: `${work.body.summary}\n\nFrom ${display(p, `${p.me}/${work.body.agent}`)} in the project "${p.title}", shared with ${p.partner} in Harness.`,
1577
- });
1578
- if (!made.ok) {
1579
- note(
1580
- p,
1581
- `No pull request for ${nameOf(work.body.agent)}'s work: ${made.error}`
1582
- );
1583
- return made;
1584
- }
1585
- write(
1586
- project(p.id),
1587
- "work",
1588
- {
1589
- pr: {
1590
- number: made.number,
1591
- url: made.url,
1592
- state: "open",
1593
- checks: "running",
1594
- },
1595
- },
1596
- work.id
1597
- );
1598
- return made;
1599
- };
1600
-
1601
- // ---- the person's commands ----
1602
-
1603
- const repos = () => {
1604
- const seen = new Set();
1605
- const listed = [];
1606
- for (const folder of knownFolders().slice(0, 40)) {
1607
- const anchored = anchorOf(folder);
1608
- if (!anchored.ok || seen.has(anchored.folder)) continue;
1609
- seen.add(anchored.folder);
1610
- listed.push({
1611
- folder: anchored.folder,
1612
- name: anchored.repo.name,
1613
- canon: anchored.repo.canon,
1614
- });
1615
- }
1616
- return listed;
1617
- };
1618
-
1619
- // What the person chose for agents when they start a project: any setting they set, the rest as they start.
1620
- const chosenSettings = (chosen) => {
1621
- const settings = initialSettings();
1622
- if (chosen && typeof chosen === "object")
1623
- for (const key of SETTING_KEYS)
1624
- if (validSetting(key, chosen[key])) settings[key] = chosen[key];
1625
- return effectiveSettings(settings, []);
1626
- };
1627
-
1628
- const create = async ({
1629
- folder,
1630
- partner,
1631
- partners,
1632
- title,
1633
- settings,
1634
- selectedAgents,
1635
- }) => {
1636
- if (Array.isArray(partners) || !folder) {
1637
- const me = await myHandle();
1638
- if (!me)
1639
- throw new Error("Claim your swarm's name first (Swarms, Your card).");
1640
- const chosen = Array.isArray(partners) ? partners : [partner];
1641
- const handles = [
1642
- ...new Set(
1643
- chosen.map((handle) =>
1644
- String(handle ?? "")
1645
- .trim()
1646
- .toLowerCase()
1647
- .replace(/^@/, "")
1648
- )
1649
- ),
1650
- ];
1651
- if (!handles.length || handles.some((handle) => !HANDLE.test(handle)))
1652
- throw new Error("Write each person's swarm name, separated by commas.");
1653
- if (handles.includes(me))
1654
- throw new Error("That's your own swarm's name.");
1655
- const anchored = folder
1656
- ? anchorOf(String(folder))
1657
- : { ok: true, repo: {}, folder: null };
1658
- if (!anchored.ok) throw new Error(anchored.error);
1659
- const name = String(
1660
- title || (anchored.repo.name ? path.basename(anchored.repo.name) : "")
1661
- )
1662
- .trim()
1663
- .slice(0, 120);
1664
- if (!name)
1665
- throw new Error(
1666
- "Give the room a name that says what you want to do together."
1667
- );
1668
- const group = channels.init({
1669
- me,
1670
- title: name,
1671
- repo: anchored.repo,
1672
- settings: chosenSettings(settings),
1673
- agents: selectedAgents,
1674
- });
1675
- const p = makeRoom(
1676
- insertProject({
1677
- id: group.id,
1678
- title: name,
1679
- me,
1680
- partner: handles[0],
1681
- role: "inviter",
1682
- status: "open",
1683
- repo: anchored.repo,
1684
- folder: anchored.folder,
1685
- agreed: group.settings,
1686
- })
1687
- );
1688
- await channels.invite(p.id, handles);
1689
- note(
1690
- p,
1691
- `Invited ${handles.join(", ")}. Shared room history is visible to people who join; the room owner can invite others.`
1692
- );
1693
- return project(p.id);
1694
- }
1695
- const handle = String(partner || "")
1696
- .toLowerCase()
1697
- .replace(/^@/, "")
1698
- .trim();
1699
- if (!HANDLE.test(handle))
1700
- throw new Error("Write the other person's swarm name, for example maya.");
1701
- const anchored = anchorOf(String(folder || ""));
1702
- if (!anchored.ok) throw new Error(anchored.error);
1703
- const me = await myHandle();
1704
- if (!me)
1705
- throw new Error("Claim your swarm's name first (Swarms, Your card).");
1706
- if (me === handle) throw new Error("That's your own swarm's name.");
1707
- const name =
1708
- String(title || "")
1709
- .trim()
1710
- .slice(0, 120) || path.basename(anchored.repo.name);
1711
- const offer = {
1712
- v: 1,
1713
- title: name,
1714
- from: me,
1715
- to: handle,
1716
- repo: anchored.repo,
1717
- settings: chosenSettings(settings),
1718
- };
1719
- const sent = await relayRequest({
1720
- to: `${handle}/person`,
1721
- fromAgent: "person",
1722
- about: `Project: ${name}`,
1723
- brief: `${me} would like your swarm and theirs to work on ${anchored.repo.name} together in Harness.`,
1724
- refs: [],
1725
- project: offer,
1726
- });
1727
- if (!sent.sealed)
1728
- throw new Error(
1729
- `${handle}'s computer can't take a sealed project yet. Ask them to update Harness.`
1730
- );
1731
- const p = makeRoom(
1732
- insertProject({
1733
- id: String(sent.threadId),
1734
- title: name,
1735
- me,
1736
- partner: handle,
1737
- role: "inviter",
1738
- status: "invited",
1739
- repo: anchored.repo,
1740
- folder: anchored.folder,
1741
- agreed: offer.settings,
1742
- })
1743
- );
1744
- note(
1745
- p,
1746
- `Invited ${handle}. Your agents and theirs work here together once they join.`
1747
- );
1748
- return p;
1749
- };
1750
-
1751
- const join = async ({ id, folder, clone, selectedAgents }) => {
1752
- const invite = (await listInvites()).find((entry) => entry.id === id);
1753
- if (!invite) throw new Error("That invitation is no longer waiting.");
1754
- const refused = offerRefusal(invite, await myHandle());
1755
- if (refused) throw new Error(refused);
1756
- const offer = invite.project;
1757
- const groupId = offer.v === 2 ? offer.id : id;
1758
- let checkout =
1759
- folder && offer.repo?.first
1760
- ? findCheckout([String(folder)], offer.repo.first)
1761
- : null;
1762
- if (folder && !checkout)
1763
- throw new Error(`That folder doesn't hold ${offer.repo.name}.`);
1764
- if (offer.repo?.first)
1765
- checkout ??= findCheckout(knownFolders(), offer.repo.first);
1766
- if (offer.repo?.first && !checkout && clone) {
1767
- const cloned = await cloneInto(offer.repo.remote, offer.repo.name);
1768
- if (!cloned.ok) throw new Error(cloned.error);
1769
- checkout = findCheckout([cloned.folder], offer.repo.first);
1770
- }
1771
- if (offer.repo?.first && !checkout)
1772
- return {
1773
- ok: false,
1774
- code: "no_folder",
1775
- error: `${offer.repo.name} isn't on this computer yet.`,
1776
- };
1777
- if (
1778
- offer.v === 2 &&
1779
- (!groupOf({ id: groupId }) || project(groupId)?.status === "left")
1780
- )
1781
- channels.join(invite, await myHandle(), selectedAgents);
1782
- if (!project(groupId))
1783
- insertProject({
1784
- id: groupId,
1785
- title: offer.title,
1786
- me: offer.to,
1787
- partner: offer.from,
1788
- role: "invitee",
1789
- status: "joining",
1790
- repo: offer.repo ?? {},
1791
- folder: checkout,
1792
- agreed: offer.settings,
1793
- });
1794
- else
1795
- save(groupId, {
1796
- folder: checkout,
1797
- repo: offer.repo ?? {},
1798
- agreed: offer.settings,
1799
- status: "joining",
1800
- });
1801
- await decideRequest(id, "accept");
1802
- return { ok: true, project: view(project(groupId)) };
1803
- };
1804
-
1805
- /**
1806
- * Why an invitation can't be taken, or null. It names the person who sent it and the person it is for, as the relay
1807
- * thread under it does (security audit P3: a v1 offer could claim to come from anyone); its repository is named by
1808
- * a commit, a branch git reads as a branch, and an address git fetches from (P5: a branch starting with "-" reached
1809
- * git as an option).
1810
- */
1811
- const offerRefusal = (invite, me) => {
1812
- const offer = invite?.project;
1813
- if (!offer || typeof offer !== "object")
1814
- return "That invitation can't be read.";
1815
- if (offer.v !== 2 && (offer.from !== invite.sender || offer.to !== me))
1816
- return "That invitation doesn't match who sent it.";
1817
- if (offer.v === 2) {
1818
- try {
1819
- channels.validate(invite, me);
1820
- } catch (error) {
1821
- return error.message;
1822
- }
1823
- }
1824
- const repo = offer.repo ?? {};
1825
- if (
1826
- repo.first &&
1827
- (!validSha(repo.first) ||
1828
- !validBranch(repo.canon) ||
1829
- (repo.remote && !validRemote(repo.remote)))
1830
- )
1831
- return "That invitation's repository isn't named in a way Harness can use safely.";
1832
- return null;
1833
- };
1834
-
1835
- /** The person thread under a project opened on this computer: the project is open, and the other side hears so. */
1836
- const channelOpened = (taskId) => {
1837
- if (channels.opened(taskId)) return;
1838
- const p = project(taskId);
1839
- if (!p || !["invited", "joining"].includes(p.status)) return;
1840
- const opened = makeRoom(save(p.id, { status: "open" }));
1841
- if (opened.role === "inviter") {
1842
- note(
1843
- opened,
1844
- `${opened.partner} joined. Their agents work here with yours from now on.`
1845
- );
1846
- notifyDesktop(
1847
- `${opened.partner} joined "${oneLine(opened.title, 60)}".`,
1848
- {
1849
- thread: opened.roomId,
1850
- }
1851
- );
1852
- } else
1853
- note(
1854
- opened,
1855
- `You joined ${opened.partner}'s project. Your agents work here with theirs.`
1856
- );
1857
- hello(opened);
1858
- resend();
1859
- void refresh().catch((error) => log(`projects: ${error.message}`));
1860
- };
1861
-
1862
- /** The thread under a project ended from the other side: they left. */
1863
- const channelEnded = (taskId) => {
1864
- if (channels.closed(taskId)) return;
1865
- const p = project(taskId);
1866
- if (!p || p.status !== "open") return;
1867
- save(p.id, { status: "left" });
1868
- store.meta(`project-ended:${p.id}`, "they_left");
1869
- note(
1870
- project(p.id),
1871
- `${p.partner} left the project. This room stays here; nothing more goes between you.`
1872
- );
1873
- notifyDesktop(`${p.partner} left the project "${oneLine(p.title, 60)}".`, {
1874
- thread: p.roomId,
1875
- });
1876
- };
1877
-
1878
- const leave = (p) => {
1879
- if (groupOf(p)) {
1880
- channels.leave(p.id);
1881
- return;
1882
- }
1883
- if (p.status === "open") send(p, { type: "left", at: now() });
1884
- save(p.id, { status: "left" });
1885
- store.meta(`project-ended:${p.id}`, "you_left");
1886
- // As a shared room does on leaving (onChange): what waits or runs in the room for the project stops with it.
1887
- if (p.roomId) stopRoom(p.roomId);
1888
- endChannel(p.id, "Left the project.");
1889
- note(
1890
- project(p.id),
1891
- "You left the project. This room stays here; nothing more goes between you."
1892
- );
1893
- };
1894
-
1895
- const setting = (p, key, value) => {
1896
- if (!validSetting(key, value))
1897
- throw new Error("That setting can't take that value.");
1898
- const current = settingsOf(p);
1899
- if (current[key] === value) return { ok: true };
1900
- if (!widens(key, current[key], value)) {
1901
- write(p, "setting", { key, value });
1902
- note(project(p.id), `You changed it: ${settingLine(key, value)}.`);
1903
- return { ok: true };
1904
- }
1905
- const open = items(p.id, "proposal").find(
1906
- (proposal) =>
1907
- proposal.body.type === "setting" &&
1908
- proposal.body.key === key &&
1909
- stateOf(p, proposal).state === "waiting"
1910
- );
1911
- if (open) return { ok: true, waiting: true };
1912
- propose(
1913
- p,
1914
- {
1915
- type: "setting",
1916
- key,
1917
- value,
1918
- needs: peopleOf(p),
1919
- text: settingLine(key, value),
1920
- },
1921
- "user"
1922
- );
1923
- return { ok: true, waiting: true };
1924
- };
1925
-
1926
- const answer = (p, proposalId, yes) => {
1927
- const proposal = item(proposalId);
1928
- if (!proposal || proposal.projectId !== p.id)
1929
- throw new Error("That proposal isn't here.");
1930
- if (!needsOf(p, proposal.body, proposal.side).includes(p.me))
1931
- throw new Error("That one doesn't need your OK.");
1932
- write(
1933
- p,
1934
- "answer",
1935
- { proposal: proposal.id, yes: Boolean(yes) },
1936
- `${proposal.id}:${p.me}`
1937
- );
1938
- answered(project(p.id), item(proposal.id));
1939
- return { ok: true };
1940
- };
1941
-
1942
- const withdraw = (p, proposalId) => {
1943
- const proposal = item(proposalId);
1944
- if (!proposal || proposal.side !== p.me)
1945
- throw new Error("Only a proposal from your side can be withdrawn here.");
1946
- if (stateOf(p, proposal).state === "accepted")
1947
- throw new Error("An agreed decision needs a new proposal to change it.");
1948
- write(p, "proposal", { withdrawn: true }, proposal.id);
1949
- return { ok: true };
1950
- };
1951
-
1952
- const workAction = async (p, workId, action) => {
1953
- const work = item(workId);
1954
- if (!work || work.projectId !== p.id || work.side !== p.me)
1955
- throw new Error("Only your side's work can be changed from here.");
1956
- if (action === "push") {
1957
- const pushed = await push(p, work);
1958
- if (!pushed.ok) throw new Error(pushed.error);
1959
- return { ok: true };
1960
- }
1961
- if (action === "pull_request") {
1962
- const made = await pullRequest(p, work);
1963
- if (!made.ok) throw new Error(made.error);
1964
- return { ok: true };
1965
- }
1966
- if (action === "stop") {
1967
- write(p, "work", { status: "stopped" }, work.id);
1968
- return { ok: true };
1969
- }
1970
- throw new Error("unknown action");
1971
- };
1972
-
1973
- // ---- what agents call ----
1974
-
1975
- /** An agent's own piece of work: what it plans now, what it touches, or that it is done. A changed plan is checked again. */
1976
- const plan = async (p, agent, { summary, touches, done, stopped }) => {
1977
- let work = openWork(p, agent);
1978
- if (!work && !summary) throw new Error("say what you plan to do (summary)");
1979
- if (!work)
1980
- work = write(p, "work", {
1981
- agent,
1982
- summary: String(summary).slice(0, SUMMARY_CHARS),
1983
- touches: [],
1984
- files: [],
1985
- status: "checking",
1986
- base: p.repo.head,
1987
- branch: `${p.me}/${agent}/${branchSlug(summary)}`,
1988
- });
1989
- if (done || stopped) {
1990
- write(p, "work", { status: done ? "review" : "stopped" }, work.id);
1991
- const fresh = project(p.id);
1992
- if (done && settingsOf(fresh).mergeDecisions) {
1993
- const result = await check(fresh, item(work.id), "merge");
1994
- if (result.decision)
1995
- say(
1996
- fresh,
1997
- `${nameOf(agent)}'s "${oneLine(work.body.summary, 90)}" changes what you decided: ${oneLine(decisionsOf(fresh).find((entry) => entry.id === result.decision)?.text, 160)}. It needs a new decision before it merges.`,
1998
- []
1999
- );
2000
- write(fresh, "work", { mergeCheck: result }, work.id);
2001
- }
2002
- if (done && settingsOf(fresh).pullRequests)
2003
- await pullRequest(fresh, item(work.id));
2004
- return { ok: true, work: workView(fresh, item(work.id)) };
2005
- }
2006
- const changed =
2007
- (summary && String(summary) !== work.body.summary) ||
2008
- (Array.isArray(touches) &&
2009
- JSON.stringify(touches) !== JSON.stringify(work.body.touches));
2010
- write(
2011
- p,
2012
- "work",
2013
- {
2014
- ...(changed ? { returned: null, verdict: null } : {}),
2015
- ...(summary
2016
- ? { summary: String(summary).slice(0, SUMMARY_CHARS) }
2017
- : {}),
2018
- ...(Array.isArray(touches)
2019
- ? { touches: touches.map(String).slice(0, 30) }
2020
- : {}),
2021
- },
2022
- work.id
2023
- );
2024
- if (!changed && work.body.status !== "checking")
2025
- return { ok: true, work: workView(p, item(work.id)) };
2026
- const result = await checkNewest(project(p.id), item(work.id));
2027
- const fresh = project(p.id);
2028
- const holdsBack =
2029
- result.verdict === "clash" && settingsOf(fresh).check === "stop";
2030
- write(fresh, "work", { status: result.verdict, check: result }, work.id);
2031
- return {
2032
- ok: true,
2033
- work: workView(fresh, item(work.id)),
2034
- ...(holdsBack
2035
- ? {
2036
- note: `This clashes with ${clashWords(fresh, work, result)}. ${result.reason ?? ""} Don't change files for it until it's settled: agree with the other agent and propose the fix.`,
2037
- }
2038
- : result.verdict === "overlap"
2039
- ? {
2040
- note: `This overlaps with ${clashWords(fresh, work, result)}. Go ahead, and keep the other side in the loop.`,
2041
- }
2042
- : {}),
2043
- };
2044
- };
2045
-
2046
- const agentPropose = (p, agent, { text, decision, about, changes }) => {
2047
- const body = String(text || "").trim();
2048
- if (!body) throw new Error("say what you propose (text)");
2049
- const known = (ids) =>
2050
- [...new Set((Array.isArray(ids) ? ids : []).map(String))].filter(
2051
- (id) => item(id)?.projectId === p.id
2052
- );
2053
- const named = known([...(about ?? []), ...(changes ?? [])]);
2054
- // The work it changes is what it releases once agreed, and whose people it needs: never more than it names.
2055
- const changing = changes?.length ? known(changes) : named;
2056
- const proposal = propose(
2057
- p,
2058
- {
2059
- type: named.length ? "fix" : "decision",
2060
- text: body,
2061
- ...(decision
2062
- ? { decision: String(decision).slice(0, PROPOSAL_CHARS) }
2063
- : {}),
2064
- about: named,
2065
- changes: changing,
2066
- // Older computers read who it needs from here; this one works it out itself (needsOf).
2067
- needs: needsFor(p, {
2068
- decision: decision || !named.length,
2069
- changes: changing,
2070
- }),
2071
- },
2072
- agent
2073
- );
2074
- return {
2075
- ok: true,
2076
- proposal: proposal.id,
2077
- waitingOn: stateOf(p, proposal).waitingOn,
2078
- };
2079
- };
2080
-
2081
- // ---- what the person reads ----
2082
-
2083
- const workView = (p, work) => {
2084
- const mine = work.side === p.me;
2085
- const where = mine && p.folder ? laneOf(p, work) : null;
2086
- return {
2087
- id: work.id,
2088
- side: work.side,
2089
- you: mine,
2090
- agent: work.body.agent,
2091
- who: display(p, `${work.side}/${work.body.agent}`),
2092
- summary: work.body.summary,
2093
- status: work.body.status,
2094
- branch: work.body.branch,
2095
- files: work.body.files?.length ?? 0,
2096
- behind:
2097
- mine && p.folder && validSha(p.repo.head)
2098
- ? behind(p.folder, work.body.base, p.repo.head)
2099
- : null,
2100
- pushed: Boolean(work.body.pushed) && work.body.pushed === work.body.head,
2101
- committed: Boolean(work.body.head),
2102
- pr: work.body.pr ?? null,
2103
- check: work.body.check
2104
- ? {
2105
- verdict: work.body.check.verdict,
2106
- reason: work.body.check.reason,
2107
- with: work.body.check.with
2108
- .map((id) => item(id))
2109
- .filter(Boolean)
2110
- .map((entry) => ({
2111
- id: entry.id,
2112
- who: display(p, `${entry.side}/${entry.body.agent}`),
2113
- summary: entry.body.summary,
2114
- })),
2115
- }
2116
- : null,
2117
- needsDecision: Boolean(work.body.mergeCheck?.decision),
2118
- folder: where,
2119
- ...verdicts?.view(p, work, where),
2120
- updatedAt: work.updatedAt,
2121
- };
2122
- };
2123
- const proposalView = (p, proposal) => {
2124
- const standing = stateOf(p, proposal);
2125
- return {
2126
- id: proposal.id,
2127
- type: proposal.body.type,
2128
- text: proposal.body.text,
2129
- decision: proposal.body.decision ?? null,
2130
- // The pieces of work a fix settles.
2131
- about: proposal.body.about ?? [],
2132
- by: display(p, proposal.body.by),
2133
- yours: proposal.side === p.me,
2134
- state: standing.state,
2135
- needsYou: standing.waitingOn.includes(p.me),
2136
- waitingOn: standing.waitingOn.map((side) =>
2137
- side === p.me ? "you" : side
2138
- ),
2139
- at: proposal.at,
2140
- };
2141
- };
2142
- const view = (p) => {
2143
- const group = groupOf(p);
2144
- const settings = settingsOf(p);
2145
- const proposals = items(p.id, "proposal").map((proposal) =>
2146
- proposalView(p, proposal)
2147
- );
2148
- const work = items(p.id, "work")
2149
- .filter(
2150
- (entry) =>
2151
- !["stopped", "merged"].includes(entry.body.status) ||
2152
- Date.parse(entry.updatedAt) > Date.now() - 3 * 86_400_000
2153
- )
2154
- .map((entry) => workView(p, entry));
2155
- const held = all(
2156
- "select post_id from project_posts where project_id = ? and state = 'held'",
2157
- p.id
2158
- ).length;
2159
- return {
2160
- id: p.id,
2161
- roomId: p.roomId,
2162
- title: p.title,
2163
- status: p.status,
2164
- role: p.role,
2165
- kind: p.repo.first ? "project" : "room",
2166
- goal: goalOf(p),
2167
- ...(group
2168
- ? {
2169
- owner: group.owner,
2170
- history: group.history,
2171
- availableAgents: agents().map((id) => ({ id, name: nameOf(id) })),
2172
- connectionErrors: group.errors,
2173
- }
2174
- : {}),
2175
- // Why it ended, as the list says it (declined, expired, they_left, you_left), or null.
2176
- ended: store.meta(`project-ended:${p.id}`) || null,
2177
- me: p.me,
2178
- partner: group ? peersOf(p).join(", ") || p.partner : p.partner,
2179
- repo: {
2180
- first: "",
2181
- name: "",
2182
- remote: "",
2183
- canon: "",
2184
- head: null,
2185
- ...p.repo,
2186
- short: p.repo.head?.slice(0, 7) ?? null,
2187
- folder: p.folder,
2188
- },
2189
- people: group
2190
- ? group.members.map((member) => ({
2191
- ...member,
2192
- you: member.handle === p.me,
2193
- agents: (member.handle === p.me
2194
- ? ownAgents(p)
2195
- : (group.rosters[member.handle] ?? [])
2196
- ).map((id) => ({
2197
- id: member.handle === p.me ? id : `${member.handle}/${id}`,
2198
- name: nameOf(id),
2199
- })),
2200
- connected:
2201
- member.handle === p.me ||
2202
- channels
2203
- .routes(p.id)
2204
- .some(
2205
- (route) =>
2206
- route.peer === member.handle && route.state === "open"
2207
- ),
2208
- }))
2209
- : [
2210
- {
2211
- handle: p.me,
2212
- you: true,
2213
- agents: agents().map((id) => ({ id, name: nameOf(id) })),
2214
- },
2215
- {
2216
- handle: p.partner,
2217
- you: false,
2218
- agents: p.roster.map((entry) => ({
2219
- id: `${p.partner}/${entry.id}`,
2220
- name: nameOf(entry.id),
2221
- })),
2222
- },
2223
- ],
2224
- work,
2225
- pieces: pieces.view(p),
2226
- strengths: pieces.strengthsOf(p),
2227
- decisions: decisionsOf(p).map((entry) => ({
2228
- ...entry,
2229
- by: display(p, entry.by),
2230
- })),
2231
- proposals: proposals.filter((proposal) => proposal.state === "waiting"),
2232
- notes: items(p.id, "note").map((entry) => ({
2233
- id: entry.id,
2234
- text: entry.body.text,
2235
- by: display(p, entry.body.by ?? `${entry.side}/person`),
2236
- at: entry.at,
2237
- })),
2238
- settings: SETTING_KEYS.filter(
2239
- (key) =>
2240
- p.repo.first ||
2241
- !["push", "pullRequests", "mergeChecks", "mergeDecisions"].includes(
2242
- key
2243
- )
2244
- ).map((key) => {
2245
- const pending = items(p.id, "proposal").find(
2246
- (proposal) =>
2247
- proposal.body.type === "setting" &&
2248
- proposal.body.key === key &&
2249
- stateOf(p, proposal).state === "waiting"
2250
- );
2251
- return {
2252
- key,
2253
- label: SETTINGS[key].label,
2254
- value: settings[key],
2255
- choices: SETTINGS[key].choices ?? null,
2256
- pending: pending
2257
- ? {
2258
- id: pending.id,
2259
- value: pending.body.value,
2260
- needsYou: stateOf(p, pending).waitingOn.includes(p.me),
2261
- by: display(p, pending.body.by),
2262
- }
2263
- : null,
2264
- };
2265
- }),
2266
- needsYou: proposals.filter((proposal) => proposal.needsYou).length + held,
2267
- held,
2268
- updatedAt: p.updatedAt,
2269
- };
2270
- };
2271
- const summaryOf = (p) => {
2272
- const full = view(p);
2273
- return {
2274
- id: p.id,
2275
- roomId: p.roomId,
2276
- title: p.title,
2277
- status: p.status,
2278
- partner: full.partner,
2279
- kind: full.kind,
2280
- invitationIds: groupOf(p)
2281
- ? channels.routes(p.id).map((route) => route.id)
2282
- : [p.id],
2283
- people: full.people.map(({ handle, status, you }) => ({
2284
- handle,
2285
- status,
2286
- you,
2287
- })),
2288
- repo: { name: p.repo.name ?? "" },
2289
- // Why a project ended: declined, expired (the invitation ran out), they_left or you_left; null while it hasn't.
2290
- ended: store.meta(`project-ended:${p.id}`) || null,
2291
- working: full.work.filter((entry) => OPEN_WORK.includes(entry.status))
2292
- .length,
2293
- needsYou: full.needsYou,
2294
- updatedAt: p.updatedAt,
2295
- };
2296
- };
2297
-
2298
- // ---- the agents' brief ----
2299
-
2300
- /** What an agent woken in a project's room is told about the project, beside the thread itself. */
2301
- const brief = (task, agent) => {
2302
- const p = projectOfRoom(task.id);
2303
- if (!p || p.status !== "open") return "";
2304
- const settings = settingsOf(p);
2305
- const work = items(p.id, "work").filter(
2306
- (entry) =>
2307
- OPEN_WORK.includes(entry.body.status) || entry.body.status === "review"
2308
- );
2309
- const own = openWork(p, agent);
2310
- const theirs = remoteAgents(p).map((entry) => `@${entry.address}`);
2311
- const decisions = decisionsOf(p);
2312
- const notes = items(p.id, "note").slice(-10);
2313
- return [
2314
- `This is a shared room with ${peersOf(p).join(", ") || "people still joining"}${p.repo.first ? `, on ${p.repo.name} (canon branch ${p.repo.canon}${p.repo.head ? ` at ${p.repo.head.slice(0, 7)}` : ""})` : ""}. Posts here reach the room's members${theirs.length ? `. Their agents: ${theirs.join(", ")} (ask one by its full name)` : ""}. Each person's private conversations, history and credentials stay theirs. Share only the material intended for this room.`,
2315
- `Shared goal: ${goalOf(p).statement}${
2316
- goalOf(p).criteria.length
2317
- ? `\nDone when:\n${goalOf(p)
2318
- .criteria.map((criterion) => `- ${criterion}`)
2319
- .join("\n")}`
2320
- : ""
2321
- }`,
2322
- own && p.repo.first
2323
- ? `Your piece of work: "${oneLine(own.body.summary, 200)}" on your own branch ${own.body.branch}, made from canon. Your changes there are committed for you after each turn. Never push to canon or to another agent's branch.`
2324
- : "",
2325
- decisions.length
2326
- ? `What the room's people decided (keep to it; changing it needs their agreement):\n${decisions.map((entry, n) => `${n + 1}. ${oneLine(entry.text, 300)}`).join("\n")}`
2327
- : "",
2328
- work.length
2329
- ? `Who is building what:\n${work.map((entry) => `- ${display(p, `${entry.side}/${entry.body.agent}`)} (work ${entry.id}): "${oneLine(entry.body.summary, 160)}" [${entry.body.status}]${entry.body.files?.length ? ` changing ${entry.body.files.slice(0, 8).join(", ")}` : ""}`).join("\n")}`
2330
- : "",
2331
- notes.length
2332
- ? `Project notes:\n${notes.map((entry) => `- ${oneLine(entry.body.text, 300)}`).join("\n")}`
2333
- : "",
2334
- pieces.brief(p, agent),
2335
- [
2336
- "In this project:",
2337
- "- Before you change code for something new, say what you plan with plan_work (summary, and the files or interfaces it touches). It is checked against the decisions and the other side's work; if it clashes, it waits.",
2338
- "- When your work is ready, call plan_work with done.",
2339
- "- To settle a clash or change a decision, agree with the other agent here, then call propose. A person OKs it before it counts.",
2340
- "- Add what the other side's agents should know too with swarm_memory (remember); it is shared.",
2341
- !p.repo.first
2342
- ? "- Work here can be research, writing or planning. Report what you produced and what evidence supports it; a claim of success alone is not completion."
2343
- : settings.push
2344
- ? "- Your branch is pushed to the shared remote for you."
2345
- : "- Your branch stays on this computer until the person pushes it.",
2346
- ].join("\n"),
2347
- ]
2348
- .filter(Boolean)
2349
- .join("\n\n");
2350
- };
2351
-
2352
- /** A note an agent saved in a project's room is the project's too: both sides' agents read it. */
2353
- const learned = (goalId, agent, text) => {
2354
- const p = projectOfRoom(goalId);
2355
- if (!p || p.status !== "open") return;
2356
- write(p, "note", {
2357
- text: String(text).slice(0, 2_000),
2358
- by: shared(p, agent),
2359
- });
2360
- };
2361
-
2362
- // ---- keeping up with the remote ----
2363
-
2364
- const refresh = async () => {
2365
- await channels.sync();
2366
- for (const p of projects().filter((entry) => entry.status === "open")) {
2367
- const head = p.folder ? await fetchCanon(p.folder, p.repo.canon) : null;
2368
- if (head && head !== p.repo.head)
2369
- save(p.id, { repo: { ...p.repo, head } });
2370
- for (const work of items(p.id, "work").filter(
2371
- (entry) =>
2372
- entry.side === p.me &&
2373
- entry.body.pr?.number &&
2374
- entry.body.pr.state === "open"
2375
- )) {
2376
- const pr = await pullRequestState(laneOf(p, work), work.body.pr.number);
2377
- if (!pr) continue;
2378
- if (
2379
- pr.state !== work.body.pr.state ||
2380
- pr.checks !== work.body.pr.checks ||
2381
- JSON.stringify(pr.review) !== JSON.stringify(work.body.pr.review) ||
2382
- pr.reviewDecision !== work.body.pr.reviewDecision
2383
- )
2384
- write(
2385
- project(p.id),
2386
- "work",
2387
- {
2388
- pr: { ...work.body.pr, ...pr },
2389
- ...(pr.state === "merged" ? { status: "merged" } : {}),
2390
- },
2391
- work.id
2392
- );
2393
- await verdicts?.detect({ id: p.id, work: work.id });
2394
- if (pr.state === "merged") {
2395
- removeLane(p.folder, laneOf(p, work));
2396
- note(
2397
- project(p.id),
2398
- `${nameOf(work.body.agent)}'s "${oneLine(work.body.summary, 90)}" is in canon.`
2399
- );
2400
- }
2401
- }
2402
- for (const work of items(p.id, "work").filter(
2403
- (entry) => entry.side === p.me
2404
- ))
2405
- await verdicts?.detect({ id: p.id, work: work.id });
2406
- pieces.refresh(project(p.id));
2407
- // A roster that changed (an agent set up here since) goes across.
2408
- const roster = JSON.stringify(ownAgents(p));
2409
- if (store.meta(`project-roster:${p.id}`) !== roster) {
2410
- store.meta(`project-roster:${p.id}`, roster);
2411
- send(p, { type: "roster", agents: ownAgents(p).map((id) => ({ id })) });
2412
- }
2413
- }
2414
- };
2415
- const timer = setInterval(
2416
- () => void refresh().catch((error) => log(`projects: ${error.message}`)),
2417
- REFRESH_MS
2418
- );
2419
- timer.unref?.();
2420
-
2421
- pieces = createPieces({
2422
- store,
2423
- log,
2424
- project,
2425
- items,
2426
- item,
2427
- write,
2428
- propose,
2429
- note,
2430
- display,
2431
- shared,
2432
- local,
2433
- ownAgents,
2434
- remoteAgents,
2435
- peopleOf,
2436
- wakeRun,
2437
- stopRun,
2438
- laneOf,
2439
- commitLane,
2440
- changedFiles,
2441
- branchSlug,
2442
- });
2443
- // The project's one board, the same on every computer in it (projectBoard.mjs).
2444
- const board = createProjectBoard({ items, write, local, shared, pieces });
2445
-
2446
- // ---- the board commands ----
2447
-
2448
- const answeredWith = (promise) => ({
2449
- pending: promise.then(
2450
- (result) => ({ ok: true, ...result }),
2451
- (error) => ({ ok: false, error: error.message })
2452
- ),
2453
- });
2454
- // An invitation the other person declined, or that ran out unanswered, says so on this side.
2455
- const noteAnswers = async () => {
2456
- const waiting = projects().filter((p) => p.status === "invited");
2457
- if (!waiting.length) return;
2458
- const answers = await sentInvites().catch(() => []);
2459
- for (const p of waiting) {
2460
- const answer = answers.find((entry) => entry.id === p.id);
2461
- if (!["declined", "blocked", "expired"].includes(answer?.status))
2462
- continue;
2463
- save(p.id, { status: "declined" });
2464
- store.meta(
2465
- `project-ended:${p.id}`,
2466
- answer.status === "expired" ? "expired" : "declined"
2467
- );
2468
- note(
2469
- project(p.id),
2470
- answer.status === "expired"
2471
- ? `${p.partner} didn't answer the invitation in a week, so it ran out.`
2472
- : `${p.partner} said no to working on this together.`
2473
- );
2474
- }
2475
- };
2476
- const projectFor = (request) =>
2477
- project(String(request.id || "")) ??
2478
- projectOfRoom(String(request.id || ""));
2479
-
2480
- const command = (request, agent) => {
2481
- const name = String(request.command || "");
2482
- if (agent !== "user") return agentCommand(name, request, agent);
2483
- if (name === "board.project.list")
2484
- return answeredWith(
2485
- noteAnswers()
2486
- .then(() => channels.sync())
2487
- .then(async () => [await listInvites(), await myHandle()])
2488
- .then(([invites, me]) => ({
2489
- projects: projects()
2490
- .filter((p) => p.status !== "joining")
2491
- .map(summaryOf),
2492
- invites: invites
2493
- .filter(
2494
- (invite) =>
2495
- invite.project.purpose !== "link" &&
2496
- !offerRefusal(invite, me) &&
2497
- (!project(
2498
- invite.project.v === 2 ? invite.project.id : invite.id
2499
- ) ||
2500
- project(
2501
- invite.project.v === 2 ? invite.project.id : invite.id
2502
- ).status === "joining" ||
2503
- project(
2504
- invite.project.v === 2 ? invite.project.id : invite.id
2505
- )?.status === "left")
2506
- )
2507
- .map((invite) => ({
2508
- id: invite.id,
2509
- // Joined here and waiting for the other computer to hear: shown as joining, not counted as waiting on you.
2510
- joining:
2511
- project(
2512
- invite.project.v === 2 ? invite.project.id : invite.id
2513
- )?.status === "joining",
2514
- title: invite.project.title,
2515
- from: invite.project.from,
2516
- at: invite.createdAt ?? null,
2517
- // Who comes with the person inviting, by name: a computer on an older version says nothing here.
2518
- theirAgents: channels
2519
- .knownAgents(invite.project.agents)
2520
- .map(nameOf),
2521
- // The sender's computer's key, to compare with them before joining (pinned only on joining).
2522
- fingerprint: invite.fingerprint ?? null,
2523
- kind: invite.project.repo?.first ? "project" : "room",
2524
- people: invite.project.members,
2525
- history: invite.project.history,
2526
- agreements: invite.project.agreements,
2527
- availableAgents:
2528
- invite.project.v === 2
2529
- ? agents().map((id) => ({
2530
- id,
2531
- name: nameOf(id),
2532
- }))
2533
- : undefined,
2534
- repo: {
2535
- name: invite.project.repo?.name ?? "",
2536
- remote: invite.project.repo?.remote ?? "",
2537
- },
2538
- here: invite.project.repo?.first
2539
- ? findCheckout(knownFolders(), invite.project.repo.first)
2540
- : null,
2541
- settings: SETTING_KEYS.filter(
2542
- (key) =>
2543
- invite.project.repo?.first ||
2544
- ![
2545
- "push",
2546
- "pullRequests",
2547
- "mergeChecks",
2548
- "mergeDecisions",
2549
- ].includes(key)
2550
- ).map((key) => ({
2551
- key,
2552
- label: SETTINGS[key].label,
2553
- value:
2554
- invite.project.settings?.[key] ?? SETTINGS[key].initial,
2555
- choices: SETTINGS[key].choices ?? null,
2556
- })),
2557
- })),
2558
- }))
2559
- );
2560
- if (name === "board.project.repos")
2561
- return {
2562
- ok: true,
2563
- repos: repos(),
2564
- availableAgents: agents().map((id) => ({ id, name: nameOf(id) })),
2565
- // What agents may do in a new project, as it starts, for the person to change before they invite.
2566
- settings: SETTING_KEYS.map((key) => ({
2567
- key,
2568
- label: SETTINGS[key].label,
2569
- value: SETTINGS[key].initial,
2570
- choices: SETTINGS[key].choices ?? null,
2571
- })),
2572
- };
2573
- if (name === "board.project.create")
2574
- return answeredWith(create(request).then((p) => ({ project: view(p) })));
2575
- if (name === "board.project.join")
2576
- return {
2577
- pending: join({
2578
- id: String(request.id || ""),
2579
- folder: request.folder,
2580
- clone: request.clone === true,
2581
- selectedAgents: request.selectedAgents,
2582
- }).catch((error) => ({ ok: false, error: error.message })),
2583
- };
2584
- if (name === "board.project.decline")
2585
- return answeredWith(
2586
- decideRequest(String(request.id || ""), "decline").then(() => ({}))
2587
- );
2588
- const p = projectFor(request);
2589
- if (!p) return { ok: false, error: "project not found" };
2590
- // A project that isn't open (waiting for the other person, declined, left) takes no new decisions, notes or settings.
2591
- if (OPEN_ONLY.has(name) && p.status !== "open")
2592
- return {
2593
- ok: false,
2594
- error:
2595
- p.status === "left" || p.status === "declined"
2596
- ? "This project has ended."
2597
- : `This waits until ${p.partner} joins.`,
2598
- };
2599
- try {
2600
- const piece = pieces.command(p, name, request, "user");
2601
- if (piece) return piece;
2602
- switch (name) {
2603
- case "board.project.retry":
2604
- return answeredWith(
2605
- channels
2606
- .retry(p.id, String(request.handle || ""))
2607
- .then(() => ({ project: view(project(p.id)) }))
2608
- );
2609
- case "board.project.goal": {
2610
- const statement = String(request.statement || "")
2611
- .trim()
2612
- .slice(0, 4000);
2613
- const criteria = [
2614
- ...new Set(
2615
- (Array.isArray(request.criteria) ? request.criteria : [])
2616
- .map(String)
2617
- .map((text) => text.trim().slice(0, 500))
2618
- .filter(Boolean)
2619
- ),
2620
- ].slice(0, 12);
2621
- if (!statement || !criteria.length)
2622
- throw new Error(
2623
- "Write the goal and at least one check that shows it is reached."
2624
- );
2625
- const text = `Shared goal: ${statement}\nDone when:\n${criteria.map((criterion) => `- ${criterion}`).join("\n")}`;
2626
- propose(
2627
- p,
2628
- {
2629
- type: "decision",
2630
- text,
2631
- goal: { statement, criteria },
2632
- needs: peopleOf(p),
2633
- },
2634
- "user"
2635
- );
2636
- return { ok: true };
2637
- }
2638
- case "board.project.invite":
2639
- return answeredWith(
2640
- channels
2641
- .invite(p.id, request.partners ?? [request.partner])
2642
- .then(() => ({ project: view(project(p.id)) }))
2643
- );
2644
- case "board.project.remove":
2645
- channels.remove(p.id, String(request.handle || ""));
2646
- return { ok: true, project: view(project(p.id)) };
2647
- case "board.project.agents": {
2648
- channels.setAgents(p.id, request.agents);
2649
- hello(p);
2650
- pieces.refresh(project(p.id));
2651
- return { ok: true, project: view(project(p.id)) };
2652
- }
2653
- case "board.project.read":
2654
- return answeredWith(
2655
- (async () => {
2656
- for (const work of items(p.id, "work").filter(
2657
- (entry) => entry.side === p.me
2658
- ))
2659
- await verdicts?.detect({ id: p.id, work: work.id });
2660
- return { project: view(project(p.id)) };
2661
- })()
2662
- );
2663
- case "board.project.answer":
2664
- return answer(
2665
- p,
2666
- String(request.proposal || ""),
2667
- request.yes === true
2668
- );
2669
- case "board.project.withdraw":
2670
- return withdraw(p, String(request.proposal || ""));
2671
- case "board.project.setting":
2672
- return setting(p, String(request.key || ""), request.value);
2673
- case "board.project.decide": {
2674
- const text = String(request.text || "").trim();
2675
- if (!text) return { ok: false, error: "write what you decide" };
2676
- propose(p, { type: "decision", text, needs: peopleOf(p) }, "user");
2677
- return { ok: true, project: view(project(p.id)) };
2678
- }
2679
- case "board.project.note": {
2680
- const text = String(request.text || "").trim();
2681
- if (!text) return { ok: false, error: "write the note" };
2682
- write(p, "note", {
2683
- text: text.slice(0, 2_000),
2684
- by: `${p.me}/person`,
2685
- });
2686
- return { ok: true };
2687
- }
2688
- case "board.project.share": {
2689
- const postId = String(request.post || "");
2690
- const row = all(
2691
- "select state from project_posts where post_id = ? and project_id = ?",
2692
- postId,
2693
- p.id
2694
- )[0];
2695
- if (row?.state !== "held")
2696
- return { ok: false, error: "that post isn't waiting" };
2697
- const post = store
2698
- .roomPosts(p.roomId, 0, 500)
2699
- .find((entry) => entry.id === postId);
2700
- if (!post) return { ok: false, error: "that post is gone" };
2701
- run(
2702
- "update project_posts set state = 'sent' where post_id = ?",
2703
- postId
2704
- );
2705
- sharePost(p, post);
2706
- return { ok: true };
2707
- }
2708
- case "board.project.held":
2709
- return {
2710
- ok: true,
2711
- posts: all(
2712
- "select post_id from project_posts where project_id = ? and state = 'held'",
2713
- p.id
2714
- )
2715
- .map((row) =>
2716
- store
2717
- .roomPosts(p.roomId, 0, 500)
2718
- .find((entry) => entry.id === row.post_id)
2719
- )
2720
- .filter(Boolean)
2721
- .map((post) => ({
2722
- id: post.id,
2723
- who: display(p, post.author),
2724
- text: post.text,
2725
- at: post.created_at,
2726
- })),
2727
- };
2728
- case "board.project.work":
2729
- return answeredWith(
2730
- workAction(
2731
- p,
2732
- String(request.work || ""),
2733
- String(request.action || "")
2734
- )
2735
- );
2736
- case "board.project.leave":
2737
- leave(p);
2738
- return { ok: true };
2739
- default:
2740
- return { ok: false, error: `unknown command ${name}` };
2741
- }
2742
- } catch (error) {
2743
- return { ok: false, error: error.message };
2744
- }
2745
- };
2746
-
2747
- const agentCommand = (name, request, agent) => {
2748
- const p = projectFor(request);
2749
- if (!p || p.status !== "open")
2750
- return { ok: false, error: "this thread is not an open shared project" };
2751
- if (!ownAgents(p).includes(agent))
2752
- return {
2753
- ok: false,
2754
- error: "This agent has not been selected for the shared room.",
2755
- };
2756
- const room = roomOf(p);
2757
- if (name === "board.project.read")
2758
- return { ok: true, record: brief(room, agent) };
2759
- if (name === "board.project.plan")
2760
- return answeredWith(plan(p, agent, request));
2761
- if (name === "board.project.propose")
2762
- try {
2763
- return agentPropose(p, agent, request);
2764
- } catch (error) {
2765
- return { ok: false, error: error.message };
2766
- }
2767
- try {
2768
- const piece = pieces.command(p, name, request, agent);
2769
- if (piece) return piece;
2770
- } catch (error) {
2771
- return { ok: false, error: error.message };
2772
- }
2773
- return { ok: false, error: `unknown command ${name}` };
2774
- };
2775
-
2776
- // The verdict module crosses this seam to read a local piece and publish its state through the existing sealed event.
2777
- const verdictContext = ({
2778
- id,
2779
- work: workId,
2780
- agent,
2781
- run: runId,
2782
- before = null,
2783
- }) => {
2784
- const p = projectFor({ id });
2785
- if (!p) return null;
2786
- const candidates = items(p.id, "work").filter(
2787
- (entry) =>
2788
- entry.side === p.me &&
2789
- entry.body.agent === agent &&
2790
- (!before || entry.at <= before)
2791
- );
2792
- const judged = runId
2793
- ? candidates.findLast((entry) => entry.body.returned?.run === runId)
2794
- : null;
2795
- const work = workId
2796
- ? item(workId)
2797
- : (judged ??
2798
- candidates.findLast((entry) =>
2799
- [...OPEN_WORK, "review"].includes(entry.body.status)
2800
- ));
2801
- if (!work || work.kind !== "work" || work.projectId !== p.id) return null;
2802
- return {
2803
- project: p,
2804
- work,
2805
- where: p.repo.first && work.side === p.me ? laneOf(p, work) : null,
2806
- update: (fields) => write(project(p.id), "work", fields, work.id),
2807
- };
2808
- };
2809
-
2810
- return {
2811
- verdictContext,
2812
- command,
2813
- receive,
2814
- delivered,
2815
- resend,
2816
- channelOpened,
2817
- channelEnded,
2818
- posted,
2819
- gate,
2820
- folderFor,
2821
- committed,
2822
- brief,
2823
- learned,
2824
- refresh,
2825
- isProjectRoom: (goalId) => Boolean(projectOfRoom(goalId)),
2826
- /** A project room's board, kept in the project's record so every computer in it shows the same cards. */
2827
- boardOf: (goalId) => {
2828
- const p = projectOfRoom(goalId);
2829
- if (!p) return null;
2830
- return {
2831
- load: () => board.load(project(p.id)),
2832
- save: (cards) => board.save(project(p.id), cards),
2833
- };
2834
- },
2835
- /**
2836
- * What a project's room waits on the person for, as the thread's needs-you items: an OK the other side or an agent
2837
- * asked for (agree), and an agent's post kept here until the person shares it (share).
2838
- */
2839
- needsOf: (goalId) => {
2840
- const p = projectOfRoom(goalId);
2841
- if (!p || p.status !== "open") return [];
2842
- const asks = items(p.id, "proposal")
2843
- .filter((proposal) => stateOf(p, proposal).waitingOn.includes(p.me))
2844
- .map((proposal) => ({
2845
- id: `agree:${proposal.id}`,
2846
- kind: "agree",
2847
- agent: local(p, proposal.body.by),
2848
- who: display(p, proposal.body.by),
2849
- text: proposal.body.text,
2850
- ...(proposal.body.decision
2851
- ? { decision: proposal.body.decision }
2852
- : {}),
2853
- projectId: p.id,
2854
- proposalId: proposal.id,
2855
- at: proposal.at,
2856
- }));
2857
- const held = all(
2858
- "select post_id from project_posts where project_id = ? and state = 'held'",
2859
- p.id
2860
- )
2861
- .map((row) =>
2862
- store
2863
- .roomPosts(goalId, 0, 500)
2864
- .find((post) => post.id === row.post_id)
2865
- )
2866
- .filter(Boolean)
2867
- .map((post) => ({
2868
- id: `share:${post.id}`,
2869
- kind: "share",
2870
- agent: post.author,
2871
- who: display(p, post.author),
2872
- text: `${display(p, post.author)}'s post waits for you to share it with ${p.partner}.`,
2873
- projectId: p.id,
2874
- postId: post.id,
2875
- seq: post.seq,
2876
- at: post.created_at,
2877
- }));
2878
- return [...asks, ...held];
2879
- },
2880
- addressesPartner: (goalId, text) => {
2881
- const p = projectOfRoom(goalId);
2882
- return Boolean(p) && partnerMentions(p, text).length > 0;
2883
- },
2884
- /** What a thread list says of a project's room: the project and who it is shared with. */
2885
- roomInfo: (goalId) => {
2886
- const p = projectOfRoom(goalId);
2887
- return p
2888
- ? {
2889
- id: p.id,
2890
- partner: peersOf(p).join(", ") || p.partner,
2891
- status: p.status,
2892
- }
2893
- : null;
2894
- },
2895
- /** Whether a relay thread is a project's channel, which Swarms does not list as a conversation. */
2896
- isChannel: (threadId) =>
2897
- Boolean(project(threadId) || channels.knowsChannel(threadId)),
2898
- // A post from the other side: its own swarm sorts it; this side's coordinator does not take a round on it.
2899
- /** The person blocked a handle: every project with them ends with them here (security audit P9). */
2900
- blocked: (handle) => {
2901
- for (const p of projects()) {
2902
- if (p.status === "left" || p.status === "declined") continue;
2903
- if (groupOf(p)) channels.block(p.id, handle);
2904
- else if (p.partner === handle) leave(p);
2905
- }
2906
- },
2907
- fromPartner: (goalId, post) => {
2908
- const p = projectOfRoom(goalId);
2909
- return Boolean(p) && isPeer(p, post.author);
2910
- },
2911
- stop: () => {
2912
- clearInterval(timer);
2913
- pieces.stop();
2914
- channels.stop();
2915
- },
2916
- };
2917
- }