memorix 1.1.7 → 1.1.9

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 (185) hide show
  1. package/CHANGELOG.md +22 -0
  2. package/CLAUDE.md +6 -1
  3. package/README.md +21 -0
  4. package/README.zh-CN.md +21 -0
  5. package/TEAM.md +86 -86
  6. package/dist/cli/index.js +852 -214
  7. package/dist/cli/index.js.map +1 -1
  8. package/dist/dashboard/static/index.html +201 -201
  9. package/dist/dashboard/static/style.css +3584 -3584
  10. package/dist/index.js +129 -62
  11. package/dist/index.js.map +1 -1
  12. package/dist/memcode-runtime/CHANGELOG.md +22 -0
  13. package/dist/memcode-runtime/package.json +4 -4
  14. package/dist/sdk.js +129 -62
  15. package/dist/sdk.js.map +1 -1
  16. package/docs/AGENT_OPERATOR_PLAYBOOK.md +18 -0
  17. package/docs/API_REFERENCE.md +2 -0
  18. package/docs/CONFIGURATION.md +18 -0
  19. package/docs/DESIGN_DECISIONS.md +357 -357
  20. package/docs/SETUP.md +10 -0
  21. package/docs/dev-log/progress.txt +23 -30
  22. package/package.json +1 -1
  23. package/src/audit/index.ts +156 -156
  24. package/src/cli/commands/agent-integrations.ts +623 -0
  25. package/src/cli/commands/audit-list.ts +89 -89
  26. package/src/cli/commands/background.ts +659 -659
  27. package/src/cli/commands/cleanup.ts +255 -255
  28. package/src/cli/commands/codegraph.ts +4 -0
  29. package/src/cli/commands/config-get.ts +9 -2
  30. package/src/cli/commands/doctor.ts +26 -0
  31. package/src/cli/commands/formation.ts +48 -48
  32. package/src/cli/commands/git-hook-install.ts +111 -111
  33. package/src/cli/commands/handoff.ts +66 -66
  34. package/src/cli/commands/hooks-status.ts +63 -63
  35. package/src/cli/commands/ingest-commit.ts +153 -153
  36. package/src/cli/commands/ingest-image.ts +73 -73
  37. package/src/cli/commands/ingest-log.ts +180 -180
  38. package/src/cli/commands/ingest.ts +44 -44
  39. package/src/cli/commands/integrate-shared.ts +15 -15
  40. package/src/cli/commands/lock.ts +96 -96
  41. package/src/cli/commands/message.ts +121 -121
  42. package/src/cli/commands/poll.ts +70 -70
  43. package/src/cli/commands/purge-all-memory.ts +85 -85
  44. package/src/cli/commands/purge-project-memory.ts +83 -83
  45. package/src/cli/commands/reasoning.ts +132 -132
  46. package/src/cli/commands/repair.ts +60 -0
  47. package/src/cli/commands/retention.ts +108 -108
  48. package/src/cli/commands/serve-shared.ts +118 -118
  49. package/src/cli/commands/setup.ts +3 -3
  50. package/src/cli/commands/skills.ts +123 -123
  51. package/src/cli/commands/task.ts +192 -192
  52. package/src/cli/commands/transfer.ts +73 -73
  53. package/src/cli/commands/uninstall-project-artifacts.ts +85 -85
  54. package/src/cli/index.ts +3 -1
  55. package/src/cli/tui/ChatView.tsx +234 -234
  56. package/src/cli/tui/CommandBar.tsx +312 -312
  57. package/src/cli/tui/ContextRail.tsx +118 -118
  58. package/src/cli/tui/HeaderBar.tsx +72 -72
  59. package/src/cli/tui/LogoBanner.tsx +51 -51
  60. package/src/cli/tui/Panels.tsx +632 -632
  61. package/src/cli/tui/Sidebar.tsx +179 -179
  62. package/src/cli/tui/chat-service.ts +742 -742
  63. package/src/cli/tui/data.ts +547 -547
  64. package/src/cli/tui/index.ts +41 -41
  65. package/src/cli/tui/markdown-render.tsx +371 -371
  66. package/src/cli/tui/theme.ts +178 -178
  67. package/src/cli/tui/use-mouse.ts +157 -157
  68. package/src/cli/tui/useNavigation.ts +56 -56
  69. package/src/cli/update-checker.ts +211 -211
  70. package/src/cli/version.ts +7 -7
  71. package/src/cli/workbench.ts +1 -1
  72. package/src/codegraph/auto-context.ts +6 -0
  73. package/src/codegraph/context-pack.ts +7 -6
  74. package/src/codegraph/exclude.ts +47 -0
  75. package/src/codegraph/lite-provider.ts +5 -24
  76. package/src/codegraph/project-context.ts +13 -15
  77. package/src/compact/token-budget.ts +74 -74
  78. package/src/config/behavior.ts +59 -59
  79. package/src/config/resolved-config.ts +6 -0
  80. package/src/config/toml-loader.ts +4 -0
  81. package/src/config/yaml-loader.ts +7 -0
  82. package/src/dashboard/project-classification.ts +64 -64
  83. package/src/dashboard/static/index.html +201 -201
  84. package/src/dashboard/static/style.css +3584 -3584
  85. package/src/embedding/fastembed-provider.ts +142 -142
  86. package/src/embedding/transformers-provider.ts +111 -111
  87. package/src/git/extractor.ts +209 -209
  88. package/src/git/hooks-path.ts +85 -85
  89. package/src/git/noise-filter.ts +210 -210
  90. package/src/hooks/installers/index.ts +4 -4
  91. package/src/hooks/official-skills.ts +1 -1
  92. package/src/hooks/pattern-detector.ts +173 -173
  93. package/src/hooks/rules/memorix-agent-rules.md +2 -2
  94. package/src/hooks/significance-filter.ts +250 -250
  95. package/src/llm/memory-manager.ts +328 -328
  96. package/src/llm/provider.ts +885 -885
  97. package/src/llm/quality.ts +248 -248
  98. package/src/memory/attribution-guard.ts +249 -249
  99. package/src/memory/auto-relations.ts +107 -107
  100. package/src/memory/consolidation.ts +302 -302
  101. package/src/memory/disclosure-policy.ts +141 -141
  102. package/src/memory/entity-extractor.ts +197 -197
  103. package/src/memory/formation/evaluate.ts +217 -217
  104. package/src/memory/formation/extract.ts +361 -361
  105. package/src/memory/formation/index.ts +417 -417
  106. package/src/memory/formation/resolve.ts +344 -344
  107. package/src/memory/formation/types.ts +315 -315
  108. package/src/memory/freshness.ts +122 -122
  109. package/src/memory/graph.ts +197 -197
  110. package/src/memory/refs.ts +94 -94
  111. package/src/memory/retention.ts +433 -433
  112. package/src/memory/secret-filter.ts +79 -79
  113. package/src/memory/session.ts +523 -523
  114. package/src/multimodal/image-loader.ts +143 -143
  115. package/src/orchestrate/adapters/claude-stream.ts +192 -192
  116. package/src/orchestrate/adapters/claude.ts +111 -111
  117. package/src/orchestrate/adapters/codex-stream.ts +134 -134
  118. package/src/orchestrate/adapters/codex.ts +41 -41
  119. package/src/orchestrate/adapters/gemini-stream.ts +166 -166
  120. package/src/orchestrate/adapters/gemini.ts +42 -42
  121. package/src/orchestrate/adapters/index.ts +73 -73
  122. package/src/orchestrate/adapters/opencode-stream.ts +143 -143
  123. package/src/orchestrate/adapters/opencode.ts +47 -47
  124. package/src/orchestrate/adapters/spawn-helper.ts +286 -286
  125. package/src/orchestrate/adapters/types.ts +77 -77
  126. package/src/orchestrate/capability-router.ts +284 -284
  127. package/src/orchestrate/context-compact.ts +188 -188
  128. package/src/orchestrate/cost-tracker.ts +219 -219
  129. package/src/orchestrate/error-recovery.ts +191 -191
  130. package/src/orchestrate/evidence.ts +140 -140
  131. package/src/orchestrate/ledger.ts +110 -110
  132. package/src/orchestrate/memorix-bridge.ts +380 -380
  133. package/src/orchestrate/output-budget.ts +80 -80
  134. package/src/orchestrate/permission.ts +152 -152
  135. package/src/orchestrate/pipeline-trace.ts +131 -131
  136. package/src/orchestrate/prompt-builder.ts +155 -155
  137. package/src/orchestrate/ring-buffer.ts +37 -37
  138. package/src/orchestrate/task-graph.ts +389 -389
  139. package/src/orchestrate/verify-gate.ts +219 -219
  140. package/src/orchestrate/worktree.ts +232 -232
  141. package/src/project/aliases.ts +374 -374
  142. package/src/project/detector.ts +268 -268
  143. package/src/rules/adapters/claude-code.ts +99 -99
  144. package/src/rules/adapters/codex.ts +97 -97
  145. package/src/rules/adapters/copilot.ts +124 -124
  146. package/src/rules/adapters/cursor.ts +114 -114
  147. package/src/rules/adapters/kiro.ts +126 -126
  148. package/src/rules/adapters/trae.ts +56 -56
  149. package/src/rules/adapters/windsurf.ts +83 -83
  150. package/src/rules/syncer.ts +235 -235
  151. package/src/sdk.ts +327 -327
  152. package/src/search/intent-detector.ts +289 -289
  153. package/src/search/query-expansion.ts +52 -52
  154. package/src/server/formation-timeout.ts +27 -27
  155. package/src/server.ts +3 -0
  156. package/src/skills/mini-skills.ts +386 -386
  157. package/src/store/chat-store.ts +119 -119
  158. package/src/store/file-lock.ts +100 -100
  159. package/src/store/graph-store.ts +249 -249
  160. package/src/store/mini-skill-store.ts +349 -349
  161. package/src/store/obs-store.ts +255 -255
  162. package/src/store/orama-store.ts +15 -8
  163. package/src/store/persistence-json.ts +212 -212
  164. package/src/store/persistence.ts +291 -291
  165. package/src/store/project-affinity.ts +195 -195
  166. package/src/store/session-store.ts +259 -259
  167. package/src/store/sqlite-store.ts +339 -339
  168. package/src/team/event-bus.ts +76 -76
  169. package/src/team/file-locks.ts +173 -173
  170. package/src/team/handoff.ts +167 -167
  171. package/src/team/messages.ts +203 -203
  172. package/src/team/poll.ts +132 -132
  173. package/src/team/tasks.ts +211 -211
  174. package/src/wiki/generator.ts +237 -237
  175. package/src/wiki/knowledge-graph.ts +334 -334
  176. package/src/wiki/types.ts +85 -85
  177. package/src/workspace/mcp-adapters/codex.ts +191 -191
  178. package/src/workspace/mcp-adapters/copilot.ts +105 -105
  179. package/src/workspace/mcp-adapters/cursor.ts +53 -53
  180. package/src/workspace/mcp-adapters/kiro.ts +64 -64
  181. package/src/workspace/mcp-adapters/opencode.ts +123 -123
  182. package/src/workspace/mcp-adapters/trae.ts +134 -134
  183. package/src/workspace/mcp-adapters/windsurf.ts +91 -91
  184. package/src/workspace/sanitizer.ts +60 -60
  185. package/src/workspace/workflow-sync.ts +131 -131
@@ -1,119 +1,119 @@
1
- /**
2
- * ChatTranscriptStore — persistence for TUI chat history.
3
- *
4
- * Backed by the shared SQLite database (chat_transcript table).
5
- * Supports multiple threads (thread_id), so /new creates a new thread
6
- * and /resume reloads the most recent one.
7
- */
8
-
9
- import { getDatabase } from './sqlite-db.js';
10
- import type { ChatTranscriptMessage } from '../cli/tui/ChatView.js';
11
-
12
- export interface ChatThreadInfo {
13
- threadId: string;
14
- messageCount: number;
15
- lastActivity: string;
16
- }
17
-
18
- function safeJsonParse(text: string, fallback: any): any {
19
- try { return JSON.parse(text); } catch { return fallback; }
20
- }
21
-
22
- export class ChatTranscriptStore {
23
- private db: any = null;
24
-
25
- async init(dataDir: string): Promise<void> {
26
- this.db = getDatabase(dataDir);
27
- }
28
-
29
- /** Append a message to a thread */
30
- append(projectId: string, threadId: string, message: ChatTranscriptMessage): void {
31
- if (!this.db) return;
32
- const now = new Date().toISOString();
33
- this.db.prepare(`
34
- INSERT INTO chat_transcript (project_id, thread_id, role, content, sources_json, meta_json, error, created_at)
35
- VALUES (?, ?, ?, ?, ?, ?, ?, ?)
36
- `).run(
37
- projectId,
38
- threadId,
39
- message.role,
40
- message.content,
41
- JSON.stringify(message.sources || []),
42
- JSON.stringify(message.meta || {}),
43
- message.error ? 1 : 0,
44
- message.timestamp || now,
45
- );
46
- }
47
-
48
- /** Load all messages for a thread, oldest first */
49
- load(projectId: string, threadId: string): ChatTranscriptMessage[] {
50
- if (!this.db) return [];
51
- const rows = this.db.prepare(`
52
- SELECT role, content, sources_json, meta_json, error, created_at
53
- FROM chat_transcript
54
- WHERE project_id = ? AND thread_id = ?
55
- ORDER BY id ASC
56
- `).all(projectId, threadId);
57
-
58
- return rows.map((row: any) => ({
59
- role: row.role as 'user' | 'assistant',
60
- content: row.content,
61
- sources: safeJsonParse(row.sources_json, []),
62
- meta: safeJsonParse(row.meta_json, {}),
63
- error: row.error === 1,
64
- timestamp: row.created_at,
65
- }));
66
- }
67
-
68
- /** Delete all messages for a thread */
69
- clear(projectId: string, threadId: string): void {
70
- if (!this.db) return;
71
- this.db.prepare(`
72
- DELETE FROM chat_transcript
73
- WHERE project_id = ? AND thread_id = ?
74
- `).run(projectId, threadId);
75
- }
76
-
77
- /** List all threads for a project, most recently active first */
78
- listThreads(projectId: string): ChatThreadInfo[] {
79
- if (!this.db) return [];
80
- const rows = this.db.prepare(`
81
- SELECT thread_id, COUNT(*) as message_count, MAX(created_at) as last_activity
82
- FROM chat_transcript
83
- WHERE project_id = ?
84
- GROUP BY thread_id
85
- ORDER BY last_activity DESC
86
- `).all(projectId);
87
-
88
- return rows.map((row: any) => ({
89
- threadId: row.thread_id,
90
- messageCount: row.message_count,
91
- lastActivity: row.last_activity,
92
- }));
93
- }
94
-
95
- /** Get the most recent thread_id for a project */
96
- getLatestThreadId(projectId: string): string | null {
97
- if (!this.db) return null;
98
- const row = this.db.prepare(`
99
- SELECT thread_id FROM chat_transcript
100
- WHERE project_id = ?
101
- ORDER BY created_at DESC
102
- LIMIT 1
103
- `).get(projectId);
104
- return row?.thread_id ?? null;
105
- }
106
-
107
- /** Generate a new thread ID (timestamp-based) */
108
- newThreadId(): string {
109
- return `t${Date.now().toString(36)}`;
110
- }
111
- }
112
-
113
- // Singleton
114
- let _store: ChatTranscriptStore | null = null;
115
-
116
- export function getChatStore(): ChatTranscriptStore {
117
- if (!_store) _store = new ChatTranscriptStore();
118
- return _store;
119
- }
1
+ /**
2
+ * ChatTranscriptStore — persistence for TUI chat history.
3
+ *
4
+ * Backed by the shared SQLite database (chat_transcript table).
5
+ * Supports multiple threads (thread_id), so /new creates a new thread
6
+ * and /resume reloads the most recent one.
7
+ */
8
+
9
+ import { getDatabase } from './sqlite-db.js';
10
+ import type { ChatTranscriptMessage } from '../cli/tui/ChatView.js';
11
+
12
+ export interface ChatThreadInfo {
13
+ threadId: string;
14
+ messageCount: number;
15
+ lastActivity: string;
16
+ }
17
+
18
+ function safeJsonParse(text: string, fallback: any): any {
19
+ try { return JSON.parse(text); } catch { return fallback; }
20
+ }
21
+
22
+ export class ChatTranscriptStore {
23
+ private db: any = null;
24
+
25
+ async init(dataDir: string): Promise<void> {
26
+ this.db = getDatabase(dataDir);
27
+ }
28
+
29
+ /** Append a message to a thread */
30
+ append(projectId: string, threadId: string, message: ChatTranscriptMessage): void {
31
+ if (!this.db) return;
32
+ const now = new Date().toISOString();
33
+ this.db.prepare(`
34
+ INSERT INTO chat_transcript (project_id, thread_id, role, content, sources_json, meta_json, error, created_at)
35
+ VALUES (?, ?, ?, ?, ?, ?, ?, ?)
36
+ `).run(
37
+ projectId,
38
+ threadId,
39
+ message.role,
40
+ message.content,
41
+ JSON.stringify(message.sources || []),
42
+ JSON.stringify(message.meta || {}),
43
+ message.error ? 1 : 0,
44
+ message.timestamp || now,
45
+ );
46
+ }
47
+
48
+ /** Load all messages for a thread, oldest first */
49
+ load(projectId: string, threadId: string): ChatTranscriptMessage[] {
50
+ if (!this.db) return [];
51
+ const rows = this.db.prepare(`
52
+ SELECT role, content, sources_json, meta_json, error, created_at
53
+ FROM chat_transcript
54
+ WHERE project_id = ? AND thread_id = ?
55
+ ORDER BY id ASC
56
+ `).all(projectId, threadId);
57
+
58
+ return rows.map((row: any) => ({
59
+ role: row.role as 'user' | 'assistant',
60
+ content: row.content,
61
+ sources: safeJsonParse(row.sources_json, []),
62
+ meta: safeJsonParse(row.meta_json, {}),
63
+ error: row.error === 1,
64
+ timestamp: row.created_at,
65
+ }));
66
+ }
67
+
68
+ /** Delete all messages for a thread */
69
+ clear(projectId: string, threadId: string): void {
70
+ if (!this.db) return;
71
+ this.db.prepare(`
72
+ DELETE FROM chat_transcript
73
+ WHERE project_id = ? AND thread_id = ?
74
+ `).run(projectId, threadId);
75
+ }
76
+
77
+ /** List all threads for a project, most recently active first */
78
+ listThreads(projectId: string): ChatThreadInfo[] {
79
+ if (!this.db) return [];
80
+ const rows = this.db.prepare(`
81
+ SELECT thread_id, COUNT(*) as message_count, MAX(created_at) as last_activity
82
+ FROM chat_transcript
83
+ WHERE project_id = ?
84
+ GROUP BY thread_id
85
+ ORDER BY last_activity DESC
86
+ `).all(projectId);
87
+
88
+ return rows.map((row: any) => ({
89
+ threadId: row.thread_id,
90
+ messageCount: row.message_count,
91
+ lastActivity: row.last_activity,
92
+ }));
93
+ }
94
+
95
+ /** Get the most recent thread_id for a project */
96
+ getLatestThreadId(projectId: string): string | null {
97
+ if (!this.db) return null;
98
+ const row = this.db.prepare(`
99
+ SELECT thread_id FROM chat_transcript
100
+ WHERE project_id = ?
101
+ ORDER BY created_at DESC
102
+ LIMIT 1
103
+ `).get(projectId);
104
+ return row?.thread_id ?? null;
105
+ }
106
+
107
+ /** Generate a new thread ID (timestamp-based) */
108
+ newThreadId(): string {
109
+ return `t${Date.now().toString(36)}`;
110
+ }
111
+ }
112
+
113
+ // Singleton
114
+ let _store: ChatTranscriptStore | null = null;
115
+
116
+ export function getChatStore(): ChatTranscriptStore {
117
+ if (!_store) _store = new ChatTranscriptStore();
118
+ return _store;
119
+ }
@@ -1,100 +1,100 @@
1
- /**
2
- * File Lock & Atomic Write Utilities
3
- *
4
- * Provides cross-process file locking using .lock files with atomic creation
5
- * (O_CREAT | O_EXCL), and atomic file writes via temp-file-then-rename.
6
- *
7
- * This prevents data corruption when multiple MCP server instances
8
- * (e.g., Cursor + Windsurf) write to the same project directory simultaneously.
9
- */
10
-
11
- import { promises as fs } from 'node:fs';
12
- import path from 'node:path';
13
-
14
- /** Lock is considered stale after 10 seconds (process crash recovery) */
15
- const LOCK_STALE_MS = 10_000;
16
- /** Retry interval when waiting for lock */
17
- const RETRY_INTERVAL_MS = 50;
18
- /** Maximum retries before giving up (50ms × 60 = 3 seconds) */
19
- const MAX_RETRIES = 60;
20
-
21
- /**
22
- * Acquire a lock file atomically.
23
- * Uses O_WRONLY | O_CREAT | O_EXCL — fails if file already exists.
24
- * Handles stale locks from crashed processes.
25
- */
26
- export async function acquireLock(lockPath: string): Promise<void> {
27
- for (let i = 0; i < MAX_RETRIES; i++) {
28
- try {
29
- const fd = await fs.open(lockPath, 'wx');
30
- await fd.writeFile(JSON.stringify({ pid: process.pid, time: Date.now() }));
31
- await fd.close();
32
- return;
33
- } catch (err: unknown) {
34
- const code = err instanceof Error && 'code' in err ? (err as NodeJS.ErrnoException).code : undefined;
35
- if (code === 'EEXIST' || code === 'EPERM') {
36
- // Lock exists — check if stale
37
- try {
38
- const stat = await fs.stat(lockPath);
39
- if (Date.now() - stat.mtimeMs > LOCK_STALE_MS) {
40
- await fs.unlink(lockPath).catch(() => {});
41
- continue;
42
- }
43
- } catch {
44
- continue; // Lock disappeared — retry immediately
45
- }
46
- await new Promise(r => setTimeout(r, RETRY_INTERVAL_MS));
47
- } else {
48
- throw err;
49
- }
50
- }
51
- }
52
- // Last resort: force-remove stale lock and try once more
53
- await fs.unlink(lockPath).catch(() => {});
54
- try {
55
- const fd = await fs.open(lockPath, 'wx');
56
- await fd.writeFile(JSON.stringify({ pid: process.pid, time: Date.now() }));
57
- await fd.close();
58
- return;
59
- } catch {
60
- throw new Error(`Failed to acquire lock: ${lockPath} (timeout after ${MAX_RETRIES * RETRY_INTERVAL_MS}ms)`);
61
- }
62
- }
63
-
64
- /**
65
- * Release a lock file.
66
- */
67
- export async function releaseLock(lockPath: string): Promise<void> {
68
- await fs.unlink(lockPath).catch(() => {});
69
- }
70
-
71
- /**
72
- * Execute a function while holding a project-level lock.
73
- * Ensures only one process writes to the project directory at a time.
74
- *
75
- * @param projectDir - The project data directory to lock
76
- * @param fn - The async function to execute while holding the lock
77
- * @returns The return value of fn
78
- */
79
- export async function withFileLock<T>(projectDir: string, fn: () => Promise<T>): Promise<T> {
80
- const lockPath = path.join(projectDir, '.memorix.lock');
81
- await acquireLock(lockPath);
82
- try {
83
- return await fn();
84
- } finally {
85
- await releaseLock(lockPath);
86
- }
87
- }
88
-
89
- /**
90
- * Write a file atomically: write to .tmp, then rename.
91
- * Prevents partial writes from corrupting data files on crash.
92
- *
93
- * On most filesystems, rename() is atomic within the same directory,
94
- * so readers always see either the old complete file or the new complete file.
95
- */
96
- export async function atomicWriteFile(filePath: string, data: string): Promise<void> {
97
- const tmpPath = filePath + `.tmp.${process.pid}`;
98
- await fs.writeFile(tmpPath, data, 'utf-8');
99
- await fs.rename(tmpPath, filePath);
100
- }
1
+ /**
2
+ * File Lock & Atomic Write Utilities
3
+ *
4
+ * Provides cross-process file locking using .lock files with atomic creation
5
+ * (O_CREAT | O_EXCL), and atomic file writes via temp-file-then-rename.
6
+ *
7
+ * This prevents data corruption when multiple MCP server instances
8
+ * (e.g., Cursor + Windsurf) write to the same project directory simultaneously.
9
+ */
10
+
11
+ import { promises as fs } from 'node:fs';
12
+ import path from 'node:path';
13
+
14
+ /** Lock is considered stale after 10 seconds (process crash recovery) */
15
+ const LOCK_STALE_MS = 10_000;
16
+ /** Retry interval when waiting for lock */
17
+ const RETRY_INTERVAL_MS = 50;
18
+ /** Maximum retries before giving up (50ms × 60 = 3 seconds) */
19
+ const MAX_RETRIES = 60;
20
+
21
+ /**
22
+ * Acquire a lock file atomically.
23
+ * Uses O_WRONLY | O_CREAT | O_EXCL — fails if file already exists.
24
+ * Handles stale locks from crashed processes.
25
+ */
26
+ export async function acquireLock(lockPath: string): Promise<void> {
27
+ for (let i = 0; i < MAX_RETRIES; i++) {
28
+ try {
29
+ const fd = await fs.open(lockPath, 'wx');
30
+ await fd.writeFile(JSON.stringify({ pid: process.pid, time: Date.now() }));
31
+ await fd.close();
32
+ return;
33
+ } catch (err: unknown) {
34
+ const code = err instanceof Error && 'code' in err ? (err as NodeJS.ErrnoException).code : undefined;
35
+ if (code === 'EEXIST' || code === 'EPERM') {
36
+ // Lock exists — check if stale
37
+ try {
38
+ const stat = await fs.stat(lockPath);
39
+ if (Date.now() - stat.mtimeMs > LOCK_STALE_MS) {
40
+ await fs.unlink(lockPath).catch(() => {});
41
+ continue;
42
+ }
43
+ } catch {
44
+ continue; // Lock disappeared — retry immediately
45
+ }
46
+ await new Promise(r => setTimeout(r, RETRY_INTERVAL_MS));
47
+ } else {
48
+ throw err;
49
+ }
50
+ }
51
+ }
52
+ // Last resort: force-remove stale lock and try once more
53
+ await fs.unlink(lockPath).catch(() => {});
54
+ try {
55
+ const fd = await fs.open(lockPath, 'wx');
56
+ await fd.writeFile(JSON.stringify({ pid: process.pid, time: Date.now() }));
57
+ await fd.close();
58
+ return;
59
+ } catch {
60
+ throw new Error(`Failed to acquire lock: ${lockPath} (timeout after ${MAX_RETRIES * RETRY_INTERVAL_MS}ms)`);
61
+ }
62
+ }
63
+
64
+ /**
65
+ * Release a lock file.
66
+ */
67
+ export async function releaseLock(lockPath: string): Promise<void> {
68
+ await fs.unlink(lockPath).catch(() => {});
69
+ }
70
+
71
+ /**
72
+ * Execute a function while holding a project-level lock.
73
+ * Ensures only one process writes to the project directory at a time.
74
+ *
75
+ * @param projectDir - The project data directory to lock
76
+ * @param fn - The async function to execute while holding the lock
77
+ * @returns The return value of fn
78
+ */
79
+ export async function withFileLock<T>(projectDir: string, fn: () => Promise<T>): Promise<T> {
80
+ const lockPath = path.join(projectDir, '.memorix.lock');
81
+ await acquireLock(lockPath);
82
+ try {
83
+ return await fn();
84
+ } finally {
85
+ await releaseLock(lockPath);
86
+ }
87
+ }
88
+
89
+ /**
90
+ * Write a file atomically: write to .tmp, then rename.
91
+ * Prevents partial writes from corrupting data files on crash.
92
+ *
93
+ * On most filesystems, rename() is atomic within the same directory,
94
+ * so readers always see either the old complete file or the new complete file.
95
+ */
96
+ export async function atomicWriteFile(filePath: string, data: string): Promise<void> {
97
+ const tmpPath = filePath + `.tmp.${process.pid}`;
98
+ await fs.writeFile(tmpPath, data, 'utf-8');
99
+ await fs.rename(tmpPath, filePath);
100
+ }