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,544 @@
1
+ import fs from "node:fs";
2
+ import os from "node:os";
3
+
4
+ // The machine (docs/senses-plan.md S2.3): the body's own state, as each computer's system says it. On a Mac the
5
+ // launcher hears the Mac's memory pressure, heat, battery, lid and network as they change (nativeSenses.mjs); Linux
6
+ // reads the kernel's own files every 5 s; Windows reads free memory every minute, and its battery and heat only when an
7
+ // agent asks. The disk is read every minute everywhere, counted on a Mac as Finder counts it.
8
+ //
9
+ // What the machine says becomes facts about this computer (facts.mjs), each written only when its level changes, and a
10
+ // happening in the log each time one does. A level clears only some way past where it set, so a value sitting at the
11
+ // line is not said again and again.
12
+ //
13
+ // The disk has two levels from the computer's own record, not a fixed floor (owner, November 12). Tight: less free
14
+ // than the larger of the worst day in the last 30 days and twice the critical point; Harness then clears its own
15
+ // scratch and rebuildable files (onTight, cleanup.mjs). Critical: less than 5 GB or 5% of the disk, whichever is
16
+ // smaller; new runs are held and the person is told. The plan named macOS's own low-disk notice for critical: the
17
+ // launcher hears those notices, but they do not say which disk they are about, and the "low" one did not come even at
18
+ // 3% free on a test disk (November 12), so they only make the daemon read the disk again at once. Until a computer
19
+ // has a week of readings, only critical applies.
20
+
21
+ const LINUX_LOOK_MS = 5_000;
22
+ const WINDOWS_LOOK_MS = 60_000;
23
+ export const DISK_LOOK_MS = 60_000;
24
+ const HOUR_MS = 3_600_000;
25
+ const KEEP_HOURS = 30 * 24;
26
+ const LEARNED_HOURS = 7 * 24;
27
+ const GB = 1e9;
28
+ const CRITICAL_BYTES = 5 * GB;
29
+ const CRITICAL_SHARE = 0.05;
30
+ const CLEAR_ABOVE = 1.2;
31
+ // Lid-Closed Mode's own battery floor (packages/desktop/src-tauri/src/lid.rs SLEEP_FLOOR_PERCENT), cleared 5 above.
32
+ const BATTERY_LOW = 20;
33
+ const BATTERY_CLEAR = 25;
34
+ const FORECAST_HOURS = 24;
35
+ // The disk readings a forecast fits: the last two hours at one a minute, and at least ten minutes of them.
36
+ const RECENT = 120;
37
+ const RECENT_LEAST_MS = 10 * 60_000;
38
+
39
+ const readText = (file) => {
40
+ try {
41
+ return fs.readFileSync(file, "utf8");
42
+ } catch {
43
+ return null;
44
+ }
45
+ };
46
+ const listed = (folder) => {
47
+ try {
48
+ return fs.readdirSync(folder);
49
+ } catch {
50
+ return null;
51
+ }
52
+ };
53
+
54
+ // The kernel says how long tasks waited for memory (PSI); it names no levels, so these follow Android's low-memory
55
+ // daemon: some tasks stalled a tenth of the time is pressure, all of them stalled a tenth of the time is critical.
56
+ function linuxPressure() {
57
+ const text = readText("/proc/pressure/memory");
58
+ if (!text) return "unknown";
59
+ const share = (kind) =>
60
+ Number(text.match(new RegExp(`^${kind} avg10=([0-9.]+)`, "m"))?.[1] ?? 0);
61
+ return share("full") >= 10
62
+ ? "critical"
63
+ : share("some") >= 10
64
+ ? "warn"
65
+ : "normal";
66
+ }
67
+
68
+ // Each sensor's own trip points, as the hardware defines them: past a passive one is fair, past a hot one serious.
69
+ function linuxHeat() {
70
+ const zones = (listed("/sys/class/thermal") ?? []).filter((name) =>
71
+ name.startsWith("thermal_zone")
72
+ );
73
+ if (!zones.length) return "unknown";
74
+ const rank = ["nominal", "fair", "serious", "critical"];
75
+ let level = 0;
76
+ for (const zone of zones) {
77
+ const folder = `/sys/class/thermal/${zone}`;
78
+ const now = Number(readText(`${folder}/temp`));
79
+ if (!Number.isFinite(now)) continue;
80
+ for (let index = 0; index < 16; index++) {
81
+ const type = readText(`${folder}/trip_point_${index}_type`)?.trim();
82
+ if (!type) break;
83
+ const trip = Number(readText(`${folder}/trip_point_${index}_temp`));
84
+ if (!Number.isFinite(trip) || trip <= 0 || now < trip) continue;
85
+ if (type === "critical") level = Math.max(level, 3);
86
+ else if (type === "hot") level = Math.max(level, 2);
87
+ else if (type === "passive") level = Math.max(level, 1);
88
+ }
89
+ }
90
+ return rank[level];
91
+ }
92
+
93
+ function linuxBattery() {
94
+ for (const name of listed("/sys/class/power_supply") ?? []) {
95
+ const folder = `/sys/class/power_supply/${name}`;
96
+ if (readText(`${folder}/type`)?.trim() !== "Battery") continue;
97
+ const percent = Number(readText(`${folder}/capacity`));
98
+ if (!Number.isFinite(percent)) continue;
99
+ const status = readText(`${folder}/status`)?.trim();
100
+ return {
101
+ percent,
102
+ onBattery: status === "Discharging",
103
+ charging: status === "Charging",
104
+ };
105
+ }
106
+ return null;
107
+ }
108
+
109
+ function linuxLid() {
110
+ for (const name of listed("/proc/acpi/button/lid") ?? []) {
111
+ const state = readText(`/proc/acpi/button/lid/${name}/state`) ?? "";
112
+ if (state.includes("closed")) return "closed";
113
+ if (state.includes("open")) return "open";
114
+ }
115
+ return null;
116
+ }
117
+
118
+ function nodeNetwork() {
119
+ const online = Object.values(os.networkInterfaces())
120
+ .flat()
121
+ .some((entry) => entry && !entry.internal);
122
+ return { online, kind: online ? "other" : "none" };
123
+ }
124
+
125
+ /** The machine kind for sources.mjs: `{}`. A reading is the machine as its system says it. */
126
+ export function createMachineKind({
127
+ native = null,
128
+ now = () => Date.now(),
129
+ platform = process.platform,
130
+ }) {
131
+ const read = () =>
132
+ platform === "linux"
133
+ ? {
134
+ pressure: linuxPressure(),
135
+ heat: linuxHeat(),
136
+ battery: linuxBattery(),
137
+ lid: linuxLid(),
138
+ network: nodeNetwork(),
139
+ disk: "unknown",
140
+ }
141
+ : {
142
+ pressure: "unknown",
143
+ heat: "unknown",
144
+ battery: null,
145
+ lid: null,
146
+ network: nodeNetwork(),
147
+ disk: "unknown",
148
+ freeMemory: os.freemem(),
149
+ };
150
+ return {
151
+ describe: () =>
152
+ native?.available()
153
+ ? platform === "linux"
154
+ ? "hears the kernel's memory pressure, network and battery as they change, and reads heat and the lid where the computer has them"
155
+ : "hears the Mac's own memory pressure, heat, battery, lid, network and low-space notices as they change"
156
+ : platform === "linux"
157
+ ? `reads the kernel's memory pressure, heat, battery, lid and network every ${LINUX_LOOK_MS / 1000} s`
158
+ : platform === "win32"
159
+ ? `reads free memory and the network every ${WINDOWS_LOOK_MS / 1000} s`
160
+ : "reads the network once; with no launcher here the rest is read only when asked",
161
+ start(_, io) {
162
+ let stopped = false;
163
+ let timer = null;
164
+ let following = null;
165
+ const look = (every) => {
166
+ if (stopped) return;
167
+ io.report({ at: now(), ...read() });
168
+ if (!every) return;
169
+ timer = setTimeout(() => look(every), every);
170
+ timer.unref?.();
171
+ };
172
+ const everyLook =
173
+ platform === "linux"
174
+ ? LINUX_LOOK_MS
175
+ : platform === "win32"
176
+ ? WINDOWS_LOOK_MS
177
+ : 0;
178
+ if (native?.available()) {
179
+ // A line that closes later (the Linux program stopped) leaves the machine read through Node.
180
+ const unhear = native.onClose?.(() => {
181
+ following = null;
182
+ if (!stopped && !timer) look(everyLook);
183
+ });
184
+ native
185
+ .followMachine((reading) => {
186
+ if (!stopped) io.report({ at: now(), ...reading });
187
+ })
188
+ .then((followed) => {
189
+ following = followed;
190
+ if (stopped) followed.stop();
191
+ else io.report({ at: now(), ...followed.reading });
192
+ })
193
+ .catch(() => {
194
+ unhear?.();
195
+ look(everyLook);
196
+ });
197
+ } else {
198
+ timer = setTimeout(() => look(everyLook), 0);
199
+ timer.unref?.();
200
+ }
201
+ return {
202
+ stop() {
203
+ stopped = true;
204
+ clearTimeout(timer);
205
+ following?.stop();
206
+ },
207
+ };
208
+ },
209
+ };
210
+ }
211
+
212
+ /** How full the disk a path is on is: `{ free, total }`, on a Mac with the launcher as Finder counts it. */
213
+ export async function readDisk(where, native = null) {
214
+ if (native?.available())
215
+ try {
216
+ const counted = await native.disk(where);
217
+ // A disk that is not the Mac's own reads 0 for what Finder counts: what can be written is the larger.
218
+ const free = Math.max(counted.important ?? 0, counted.available ?? 0);
219
+ if (counted.total) return { free, total: counted.total };
220
+ } catch {}
221
+ const stat = await fs.promises.statfs(where);
222
+ return { free: stat.bavail * stat.bsize, total: stat.blocks * stat.bsize };
223
+ }
224
+
225
+ /** The disk kind for sources.mjs: `{ path }`, read every minute. */
226
+ export function createDiskKind({ native = null, now = () => Date.now() }) {
227
+ return {
228
+ describe: ({ path: where }) =>
229
+ `reads how full the disk holding ${where} is every ${DISK_LOOK_MS / 1000} s${native?.available() && process.platform === "darwin" ? ", as Finder counts it" : ""}`,
230
+ start({ path: where }, io) {
231
+ let stopped = false;
232
+ let timer = null;
233
+ const read = async () => {
234
+ let reading;
235
+ try {
236
+ reading = await readDisk(where, native);
237
+ } catch (error) {
238
+ reading = { error: error.message };
239
+ }
240
+ if (stopped) return;
241
+ io.report({ at: now(), ...reading });
242
+ timer = setTimeout(read, DISK_LOOK_MS);
243
+ timer.unref?.();
244
+ };
245
+ timer = setTimeout(read, 0);
246
+ timer.unref?.();
247
+ return {
248
+ stop() {
249
+ stopped = true;
250
+ clearTimeout(timer);
251
+ },
252
+ };
253
+ },
254
+ };
255
+ }
256
+
257
+ const gb = (bytes) =>
258
+ bytes >= 10 * GB
259
+ ? `${Math.round(bytes / GB)} GB`
260
+ : bytes >= GB
261
+ ? `${(bytes / GB).toFixed(1)} GB`
262
+ : `${Math.max(0, Math.round(bytes / 1e6))} MB`;
263
+
264
+ /** The largest fall in free space within any 24 hours of an hourly record (each hour's lowest). */
265
+ export function worstDay(hours) {
266
+ let worst = 0;
267
+ for (let index = 0; index < hours.length; index++)
268
+ for (let back = index - 1; back >= 0; back--) {
269
+ if (hours[index].hour - hours[back].hour > 24) break;
270
+ worst = Math.max(worst, hours[back].low - hours[index].low);
271
+ }
272
+ return worst;
273
+ }
274
+
275
+ /** Bytes an hour the free space moves by over the recent readings (negative while filling), or null. */
276
+ function slopePerHour(recent) {
277
+ if (recent.length < 10 || recent.at(-1).at - recent[0].at < RECENT_LEAST_MS)
278
+ return null;
279
+ const t0 = recent[0].at;
280
+ const xs = recent.map((entry) => (entry.at - t0) / HOUR_MS);
281
+ const ys = recent.map((entry) => entry.free);
282
+ const mx = xs.reduce((a, b) => a + b, 0) / xs.length;
283
+ const my = ys.reduce((a, b) => a + b, 0) / ys.length;
284
+ const spread = xs.reduce((sum, x) => sum + (x - mx) ** 2, 0);
285
+ return spread
286
+ ? xs.reduce((sum, x, index) => sum + (x - mx) * (ys[index] - my), 0) /
287
+ spread
288
+ : null;
289
+ }
290
+
291
+ /**
292
+ * This computer's machine: follows the machine and the disk Harness keeps its things on (`home`) from the start, keeps
293
+ * the facts and says the changes. `hold(on, how)` holds new runs while the disk is critical; `notify(text)` tells the
294
+ * person; `onTight(level)` lets cleanup clear Harness's own files first. `now()` is the machine as last read, for Lid-
295
+ * Closed Mode's loop.
296
+ */
297
+ export function createMachine({
298
+ sources,
299
+ facts,
300
+ events,
301
+ store,
302
+ machineId,
303
+ home,
304
+ native = null,
305
+ notify = () => {},
306
+ hold = () => {},
307
+ onTight = () => {},
308
+ // Facts are written on home, where the board is: a worker's board is home's copy, which home writes over. A worker
309
+ // keeps its levels here and says their changes in its own log; its facts reach the others with the nerves (S6).
310
+ isHome = () => true,
311
+ now = () => Date.now(),
312
+ log = () => {},
313
+ }) {
314
+ const HISTORY_KEY = "machine-disk-history";
315
+ let hours = (() => {
316
+ try {
317
+ return JSON.parse(store.meta(HISTORY_KEY) || "[]");
318
+ } catch {
319
+ return [];
320
+ }
321
+ })();
322
+ const recent = [];
323
+ let machine = null;
324
+ let disk = null;
325
+ let holding = false;
326
+ let following = [];
327
+
328
+ // What each fact last said, as written here: compared before writing again, so a reading that says nothing new
329
+ // writes nothing, and on a worker the level is kept even though it writes no fact.
330
+ const said = new Map();
331
+ const factOf = (aspect) => {
332
+ if (!said.has(aspect))
333
+ said.set(
334
+ aspect,
335
+ isHome()
336
+ ? (facts.get(`machine.${aspect}`, { machine: machineId })?.value ??
337
+ null)
338
+ : null
339
+ );
340
+ return said.get(aspect);
341
+ };
342
+
343
+ /** Keeps a level about this computer when it says something new: a fact on home, and a happening in the log. */
344
+ const keep = (aspect, value, text, cause = null) => {
345
+ const before = factOf(aspect);
346
+ if (JSON.stringify(before) === JSON.stringify(value)) return false;
347
+ said.set(aspect, value);
348
+ if (isHome())
349
+ facts.set(`machine.${aspect}`, value, {
350
+ source: "machine",
351
+ machine: machineId,
352
+ });
353
+ events.append({
354
+ source: "machine",
355
+ kind: "level",
356
+ subject: aspect,
357
+ text,
358
+ data: { aspect, ...value, was: before },
359
+ cause,
360
+ });
361
+ return true;
362
+ };
363
+
364
+ const fromMachine = (reading) => {
365
+ const diskNotice = machine && reading.disk !== machine.disk;
366
+ machine = reading;
367
+ const cause = reading.event ?? null;
368
+ if (reading.pressure && reading.pressure !== "unknown")
369
+ keep(
370
+ "memory",
371
+ { level: reading.pressure },
372
+ `memory pressure is ${reading.pressure}`,
373
+ cause
374
+ );
375
+ if (reading.heat && reading.heat !== "unknown")
376
+ keep(
377
+ "heat",
378
+ { level: reading.heat },
379
+ `the computer's heat is ${reading.heat}`,
380
+ cause
381
+ );
382
+ if (reading.battery) {
383
+ const { percent, onBattery } = reading.battery;
384
+ const wasLow = factOf("battery")?.level === "low";
385
+ const low =
386
+ onBattery &&
387
+ (percent <= BATTERY_LOW || (wasLow && percent < BATTERY_CLEAR));
388
+ const rounded = Math.round(percent);
389
+ keep(
390
+ "battery",
391
+ { level: low ? "low" : "ok", onBattery },
392
+ low
393
+ ? `the battery is low: ${rounded}%, on battery`
394
+ : onBattery
395
+ ? `on battery, ${rounded}%`
396
+ : `plugged in, ${rounded}%`,
397
+ cause
398
+ );
399
+ }
400
+ if (reading.lid)
401
+ keep("lid", { state: reading.lid }, `the lid is ${reading.lid}`, cause);
402
+ if (reading.network)
403
+ keep(
404
+ "network",
405
+ { online: reading.network.online, kind: reading.network.kind },
406
+ reading.network.online
407
+ ? `the network is on (${reading.network.kind})`
408
+ : "the network is off",
409
+ cause
410
+ );
411
+ // The Mac says one of its disks is filling or has room: read this one now rather than within the minute.
412
+ if (diskNotice && home)
413
+ void readDisk(home, native)
414
+ .then((counted) => fromDisk({ at: now(), ...counted, event: cause }))
415
+ .catch(() => {});
416
+ };
417
+
418
+ const remember = (at, free) => {
419
+ const hour = Math.floor(at / HOUR_MS);
420
+ const last = hours.at(-1);
421
+ if (last?.hour === hour) {
422
+ if (free < last.low) last.low = free;
423
+ return;
424
+ }
425
+ hours.push({ hour, low: free });
426
+ hours = hours.filter((entry) => entry.hour > hour - KEEP_HOURS);
427
+ store.meta(HISTORY_KEY, JSON.stringify(hours));
428
+ };
429
+
430
+ /** The disk's level for a reading, from where it was: the lines it is measured against come from this computer's record. */
431
+ const levelFor = ({ free, total }, was) => {
432
+ const critical = Math.min(CRITICAL_BYTES, CRITICAL_SHARE * total);
433
+ const learned =
434
+ hours.length && hours.at(-1).hour - hours[0].hour >= LEARNED_HOURS;
435
+ const worst = learned ? worstDay(hours) : 0;
436
+ const tight = learned ? Math.max(worst, 2 * critical) : null;
437
+ const level =
438
+ free < critical || (was === "critical" && free < critical * CLEAR_ABOVE)
439
+ ? "critical"
440
+ : tight !== null &&
441
+ (free < tight || (was !== "ok" && free < tight * CLEAR_ABOVE))
442
+ ? "tight"
443
+ : "ok";
444
+ return { level, critical, tight, worst };
445
+ };
446
+
447
+ const fromDisk = (reading) => {
448
+ if (reading.error || !Number.isFinite(reading.free) || !reading.total)
449
+ return;
450
+ disk = reading;
451
+ remember(reading.at, reading.free);
452
+ recent.push({ at: reading.at, free: reading.free });
453
+ if (recent.length > RECENT) recent.shift();
454
+ const was = factOf("disk")?.level ?? "ok";
455
+ const free = reading.free;
456
+ const { level, critical, tight, worst } = levelFor(reading, was);
457
+ const slope = slopePerHour(recent);
458
+ const line = tight ?? critical;
459
+ const hoursLeft =
460
+ slope !== null && slope < 0 ? (free - line) / -slope : null;
461
+ const filling =
462
+ level === "ok" &&
463
+ hoursLeft !== null &&
464
+ hoursLeft >= 0 &&
465
+ hoursLeft <= FORECAST_HOURS;
466
+ const text =
467
+ level === "critical"
468
+ ? `the disk is nearly full: ${gb(free)} free`
469
+ : level === "tight"
470
+ ? `the disk is tight: ${gb(free)} free, less than its worst day lately (${gb(worst)})`
471
+ : filling
472
+ ? `the disk is filling: ${gb(free)} free, about ${gb(-slope)} an hour; it is ${tight !== null ? "tight" : "nearly full"} in about ${Math.max(1, Math.round(hoursLeft))} hour${Math.round(hoursLeft) === 1 ? "" : "s"}`
473
+ : `the disk has room: ${gb(free)} free`;
474
+ keep("disk", { level, filling }, text, reading.event ?? null);
475
+ if (level !== "ok" && was === "ok") onTight(level);
476
+ if (level === "critical" && !holding) {
477
+ holding = true;
478
+ hold(true, {
479
+ by: "disk",
480
+ why: "the disk is nearly full",
481
+ until: "the disk has room again",
482
+ });
483
+ onTight(level);
484
+ notify(
485
+ `The disk is nearly full (${gb(free)} free). Harness holds new work until there is room.`
486
+ );
487
+ } else if (level !== "critical" && holding) {
488
+ holding = false;
489
+ hold(false, { by: "disk" });
490
+ notify(`The disk has room again (${gb(free)} free). Held work starts.`);
491
+ }
492
+ };
493
+
494
+ return {
495
+ start() {
496
+ following = [
497
+ sources.subscribe({ kind: "machine" }, (reading) => {
498
+ try {
499
+ fromMachine(reading);
500
+ } catch (error) {
501
+ log(`machine: ${error.message}`);
502
+ }
503
+ }),
504
+ ...(home
505
+ ? [
506
+ sources.subscribe({ kind: "disk", path: home }, (reading) => {
507
+ try {
508
+ fromDisk(reading);
509
+ } catch (error) {
510
+ log(`machine: the disk: ${error.message}`);
511
+ }
512
+ }),
513
+ ]
514
+ : []),
515
+ ];
516
+ },
517
+ /** Whether the disk has room again now, read afresh: cleanup clears until it has. */
518
+ async hasRoom() {
519
+ if (!home) return true;
520
+ const counted = await readDisk(home, native);
521
+ return levelFor(counted, factOf("disk")?.level ?? "ok").level === "ok";
522
+ },
523
+ /** The machine as last read: what Lid-Closed Mode's loop and an agent's look read. */
524
+ now: () => ({
525
+ pressure: machine?.pressure ?? "unknown",
526
+ heat: machine?.heat ?? "unknown",
527
+ battery: machine?.battery ?? null,
528
+ lid: machine?.lid ?? null,
529
+ network: machine?.network ?? null,
530
+ disk: disk
531
+ ? {
532
+ level: factOf("disk")?.level ?? "ok",
533
+ free: disk.free,
534
+ total: disk.total,
535
+ }
536
+ : null,
537
+ }),
538
+ stop() {
539
+ for (const unfollow of following) unfollow();
540
+ following = [];
541
+ if (hours.length) store.meta(HISTORY_KEY, JSON.stringify(hours));
542
+ },
543
+ };
544
+ }