teamshare-bridge 0.30.1 → 0.30.3

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 (87) hide show
  1. package/README.md +10 -6
  2. package/dist/bridge/daemon-inbox.js +27 -0
  3. package/dist/bridge/daemon-inbox.js.map +1 -1
  4. package/dist/bridge/daemon.js +16 -0
  5. package/dist/bridge/daemon.js.map +1 -1
  6. package/dist/bridge/doctor.js +3 -2
  7. package/dist/bridge/doctor.js.map +1 -1
  8. package/dist/cli/commands/blog.js +6 -1
  9. package/dist/cli/commands/blog.js.map +1 -1
  10. package/dist/cli/commands/board.js +5 -1
  11. package/dist/cli/commands/board.js.map +1 -1
  12. package/dist/cli/commands/build.js +10 -2
  13. package/dist/cli/commands/build.js.map +1 -1
  14. package/dist/cli/commands/chat.js +1 -1
  15. package/dist/cli/commands/chat.js.map +1 -1
  16. package/dist/cli/commands/doc.js +5 -1
  17. package/dist/cli/commands/doc.js.map +1 -1
  18. package/dist/cli/commands/git.d.ts +1 -0
  19. package/dist/cli/commands/git.js +68 -0
  20. package/dist/cli/commands/git.js.map +1 -0
  21. package/dist/cli/commands/insight.js +6 -1
  22. package/dist/cli/commands/insight.js.map +1 -1
  23. package/dist/cli/commands/planner.js +1 -0
  24. package/dist/cli/commands/planner.js.map +1 -1
  25. package/dist/cli/commands/research.d.ts +8 -0
  26. package/dist/cli/commands/research.js +30 -3
  27. package/dist/cli/commands/research.js.map +1 -1
  28. package/dist/cli/commands/run.js +1 -0
  29. package/dist/cli/commands/run.js.map +1 -1
  30. package/dist/cli/commands/worker.js +9 -1
  31. package/dist/cli/commands/worker.js.map +1 -1
  32. package/dist/cli/commands/workflow-author.js +1 -1
  33. package/dist/cli/commands/workflow-author.js.map +1 -1
  34. package/dist/cli/commands/workflow.js +4 -0
  35. package/dist/cli/commands/workflow.js.map +1 -1
  36. package/dist/cli/index.js +7 -0
  37. package/dist/cli/index.js.map +1 -1
  38. package/dist/lib/api-agents.d.ts +84 -0
  39. package/dist/lib/api-agents.js +22 -0
  40. package/dist/lib/api-agents.js.map +1 -1
  41. package/dist/lib/api-types.d.ts +10 -0
  42. package/dist/lib/api.d.ts +14 -11
  43. package/dist/lib/api.js +12 -5
  44. package/dist/lib/api.js.map +1 -1
  45. package/dist/lib/brief.d.ts +6 -0
  46. package/dist/lib/brief.js +14 -0
  47. package/dist/lib/brief.js.map +1 -1
  48. package/dist/lib/chat/board-reply.js +15 -2
  49. package/dist/lib/chat/board-reply.js.map +1 -1
  50. package/dist/lib/chat/chat-reply.d.ts +7 -1
  51. package/dist/lib/chat/chat-reply.js +21 -2
  52. package/dist/lib/chat/chat-reply.js.map +1 -1
  53. package/dist/lib/chat/doc-reply.js +16 -2
  54. package/dist/lib/chat/doc-reply.js.map +1 -1
  55. package/dist/lib/coord/format.d.ts +143 -0
  56. package/dist/lib/coord/format.js +398 -0
  57. package/dist/lib/coord/format.js.map +1 -0
  58. package/dist/lib/coord/guidance.d.ts +21 -0
  59. package/dist/lib/coord/guidance.js +110 -0
  60. package/dist/lib/coord/guidance.js.map +1 -0
  61. package/dist/lib/coord/index.d.ts +12 -0
  62. package/dist/lib/coord/index.js +38 -0
  63. package/dist/lib/coord/index.js.map +1 -0
  64. package/dist/lib/coord/monitor.d.ts +180 -0
  65. package/dist/lib/coord/monitor.js +746 -0
  66. package/dist/lib/coord/monitor.js.map +1 -0
  67. package/dist/lib/coord/paths.d.ts +20 -0
  68. package/dist/lib/coord/paths.js +76 -0
  69. package/dist/lib/coord/paths.js.map +1 -0
  70. package/dist/lib/coord/store.d.ts +13 -0
  71. package/dist/lib/coord/store.js +104 -0
  72. package/dist/lib/coord/store.js.map +1 -0
  73. package/dist/lib/git/git-naming.js +4 -0
  74. package/dist/lib/git/git-naming.js.map +1 -1
  75. package/dist/lib/git/git-pull.d.ts +35 -0
  76. package/dist/lib/git/git-pull.js +233 -0
  77. package/dist/lib/git/git-pull.js.map +1 -0
  78. package/dist/lib/harness/harness-adapter.js +7 -0
  79. package/dist/lib/harness/harness-adapter.js.map +1 -1
  80. package/dist/lib/lock.d.ts +8 -0
  81. package/dist/lib/lock.js.map +1 -1
  82. package/dist/lib/scope-guard.js +9 -1
  83. package/dist/lib/scope-guard.js.map +1 -1
  84. package/dist/lib/workspace/stop-marker.d.ts +52 -0
  85. package/dist/lib/workspace/stop-marker.js +92 -0
  86. package/dist/lib/workspace/stop-marker.js.map +1 -0
  87. package/package.json +1 -1
@@ -0,0 +1,746 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.CoordinationMonitor = void 0;
4
+ /**
5
+ * Machine-local coordination monitor (2026-11-21).
6
+ *
7
+ * One loop, owned by the daemon, that turns the machine-local tree into:
8
+ * - `workboard.md` - what every agent and the human on this PC reads
9
+ * - `inbox/*.ndjson` - peer notes, local delivery, zero cloud traffic
10
+ * - a THROTTLED hub projection (members + new notes) so a human on any
11
+ * device, and an agent on another PC, can see the same board
12
+ *
13
+ * It is purely OBSERVATIONAL: agents appear because they hold a session lock
14
+ * (`~/.teamshare/locks/<agentId>.lock`) whose pid is alive. Nothing has to call
15
+ * a register/unregister hook, so every CLI command - existing and future - is
16
+ * covered without touching it, and a run that is killed simply stops being
17
+ * fresh.
18
+ *
19
+ * NO WAKE, EVER. A note from one agent never emits a wake, never starts a run
20
+ * and never queues work for an agent that is not running. A live agent with an
21
+ * URGENT note gets one deduped self-instruction (the same mechanism the stall
22
+ * watchdog uses); everything else waits for its next checkpoint.
23
+ */
24
+ const node_crypto_1 = require("node:crypto");
25
+ const node_fs_1 = require("node:fs");
26
+ const node_path_1 = require("node:path");
27
+ const config_1 = require("../config");
28
+ const lock_1 = require("../lock");
29
+ const format_1 = require("./format");
30
+ const paths_1 = require("./paths");
31
+ const store_1 = require("./store");
32
+ /** Notes a single push carries, so a backlog cannot become a huge request. */
33
+ const MAX_NOTES_PER_PUSH = 25;
34
+ const MAX_LEDGER = 500;
35
+ const MAX_PUSHED_IDS = 500;
36
+ /** Urgent nudge cooldown, per (from -> to). */
37
+ const NUDGE_COOLDOWN_MS = 10 * 60_000;
38
+ /** A project's local tree is removed this long after its board closed. */
39
+ const LOCAL_RETENTION_MS = 35 * 60_000;
40
+ /**
41
+ * The hub marks a member `lost` after 5 minutes of silence, so a QUIET board
42
+ * (an agent thinking, a long build) must still be refreshed inside that window
43
+ * or a working agent would vanish from the human's tab. 2 minutes leaves room
44
+ * for one missed beat; a status CHANGE still pushes immediately (10s floor).
45
+ */
46
+ const HEARTBEAT_MS = 2 * 60_000;
47
+ /**
48
+ * A failed push used to retry on EVERY tick (2s, once per bound agent) because
49
+ * the floor was measured from the last SUCCESS. A capped backoff keeps a dead
50
+ * project or a 5xx from becoming a hot loop while still recovering inside the
51
+ * hub's liveness window.
52
+ */
53
+ const PUSH_MAX_BACKOFF_MS = 60_000;
54
+ const emptyState = () => ({
55
+ agents: {},
56
+ pushedNotes: [],
57
+ seenRemoteNotes: [],
58
+ nudges: {},
59
+ lastPushAt: 0,
60
+ lastPushAttemptAt: 0,
61
+ pushFailures: 0,
62
+ lastRemoteAt: 0,
63
+ closedAt: null,
64
+ });
65
+ const hash = (value) => (0, node_crypto_1.createHash)('sha1').update(value).digest('hex').slice(0, 16);
66
+ /** mtime in ms, or NaN when the file does not exist. */
67
+ function mtimeMs(path) {
68
+ try {
69
+ return (0, node_fs_1.statSync)(path).mtimeMs;
70
+ }
71
+ catch {
72
+ return Number.NaN;
73
+ }
74
+ }
75
+ /**
76
+ * The identity of the current unit of work. A new unit gets a fresh seed; a
77
+ * continuation (the same task, or the same tool run resumed after a question)
78
+ * keeps the status the agent already wrote.
79
+ */
80
+ function unitKey(local) {
81
+ const identity = local.taskId ?? local.runId ?? local.label ?? '';
82
+ return `${local.mode}:${identity}`;
83
+ }
84
+ const emptyBoard = (projectId) => ({
85
+ projectId,
86
+ projectName: null,
87
+ updatedAt: new Date(0).toISOString(),
88
+ members: [],
89
+ notes: [],
90
+ closedAt: null,
91
+ });
92
+ /** Matches a `to:` token against an agent id (full or first-8 prefix). */
93
+ function matchesAgent(token, agentId) {
94
+ const clean = token.replace(/[`"'\s]/g, '').toLowerCase();
95
+ // A template placeholder (`<agentId>`) is not an addressee.
96
+ if (!clean || clean.includes('<') || clean.includes('>'))
97
+ return false;
98
+ const id = agentId.toLowerCase();
99
+ return (id === clean || id.startsWith(clean) || clean.startsWith(id.slice(0, 8)));
100
+ }
101
+ class CoordinationMonitor {
102
+ opts;
103
+ timer;
104
+ running = false;
105
+ intervalMs;
106
+ pushFloorMs;
107
+ remoteRefreshMs;
108
+ taskCache = new Map();
109
+ /** Agent display names, resolved once per 30 min (no config field for it). */
110
+ names = new Map();
111
+ /**
112
+ * Urgent-nudge cooldown per `sender>target`, in memory only. The note-text
113
+ * dedupe is the durable guard; this only stops a status file that is rewritten
114
+ * every few seconds from nudging the same agent repeatedly.
115
+ */
116
+ nudges = new Map();
117
+ /** Projects processed last tick, so a closing board is still visited. */
118
+ known = new Set();
119
+ /** Per-tick dirty flag per project (drives the push floor). */
120
+ dirty = new Map();
121
+ constructor(opts) {
122
+ this.opts = opts;
123
+ this.intervalMs = opts.intervalMs ?? 2_000;
124
+ this.pushFloorMs = opts.pushFloorMs ?? 10_000;
125
+ this.remoteRefreshMs = opts.remoteRefreshMs ?? 15_000;
126
+ this.isLive = opts.isLive ?? ((agentId) => (0, lock_1.isLockBusy)(agentId));
127
+ }
128
+ /** Session liveness: the bridge's lock is the one signal every mode keeps. */
129
+ isLive;
130
+ start() {
131
+ if (this.timer)
132
+ return;
133
+ this.timer = setInterval(() => void this.tick(), this.intervalMs);
134
+ this.timer.unref?.();
135
+ }
136
+ stop() {
137
+ if (this.timer)
138
+ clearInterval(this.timer);
139
+ this.timer = undefined;
140
+ }
141
+ /** One pass. Public so tests (and `doctor`) can drive it deterministically. */
142
+ async tick(now = Date.now()) {
143
+ if (this.running)
144
+ return;
145
+ this.running = true;
146
+ try {
147
+ const localsByProject = await this.collectLocals();
148
+ for (const projectId of this.known) {
149
+ if (!localsByProject.has(projectId))
150
+ localsByProject.set(projectId, []);
151
+ }
152
+ for (const [projectId, locals] of localsByProject) {
153
+ await this.processProject(projectId, locals, now);
154
+ this.known.add(projectId);
155
+ }
156
+ this.sweepLocal(now);
157
+ }
158
+ catch (error) {
159
+ this.opts.log(`[coord] pass failed: ${error instanceof Error ? error.message : String(error)}`);
160
+ }
161
+ finally {
162
+ this.running = false;
163
+ }
164
+ }
165
+ // -- discovery -------------------------------------------------------------
166
+ /**
167
+ * Live members come from the SESSION LOCKS, not from a register call: a lock
168
+ * with a live pid is the one piece of state every CLI command already keeps,
169
+ * so no spawn path needs to know this feature exists.
170
+ */
171
+ async collectLocals() {
172
+ const out = new Map();
173
+ for (const binding of this.opts.agents()) {
174
+ if (!binding.agentId || !binding.api)
175
+ continue;
176
+ if (!this.isLive(binding.agentId))
177
+ continue;
178
+ const lock = (0, lock_1.readLock)(binding.agentId);
179
+ if (!lock)
180
+ continue;
181
+ let projectId = lock.projectId ?? null;
182
+ let taskTitle = null;
183
+ if (lock.taskId) {
184
+ const task = await this.lookupTask(binding.api, lock.taskId);
185
+ taskTitle = task?.title ?? null;
186
+ if (!projectId)
187
+ projectId = task?.projectId ?? null;
188
+ }
189
+ if (!projectId)
190
+ continue;
191
+ const members = out.get(projectId) ?? [];
192
+ members.push({
193
+ binding,
194
+ mode: lock.kind,
195
+ taskId: lock.taskId ?? null,
196
+ startedAt: lock.startedAt,
197
+ taskTitle,
198
+ label: lock.label ?? null,
199
+ runId: lock.runId ?? null,
200
+ });
201
+ out.set(projectId, members);
202
+ }
203
+ return out;
204
+ }
205
+ /**
206
+ * The agent's display name. `config.json` has no name field, so it is read
207
+ * once from the settings snapshot and cached for 30 minutes.
208
+ */
209
+ async nameFor(binding) {
210
+ if (binding.agentName)
211
+ return binding.agentName;
212
+ const id8 = binding.agentId.slice(0, 8);
213
+ const cached = this.names.get(binding.agentId);
214
+ if (cached && Date.now() - cached.at < 30 * 60_000) {
215
+ return cached.name ?? id8;
216
+ }
217
+ if (!binding.api.getAgentSettings)
218
+ return id8;
219
+ try {
220
+ const settings = await binding.api.getAgentSettings(binding.agentId);
221
+ const name = settings.agentName ?? null;
222
+ this.names.set(binding.agentId, { name, at: Date.now() });
223
+ return name ?? id8;
224
+ }
225
+ catch {
226
+ // Keep the id fragment and retry on the next pass.
227
+ return id8;
228
+ }
229
+ }
230
+ async lookupTask(api, taskId) {
231
+ const cached = this.taskCache.get(taskId);
232
+ if (cached && Date.now() - cached.at < 6 * 60 * 60_000)
233
+ return cached.task;
234
+ let task = null;
235
+ try {
236
+ task = await api.getTask(taskId);
237
+ }
238
+ catch {
239
+ // A 404/403 means the agent cannot see the task; the member still shows
240
+ // as `task` mode, just without a title or a project. Retry in 10 min.
241
+ task = null;
242
+ }
243
+ this.taskCache.set(taskId, { task, at: Date.now() });
244
+ if (this.taskCache.size > 200) {
245
+ const oldest = [...this.taskCache.entries()].sort((a, b) => a[1].at - b[1].at)[0];
246
+ if (oldest)
247
+ this.taskCache.delete(oldest[0]);
248
+ }
249
+ return task;
250
+ }
251
+ /** Project dirs that still need a visit (an open board with no live agent). */
252
+ listProjectDirs() {
253
+ try {
254
+ return (0, node_fs_1.readdirSync)(paths_1.COORD_ROOT, { withFileTypes: true })
255
+ .filter((entry) => entry.isDirectory())
256
+ .map((entry) => entry.name);
257
+ }
258
+ catch {
259
+ return [];
260
+ }
261
+ }
262
+ // -- one project -----------------------------------------------------------
263
+ async processProject(projectId, locals, now) {
264
+ const dir = (0, paths_1.projectCoordDir)(projectId);
265
+ (0, store_1.ensureDir)(dir);
266
+ (0, store_1.ensureDir)((0, paths_1.agentsDir)(projectId));
267
+ (0, store_1.ensureDir)((0, paths_1.inboxDir)(projectId));
268
+ const state = (0, store_1.readJson)((0, paths_1.statePath)(projectId), emptyState());
269
+ const board = (0, store_1.readJson)((0, paths_1.boardJsonPath)(projectId), emptyBoard(projectId));
270
+ // A project with no live agent AND an already-closed board needs nothing.
271
+ if (locals.length === 0 && board.closedAt) {
272
+ return;
273
+ }
274
+ let dirty = false;
275
+ const members = [];
276
+ const liveIds = new Set(locals.map((local) => local.binding.agentId));
277
+ for (const local of locals) {
278
+ const agentId = local.binding.agentId;
279
+ const displayName = await this.nameFor(local.binding);
280
+ const file = (0, paths_1.agentStatusPath)(projectId, agentId);
281
+ const label = (local.taskTitle || local.label || '')
282
+ .replace(/\s+/g, ' ')
283
+ .trim();
284
+ const template = (0, format_1.renderStatusTemplate)({
285
+ agentId,
286
+ agentName: displayName,
287
+ projectId,
288
+ mode: local.mode,
289
+ taskTitle: local.taskTitle,
290
+ label,
291
+ workboardFile: (0, paths_1.workboardPath)(projectId),
292
+ inboxFile: (0, paths_1.inboxPath)(projectId, agentId),
293
+ });
294
+ const previous = state.agents[agentId];
295
+ const unit = unitKey(local);
296
+ const existing = (0, store_1.readText)(file);
297
+ const fileTime = mtimeMs(file);
298
+ const startedMs = Date.parse(local.startedAt);
299
+ // A file from an EARLIER run (or an untouched old seed) must not be shown
300
+ // as this run's status. mtime is the authority: a resume and a brand new
301
+ // run both write their file AFTER the lock, so only a file that PREDATES
302
+ // the lock is stale. Writing it is safe - the agent owns it from then on.
303
+ const stale = !existing ||
304
+ !existing.trim() ||
305
+ (previous?.unit !== undefined && previous.unit !== unit) ||
306
+ (Number.isFinite(fileTime) &&
307
+ Number.isFinite(startedMs) &&
308
+ fileTime + 1_500 < startedMs);
309
+ let seeded = false;
310
+ if (stale) {
311
+ (0, store_1.writeTextAtomic)(file, template);
312
+ seeded = true;
313
+ dirty = true;
314
+ }
315
+ const current = seeded ? template : (existing ?? '');
316
+ const seedHash = seeded ? hash(template) : previous?.seedHash;
317
+ const parsed = (0, format_1.parseStatusFile)(current);
318
+ // `reported` is exact: the file is still byte-for-byte what the bridge
319
+ // wrote. The UI shows the run's subject and says "waiting for its first
320
+ // status" instead of pretending the seed is the agent's words.
321
+ const reported = seedHash ? hash(current) !== seedHash : !parsed.blank;
322
+ const notesHash = hash(`${parsed.to.join(',')}|${parsed.notes}`);
323
+ if (parsed.notes.trim() &&
324
+ parsed.to.length > 0 &&
325
+ previous?.notesHash !== notesHash) {
326
+ const created = this.fanOut(projectId, local, parsed, now, locals);
327
+ if (created > 0)
328
+ dirty = true;
329
+ }
330
+ else if (parsed.notes.trim() && parsed.to.length === 0) {
331
+ // A note with no addressee still belongs on the shared log, so the
332
+ // human and the other agents can see it. Deduped by the same hash.
333
+ if (previous?.notesHash !== notesHash) {
334
+ const created = this.appendLedger(projectId, {
335
+ kind: parsed.status === 'blocked' ? 'blocker' : 'note',
336
+ authorId: agentId,
337
+ authorName: displayName,
338
+ authorKind: 'agent',
339
+ toAgentId: null,
340
+ body: parsed.notes,
341
+ urgent: false,
342
+ createdAt: new Date(now).toISOString(),
343
+ });
344
+ if (created)
345
+ dirty = true;
346
+ }
347
+ }
348
+ state.agents[agentId] = { notesHash, seedHash, unit, updatedAt: now };
349
+ members.push({
350
+ agentId,
351
+ agentName: displayName,
352
+ mode: local.mode,
353
+ taskId: local.taskId,
354
+ // A live lock IS work; only let the file override it when the agent
355
+ // actually wrote a status line.
356
+ status: parsed.statusReported ? parsed.status : 'working',
357
+ summary: parsed.summary || label || '',
358
+ areas: parsed.areas,
359
+ startedAt: local.startedAt,
360
+ derived: {
361
+ taskTitle: local.taskTitle,
362
+ label: label || null,
363
+ reported,
364
+ runId: local.runId,
365
+ },
366
+ });
367
+ }
368
+ // A member that was live last tick and is not any more ends HERE, so the
369
+ // board closes locally even when the CLI could not send a final push.
370
+ for (const previous of board.members) {
371
+ if (previous.remote)
372
+ continue;
373
+ if (liveIds.has(previous.agentId))
374
+ continue;
375
+ if (previous.endedAt) {
376
+ members.push(previous);
377
+ continue;
378
+ }
379
+ members.push({
380
+ ...previous,
381
+ status: previous.status === 'lost' ? 'lost' : 'done',
382
+ endedAt: new Date(now).toISOString(),
383
+ });
384
+ dirty = true;
385
+ }
386
+ // Remote roster (another PC): only while this project has someone working
387
+ // here, otherwise the human's tab reads the hub directly.
388
+ let remotes = board.members.filter((m) => m.remote);
389
+ if (locals.length > 0 && now - state.lastRemoteAt >= this.remoteRefreshMs) {
390
+ state.lastRemoteAt = now;
391
+ const fetched = await this.fetchRemote(projectId, locals[0].binding);
392
+ if (fetched) {
393
+ remotes = fetched.members
394
+ .filter((member) => Boolean(member.agentId))
395
+ .map((member) => ({
396
+ agentId: member.agentId,
397
+ agentName: member.agentName ?? member.agentId.slice(0, 8),
398
+ mode: member.mode,
399
+ taskId: member.taskId,
400
+ status: member.status,
401
+ summary: member.summary,
402
+ areas: member.areas,
403
+ startedAt: member.startedAt,
404
+ endedAt: member.endedAt,
405
+ machineLabel: member.machineLabel,
406
+ derived: {
407
+ taskTitle: typeof member.derived?.taskTitle === 'string'
408
+ ? member.derived.taskTitle
409
+ : null,
410
+ },
411
+ remote: true,
412
+ }));
413
+ this.absorbRemoteNotes(projectId, locals, fetched.notes, state, now);
414
+ }
415
+ }
416
+ members.push(...remotes);
417
+ const ledger = (0, store_1.readNdjson)((0, paths_1.notesPath)(projectId));
418
+ const notes = ledger.slice(-40).map((note) => ({
419
+ at: note.createdAt,
420
+ author: note.authorName,
421
+ kind: note.kind,
422
+ body: note.body,
423
+ to: note.toAgentId,
424
+ urgent: note.urgent,
425
+ }));
426
+ const projectName = board.projectName ?? null;
427
+ const rendered = (0, format_1.renderWorkboard)({
428
+ projectId,
429
+ projectName,
430
+ members,
431
+ notes,
432
+ now,
433
+ });
434
+ // The file is still rewritten every tick (a human may open it), but its
435
+ // SECOND-resolution timestamp made `dirty` permanently true, which turned
436
+ // the intended heartbeat into a push every 10s for the whole run. Only a
437
+ // real change (member state below, or a note) may wake the hub.
438
+ (0, store_1.writeTextIfChanged)((0, paths_1.workboardPath)(projectId), rendered);
439
+ let closedAt = board.closedAt;
440
+ if (locals.length > 0)
441
+ closedAt = null;
442
+ if (locals.length === 0 && members.every((m) => m.remote || m.endedAt)) {
443
+ closedAt = closedAt ?? new Date(now).toISOString();
444
+ }
445
+ const nextBoard = {
446
+ projectId,
447
+ projectName,
448
+ updatedAt: new Date(now).toISOString(),
449
+ members,
450
+ notes,
451
+ closedAt,
452
+ };
453
+ if (JSON.stringify(nextBoard.members) !== JSON.stringify(board.members)) {
454
+ dirty = true;
455
+ }
456
+ (0, store_1.writeJsonAtomic)((0, paths_1.boardJsonPath)(projectId), nextBoard);
457
+ this.dirty.set(projectId, dirty);
458
+ // Push the caller's own slice: members on THIS machine + unpushed notes.
459
+ // A quiet board still refreshes inside the hub's liveness window.
460
+ const failures = state.pushFailures ?? 0;
461
+ const backoff = Math.min(PUSH_MAX_BACKOFF_MS, this.pushFloorMs * 2 ** Math.min(4, failures));
462
+ const floor = Math.max(this.pushFloorMs, backoff);
463
+ const due = dirty || now - state.lastPushAt >= HEARTBEAT_MS;
464
+ const sinceAttempt = now - (state.lastPushAttemptAt ?? 0);
465
+ const shouldPush = due && sinceAttempt >= floor;
466
+ if (shouldPush) {
467
+ // Recorded BEFORE the await: a failing push must respect the floor too,
468
+ // or a dead project retries on every 2s tick (once per bound agent).
469
+ state.lastPushAttemptAt = now;
470
+ const ok = await this.pushProject(projectId, locals, members, state, now);
471
+ if (ok) {
472
+ state.lastPushAt = now;
473
+ state.pushFailures = 0;
474
+ if (state.closedAt == null && locals.length === 0)
475
+ state.closedAt = now;
476
+ }
477
+ else {
478
+ state.pushFailures = failures + 1;
479
+ }
480
+ }
481
+ if (locals.length > 0)
482
+ state.closedAt = null;
483
+ if (state.closedAt == null && locals.length === 0 && closedAt) {
484
+ state.closedAt = now;
485
+ }
486
+ state.pushedNotes = state.pushedNotes.slice(-MAX_PUSHED_IDS);
487
+ state.seenRemoteNotes = state.seenRemoteNotes.slice(-MAX_PUSHED_IDS);
488
+ (0, store_1.writeJsonAtomic)((0, paths_1.statePath)(projectId), state);
489
+ }
490
+ // -- notes -----------------------------------------------------------------
491
+ /**
492
+ * Turns the `to:` + notes text of one agent's status file into peer notes.
493
+ * Returns how many ledger rows were created.
494
+ */
495
+ fanOut(projectId, local, parsed, now, peers = []) {
496
+ // Resolve the addressee against the LIVE local roster first (a nobody-else
497
+ // case is the common one), then the daemon's configured agents.
498
+ const bindings = [
499
+ ...peers.map((peer) => peer.binding),
500
+ ...this.opts.agents(),
501
+ ];
502
+ let created = 0;
503
+ for (const token of parsed.to) {
504
+ const target = bindings.find((b) => matchesAgent(token, b.agentId));
505
+ const targetId = target?.agentId ?? token;
506
+ const urgent = parsed.status === 'blocked' ||
507
+ /urgent|asap|blocking/i.test(parsed.notes);
508
+ const note = {
509
+ id: globalThis.crypto.randomUUID(),
510
+ kind: urgent ? 'urgent' : 'question',
511
+ authorId: local.binding.agentId,
512
+ authorName: local.binding.agentName ?? local.binding.agentId.slice(0, 8),
513
+ authorKind: 'agent',
514
+ toAgentId: targetId,
515
+ body: parsed.notes,
516
+ urgent,
517
+ createdAt: new Date(now).toISOString(),
518
+ pushed: false,
519
+ };
520
+ if (!this.appendLedger(projectId, note))
521
+ continue;
522
+ created += 1;
523
+ (0, store_1.appendNdjson)((0, paths_1.inboxPath)(projectId, targetId), [
524
+ {
525
+ id: note.id,
526
+ fromAgentId: note.authorId,
527
+ fromName: note.authorName,
528
+ body: note.body,
529
+ urgent: note.urgent,
530
+ at: note.createdAt,
531
+ },
532
+ ]);
533
+ if (urgent && target && target.agentId !== local.binding.agentId) {
534
+ void this.nudge(target, projectId, {
535
+ agentId: local.binding.agentId,
536
+ agentName: local.binding.agentName,
537
+ }, parsed.notes, now);
538
+ }
539
+ }
540
+ return created;
541
+ }
542
+ appendLedger(projectId, input) {
543
+ const note = {
544
+ ...input,
545
+ id: globalThis.crypto.randomUUID(),
546
+ pushed: false,
547
+ };
548
+ const ledger = (0, store_1.readNdjson)((0, paths_1.notesPath)(projectId));
549
+ if (ledger.some((entry) => entry.id === note.id))
550
+ return false;
551
+ // The same words twice in ten minutes is one note; an agent rewriting its
552
+ // status file must not spam every colleague.
553
+ const duplicate = ledger.some((entry) => entry.body === note.body &&
554
+ entry.authorId === note.authorId &&
555
+ entry.toAgentId === note.toAgentId &&
556
+ Math.abs(Date.parse(note.createdAt) - Date.parse(entry.createdAt)) <
557
+ 10 * 60_000);
558
+ if (duplicate)
559
+ return false;
560
+ (0, store_1.appendNdjson)((0, paths_1.notesPath)(projectId), [note], MAX_LEDGER);
561
+ return true;
562
+ }
563
+ /**
564
+ * ONE deduped self-instruction for an urgent note. This is the same channel
565
+ * the stall watchdog uses: no wake, no spawn, no queue for an offline agent,
566
+ * and the agent decides what to do with it. Cooldown is per sender -> target.
567
+ */
568
+ async nudge(target, projectId, from, body, now) {
569
+ const key = `${from.agentId}>${target.agentId}`;
570
+ if (now - (this.nudges.get(key) ?? 0) < NUDGE_COOLDOWN_MS)
571
+ return;
572
+ if (!this.isLive(target.agentId))
573
+ return;
574
+ this.nudges.set(key, now);
575
+ const lock = (0, lock_1.readLock)(target.agentId);
576
+ try {
577
+ await target.api.createSelfInstruction({
578
+ projectId,
579
+ taskId: lock?.taskId ?? null,
580
+ body: `[workboard] ${from.agentName ?? from.agentId.slice(0, 8)} ` +
581
+ `marked a note URGENT for you. Read ${(0, paths_1.inboxPath)(projectId, target.agentId)} ` +
582
+ `before your next action:\n\n${body}`,
583
+ });
584
+ }
585
+ catch {
586
+ // Best-effort, exactly like the stall note: the note is still on the
587
+ // board and in the inbox, and the agent reads it at its next checkpoint.
588
+ }
589
+ }
590
+ // -- hub -------------------------------------------------------------------
591
+ async pushProject(projectId, locals, members, state, now) {
592
+ const ledger = (0, store_1.readNdjson)((0, paths_1.notesPath)(projectId));
593
+ const unpushed = ledger.filter((note) => !note.pushed && !state.pushedNotes.includes(note.id));
594
+ const localIds = new Set(locals.map((local) => local.binding.agentId));
595
+ const ownMembers = members
596
+ .filter((member) => !member.remote && (localIds.has(member.agentId) || member.endedAt))
597
+ .map((member) => ({
598
+ sessionKey: `${(0, config_1.machineId)()}:${member.agentId}`,
599
+ agentId: member.agentId,
600
+ agentName: member.agentName,
601
+ mode: member.mode,
602
+ taskId: member.taskId ?? null,
603
+ status: member.status,
604
+ summary: member.summary,
605
+ areas: member.areas,
606
+ derived: {
607
+ taskTitle: member.derived?.taskTitle ?? null,
608
+ label: member.derived?.label ?? null,
609
+ reported: member.derived?.reported ?? null,
610
+ runId: member.derived?.runId ?? null,
611
+ branch: member.derived?.branch ?? null,
612
+ elapsedMin: Math.max(0, Math.round((now - Date.parse(member.startedAt)) / 60_000)),
613
+ },
614
+ startedAt: member.startedAt,
615
+ endedAt: member.endedAt ?? null,
616
+ }));
617
+ const batches = unpushed.slice(0, MAX_NOTES_PER_PUSH);
618
+ const body = {
619
+ projectId,
620
+ machineId: (0, config_1.machineId)(),
621
+ machineLabel: (0, config_1.machineLabel)(),
622
+ members: ownMembers,
623
+ notes: batches.map((note) => ({
624
+ clientId: note.id,
625
+ kind: note.kind,
626
+ authorId: note.authorId,
627
+ authorName: note.authorName,
628
+ authorKind: note.authorKind,
629
+ toAgentId: note.toAgentId,
630
+ body: note.body,
631
+ urgent: note.urgent,
632
+ createdAt: note.createdAt,
633
+ })),
634
+ };
635
+ const bindings = locals.map((local) => local.binding);
636
+ for (const binding of bindings.length > 0 ? bindings : this.opts.agents()) {
637
+ try {
638
+ await binding.api.pushCoordination(binding.agentId, body);
639
+ for (const note of batches)
640
+ state.pushedNotes.push(note.id);
641
+ state.pushedNotes = [...new Set(state.pushedNotes)].slice(-MAX_PUSHED_IDS);
642
+ // Flip the local ledger flag. The hub ALSO dedupes by clientId, so a
643
+ // crash between the POST and this write cannot duplicate a note.
644
+ const updated = ledger.map((note) => batches.some((sent) => sent.id === note.id)
645
+ ? { ...note, pushed: true }
646
+ : note);
647
+ (0, store_1.writeNdjson)((0, paths_1.notesPath)(projectId), updated, MAX_LEDGER);
648
+ this.dirty.set(projectId, false);
649
+ return true;
650
+ }
651
+ catch (error) {
652
+ this.opts.log(`[coord] push failed for ${projectId} as ${binding.agentId.slice(0, 8)}: ${error instanceof Error ? error.message : String(error)}`);
653
+ }
654
+ }
655
+ return false;
656
+ }
657
+ async fetchRemote(projectId, binding) {
658
+ try {
659
+ const remote = await binding.api.getProjectCoordination(projectId);
660
+ const mine = (0, config_1.machineId)();
661
+ return {
662
+ ...remote,
663
+ // Our own rows echo back from the hub; they are already local.
664
+ members: (remote.members ?? []).filter((member) => member.machineId !== mine),
665
+ notes: remote.notes ?? [],
666
+ };
667
+ }
668
+ catch {
669
+ return null;
670
+ }
671
+ }
672
+ /**
673
+ * A note another PC addressed to an agent HERE must land in that agent's
674
+ * local inbox, or a cross-machine colleague could never be reached.
675
+ */
676
+ absorbRemoteNotes(projectId, locals, notes, state, now) {
677
+ if (notes.length === 0)
678
+ return;
679
+ const seen = new Set(state.seenRemoteNotes);
680
+ for (const note of notes) {
681
+ if (seen.has(note.id))
682
+ continue;
683
+ const target = locals.find((local) => note.toAgentId && matchesAgent(note.toAgentId, local.binding.agentId));
684
+ if (!target)
685
+ continue;
686
+ seen.add(note.id);
687
+ state.seenRemoteNotes.push(note.id);
688
+ (0, store_1.appendNdjson)((0, paths_1.inboxPath)(projectId, target.binding.agentId), [
689
+ {
690
+ id: note.id,
691
+ fromAgentId: note.authorId,
692
+ fromName: note.authorName ?? 'another agent',
693
+ body: note.body,
694
+ urgent: note.urgent,
695
+ at: note.createdAt,
696
+ remote: true,
697
+ },
698
+ ]);
699
+ this.dirty.set(projectId, true);
700
+ if (note.urgent) {
701
+ void this.nudge(target.binding, projectId, {
702
+ agentId: note.authorId ?? 'remote',
703
+ agentName: note.authorName ?? 'another agent',
704
+ }, note.body, now);
705
+ }
706
+ }
707
+ }
708
+ // -- housekeeping ----------------------------------------------------------
709
+ /** Deletes a project's local tree a while after its board closed. */
710
+ sweepLocal(now) {
711
+ for (const projectId of this.listProjectDirs()) {
712
+ const board = (0, store_1.readJson)((0, paths_1.boardJsonPath)(projectId), emptyBoard(projectId));
713
+ if (!board.closedAt) {
714
+ this.known.add(projectId);
715
+ continue;
716
+ }
717
+ const closed = Date.parse(board.closedAt);
718
+ if (!Number.isFinite(closed))
719
+ continue;
720
+ if (now - closed < LOCAL_RETENTION_MS) {
721
+ this.known.add(projectId);
722
+ continue;
723
+ }
724
+ try {
725
+ (0, node_fs_1.rmSync)((0, node_path_1.join)(paths_1.COORD_ROOT, projectId), { recursive: true, force: true });
726
+ this.known.delete(projectId);
727
+ this.dirty.delete(projectId);
728
+ }
729
+ catch {
730
+ // A locked file on Windows: the next pass retries.
731
+ }
732
+ }
733
+ }
734
+ /** Overlap pairs for the current board (used by the renderer and tests). */
735
+ overlapsFor(members) {
736
+ return (0, format_1.findOverlaps)(members
737
+ .filter((member) => !member.endedAt)
738
+ .map((member) => ({
739
+ agentId: member.agentId,
740
+ agentName: member.agentName,
741
+ areas: member.areas,
742
+ })));
743
+ }
744
+ }
745
+ exports.CoordinationMonitor = CoordinationMonitor;
746
+ //# sourceMappingURL=monitor.js.map