tryharness 0.7.82 → 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 (216) 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 +193 -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 +57 -2
  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 +2435 -333
  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 +2 -2
  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/onboard.mjs +6 -6
  107. package/lib/originals.mjs +216 -0
  108. package/lib/outsideEvents.mjs +383 -0
  109. package/lib/outsideRuns.mjs +230 -0
  110. package/lib/ownMachines.mjs +674 -256
  111. package/lib/pain.mjs +215 -0
  112. package/lib/pairing.mjs +91 -11
  113. package/lib/paths.mjs +42 -3
  114. package/lib/peerProcess.mjs +21 -7
  115. package/lib/peopleLink.mjs +268 -0
  116. package/lib/personNotices.mjs +3 -2
  117. package/lib/phones.mjs +252 -542
  118. package/lib/placeCards.mjs +282 -0
  119. package/lib/placeChecks.mjs +95 -0
  120. package/lib/placeCommands.mjs +8 -17
  121. package/lib/placeRequests.mjs +152 -0
  122. package/lib/placeStore.mjs +295 -0
  123. package/lib/placeTool.d.ts +12 -0
  124. package/lib/placeTool.js +40 -0
  125. package/lib/places.mjs +63 -14
  126. package/lib/plans.mjs +53 -8
  127. package/lib/presence.mjs +270 -0
  128. package/lib/privateNetwork.d.ts +2 -0
  129. package/lib/privateNetwork.js +93 -0
  130. package/lib/proposals.mjs +300 -0
  131. package/lib/publicFetch.d.ts +32 -0
  132. package/lib/publicFetch.js +248 -0
  133. package/lib/reach.mjs +128 -0
  134. package/lib/rebuildable.mjs +72 -0
  135. package/lib/recall.mjs +216 -0
  136. package/lib/record.mjs +13 -0
  137. package/lib/reflexes.mjs +392 -0
  138. package/lib/relayLimits.mjs +31 -2
  139. package/lib/releaseNotice.mjs +198 -0
  140. package/lib/removeHarness.mjs +15 -4
  141. package/lib/repoLinks.mjs +204 -35
  142. package/lib/runAuthority.mjs +102 -39
  143. package/lib/runBrief.mjs +93 -40
  144. package/lib/runRequests.mjs +52 -14
  145. package/lib/runUsage.mjs +31 -0
  146. package/lib/runWorker.mjs +74 -25
  147. package/lib/runner.mjs +289 -45
  148. package/lib/runtime-install.mjs +37 -8
  149. package/lib/schedules.mjs +171 -47
  150. package/lib/screenWatches.mjs +221 -0
  151. package/lib/sealed.mjs +12 -30
  152. package/lib/sealedThreads.mjs +198 -392
  153. package/lib/secretStore.mjs +178 -0
  154. package/lib/secrets.mjs +11 -0
  155. package/lib/seen.mjs +3 -9
  156. package/lib/selfUpdate.mjs +51 -15
  157. package/lib/senseCall.mjs +1514 -0
  158. package/lib/senseHook.mjs +114 -0
  159. package/lib/senseTools.mjs +1298 -0
  160. package/lib/sessionBriefs.mjs +87 -0
  161. package/lib/sessionControl.mjs +63 -13
  162. package/lib/sessionFiles.mjs +85 -0
  163. package/lib/setupChoices.mjs +12 -3
  164. package/lib/setupMode.mjs +70 -25
  165. package/lib/sharedKeys.mjs +166 -0
  166. package/lib/sleep.mjs +396 -0
  167. package/lib/sources.mjs +306 -0
  168. package/lib/speech.mjs +166 -411
  169. package/lib/spoken.mjs +210 -0
  170. package/lib/steerHook.mjs +3 -1
  171. package/lib/steerQueue.mjs +40 -11
  172. package/lib/store.mjs +323 -130
  173. package/lib/stuck.mjs +85 -7
  174. package/lib/swarm.mjs +157 -49
  175. package/lib/swarmDevices.mjs +25 -85
  176. package/lib/swarmMemory.mjs +93 -9
  177. package/lib/t3.mjs +73 -3
  178. package/lib/taskCommands.mjs +51 -60
  179. package/lib/taskRooms.mjs +30 -4
  180. package/lib/taskRules.json +29 -0
  181. package/lib/taskRules.mjs +21 -0
  182. package/lib/taskRuns.mjs +74 -11
  183. package/lib/team.mjs +2 -1
  184. package/lib/threadActions.mjs +37 -9
  185. package/lib/threadAuthority.mjs +4 -4
  186. package/lib/threadBriefs.mjs +173 -43
  187. package/lib/threadNotes.mjs +320 -0
  188. package/lib/threadRecord.mjs +491 -0
  189. package/lib/threadRuns.mjs +216 -108
  190. package/lib/threadView.mjs +27 -30
  191. package/lib/threadWatches.mjs +1962 -0
  192. package/lib/timeSense.mjs +839 -0
  193. package/lib/tripwires.mjs +454 -0
  194. package/lib/ui.mjs +1 -1
  195. package/lib/vault.mjs +560 -45
  196. package/lib/vaultCommands.mjs +5 -3
  197. package/lib/vaultPeers.mjs +165 -0
  198. package/lib/vaultTools.d.ts +4 -1
  199. package/lib/vaultTools.js +22 -1
  200. package/lib/verdicts.mjs +12 -26
  201. package/lib/versions.mjs +117 -0
  202. package/lib/waitTool.mjs +278 -0
  203. package/lib/wakePicture.mjs +268 -0
  204. package/lib/wakeQueue.mjs +108 -0
  205. package/lib/watchResponses.mjs +533 -0
  206. package/lib/watches.mjs +290 -145
  207. package/lib/windowAsks.mjs +80 -17
  208. package/lib/worktrees.mjs +159 -9
  209. package/npm-shrinkwrap.json +138 -631
  210. package/package.json +7 -6
  211. package/release.json +212 -130
  212. package/lib/callSessions.mjs +0 -51
  213. package/lib/directLink.mjs +0 -349
  214. package/lib/peopleBoard.mjs +0 -131
  215. package/lib/projects.mjs +0 -2917
  216. package/lib/roomChannels.mjs +0 -667
@@ -0,0 +1,166 @@
1
+ import { webcrypto } from "node:crypto";
2
+
3
+ // The computer's twin of src/shared/backupKeys.ts: the person's shared keys as one bundle, sealed to each of their
4
+ // devices. A computer makes them when it is the person's first device (owner, November 14: whichever device comes
5
+ // first, a browser or a computer), and opens its sealed copy to use the account's keys, which are the person's
6
+ // identity toward other people (identityLink.mjs). The bundle's format is the browser's, byte for byte.
7
+
8
+ const { subtle } = webcrypto;
9
+ const ECDH = { name: "ECDH", namedCurve: "P-256" };
10
+ const ECDSA = { name: "ECDSA", namedCurve: "P-256" };
11
+ const KEPT_PREVIOUS = 8;
12
+ const toBase64 = (bytes) => Buffer.from(bytes).toString("base64");
13
+ const fromBase64 = (text) =>
14
+ new Uint8Array(Buffer.from(String(text), "base64"));
15
+
16
+ /**
17
+ * New shared keys: the bundle to seal to each device and the public halves of the account's keys. Given the bundle
18
+ * they replace, the new one carries its keys as previous ones.
19
+ */
20
+ export async function createSharedKeys(replacing) {
21
+ const before = replacing
22
+ ? JSON.parse(new TextDecoder().decode(replacing))
23
+ : null;
24
+ const account = await subtle.generateKey(ECDH, true, ["deriveBits"]);
25
+ const signing = await subtle.generateKey(ECDSA, true, ["sign", "verify"]);
26
+ const accountPublicKey = toBase64(
27
+ new Uint8Array(await subtle.exportKey("raw", account.publicKey))
28
+ );
29
+ const accountSigningPublicKey = toBase64(
30
+ new Uint8Array(await subtle.exportKey("raw", signing.publicKey))
31
+ );
32
+ const bundle = {
33
+ v: 3,
34
+ backupKey: toBase64(webcrypto.getRandomValues(new Uint8Array(32))),
35
+ accountPrivateKey: toBase64(
36
+ new Uint8Array(await subtle.exportKey("pkcs8", account.privateKey))
37
+ ),
38
+ accountPublicKey,
39
+ accountSigningKey: toBase64(
40
+ new Uint8Array(await subtle.exportKey("pkcs8", signing.privateKey))
41
+ ),
42
+ accountSigningPublicKey,
43
+ previousBackupKeys: before
44
+ ? [before.backupKey, ...before.previousBackupKeys].slice(0, KEPT_PREVIOUS)
45
+ : [],
46
+ previousAccountKeys: before
47
+ ? [before.accountPrivateKey, ...before.previousAccountKeys].slice(
48
+ 0,
49
+ KEPT_PREVIOUS
50
+ )
51
+ : [],
52
+ };
53
+ return {
54
+ bundle: new TextEncoder().encode(JSON.stringify(bundle)),
55
+ accountPublicKey,
56
+ accountSigningPublicKey,
57
+ };
58
+ }
59
+
60
+ // An ECDH private key's public half, raw, from the private key itself (an earlier key keeps only its private half).
61
+ async function publicOf(pkcs8) {
62
+ const key = await subtle.importKey("pkcs8", fromBase64(pkcs8), ECDH, true, [
63
+ "deriveBits",
64
+ ]);
65
+ const jwk = await subtle.exportKey("jwk", key);
66
+ const point = new Uint8Array(65);
67
+ point[0] = 4;
68
+ point.set(Buffer.from(jwk.x, "base64url"), 1);
69
+ point.set(Buffer.from(jwk.y, "base64url"), 33);
70
+ return toBase64(point);
71
+ }
72
+
73
+ const importAccountKey = (pkcs8) =>
74
+ subtle.importKey("pkcs8", fromBase64(pkcs8), ECDH, false, ["deriveBits"]);
75
+
76
+ /**
77
+ * The person's identity from their shared keys, as keys this computer uses but never exports: the account's ECDH key
78
+ * and signing key, the signing key's public half when the bundle carries it (`accountSigningKeyPublic`, else null:
79
+ * the device list holds it), and the earlier account keys, newest first, with their public halves.
80
+ */
81
+ export async function openIdentity(bundleBytes) {
82
+ const bundle = JSON.parse(new TextDecoder().decode(bundleBytes));
83
+ return {
84
+ publicKey: bundle.accountPublicKey,
85
+ signingKey: bundle.accountSigningPublicKey ?? null,
86
+ privateKey: await importAccountKey(bundle.accountPrivateKey),
87
+ signingPrivateKey: await subtle.importKey(
88
+ "pkcs8",
89
+ fromBase64(bundle.accountSigningKey),
90
+ ECDSA,
91
+ false,
92
+ ["sign"]
93
+ ),
94
+ previous: await Promise.all(
95
+ (bundle.previousAccountKeys ?? []).map(async (pkcs8) => ({
96
+ publicKey: await publicOf(pkcs8),
97
+ privateKey: await importAccountKey(pkcs8),
98
+ }))
99
+ ),
100
+ };
101
+ }
102
+
103
+ // ── Recovery code (src/shared/backupKeys.ts) ──────────────────────────────────────────────────────────────────────
104
+
105
+ const ALPHABET = "0123456789ABCDEFGHJKMNPQRSTVWXYZ";
106
+ const RECOVERY_INFO = new TextEncoder().encode("harness backup recovery v1");
107
+
108
+ export function createRecoveryCode() {
109
+ const bytes = webcrypto.getRandomValues(new Uint8Array(16));
110
+ let bits = 0;
111
+ let value = 0;
112
+ let out = "";
113
+ for (const byte of bytes) {
114
+ value = (value << 8) | byte;
115
+ bits += 8;
116
+ while (bits >= 5) {
117
+ out += ALPHABET[(value >>> (bits - 5)) & 31];
118
+ bits -= 5;
119
+ }
120
+ }
121
+ if (bits > 0) out += ALPHABET[(value << (5 - bits)) & 31];
122
+ return out.match(/.{1,4}/g).join("-");
123
+ }
124
+
125
+ const normalizeRecoveryCode = (typed) =>
126
+ String(typed)
127
+ .toUpperCase()
128
+ .replace(/[\s-]/g, "")
129
+ .replace(/[IL]/g, "1")
130
+ .replace(/O/g, "0");
131
+
132
+ async function recoveryKey(code) {
133
+ const material = await subtle.importKey(
134
+ "raw",
135
+ new TextEncoder().encode(normalizeRecoveryCode(code)),
136
+ "HKDF",
137
+ false,
138
+ ["deriveKey"]
139
+ );
140
+ return subtle.deriveKey(
141
+ {
142
+ name: "HKDF",
143
+ hash: "SHA-256",
144
+ salt: new Uint8Array(0),
145
+ info: RECOVERY_INFO,
146
+ },
147
+ material,
148
+ { name: "AES-GCM", length: 256 },
149
+ false,
150
+ ["encrypt", "decrypt"]
151
+ );
152
+ }
153
+
154
+ export async function sealWithRecoveryCode(bundle, code) {
155
+ const iv = webcrypto.getRandomValues(new Uint8Array(12));
156
+ const ct = await subtle.encrypt(
157
+ { name: "AES-GCM", iv },
158
+ await recoveryKey(code),
159
+ bundle
160
+ );
161
+ return JSON.stringify({
162
+ v: 1,
163
+ iv: toBase64(iv),
164
+ ct: toBase64(new Uint8Array(ct)),
165
+ });
166
+ }
package/lib/sleep.mjs ADDED
@@ -0,0 +1,396 @@
1
+ // Sleep (docs/senses-plan.md S8.1): each computer folds its own log before the log forgets it (30 days, events.mjs), so
2
+ // what its days are usually like outlives the happenings themselves. Code does what code can, and writes it as facts
3
+ // every agent reads (facts.mjs):
4
+ // - `sleep.usual`: for each kind of happening, the middle half of its daily counts over the days folded, with the
5
+ // median, and on how many days it was seen;
6
+ // - `sleep.follows`: what tends to follow what: each happening counted against the one that caused it (the log keeps
7
+ // the cause), with the share of the first kind that led to the second;
8
+ // - `sleep.ignored`: a watch that told the person something and fired again before they wrote in that thread.
9
+ // A model pass then says, in a few plain sentences, what the computer's days are like (`sleep.summary`). It runs only on
10
+ // the person's own computer, with the local model there (owner, November 15: "local model runs the passes if its able
11
+ // to"), and is kept only when code finds every number and kind in it in the facts it was given.
12
+ //
13
+ // What is folded is counted by the log's own numbers: every happening once, up to yesterday each day, and everything
14
+ // before a happening the log is about to forget.
15
+
16
+ export const SLEEP_TABLES = `
17
+ create table if not exists board_log_days (
18
+ day text not null,
19
+ label text not null,
20
+ n integer not null,
21
+ primary key (day, label)
22
+ );
23
+ create table if not exists board_log_follows (
24
+ first_kind text not null,
25
+ next_kind text not null,
26
+ n integer not null,
27
+ primary key (first_kind, next_kind)
28
+ );
29
+ `;
30
+
31
+ // What is said in a summary and kept in a fact, at most: a few lines, never a page.
32
+ const MOST_USUAL = 12;
33
+ const MOST_FOLLOWS = 10;
34
+ const MOST_SENTENCES = 5;
35
+ const SENTENCE_CHARS = 200;
36
+
37
+ /** A happening's kind as the folded facts name it. */
38
+ export const labelOf = (happening) => `${happening.source}: ${happening.kind}`;
39
+
40
+ /** The day a happening fell on, on this computer's clock. */
41
+ export function dayOf(at) {
42
+ const when = new Date(at);
43
+ const pad = (n) => String(n).padStart(2, "0");
44
+ return `${when.getFullYear()}-${pad(when.getMonth() + 1)}-${pad(when.getDate())}`;
45
+ }
46
+
47
+ /**
48
+ * Folds happenings into counts: each day's count of each kind, and each kind counted against the kind that caused it.
49
+ * `causeOf(seq)` is the happening a cause number names, or null when the log no longer has it.
50
+ */
51
+ export function foldHappenings(happenings, causeOf) {
52
+ const days = new Map();
53
+ const follows = new Map();
54
+ for (const happening of happenings) {
55
+ const label = labelOf(happening);
56
+ const day = `${dayOf(happening.at)}\u0000${label}`;
57
+ days.set(day, (days.get(day) ?? 0) + 1);
58
+ const cause = happening.cause ? causeOf(happening.cause) : null;
59
+ if (!cause) continue;
60
+ const pair = `${labelOf(cause)}\u0000${label}`;
61
+ follows.set(pair, (follows.get(pair) ?? 0) + 1);
62
+ }
63
+ return {
64
+ days: [...days].map(([key, n]) => {
65
+ const [day, label] = key.split("\u0000");
66
+ return { day, label, n };
67
+ }),
68
+ follows: [...follows].map(([key, n]) => {
69
+ const [after, then] = key.split("\u0000");
70
+ return { after, then, n };
71
+ }),
72
+ };
73
+ }
74
+
75
+ const quartile = (sorted, q) =>
76
+ sorted[Math.min(sorted.length - 1, Math.floor((sorted.length - 1) * q))];
77
+
78
+ /**
79
+ * The facts code can say from folded counts: each kind's usual day (the middle half of its daily counts over every day
80
+ * folded, a day without it counting as none), and what tends to follow what.
81
+ */
82
+ export function factsFrom({ days, follows }) {
83
+ const allDays = [...new Set(days.map((row) => row.day))].sort();
84
+ const byLabel = new Map();
85
+ for (const row of days) {
86
+ const counts = byLabel.get(row.label) ?? new Map();
87
+ counts.set(row.day, (counts.get(row.day) ?? 0) + row.n);
88
+ byLabel.set(row.label, counts);
89
+ }
90
+ const usual = [...byLabel]
91
+ .map(([label, counts]) => {
92
+ const daily = allDays
93
+ .map((day) => counts.get(day) ?? 0)
94
+ .sort((a, b) => a - b);
95
+ return {
96
+ kind: label,
97
+ low: quartile(daily, 0.25),
98
+ median: quartile(daily, 0.5),
99
+ high: quartile(daily, 0.75),
100
+ seenOn: counts.size,
101
+ of: allDays.length,
102
+ };
103
+ })
104
+ .sort((a, b) => b.median - a.median || b.seenOn - a.seenOn)
105
+ .slice(0, MOST_USUAL);
106
+ const totals = new Map();
107
+ for (const row of days)
108
+ totals.set(row.label, (totals.get(row.label) ?? 0) + row.n);
109
+ const led = new Map();
110
+ for (const row of follows)
111
+ led.set(row.after, (led.get(row.after) ?? 0) + row.n);
112
+ const followed = follows
113
+ .filter((row) => row.after !== row.then)
114
+ .map((row) => ({
115
+ after: row.after,
116
+ then: row.then,
117
+ times: row.n,
118
+ percent: Math.round((100 * row.n) / Math.max(1, led.get(row.after) ?? 0)),
119
+ }))
120
+ .sort((a, b) => b.times - a.times)
121
+ .slice(0, MOST_FOLLOWS);
122
+ return { days: allDays.length, usual, follows: followed };
123
+ }
124
+
125
+ /** What the local model is asked: the facts, and to say them in a few sentences with nothing added. */
126
+ export const SUMMARY_ASK = `You are given what code counted in one computer's log of an AI agent swarm's work. Say what this computer's days are usually like in at most ${MOST_SENTENCES} short plain sentences. Use only the facts given: every number you write must be one of the numbers in them, and name kinds of happening as they are written there. Do not guess causes or add advice. Answer with JSON only: {"sentences": ["..."]}`;
127
+
128
+ /** The facts as the model reads them: short, and only what it may say. */
129
+ export const summaryInput = (facts, ignored = []) => ({
130
+ days: facts.days,
131
+ usual: facts.usual.map(({ kind, low, median, high, seenOn }) => ({
132
+ kind,
133
+ usual_per_day: `${low} to ${high}`,
134
+ median,
135
+ days_seen: seenOn,
136
+ })),
137
+ follows: facts.follows.map(({ after, then, times, percent }) => ({
138
+ after,
139
+ then,
140
+ times,
141
+ percent,
142
+ })),
143
+ ...(ignored.length ? { let_pass: ignored } : {}),
144
+ });
145
+
146
+ /** Every number in a text, as written. */
147
+ const numbersIn = (text) =>
148
+ [...String(text).matchAll(/\d+(?:\.\d+)?/g)].map((match) => match[0]);
149
+
150
+ /**
151
+ * The model's answer, held to the facts: well-formed, a few short sentences, and every number in it one the facts
152
+ * hold. `{ sentences }`, or `{ error }` saying what did not hold.
153
+ */
154
+ export function checkSummary(answer, input) {
155
+ let parsed = answer;
156
+ if (typeof answer === "string") {
157
+ const json = answer.slice(answer.indexOf("{"), answer.lastIndexOf("}") + 1);
158
+ try {
159
+ parsed = JSON.parse(json);
160
+ } catch {
161
+ return { error: "not JSON" };
162
+ }
163
+ }
164
+ const sentences = Array.isArray(parsed?.sentences)
165
+ ? parsed.sentences.map((each) => String(each).trim()).filter(Boolean)
166
+ : [];
167
+ if (!sentences.length) return { error: "no sentences" };
168
+ if (sentences.length > MOST_SENTENCES)
169
+ return { error: `${sentences.length} sentences` };
170
+ if (sentences.some((each) => each.length > SENTENCE_CHARS))
171
+ return { error: "a sentence too long" };
172
+ const known = new Set(numbersIn(JSON.stringify(input)));
173
+ const invented = sentences.flatMap(numbersIn).filter((n) => !known.has(n));
174
+ if (invented.length)
175
+ return {
176
+ error: `numbers not in the facts: ${[...new Set(invented)].join(", ")}`,
177
+ };
178
+ // Each number belongs to the kind it is said of: a sentence with a number names the who and the what of a fact that
179
+ // holds that number (a right number on the wrong agent is the mistake the measurement found).
180
+ const facts = [
181
+ ...(input.usual ?? []).map((row) => ({
182
+ kind: row.kind,
183
+ numbers: numbersIn(JSON.stringify(row)),
184
+ })),
185
+ ...(input.follows ?? []).map((row) => ({
186
+ kind: `${row.after} ${row.then}`,
187
+ numbers: numbersIn(JSON.stringify(row)),
188
+ })),
189
+ ];
190
+ const wordsOf = (kind) =>
191
+ String(kind)
192
+ .toLowerCase()
193
+ .replace(/claude-code/g, "claude code")
194
+ .split(/[^a-z]+/)
195
+ .filter(
196
+ (word) => word.length > 2 && !["wrote", "the", "and"].includes(word)
197
+ );
198
+ const named = (sentence, kind) => {
199
+ const lower = sentence.toLowerCase();
200
+ return wordsOf(kind).every((word) => lower.includes(word));
201
+ };
202
+ for (const sentence of sentences) {
203
+ const numbers = numbersIn(sentence).filter((n) => n !== String(input.days));
204
+ if (!numbers.length) continue;
205
+ const owner = facts.find(
206
+ (fact) =>
207
+ named(sentence, fact.kind) &&
208
+ numbers.every((n) => fact.numbers.includes(n))
209
+ );
210
+ if (!owner)
211
+ return { error: `a number said of the wrong kind: "${sentence}"` };
212
+ }
213
+ return { sentences };
214
+ }
215
+
216
+ const thousands = (n) => Number(n).toLocaleString("en-US");
217
+
218
+ /**
219
+ * What the facts say, in plain sentences written by code (the summary). The local fine-tune was measured for this and
220
+ * did not hold: it restated the table, said nothing of what follows what, and put true numbers on the wrong agent in 7
221
+ * of 20 windows of the person's own month even held to a schema (.harness-runs/senses-sleep/20261115-real-log).
222
+ */
223
+ export function sentencesOf(facts, ignored = []) {
224
+ const usual = facts.usual
225
+ .slice(0, 3)
226
+ .map(
227
+ (row) =>
228
+ `${row.kind}: ${thousands(row.low)} to ${thousands(row.high)} a day, usually ${thousands(row.median)}, seen on ${row.seenOn} of ${row.of} days.`
229
+ );
230
+ const follows = facts.follows
231
+ .slice(0, 2)
232
+ .map(
233
+ (row) =>
234
+ `After ${row.after}, ${row.then} came next ${row.percent}% of the time (${thousands(row.times)} times).`
235
+ );
236
+ const passed = ignored
237
+ .filter((row) => row.letPass > 0)
238
+ .slice(0, 1)
239
+ .map(
240
+ (row) =>
241
+ `The person let ${row.watch} pass ${row.letPass} of the ${row.told} times it told them.`
242
+ );
243
+ return [...usual, ...follows, ...passed].slice(0, MOST_SENTENCES);
244
+ }
245
+
246
+ /**
247
+ * The fold on this computer. `fold(throughSeq)` folds every own happening not folded yet, up to `throughSeq` (all up
248
+ * to yesterday when not given), then writes the facts; the log calls it before it forgets (events.mjs onForget), the
249
+ * daemon as it starts (a computer that was off at night), and the daily cleanup. Returns how many it folded.
250
+ */
251
+ export function createSleep({
252
+ store,
253
+ facts,
254
+ log = () => {},
255
+ now = () => Date.now(),
256
+ }) {
257
+ const db = store.db;
258
+ db.exec(SLEEP_TABLES);
259
+ const FOLDED = "sleep-folded-seq";
260
+ const PAGE = 5_000;
261
+
262
+ const startOfToday = () => {
263
+ const today = new Date(now());
264
+ today.setHours(0, 0, 0, 0);
265
+ return today.toISOString();
266
+ };
267
+
268
+ const causeOf = (seq) => {
269
+ const row = db.get(
270
+ "select seq, at, source, kind from board_events where seq = ?",
271
+ [seq]
272
+ );
273
+ return row ?? null;
274
+ };
275
+
276
+ const add = ({ days, follows }) => {
277
+ for (const row of days)
278
+ db.run(
279
+ "insert into board_log_days(day, label, n) values(?, ?, ?) on conflict(day, label) do update set n = n + excluded.n",
280
+ [row.day, row.label, row.n]
281
+ );
282
+ for (const row of follows)
283
+ db.run(
284
+ "insert into board_log_follows(first_kind, next_kind, n) values(?, ?, ?) on conflict(first_kind, next_kind) do update set n = n + excluded.n",
285
+ [row.after, row.then, row.n]
286
+ );
287
+ };
288
+
289
+ /** A watch that told the person and fired again before they wrote in its thread, counted per watch. */
290
+ const ignored = () => {
291
+ let fires;
292
+ try {
293
+ fires = db.all(
294
+ "select f.watch, f.thread, f.at, w.source from board_watch_fires f left join board_watches w on w.id = f.watch where f.outcome = 'told the person' and f.edge = 'tripped' order by f.watch, f.at"
295
+ );
296
+ } catch {
297
+ return [];
298
+ }
299
+ const byWatch = new Map();
300
+ for (const fire of fires) {
301
+ const list = byWatch.get(fire.watch) ?? [];
302
+ list.push(fire);
303
+ byWatch.set(fire.watch, list);
304
+ }
305
+ const rows = [];
306
+ for (const [watch, list] of byWatch) {
307
+ let letPass = 0;
308
+ for (let i = 1; i < list.length; i++) {
309
+ const wrote = list[i].thread
310
+ ? db.get(
311
+ "select 1 from board_contributions where task_id = ? and author = 'user' and created_at > ? and created_at < ? limit 1",
312
+ [list[i].thread, list[i - 1].at, list[i].at]
313
+ )
314
+ : null;
315
+ if (!wrote) letPass += 1;
316
+ }
317
+ rows.push({
318
+ id: watch,
319
+ watch: `watch ${String(watch).slice(0, 8)}`,
320
+ told: list.length,
321
+ letPass,
322
+ });
323
+ }
324
+ return rows.sort((a, b) => b.letPass - a.letPass).slice(0, MOST_FOLLOWS);
325
+ };
326
+
327
+ const writeFacts = () => {
328
+ const folded = factsFrom({
329
+ days: db.all("select day, label, n from board_log_days"),
330
+ follows: db
331
+ .all("select first_kind, next_kind, n from board_log_follows")
332
+ .map((row) => ({
333
+ after: row.first_kind,
334
+ then: row.next_kind,
335
+ n: row.n,
336
+ })),
337
+ });
338
+ if (!folded.days) return;
339
+ const passed = ignored();
340
+ facts.set(
341
+ "sleep.usual",
342
+ { days: folded.days, kinds: folded.usual },
343
+ { source: "sleep" }
344
+ );
345
+ facts.set("sleep.follows", folded.follows, { source: "sleep" });
346
+ facts.set("sleep.ignored", passed, { source: "sleep" });
347
+ facts.set("sleep.summary", sentencesOf(folded, passed), {
348
+ source: "sleep",
349
+ });
350
+ };
351
+
352
+ const fold = (throughSeq = null) => {
353
+ const from = Number(store.meta(FOLDED) || 0);
354
+ const through =
355
+ throughSeq ??
356
+ db.get(
357
+ "select max(seq) as seq from board_events where at < ? and machine is null",
358
+ [startOfToday()]
359
+ )?.seq ??
360
+ 0;
361
+ if (!(through > from)) {
362
+ writeSafely();
363
+ return 0;
364
+ }
365
+ let after = from;
366
+ let count = 0;
367
+ for (;;) {
368
+ const rows = db.all(
369
+ "select seq, at, source, kind, cause from board_events where seq > ? and seq <= ? and machine is null order by seq limit ?",
370
+ [after, through, PAGE]
371
+ );
372
+ if (!rows.length) break;
373
+ add(foldHappenings(rows, causeOf));
374
+ count += rows.length;
375
+ after = rows.at(-1).seq;
376
+ if (rows.length < PAGE) break;
377
+ }
378
+ store.meta(FOLDED, String(through));
379
+ writeSafely();
380
+ return count;
381
+ };
382
+ // The facts again after each fold: what the person let pass changes without a happening to fold.
383
+ const writeSafely = () => {
384
+ try {
385
+ writeFacts();
386
+ } catch (error) {
387
+ log(`sleep: the facts were not written: ${error.message}`);
388
+ }
389
+ };
390
+
391
+ return {
392
+ fold,
393
+ /** Each watch that told the person, how often, and how often they let it pass (proposals.mjs). */
394
+ letPass: () => ignored().map((row) => ({ ...row, label: row.watch })),
395
+ };
396
+ }