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,540 @@
1
+ import fs from "node:fs";
2
+ import path from "node:path";
3
+ import { execFile } from "node:child_process";
4
+
5
+ // The file source (docs/senses-plan.md S2.1): which files change in a folder. Changes are allowed 2 s to settle and a
6
+ // burst is said once (S0.1: a checkout of 4,395 files made 4,736 events in about 2.2 s); what to ignore is what the
7
+ // repository's own ignore rules name, asked of git itself, plus git's own folder, never a list kept here (S0.1 found a
8
+ // fixed list missing two build folders). Each burst names who was working there: a run Harness started in the folder,
9
+ // or someone else (S4.2 sharpens it to the agent and the call).
10
+ //
11
+ // A followed folder also says what changed in it while Harness was off. On a Mac the launcher asks the Mac's numbered
12
+ // history of file changes from the mark the source last kept (nativeSenses.mjs); where there is no launcher, or the
13
+ // history cannot answer (too far back, started again, lost track), a snapshot is compared: for a repository, its
14
+ // commit and the size and time of each file git counts as changed (git keeps the rest); for another folder, its file
15
+ // list. A quiet source (the agents' history folders, the file library) hands its changes to its follower alone: they
16
+ // change with every message an agent writes, so the log never hears of them, and their followers catch up themselves.
17
+
18
+ export const SETTLE_MS = 2_000;
19
+ // A folder that never goes quiet still reports this often.
20
+ const LONGEST_MS = 30_000;
21
+ // The files a happening names; the reading itself has them all.
22
+ const NAMED = 20;
23
+ // A repository's snapshot is taken again at most this often while files keep changing: one that is older only means
24
+ // a change said live may be said again after a restart, never that one is missed.
25
+ const SNAPSHOT_EVERY_MS = 60_000;
26
+ // How far a snapshot goes: past this many files a folder is too large to compare, and that is said instead.
27
+ const MOST_FILES = 20_000;
28
+ // Where each folder is watched on its own (Linux, and where Node cannot watch a whole tree), up to this many.
29
+ const MOST_FOLDERS = 5_000;
30
+ // How far back the Mac's history is read before a snapshot is compared instead (S0.1: 43,788 changes took 42 s).
31
+ const HISTORY_BOUND = { maxEvents: 20_000, maxMs: 10_000 };
32
+
33
+ const split0 = (text) =>
34
+ String(text ?? "")
35
+ .split("\0")
36
+ .filter(Boolean);
37
+
38
+ /** Runs git and gives its output; "" when it fails, null when git cannot be found. */
39
+ const git = (args, cwd, input) =>
40
+ new Promise((resolve) => {
41
+ const child = execFile(
42
+ "git",
43
+ args,
44
+ { cwd, encoding: "utf8", maxBuffer: 64 * 1024 * 1024 },
45
+ (error, stdout) =>
46
+ resolve(error?.code === "ENOENT" ? null : (stdout ?? ""))
47
+ );
48
+ child.stdin?.on("error", () => {});
49
+ if (input !== undefined) child.stdin?.end(input);
50
+ });
51
+
52
+ /** The repository a folder is in: its top, and the folders its ignore rules leave out, relative to the folder. */
53
+ async function repositoryOf(folder) {
54
+ const top = (await git(["rev-parse", "--show-toplevel"], folder))?.trim();
55
+ if (!top) return null;
56
+ return {
57
+ top: fs.realpathSync(top),
58
+ ignored: await ignoredFolders(top, folder),
59
+ };
60
+ }
61
+
62
+ async function ignoredFolders(top, folder) {
63
+ const listed = await git(
64
+ [
65
+ "ls-files",
66
+ "--others",
67
+ "--ignored",
68
+ "--exclude-standard",
69
+ "--directory",
70
+ "-z",
71
+ ],
72
+ top
73
+ );
74
+ return split0(listed)
75
+ .filter((entry) => entry.endsWith("/"))
76
+ .map((entry) => path.relative(folder, path.join(top, entry)))
77
+ .filter((relative) => relative && !relative.startsWith(".."))
78
+ .map((relative) => relative + path.sep);
79
+ }
80
+
81
+ /** The names git's ignore rules leave out, asked in one go; tracked files are never left out. */
82
+ async function notIgnored(folder, names) {
83
+ const asked = names.filter((name) => name !== ".");
84
+ if (!asked.length) return names;
85
+ const ignored = new Set(
86
+ split0(
87
+ await git(
88
+ ["check-ignore", "-z", "--stdin"],
89
+ folder,
90
+ `${asked.join("\0")}\0`
91
+ )
92
+ )
93
+ );
94
+ return names.filter((name) => !ignored.has(name));
95
+ }
96
+
97
+ /** A repository as it stands: its commit, and the size and time of each file git counts as changed. */
98
+ async function repositorySnapshot(top) {
99
+ const head =
100
+ (await git(["rev-parse", "--verify", "-q", "HEAD"], top))?.trim() || null;
101
+ const status = split0(
102
+ await git(["status", "--porcelain=v1", "-z", "--untracked-files=all"], top)
103
+ );
104
+ const dirty = {};
105
+ for (let index = 0; index < status.length; index++) {
106
+ const entry = status[index];
107
+ if (entry.length < 4) continue;
108
+ // A rename or copy is followed by its old name.
109
+ if (entry[0] === "R" || entry[0] === "C") index++;
110
+ const file = entry.slice(3);
111
+ const stat = fs.statSync(path.join(top, file), { throwIfNoEntry: false });
112
+ dirty[file] = stat ? [stat.size, Math.round(stat.mtimeMs)] : [-1, 0];
113
+ if (Object.keys(dirty).length >= MOST_FILES) break;
114
+ }
115
+ return { head, dirty };
116
+ }
117
+
118
+ /** What differs between two snapshots of a repository, relative to its top. */
119
+ async function repositoryChanges(top, before, now) {
120
+ const changed = new Set();
121
+ if (before.head && now.head && before.head !== now.head)
122
+ for (const file of split0(
123
+ await git(["diff", "--name-only", "-z", before.head, now.head], top)
124
+ ))
125
+ changed.add(file);
126
+ for (const [file, stamp] of Object.entries(now.dirty)) {
127
+ const was = before.dirty?.[file];
128
+ if (!was || was[0] !== stamp[0] || was[1] !== stamp[1]) changed.add(file);
129
+ }
130
+ for (const file of Object.keys(before.dirty ?? {}))
131
+ if (!(file in now.dirty)) changed.add(file);
132
+ return [...changed];
133
+ }
134
+
135
+ /** Every file under a folder with its size and time, or `{ tooMany }` past MOST_FILES; `leftOut` folders skipped. */
136
+ async function fileList(folder, leftOut = () => false) {
137
+ const files = {};
138
+ let count = 0;
139
+ const walk = async (directory) => {
140
+ let entries;
141
+ try {
142
+ entries = await fs.promises.readdir(directory, { withFileTypes: true });
143
+ } catch {
144
+ return true;
145
+ }
146
+ for (const entry of entries) {
147
+ if (entry.name === ".git") continue;
148
+ const full = path.join(directory, entry.name);
149
+ if (entry.isDirectory()) {
150
+ if (leftOut(path.relative(folder, full) + path.sep)) continue;
151
+ if (!(await walk(full))) return false;
152
+ } else if (entry.isFile()) {
153
+ const stat = await fs.promises.stat(full).catch(() => null);
154
+ if (!stat) continue;
155
+ files[path.relative(folder, full)] = [
156
+ stat.size,
157
+ Math.round(stat.mtimeMs),
158
+ ];
159
+ if (++count > MOST_FILES) return false;
160
+ }
161
+ }
162
+ return true;
163
+ };
164
+ return (await walk(folder)) ? { files } : { tooMany: true };
165
+ }
166
+
167
+ function listChanges(before, now) {
168
+ const changed = [];
169
+ for (const [file, stamp] of Object.entries(now))
170
+ if (
171
+ !before[file] ||
172
+ before[file][0] !== stamp[0] ||
173
+ before[file][1] !== stamp[1]
174
+ )
175
+ changed.push(file);
176
+ for (const file of Object.keys(before))
177
+ if (!(file in now)) changed.push(file);
178
+ return changed;
179
+ }
180
+
181
+ /**
182
+ * Watches a whole tree. On Linux, Node's own recursive watch puts a kernel watch on every folder, ignored or not: one
183
+ * `npm install` took 18,374 of a 4 GB machine's 30,150 (docs/senses-plan.md, the Linux baseline). So there, and where
184
+ * Node cannot watch a tree, each folder is watched on its own, leaving out what `leftOut` names, and a folder made
185
+ * later is watched once `ignoredLater` says the repository does not ignore it (a node_modules made after the folder
186
+ * was followed is not in the list of ignored folders taken at the start).
187
+ */
188
+ function watchTree(
189
+ folder,
190
+ changed,
191
+ failed,
192
+ leftOut,
193
+ ignoredLater = async () => false,
194
+ platform = process.platform
195
+ ) {
196
+ if (platform !== "linux")
197
+ try {
198
+ const watcher = fs.watch(
199
+ folder,
200
+ { recursive: true, persistent: false },
201
+ (_, name) => changed(name == null ? null : String(name))
202
+ );
203
+ watcher.on("error", failed);
204
+ return [watcher];
205
+ } catch (error) {
206
+ if (error.code !== "ERR_FEATURE_UNAVAILABLE_ON_PLATFORM") throw error;
207
+ }
208
+ // Grows as folders appear; the caller closes every one on stop.
209
+ const watchers = [];
210
+ const watched = new Map();
211
+ const isFolder = (full) => {
212
+ try {
213
+ return fs.statSync(full).isDirectory();
214
+ } catch {
215
+ return false;
216
+ }
217
+ };
218
+ const forget = (directory) => {
219
+ watched.get(directory)?.close();
220
+ watched.delete(directory);
221
+ };
222
+ const appeared = async (full, relative) => {
223
+ if (leftOut(relative + path.sep) || (await ignoredLater(relative))) return;
224
+ // What was written into it before its watch began (a checkout or an agent writes a new folder at once) is said too.
225
+ walk(full, { sayFiles: true });
226
+ };
227
+ let capSaid = false;
228
+ const walk = (directory, { sayFiles = false } = {}) => {
229
+ if (watched.has(directory)) return;
230
+ if (watched.size >= MOST_FOLDERS) {
231
+ // Said once: changes in the folders past this many are not heard live, only by the next snapshot.
232
+ if (!capSaid)
233
+ failed(new Error(`only the first ${MOST_FOLDERS} folders are watched`));
234
+ capSaid = true;
235
+ return;
236
+ }
237
+ const relative = path.relative(folder, directory);
238
+ if (relative && leftOut(relative + path.sep)) return;
239
+ let watcher;
240
+ try {
241
+ watcher = fs.watch(directory, { persistent: false }, (_, name) => {
242
+ if (name == null) return changed(null);
243
+ const inside = path.join(directory, String(name));
244
+ const insideRelative = path.join(relative, String(name));
245
+ changed(insideRelative);
246
+ if (String(name) === ".git") return;
247
+ const folderNow = isFolder(inside);
248
+ if (watched.has(inside) && !folderNow) forget(inside);
249
+ else if (!watched.has(inside) && folderNow)
250
+ void appeared(inside, insideRelative).catch(failed);
251
+ });
252
+ } catch {
253
+ return;
254
+ }
255
+ watcher.on("error", (error) => {
256
+ forget(directory);
257
+ // A folder that was removed ends its own watch; anything else is the follower's to hear.
258
+ if (fs.existsSync(directory)) failed(error);
259
+ });
260
+ watched.set(directory, watcher);
261
+ watchers.push(watcher);
262
+ let entries = [];
263
+ try {
264
+ entries = fs.readdirSync(directory, { withFileTypes: true });
265
+ } catch {}
266
+ for (const entry of entries)
267
+ if (entry.isDirectory() && entry.name !== ".git")
268
+ walk(path.join(directory, entry.name), { sayFiles });
269
+ else if (sayFiles && entry.isFile())
270
+ changed(path.join(relative, entry.name));
271
+ };
272
+ walk(folder);
273
+ return watchers;
274
+ }
275
+
276
+ const named = (files, count) =>
277
+ count === 1 ? files[0] : `${files[0]} and ${count - 1} more`;
278
+ const whoOf = (by) =>
279
+ by.length
280
+ ? by.map((run) => `${run.agent}'s run`).join(" and ")
281
+ : "someone else";
282
+
283
+ /**
284
+ * The file kind for sources.mjs: `{ folder, quiet }`. `native` is the launcher's line or null; `runsIn(folder)` names
285
+ * the runs Harness has going in that folder (`{ run, agent, thread }`). `leaveOut`: folders whose changes are never
286
+ * said, Harness's own home among them: a followed folder holding it (a thread working in the person's home folder)
287
+ * would otherwise hear each write to Harness's own log and write it there again, every 2 s, for ever. A folder
288
+ * followed inside one of them (a thread's copy among Harness's) is followed as itself.
289
+ */
290
+ export function createFileKind({
291
+ native = null,
292
+ runsIn = () => [],
293
+ leaveOut = [],
294
+ now = () => Date.now(),
295
+ }) {
296
+ return {
297
+ describe: ({ folder, quiet }) =>
298
+ `follows which files change in ${folder}${quiet ? "" : ", and what changed there while Harness was off"}`,
299
+ start(options, io) {
300
+ // A folder that is not there cannot be followed: the follower hears so at once.
301
+ const folder = fs.realpathSync(options.folder);
302
+ if (!fs.statSync(folder).isDirectory())
303
+ throw new Error(`${folder} is not a folder`);
304
+ const quiet = Boolean(options.quiet);
305
+ const pending = new Set();
306
+ let repository = null;
307
+ let watchers = [];
308
+ let stopped = false;
309
+ let settle = null;
310
+ let firstAt = null;
311
+ let ignoresChanged = false;
312
+ let memory = null;
313
+ let snapshotAt = 0;
314
+ let snapshotLater = null;
315
+
316
+ // Harness's own folders inside this one, relative to it, each ending in a separator.
317
+ const ownInside = leaveOut
318
+ .map((own) => {
319
+ try {
320
+ return fs.realpathSync(own);
321
+ } catch {
322
+ return path.resolve(own);
323
+ }
324
+ })
325
+ .map((own) => path.relative(folder, own))
326
+ .filter(
327
+ (relative) =>
328
+ relative && !relative.startsWith("..") && !path.isAbsolute(relative)
329
+ )
330
+ .map((relative) => relative + path.sep);
331
+ const leftOut = (relative) =>
332
+ ownInside.some(
333
+ (own) => relative + path.sep === own || relative.startsWith(own)
334
+ ) ||
335
+ (repository?.ignored.some(
336
+ (folderOut) =>
337
+ relative === folderOut || relative.startsWith(folderOut)
338
+ ) ??
339
+ false);
340
+
341
+ const keep = async ({ snapshot }) => {
342
+ if (quiet || stopped) return;
343
+ memory = { ...(memory ?? {}), at: new Date(now()).toISOString() };
344
+ if (native?.available())
345
+ memory.native = await native.mark(folder).catch(() => memory.native);
346
+ if (snapshot) {
347
+ snapshotAt = now();
348
+ if (repository)
349
+ memory.repository = await repositorySnapshot(repository.top);
350
+ else {
351
+ const listed = await fileList(folder, leftOut);
352
+ memory.files = listed.tooMany ? null : listed.files;
353
+ }
354
+ } else if (!snapshotLater) {
355
+ snapshotLater = setTimeout(
356
+ () => {
357
+ snapshotLater = null;
358
+ void keep({ snapshot: true });
359
+ },
360
+ Math.max(0, snapshotAt + SNAPSHOT_EVERY_MS - now())
361
+ );
362
+ snapshotLater.unref?.();
363
+ }
364
+ io.remember(memory);
365
+ };
366
+
367
+ const say = (changed, extra = {}) => {
368
+ const by = extra.whileOff ? [] : runsIn(folder);
369
+ const reading = {
370
+ at: now(),
371
+ changed,
372
+ count: changed.length,
373
+ by,
374
+ ...extra,
375
+ };
376
+ const text = extra.whileOff
377
+ ? `${named(changed, changed.length)} changed while Harness was off`
378
+ : `${named(changed, changed.length)} changed, by ${whoOf(by)}`;
379
+ io.report(
380
+ reading,
381
+ quiet
382
+ ? null
383
+ : {
384
+ kind: "changed",
385
+ text,
386
+ data: {
387
+ files: changed.slice(0, NAMED),
388
+ count: changed.length,
389
+ by: by.length ? by : "someone else",
390
+ ...extra,
391
+ },
392
+ }
393
+ );
394
+ };
395
+
396
+ const flush = async () => {
397
+ settle = null;
398
+ firstAt = null;
399
+ const names = [...pending];
400
+ pending.clear();
401
+ if (ignoresChanged && repository) {
402
+ ignoresChanged = false;
403
+ repository.ignored = await ignoredFolders(repository.top, folder);
404
+ }
405
+ const changed = repository ? await notIgnored(folder, names) : names;
406
+ if (stopped || !changed.length) return;
407
+ say(changed);
408
+ await keep({ snapshot: now() - snapshotAt >= SNAPSHOT_EVERY_MS });
409
+ };
410
+
411
+ const changedHere = (name) => {
412
+ if (stopped) return;
413
+ const relative = name ?? ".";
414
+ // macOS also says the followed folder itself changed, under its own name, when a file in it does: that is not
415
+ // a file of the folder's (seen November 13, a thread's copy named in place of the file written in it).
416
+ if (
417
+ relative === path.basename(folder) &&
418
+ !fs.existsSync(path.join(folder, relative))
419
+ )
420
+ return;
421
+ const parts = relative.split(path.sep);
422
+ // Git's own files: what git does is the repository source's to say (S2.5).
423
+ if (parts.includes(".git")) return;
424
+ if (parts.at(-1) === ".gitignore") ignoresChanged = true;
425
+ if (leftOut(relative)) return;
426
+ pending.add(relative);
427
+ firstAt ??= now();
428
+ clearTimeout(settle);
429
+ settle = setTimeout(
430
+ () => void flush(),
431
+ now() - firstAt >= LONGEST_MS ? 0 : SETTLE_MS
432
+ );
433
+ settle.unref?.();
434
+ };
435
+
436
+ // What changed while Harness was off: from the Mac's history when the launcher can say, else a snapshot.
437
+ const catchUp = async () => {
438
+ const before = io.remembered();
439
+ memory = before;
440
+ let found = null;
441
+ let why = null;
442
+ if (before?.native && native?.available()) {
443
+ const history = await native
444
+ .historySince(folder, before.native, HISTORY_BOUND)
445
+ .catch((error) => ({ complete: false, reason: error.message }));
446
+ if (history.complete)
447
+ found = {
448
+ how: "history",
449
+ changed: history.changed
450
+ .map((file) => path.relative(folder, file))
451
+ .filter((relative) => relative && !relative.startsWith("..")),
452
+ };
453
+ else why = history.reason;
454
+ }
455
+ if (!found && before?.repository && repository) {
456
+ const relativeToTop = await repositoryChanges(
457
+ repository.top,
458
+ before.repository,
459
+ await repositorySnapshot(repository.top)
460
+ );
461
+ found = {
462
+ how: "snapshot",
463
+ changed: relativeToTop
464
+ .map((file) =>
465
+ path.relative(folder, path.join(repository.top, file))
466
+ )
467
+ .filter((relative) => relative && !relative.startsWith("..")),
468
+ };
469
+ }
470
+ if (!found && before?.files && !repository) {
471
+ const listed = await fileList(folder, leftOut);
472
+ if (!listed.tooMany)
473
+ found = {
474
+ how: "snapshot",
475
+ changed: listChanges(before.files, listed.files),
476
+ };
477
+ else why = `more than ${MOST_FILES} files to compare`;
478
+ }
479
+ await keep({ snapshot: true });
480
+ if (stopped) return;
481
+ if (!found) {
482
+ // A folder followed for the first time has nothing to compare; one followed before says it cannot tell.
483
+ if (before)
484
+ io.report(
485
+ { at: now(), changed: [], count: 0, by: [], whileOff: true },
486
+ {
487
+ kind: "unknown",
488
+ text: `could not tell what changed while Harness was off${why ? `: ${why}` : ""}`,
489
+ data: { whileOff: true, reason: why },
490
+ }
491
+ );
492
+ return;
493
+ }
494
+ const kept = found.changed.filter(
495
+ (relative) =>
496
+ !relative.split(path.sep).includes(".git") && !leftOut(relative)
497
+ );
498
+ const changed = repository ? await notIgnored(folder, kept) : kept;
499
+ if (changed.length && !stopped)
500
+ say(changed, { whileOff: true, how: found.how });
501
+ };
502
+
503
+ void (async () => {
504
+ repository = quiet ? null : await repositoryOf(folder);
505
+ if (stopped) return;
506
+ try {
507
+ watchers = watchTree(
508
+ folder,
509
+ changedHere,
510
+ (error) => io.report({ at: now(), error: error.message }),
511
+ leftOut,
512
+ async (relative) =>
513
+ repository
514
+ ? !(await notIgnored(folder, [relative + path.sep])).length
515
+ : false
516
+ );
517
+ } catch (error) {
518
+ io.report({ at: now(), error: error.message });
519
+ return;
520
+ }
521
+ if (!quiet) await catchUp();
522
+ })().catch((error) => io.report({ at: now(), error: error.message }));
523
+
524
+ return {
525
+ stop() {
526
+ // Changes said since the last snapshot are kept now, so following the folder again does not say them again.
527
+ if (snapshotLater) {
528
+ clearTimeout(snapshotLater);
529
+ snapshotLater = null;
530
+ void keep({ snapshot: true });
531
+ }
532
+ stopped = true;
533
+ clearTimeout(settle);
534
+ clearTimeout(snapshotLater);
535
+ for (const watcher of watchers) watcher.close();
536
+ },
537
+ };
538
+ },
539
+ };
540
+ }
package/lib/files.mjs CHANGED
@@ -19,8 +19,8 @@ export function readJson(file, fallback = {}) {
19
19
  }
20
20
  }
21
21
 
22
- export function writeJsonAtomic(file, value, mode = 0o600) {
23
- ensureDir(path.dirname(file));
22
+ // Written beside the file and renamed over it, so a reader never sees half of it and a failed write loses nothing.
23
+ function replaceJson(file, value, mode) {
24
24
  const temporary = `${file}.tmp-${process.pid}-${Date.now()}`;
25
25
  fs.writeFileSync(temporary, JSON.stringify(value, null, 2) + "\n", { mode });
26
26
  fs.renameSync(temporary, file);
@@ -29,6 +29,51 @@ export function writeJsonAtomic(file, value, mode = 0o600) {
29
29
  } catch {}
30
30
  }
31
31
 
32
+ export function writeJsonAtomic(file, value, mode = 0o600) {
33
+ ensureDir(path.dirname(file));
34
+ replaceJson(file, value, mode);
35
+ }
36
+
37
+ /**
38
+ * Changes a JSON file Harness shares with the person or their agents (their settings, Harness's own config) without
39
+ * losing anything else in it. `change(current)` returns the whole new value, or null to leave the file as it is. A file
40
+ * that is not there starts empty; one that is there but cannot be read as JSON (a comment in it, no permission) is
41
+ * never taken as empty and written over: this throws, saying why, and the file stays as it was. The file keeps its
42
+ * mode, and a file that is a link (dotfiles kept elsewhere) stays one: what it points to is changed.
43
+ */
44
+ export function updateJson(file, change) {
45
+ let target = file;
46
+ let mode = 0o600;
47
+ let current = {};
48
+ let text = null;
49
+ try {
50
+ target = fs.realpathSync(file);
51
+ mode = fs.statSync(target).mode & 0o777;
52
+ text = fs.readFileSync(target, "utf8");
53
+ } catch (error) {
54
+ if (error.code !== "ENOENT") throw unreadable(file, error.message);
55
+ }
56
+ if (text !== null && text.trim()) {
57
+ try {
58
+ current = JSON.parse(text);
59
+ } catch (error) {
60
+ throw unreadable(file, error.message);
61
+ }
62
+ if (!current || typeof current !== "object" || Array.isArray(current))
63
+ throw unreadable(file, "it is not a JSON object");
64
+ }
65
+ const next = change(current);
66
+ if (next === null || next === undefined) return false;
67
+ fs.mkdirSync(path.dirname(target), { recursive: true });
68
+ replaceJson(target, next, mode);
69
+ return true;
70
+ }
71
+
72
+ const unreadable = (file, why) =>
73
+ new Error(
74
+ `Harness could not read ${file} (${why}), so it left it as it is rather than lose what is in it.`
75
+ );
76
+
32
77
  export function appendLog(file, message) {
33
78
  ensureDir(path.dirname(file));
34
79
  try {
package/lib/gitHost.mjs CHANGED
@@ -24,7 +24,12 @@ export function remoteWeb(remote) {
24
24
  const parsed = new URL(text);
25
25
  if (!["https:", "http:", "ssh:", "git:"].includes(parsed.protocol))
26
26
  return null;
27
- return { host: parsed.hostname, path: parsed.pathname };
27
+ // A web address keeps its port; an ssh port says nothing about where the host's pages are.
28
+ const isWeb = ["https:", "http:"].includes(parsed.protocol);
29
+ return {
30
+ host: isWeb ? parsed.host : parsed.hostname,
31
+ path: parsed.pathname,
32
+ };
28
33
  } catch {
29
34
  return null;
30
35
  }
@@ -41,6 +46,13 @@ export function remoteWeb(remote) {
41
46
  };
42
47
  }
43
48
 
49
+ /** The page where a repository's owner gives someone access; the repository's own page on a host we don't know. */
50
+ export function accessPage(host) {
51
+ if (host.kind === "github") return `${host.web}/settings/access`;
52
+ if (host.kind === "gitlab") return `${host.web}/-/project_members`;
53
+ return host.web;
54
+ }
55
+
44
56
  /** The page that shows a pull request's changes, on the host that has it. */
45
57
  export function changesPage(host, request) {
46
58
  if (host.kind === "gitlab") return `${request.url}/diffs`;
@@ -74,6 +86,7 @@ const FIELDS =
74
86
  // vercel/next.js) and `gh pr view` 347-790 ms (10 runs). Ten seconds is about ten times the slowest; past it the board
75
87
  // says GitHub did not answer rather than waiting on it.
76
88
  const GH_DEADLINE_MS = 10_000;
89
+ const LOGIN = /^[A-Za-z0-9][A-Za-z0-9-]{0,38}$/;
77
90
  const LIST_FRESH_MS = 60_000;
78
91
  const ONE_FRESH_MS = 5 * 60_000;
79
92
 
@@ -90,6 +103,31 @@ const requestOf = (row) => ({
90
103
  updatedAt: row.updatedAt ?? null,
91
104
  });
92
105
 
106
+ /** The GitHub username signed in on this computer through `gh`, or null. */
107
+ export function githubLogin() {
108
+ return new Promise((resolve) => {
109
+ const gh = resolveCommand("gh");
110
+ if (!gh) return resolve(null);
111
+ // `gh api user` took 254-396 ms (10 runs on a Mac, November 2026), inside the deadline above.
112
+ const child = spawn(gh, ["api", "user", "--jq", ".login"], {
113
+ env: { ...process.env, GH_PROMPT_DISABLED: "1", NO_COLOR: "1" },
114
+ stdio: ["ignore", "pipe", "ignore"],
115
+ });
116
+ let out = "";
117
+ const timer = setTimeout(() => child.kill("SIGTERM"), GH_DEADLINE_MS);
118
+ child.stdout.on("data", (chunk) => (out += chunk));
119
+ child.on("error", () => {
120
+ clearTimeout(timer);
121
+ resolve(null);
122
+ });
123
+ child.on("close", (code) => {
124
+ clearTimeout(timer);
125
+ const login = out.trim();
126
+ resolve(code === 0 && LOGIN.test(login) ? login : null);
127
+ });
128
+ });
129
+ }
130
+
93
131
  /**
94
132
  * GitHub's pull requests through `gh`, kept a minute (a single one five) so a surface reading the board every few
95
133
  * seconds asks GitHub at most once a minute. `answer` is how the board says it could not ask.