memorix 1.4.5 → 1.5.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 (75) hide show
  1. package/CHANGELOG.md +78 -0
  2. package/CLAUDE.md +7 -3
  3. package/README.md +5 -2
  4. package/dist/cli/index.js +1470 -1014
  5. package/dist/index.js +1279 -989
  6. package/dist/{maintenance-jobs-B1-W0ssz.d.ts → maintenance-jobs-DVRF-46r.d.ts} +1 -1
  7. package/dist/maintenance-runner.d.ts +1 -1
  8. package/dist/maintenance-runner.js +1769 -830
  9. package/dist/media-audio-runner.js +1774 -836
  10. package/dist/media-video-runner.js +1769 -831
  11. package/dist/memcode-runtime/CHANGELOG.md +78 -0
  12. package/dist/sdk.js +1271 -988
  13. package/dist/types.d.ts +6 -0
  14. package/dist/vector-backfill-runner.d.ts +1 -1
  15. package/dist/vector-backfill-runner.js +1765 -827
  16. package/docs/1.4.5-AGENT-AUTO-MEMORY-RESEARCH.md +95 -0
  17. package/docs/API_REFERENCE.md +23 -4
  18. package/docs/CONFIGURATION.md +29 -3
  19. package/docs/SETUP.md +5 -3
  20. package/package.json +1 -1
  21. package/plugins/antigravity/memorix/mcp_config.json +3 -1
  22. package/plugins/claude/memorix/.claude-plugin/plugin.json +1 -1
  23. package/plugins/claude/memorix/.mcp.json +1 -1
  24. package/plugins/codebuddy/memorix/.codebuddy-plugin/plugin.json +1 -1
  25. package/plugins/codebuddy/memorix/.mcp.json +1 -1
  26. package/plugins/codex/memorix/.codex-plugin/plugin.json +1 -1
  27. package/plugins/codex/memorix/.mcp.json +1 -1
  28. package/plugins/copilot/memorix/.mcp.json +1 -1
  29. package/plugins/copilot/memorix/plugin.json +1 -1
  30. package/plugins/gemini/memorix/gemini-extension.json +4 -2
  31. package/plugins/omp/memorix/package.json +1 -1
  32. package/plugins/openclaw/memorix/.codex-plugin/plugin.json +1 -1
  33. package/plugins/openclaw/memorix/.mcp.json +3 -1
  34. package/plugins/pi/memorix/package.json +1 -1
  35. package/server.json +2 -2
  36. package/src/cli/commands/dashboard.ts +14 -3
  37. package/src/cli/commands/ingest-commit.ts +47 -3
  38. package/src/cli/commands/memory.ts +17 -4
  39. package/src/cli/commands/purge.ts +120 -0
  40. package/src/cli/commands/serve-http.ts +39 -5
  41. package/src/cli/commands/setup.ts +3 -1
  42. package/src/cli/index.ts +3 -804
  43. package/src/codegraph/auto-context.ts +82 -1
  44. package/src/config/yaml-loader.ts +3 -8
  45. package/src/config.ts +23 -7
  46. package/src/evaluation/session-replay.ts +98 -0
  47. package/src/git/extractor.ts +5 -3
  48. package/src/hooks/installers/index.ts +15 -0
  49. package/src/knowledge/workset.ts +58 -0
  50. package/src/memory/long-term.ts +97 -2
  51. package/src/runtime/control-plane-maintenance.ts +1 -0
  52. package/src/runtime/isolated-maintenance.ts +1 -0
  53. package/src/runtime/lifecycle.ts +19 -0
  54. package/src/runtime/maintenance-jobs.ts +1 -0
  55. package/src/runtime/project-maintenance.ts +8 -0
  56. package/src/search/surfaced-registry.ts +62 -0
  57. package/src/server.ts +74 -14
  58. package/src/store/orama-store.ts +17 -1
  59. package/src/types.ts +6 -0
  60. package/src/cli/commands/audit-list.ts +0 -89
  61. package/src/cli/commands/purge-all-memory.ts +0 -85
  62. package/src/cli/commands/purge-project-memory.ts +0 -83
  63. package/src/cli/commands/uninstall-project-artifacts.ts +0 -86
  64. package/src/cli/tui/Sidebar.tsx +0 -179
  65. package/src/cli/tui/interactive-commands.ts +0 -261
  66. package/src/cli/tui/markdown-render.tsx +0 -371
  67. package/src/cli/tui/use-mouse.ts +0 -157
  68. package/src/cli/tui/useNavigation.ts +0 -56
  69. package/src/orchestrate/context-compact.ts +0 -188
  70. package/src/team/file-locks.ts +0 -173
  71. package/src/team/index.ts +0 -23
  72. package/src/team/messages.ts +0 -203
  73. package/src/team/persistence.ts +0 -96
  74. package/src/team/registry.ts +0 -158
  75. package/src/team/tasks.ts +0 -211
@@ -1,188 +0,0 @@
1
- /**
2
- * Context Compaction — Phase 7, Step 6: 4-layer compaction for long pipelines.
3
- *
4
- * Prevents context overflow by progressively compacting older content:
5
- * Layer 1: Tool Result Micro-Compact — trim old ledger entries to short placeholders
6
- * Layer 2: Gate Output Compact — handled by output-budget.ts (trimAndPersist)
7
- * Layer 3: Fix Prompt Compaction — summarize previous fix attempts
8
- * Layer 4: Pipeline-Level Compaction — compact old tasks in long pipelines
9
- *
10
- * Circuit Breaker: if compaction fails, fall back to simple truncation
11
- * (first 500 + last 500 chars). Never let compaction crash the pipeline.
12
- */
13
-
14
- import { trimToBudget } from './output-budget.js';
15
-
16
- // ── Types ──────────────────────────────────────────────────────────
17
-
18
- export interface CompactionConfig {
19
- /** Max number of full ledger entries to keep (older ones get compacted). Default: 5 */
20
- maxFullEntries: number;
21
- /** Max total chars for all fix attempt summaries. Default: 2000 */
22
- fixHistoryBudget: number;
23
- /** Pipeline task count threshold for pipeline-level compaction. Default: 20 */
24
- pipelineCompactThreshold: number;
25
- /** Number of recent tasks to keep in full detail during pipeline compaction. Default: 5 */
26
- recentTaskWindow: number;
27
- }
28
-
29
- export const DEFAULT_COMPACTION_CONFIG: CompactionConfig = {
30
- maxFullEntries: 5,
31
- fixHistoryBudget: 2000,
32
- pipelineCompactThreshold: 20,
33
- recentTaskWindow: 5,
34
- };
35
-
36
- export interface LedgerEntry {
37
- taskId: string;
38
- role: string;
39
- agent: string;
40
- status: 'completed' | 'failed';
41
- summary: string;
42
- durationMs: number;
43
- }
44
-
45
- export interface FixAttemptRecord {
46
- attempt: number;
47
- gate: string;
48
- errorOutput: string;
49
- fixOutput: string;
50
- passed: boolean;
51
- }
52
-
53
- // ── Layer 1: Tool Result Micro-Compact ─────────────────────────────
54
-
55
- /**
56
- * Compact old ledger entries: keep only the N most recent in full detail,
57
- * replace older ones with one-line placeholders.
58
- *
59
- * Never throws — returns input unchanged on error.
60
- */
61
- export function compactLedgerEntries(
62
- entries: LedgerEntry[],
63
- config: CompactionConfig = DEFAULT_COMPACTION_CONFIG,
64
- ): string {
65
- try {
66
- if (entries.length <= config.maxFullEntries) {
67
- return entries.map(formatFullEntry).join('\n');
68
- }
69
-
70
- const oldEntries = entries.slice(0, entries.length - config.maxFullEntries);
71
- const recentEntries = entries.slice(-config.maxFullEntries);
72
-
73
- const compactedOld = oldEntries.map(e => {
74
- const status = e.status === 'completed' ? '[OK]' : '[ERROR]';
75
- return ` ${status} ${e.role}/${e.agent}: ${e.summary.slice(0, 60)}`;
76
- }).join('\n');
77
-
78
- const compactedHeader = `### Earlier tasks (${oldEntries.length} compacted)\n${compactedOld}`;
79
- const recentSection = `### Recent tasks (${recentEntries.length} full)\n${recentEntries.map(formatFullEntry).join('\n')}`;
80
-
81
- return `${compactedHeader}\n\n${recentSection}`;
82
- } catch {
83
- // Circuit breaker: return raw entries on failure
84
- return entries.map(formatFullEntry).join('\n');
85
- }
86
- }
87
-
88
- // ── Layer 3: Fix Prompt Compaction ─────────────────────────────────
89
-
90
- /**
91
- * Compact fix attempt history for inclusion in the next fix prompt.
92
- * After the first attempt, summarize previous attempts instead of
93
- * including full error + fix outputs each time.
94
- *
95
- * Never throws — returns simple concatenation on error.
96
- */
97
- export function compactFixHistory(
98
- attempts: FixAttemptRecord[],
99
- config: CompactionConfig = DEFAULT_COMPACTION_CONFIG,
100
- ): string {
101
- try {
102
- if (attempts.length === 0) return '';
103
-
104
- // First attempt: no history needed
105
- if (attempts.length === 1) {
106
- return formatFixAttempt(attempts[0]);
107
- }
108
-
109
- // Multiple attempts: summarize older, keep latest full
110
- const older = attempts.slice(0, -1);
111
- const latest = attempts[attempts.length - 1];
112
-
113
- const olderSummary = older.map((a, i) => {
114
- const status = a.passed ? 'PASSED' : 'FAILED';
115
- return ` - Attempt ${i + 1}: ${status} (${a.gate}) — ${a.errorOutput.slice(0, 80)}`;
116
- }).join('\n');
117
-
118
- let history = `### Previous fix attempts (${older.length} summarized)\n${olderSummary}`;
119
-
120
- // Enforce budget on history section
121
- if (history.length > config.fixHistoryBudget) {
122
- history = trimToBudget(history, config.fixHistoryBudget);
123
- }
124
-
125
- return `${history}\n\n### Latest attempt\n${formatFixAttempt(latest)}`;
126
- } catch {
127
- // Circuit breaker: simple concatenation
128
- return attempts.map(formatFixAttempt).join('\n---\n');
129
- }
130
- }
131
-
132
- // ── Layer 4: Pipeline-Level Compaction ─────────────────────────────
133
-
134
- /**
135
- * Compact an entire pipeline's task list for prompt injection.
136
- * For long pipelines (>threshold tasks), compact older entries into
137
- * a summary paragraph, keeping only the recent N tasks in full.
138
- *
139
- * Never throws — returns full list on error.
140
- */
141
- export function compactPipelineContext(
142
- entries: LedgerEntry[],
143
- config: CompactionConfig = DEFAULT_COMPACTION_CONFIG,
144
- ): string {
145
- try {
146
- if (entries.length <= config.pipelineCompactThreshold) {
147
- return compactLedgerEntries(entries, config);
148
- }
149
-
150
- const oldEntries = entries.slice(0, entries.length - config.recentTaskWindow);
151
- const recentEntries = entries.slice(-config.recentTaskWindow);
152
-
153
- // Summary stats for old entries
154
- const completedCount = oldEntries.filter(e => e.status === 'completed').length;
155
- const failedCount = oldEntries.filter(e => e.status === 'failed').length;
156
- const roles = [...new Set(oldEntries.map(e => e.role))];
157
-
158
- const summary = [
159
- `### Pipeline progress (${entries.length} total tasks)`,
160
- `${oldEntries.length} earlier tasks: ${completedCount} completed, ${failedCount} failed.`,
161
- `Roles involved: ${roles.join(', ')}.`,
162
- ].join('\n');
163
-
164
- const recentSection = `### Recent tasks (${recentEntries.length} full detail)\n${recentEntries.map(formatFullEntry).join('\n')}`;
165
-
166
- return `${summary}\n\n${recentSection}`;
167
- } catch {
168
- // Circuit breaker: return full list via basic compaction
169
- return compactLedgerEntries(entries, config);
170
- }
171
- }
172
-
173
- // ── Helpers ────────────────────────────────────────────────────────
174
-
175
- function formatFullEntry(e: LedgerEntry): string {
176
- const status = e.status === 'completed' ? '[OK]' : '[ERROR]';
177
- const duration = `${(e.durationMs / 1000).toFixed(1)}s`;
178
- return `- [${status}] **${e.role}** (${e.agent}, ${duration}): ${e.summary}`;
179
- }
180
-
181
- function formatFixAttempt(a: FixAttemptRecord): string {
182
- const status = a.passed ? 'PASSED' : 'FAILED';
183
- return [
184
- `**Attempt ${a.attempt}** [${status}] — ${a.gate} gate`,
185
- `Error: ${a.errorOutput.slice(0, 300)}`,
186
- `Fix: ${a.fixOutput.slice(0, 300)}`,
187
- ].join('\n');
188
- }
@@ -1,173 +0,0 @@
1
- /**
2
- * File Lock Registry — Advisory file locks for multi-agent coordination
3
- *
4
- * Prevents conflicting edits when multiple agents work on the same project.
5
- * Locks are advisory (not enforced at OS level) with TTL auto-release.
6
- * Default TTL: 10 minutes. Agents see lock status via session_start injection.
7
- */
8
-
9
- // ─── Types ───────────────────────────────────────────────────────────
10
-
11
- export interface LockResult {
12
- success: boolean;
13
- lockedBy: string;
14
- file: string;
15
- }
16
-
17
- export interface LockInfo {
18
- file: string;
19
- lockedBy: string;
20
- lockedAt: Date;
21
- expiresAt: Date;
22
- }
23
-
24
- export interface LockOptions {
25
- ttlMs?: number;
26
- }
27
-
28
- const DEFAULT_TTL_MS = 10 * 60 * 1000; // 10 minutes
29
-
30
- // ─── Internal Lock Entry ─────────────────────────────────────────────
31
-
32
- interface LockEntry {
33
- file: string;
34
- lockedBy: string;
35
- lockedAt: Date;
36
- expiresAt: Date;
37
- }
38
-
39
- // ─── Registry ────────────────────────────────────────────────────────
40
-
41
- export class FileLockRegistry {
42
- private locks = new Map<string, LockEntry>();
43
-
44
- /**
45
- * Attempt to lock a file for an agent.
46
- * Returns success:true if lock acquired, or success:false with current owner.
47
- * Same agent re-locking is idempotent (refreshes TTL).
48
- */
49
- lock(file: string, agentId: string, options?: LockOptions): LockResult {
50
- const ttl = options?.ttlMs ?? DEFAULT_TTL_MS;
51
-
52
- // Clean expired locks first
53
- this.cleanExpiredEntry(file);
54
-
55
- const existing = this.locks.get(file);
56
-
57
- if (existing) {
58
- if (existing.lockedBy === agentId) {
59
- // Same agent — refresh TTL
60
- existing.expiresAt = new Date(Date.now() + ttl);
61
- return { success: true, lockedBy: agentId, file };
62
- }
63
- // Different agent holds the lock
64
- return { success: false, lockedBy: existing.lockedBy, file };
65
- }
66
-
67
- // No lock — acquire
68
- const now = new Date();
69
- this.locks.set(file, {
70
- file,
71
- lockedBy: agentId,
72
- lockedAt: now,
73
- expiresAt: new Date(now.getTime() + ttl),
74
- });
75
-
76
- return { success: true, lockedBy: agentId, file };
77
- }
78
-
79
- /**
80
- * Release a lock. Only the owner can release.
81
- * Returns true if released, false if not found or not owner.
82
- */
83
- unlock(file: string, agentId: string): boolean {
84
- const entry = this.locks.get(file);
85
- if (!entry) return false;
86
- if (entry.lockedBy !== agentId) return false;
87
-
88
- this.locks.delete(file);
89
- return true;
90
- }
91
-
92
- /**
93
- * Get lock status for a specific file. Returns null if unlocked.
94
- */
95
- getStatus(file: string): LockInfo | null {
96
- this.cleanExpiredEntry(file);
97
- const entry = this.locks.get(file);
98
- if (!entry) return null;
99
- return { ...entry };
100
- }
101
-
102
- /**
103
- * List all active locks, optionally filtered by agent.
104
- */
105
- listLocks(agentId?: string): LockInfo[] {
106
- this.cleanExpired();
107
- const all = [...this.locks.values()];
108
- const filtered = agentId ? all.filter(l => l.lockedBy === agentId) : all;
109
- return filtered.map(l => ({ ...l }));
110
- }
111
-
112
- /**
113
- * Release all locks held by a specific agent. Returns count released.
114
- */
115
- releaseAll(agentId: string): number {
116
- let count = 0;
117
- for (const [file, entry] of this.locks) {
118
- if (entry.lockedBy === agentId) {
119
- this.locks.delete(file);
120
- count++;
121
- }
122
- }
123
- return count;
124
- }
125
-
126
- /**
127
- * Remove all expired locks.
128
- */
129
- cleanExpired(): void {
130
- const now = Date.now();
131
- for (const [file, entry] of this.locks) {
132
- if (entry.expiresAt.getTime() <= now) {
133
- this.locks.delete(file);
134
- }
135
- }
136
- }
137
-
138
- /**
139
- * Check and remove a single expired lock entry.
140
- */
141
- private cleanExpiredEntry(file: string): void {
142
- const entry = this.locks.get(file);
143
- if (entry && entry.expiresAt.getTime() <= Date.now()) {
144
- this.locks.delete(file);
145
- }
146
- }
147
-
148
- /** Serialize state for file persistence */
149
- serialize(): { locks: Record<string, unknown> } {
150
- const locks: Record<string, unknown> = {};
151
- for (const [file, entry] of this.locks) {
152
- locks[file] = {
153
- ...entry,
154
- lockedAt: entry.lockedAt.toISOString(),
155
- expiresAt: entry.expiresAt.toISOString(),
156
- };
157
- }
158
- return { locks };
159
- }
160
-
161
- /** Hydrate state from file persistence */
162
- hydrate(data: { locks?: Record<string, any> }): void {
163
- this.locks.clear();
164
- if (!data?.locks) return;
165
- for (const [file, raw] of Object.entries(data.locks)) {
166
- this.locks.set(file, {
167
- ...(raw as any),
168
- lockedAt: new Date((raw as any).lockedAt),
169
- expiresAt: new Date((raw as any).expiresAt),
170
- });
171
- }
172
- }
173
- }
package/src/team/index.ts DELETED
@@ -1,23 +0,0 @@
1
- /**
2
- * Team Module - Autonomous Multi-Agent Coordination
3
- *
4
- * Provides agent registry, message bus, file locks, and task management
5
- * for coordinating multiple AI agents working on the same project.
6
- *
7
- * Usage via HTTP transport:
8
- * memorix serve-http --port 3211
9
- *
10
- * All team state is in-memory and shared across MCP sessions on the same server.
11
- */
12
-
13
- export { AgentRegistry } from './registry.js';
14
- export type { AgentInfo, AgentJoinInput, AgentListFilter } from './registry.js';
15
-
16
- export { MessageBus } from './messages.js';
17
- export type { Message, MessageType, MessageSendInput, MessageBroadcastInput } from './messages.js';
18
-
19
- export { FileLockRegistry } from './file-locks.js';
20
- export type { LockResult, LockInfo, LockOptions } from './file-locks.js';
21
-
22
- export { TaskManager } from './tasks.js';
23
- export type { Task, TaskStatus, TaskCreateInput, TaskListFilter } from './tasks.js';
@@ -1,203 +0,0 @@
1
- /**
2
- * Message Bus — Agent-to-agent communication
3
- *
4
- * In-memory message queue for team coordination.
5
- * Messages are temporary (not persisted as observations).
6
- * Supports direct send, broadcast, inbox retrieval, and read tracking.
7
- */
8
-
9
- import { randomUUID } from 'node:crypto';
10
- import type { AgentRegistry } from './registry.js';
11
-
12
- // ─── Types ───────────────────────────────────────────────────────────
13
-
14
- export type MessageType = 'request' | 'response' | 'info' | 'announcement' | 'contract' | 'error';
15
-
16
- export interface MessageSendInput {
17
- from: string;
18
- to: string;
19
- type: MessageType;
20
- content: string;
21
- }
22
-
23
- export interface MessageBroadcastInput {
24
- from: string;
25
- type: MessageType;
26
- content: string;
27
- }
28
-
29
- export interface Message {
30
- id: string;
31
- from: string;
32
- to: string;
33
- type: MessageType;
34
- content: string;
35
- timestamp: Date;
36
- read: boolean;
37
- }
38
-
39
- // ─── Message Bus ─────────────────────────────────────────────────────
40
-
41
- /** Max messages per inbox. Oldest read messages are evicted first. */
42
- const MAX_INBOX_SIZE = 200;
43
- /** Max message content length in bytes */
44
- const MAX_CONTENT_LENGTH = 10_000;
45
-
46
- export class MessageBus {
47
- private inboxes = new Map<string, Message[]>();
48
- private registry: AgentRegistry;
49
-
50
- constructor(registry: AgentRegistry) {
51
- this.registry = registry;
52
- }
53
-
54
- /**
55
- * Send a message to a specific agent.
56
- * Throws if receiver is unknown.
57
- */
58
- send(input: MessageSendInput): Message {
59
- const receiver = this.registry.getAgent(input.to);
60
- if (!receiver) {
61
- throw new Error(`Unknown receiver agent: ${input.to}`);
62
- }
63
- if (receiver.status !== 'active') {
64
- throw new Error(`Receiver agent is inactive: ${receiver.name}`);
65
- }
66
-
67
- const msg: Message = {
68
- id: randomUUID(),
69
- from: input.from,
70
- to: input.to,
71
- type: input.type,
72
- content: input.content,
73
- timestamp: new Date(),
74
- read: false,
75
- };
76
-
77
- const inbox = this.inboxes.get(input.to) ?? [];
78
- inbox.push(msg);
79
-
80
- // Evict oldest read messages if inbox exceeds limit
81
- if (inbox.length > MAX_INBOX_SIZE) {
82
- const readIndices: number[] = [];
83
- for (let i = 0; i < inbox.length; i++) {
84
- if (inbox[i].read) readIndices.push(i);
85
- }
86
- // Remove oldest read messages first
87
- const toRemove = inbox.length - MAX_INBOX_SIZE;
88
- for (let i = Math.min(toRemove, readIndices.length) - 1; i >= 0; i--) {
89
- inbox.splice(readIndices[i], 1);
90
- }
91
- // If still over limit, remove oldest unread
92
- while (inbox.length > MAX_INBOX_SIZE) {
93
- inbox.shift();
94
- }
95
- }
96
-
97
- this.inboxes.set(input.to, inbox);
98
- return msg;
99
- }
100
-
101
- /**
102
- * Broadcast a message to all active agents except the sender.
103
- */
104
- broadcast(input: MessageBroadcastInput): Message[] {
105
- const activeAgents = this.registry.listAgents({ status: 'active' });
106
- const messages: Message[] = [];
107
-
108
- for (const agent of activeAgents) {
109
- if (agent.id === input.from) continue;
110
-
111
- const msg = this.send({
112
- from: input.from,
113
- to: agent.id,
114
- type: input.type,
115
- content: input.content,
116
- });
117
- messages.push(msg);
118
- }
119
-
120
- return messages;
121
- }
122
-
123
- /**
124
- * Get all messages in an agent's inbox (both read and unread).
125
- */
126
- getInbox(agentId: string): Message[] {
127
- return [...(this.inboxes.get(agentId) ?? [])];
128
- }
129
-
130
- /**
131
- * Mark specific messages as read.
132
- */
133
- markRead(agentId: string, messageIds: string[]): number {
134
- const inbox = this.inboxes.get(agentId);
135
- if (!inbox) return 0;
136
-
137
- const idSet = new Set(messageIds);
138
- let count = 0;
139
- for (const msg of inbox) {
140
- if (idSet.has(msg.id) && !msg.read) {
141
- msg.read = true;
142
- count++;
143
- }
144
- }
145
- return count;
146
- }
147
-
148
- /**
149
- * Count unread messages for an agent.
150
- */
151
- getUnreadCount(agentId: string): number {
152
- const inbox = this.inboxes.get(agentId);
153
- if (!inbox) return 0;
154
- return inbox.filter(m => !m.read).length;
155
- }
156
-
157
- /**
158
- * Remove all read messages from an agent's inbox.
159
- * Returns the number of messages pruned.
160
- */
161
- pruneRead(agentId: string): number {
162
- const inbox = this.inboxes.get(agentId);
163
- if (!inbox) return 0;
164
- const before = inbox.length;
165
- const unread = inbox.filter(m => !m.read);
166
- this.inboxes.set(agentId, unread);
167
- return before - unread.length;
168
- }
169
-
170
- /**
171
- * Clear all messages for an agent (used on agent leave).
172
- */
173
- clearInbox(agentId: string): void {
174
- this.inboxes.delete(agentId);
175
- }
176
-
177
- /** Max allowed content length */
178
- static get MAX_CONTENT_LENGTH() { return MAX_CONTENT_LENGTH; }
179
-
180
- /** Serialize state for file persistence */
181
- serialize(): { inboxes: Record<string, unknown[]> } {
182
- const inboxes: Record<string, unknown[]> = {};
183
- for (const [agentId, msgs] of this.inboxes) {
184
- inboxes[agentId] = msgs.map(m => ({
185
- ...m,
186
- timestamp: m.timestamp.toISOString(),
187
- }));
188
- }
189
- return { inboxes };
190
- }
191
-
192
- /** Hydrate state from file persistence */
193
- hydrate(data: { inboxes?: Record<string, any[]> }): void {
194
- this.inboxes.clear();
195
- if (!data?.inboxes) return;
196
- for (const [agentId, msgs] of Object.entries(data.inboxes)) {
197
- this.inboxes.set(agentId, msgs.map(m => ({
198
- ...m,
199
- timestamp: new Date(m.timestamp),
200
- })));
201
- }
202
- }
203
- }
@@ -1,96 +0,0 @@
1
- /**
2
- * Team State Persistence - File-based shared state for orchestration coordination
3
- *
4
- * In stdio mode, each IDE spawns its own MCP process with isolated in-memory team state.
5
- * This persistence layer writes team state to a shared JSON file so all MCP processes
6
- * (Windsurf, Cursor, Claude Code, Antigravity, etc.) see the same agents, messages,
7
- * locks, and tasks.
8
- *
9
- * sync() — reload from disk if file changed (mtime check)
10
- * flush() — atomic write to disk (write tmp + rename)
11
- */
12
-
13
- import { readFile, writeFile, mkdir } from 'node:fs/promises';
14
- import { statSync, renameSync, existsSync } from 'node:fs';
15
- import { dirname } from 'node:path';
16
- import type { AgentRegistry } from './registry.js';
17
- import type { MessageBus } from './messages.js';
18
- import type { TaskManager } from './tasks.js';
19
- import type { FileLockRegistry } from './file-locks.js';
20
-
21
- // ─── Types ───────────────────────────────────────────────────────────
22
-
23
- interface TeamStateSnapshot {
24
- version: 1;
25
- updatedAt: string;
26
- registry: ReturnType<AgentRegistry['serialize']>;
27
- messages: ReturnType<MessageBus['serialize']>;
28
- tasks: ReturnType<TaskManager['serialize']>;
29
- locks: ReturnType<FileLockRegistry['serialize']>;
30
- }
31
-
32
- // ─── Persistence ─────────────────────────────────────────────────────
33
-
34
- export class TeamPersistence {
35
- private lastMtimeMs = 0;
36
-
37
- constructor(
38
- private filePath: string,
39
- private registry: AgentRegistry,
40
- private messageBus: MessageBus,
41
- private taskManager: TaskManager,
42
- private fileLocks: FileLockRegistry,
43
- ) {}
44
-
45
- /** Reload state from disk if the file changed since last read */
46
- async sync(): Promise<void> {
47
- try {
48
- if (!existsSync(this.filePath)) return;
49
- const st = statSync(this.filePath);
50
- if (st.mtimeMs <= this.lastMtimeMs) return;
51
- } catch {
52
- return;
53
- }
54
-
55
- try {
56
- const raw = await readFile(this.filePath, 'utf8');
57
- const snap: TeamStateSnapshot = JSON.parse(raw);
58
- if (snap.version !== 1) return;
59
-
60
- this.registry.hydrate(snap.registry);
61
- this.messageBus.hydrate(snap.messages);
62
- this.taskManager.hydrate(snap.tasks);
63
- this.fileLocks.hydrate(snap.locks);
64
-
65
- try { this.lastMtimeMs = statSync(this.filePath).mtimeMs; } catch { /* */ }
66
- } catch {
67
- // Corrupted or partial write — ignore, will be overwritten on next flush
68
- }
69
- }
70
-
71
- /** Write current state to disk atomically (tmp + rename) */
72
- async flush(): Promise<void> {
73
- const snap: TeamStateSnapshot = {
74
- version: 1,
75
- updatedAt: new Date().toISOString(),
76
- registry: this.registry.serialize(),
77
- messages: this.messageBus.serialize(),
78
- tasks: this.taskManager.serialize(),
79
- locks: this.fileLocks.serialize(),
80
- };
81
-
82
- await mkdir(dirname(this.filePath), { recursive: true });
83
- const tmp = this.filePath + '.' + process.pid + '.tmp';
84
- await writeFile(tmp, JSON.stringify(snap, null, 2), 'utf8');
85
-
86
- try {
87
- renameSync(tmp, this.filePath);
88
- } catch {
89
- // Fallback: direct write if rename fails (cross-device)
90
- await writeFile(this.filePath, JSON.stringify(snap, null, 2), 'utf8');
91
- try { const { unlinkSync } = await import('node:fs'); unlinkSync(tmp); } catch { /* */ }
92
- }
93
-
94
- try { this.lastMtimeMs = statSync(this.filePath).mtimeMs; } catch { /* */ }
95
- }
96
- }