@linxiraos/pi-messenger 1.1.0

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 (58) hide show
  1. package/CHANGELOG.md +676 -0
  2. package/README.md +424 -0
  3. package/config-overlay.ts +171 -0
  4. package/config.ts +209 -0
  5. package/crew/agents/crew-plan-sync.md +64 -0
  6. package/crew/agents/crew-planner.md +172 -0
  7. package/crew/agents/crew-reviewer.md +58 -0
  8. package/crew/agents/crew-worker.md +129 -0
  9. package/crew/agents.ts +434 -0
  10. package/crew/handlers/coordination.ts +332 -0
  11. package/crew/handlers/plan.ts +906 -0
  12. package/crew/handlers/review.ts +333 -0
  13. package/crew/handlers/revise.ts +376 -0
  14. package/crew/handlers/status.ts +295 -0
  15. package/crew/handlers/sync.ts +233 -0
  16. package/crew/handlers/task.ts +792 -0
  17. package/crew/handlers/team.ts +235 -0
  18. package/crew/handlers/work.ts +425 -0
  19. package/crew/id-allocator.ts +30 -0
  20. package/crew/index.ts +257 -0
  21. package/crew/live-progress.ts +58 -0
  22. package/crew/lobby.ts +473 -0
  23. package/crew/prompt.ts +252 -0
  24. package/crew/registry.ts +114 -0
  25. package/crew/spawn.ts +111 -0
  26. package/crew/state-autonomous.ts +164 -0
  27. package/crew/state-planning.ts +263 -0
  28. package/crew/state.ts +20 -0
  29. package/crew/store.ts +642 -0
  30. package/crew/task-actions.ts +131 -0
  31. package/crew/team/store.ts +479 -0
  32. package/crew/team/subagent-roles.ts +87 -0
  33. package/crew/team/types.ts +50 -0
  34. package/crew/types.ts +194 -0
  35. package/crew/utils/artifacts.ts +62 -0
  36. package/crew/utils/config.ts +156 -0
  37. package/crew/utils/discover.ts +219 -0
  38. package/crew/utils/install.ts +85 -0
  39. package/crew/utils/progress.ts +187 -0
  40. package/crew/utils/result.ts +16 -0
  41. package/crew/utils/risk-labels.ts +7 -0
  42. package/crew/utils/task-format.ts +14 -0
  43. package/crew/utils/team-roles.ts +28 -0
  44. package/crew/utils/truncate.ts +79 -0
  45. package/crew/utils/verdict.ts +55 -0
  46. package/feed.ts +268 -0
  47. package/handlers.ts +1107 -0
  48. package/index.ts +1206 -0
  49. package/install.mjs +189 -0
  50. package/lib.ts +467 -0
  51. package/overlay-actions.ts +511 -0
  52. package/overlay-coordinator.ts +150 -0
  53. package/overlay-render.ts +676 -0
  54. package/overlay.ts +830 -0
  55. package/package.json +62 -0
  56. package/skills/pi-messenger-crew/SKILL.md +347 -0
  57. package/store.ts +1139 -0
  58. package/vitest.config.ts +10 -0
package/store.ts ADDED
@@ -0,0 +1,1139 @@
1
+ /**
2
+ * Pi Messenger - File Storage Operations
3
+ */
4
+
5
+ import * as fs from "node:fs";
6
+ import { randomUUID } from "node:crypto";
7
+ import { join, resolve } from "node:path";
8
+ import { execSync } from "node:child_process";
9
+ import type { ExtensionContext } from "@earendil-works/pi-coding-agent";
10
+ import {
11
+ type AgentRegistration,
12
+ type AgentMailMessage,
13
+ type ReservationConflict,
14
+ type MessengerState,
15
+ type Dirs,
16
+ type ClaimEntry,
17
+ type CompletionEntry,
18
+ type SpecClaims,
19
+ type SpecCompletions,
20
+ type AllClaims,
21
+ type AllCompletions,
22
+ type NameThemeConfig,
23
+ MAX_WATCHER_RETRIES,
24
+ isProcessAlive,
25
+ normalizeAgentMailMessage,
26
+ generateMemorableName,
27
+ isValidAgentName,
28
+ pathMatchesReservation,
29
+ } from "./lib.ts";
30
+
31
+ // =============================================================================
32
+ // Agents Cache (Fix 1: Reduce disk I/O)
33
+ // =============================================================================
34
+
35
+ interface AgentsCache {
36
+ allAgents: AgentRegistration[];
37
+ filtered: Map<string, AgentRegistration[]>; // keyed by excluded agent name
38
+ timestamp: number;
39
+ registryPath: string;
40
+ }
41
+
42
+ const AGENTS_CACHE_TTL_MS = 1000;
43
+ let agentsCache: AgentsCache | null = null;
44
+
45
+ export function invalidateAgentsCache(): void {
46
+ agentsCache = null;
47
+ }
48
+
49
+ // =============================================================================
50
+ // Message Processing Guard (Fix 3: Prevent race conditions)
51
+ // =============================================================================
52
+
53
+ let isProcessingMessages = false;
54
+ let pendingProcessArgs: {
55
+ state: MessengerState;
56
+ dirs: Dirs;
57
+ deliverFn: (msg: AgentMailMessage) => void;
58
+ } | null = null;
59
+
60
+ // =============================================================================
61
+ // File System Helpers
62
+ // =============================================================================
63
+
64
+ function ensureDirSync(dir: string): void {
65
+ if (!fs.existsSync(dir)) {
66
+ fs.mkdirSync(dir, { recursive: true });
67
+ }
68
+ }
69
+
70
+ function normalizeCwd(cwd: string): string {
71
+ try {
72
+ return fs.realpathSync.native(cwd);
73
+ } catch {
74
+ return resolve(cwd);
75
+ }
76
+ }
77
+
78
+ function getGitBranch(cwd: string): string | undefined {
79
+ try {
80
+ const result = execSync('git branch --show-current', {
81
+ cwd,
82
+ encoding: 'utf-8',
83
+ timeout: 2000,
84
+ stdio: ['pipe', 'pipe', 'pipe']
85
+ }).trim();
86
+
87
+ if (result) return result;
88
+
89
+ const sha = execSync('git rev-parse --short HEAD', {
90
+ cwd,
91
+ encoding: 'utf-8',
92
+ timeout: 2000,
93
+ stdio: ['pipe', 'pipe', 'pipe']
94
+ }).trim();
95
+
96
+ return sha ? `@${sha}` : undefined;
97
+ } catch {
98
+ return undefined;
99
+ }
100
+ }
101
+
102
+ const LOCK_STALE_MS = 10000;
103
+
104
+ async function withSwarmLock<T>(baseDir: string, fn: () => T): Promise<T> {
105
+ const lockPath = join(baseDir, "swarm.lock");
106
+ const maxRetries = 50;
107
+ const retryDelay = 100;
108
+
109
+ for (let i = 0; i < maxRetries; i++) {
110
+ try {
111
+ const stat = fs.statSync(lockPath);
112
+ const ageMs = Date.now() - stat.mtimeMs;
113
+ if (ageMs > LOCK_STALE_MS) {
114
+ try {
115
+ const pid = parseInt(fs.readFileSync(lockPath, "utf-8").trim(), 10);
116
+ if (!pid || !isProcessAlive(pid)) {
117
+ fs.unlinkSync(lockPath);
118
+ }
119
+ } catch {
120
+ try {
121
+ fs.unlinkSync(lockPath);
122
+ } catch {
123
+ // Ignore
124
+ }
125
+ }
126
+ }
127
+ } catch {
128
+ // Lock doesn't exist
129
+ }
130
+
131
+ try {
132
+ const fd = fs.openSync(lockPath, fs.constants.O_CREAT | fs.constants.O_EXCL | fs.constants.O_RDWR);
133
+ fs.writeSync(fd, String(process.pid));
134
+ fs.closeSync(fd);
135
+ break;
136
+ } catch (err) {
137
+ const code = (err as NodeJS.ErrnoException).code;
138
+ if (code === "EEXIST") {
139
+ if (i === maxRetries - 1) {
140
+ throw new Error("Failed to acquire swarm lock");
141
+ }
142
+ await new Promise(resolve => setTimeout(resolve, retryDelay));
143
+ continue;
144
+ }
145
+ throw err;
146
+ }
147
+ }
148
+
149
+ try {
150
+ return fn();
151
+ } finally {
152
+ try {
153
+ fs.unlinkSync(lockPath);
154
+ } catch {
155
+ // Ignore
156
+ }
157
+ }
158
+ }
159
+
160
+ // =============================================================================
161
+ // Registry Operations
162
+ // =============================================================================
163
+
164
+ export function getRegistrationPath(state: MessengerState, dirs: Dirs): string {
165
+ return join(dirs.registry, `${state.agentName}.json`);
166
+ }
167
+
168
+ export function getActiveAgents(state: MessengerState, dirs: Dirs): AgentRegistration[] {
169
+ const now = Date.now();
170
+ const excludeName = state.agentName;
171
+ const myCwd = normalizeCwd(state.cwd);
172
+ const scopeToFolder = state.scopeToFolder;
173
+
174
+ // Cache key includes scopeToFolder and cwd for proper cache invalidation
175
+ const cacheKey = scopeToFolder ? `${excludeName}:${myCwd}` : excludeName;
176
+
177
+ // Return cached if valid (Fix 1)
178
+ if (
179
+ agentsCache &&
180
+ agentsCache.registryPath === dirs.registry &&
181
+ now - agentsCache.timestamp < AGENTS_CACHE_TTL_MS
182
+ ) {
183
+ // Check if we have a cached filtered result for this cache key
184
+ const cachedFiltered = agentsCache.filtered.get(cacheKey);
185
+ if (cachedFiltered) return cachedFiltered;
186
+
187
+ // Create and cache filtered result
188
+ let filtered = agentsCache.allAgents.filter(a => a.name !== excludeName);
189
+ if (scopeToFolder) {
190
+ filtered = filtered.filter(a => a.cwd === myCwd);
191
+ }
192
+ agentsCache.filtered.set(cacheKey, filtered);
193
+ return filtered;
194
+ }
195
+
196
+ // Read from disk
197
+ const allAgents: AgentRegistration[] = [];
198
+
199
+ if (!fs.existsSync(dirs.registry)) {
200
+ agentsCache = { allAgents, filtered: new Map(), timestamp: now, registryPath: dirs.registry };
201
+ return allAgents;
202
+ }
203
+
204
+ let files: string[];
205
+ try {
206
+ files = fs.readdirSync(dirs.registry);
207
+ } catch {
208
+ return allAgents;
209
+ }
210
+
211
+ for (const file of files) {
212
+ if (!file.endsWith(".json")) continue;
213
+
214
+ try {
215
+ const content = fs.readFileSync(join(dirs.registry, file), "utf-8");
216
+ const reg: AgentRegistration = JSON.parse(content);
217
+
218
+ if (!isProcessAlive(reg.pid)) {
219
+ try {
220
+ fs.unlinkSync(join(dirs.registry, file));
221
+ } catch {
222
+ // Ignore cleanup errors
223
+ }
224
+ continue;
225
+ }
226
+
227
+ if (reg.session === undefined) {
228
+ reg.session = { toolCalls: 0, tokens: 0, filesModified: [] };
229
+ }
230
+ if (reg.activity === undefined) {
231
+ reg.activity = { lastActivityAt: reg.startedAt };
232
+ }
233
+ if (reg.isHuman === undefined) {
234
+ reg.isHuman = false;
235
+ }
236
+ reg.cwd = normalizeCwd(reg.cwd);
237
+ allAgents.push(reg);
238
+ } catch {
239
+ // Ignore malformed registrations
240
+ }
241
+ }
242
+
243
+ // Cache the full list and create filtered result
244
+ let filtered = allAgents.filter(a => a.name !== excludeName);
245
+ if (scopeToFolder) {
246
+ filtered = filtered.filter(a => a.cwd === myCwd);
247
+ }
248
+ const filteredMap = new Map<string, AgentRegistration[]>();
249
+ filteredMap.set(cacheKey, filtered);
250
+
251
+ agentsCache = { allAgents, filtered: filteredMap, timestamp: now, registryPath: dirs.registry };
252
+
253
+ return filtered;
254
+ }
255
+
256
+ export function findAvailableName(baseName: string, dirs: Dirs): string | null {
257
+ const basePath = join(dirs.registry, `${baseName}.json`);
258
+ if (!fs.existsSync(basePath)) return baseName;
259
+
260
+ try {
261
+ const existing: AgentRegistration = JSON.parse(fs.readFileSync(basePath, "utf-8"));
262
+ if (!isProcessAlive(existing.pid) || existing.pid === process.pid) {
263
+ return baseName;
264
+ }
265
+ } catch {
266
+ return baseName;
267
+ }
268
+
269
+ for (let i = 2; i <= 99; i++) {
270
+ const altName = `${baseName}${i}`;
271
+ const altPath = join(dirs.registry, `${altName}.json`);
272
+
273
+ if (!fs.existsSync(altPath)) return altName;
274
+
275
+ try {
276
+ const altReg: AgentRegistration = JSON.parse(fs.readFileSync(altPath, "utf-8"));
277
+ if (!isProcessAlive(altReg.pid)) return altName;
278
+ } catch {
279
+ return altName;
280
+ }
281
+ }
282
+
283
+ return null;
284
+ }
285
+
286
+ export function register(state: MessengerState, dirs: Dirs, ctx: ExtensionContext, nameTheme?: NameThemeConfig): boolean {
287
+ if (state.registered) return true;
288
+
289
+ ensureDirSync(dirs.registry);
290
+
291
+ if (!state.agentName) {
292
+ state.agentName = generateMemorableName(nameTheme);
293
+ }
294
+
295
+ const isExplicitName = !!process.env.PI_AGENT_NAME;
296
+ const maxAttempts = isExplicitName ? 1 : 3;
297
+
298
+ for (let attempt = 0; attempt < maxAttempts; attempt++) {
299
+ // Validate and find available name
300
+ if (isExplicitName) {
301
+ if (!isValidAgentName(state.agentName)) {
302
+ if (ctx.hasUI) {
303
+ ctx.ui.notify(`Invalid agent name "${state.agentName}" - use only letters, numbers, underscore, hyphen`, "error");
304
+ }
305
+ return false;
306
+ }
307
+ const regPath = join(dirs.registry, `${state.agentName}.json`);
308
+ if (fs.existsSync(regPath)) {
309
+ try {
310
+ const existing: AgentRegistration = JSON.parse(fs.readFileSync(regPath, "utf-8"));
311
+ if (isProcessAlive(existing.pid) && existing.pid !== process.pid) {
312
+ if (ctx.hasUI) {
313
+ ctx.ui.notify(`Agent name "${state.agentName}" already in use (PID ${existing.pid})`, "error");
314
+ }
315
+ return false;
316
+ }
317
+ } catch {
318
+ // Malformed, proceed to overwrite
319
+ }
320
+ }
321
+ } else {
322
+ const availableName = findAvailableName(state.agentName, dirs);
323
+ if (!availableName) {
324
+ if (ctx.hasUI) {
325
+ ctx.ui.notify("Could not find available agent name after 99 attempts", "error");
326
+ }
327
+ return false;
328
+ }
329
+ state.agentName = availableName;
330
+ }
331
+
332
+ const regPath = getRegistrationPath(state, dirs);
333
+ if (fs.existsSync(regPath)) {
334
+ try {
335
+ fs.unlinkSync(regPath);
336
+ } catch {
337
+ // Ignore
338
+ }
339
+ }
340
+
341
+ ensureDirSync(getMyInbox(state, dirs));
342
+
343
+ const cwd = normalizeCwd(ctx.cwd);
344
+ const gitBranch = getGitBranch(cwd);
345
+ const now = new Date().toISOString();
346
+ const registration: AgentRegistration = {
347
+ name: state.agentName,
348
+ pid: process.pid,
349
+ sessionId: ctx.sessionManager.getSessionId(),
350
+ cwd,
351
+ model: ctx.model?.id ?? "unknown",
352
+ startedAt: now,
353
+ gitBranch,
354
+ spec: state.spec,
355
+ isHuman: state.isHuman,
356
+ session: { ...state.session },
357
+ activity: { lastActivityAt: now },
358
+ };
359
+
360
+ try {
361
+ fs.writeFileSync(regPath, JSON.stringify(registration, null, 2));
362
+ } catch (err) {
363
+ if (ctx.hasUI) {
364
+ const msg = err instanceof Error ? err.message : "unknown error";
365
+ ctx.ui.notify(`Failed to register: ${msg}`, "error");
366
+ }
367
+ return false;
368
+ }
369
+
370
+ let verified = false;
371
+ let verifyError = false;
372
+ try {
373
+ const written: AgentRegistration = JSON.parse(fs.readFileSync(regPath, "utf-8"));
374
+ verified = written.pid === process.pid;
375
+ } catch {
376
+ verifyError = true;
377
+ }
378
+
379
+ if (verified) {
380
+ state.registered = true;
381
+ state.model = ctx.model?.id ?? "unknown";
382
+ state.cwd = cwd;
383
+ state.gitBranch = gitBranch;
384
+ state.activity.lastActivityAt = now;
385
+ invalidateAgentsCache();
386
+ return true;
387
+ }
388
+
389
+ // Verification failed - clean up our write attempt if file still contains our data
390
+ // (handles I/O error case where we wrote successfully but couldn't read back)
391
+ if (verifyError) {
392
+ try {
393
+ const checkContent = fs.readFileSync(regPath, "utf-8");
394
+ const checkReg: AgentRegistration = JSON.parse(checkContent);
395
+ if (checkReg.pid === process.pid) {
396
+ fs.unlinkSync(regPath);
397
+ }
398
+ } catch {
399
+ // Best effort cleanup
400
+ }
401
+ }
402
+
403
+ // Another agent claimed this name - retry with fresh lookup (auto-generated only)
404
+ if (isExplicitName) {
405
+ if (ctx.hasUI) {
406
+ ctx.ui.notify(`Agent name "${state.agentName}" was claimed by another agent`, "error");
407
+ }
408
+ return false;
409
+ }
410
+ invalidateAgentsCache();
411
+ }
412
+
413
+ // Exhausted retries
414
+ if (ctx.hasUI) {
415
+ ctx.ui.notify("Failed to register after multiple attempts due to name conflicts", "error");
416
+ }
417
+ return false;
418
+ }
419
+
420
+ export function updateRegistration(state: MessengerState, dirs: Dirs, ctx: ExtensionContext): void {
421
+ if (!state.registered) return;
422
+
423
+ const regPath = getRegistrationPath(state, dirs);
424
+ if (!fs.existsSync(regPath)) return;
425
+
426
+ try {
427
+ const reg: AgentRegistration = JSON.parse(fs.readFileSync(regPath, "utf-8"));
428
+ const currentModel = ctx.model?.id ?? reg.model;
429
+ reg.model = currentModel;
430
+ state.model = currentModel;
431
+ reg.cwd = state.cwd;
432
+ reg.reservations = state.reservations.length > 0 ? state.reservations : undefined;
433
+ if (state.spec) {
434
+ reg.spec = state.spec;
435
+ } else {
436
+ delete reg.spec;
437
+ }
438
+ reg.session = { ...state.session };
439
+ reg.activity = { ...state.activity };
440
+ reg.statusMessage = state.statusMessage;
441
+ fs.writeFileSync(regPath, JSON.stringify(reg, null, 2));
442
+ } catch {
443
+ // Ignore errors
444
+ }
445
+ }
446
+
447
+ export function flushActivityToRegistry(state: MessengerState, dirs: Dirs, ctx: ExtensionContext): void {
448
+ if (!state.registered) return;
449
+
450
+ const regPath = getRegistrationPath(state, dirs);
451
+ if (!fs.existsSync(regPath)) return;
452
+
453
+ try {
454
+ const reg: AgentRegistration = JSON.parse(fs.readFileSync(regPath, "utf-8"));
455
+ const currentModel = ctx.model?.id ?? reg.model;
456
+ reg.model = currentModel;
457
+ state.model = currentModel;
458
+ reg.cwd = state.cwd;
459
+ reg.session = { ...state.session };
460
+ reg.activity = { ...state.activity };
461
+ reg.statusMessage = state.statusMessage;
462
+ fs.writeFileSync(regPath, JSON.stringify(reg, null, 2));
463
+ } catch {
464
+ // Ignore errors
465
+ }
466
+ }
467
+
468
+ export function unregister(state: MessengerState, dirs: Dirs): void {
469
+ if (!state.registered) return;
470
+
471
+ const regPath = getRegistrationPath(state, dirs);
472
+ try {
473
+ fs.unlinkSync(regPath);
474
+ } catch (error) {
475
+ if (fs.existsSync(regPath)) {
476
+ throw error;
477
+ }
478
+ }
479
+
480
+ state.registered = false;
481
+ invalidateAgentsCache();
482
+ }
483
+
484
+ export type RenameResult =
485
+ | { success: true; oldName: string; newName: string }
486
+ | { success: false; error: "not_registered" | "invalid_name" | "name_taken" | "same_name" | "race_lost" };
487
+
488
+ export function renameAgent(
489
+ state: MessengerState,
490
+ dirs: Dirs,
491
+ ctx: ExtensionContext,
492
+ newName: string,
493
+ deliverFn: (msg: AgentMailMessage) => void
494
+ ): RenameResult {
495
+ if (!state.registered) {
496
+ return { success: false, error: "not_registered" };
497
+ }
498
+
499
+ if (!isValidAgentName(newName)) {
500
+ return { success: false, error: "invalid_name" };
501
+ }
502
+
503
+ if (newName === state.agentName) {
504
+ return { success: false, error: "same_name" };
505
+ }
506
+
507
+ const newRegPath = join(dirs.registry, `${newName}.json`);
508
+ if (fs.existsSync(newRegPath)) {
509
+ try {
510
+ const existing: AgentRegistration = JSON.parse(fs.readFileSync(newRegPath, "utf-8"));
511
+ if (isProcessAlive(existing.pid) && existing.pid !== process.pid) {
512
+ return { success: false, error: "name_taken" };
513
+ }
514
+ } catch {
515
+ // Malformed file, we can overwrite
516
+ }
517
+ }
518
+
519
+ const oldName = state.agentName;
520
+ const oldRegPath = getRegistrationPath(state, dirs);
521
+ const oldInbox = getMyInbox(state, dirs);
522
+ const newInbox = join(dirs.inbox, newName);
523
+
524
+ processAllPendingMessages(state, dirs, deliverFn);
525
+
526
+ const cwd = normalizeCwd(ctx.cwd);
527
+ const gitBranch = getGitBranch(cwd);
528
+ const now = new Date().toISOString();
529
+ const registration: AgentRegistration = {
530
+ name: newName,
531
+ pid: process.pid,
532
+ sessionId: ctx.sessionManager.getSessionId(),
533
+ cwd,
534
+ model: ctx.model?.id ?? "unknown",
535
+ startedAt: now,
536
+ reservations: state.reservations.length > 0 ? state.reservations : undefined,
537
+ gitBranch,
538
+ spec: state.spec,
539
+ isHuman: state.isHuman,
540
+ session: { ...state.session },
541
+ activity: { lastActivityAt: now },
542
+ statusMessage: state.statusMessage,
543
+ };
544
+
545
+ ensureDirSync(dirs.registry);
546
+
547
+ try {
548
+ fs.writeFileSync(join(dirs.registry, `${newName}.json`), JSON.stringify(registration, null, 2));
549
+ } catch (err) {
550
+ return { success: false, error: "invalid_name" as const };
551
+ }
552
+
553
+ // Verify we own the new registration (guards against race condition)
554
+ let verified = false;
555
+ let verifyError = false;
556
+ try {
557
+ const written: AgentRegistration = JSON.parse(fs.readFileSync(newRegPath, "utf-8"));
558
+ verified = written.pid === process.pid;
559
+ } catch {
560
+ verifyError = true;
561
+ }
562
+
563
+ if (!verified) {
564
+ // Clean up our write attempt if file still contains our data (I/O error case)
565
+ if (verifyError) {
566
+ try {
567
+ const checkReg: AgentRegistration = JSON.parse(fs.readFileSync(newRegPath, "utf-8"));
568
+ if (checkReg.pid === process.pid) {
569
+ fs.unlinkSync(newRegPath);
570
+ }
571
+ } catch {
572
+ // Best effort cleanup
573
+ }
574
+ }
575
+ return { success: false, error: "race_lost" };
576
+ }
577
+
578
+ try {
579
+ fs.unlinkSync(oldRegPath);
580
+ } catch {
581
+ // Ignore - old file might already be gone
582
+ }
583
+
584
+ state.agentName = newName;
585
+
586
+ if (fs.existsSync(newInbox)) {
587
+ try {
588
+ const staleFiles = fs.readdirSync(newInbox).filter(f => f.endsWith(".json"));
589
+ for (const file of staleFiles) {
590
+ try {
591
+ fs.unlinkSync(join(newInbox, file));
592
+ } catch {
593
+ // Ignore
594
+ }
595
+ }
596
+ } catch {
597
+ // Ignore
598
+ }
599
+ }
600
+ ensureDirSync(newInbox);
601
+
602
+ try {
603
+ fs.rmdirSync(oldInbox);
604
+ } catch {
605
+ // Ignore - might have new messages or not exist
606
+ }
607
+
608
+ state.model = ctx.model?.id ?? "unknown";
609
+ state.cwd = cwd;
610
+ state.gitBranch = gitBranch;
611
+ state.sessionStartedAt = now;
612
+ state.activity.lastActivityAt = now;
613
+ invalidateAgentsCache();
614
+ return { success: true, oldName, newName };
615
+ }
616
+
617
+ export function getConflictsWithOtherAgents(
618
+ filePath: string,
619
+ state: MessengerState,
620
+ dirs: Dirs
621
+ ): ReservationConflict[] {
622
+ const conflicts: ReservationConflict[] = [];
623
+ const agents = getActiveAgents(state, dirs);
624
+
625
+ for (const agent of agents) {
626
+ if (!agent.reservations) continue;
627
+ for (const res of agent.reservations) {
628
+ if (pathMatchesReservation(filePath, res.pattern)) {
629
+ conflicts.push({
630
+ path: filePath,
631
+ agent: agent.name,
632
+ pattern: res.pattern,
633
+ reason: res.reason,
634
+ registration: agent
635
+ });
636
+ }
637
+ }
638
+ }
639
+
640
+ return conflicts;
641
+ }
642
+
643
+ // =============================================================================
644
+ // Swarm Coordination
645
+ // =============================================================================
646
+
647
+ const CLAIMS_FILE = "claims.json";
648
+ const COMPLETIONS_FILE = "completions.json";
649
+
650
+ function readClaimsSync(dirs: Dirs): AllClaims {
651
+ const path = join(dirs.base, CLAIMS_FILE);
652
+ if (!fs.existsSync(path)) return {};
653
+ try {
654
+ const raw = fs.readFileSync(path, "utf-8");
655
+ const parsed = JSON.parse(raw) as AllClaims;
656
+ if (parsed && typeof parsed === "object") return parsed;
657
+ } catch {
658
+ // Ignore
659
+ }
660
+ return {};
661
+ }
662
+
663
+ function readCompletionsSync(dirs: Dirs): AllCompletions {
664
+ const path = join(dirs.base, COMPLETIONS_FILE);
665
+ if (!fs.existsSync(path)) return {};
666
+ try {
667
+ const raw = fs.readFileSync(path, "utf-8");
668
+ const parsed = JSON.parse(raw) as AllCompletions;
669
+ if (parsed && typeof parsed === "object") return parsed;
670
+ } catch {
671
+ // Ignore
672
+ }
673
+ return {};
674
+ }
675
+
676
+ function writeClaimsSync(dirs: Dirs, claims: AllClaims): void {
677
+ ensureDirSync(dirs.base);
678
+ const target = join(dirs.base, CLAIMS_FILE);
679
+ const temp = join(dirs.base, `${CLAIMS_FILE}.tmp-${process.pid}-${Date.now()}`);
680
+ fs.writeFileSync(temp, JSON.stringify(claims, null, 2));
681
+ fs.renameSync(temp, target);
682
+ }
683
+
684
+ function writeCompletionsSync(dirs: Dirs, completions: AllCompletions): void {
685
+ ensureDirSync(dirs.base);
686
+ const target = join(dirs.base, COMPLETIONS_FILE);
687
+ const temp = join(dirs.base, `${COMPLETIONS_FILE}.tmp-${process.pid}-${Date.now()}`);
688
+ fs.writeFileSync(temp, JSON.stringify(completions, null, 2));
689
+ fs.renameSync(temp, target);
690
+ }
691
+
692
+ function isClaimStale(claim: ClaimEntry, dirs: Dirs): boolean {
693
+ if (!isProcessAlive(claim.pid)) return true;
694
+ const regPath = join(dirs.registry, `${claim.agent}.json`);
695
+ if (!fs.existsSync(regPath)) return true;
696
+ try {
697
+ const reg: AgentRegistration = JSON.parse(fs.readFileSync(regPath, "utf-8"));
698
+ if (!isProcessAlive(reg.pid)) return true;
699
+ if (reg.sessionId !== claim.sessionId) return true;
700
+ } catch {
701
+ return true;
702
+ }
703
+ return false;
704
+ }
705
+
706
+ function cleanupStaleClaims(claims: AllClaims, dirs: Dirs): number {
707
+ let removed = 0;
708
+ for (const [spec, tasks] of Object.entries(claims)) {
709
+ for (const [taskId, claim] of Object.entries(tasks)) {
710
+ if (isClaimStale(claim, dirs)) {
711
+ delete tasks[taskId];
712
+ removed++;
713
+ }
714
+ }
715
+ if (Object.keys(tasks).length === 0) {
716
+ delete claims[spec];
717
+ }
718
+ }
719
+ return removed;
720
+ }
721
+
722
+ function filterStaleClaims(claims: AllClaims, dirs: Dirs): AllClaims {
723
+ const filtered: AllClaims = {};
724
+ for (const [spec, tasks] of Object.entries(claims)) {
725
+ const filteredTasks: SpecClaims = {};
726
+ for (const [taskId, claim] of Object.entries(tasks)) {
727
+ if (!isClaimStale(claim, dirs)) {
728
+ filteredTasks[taskId] = claim;
729
+ }
730
+ }
731
+ if (Object.keys(filteredTasks).length > 0) {
732
+ filtered[spec] = filteredTasks;
733
+ }
734
+ }
735
+ return filtered;
736
+ }
737
+
738
+ function findAgentClaim(claims: AllClaims, agent: string): { spec: string; taskId: string } | null {
739
+ for (const [spec, tasks] of Object.entries(claims)) {
740
+ for (const [taskId, claim] of Object.entries(tasks)) {
741
+ if (claim.agent === agent) {
742
+ return { spec, taskId };
743
+ }
744
+ }
745
+ }
746
+ return null;
747
+ }
748
+
749
+ export function getClaims(dirs: Dirs): AllClaims {
750
+ const claims = readClaimsSync(dirs);
751
+ return filterStaleClaims(claims, dirs);
752
+ }
753
+
754
+ export function getClaimsForSpec(dirs: Dirs, specPath: string): SpecClaims {
755
+ const claims = getClaims(dirs);
756
+ return claims[specPath] ?? {};
757
+ }
758
+
759
+ export function getCompletions(dirs: Dirs): AllCompletions {
760
+ return readCompletionsSync(dirs);
761
+ }
762
+
763
+ export function getCompletionsForSpec(dirs: Dirs, specPath: string): SpecCompletions {
764
+ const completions = getCompletions(dirs);
765
+ return completions[specPath] ?? {};
766
+ }
767
+
768
+ export function getAgentCurrentClaim(
769
+ dirs: Dirs,
770
+ agent: string
771
+ ): { spec: string; taskId: string; reason?: string } | null {
772
+ const claims = getClaims(dirs);
773
+ for (const [spec, tasks] of Object.entries(claims)) {
774
+ for (const [taskId, claim] of Object.entries(tasks)) {
775
+ if (claim.agent === agent) {
776
+ return { spec, taskId, reason: claim.reason };
777
+ }
778
+ }
779
+ }
780
+ return null;
781
+ }
782
+
783
+ export type ClaimResult =
784
+ | { success: true; claimedAt: string }
785
+ | { success: false; error: "already_claimed"; conflict: ClaimEntry }
786
+ | { success: false; error: "already_have_claim"; existing: { spec: string; taskId: string } };
787
+
788
+ export function isClaimSuccess(r: ClaimResult): r is { success: true; claimedAt: string } {
789
+ return r.success === true;
790
+ }
791
+ export function isClaimAlreadyClaimed(r: ClaimResult): r is { success: false; error: "already_claimed"; conflict: ClaimEntry } {
792
+ return "error" in r && r.error === "already_claimed";
793
+ }
794
+ export function isClaimAlreadyHaveClaim(r: ClaimResult): r is { success: false; error: "already_have_claim"; existing: { spec: string; taskId: string } } {
795
+ return "error" in r && r.error === "already_have_claim";
796
+ }
797
+
798
+ export async function claimTask(
799
+ dirs: Dirs,
800
+ specPath: string,
801
+ taskId: string,
802
+ agent: string,
803
+ sessionId: string,
804
+ pid: number,
805
+ reason?: string
806
+ ): Promise<ClaimResult> {
807
+ return withSwarmLock(dirs.base, () => {
808
+ const claims = readClaimsSync(dirs);
809
+ const removed = cleanupStaleClaims(claims, dirs);
810
+
811
+ const existing = findAgentClaim(claims, agent);
812
+ if (existing) {
813
+ if (removed > 0) writeClaimsSync(dirs, claims);
814
+ return { success: false, error: "already_have_claim", existing };
815
+ }
816
+
817
+ const existingClaim = claims[specPath]?.[taskId];
818
+ if (existingClaim) {
819
+ if (removed > 0) writeClaimsSync(dirs, claims);
820
+ return { success: false, error: "already_claimed", conflict: existingClaim };
821
+ }
822
+
823
+ if (!claims[specPath]) claims[specPath] = {};
824
+ const newClaim: ClaimEntry = {
825
+ agent,
826
+ sessionId,
827
+ pid,
828
+ claimedAt: new Date().toISOString(),
829
+ reason
830
+ };
831
+ claims[specPath][taskId] = newClaim;
832
+ writeClaimsSync(dirs, claims);
833
+ return { success: true, claimedAt: newClaim.claimedAt };
834
+ });
835
+ }
836
+
837
+ export type UnclaimResult =
838
+ | { success: true }
839
+ | { success: false; error: "not_claimed" }
840
+ | { success: false; error: "not_your_claim"; claimedBy: string };
841
+
842
+ export function isUnclaimSuccess(r: UnclaimResult): r is { success: true } {
843
+ return r.success === true;
844
+ }
845
+ export function isUnclaimNotYours(r: UnclaimResult): r is { success: false; error: "not_your_claim"; claimedBy: string } {
846
+ return "error" in r && r.error === "not_your_claim";
847
+ }
848
+
849
+ export async function unclaimTask(
850
+ dirs: Dirs,
851
+ specPath: string,
852
+ taskId: string,
853
+ agent: string
854
+ ): Promise<UnclaimResult> {
855
+ return withSwarmLock(dirs.base, () => {
856
+ const claims = readClaimsSync(dirs);
857
+ const removed = cleanupStaleClaims(claims, dirs);
858
+
859
+ const claim = claims[specPath]?.[taskId];
860
+ if (!claim) {
861
+ if (removed > 0) writeClaimsSync(dirs, claims);
862
+ return { success: false, error: "not_claimed" };
863
+ }
864
+ if (claim.agent !== agent) {
865
+ if (removed > 0) writeClaimsSync(dirs, claims);
866
+ return { success: false, error: "not_your_claim", claimedBy: claim.agent };
867
+ }
868
+
869
+ delete claims[specPath][taskId];
870
+ if (Object.keys(claims[specPath]).length === 0) {
871
+ delete claims[specPath];
872
+ }
873
+ writeClaimsSync(dirs, claims);
874
+ return { success: true };
875
+ });
876
+ }
877
+
878
+ export type CompleteResult =
879
+ | { success: true; completedAt: string }
880
+ | { success: false; error: "not_claimed" }
881
+ | { success: false; error: "not_your_claim"; claimedBy: string }
882
+ | { success: false; error: "already_completed"; completion: CompletionEntry };
883
+
884
+ export function isCompleteSuccess(r: CompleteResult): r is { success: true; completedAt: string } {
885
+ return r.success === true;
886
+ }
887
+ export function isCompleteAlreadyCompleted(r: CompleteResult): r is { success: false; error: "already_completed"; completion: CompletionEntry } {
888
+ return "error" in r && r.error === "already_completed";
889
+ }
890
+ export function isCompleteNotYours(r: CompleteResult): r is { success: false; error: "not_your_claim"; claimedBy: string } {
891
+ return "error" in r && r.error === "not_your_claim";
892
+ }
893
+
894
+ export async function completeTask(
895
+ dirs: Dirs,
896
+ specPath: string,
897
+ taskId: string,
898
+ agent: string,
899
+ notes?: string
900
+ ): Promise<CompleteResult> {
901
+ return withSwarmLock(dirs.base, () => {
902
+ const claims = readClaimsSync(dirs);
903
+ const completions = readCompletionsSync(dirs);
904
+ const removed = cleanupStaleClaims(claims, dirs);
905
+
906
+ const existingCompletion = completions[specPath]?.[taskId];
907
+ if (existingCompletion) {
908
+ if (removed > 0) writeClaimsSync(dirs, claims);
909
+ return { success: false, error: "already_completed", completion: existingCompletion };
910
+ }
911
+
912
+ const claim = claims[specPath]?.[taskId];
913
+ if (!claim) {
914
+ if (removed > 0) writeClaimsSync(dirs, claims);
915
+ return { success: false, error: "not_claimed" };
916
+ }
917
+ if (claim.agent !== agent) {
918
+ if (removed > 0) writeClaimsSync(dirs, claims);
919
+ return { success: false, error: "not_your_claim", claimedBy: claim.agent };
920
+ }
921
+
922
+ delete claims[specPath][taskId];
923
+ if (Object.keys(claims[specPath]).length === 0) {
924
+ delete claims[specPath];
925
+ }
926
+
927
+ if (!completions[specPath]) completions[specPath] = {};
928
+ const completion: CompletionEntry = {
929
+ completedBy: agent,
930
+ completedAt: new Date().toISOString(),
931
+ notes
932
+ };
933
+ completions[specPath][taskId] = completion;
934
+
935
+ // Write completions first - if claims write fails, we at least have the completion
936
+ // recorded (the important part). The stale claim will be cleaned up eventually.
937
+ writeCompletionsSync(dirs, completions);
938
+ writeClaimsSync(dirs, claims);
939
+ return { success: true, completedAt: completion.completedAt };
940
+ });
941
+ }
942
+
943
+ // =============================================================================
944
+ // Messaging Operations
945
+ // =============================================================================
946
+
947
+ export function getMyInbox(state: MessengerState, dirs: Dirs): string {
948
+ return join(dirs.inbox, state.agentName);
949
+ }
950
+
951
+ export function processAllPendingMessages(
952
+ state: MessengerState,
953
+ dirs: Dirs,
954
+ deliverFn: (msg: AgentMailMessage) => void
955
+ ): void {
956
+ if (!state.registered) return;
957
+
958
+ // Fix 3: Prevent concurrent processing
959
+ if (isProcessingMessages) {
960
+ pendingProcessArgs = { state, dirs, deliverFn };
961
+ return;
962
+ }
963
+
964
+ isProcessingMessages = true;
965
+
966
+ try {
967
+ const inbox = getMyInbox(state, dirs);
968
+ if (!fs.existsSync(inbox)) return;
969
+
970
+ let files: string[];
971
+ try {
972
+ files = fs.readdirSync(inbox).filter(f => f.endsWith(".json")).sort();
973
+ } catch {
974
+ return;
975
+ }
976
+
977
+ for (const file of files) {
978
+ const msgPath = join(inbox, file);
979
+ try {
980
+ const content = fs.readFileSync(msgPath, "utf-8");
981
+ const msg = normalizeAgentMailMessage(JSON.parse(content), {
982
+ id: file.endsWith(".json") ? file.slice(0, -5) : file,
983
+ from: "unknown",
984
+ to: state.agentName,
985
+ timestamp: new Date().toISOString(),
986
+ });
987
+ deliverFn(msg);
988
+ fs.unlinkSync(msgPath);
989
+ } catch {
990
+ // On any failure (read, parse, deliver), delete to avoid infinite retry loops
991
+ try {
992
+ fs.unlinkSync(msgPath);
993
+ } catch {
994
+ // Already gone or can't delete
995
+ }
996
+ }
997
+ }
998
+ } finally {
999
+ isProcessingMessages = false;
1000
+
1001
+ // Re-process if new calls came in while we were processing
1002
+ if (pendingProcessArgs) {
1003
+ const args = pendingProcessArgs;
1004
+ pendingProcessArgs = null;
1005
+ processAllPendingMessages(args.state, args.dirs, args.deliverFn);
1006
+ }
1007
+ }
1008
+ }
1009
+
1010
+ export function sendMessageToAgent(
1011
+ state: MessengerState,
1012
+ dirs: Dirs,
1013
+ to: string,
1014
+ text: string,
1015
+ replyTo?: string
1016
+ ): AgentMailMessage {
1017
+ const targetInbox = join(dirs.inbox, to);
1018
+ ensureDirSync(targetInbox);
1019
+
1020
+ const msg: AgentMailMessage = {
1021
+ id: randomUUID(),
1022
+ from: state.agentName,
1023
+ to,
1024
+ text,
1025
+ timestamp: new Date().toISOString(),
1026
+ replyTo: replyTo ?? null
1027
+ };
1028
+
1029
+ const random = Math.random().toString(36).substring(2, 8);
1030
+ const msgFile = join(targetInbox, `${Date.now()}-${random}.json`);
1031
+ fs.writeFileSync(msgFile, JSON.stringify(msg, null, 2));
1032
+
1033
+ return msg;
1034
+ }
1035
+
1036
+ // =============================================================================
1037
+ // Watcher
1038
+ // =============================================================================
1039
+
1040
+ const WATCHER_DEBOUNCE_MS = 50;
1041
+
1042
+ export function startWatcher(
1043
+ state: MessengerState,
1044
+ dirs: Dirs,
1045
+ deliverFn: (msg: AgentMailMessage) => void
1046
+ ): void {
1047
+ if (!state.registered) return;
1048
+ if (state.watcher) return;
1049
+ if (state.watcherRetries >= MAX_WATCHER_RETRIES) return;
1050
+
1051
+ const inbox = getMyInbox(state, dirs);
1052
+ ensureDirSync(inbox);
1053
+
1054
+ processAllPendingMessages(state, dirs, deliverFn);
1055
+
1056
+ function scheduleRetry(): void {
1057
+ state.watcherRetries++;
1058
+ if (state.watcherRetries < MAX_WATCHER_RETRIES) {
1059
+ const delay = Math.min(1000 * Math.pow(2, state.watcherRetries - 1), 30000);
1060
+ state.watcherRetryTimer = setTimeout(() => {
1061
+ state.watcherRetryTimer = null;
1062
+ startWatcher(state, dirs, deliverFn);
1063
+ }, delay);
1064
+ }
1065
+ }
1066
+
1067
+ try {
1068
+ state.watcher = fs.watch(inbox, () => {
1069
+ // Fix 2: Debounce rapid events
1070
+ if (state.watcherDebounceTimer) {
1071
+ clearTimeout(state.watcherDebounceTimer);
1072
+ }
1073
+ state.watcherDebounceTimer = setTimeout(() => {
1074
+ state.watcherDebounceTimer = null;
1075
+ processAllPendingMessages(state, dirs, deliverFn);
1076
+ }, WATCHER_DEBOUNCE_MS);
1077
+ });
1078
+ } catch {
1079
+ scheduleRetry();
1080
+ return;
1081
+ }
1082
+
1083
+ state.watcher.on("error", () => {
1084
+ stopWatcher(state);
1085
+ scheduleRetry();
1086
+ });
1087
+
1088
+ state.watcherRetries = 0;
1089
+ }
1090
+
1091
+ export function stopWatcher(state: MessengerState): void {
1092
+ if (state.watcherDebounceTimer) {
1093
+ clearTimeout(state.watcherDebounceTimer);
1094
+ state.watcherDebounceTimer = null;
1095
+ }
1096
+ if (state.watcherRetryTimer) {
1097
+ clearTimeout(state.watcherRetryTimer);
1098
+ state.watcherRetryTimer = null;
1099
+ }
1100
+ if (state.watcher) {
1101
+ state.watcher.close();
1102
+ state.watcher = null;
1103
+ }
1104
+ }
1105
+
1106
+ // =============================================================================
1107
+ // Target Validation
1108
+ // =============================================================================
1109
+
1110
+ export type TargetValidation =
1111
+ | { valid: true }
1112
+ | { valid: false; error: "invalid_name" | "not_found" | "not_active" | "invalid_registration" };
1113
+
1114
+ export function validateTargetAgent(to: string, dirs: Dirs): TargetValidation {
1115
+ if (!isValidAgentName(to)) {
1116
+ return { valid: false, error: "invalid_name" };
1117
+ }
1118
+
1119
+ const targetReg = join(dirs.registry, `${to}.json`);
1120
+ if (!fs.existsSync(targetReg)) {
1121
+ return { valid: false, error: "not_found" };
1122
+ }
1123
+
1124
+ try {
1125
+ const reg: AgentRegistration = JSON.parse(fs.readFileSync(targetReg, "utf-8"));
1126
+ if (!isProcessAlive(reg.pid)) {
1127
+ try {
1128
+ fs.unlinkSync(targetReg);
1129
+ } catch {
1130
+ // Ignore cleanup errors
1131
+ }
1132
+ return { valid: false, error: "not_active" };
1133
+ }
1134
+ } catch {
1135
+ return { valid: false, error: "invalid_registration" };
1136
+ }
1137
+
1138
+ return { valid: true };
1139
+ }