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
@@ -0,0 +1,491 @@
1
+ import fs from "node:fs";
2
+ import path from "node:path";
3
+ import { nameOf } from "./members.mjs";
4
+ import { harnessHome } from "./paths.mjs";
5
+
6
+ // A thread's record (docs/senses-plan.md S3.7): what Harness did and noticed in a thread, a few plain words a line, for
7
+ // the person who opens it from the thread's ··· on the buddy or the phone. It is minimal on purpose: the person is not
8
+ // here for Harness's bookkeeping. What is on now comes first (an agent's waits, then the watches), then the latest
9
+ // things, newest first: a watch or a wait that woke an agent, an agent found stuck, an agent going in circles. It reads
10
+ // this computer's watches and log, which stay on it (events.mjs), so each computer shows what it read itself.
11
+ const MOST_LINES = 5;
12
+ // What got stuck or went in circles is looked for in the log's newest happenings of that source.
13
+ const STUCK_READ = 100;
14
+ // A command is named this long.
15
+ const COMMAND_CHARS = 40;
16
+ // What a turn used, counted against the watch that woke it.
17
+ const TOKEN_FIELDS = [
18
+ "input_tokens",
19
+ "output_tokens",
20
+ "cache_read_tokens",
21
+ "cache_write_tokens",
22
+ ];
23
+
24
+ const parsed = (text) => {
25
+ try {
26
+ return text ? JSON.parse(text) : null;
27
+ } catch {
28
+ return null;
29
+ }
30
+ };
31
+
32
+ /** A path by its last two parts: "build/done.txt". */
33
+ const shortPath = (file) =>
34
+ String(file ?? "")
35
+ .split(/[\\/]/)
36
+ .filter(Boolean)
37
+ .slice(-2)
38
+ .join("/");
39
+
40
+ const shortCommand = (command) => {
41
+ const line = String(command ?? "")
42
+ .split(/\s+/)
43
+ .join(" ")
44
+ .trim();
45
+ return line.length > COMMAND_CHARS
46
+ ? `${line.slice(0, COMMAND_CHARS - 1)}…`
47
+ : line;
48
+ };
49
+
50
+ const isFileCheck = (source) =>
51
+ source?.what === "file" || (!source?.what && Boolean(source?.file));
52
+
53
+ /** What a watch reads, in a few words. */
54
+ function thingOf(source) {
55
+ switch (source?.kind) {
56
+ case "check":
57
+ if (isFileCheck(source)) return shortPath(source.file);
58
+ return source.port ? `port ${source.port}` : String(source.address);
59
+ case "files":
60
+ return `the files in ${path.basename(String(source.folder ?? ""))}`;
61
+ case "process":
62
+ return `process ${source.pid}`;
63
+ case "command":
64
+ return shortCommand(source.command);
65
+ case "fact":
66
+ return `the fact ${source.key}`;
67
+ case "screen":
68
+ return String(source.spec?.intent ?? "the screen");
69
+ case "reach":
70
+ return source.from === "quotient"
71
+ ? `the odds of ${source.market}`
72
+ : source.from === "bankr"
73
+ ? `your wallet's ${source.holding ?? "total"}`
74
+ : `${new URL(String(source.address)).host}${source.field ? ` ${source.field}` : ""}`;
75
+ case "outside":
76
+ return "events at an outside address";
77
+ case "all":
78
+ return (source.of ?? [])
79
+ .map((part) => thingOf(part.source))
80
+ .join(" and ");
81
+ default:
82
+ return "the clock";
83
+ }
84
+ }
85
+
86
+ // Where a watch is read, said beside it in the record (owner, November 15, the compact line): the person's screen,
87
+ // a source outside, or their computer.
88
+ const QUOTIENT_LOOK_USD = 0.005;
89
+ function whereOf(source) {
90
+ switch (source?.kind) {
91
+ case "screen":
92
+ return "your screen";
93
+ case "reach":
94
+ return source.from === "quotient"
95
+ ? `Quotient · $${QUOTIENT_LOOK_USD} a look`
96
+ : source.from === "bankr"
97
+ ? "your Bankr wallet"
98
+ : "from outside";
99
+ case "outside":
100
+ return "from outside";
101
+ case "all":
102
+ return [
103
+ ...new Set((source.of ?? []).map((part) => whereOf(part.source))),
104
+ ].join(" and ");
105
+ default:
106
+ return "your computer";
107
+ }
108
+ }
109
+ // Words start with a capital; a path or an address stays as it is written.
110
+ const capital = (text) =>
111
+ /^[a-z]+ /.test(text) ? text.charAt(0).toUpperCase() + text.slice(1) : text;
112
+
113
+ /** What happened when a watch answered on `edge`, in a few words: "build/done.txt appeared". */
114
+ function happenedOf(source, condition, edge, wait) {
115
+ if (edge === "timeout") return "its wait ran out";
116
+ if (edge === "blind") return `${thingOf(source)} could not be read`;
117
+ if (wait?.timer || source?.kind === "clock") return "its time came";
118
+ const thing = thingOf(source);
119
+ if (source?.kind === "check") {
120
+ const there = Boolean(condition?.value) !== (edge === "cleared");
121
+ if (isFileCheck(source))
122
+ return there ? `${thing} appeared` : `${thing} went away`;
123
+ return there ? `${thing} answered` : `${thing} stopped answering`;
124
+ }
125
+ if (source?.kind === "process") return `${thing} ended`;
126
+ if (condition?.when === "off" && edge !== "cleared")
127
+ return `${thing} went off its limits`;
128
+ return `${thing} changed`;
129
+ }
130
+
131
+ /** The time a wait ends, as this computer says a time: "10:42 AM". */
132
+ const clockOf = (iso) =>
133
+ new Date(iso).toLocaleTimeString(undefined, {
134
+ hour: "numeric",
135
+ minute: "2-digit",
136
+ });
137
+
138
+ const endOf = (source, wait) =>
139
+ wait?.timer || !source || source.kind === "clock"
140
+ ? (wait?.timer ? wait.endsAt : source?.at) || wait?.endsAt
141
+ : null;
142
+
143
+ /** What got stuck, as found: "Hermes was stuck". */
144
+ const stuckText = (data) =>
145
+ data?.what === "unanswered"
146
+ ? `A question waited for ${data.agent === "user" ? "you" : nameOf(data.agent)}`
147
+ : `${nameOf(data?.agent)} was stuck`;
148
+
149
+ /** Going in circles, as found (circling.mjs): "Codex repeated a command". */
150
+ const circlingText = (data) =>
151
+ data?.what === "file"
152
+ ? `${nameOf(data.agent)} went back and forth on ${data.file}`
153
+ : `${nameOf(data?.agent)} repeated a command`;
154
+
155
+ const tokensOf = (usage) => {
156
+ const figures = parsed(usage) ?? {};
157
+ return TOKEN_FIELDS.reduce(
158
+ (sum, field) => sum + (Number(figures[field]) || 0),
159
+ 0
160
+ );
161
+ };
162
+
163
+ /**
164
+ * The record of each thread on this computer: `of(thread)` its lines, `waitingLine(thread, agent, since)` what a
165
+ * turn that ended on a wait says when its agent wrote nothing, and `spentOf(watch)` what a watch has cost.
166
+ */
167
+ export function createThreadRecord({
168
+ store,
169
+ events,
170
+ // The person's computers whose link with this one is broken now (nerves.mjs status): `{ id, label, cutSince }`.
171
+ cuts = () => [],
172
+ // This computer, when it is a worker: a broken link with home touches every thread with work here.
173
+ worker = () => null,
174
+ home = harnessHome,
175
+ }) {
176
+ const { db } = store;
177
+
178
+ // The sessions that worked in this thread: its runs' and wakes' own.
179
+ const sessionsOf = (thread) =>
180
+ new Set(
181
+ db
182
+ .all(
183
+ "select session_id from board_tasks where parent_id = ? and session_id is not null",
184
+ [thread]
185
+ )
186
+ .map((row) => String(row.session_id))
187
+ );
188
+
189
+ /** Where an agent working here pointed the person (senseTools.mjs ask to the person), newest first. */
190
+ const pointed = (thread) => {
191
+ const sessions = sessionsOf(thread);
192
+ if (!sessions.size) return [];
193
+ const folder = path.join(home, "senses", "pointers");
194
+ let names = [];
195
+ try {
196
+ names = fs.readdirSync(folder).filter((name) => name.endsWith(".json"));
197
+ } catch {
198
+ return [];
199
+ }
200
+ return names
201
+ .map((name) => parsed(fs.readFileSync(path.join(folder, name), "utf8")))
202
+ .filter((pointer) => pointer && sessions.has(String(pointer.session)))
203
+ .map((pointer) => {
204
+ const where = pointer.url
205
+ ? new URL(pointer.url).host + new URL(pointer.url).pathname
206
+ : `${shortPath(pointer.file)}${pointer.line ? `:${pointer.line}` : ""}`;
207
+ const why = pointer.why
208
+ ? `: “${pointer.why.length > 60 ? `${pointer.why.slice(0, 59).trimEnd()}…` : pointer.why}”`
209
+ : "";
210
+ return {
211
+ text: `${pointer.by} points you at ${where}${why}`,
212
+ at: pointer.at,
213
+ };
214
+ });
215
+ };
216
+
217
+ /** What a reflex did here (reflexes.mjs) and who let it go, newest first. */
218
+ const reflexed = (thread) =>
219
+ db
220
+ .all(
221
+ "select id, response, outcome, done_at, at from board_watch_fires where thread = ? and watch like 'reflex:%' and state = 'done' order by id desc limit ?",
222
+ [thread, MOST_LINES]
223
+ )
224
+ .flatMap((fire) => {
225
+ const response = parsed(fire.response) ?? {};
226
+ const did =
227
+ response.do === "pause"
228
+ ? `Harness paused ${shortCommand(response.command)}: ${response.why}`
229
+ : response.do === "hold"
230
+ ? `Harness held the agents here: ${response.why}`
231
+ : null;
232
+ if (!did) return [];
233
+ const released = parsed(store.meta(`reflex-release:${fire.id}`));
234
+ return [
235
+ { text: did, at: fire.done_at || fire.at },
236
+ ...(released
237
+ ? [
238
+ {
239
+ text:
240
+ released.by === "harness"
241
+ ? `It let go by itself${released.reason ? `: ${released.reason}` : ""}`
242
+ : `${released.by === "user" ? "You" : nameOf(released.by)} let it go${released.reason ? `: “${released.reason.length > 50 ? `${released.reason.slice(0, 49).trimEnd()}…` : released.reason}”` : ""}`,
243
+ at: released.at,
244
+ },
245
+ ]
246
+ : []),
247
+ ];
248
+ });
249
+
250
+ /** A report here whose claim did not hold against the record (audit.mjs), in a few words. */
251
+ const unheld = (thread) =>
252
+ db
253
+ .all(
254
+ "select target_agent, audit, reported_at, updated_at from board_tasks where parent_id = ? and audit is not null order by updated_at desc limit ?",
255
+ [thread, MOST_LINES]
256
+ )
257
+ .flatMap((task) => {
258
+ const audit = parsed(task.audit);
259
+ if (!audit || audit.ok !== false) return [];
260
+ const who = nameOf(task.target_agent);
261
+ return (audit.mismatches ?? [])
262
+ .filter((found) => found.against === "agent")
263
+ .map((found) => ({
264
+ text:
265
+ found.kind === "tests_failing"
266
+ ? `${who} said the tests pass; ${/`([^`]+)`/.exec(found.detail)?.[1] ?? "its last test"} failed after its last change`
267
+ : found.kind === "tests_not_recorded"
268
+ ? `${who} said the tests pass; no passing test after its change is on record`
269
+ : `${who}'s report did not hold: ${found.detail}`,
270
+ at: audit.at ?? task.reported_at ?? task.updated_at,
271
+ }));
272
+ });
273
+
274
+ /** An agent's waits, then the watches, on now. */
275
+ const onNow = (thread) => {
276
+ const rows = db.all(
277
+ "select id, armed_by, source, detail from board_watches where thread = ? and state = 'on' and kind != 'check-in' order by created_at desc",
278
+ [thread]
279
+ );
280
+ // Whether a watch can read now, as the computer that reads it last said (threadWatches.mjs keeps its state).
281
+ const blind = (id) => {
282
+ try {
283
+ return (
284
+ JSON.parse(
285
+ db.get("select value from board_meta where key = ?", [
286
+ `watch-state:${id}`,
287
+ ])?.value || "null"
288
+ )?.blind === true
289
+ );
290
+ } catch {
291
+ return false;
292
+ }
293
+ };
294
+ const waits = [];
295
+ const watching = [];
296
+ for (const row of rows) {
297
+ const source = parsed(row.source);
298
+ const wait = parsed(row.detail)?.wait;
299
+ if (!wait) {
300
+ const off = blind(row.id);
301
+ watching.push({
302
+ text: `${capital(thingOf(source))}${off ? " · can't see it" : ""}`,
303
+ at: null,
304
+ where:
305
+ off && source?.kind === "screen"
306
+ ? "share the tab again"
307
+ : whereOf(source),
308
+ ...(off ? { off: true } : {}),
309
+ });
310
+ continue;
311
+ }
312
+ const who = nameOf(row.armed_by);
313
+ const until = endOf(source, wait);
314
+ waits.push(
315
+ until
316
+ ? { text: `${who} waits`, at: null, until }
317
+ : { text: `${who} waits for ${thingOf(source)}`, at: null }
318
+ );
319
+ }
320
+ return [...waits, ...watching];
321
+ };
322
+
323
+ /** The watches and waits that woke an agent here (watchResponses.mjs), newest first. */
324
+ const wakes = (thread) =>
325
+ db
326
+ .all(
327
+ `select f.edge, f.response, f.outcome, f.at, f.done_at, w.source, w.condition, w.detail
328
+ from board_watch_fires f left join board_watches w on w.id = f.watch
329
+ where f.thread = ? and f.state = 'done' and f.outcome like 'woke %' and coalesce(w.kind, '') != 'check-in'
330
+ order by f.id desc limit ?`,
331
+ [thread, MOST_LINES]
332
+ )
333
+ .map((fire) => {
334
+ const response = parsed(fire.response) ?? {};
335
+ // Who it woke, as the fire recorded it ("woke codex, claude-code, one wake for 2"): attention may have handed
336
+ // the wake to another agent of the thread than the watch names (S9.1).
337
+ const woke = String(fire.outcome)
338
+ .replace(/^woke /, "")
339
+ .split(", one wake for")[0]
340
+ .split(", ")
341
+ .filter((agent) => agent && agent !== "the lead");
342
+ const named = woke.length
343
+ ? woke
344
+ : (response.agents ?? (response.agent ? [response.agent] : []));
345
+ const who = named.map(nameOf).join(" and ") || "An agent";
346
+ const happened = happenedOf(
347
+ parsed(fire.source),
348
+ parsed(fire.condition),
349
+ fire.edge,
350
+ parsed(fire.detail)?.wait
351
+ );
352
+ return {
353
+ text: `${who} woke: ${happened}`,
354
+ at: fire.done_at || fire.at,
355
+ };
356
+ });
357
+
358
+ /** A wake another of the person's computers carried out here (nerves.mjs), as a wake here is said. */
359
+ const wokeElsewhere = (thread) =>
360
+ events
361
+ .read({ sources: ["watch-response"], limit: STUCK_READ })
362
+ .filter(
363
+ (happening) =>
364
+ happening.machine &&
365
+ happening.kind === "answered" &&
366
+ happening.data?.thread === thread &&
367
+ / woke /.test(` ${happening.text}`)
368
+ )
369
+ .flatMap((happening) => {
370
+ const watch = db.get(
371
+ "select kind, source, condition, detail, response from board_watches where id = ?",
372
+ [happening.subject]
373
+ );
374
+ if (!watch || watch.kind === "check-in") return [];
375
+ const response = parsed(watch.response) ?? {};
376
+ const named =
377
+ response.agents ?? (response.agent ? [response.agent] : []);
378
+ const who = named.map(nameOf).join(" and ") || "An agent";
379
+ return [
380
+ {
381
+ text: `${who} woke: ${happenedOf(
382
+ parsed(watch.source),
383
+ parsed(watch.condition),
384
+ happening.data?.edge,
385
+ parsed(watch.detail)?.wait
386
+ )}`,
387
+ at: happening.at,
388
+ },
389
+ ];
390
+ });
391
+
392
+ /** A broken link with a computer that has work in this thread, or with home for work here: one line each. */
393
+ const cutLines = (thread) =>
394
+ cuts().flatMap((cut) => {
395
+ const machines = new Set(
396
+ db
397
+ .all(
398
+ "select coalesce(claimed_machine, target_machine) as machine from board_tasks where parent_id = ?",
399
+ [thread]
400
+ )
401
+ .map((row) => row.machine)
402
+ );
403
+ const here = worker();
404
+ if (!machines.has(cut.id) && !(here && machines.has(here))) return [];
405
+ return [
406
+ {
407
+ text: `The link with ${cut.label || "another computer"} broke; each keeps working on its own`,
408
+ at: cut.cutSince,
409
+ },
410
+ ];
411
+ });
412
+
413
+ /** Who was found stuck here and who went in circles (stuck.mjs, circling.mjs). */
414
+ const stuck = (thread) =>
415
+ events
416
+ .read({ sources: ["stuck"], limit: STUCK_READ })
417
+ .filter((happening) => happening.data?.thread === thread)
418
+ .flatMap((happening) =>
419
+ happening.kind === "found"
420
+ ? [{ text: stuckText(happening.data), at: happening.at }]
421
+ : happening.kind === "circling"
422
+ ? [{ text: circlingText(happening.data), at: happening.at }]
423
+ : []
424
+ );
425
+
426
+ return {
427
+ /**
428
+ * At most five lines, each `{ text, at }`: `at` (ISO) when it happened, null for what is on now; a wait that ends
429
+ * at a time has `until` (ISO), for the reader to say in its own time ("Codex waits until 10:42").
430
+ */
431
+ of(thread) {
432
+ const past = [
433
+ ...cutLines(thread),
434
+ ...wakes(thread),
435
+ ...wokeElsewhere(thread),
436
+ ...stuck(thread),
437
+ ...pointed(thread),
438
+ ...unheld(thread),
439
+ ...reflexed(thread),
440
+ ].sort((a, b) => b.at.localeCompare(a.at));
441
+ return [...onNow(thread), ...past].slice(0, MOST_LINES);
442
+ },
443
+ /** The wait `agent` set in `thread` since `since` (ISO), in words for the turn's end, or null. */
444
+ waitingLine(thread, agent, since) {
445
+ const row = db.get(
446
+ "select source, detail from board_watches where thread = ? and armed_by = ? and state in ('on', 'held') and detail is not null and created_at >= ? order by created_at desc limit 1",
447
+ [thread, agent, since]
448
+ );
449
+ const wait = parsed(row?.detail)?.wait;
450
+ if (!wait) return null;
451
+ const source = parsed(row.source);
452
+ const until = endOf(source, wait);
453
+ return until
454
+ ? `Waiting until ${clockOf(until)}.`
455
+ : `Waiting for ${thingOf(source)}.`;
456
+ },
457
+ /**
458
+ * What a watch has cost (docs/senses-plan.md, row 10): how often it fired, the turns it woke (each wake whose
459
+ * reason names one of its fires, threadRuns.mjs) and the tokens those turns used.
460
+ */
461
+ spentOf(watch) {
462
+ const fires = db.all(
463
+ "select cause from board_watch_fires where watch = ?",
464
+ [watch]
465
+ );
466
+ const causes = new Set(
467
+ fires
468
+ .map((fire) => fire.cause)
469
+ .filter((cause) => cause !== null && cause !== undefined)
470
+ .map(Number)
471
+ );
472
+ const thread = db.get("select thread from board_watches where id = ?", [
473
+ watch,
474
+ ])?.thread;
475
+ let woke = 0;
476
+ let tokens = 0;
477
+ if (thread && causes.size)
478
+ for (const turn of db.all(
479
+ "select id, usage from board_tasks where parent_id = ? and kind = 'wake'",
480
+ [thread]
481
+ )) {
482
+ const reason = parsed(store.meta(`wake-reason:${turn.id}`));
483
+ if (!reason?.causes?.some((cause) => causes.has(Number(cause))))
484
+ continue;
485
+ woke++;
486
+ tokens += tokensOf(turn.usage);
487
+ }
488
+ return { fired: fires.length, woke, tokens };
489
+ },
490
+ };
491
+ }