tryharness 0.7.67 → 0.7.69

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 (54) hide show
  1. package/lib/boardFileCommands.mjs +5 -7
  2. package/lib/boardFiles.mjs +5 -0
  3. package/lib/boardProtocol.json +50 -64
  4. package/lib/boardWaits.mjs +6 -0
  5. package/lib/cards.mjs +13 -1
  6. package/lib/comfyExecution.mjs +545 -0
  7. package/lib/context.mjs +34 -20
  8. package/lib/contextWorker.mjs +199 -0
  9. package/lib/coordinator.mjs +224 -22
  10. package/lib/daemon.mjs +196 -14
  11. package/lib/dispatchContract.json +313 -0
  12. package/lib/dispatchTools.js +87 -0
  13. package/lib/dispatches.mjs +975 -0
  14. package/lib/environment.mjs +54 -69
  15. package/lib/files.mjs +35 -0
  16. package/lib/frames.mjs +5 -9
  17. package/lib/goalCommands.mjs +13 -10
  18. package/lib/kept.mjs +131 -0
  19. package/lib/landed.mjs +1 -34
  20. package/lib/library.mjs +18 -11
  21. package/lib/live.mjs +30 -11
  22. package/lib/localAgentAsk.mjs +27 -4
  23. package/lib/localStack.mjs +17 -13
  24. package/lib/machineRoutes.mjs +5 -0
  25. package/lib/machineRuns.mjs +2 -1
  26. package/lib/mcp-stdio.mjs +42 -1
  27. package/lib/openHere.mjs +36 -0
  28. package/lib/openRequests.mjs +56 -0
  29. package/lib/ownMachines.mjs +232 -24
  30. package/lib/phones.mjs +29 -4
  31. package/lib/places.mjs +44 -11
  32. package/lib/portCalls.mjs +54 -0
  33. package/lib/promptDecider.mjs +471 -0
  34. package/lib/promptFlow.mjs +562 -0
  35. package/lib/promptScopes.mjs +670 -0
  36. package/lib/provenance.mjs +3 -2
  37. package/lib/runAuthority.mjs +14 -2
  38. package/lib/runBrief.mjs +2 -2
  39. package/lib/runWorker.mjs +25 -5
  40. package/lib/runner.mjs +62 -6
  41. package/lib/sealed.mjs +37 -0
  42. package/lib/sessionControl.mjs +47 -14
  43. package/lib/sessionIndex.mjs +11 -3
  44. package/lib/store.mjs +362 -40
  45. package/lib/swarm.mjs +85 -34
  46. package/lib/swarmMemory.mjs +39 -16
  47. package/lib/taskCommands.mjs +125 -1
  48. package/lib/team.json +10 -0
  49. package/lib/team.mjs +287 -26
  50. package/lib/threadBriefs.mjs +43 -31
  51. package/lib/threadRuns.mjs +47 -3
  52. package/npm-shrinkwrap.json +14 -14
  53. package/package.json +4 -4
  54. package/release.json +55 -43
package/lib/store.mjs CHANGED
@@ -7,6 +7,9 @@ import { BOOK_TABLES } from "./book.mjs";
7
7
 
8
8
  const SCHEMA_VERSION = 11;
9
9
  const INDEX_FORMAT_VERSION = 2;
10
+ // How long agents' board-call times wait in memory before they are written together (touchAgent).
11
+ const SEEN_WRITE_MS = 5_000;
12
+ const PHONE_SEEN_WRITE_MS = 30_000;
10
13
  const { Database } = sqliteWasm;
11
14
 
12
15
  function bindings(values) {
@@ -48,6 +51,23 @@ const MEMORY_SELECT = `select c.id, c.task_id, c.seq, c.kind, c.author, c.text,
48
51
  const MEMORY_JOINS = `join board_tasks t on t.id = c.task_id left join board_tasks p on p.id = t.parent_id
49
52
  left join board_memory_marks m on m.contribution_id = c.id`;
50
53
  const MEMORY_WHERE = `c.kind in (${MEMORY_KINDS.map((kind) => `'${kind}'`).join(", ")}) and m.contribution_id is null`;
54
+ // Limits a memory query to these threads (goal ids): a post in one, or in one of its jobs. None given: every thread.
55
+ // The ids are bound as @thread0, @thread1, ...
56
+ const inThreads = (threads) => {
57
+ if (!threads) return { sql: "", params: {} };
58
+ const params = Object.fromEntries(
59
+ [...threads].map((id, i) => [`thread${i}`, String(id)])
60
+ );
61
+ const list = Object.keys(params)
62
+ .map((name) => `@${name}`)
63
+ .join(", ");
64
+ return {
65
+ sql: list
66
+ ? ` and (c.task_id in (${list}) or t.parent_id in (${list}))`
67
+ : " and 0",
68
+ params,
69
+ };
70
+ };
51
71
  const PURGED = "[deleted at the person's request]";
52
72
  // A full-text query for any of a text's words longer than two letters, or null with none.
53
73
  const anyWordOf = (text) => {
@@ -78,8 +98,10 @@ export function openStore(file) {
78
98
  const db = new Database(file);
79
99
  // The daemon is the database's single writer. DELETE mode is portable across the
80
100
  // WASM VFS on every supported Node LTS line; no native addon or ABI is involved.
101
+ // Every page the cache misses is a synchronous read on the daemon's one thread; 32 MB (SQLite's default is 2) halved
102
+ // the time of the buddy's and agents' usual reads on a copy of the owner's 256 MB database (October 28).
81
103
  db.exec(
82
- "pragma journal_mode = DELETE; pragma synchronous = NORMAL; pragma busy_timeout = 5000;"
104
+ "pragma journal_mode = DELETE; pragma synchronous = NORMAL; pragma busy_timeout = 5000; pragma cache_size = -32768;"
83
105
  );
84
106
  db.exec(`
85
107
  create table if not exists schema_info (version integer not null);
@@ -171,6 +193,12 @@ export function openStore(file) {
171
193
  key text primary key,
172
194
  value text not null
173
195
  );
196
+ create table if not exists board_dispatch_advisories (
197
+ seq integer primary key autoincrement,
198
+ task_id text not null,
199
+ value text not null
200
+ );
201
+ create index if not exists dispatch_advisories_task on board_dispatch_advisories(task_id,seq);
174
202
  create table if not exists board_agents (
175
203
  agent text primary key,
176
204
  last_seen_at text not null
@@ -643,6 +671,52 @@ export function openStore(file) {
643
671
  };
644
672
 
645
673
  const roomPostListeners = [];
674
+ const publishRoomPost = (goalId, post) => {
675
+ for (const listener of roomPostListeners)
676
+ try {
677
+ listener(goalId, post);
678
+ } catch {}
679
+ };
680
+
681
+ // When each agent last called the board, by computer. The buddy, every agent and the other computers call several
682
+ // times a second, and each write waits for the disk (4 s in every 50 on the owner's daemon, October 28), so the times
683
+ // are kept here, answered from here, and written together within SEEN_WRITE_MS. A crash loses that much of them: an
684
+ // agent may hear again what was new in its last few seconds.
685
+ const seenNow = new Map();
686
+ let seenWrite = null;
687
+ const seenKey = (agent, machine) => `${agent}\0${machine ?? ""}`;
688
+ const writeSeen = () => {
689
+ clearTimeout(seenWrite);
690
+ seenWrite = null;
691
+ if (!seenNow.size) return;
692
+ const rows = [...seenNow.values()];
693
+ db.exec("begin");
694
+ try {
695
+ for (const { agent, machine, at } of rows)
696
+ if (machine)
697
+ execute(
698
+ "run",
699
+ "insert into board_agent_computers(agent, machine, last_seen_at) values(?, ?, ?) on conflict(agent, machine) do update set last_seen_at = excluded.last_seen_at",
700
+ agent,
701
+ machine,
702
+ at
703
+ );
704
+ else
705
+ execute(
706
+ "run",
707
+ "insert into board_agents(agent, last_seen_at) values(?, ?) on conflict(agent) do update set last_seen_at = excluded.last_seen_at",
708
+ agent,
709
+ at
710
+ );
711
+ db.exec("commit");
712
+ seenNow.clear();
713
+ } catch (error) {
714
+ db.exec("rollback");
715
+ throw error;
716
+ }
717
+ };
718
+ // A device's last call, written at most this often: it is shown as "last seen", never decided on.
719
+ const phoneSeenAt = new Map();
646
720
 
647
721
  return {
648
722
  db,
@@ -1115,14 +1189,16 @@ export function openStore(file) {
1115
1189
  workspaces,
1116
1190
  daily_cap: row ? Number(row.daily_cap) : DEFAULT_DAILY_RUNS,
1117
1191
  set_at: row?.set_at || null,
1118
- runs_today: Number(
1119
- execute(
1120
- "get",
1121
- "select count(*) as n from board_tasks where target_agent = ? and run_authorized_by = 'standing' and run_authorized_at >= ?",
1122
- agent,
1123
- since
1124
- ).n
1125
- ),
1192
+ runs_today:
1193
+ Number(this.meta(`prompt-quota:${since}:${agent}`) || "0") +
1194
+ Number(
1195
+ execute(
1196
+ "get",
1197
+ "select count(*) as n from board_tasks where target_agent = ? and run_authorized_by = 'standing' and run_authorized_at >= ?",
1198
+ agent,
1199
+ since
1200
+ ).n
1201
+ ),
1126
1202
  };
1127
1203
  });
1128
1204
  },
@@ -1139,6 +1215,141 @@ export function openStore(file) {
1139
1215
  String(value)
1140
1216
  );
1141
1217
  },
1218
+ // Proposal identity, task and grant must appear together, even after a crash.
1219
+ dispatchTransaction(operation) {
1220
+ db.exec("begin immediate");
1221
+ try {
1222
+ const result = operation();
1223
+ db.exec("commit");
1224
+ return result;
1225
+ } catch (error) {
1226
+ if (db.inTransaction) db.exec("rollback");
1227
+ throw error;
1228
+ }
1229
+ },
1230
+ appendDispatchAdvisory(id, value) {
1231
+ if (this.meta(`dispatch-advisories:${id}`)) this.dispatchAdvisories(id);
1232
+ execute(
1233
+ "run",
1234
+ "insert into board_dispatch_advisories(task_id,value) values(?,?)",
1235
+ id,
1236
+ JSON.stringify(value)
1237
+ );
1238
+ },
1239
+ dispatchAdvisories(id, before = null) {
1240
+ // Migrate the earlier unbounded meta array without losing its audit records.
1241
+ const key = `dispatch-advisories:${id}`;
1242
+ if (this.meta(key))
1243
+ this.dispatchTransaction(() => {
1244
+ for (const record of JSON.parse(this.meta(key) || "[]"))
1245
+ execute(
1246
+ "run",
1247
+ "insert into board_dispatch_advisories(task_id,value) values(?,?)",
1248
+ id,
1249
+ JSON.stringify(record)
1250
+ );
1251
+ execute("run", "delete from board_meta where key = ?", key);
1252
+ });
1253
+ const rows = execute(
1254
+ "all",
1255
+ "select seq,value from board_dispatch_advisories where task_id = ? and (? is null or seq < ?) order by seq desc limit 32",
1256
+ id,
1257
+ before,
1258
+ before
1259
+ );
1260
+ return {
1261
+ records: rows.map((row) => JSON.parse(row.value)),
1262
+ next_before: rows.length === 32 ? rows.at(-1).seq : null,
1263
+ };
1264
+ },
1265
+ // The task row is the durable execution outbox. Reserve its sole approved
1266
+ // start and authorize that same row atomically; a retry cannot create a task.
1267
+ commitTaskDispatch({
1268
+ id,
1269
+ expectedGrant,
1270
+ expectedVersion,
1271
+ nextGrant,
1272
+ targetAgent = null,
1273
+ scopeRef = null,
1274
+ expectedScope = null,
1275
+ nextScope = null,
1276
+ quota = null,
1277
+ }) {
1278
+ db.exec("begin immediate");
1279
+ try {
1280
+ const task = this.getTask(id);
1281
+ const key = `dispatch-grant:${id}`;
1282
+ const rule = quota
1283
+ ? this.standing([quota.agent], quota.period)[0]
1284
+ : null;
1285
+ if (
1286
+ this.meta(key) !== expectedGrant ||
1287
+ task?.version !== expectedVersion ||
1288
+ task.status !== "open" ||
1289
+ task.run_authorized_at ||
1290
+ (scopeRef &&
1291
+ this.meta(`dispatch-scope:${scopeRef}`) !== expectedScope) ||
1292
+ (quota &&
1293
+ (quota.remaining < 1 ||
1294
+ this.meta(quota.key) !== quota.expected ||
1295
+ rule.daily_cap !== quota.limit ||
1296
+ rule.set_at !== quota.rule_epoch ||
1297
+ rule.mode !== quota.rule_mode ||
1298
+ rule.runs_today >= rule.daily_cap))
1299
+ ) {
1300
+ db.exec("commit");
1301
+ return false;
1302
+ }
1303
+ if (targetAgent)
1304
+ execute(
1305
+ "run",
1306
+ "update board_tasks set target_agent = ?, holder = ? where id = ?",
1307
+ targetAgent,
1308
+ targetAgent,
1309
+ id
1310
+ );
1311
+ const authorized = this.authorizeRun(id, "dispatch");
1312
+ if (!authorized.ok) {
1313
+ db.exec("rollback");
1314
+ return false;
1315
+ }
1316
+ this.meta(key, nextGrant);
1317
+ if (scopeRef) this.meta(`dispatch-scope:${scopeRef}`, nextScope);
1318
+ if (quota) this.meta(quota.key, quota.next);
1319
+ db.exec("commit");
1320
+ return true;
1321
+ } catch (error) {
1322
+ if (db.inTransaction) db.exec("rollback");
1323
+ throw error;
1324
+ }
1325
+ },
1326
+ replaceDispatchGrant({ id, expectedGrant, nextGrant }) {
1327
+ return (
1328
+ execute(
1329
+ "run",
1330
+ "update board_meta set value = ? where key = ? and value = ?",
1331
+ nextGrant,
1332
+ `dispatch-grant:${id}`,
1333
+ expectedGrant
1334
+ ).changes === 1
1335
+ );
1336
+ },
1337
+ failUnstartedDispatch(id, reason) {
1338
+ const now = new Date().toISOString();
1339
+ return (
1340
+ execute(
1341
+ "run",
1342
+ `update board_tasks set status = 'failed', failure = 'start', result = ?,
1343
+ holder = null, reported_at = ?, updated_at = ?, version = version + 1
1344
+ where id = ? and origin_agent = 'user' and status = 'open'
1345
+ and run_authorized_at is null and claimed_by is null`,
1346
+ reason,
1347
+ now,
1348
+ now,
1349
+ id
1350
+ ).changes === 1
1351
+ );
1352
+ },
1142
1353
  // The person's choices about what each agent is good at (specialties.mjs owns the rules; these keep the rows).
1143
1354
  specialtyChoices(agent) {
1144
1355
  return execute(
@@ -1469,11 +1680,7 @@ export function openStore(file) {
1469
1680
  );
1470
1681
  const made = post ? { ...post, mentions } : null;
1471
1682
  // Whoever follows a room's posts (a shared project carries them to the other side) hears each one as it is made.
1472
- if (made)
1473
- for (const listener of roomPostListeners)
1474
- try {
1475
- listener(goalId, made);
1476
- } catch {}
1683
+ if (made) publishRoomPost(goalId, made);
1477
1684
  return made;
1478
1685
  },
1479
1686
  onRoomPost(listener) {
@@ -1506,6 +1713,26 @@ export function openStore(file) {
1506
1713
  earlierBefore: rows.length > count ? (posts[0]?.seq ?? null) : null,
1507
1714
  };
1508
1715
  },
1716
+ // The person's own posts in a room before a post number, the newest `limit` of them, oldest first, and whether
1717
+ // there are more: what a brief carries of the person's say further back than the newest posts. None they forgot or
1718
+ // replaced (board_memory_marks).
1719
+ personRoomPosts(goalId, { before, limit = 12 }) {
1720
+ const count = Math.max(1, Math.min(100, Number(limit) || 12));
1721
+ const rows = execute(
1722
+ "all",
1723
+ `select c.id, c.seq, c.kind, c.author, c.machine, c.text, c.mentions, c.source, c.created_at
1724
+ from board_contributions c left join board_memory_marks m on m.contribution_id = c.id
1725
+ where c.task_id = ? and c.seq < ? and c.author = 'user' and c.kind != 'held' and m.contribution_id is null
1726
+ order by c.seq desc limit ?`,
1727
+ goalId,
1728
+ Number(before) > 0 ? Number(before) : Number.MAX_SAFE_INTEGER,
1729
+ count + 1
1730
+ );
1731
+ return {
1732
+ posts: rows.slice(0, count).reverse().map(roomPostOf),
1733
+ more: rows.length > count,
1734
+ };
1735
+ },
1509
1736
  // What each agent's finished runs' receipts showed (receipts.mjs, kept as receipt:<task>): { agent: { tested, untested, failing } }.
1510
1737
  receiptCounts() {
1511
1738
  const counts = {};
@@ -1861,7 +2088,7 @@ export function openStore(file) {
1861
2088
  // was said or done; posts the guard held never come back; nor does anything the person had forgotten or replaced.
1862
2089
  // The first twelve words of a query, as searchThreads read them (measured with 24: long job results that
1863
2090
  // share many common words crowded out the person's own earlier posts).
1864
- memoryWords(query, limit = 60) {
2091
+ memoryWords(query, limit = 60, { threads = null } = {}) {
1865
2092
  const terms = [
1866
2093
  ...new Set(
1867
2094
  String(query)
@@ -1875,13 +2102,26 @@ export function openStore(file) {
1875
2102
  const match = terms
1876
2103
  .map((term) => `"${term.replaceAll('"', '""')}"`)
1877
2104
  .join(" OR ");
2105
+ const scope = inThreads(threads);
1878
2106
  return execute(
1879
2107
  "all",
1880
2108
  `${MEMORY_SELECT}, bm25(board_contributions_fts) as rank
1881
2109
  from board_contributions_fts f join board_contributions c on c.id = f.id ${MEMORY_JOINS}
1882
- where board_contributions_fts match @match and ${MEMORY_WHERE}
2110
+ where board_contributions_fts match @match and ${MEMORY_WHERE}${scope.sql}
1883
2111
  order by rank limit @limit`,
1884
- { match, limit: Math.max(1, Math.min(200, limit)) }
2112
+ { match, limit: Math.max(1, Math.min(200, limit)), ...scope.params }
2113
+ );
2114
+ },
2115
+ // The ids of what memory can show in these threads (their posts and their jobs'), so a search limited to them ranks
2116
+ // among them alone instead of filtering the whole swarm's best few.
2117
+ memoryIdsIn(threads) {
2118
+ const scope = inThreads(threads);
2119
+ return new Set(
2120
+ execute(
2121
+ "all",
2122
+ `select c.id from board_contributions c ${MEMORY_JOINS} where ${MEMORY_WHERE}${scope.sql}`,
2123
+ scope.params
2124
+ ).map((row) => row.id)
1885
2125
  );
1886
2126
  },
1887
2127
  memoryPosts(ids) {
@@ -2343,6 +2583,73 @@ export function openStore(file) {
2343
2583
  )
2344
2584
  );
2345
2585
  },
2586
+ // Retire only an unstarted agent ask, with the task and room receipts in
2587
+ // the same transaction. The route supplies relevance; the store preserves
2588
+ // ownership if another worker claimed or changed the task in the meantime.
2589
+ retireRouteAsk(goalId, id, expectedVersion, reason) {
2590
+ db.exec("begin immediate");
2591
+ try {
2592
+ const task = this.getTask(id);
2593
+ const untouched =
2594
+ task?.kind === "task" &&
2595
+ task.parent_id === goalId &&
2596
+ task.origin_agent !== "user" &&
2597
+ task.status === "open" &&
2598
+ task.version === expectedVersion &&
2599
+ task.context_refs.some((ref) => ref.kind === "ask") &&
2600
+ !task.claimed_by &&
2601
+ !task.claimed_at &&
2602
+ !task.claimed_machine &&
2603
+ !task.target_machine &&
2604
+ !task.session_id &&
2605
+ !task.run_workspace &&
2606
+ !task.run_authorized_at &&
2607
+ !task.usage &&
2608
+ !this.meta(`harness-window:${id}`) &&
2609
+ !this.meta(`harness-served:${id}`);
2610
+ if (!untouched) {
2611
+ db.exec("commit");
2612
+ return false;
2613
+ }
2614
+ const at = new Date().toISOString();
2615
+ const text = `Canceled unstarted route ask ${id} for ${task.target_agent}: ${reason}. No work was reported as completed.`;
2616
+ const retired = execute(
2617
+ "run",
2618
+ `update board_tasks set status = 'failed', failure = 'start', result = ?, holder = null,
2619
+ reported_at = ?, updated_at = ?, version = version + 1 where id = ? and status = 'open' and version = ?`,
2620
+ text,
2621
+ at,
2622
+ at,
2623
+ id,
2624
+ expectedVersion
2625
+ );
2626
+ if (retired.changes !== 1) {
2627
+ db.exec("commit");
2628
+ return false;
2629
+ }
2630
+ this.addContribution({
2631
+ taskId: id,
2632
+ kind: "receipt",
2633
+ author: "harness",
2634
+ text,
2635
+ source: "route",
2636
+ });
2637
+ const receipt = this.addContribution({
2638
+ taskId: goalId,
2639
+ kind: "receipt",
2640
+ author: "harness",
2641
+ text,
2642
+ source: "room",
2643
+ });
2644
+ db.exec("commit");
2645
+ // Other computers hear the receipt only after its cancellation is durable.
2646
+ publishRoomPost(goalId, { ...receipt, mentions: [] });
2647
+ return true;
2648
+ } catch (error) {
2649
+ if (db.inTransaction) db.exec("rollback");
2650
+ throw error;
2651
+ }
2652
+ },
2346
2653
  // Stop: every open child closes; the caller stops what is running.
2347
2654
  // `agent`: only that agent's runs, the rest of the goal's work going on (a shared project's piece released).
2348
2655
  closeGoalChildren(goalId, reason, agent = null) {
@@ -3445,8 +3752,10 @@ export function openStore(file) {
3445
3752
  // what is new since they looked, not since the other did. An agent not yet seen there counts from when it last looked
3446
3753
  // anywhere, as it did before the board knew computers, so nothing old is told again.
3447
3754
  lastSeenAt(agent, machine = null) {
3755
+ const kept = machine ? seenNow.get(seenKey(agent, machine))?.at : null;
3448
3756
  const there = machine
3449
- ? execute(
3757
+ ? kept ||
3758
+ execute(
3450
3759
  "get",
3451
3760
  "select last_seen_at from board_agent_computers where agent = ? and machine = ?",
3452
3761
  agent,
@@ -3580,6 +3889,9 @@ export function openStore(file) {
3580
3889
  );
3581
3890
  },
3582
3891
  touchPhone(id) {
3892
+ const now = Date.now();
3893
+ if (now - (phoneSeenAt.get(id) ?? 0) < PHONE_SEEN_WRITE_MS) return;
3894
+ phoneSeenAt.set(id, now);
3583
3895
  execute(
3584
3896
  "run",
3585
3897
  "update phone_devices set last_seen_at = ? where id = ?",
@@ -3602,40 +3914,49 @@ export function openStore(file) {
3602
3914
  // When an agent last called the board, from `machine` when the call says which computer (every daemon's does): one
3603
3915
  // row a call, the same writes as before computers. A row without a computer is from before.
3604
3916
  touchAgent(agent, machine = null) {
3605
- const now = new Date().toISOString();
3606
- if (machine)
3607
- execute(
3608
- "run",
3609
- "insert into board_agent_computers(agent, machine, last_seen_at) values(?, ?, ?) on conflict(agent, machine) do update set last_seen_at = excluded.last_seen_at",
3610
- agent,
3611
- machine,
3612
- now
3613
- );
3614
- else
3615
- execute(
3616
- "run",
3617
- "insert into board_agents(agent, last_seen_at) values(?, ?) on conflict(agent) do update set last_seen_at = excluded.last_seen_at",
3618
- agent,
3619
- now
3620
- );
3917
+ seenNow.set(seenKey(agent, machine), {
3918
+ agent,
3919
+ machine,
3920
+ at: new Date().toISOString(),
3921
+ });
3922
+ seenWrite ??= setTimeout(writeSeen, SEEN_WRITE_MS);
3923
+ seenWrite.unref?.();
3621
3924
  },
3622
3925
  // Which agents called the board from which computer since `since`: where an agent that runs itself (Hermes, OpenClaw)
3623
3926
  // lives, since the daemon never starts it.
3624
3927
  agentsSeenOnComputers(since) {
3625
- return execute(
3928
+ const rows = execute(
3626
3929
  "all",
3627
3930
  "select agent, machine from board_agent_computers where last_seen_at >= ? order by agent",
3628
3931
  since
3629
3932
  );
3933
+ const listed = new Set(
3934
+ rows.map((row) => seenKey(row.agent, row.machine))
3935
+ );
3936
+ for (const kept of seenNow.values())
3937
+ if (
3938
+ kept.machine &&
3939
+ kept.at >= since &&
3940
+ !listed.has(seenKey(kept.agent, kept.machine))
3941
+ )
3942
+ rows.push({ agent: kept.agent, machine: kept.machine });
3943
+ return rows.sort((a, b) => a.agent.localeCompare(b.agent));
3630
3944
  },
3631
3945
  // When each agent last called the board, from any computer.
3632
3946
  agentsSeen() {
3633
- return execute(
3634
- "all",
3635
- `select agent, max(last_seen_at) as last_seen_at from (
3636
- select agent, last_seen_at from board_agents union all select agent, last_seen_at from board_agent_computers
3637
- ) group by agent order by last_seen_at desc`
3947
+ const latest = new Map(
3948
+ execute(
3949
+ "all",
3950
+ `select agent, max(last_seen_at) as last_seen_at from (
3951
+ select agent, last_seen_at from board_agents union all select agent, last_seen_at from board_agent_computers
3952
+ ) group by agent`
3953
+ ).map((row) => [row.agent, row.last_seen_at])
3638
3954
  );
3955
+ for (const { agent, at } of seenNow.values())
3956
+ if (!latest.has(agent) || at > latest.get(agent)) latest.set(agent, at);
3957
+ return [...latest]
3958
+ .map(([agent, last_seen_at]) => ({ agent, last_seen_at }))
3959
+ .sort((a, b) => b.last_seen_at.localeCompare(a.last_seen_at));
3639
3960
  },
3640
3961
  // Wakes sent to an agent's own gateway (wakes.mjs), one row per attempt: `outcome` is sent, refused, unsure (it may
3641
3962
  // have landed), merged into one already out, or capped. `about` names the result a wake told the agent of.
@@ -4015,6 +4336,7 @@ export function openStore(file) {
4015
4336
  );
4016
4337
  },
4017
4338
  close() {
4339
+ writeSeen();
4018
4340
  for (const statement of statements) {
4019
4341
  try {
4020
4342
  statement.finalize();