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
@@ -0,0 +1,623 @@
1
+ import { existsSync } from 'node:fs';
2
+ import { mkdir, readFile, writeFile } from 'node:fs/promises';
3
+ import { basename, dirname, resolve } from 'node:path';
4
+ import { homedir } from 'node:os';
5
+ import type { MCPServerEntry } from '../../types.js';
6
+ import type { AgentName } from '../../hooks/types.js';
7
+ import { getAgentRulesPath, installAgentGuidance } from '../../hooks/installers/index.js';
8
+ import {
9
+ buildMemorixServer,
10
+ getMcpAdapter,
11
+ getSetupAgentTargets,
12
+ installMcpConfig,
13
+ type McpConfigAgent,
14
+ } from './setup.js';
15
+
16
+ export type AgentIntegrationScope = 'local' | 'project' | 'global' | 'all';
17
+ export type AgentIntegrationStatus = 'ok' | 'missing' | 'repairable' | 'skipped';
18
+
19
+ export interface AgentMcpCheck {
20
+ scope: Exclude<AgentIntegrationScope, 'all'>;
21
+ path: string;
22
+ exists: boolean;
23
+ status: AgentIntegrationStatus;
24
+ issues: string[];
25
+ server?: {
26
+ transport: 'stdio' | 'http';
27
+ command?: string;
28
+ args?: string[];
29
+ url?: string;
30
+ alwaysLoad?: boolean;
31
+ envKeys?: string[];
32
+ };
33
+ }
34
+
35
+ export interface AgentGuidanceCheck {
36
+ scope: Exclude<AgentIntegrationScope, 'all'>;
37
+ path: string;
38
+ exists: boolean;
39
+ status: AgentIntegrationStatus;
40
+ issues: string[];
41
+ }
42
+
43
+ export interface AgentIntegrationEntry {
44
+ agent: AgentName;
45
+ mcp: {
46
+ status: AgentIntegrationStatus;
47
+ issues: string[];
48
+ checks: AgentMcpCheck[];
49
+ };
50
+ guidance: {
51
+ status: AgentIntegrationStatus;
52
+ issues: string[];
53
+ checks: AgentGuidanceCheck[];
54
+ };
55
+ }
56
+
57
+ export interface AgentIntegrationReport {
58
+ projectRoot: string;
59
+ scope: AgentIntegrationScope;
60
+ entries: AgentIntegrationEntry[];
61
+ summary: {
62
+ checked: number;
63
+ ok: number;
64
+ missing: number;
65
+ repairable: number;
66
+ };
67
+ repairCommand: string;
68
+ }
69
+
70
+ export interface AgentRepairResult {
71
+ projectRoot: string;
72
+ scope: AgentIntegrationScope;
73
+ changed: string[];
74
+ skipped: string[];
75
+ before: AgentIntegrationReport;
76
+ after?: AgentIntegrationReport;
77
+ }
78
+
79
+ const GUIDANCE_AGENTS = new Set<AgentName>([
80
+ 'claude',
81
+ 'codex',
82
+ 'cursor',
83
+ 'windsurf',
84
+ 'copilot',
85
+ 'gemini-cli',
86
+ 'antigravity',
87
+ 'kiro',
88
+ 'opencode',
89
+ 'trae',
90
+ ]);
91
+
92
+ type ConcreteAgentIntegrationScope = Exclude<AgentIntegrationScope, 'all'>;
93
+ type JsonRecord = Record<string, unknown>;
94
+
95
+ function requestedAgents(agent?: string): AgentName[] {
96
+ const all = getSetupAgentTargets();
97
+ if (!agent || agent === 'all') return all;
98
+ return all.includes(agent as AgentName) ? [agent as AgentName] : [];
99
+ }
100
+
101
+ function requestedMcpScopes(agent: AgentName, scope?: string): ConcreteAgentIntegrationScope[] {
102
+ if (scope === 'local') return agent === 'claude' ? ['local'] : [];
103
+ if (scope === 'project' || scope === 'global') return [scope];
104
+ return agent === 'claude' ? ['local', 'project', 'global'] : ['project', 'global'];
105
+ }
106
+
107
+ function requestedGuidanceScopes(scope?: string): ConcreteAgentIntegrationScope[] {
108
+ if (scope === 'project' || scope === 'global') return [scope];
109
+ if (scope === 'local') return [];
110
+ return ['project', 'global'];
111
+ }
112
+
113
+ function unique(values: string[]): string[] {
114
+ return [...new Set(values)];
115
+ }
116
+
117
+ function worstStatus(statuses: AgentIntegrationStatus[]): AgentIntegrationStatus {
118
+ if (statuses.includes('repairable')) return 'repairable';
119
+ if (statuses.includes('missing')) return 'missing';
120
+ if (statuses.includes('ok')) return 'ok';
121
+ return 'skipped';
122
+ }
123
+
124
+ function isMcpConfigAgent(agent: AgentName): agent is McpConfigAgent {
125
+ return agent !== 'pi';
126
+ }
127
+
128
+ function isActionableMcpRepairIssue(issue: string): boolean {
129
+ return issue !== 'memorix-server-missing';
130
+ }
131
+
132
+ function aggregateMcpStatus(checks: AgentMcpCheck[]): AgentIntegrationStatus {
133
+ const actionableRepair = checks.some((check) =>
134
+ check.status === 'repairable' && check.issues.some(isActionableMcpRepairIssue)
135
+ );
136
+ if (actionableRepair) return 'repairable';
137
+ if (checks.some((check) => check.status === 'ok')) return 'ok';
138
+ if (checks.some((check) => check.status === 'repairable')) return 'repairable';
139
+ if (checks.some((check) => check.status === 'missing')) return 'missing';
140
+ return 'skipped';
141
+ }
142
+
143
+ function aggregateMcpIssues(checks: AgentMcpCheck[]): string[] {
144
+ const status = aggregateMcpStatus(checks);
145
+ if (status === 'repairable') {
146
+ return unique(checks
147
+ .filter((check) => check.status === 'repairable')
148
+ .flatMap((check) => check.issues.filter(isActionableMcpRepairIssue)));
149
+ }
150
+ if (status === 'missing') {
151
+ return unique(checks.filter((check) => check.status === 'missing').flatMap((check) => check.issues));
152
+ }
153
+ return [];
154
+ }
155
+
156
+ function aggregateGuidanceStatus(checks: AgentGuidanceCheck[]): AgentIntegrationStatus {
157
+ const projectCheck = checks.find((check) => check.scope === 'project');
158
+ if (projectCheck?.status === 'repairable') return 'repairable';
159
+ if (checks.some((check) => check.status === 'ok')) return 'ok';
160
+ if (checks.some((check) => check.status === 'repairable')) return 'repairable';
161
+ if (checks.some((check) => check.status === 'missing')) return 'missing';
162
+ return 'skipped';
163
+ }
164
+
165
+ function aggregateGuidanceIssues(checks: AgentGuidanceCheck[]): string[] {
166
+ const status = aggregateGuidanceStatus(checks);
167
+ if (status === 'repairable') {
168
+ const projectCheck = checks.find((check) => check.scope === 'project');
169
+ if (projectCheck?.status === 'repairable') return projectCheck.issues;
170
+ return unique(checks.filter((check) => check.status === 'repairable').flatMap((check) => check.issues));
171
+ }
172
+ if (status === 'missing') {
173
+ return unique(checks.filter((check) => check.status === 'missing').flatMap((check) => check.issues));
174
+ }
175
+ return [];
176
+ }
177
+
178
+ function asRecord(value: unknown): JsonRecord | null {
179
+ return value && typeof value === 'object' && !Array.isArray(value) ? value as JsonRecord : null;
180
+ }
181
+
182
+ function looksLikeStaleMemorixCommand(server: MCPServerEntry): boolean {
183
+ const text = [server.command, ...(server.args ?? [])].join(' ');
184
+ return /[\\/]\.worktrees[\\/]/i.test(text) || /[\\/]dist[\\/]cli[\\/]index\.js/i.test(text);
185
+ }
186
+
187
+ function isRecommendedStdioServer(server: MCPServerEntry): boolean {
188
+ const commandBase = basename(server.command).toLowerCase().replace(/\.(cmd|ps1|exe)$/i, '');
189
+ return commandBase === 'memorix' && server.args?.[0] === 'serve';
190
+ }
191
+
192
+ function sanitizeServer(server: MCPServerEntry): AgentMcpCheck['server'] {
193
+ if (server.url) {
194
+ return {
195
+ transport: 'http',
196
+ url: server.url,
197
+ envKeys: server.env ? Object.keys(server.env) : undefined,
198
+ };
199
+ }
200
+ return {
201
+ transport: 'stdio',
202
+ command: server.command,
203
+ args: server.args ?? [],
204
+ alwaysLoad: server.alwaysLoad,
205
+ envKeys: server.env ? Object.keys(server.env) : undefined,
206
+ };
207
+ }
208
+
209
+ function normalizeProjectKey(projectRoot: string): string {
210
+ return resolve(projectRoot).replace(/\\/g, '/').toLowerCase();
211
+ }
212
+
213
+ function defaultClaudeProjectKey(projectRoot: string): string {
214
+ return resolve(projectRoot).replace(/\\/g, '/');
215
+ }
216
+
217
+ function getClaudeLocalConfigPath(): string {
218
+ return `${homedir()}/.claude.json`;
219
+ }
220
+
221
+ function coerceClaudeLocalServer(name: string, value: unknown): MCPServerEntry | null {
222
+ const entry = asRecord(value);
223
+ if (!entry) return null;
224
+ const args = Array.isArray(entry.args) ? entry.args.map(String) : [];
225
+ return {
226
+ name,
227
+ command: typeof entry.command === 'string' ? entry.command : '',
228
+ args,
229
+ ...(asRecord(entry.env) ? { env: entry.env as Record<string, string> } : {}),
230
+ ...(typeof entry.url === 'string' ? { url: entry.url } : {}),
231
+ ...(entry.alwaysLoad === true ? { alwaysLoad: true } : {}),
232
+ };
233
+ }
234
+
235
+ function findClaudeLocalProject(config: JsonRecord, projectRoot: string): { key: string; project: JsonRecord } | null {
236
+ const projects = asRecord(config.projects);
237
+ if (!projects) return null;
238
+ const target = normalizeProjectKey(projectRoot);
239
+ for (const [key, value] of Object.entries(projects)) {
240
+ if (normalizeProjectKey(key) !== target) continue;
241
+ const project = asRecord(value);
242
+ return project ? { key, project } : null;
243
+ }
244
+ return null;
245
+ }
246
+
247
+ async function inspectClaudeLocalMcp(projectRoot: string): Promise<AgentMcpCheck> {
248
+ const configPath = getClaudeLocalConfigPath();
249
+ if (!existsSync(configPath)) {
250
+ return {
251
+ scope: 'local',
252
+ path: configPath,
253
+ exists: false,
254
+ status: 'missing',
255
+ issues: ['mcp-config-missing'],
256
+ };
257
+ }
258
+
259
+ let config: JsonRecord = {};
260
+ try {
261
+ config = JSON.parse(await readFile(configPath, 'utf-8')) as JsonRecord;
262
+ } catch {
263
+ return {
264
+ scope: 'local',
265
+ path: configPath,
266
+ exists: true,
267
+ status: 'repairable',
268
+ issues: ['mcp-config-unreadable'],
269
+ };
270
+ }
271
+
272
+ const localProject = findClaudeLocalProject(config, projectRoot);
273
+ const pathLabel = localProject ? `${configPath}#projects[${localProject.key}]` : configPath;
274
+ if (!localProject) {
275
+ return {
276
+ scope: 'local',
277
+ path: pathLabel,
278
+ exists: true,
279
+ status: 'missing',
280
+ issues: ['mcp-config-missing'],
281
+ };
282
+ }
283
+
284
+ const servers = asRecord(localProject.project.mcpServers);
285
+ const server = coerceClaudeLocalServer('memorix', servers?.memorix);
286
+ if (!server) {
287
+ return {
288
+ scope: 'local',
289
+ path: pathLabel,
290
+ exists: true,
291
+ status: 'repairable',
292
+ issues: ['memorix-server-missing'],
293
+ };
294
+ }
295
+
296
+ const issues: string[] = [];
297
+ if (!server.url && looksLikeStaleMemorixCommand(server)) issues.push('stale-command-path');
298
+ if (!server.url && !isRecommendedStdioServer(server)) issues.push('nonstandard-mcp-command');
299
+ if (server.alwaysLoad !== true) issues.push('claude-always-load-missing');
300
+
301
+ return {
302
+ scope: 'local',
303
+ path: pathLabel,
304
+ exists: true,
305
+ status: issues.length > 0 ? 'repairable' : 'ok',
306
+ issues,
307
+ server: sanitizeServer(server),
308
+ };
309
+ }
310
+
311
+ async function installClaudeLocalMcpConfig(projectRoot: string): Promise<void> {
312
+ const configPath = getClaudeLocalConfigPath();
313
+ let config: JsonRecord = {};
314
+ try {
315
+ config = JSON.parse(await readFile(configPath, 'utf-8')) as JsonRecord;
316
+ } catch {
317
+ config = {};
318
+ }
319
+
320
+ const projects = asRecord(config.projects) ?? {};
321
+ const existing = findClaudeLocalProject({ ...config, projects }, projectRoot);
322
+ const projectKey = existing?.key ?? defaultClaudeProjectKey(projectRoot);
323
+ const project = existing?.project ?? asRecord(projects[projectKey]) ?? {};
324
+ const mcpServers = asRecord(project.mcpServers) ?? {};
325
+ const server = buildMemorixServer('stdio');
326
+ server.alwaysLoad = true;
327
+
328
+ mcpServers.memorix = {
329
+ type: 'stdio',
330
+ command: server.command,
331
+ args: server.args,
332
+ alwaysLoad: true,
333
+ };
334
+ project.mcpServers = mcpServers;
335
+ projects[projectKey] = project;
336
+ config.projects = projects;
337
+
338
+ await mkdir(dirname(configPath), { recursive: true });
339
+ await writeFile(configPath, `${JSON.stringify(config, null, 2)}\n`, 'utf-8');
340
+ }
341
+
342
+ async function inspectMcp(agent: AgentName, projectRoot: string, scope: AgentIntegrationScope): Promise<AgentIntegrationEntry['mcp']> {
343
+ if (!isMcpConfigAgent(agent)) {
344
+ return { status: 'skipped', issues: ['mcp-managed-by-package'], checks: [] };
345
+ }
346
+
347
+ const adapter = getMcpAdapter(agent);
348
+ const checks: AgentMcpCheck[] = [];
349
+
350
+ for (const targetScope of requestedMcpScopes(agent, scope)) {
351
+ if (agent === 'claude' && targetScope === 'local') {
352
+ checks.push(await inspectClaudeLocalMcp(projectRoot));
353
+ continue;
354
+ }
355
+
356
+ const configPath = adapter.getConfigPath(targetScope === 'project' ? projectRoot : undefined);
357
+ if (targetScope === 'global' && configPath === adapter.getConfigPath(projectRoot)) continue;
358
+
359
+ if (!existsSync(configPath)) {
360
+ checks.push({
361
+ scope: targetScope,
362
+ path: configPath,
363
+ exists: false,
364
+ status: 'missing',
365
+ issues: ['mcp-config-missing'],
366
+ });
367
+ continue;
368
+ }
369
+
370
+ const content = await readFile(configPath, 'utf-8');
371
+ if (agent === 'claude' && targetScope === 'global') {
372
+ try {
373
+ const parsed = JSON.parse(content) as JsonRecord;
374
+ if (asRecord(parsed.projects) && !asRecord(parsed.mcpServers)) {
375
+ checks.push({
376
+ scope: targetScope,
377
+ path: configPath,
378
+ exists: true,
379
+ status: 'missing',
380
+ issues: ['mcp-config-missing'],
381
+ });
382
+ continue;
383
+ }
384
+ } catch {
385
+ checks.push({
386
+ scope: targetScope,
387
+ path: configPath,
388
+ exists: true,
389
+ status: 'repairable',
390
+ issues: ['mcp-config-unreadable'],
391
+ });
392
+ continue;
393
+ }
394
+ }
395
+
396
+ const servers = adapter.parse(content);
397
+ const server = servers.find((entry) => entry.name === 'memorix');
398
+ if (!server) {
399
+ checks.push({
400
+ scope: targetScope,
401
+ path: configPath,
402
+ exists: true,
403
+ status: 'repairable',
404
+ issues: ['memorix-server-missing'],
405
+ });
406
+ continue;
407
+ }
408
+
409
+ const issues: string[] = [];
410
+ if (!server.url && looksLikeStaleMemorixCommand(server)) issues.push('stale-command-path');
411
+ if (!server.url && !isRecommendedStdioServer(server)) issues.push('nonstandard-mcp-command');
412
+ if (agent === 'claude' && server.alwaysLoad !== true) issues.push('claude-always-load-missing');
413
+
414
+ checks.push({
415
+ scope: targetScope,
416
+ path: configPath,
417
+ exists: true,
418
+ status: issues.length > 0 ? 'repairable' : 'ok',
419
+ issues,
420
+ server: sanitizeServer(server),
421
+ });
422
+ }
423
+
424
+ return {
425
+ status: aggregateMcpStatus(checks),
426
+ issues: aggregateMcpIssues(checks),
427
+ checks,
428
+ };
429
+ }
430
+
431
+ function isCurrentGuidance(content: string): boolean {
432
+ return (
433
+ content.includes('Memory Autopilot') &&
434
+ content.includes('Default first step for non-trivial coding work') &&
435
+ content.includes('memorix_project_context')
436
+ );
437
+ }
438
+
439
+ async function inspectGuidance(agent: AgentName, projectRoot: string, scope: AgentIntegrationScope): Promise<AgentIntegrationEntry['guidance']> {
440
+ if (!GUIDANCE_AGENTS.has(agent)) {
441
+ return { status: 'skipped', issues: ['guidance-managed-by-package'], checks: [] };
442
+ }
443
+
444
+ const checks: AgentGuidanceCheck[] = [];
445
+ for (const targetScope of requestedGuidanceScopes(scope)) {
446
+ const root = targetScope === 'project' ? projectRoot : homedir();
447
+ const rulesPath = getAgentRulesPath(agent, root, targetScope === 'global');
448
+
449
+ if (!existsSync(rulesPath)) {
450
+ checks.push({
451
+ scope: targetScope,
452
+ path: rulesPath,
453
+ exists: false,
454
+ status: 'missing',
455
+ issues: ['guidance-missing'],
456
+ });
457
+ continue;
458
+ }
459
+
460
+ const content = await readFile(rulesPath, 'utf-8');
461
+ const issues = isCurrentGuidance(content) ? [] : ['guidance-outdated'];
462
+ checks.push({
463
+ scope: targetScope,
464
+ path: rulesPath,
465
+ exists: true,
466
+ status: issues.length > 0 ? 'repairable' : 'ok',
467
+ issues,
468
+ });
469
+ }
470
+
471
+ return {
472
+ status: aggregateGuidanceStatus(checks),
473
+ issues: aggregateGuidanceIssues(checks),
474
+ checks,
475
+ };
476
+ }
477
+
478
+ export async function inspectAgentIntegrations(options: {
479
+ projectRoot?: string;
480
+ agent?: string;
481
+ scope?: string;
482
+ } = {}): Promise<AgentIntegrationReport> {
483
+ const projectRoot = options.projectRoot ?? process.cwd();
484
+ const scope = (options.scope === 'local' || options.scope === 'project' || options.scope === 'global' || options.scope === 'all')
485
+ ? options.scope
486
+ : 'all';
487
+ const agents = requestedAgents(options.agent);
488
+ const entries: AgentIntegrationEntry[] = [];
489
+
490
+ for (const agent of agents) {
491
+ entries.push({
492
+ agent,
493
+ mcp: await inspectMcp(agent, projectRoot, scope),
494
+ guidance: await inspectGuidance(agent, projectRoot, scope),
495
+ });
496
+ }
497
+
498
+ const entryStatuses = entries.map((entry) => worstStatus([entry.mcp.status, entry.guidance.status]));
499
+ return {
500
+ projectRoot,
501
+ scope,
502
+ entries,
503
+ summary: {
504
+ checked: entries.length,
505
+ ok: entryStatuses.filter((status) => status === 'ok').length,
506
+ missing: entryStatuses.filter((status) => status === 'missing').length,
507
+ repairable: entryStatuses.filter((status) => status === 'repairable').length,
508
+ },
509
+ repairCommand: `memorix repair agents${options.agent ? ` --agent ${options.agent}` : ''}${scope === 'all' ? '' : ` --scope ${scope}`}`,
510
+ };
511
+ }
512
+
513
+ export function formatAgentIntegrationReport(report: AgentIntegrationReport): string {
514
+ const lines = [
515
+ 'Memorix Agent Doctor',
516
+ `Project: ${report.projectRoot}`,
517
+ `Scope: ${report.scope}`,
518
+ '',
519
+ ];
520
+
521
+ for (const entry of report.entries) {
522
+ const status = worstStatus([entry.mcp.status, entry.guidance.status]);
523
+ lines.push(`${entry.agent}: ${status}`);
524
+ if (entry.mcp.issues.length > 0) lines.push(` MCP: ${entry.mcp.issues.join(', ')}`);
525
+ if (entry.guidance.issues.length > 0) lines.push(` Guidance: ${entry.guidance.issues.join(', ')}`);
526
+ }
527
+
528
+ lines.push('');
529
+ lines.push(`Repair: ${report.repairCommand}`);
530
+ return lines.join('\n');
531
+ }
532
+
533
+ export async function repairAgentIntegrations(options: {
534
+ projectRoot?: string;
535
+ agent?: string;
536
+ scope?: string;
537
+ dry?: boolean;
538
+ } = {}): Promise<AgentRepairResult> {
539
+ const projectRoot = options.projectRoot ?? process.cwd();
540
+ const scope = (options.scope === 'local' || options.scope === 'project' || options.scope === 'global' || options.scope === 'all')
541
+ ? options.scope
542
+ : 'all';
543
+ const before = await inspectAgentIntegrations({ projectRoot, agent: options.agent, scope });
544
+ const changed: string[] = [];
545
+ const skipped: string[] = [];
546
+ const canInstallMissing = Boolean(options.agent && scope !== 'all');
547
+
548
+ for (const entry of before.entries) {
549
+ if (isMcpConfigAgent(entry.agent)) {
550
+ for (const check of entry.mcp.checks) {
551
+ if (check.status === 'ok' || check.status === 'skipped') continue;
552
+ if (check.status === 'missing' && !canInstallMissing) {
553
+ skipped.push(`${entry.agent}:mcp:${check.scope}:missing`);
554
+ continue;
555
+ }
556
+ if (!options.dry) {
557
+ if (entry.agent === 'claude' && check.scope === 'local') {
558
+ await installClaudeLocalMcpConfig(projectRoot);
559
+ } else {
560
+ await installMcpConfig({
561
+ agent: entry.agent,
562
+ projectRoot,
563
+ global: check.scope === 'global',
564
+ mcp: 'stdio',
565
+ });
566
+ }
567
+ }
568
+ changed.push(`${entry.agent}:mcp:${check.scope}`);
569
+ }
570
+ } else {
571
+ skipped.push(`${entry.agent}:mcp`);
572
+ }
573
+
574
+ if (GUIDANCE_AGENTS.has(entry.agent)) {
575
+ for (const check of entry.guidance.checks) {
576
+ if (check.status === 'ok' || check.status === 'skipped') continue;
577
+ if (check.status === 'missing' && !canInstallMissing) {
578
+ skipped.push(`${entry.agent}:guidance:${check.scope}:missing`);
579
+ continue;
580
+ }
581
+ if (!options.dry) {
582
+ await installAgentGuidance(entry.agent, projectRoot, check.scope === 'global');
583
+ }
584
+ changed.push(`${entry.agent}:guidance:${check.scope}`);
585
+ }
586
+ } else {
587
+ skipped.push(`${entry.agent}:guidance`);
588
+ }
589
+ }
590
+
591
+ return {
592
+ projectRoot,
593
+ scope,
594
+ changed,
595
+ skipped,
596
+ before,
597
+ after: options.dry ? undefined : await inspectAgentIntegrations({ projectRoot, agent: options.agent, scope }),
598
+ };
599
+ }
600
+
601
+ export function formatAgentRepairResult(result: AgentRepairResult): string {
602
+ const lines = [
603
+ 'Memorix Agent Repair',
604
+ `Project: ${result.projectRoot}`,
605
+ `Scope: ${result.scope}`,
606
+ '',
607
+ ];
608
+
609
+ if (result.changed.length === 0) {
610
+ lines.push('No repairable agent integration issues found.');
611
+ } else {
612
+ lines.push('Changed:');
613
+ for (const item of result.changed) lines.push(`- ${item}`);
614
+ }
615
+
616
+ if (result.skipped.length > 0) {
617
+ lines.push('');
618
+ lines.push('Skipped:');
619
+ for (const item of result.skipped) lines.push(`- ${item}`);
620
+ }
621
+
622
+ return lines.join('\n');
623
+ }