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