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/record.mjs CHANGED
@@ -72,6 +72,19 @@ function judgmentOf(run, verdict) {
72
72
  return null;
73
73
  }
74
74
 
75
+ /**
76
+ * Every routed run that was judged, oldest first, with how: { run, judged } where judged is "accepted" or "rejected"
77
+ * (eval agent-record replays the record as it stood before each, S9.3).
78
+ */
79
+ export function judgedRuns(store) {
80
+ const verdicts = verdictsByRun(store);
81
+ return store
82
+ .routedRuns()
83
+ .map((run) => ({ run, judged: judgmentOf(run, verdicts.get(run.id)) }))
84
+ .filter((entry) => entry.judged)
85
+ .sort((a, b) => a.run.reported_at.localeCompare(b.run.reported_at));
86
+ }
87
+
75
88
  /** Every agent's record: agent -> model -> specialty -> { accepted, rejected, judged }. */
76
89
  function records(store) {
77
90
  const verdicts = verdictsByRun(store);
@@ -0,0 +1,392 @@
1
+ import { execFileSync } from "node:child_process";
2
+ import fs from "node:fs";
3
+ import path from "node:path";
4
+ import { harnessHome } from "./paths.mjs";
5
+ import {
6
+ dropHold,
7
+ putHold,
8
+ sessionOfPid,
9
+ sessionsAtWork,
10
+ versionsOf,
11
+ } from "./senseCall.mjs";
12
+ import { PARENT, SENSE, putSteer } from "./steerQueue.mjs";
13
+
14
+ // Reflexes (docs/senses-plan.md S5): the body protecting itself in code, with no model. Each is armed by the system,
15
+ // never by an agent or the person, and acts through the response table's protective responses (watchResponses.mjs):
16
+ // hold an agent's next calls, pause a process, save a copy. What a reflex does is written down before it is done and
17
+ // done once; it leaves a record with its cause, the agent hears what was done while it worked, and the thread's record
18
+ // shows it. A reflex never deletes, sends, spends or starts work, and never stops anything in the middle of a step:
19
+ // a hold waits for the agent's next call, a pause suspends a process (SIGSTOP) that resumes as it was (SIGCONT).
20
+ // Anyone may let one go with a reason, which is kept (owner, November 13: the person always; an agent with a reason).
21
+ //
22
+ // The reflexes:
23
+ // - ceiling: a thread that has spent all its ceiling allows holds the calls of its agents at work; raising the
24
+ // ceiling lets them go.
25
+ // - runaway: the computer critical on memory, disk or heat for RUNAWAY_MS pauses the busiest long-running process an
26
+ // agent started; it resumes when the level clears.
27
+
28
+ // How long the computer stays critical before a runaway process is paused. A starting value, not measured yet: the
29
+ // levels already clear only past where they set (machine.mjs), so a passing spike does not reach it.
30
+ export const RUNAWAY_MS = 2 * 60_000;
31
+ // A process younger than this is the agent's own step under way, never paused.
32
+ const SETTLED_MS = 60_000;
33
+ const ACTIVE_KEY = "reflexes-active";
34
+ const CRITICAL = {
35
+ disk: (level) => level === "critical",
36
+ memory: (level) => level === "critical",
37
+ heat: (level) => level === "critical",
38
+ };
39
+
40
+ const elapsedMs = (etime) => {
41
+ // ps etime: [[dd-]hh:]mm:ss
42
+ const match = /^(?:(\d+)-)?(?:(\d+):)?(\d+):(\d+)$/.exec(
43
+ String(etime).trim()
44
+ );
45
+ if (!match) return 0;
46
+ const [, days = 0, hours = 0, minutes, seconds] = match.map((part) =>
47
+ Number(part ?? 0)
48
+ );
49
+ return (((days * 24 + hours) * 60 + minutes) * 60 + seconds) * 1000;
50
+ };
51
+
52
+ /** Every process here: `{ pid, ppid, ageMs, rss, cpu, command }`. */
53
+ function processes() {
54
+ let text = "";
55
+ try {
56
+ text = execFileSync(
57
+ "/bin/ps",
58
+ ["-A", "-o", "pid=,ppid=,etime=,rss=,%cpu=,command="],
59
+ { encoding: "utf8", timeout: 3_000, maxBuffer: 16 << 20 }
60
+ );
61
+ } catch {
62
+ return [];
63
+ }
64
+ return text
65
+ .split("\n")
66
+ .map((line) =>
67
+ /^\s*(\d+)\s+(\d+)\s+(\S+)\s+(\d+)\s+([\d.]+)\s+(.*)$/.exec(line)
68
+ )
69
+ .filter(Boolean)
70
+ .map((match) => ({
71
+ pid: Number(match[1]),
72
+ ppid: Number(match[2]),
73
+ ageMs: elapsedMs(match[3]),
74
+ rss: Number(match[4]),
75
+ cpu: Number(match[5]),
76
+ command: match[6].trim(),
77
+ }));
78
+ }
79
+
80
+ /**
81
+ * `responses` is the response table (its `fire`); `events` the log (followed); `sessionsOfThread(thread)` the sessions of
82
+ * a thread's runs; `nameOf(agent)`. `protect(response, fire)` is what the table calls to carry out a protective response.
83
+ */
84
+ export function createReflexes({
85
+ responses = null,
86
+ events,
87
+ store,
88
+ sessionsOfThread = () => [],
89
+ // The thread a session works for, so a pause shows in that thread's record; null for one of no thread.
90
+ threadOfSession = () => null,
91
+ nameOf = (agent) => agent,
92
+ home = harnessHome,
93
+ listProcesses = processes,
94
+ signal = (pid, name) => process.kill(pid, name),
95
+ runawayMs = RUNAWAY_MS,
96
+ settledMs = SETTLED_MS,
97
+ now = () => Date.now(),
98
+ log = () => {},
99
+ }) {
100
+ let table = responses;
101
+ let stopFollowing = null;
102
+ const critical = new Map();
103
+ const versions = versionsOf(home);
104
+
105
+ // What is held or paused now, kept across a restart so it can still be let go: fire id -> what it did.
106
+ const active = () => {
107
+ try {
108
+ return JSON.parse(store.meta(ACTIVE_KEY) || "{}");
109
+ } catch {
110
+ return {};
111
+ }
112
+ };
113
+ const keepActive = (value) => store.meta(ACTIVE_KEY, JSON.stringify(value));
114
+
115
+ const tell = (session, text) =>
116
+ putSteer({ session, agent: PARENT, kind: SENSE, text }, home);
117
+
118
+ /** Carries out a protective response for the table: what it did, or null. */
119
+ const protect = (response, fire) => {
120
+ const id = String(fire.id);
121
+ if (response.do === "hold") {
122
+ const sessions = (response.sessions ?? []).filter(Boolean);
123
+ for (const session of sessions)
124
+ putHold(session, { id, why: response.why, at: fire.at }, home);
125
+ if (!sessions.length) return null;
126
+ keepActive({
127
+ ...active(),
128
+ [id]: {
129
+ kind: "hold",
130
+ reflex: response.reflex,
131
+ sessions,
132
+ why: response.why,
133
+ thread: fire.thread,
134
+ at: fire.at,
135
+ },
136
+ });
137
+ return `held ${sessions.length} session${sessions.length === 1 ? "" : "s"}: ${response.why}`;
138
+ }
139
+ if (response.do === "pause") {
140
+ try {
141
+ signal(response.pid, "SIGSTOP");
142
+ } catch (error) {
143
+ log(`reflex: could not pause ${response.pid}: ${error.message}`);
144
+ return null;
145
+ }
146
+ keepActive({
147
+ ...active(),
148
+ [id]: {
149
+ kind: "pause",
150
+ reflex: response.reflex,
151
+ pid: response.pid,
152
+ command: response.command,
153
+ session: response.session ?? null,
154
+ why: response.why,
155
+ thread: fire.thread,
156
+ at: fire.at,
157
+ },
158
+ });
159
+ if (response.session)
160
+ tell(
161
+ response.session,
162
+ `While you worked, Harness paused \`${response.command}\` (process ${response.pid}): ${response.why}. It resumes when that clears; to resume it now, give a reason with look {release: "${id}", reason}.`
163
+ );
164
+ return `paused \`${response.command}\` (process ${response.pid}): ${response.why}`;
165
+ }
166
+ if (response.do === "save") {
167
+ const kept = (response.files ?? [])
168
+ .map((file) => ({ file, id: versions.keep(file) }))
169
+ .filter((each) => each.id);
170
+ return kept.length
171
+ ? `kept ${kept.map((each) => `${path.basename(each.file)} (${each.id.slice(0, 12)})`).join(", ")}`
172
+ : null;
173
+ }
174
+ return null;
175
+ };
176
+
177
+ // A reflex acts through the table, written down first.
178
+ const fire = ({ reflex, key, thread = null, response, text, cause = null }) =>
179
+ table?.fire({
180
+ watch: {
181
+ id: `reflex:${reflex}:${key}`,
182
+ thread,
183
+ response: { ...response, reflex },
184
+ reflex: true,
185
+ },
186
+ edge: "tripped",
187
+ text,
188
+ cause,
189
+ own: false,
190
+ }) ?? null;
191
+
192
+ /** Lets a held or paused reflex go: `by` the person ("user"), an agent with a reason, or Harness as its cause cleared. */
193
+ const release = (fireId, { by, reason }) => {
194
+ const id = String(fireId);
195
+ const all = active();
196
+ const what = all[id];
197
+ if (!what)
198
+ return { ok: false, error: `nothing named ${id} is held or paused now` };
199
+ const words = String(reason ?? "").trim();
200
+ if (by !== "user" && by !== "harness" && !words)
201
+ return {
202
+ ok: false,
203
+ error: "say why you let it go: release needs a reason",
204
+ };
205
+ if (what.kind === "hold")
206
+ for (const session of what.sessions) dropHold(session, home);
207
+ if (what.kind === "pause")
208
+ try {
209
+ signal(what.pid, "SIGCONT");
210
+ } catch {}
211
+ delete all[id];
212
+ keepActive(all);
213
+ // The reason is kept with the reflex; the log says who let it go, never their words.
214
+ store.meta(
215
+ `reflex-release:${id}`,
216
+ JSON.stringify({
217
+ by,
218
+ reason: words || null,
219
+ at: new Date(now()).toISOString(),
220
+ })
221
+ );
222
+ events.append({
223
+ source: "reflex",
224
+ kind: "released",
225
+ subject: `fire:${id}`,
226
+ text: `${by === "harness" ? "Harness" : nameOf(by)} let go of a ${what.kind} (${what.reflex})${words ? ", with a reason" : ""}`,
227
+ data: {
228
+ fire: Number(id),
229
+ kind: what.kind,
230
+ reflex: what.reflex,
231
+ thread: what.thread ?? null,
232
+ by,
233
+ },
234
+ });
235
+ const sessions =
236
+ what.kind === "hold" ? what.sessions : what.session ? [what.session] : [];
237
+ for (const session of sessions)
238
+ tell(
239
+ session,
240
+ what.kind === "hold"
241
+ ? `Harness no longer holds your calls${by === "harness" ? `: ${words}` : ""}.`
242
+ : `\`${what.command}\` (process ${what.pid}) runs again${by === "harness" ? `: ${words}` : ""}.`
243
+ );
244
+ return { ok: true, released: id };
245
+ };
246
+
247
+ // --- the ceiling reflex ---
248
+
249
+ const onLimit = (happening) => {
250
+ const subject = String(happening.subject ?? "");
251
+ if (!subject.startsWith("limits.spend.")) return;
252
+ const thread = subject.slice("limits.spend.".length);
253
+ const held = Object.entries(active()).filter(
254
+ ([, what]) => what.reflex === "ceiling" && what.thread === thread
255
+ );
256
+ if (happening.data?.level === "reached") {
257
+ if (held.length) return;
258
+ const working = new Set(
259
+ sessionsAtWork(30 * 60_000, home, now()).map((each) => each.session)
260
+ );
261
+ const sessions = sessionsOfThread(thread)
262
+ .map(String)
263
+ .filter((session) => working.has(session));
264
+ if (!sessions.length) return;
265
+ fire({
266
+ reflex: "ceiling",
267
+ key: thread,
268
+ thread,
269
+ response: {
270
+ do: "hold",
271
+ sessions,
272
+ why: `this thread has spent all it may (${happening.text})`,
273
+ },
274
+ text: `held the thread's agents at work: ${happening.text}`,
275
+ cause: happening.seq,
276
+ });
277
+ } else
278
+ for (const [id] of held)
279
+ release(id, {
280
+ by: "harness",
281
+ reason: "the thread's ceiling allows more again",
282
+ });
283
+ };
284
+
285
+ // --- the runaway reflex ---
286
+
287
+ // The busiest settled process an agent started: in the tree of an agent's process (its hooks name it), not the agent
288
+ // itself, older than a step.
289
+ const runaway = (aspect) => {
290
+ const all = listProcesses();
291
+ const children = new Map();
292
+ for (const each of all)
293
+ children.set(each.ppid, [...(children.get(each.ppid) ?? []), each]);
294
+ const agentPids = (() => {
295
+ try {
296
+ return fs
297
+ .readdirSync(path.join(home, "senses", "pids"))
298
+ .filter((name) => /^\d+$/.test(name))
299
+ .map(Number);
300
+ } catch {
301
+ return [];
302
+ }
303
+ })();
304
+ const found = [];
305
+ const climb = (pid, agentPid) => {
306
+ for (const child of children.get(pid) ?? []) {
307
+ found.push({ ...child, agentPid });
308
+ climb(child.pid, agentPid);
309
+ }
310
+ };
311
+ for (const agentPid of agentPids) climb(agentPid, agentPid);
312
+ const paused = new Set(
313
+ Object.values(active())
314
+ .filter((what) => what.kind === "pause")
315
+ .map((what) => what.pid)
316
+ );
317
+ const settled = found.filter(
318
+ (each) =>
319
+ each.ageMs >= settledMs &&
320
+ !paused.has(each.pid) &&
321
+ !/senseHook\.mjs|\bps\b|\blsof\b/.test(each.command)
322
+ );
323
+ const weight =
324
+ aspect === "memory" ? (each) => each.rss : (each) => each.cpu;
325
+ return settled.sort((a, b) => weight(b) - weight(a))[0] ?? null;
326
+ };
327
+
328
+ const onMachine = (happening) => {
329
+ const aspect = String(happening.subject ?? "");
330
+ if (!CRITICAL[aspect]) return;
331
+ if (CRITICAL[aspect](happening.data?.level)) {
332
+ if (critical.has(aspect)) return;
333
+ const timer = setTimeout(() => {
334
+ critical.get(aspect).fired = true;
335
+ const target = runaway(aspect);
336
+ if (!target) return;
337
+ const session = sessionOfPid(target.agentPid, home);
338
+ fire({
339
+ reflex: "runaway",
340
+ key: `${aspect}:${target.pid}`,
341
+ thread: session ? threadOfSession(session) : null,
342
+ response: {
343
+ do: "pause",
344
+ pid: target.pid,
345
+ command: target.command.slice(0, 80),
346
+ session,
347
+ why: happening.text,
348
+ },
349
+ text: `paused a process an agent started: ${happening.text}`,
350
+ cause: happening.seq,
351
+ });
352
+ }, runawayMs);
353
+ timer.unref?.();
354
+ critical.set(aspect, { timer, fired: false });
355
+ } else {
356
+ const was = critical.get(aspect);
357
+ if (!was) return;
358
+ clearTimeout(was.timer);
359
+ critical.delete(aspect);
360
+ for (const [id, what] of Object.entries(active()))
361
+ if (what.reflex === "runaway")
362
+ release(id, { by: "harness", reason: happening.text });
363
+ }
364
+ };
365
+
366
+ return {
367
+ protect,
368
+ release,
369
+ /** What is held or paused now, newest first. */
370
+ active: () =>
371
+ Object.entries(active())
372
+ .map(([id, what]) => ({ id, ...what }))
373
+ .sort((a, b) => String(b.at).localeCompare(String(a.at))),
374
+ /** The response table, once it is made (it calls protect). */
375
+ useTable(given) {
376
+ table = given;
377
+ },
378
+ start() {
379
+ stopFollowing ??= events.follow((happening) => {
380
+ if (happening.kind !== "level") return;
381
+ if (happening.source === "limits") onLimit(happening);
382
+ if (happening.source === "machine") onMachine(happening);
383
+ });
384
+ },
385
+ stop() {
386
+ stopFollowing?.();
387
+ stopFollowing = null;
388
+ for (const { timer } of critical.values()) clearTimeout(timer);
389
+ critical.clear();
390
+ },
391
+ };
392
+ }
@@ -1,7 +1,7 @@
1
1
  // What one other person's computer may leave on this one through threads with them (security audit P8, October 25:
2
2
  // nothing bounded it, and a file can be 45 MB). Past a limit a message or file is refused; Harness keeps it for a few
3
- // tries, then sets it aside and tells the sender it was not taken. A shared project's own record and posts have their
4
- // limits in projects.mjs.
3
+ // tries, then sets it aside and tells the sender it was not taken. A jam's own record and posts have their
4
+ // limits in jams.mjs.
5
5
  //
6
6
  // For owner review: a busy thread is a few hundred messages of at most 50,000 characters each, and files are counted
7
7
  // by the bytes that arrived.
@@ -18,6 +18,35 @@ export const RELAY_LIMITS = {
18
18
  personBytes: 1024 * MB,
19
19
  };
20
20
 
21
+ // Messages and files a minute from one other person, across every thread with them (owner, November 12: Harness's own
22
+ // rate for thread requests, 120 a minute, on top of the totals above).
23
+ export const PER_MINUTE = 120;
24
+ const MINUTE_MS = 60_000;
25
+
26
+ /**
27
+ * How many messages and files one person sent in the last minute: `take(handle)` counts one and says whether it is
28
+ * within PER_MINUTE. Kept in memory: a restart starts the count again.
29
+ */
30
+ export function createPerMinute({
31
+ limit = PER_MINUTE,
32
+ now = () => Date.now(),
33
+ } = {}) {
34
+ const sent = new Map();
35
+ return {
36
+ take(handle) {
37
+ const since = now() - MINUTE_MS;
38
+ const recent = (sent.get(handle) ?? []).filter((at) => at > since);
39
+ if (recent.length >= limit) {
40
+ sent.set(handle, recent);
41
+ return false;
42
+ }
43
+ recent.push(now());
44
+ sent.set(handle, recent);
45
+ return true;
46
+ },
47
+ };
48
+ }
49
+
21
50
  const one = (db, sql, values) => db.all(sql, values)[0] ?? {};
22
51
 
23
52
  /**
@@ -0,0 +1,198 @@
1
+ import fs from "node:fs";
2
+ import path from "node:path";
3
+ import { fileURLToPath } from "node:url";
4
+ import { newerVersion } from "./desktop.mjs";
5
+ import { paths } from "./paths.mjs";
6
+
7
+ // Tells the person when a newer tryharness release is published and which of their computers are behind it. Home says
8
+ // it once, for every computer; a worker with no confirmed home says it for itself. Nothing is fetched or installed
9
+ // here: the person's press on Update does that, through the signed upgrade (selfUpdate.mjs).
10
+
11
+ // npm's newest is read when the daemon starts and then this often.
12
+ const CHECK_EVERY_MS = 6 * 60 * 60_000;
13
+ // Timers stop while a laptop sleeps, so a due check is looked for this often rather than left to one long timer.
14
+ const LOOK_EVERY_MS = 10 * 60_000;
15
+ // Settings reads every few seconds while open; the other computers are asked at most this often.
16
+ const COMPUTERS_FRESH_MS = 20_000;
17
+ // Measured November 6, 2026 from the owner's Mac, 30 GETs of this endpoint to the end of the body: all 200, min 0.09 s,
18
+ // mean 0.69 s, max 4.9 s. About six times the slowest; a check that runs out only waits for the next one.
19
+ const REGISTRY_DEADLINE_MS = 30_000;
20
+
21
+ const NPM_REGISTRY = "https://registry.npmjs.org";
22
+ const RELEASE = /^\d+\.\d+\.\d+$/;
23
+
24
+ // A local build (0.7.83-local.ab12) counts as its release, as an update does (ownMachines.mjs).
25
+ const releaseOf = (version) => String(version).split("-")[0];
26
+
27
+ /** Only a daemon running an installed release can be updated: one from a checkout is the person's own code. */
28
+ function runsAnInstalledRelease() {
29
+ const here = fileURLToPath(new URL("..", import.meta.url));
30
+ try {
31
+ const installed = fs.realpathSync(paths.runtime) + path.sep;
32
+ return fs.realpathSync(here).startsWith(installed);
33
+ } catch {
34
+ return false;
35
+ }
36
+ }
37
+
38
+ /** The newest published release, or null when npm cannot say. */
39
+ async function readLatest(registry) {
40
+ const base = String(registry || NPM_REGISTRY).replace(/\/+$/, "");
41
+ const response = await fetch(`${base}/tryharness/latest`, {
42
+ headers: { accept: "application/json" },
43
+ signal: AbortSignal.timeout(REGISTRY_DEADLINE_MS),
44
+ });
45
+ if (!response.ok) throw new Error(`npm answered ${response.status}`);
46
+ const { version } = await response.json();
47
+ if (!RELEASE.test(String(version)))
48
+ throw new Error(`npm named no release: ${version}`);
49
+ return version;
50
+ }
51
+
52
+ const joined = (names) =>
53
+ names.length < 2
54
+ ? names.join("")
55
+ : `${names.slice(0, -1).join(", ")} and ${names.at(-1)}`;
56
+
57
+ /** The notice, as the person reads it. */
58
+ function noticeWords(latest, behind) {
59
+ const here = behind.length === 1 && behind[0].here;
60
+ const who = here
61
+ ? `This computer runs ${behind[0].version}`
62
+ : `${joined(behind.map((computer) => (computer.here ? "This computer" : computer.label)))} ${behind.length === 1 ? "is" : "are"} behind`;
63
+ return `Harness ${latest} is out. ${who}. Update in Settings, under Your devices.`;
64
+ }
65
+
66
+ export function createReleaseNotice({
67
+ store,
68
+ log = () => {},
69
+ // Every computer this one can speak for, this one first: { id, label, here, connected, version, older, update }.
70
+ computers,
71
+ // Whether this computer is the one that tells the person (home, or a worker on its own).
72
+ tellsPerson = () => true,
73
+ // Whether the person wants notices at all.
74
+ speaks = () => true,
75
+ // Whether the computer is in Standby: nothing is fetched or said until it is back.
76
+ quiet = () => false,
77
+ // The notice: true once it was given to the desktop.
78
+ tell = () => false,
79
+ // Something a surface reads changed.
80
+ changed = () => {},
81
+ installed = runsAnInstalledRelease(),
82
+ registry = process.env.npm_config_registry,
83
+ now = () => Date.now(),
84
+ }) {
85
+ let latest = null;
86
+ let checkedAt = 0;
87
+ let known = [];
88
+ let knownAt = 0;
89
+ let computersMoved = false;
90
+ let reading = null;
91
+ let timer = null;
92
+
93
+ const isBehind = (computer) =>
94
+ Boolean(latest) &&
95
+ (computer.older === true ||
96
+ (Boolean(computer.version) &&
97
+ newerVersion(latest, releaseOf(computer.version))));
98
+
99
+ const readComputers = () => {
100
+ reading ??= Promise.resolve()
101
+ .then(computers)
102
+ .then((list) => {
103
+ known = list;
104
+ knownAt = now();
105
+ computersMoved = false;
106
+ })
107
+ .catch((error) => log(`release notice: ${error.message}`))
108
+ .finally(() => {
109
+ reading = null;
110
+ });
111
+ return reading;
112
+ };
113
+
114
+ const toldKey = (release) => `told:release:${release}`;
115
+
116
+ // Once per release and computer; a computer found behind later is told then.
117
+ function tellNew() {
118
+ if (!latest || !tellsPerson() || !speaks() || quiet()) return;
119
+ let told = [];
120
+ try {
121
+ told = JSON.parse(store.meta(toldKey(latest)) || "[]");
122
+ } catch {}
123
+ const behind = known.filter(isBehind);
124
+ if (!behind.some((computer) => !told.includes(computer.id))) return;
125
+ if (!tell(noticeWords(latest, behind), `release:${latest}`)) return;
126
+ const ids = behind.map((computer) => computer.id);
127
+ store.meta(
128
+ toldKey(latest),
129
+ JSON.stringify([...new Set([...told, ...ids])])
130
+ );
131
+ }
132
+
133
+ async function check() {
134
+ try {
135
+ latest = await readLatest(registry);
136
+ checkedAt = now();
137
+ } catch (error) {
138
+ // Offline is ordinary. It tries again at the next look, and the person is not told about it.
139
+ log(`release notice: could not read npm (${error.message})`);
140
+ return;
141
+ }
142
+ await readComputers();
143
+ tellNew();
144
+ changed();
145
+ }
146
+
147
+ async function look() {
148
+ if (quiet()) return;
149
+ const due = now() - checkedAt >= CHECK_EVERY_MS;
150
+ if (due) return check();
151
+ if (computersMoved) {
152
+ await readComputers();
153
+ changed();
154
+ }
155
+ tellNew();
156
+ }
157
+
158
+ return {
159
+ start() {
160
+ if (!installed) return;
161
+ void look();
162
+ timer = setInterval(() => void look(), LOOK_EVERY_MS);
163
+ timer.unref?.();
164
+ },
165
+ stop() {
166
+ clearInterval(timer);
167
+ },
168
+ /** A computer came, went, restarted or was asked to update: its release is read at the next look or view. */
169
+ computersChanged() {
170
+ computersMoved = true;
171
+ knownAt = 0;
172
+ },
173
+ /** For Settings: every computer's release, read again when the last reading has aged. */
174
+ async view() {
175
+ if (now() - knownAt >= COMPUTERS_FRESH_MS) await readComputers();
176
+ tellNew();
177
+ return {
178
+ ok: true,
179
+ latest,
180
+ computers: known.map((computer) => ({
181
+ ...computer,
182
+ behind: isBehind(computer),
183
+ })),
184
+ };
185
+ },
186
+ /** For `tryharness status`, from what was last read. */
187
+ status() {
188
+ return {
189
+ latest,
190
+ behind: known.filter(isBehind).map((computer) => ({
191
+ label: computer.label,
192
+ here: computer.here,
193
+ version: computer.version ?? null,
194
+ })),
195
+ };
196
+ },
197
+ };
198
+ }
@@ -3,7 +3,12 @@ import path from "node:path";
3
3
  import { removeAgentConfigurations } from "./adapters.mjs";
4
4
  import { detectAgents } from "./commands.mjs";
5
5
  import { uninstallDesktop } from "./desktop.mjs";
6
- import { readJson, writeJsonAtomic } from "./files.mjs";
6
+ import { readJson, updateJson } from "./files.mjs";
7
+ import {
8
+ forgetConnectionToken,
9
+ readConfig,
10
+ removeSecretFile,
11
+ } from "./secretStore.mjs";
7
12
  import { removeNativeHost } from "./nativeHost.mjs";
8
13
  import { uninstallService } from "./service.mjs";
9
14
  import { removeLocalWakes } from "./wakes.mjs";
@@ -39,6 +44,12 @@ export function removeHarnessHere({
39
44
  try {
40
45
  fs.rmSync(target, { recursive: true, force: true });
41
46
  } catch {}
47
+ // The connection goes either way; the keys go with the folder (on a Mac they are in the keychain, secretStore.mjs).
48
+ forgetConnectionToken(paths.config);
49
+ if (wholeFolder) {
50
+ removeSecretFile(paths.phoneIdentity);
51
+ removeSecretFile(paths.deviceIdentity);
52
+ }
42
53
  if (!wholeFolder) keepChoicesOnly(paths.config);
43
54
  return { folderRemoved: wholeFolder };
44
55
  }
@@ -52,7 +63,7 @@ export function stopSetupHere({ paths }) {
52
63
 
53
64
  /** The agents setup set up before sign-in: the ones the person chose on an earlier install, if any. */
54
65
  export function chosenAgents(paths) {
55
- return readJson(paths.config, {}).swarmAgents ?? [];
66
+ return readConfig(paths.config, {}).swarmAgents ?? [];
56
67
  }
57
68
 
58
69
  // Each agent's Harness setup is undone through its own CLI, a second or so apiece, so only the ones changed are.
@@ -86,6 +97,6 @@ function downloadedParts(paths) {
86
97
  // The pairing goes; the person's choices stay (who is in their swarm, who they took out), so setting up again keeps
87
98
  // their swarm (a reinstall once came back without Bankr, Quotient, Grok Bot and Muse).
88
99
  function keepChoicesOnly(configPath) {
89
- const { token: _token, ...choices } = readJson(configPath, {});
90
- if (Object.keys(choices).length) writeJsonAtomic(configPath, choices);
100
+ if (!fs.existsSync(configPath)) return;
101
+ updateJson(configPath, ({ token: _token, ...choices }) => choices);
91
102
  }