memorix 1.10.2 → 1.10.3

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (66) hide show
  1. package/CHANGELOG.md +20 -0
  2. package/README.md +3 -1
  3. package/README.zh-CN.md +3 -1
  4. package/dist/cli/index.js +397 -215
  5. package/dist/cli/memcode.js +0 -0
  6. package/dist/index.js +150 -38
  7. package/dist/maintenance-runner.js +108 -22
  8. package/dist/media-audio-runner.js +108 -22
  9. package/dist/media-video-runner.js +108 -22
  10. package/dist/memcode-runtime/CHANGELOG.md +20 -0
  11. package/dist/sdk.js +149 -37
  12. package/dist/types.d.ts +1 -1
  13. package/dist/vector-backfill-runner.js +108 -22
  14. package/docs/CONFIGURATION.md +34 -0
  15. package/docs/DEVELOPMENT.md +1 -1
  16. package/docs/INTEGRATIONS.md +1 -1
  17. package/docs/README.md +2 -1
  18. package/docs/ROADMAP-1.9.12-2.0.md +1 -1
  19. package/docs/SETUP.md +19 -4
  20. package/package.json +1 -1
  21. package/plugins/antigravity/memorix/plugin.json +1 -1
  22. package/plugins/claude/memorix/.claude-plugin/plugin.json +1 -1
  23. package/plugins/codebuddy/memorix/.codebuddy-plugin/plugin.json +1 -1
  24. package/plugins/codex/memorix/.codex-plugin/plugin.json +1 -1
  25. package/plugins/copilot/memorix/plugin.json +1 -1
  26. package/plugins/gemini/memorix/gemini-extension.json +1 -1
  27. package/plugins/hermes/memorix/plugin.yaml +1 -1
  28. package/plugins/omp/memorix/package.json +1 -1
  29. package/plugins/openclaw/memorix/.codex-plugin/plugin.json +1 -1
  30. package/plugins/pi/memorix/package.json +1 -1
  31. package/server.json +2 -2
  32. package/src/cli/commands/agent-integrations.ts +1 -1
  33. package/src/cli/commands/background.ts +1 -1
  34. package/src/cli/commands/context.ts +3 -2
  35. package/src/cli/commands/doctor.ts +9 -0
  36. package/src/cli/commands/explain.ts +3 -2
  37. package/src/cli/commands/init.ts +6 -2
  38. package/src/cli/commands/setup.ts +9 -6
  39. package/src/cli/commands/uninstall.ts +15 -0
  40. package/src/cli/tui/App.tsx +9 -16
  41. package/src/cli/tui/ConfigureView.tsx +2 -0
  42. package/src/codegraph/auto-context.ts +1 -1
  43. package/src/codegraph/store.ts +37 -0
  44. package/src/codegraph/types.ts +3 -0
  45. package/src/config/dotenv-loader.ts +1 -0
  46. package/src/config/resolved-config.ts +7 -2
  47. package/src/config/toml-loader.ts +1 -0
  48. package/src/config/yaml-loader.ts +4 -2
  49. package/src/dashboard/server.ts +5 -6
  50. package/src/hooks/handler.ts +0 -1
  51. package/src/integrations/registry.ts +2 -1
  52. package/src/llm/provider.ts +2 -1
  53. package/src/memory/observations.ts +61 -17
  54. package/src/multimodal/image-loader.ts +2 -2
  55. package/src/runtime/open-browser.ts +25 -0
  56. package/src/server.ts +2 -2
  57. package/src/store/orama-store.ts +27 -3
  58. package/src/types.ts +1 -1
  59. package/src/workspace/mcp-adapters/pi.ts +58 -0
  60. package/plugins/pi/memorix/skills/memorix-git-memory/SKILL.md +0 -26
  61. package/plugins/pi/memorix/skills/memorix-memory/SKILL.md +0 -51
  62. package/plugins/pi/memorix/skills/memorix-mini-skills/SKILL.md +0 -31
  63. package/plugins/pi/memorix/skills/memorix-orchestrate/SKILL.md +0 -28
  64. package/plugins/pi/memorix/skills/memorix-reasoning/SKILL.md +0 -30
  65. package/plugins/pi/memorix/skills/memorix-sessions/SKILL.md +0 -25
  66. package/plugins/pi/memorix/skills/memorix-troubleshooting/SKILL.md +0 -27
@@ -96,7 +96,7 @@ export function resetObservationRuntime(): void {
96
96
  loadedObservationStore = null;
97
97
  embeddingWriteMode = 'background';
98
98
  embeddingWorkerProjectRoot = undefined;
99
- vectorMissingIds.clear();
99
+ clearVectorMissingIds();
100
100
  vectorSchemaUpgradePromise = null;
101
101
  embeddingFailureLogTimestamps.clear();
102
102
  }
@@ -105,6 +105,22 @@ export function resetObservationRuntime(): void {
105
105
  // Tracks observation IDs whose async embedding write failed or was skipped.
106
106
  // Enables observability ("how many memories lack vectors?") and backfill.
107
107
  const vectorMissingIds = new Set<number>();
108
+ const vectorMissingProjectIds = new Map<number, string>();
109
+
110
+ function markVectorMissing(observationId: number, projectId: string): void {
111
+ vectorMissingIds.add(observationId);
112
+ vectorMissingProjectIds.set(observationId, projectId);
113
+ }
114
+
115
+ function clearVectorMissing(observationId: number): void {
116
+ vectorMissingIds.delete(observationId);
117
+ vectorMissingProjectIds.delete(observationId);
118
+ }
119
+
120
+ function clearVectorMissingIds(): void {
121
+ vectorMissingIds.clear();
122
+ vectorMissingProjectIds.clear();
123
+ }
108
124
  let vectorBackfillRunning = false;
109
125
  let vectorSchemaUpgradePromise: Promise<boolean> | null = null;
110
126
  let lastVectorBackfill: {
@@ -290,12 +306,18 @@ function isVectorCompatibleWithCurrentIndex(embedding: number[] | null): boolean
290
306
  */
291
307
  async function upgradeVectorSchemaAfterFirstEmbedding(embedding: number[]): Promise<boolean> {
292
308
  if (isVectorCompatibleWithCurrentIndex(embedding)) return true;
293
- if (getVectorDimensions() !== null || !embedding.every(Number.isFinite)) return false;
309
+ if (!embedding.every(Number.isFinite)) return false;
294
310
 
295
311
  const targetProjectDir = projectDir;
296
312
  if (!vectorSchemaUpgradePromise) {
297
- vectorSchemaUpgradePromise = reindexObservations()
298
- .then(() => projectDir === targetProjectDir && isVectorCompatibleWithCurrentIndex(embedding))
313
+ vectorSchemaUpgradePromise = getDb()
314
+ .then(async () => {
315
+ // Lazy corpus mode intentionally has no in-memory observations. The
316
+ // provider dimensions are enough to create the Orama schema; a full
317
+ // corpus rebuild would be both unnecessary and impossible here.
318
+ if (getVectorDimensions() === null && observations.length > 0) await reindexObservations();
319
+ return projectDir === targetProjectDir && isVectorCompatibleWithCurrentIndex(embedding);
320
+ })
299
321
  .catch(() => false)
300
322
  .finally(() => {
301
323
  vectorSchemaUpgradePromise = null;
@@ -359,13 +381,13 @@ function scheduleObservationEmbedding(input: {
359
381
  doc: MemorixDocument;
360
382
  }): void {
361
383
  const { observationId, projectId, searchableText, doc } = input;
362
- vectorMissingIds.add(observationId);
384
+ markVectorMissing(observationId, projectId);
363
385
 
364
386
  // Ordinary store must not pay embedding-provider or cache I/O when vectors
365
387
  // are disabled. Check before generateEmbedding() so MEMORIX_EMBEDDING=off
366
388
  // stays on the lexical write path.
367
389
  if (isEmbeddingExplicitlyDisabled()) {
368
- vectorMissingIds.delete(observationId);
390
+ clearVectorMissing(observationId);
369
391
  return;
370
392
  }
371
393
 
@@ -405,13 +427,13 @@ function scheduleObservationEmbedding(input: {
405
427
  vector: embedding,
406
428
  });
407
429
  }
408
- vectorMissingIds.delete(observationId);
430
+ clearVectorMissing(observationId);
409
431
  } catch {
410
432
  console.error(`[memorix] Embedding index update failed for obs-${observationId} (kept in backfill queue)`);
411
433
  queueVectorBackfill(projectId);
412
434
  }
413
435
  } else if (isEmbeddingExplicitlyDisabled()) {
414
- vectorMissingIds.delete(observationId);
436
+ clearVectorMissing(observationId);
415
437
  } else {
416
438
  queueVectorBackfill(projectId);
417
439
  logEmbeddingFailureOnce(
@@ -1246,7 +1268,7 @@ export async function reindexObservations(): Promise<number> {
1246
1268
  // Reset the Orama index to ensure clean reindex (idempotent)
1247
1269
  await resetDb();
1248
1270
  searchIndexPrepared = false;
1249
- vectorMissingIds.clear();
1271
+ clearVectorMissingIds();
1250
1272
 
1251
1273
  // Prefer already-persisted vectors for remote providers. This restores semantic
1252
1274
  // recall after a restart without waiting on the network; cache misses remain
@@ -1327,7 +1349,7 @@ export async function reindexObservations(): Promise<number> {
1327
1349
  };
1328
1350
  await insertObservation(doc);
1329
1351
  if (!compatibleEmbedding && !isEmbeddingExplicitlyDisabled()) {
1330
- vectorMissingIds.add(obs.id);
1352
+ markVectorMissing(obs.id, obs.projectId);
1331
1353
  }
1332
1354
  count++;
1333
1355
  } catch (err) {
@@ -1356,7 +1378,21 @@ export async function prepareSearchIndex(options: { skipCachedVectors?: boolean
1356
1378
  if (!isEmbeddingExplicitlyDisabled()) {
1357
1379
  const store = getObservationStore();
1358
1380
  const projects = await store.listProjectIds?.() ?? [];
1359
- for (const projectId of projects) queueVectorBackfill(projectId);
1381
+ // Initialize the lightweight vector schema without hydrating the corpus.
1382
+ // The persistent Lance ID set is the source of truth in lazy mode.
1383
+ await getDb({ allowNetworkProbe: false }).catch(() => undefined);
1384
+ const persistedIds = projectDir
1385
+ ? await getPersistentSemanticVectorIds(projectDir).catch(() => null)
1386
+ : null;
1387
+ for (const projectId of projects) {
1388
+ const projectObservations = await store.loadByProject(projectId);
1389
+ for (const observation of projectObservations) {
1390
+ if (!persistedIds?.has(observation.id)) markVectorMissing(observation.id, observation.projectId);
1391
+ }
1392
+ if (projectObservations.some((observation) => !persistedIds?.has(observation.id))) {
1393
+ queueVectorBackfill(projectId);
1394
+ }
1395
+ }
1360
1396
  }
1361
1397
  return 0;
1362
1398
  }
@@ -1372,7 +1408,7 @@ export async function prepareSearchIndex(options: { skipCachedVectors?: boolean
1372
1408
  const hydratedProjectDir = projectDir;
1373
1409
  const queueMissingVectors = async () => {
1374
1410
  if (!hydratedProjectDir || projectDir !== hydratedProjectDir) return;
1375
- vectorMissingIds.clear();
1411
+ clearVectorMissingIds();
1376
1412
  if (!isEmbeddingExplicitlyDisabled()) {
1377
1413
  const persistedSemanticIds = await getPersistentSemanticVectorIds(hydratedProjectDir).catch(() => null);
1378
1414
  const projectsWithMissingVectors = new Set<string>();
@@ -1381,7 +1417,7 @@ export async function prepareSearchIndex(options: { skipCachedVectors?: boolean
1381
1417
  // not at index time. Omitting non-active observations here would permanently
1382
1418
  // exclude resolved/archived memories from hybrid search after restart.
1383
1419
  if (!hasObservationVector(obs.projectId, obs.id) && !persistedSemanticIds?.has(obs.id)) {
1384
- vectorMissingIds.add(obs.id);
1420
+ markVectorMissing(obs.id, obs.projectId);
1385
1421
  projectsWithMissingVectors.add(obs.projectId);
1386
1422
  }
1387
1423
  }
@@ -1410,6 +1446,9 @@ export async function prepareSearchIndex(options: { skipCachedVectors?: boolean
1410
1446
  */
1411
1447
  export function getVectorMissingIds(projectId?: string): number[] {
1412
1448
  if (!projectId) return [...vectorMissingIds];
1449
+ if (!corpusLoaded) {
1450
+ return [...vectorMissingIds].filter((id) => vectorMissingProjectIds.get(id) === projectId);
1451
+ }
1413
1452
  const observationById = new Map(observations.map((observation) => [observation.id, observation]));
1414
1453
  return [...vectorMissingIds].filter((id) => observationById.get(id)?.projectId === projectId);
1415
1454
  }
@@ -1491,7 +1530,12 @@ export async function backfillVectorEmbeddings(options: {
1491
1530
  }
1492
1531
  vectorBackfillRunning = true;
1493
1532
 
1494
- const observationById = new Map(observations.map((observation) => [observation.id, observation]));
1533
+ const sourceObservations = corpusLoaded
1534
+ ? observations
1535
+ : options.projectId
1536
+ ? await getObservationStore().loadByProject(options.projectId, { status: 'active' })
1537
+ : await getObservationStore().loadAll();
1538
+ const observationById = new Map(sourceObservations.map((observation) => [observation.id, observation]));
1495
1539
  const limit = Number.isFinite(options.limit)
1496
1540
  ? Math.max(1, Math.floor(options.limit!))
1497
1541
  : Number.POSITIVE_INFINITY;
@@ -1512,7 +1556,7 @@ export async function backfillVectorEmbeddings(options: {
1512
1556
  for (const id of ids) {
1513
1557
  const observation = observationById.get(id);
1514
1558
  if (!observation) {
1515
- vectorMissingIds.delete(id);
1559
+ clearVectorMissing(id);
1516
1560
  continue;
1517
1561
  }
1518
1562
  candidates.push({
@@ -1532,7 +1576,7 @@ export async function backfillVectorEmbeddings(options: {
1532
1576
  const provider = await getEmbeddingProvider();
1533
1577
  if (!provider) {
1534
1578
  if (isEmbeddingExplicitlyDisabled()) {
1535
- for (const candidate of candidates) vectorMissingIds.delete(candidate.id);
1579
+ for (const candidate of candidates) clearVectorMissing(candidate.id);
1536
1580
  } else {
1537
1581
  recordFailure('embedding provider unavailable');
1538
1582
  failed += candidates.length;
@@ -1612,7 +1656,7 @@ export async function backfillVectorEmbeddings(options: {
1612
1656
  vector: embedding,
1613
1657
  });
1614
1658
  }
1615
- vectorMissingIds.delete(id);
1659
+ clearVectorMissing(id);
1616
1660
  succeeded++;
1617
1661
  } catch (error) {
1618
1662
  recordFailure(vectorBackfillError(error));
@@ -19,7 +19,7 @@ import {
19
19
  } from './image-payload.js';
20
20
 
21
21
  // Providers that use the OpenAI-compatible /chat/completions Vision endpoint
22
- const OPENAI_COMPATIBLE_PROVIDERS = new Set(['openai', 'openrouter', 'requesty', 'apiroute', 'cheaperinference', 'custom']);
22
+ const OPENAI_COMPATIBLE_PROVIDERS = new Set(['openai', 'openrouter', 'requesty', 'apiroute', 'cheaperinference', 'runcrate', 'custom']);
23
23
  const MAX_VISION_PROMPT_CHARS = 12_000;
24
24
  const MAX_VISION_DESCRIPTION_CHARS = 12_000;
25
25
  const MAX_VISION_LABELS = 50;
@@ -138,7 +138,7 @@ export async function analyzeImage(input: ImageInput): Promise<ImageAnalysisResu
138
138
  const config = getLLMConfig()!;
139
139
  if (!OPENAI_COMPATIBLE_PROVIDERS.has(config.provider)) {
140
140
  throw new Error(
141
- `Image analysis requires an OpenAI-compatible provider (openai, openrouter, requesty, apiroute, cheaperinference, or custom). ` +
141
+ `Image analysis requires an OpenAI-compatible provider (openai, openrouter, requesty, apiroute, cheaperinference, runcrate, or custom). ` +
142
142
  `Current provider "${config.provider}" uses a different API shape. ` +
143
143
  `Set MEMORIX_LLM_PROVIDER=openai or configure an OpenAI-compatible base URL.`,
144
144
  );
@@ -0,0 +1,25 @@
1
+ import { spawn } from 'node:child_process';
2
+
3
+ const LOCAL_HTTP_HOSTS = new Set(['127.0.0.1', 'localhost', '[::1]']);
4
+
5
+ export function resolveLocalBrowserCommand(
6
+ target: string,
7
+ platform: NodeJS.Platform = process.platform,
8
+ ): { command: string; args: string[] } {
9
+ const url = new URL(target);
10
+ if (url.protocol !== 'http:' || !LOCAL_HTTP_HOSTS.has(url.hostname) || !url.port || url.username || url.password) {
11
+ throw new Error('Only unauthenticated loopback HTTP URLs can be opened automatically');
12
+ }
13
+ return platform === 'win32'
14
+ ? { command: 'explorer.exe', args: [url.toString()] }
15
+ : platform === 'darwin'
16
+ ? { command: 'open', args: [url.toString()] }
17
+ : { command: 'xdg-open', args: [url.toString()] };
18
+ }
19
+
20
+ export function openLocalBrowser(target: string): void {
21
+ const { command, args } = resolveLocalBrowserCommand(target);
22
+ const child = spawn(command, args, { detached: true, stdio: 'ignore', windowsHide: true });
23
+ child.once('error', () => undefined);
24
+ child.unref();
25
+ }
package/src/server.ts CHANGED
@@ -1642,7 +1642,7 @@ export async function createMemorixServer(
1642
1642
  inputSchema: {
1643
1643
  task: z.string().optional().describe('Current coding task or question'),
1644
1644
  taskId: z.string().max(120).optional().describe('Optional task continuity ledger id to include in the brief'),
1645
- refresh: z.enum(['auto', 'always', 'never']).optional().default('auto').describe(
1645
+ refresh: z.enum(['auto', 'always', 'never']).optional().describe(
1646
1646
  'Code Memory refresh policy. auto refreshes only when missing or stale.',
1647
1647
  ),
1648
1648
  format: z.enum(['prompt', 'summary', 'json', 'receipt']).optional().default('prompt').describe(
@@ -1688,7 +1688,7 @@ export async function createMemorixServer(
1688
1688
  task,
1689
1689
  taskId,
1690
1690
  agent,
1691
- refresh: refresh ?? 'auto',
1691
+ ...(refresh ? { refresh } : {}),
1692
1692
  reader: getObservationReader(),
1693
1693
  enqueueRefresh: () => {
1694
1694
  enqueueCodegraphRefresh({
@@ -52,6 +52,16 @@ let indexEmbeddingProvider: EmbeddingProvider | null = null;
52
52
  let deferredCachedVectorHydration: Promise<void> | null = null;
53
53
  const NON_CJK_HYBRID_SIMILARITY = 0.45;
54
54
  const CJK_RUN = /[\u3400-\u4dbf\u4e00-\u9fff\u3040-\u30ff\uac00-\ud7af]+/gu;
55
+
56
+ /** CJK tokenization already emits character and bigram tokens. Fuzzy matching
57
+ * those expanded tokens grows superlinearly on large Orama indexes. */
58
+ export function resolveSearchFuzzyTolerance(query: string, quality: 'fast' | 'balanced' | 'thorough'): number | undefined {
59
+ if (quality === 'fast') return undefined;
60
+ const characters = [...query];
61
+ const cjkCount = characters.filter((char) => /[\u3400-\u4dbf\u4e00-\u9fff\u3040-\u30ff\uac00-\ud7af]/u.test(char)).length;
62
+ if (characters.length > 0 && cjkCount / characters.length > 0.3) return undefined;
63
+ return query.length > 6 ? 2 : 1;
64
+ }
55
65
  const lastSearchModeByProject = new Map<string, string>();
56
66
  export interface SearchDiagnostics {
57
67
  version: '1';
@@ -1046,7 +1056,12 @@ export async function searchObservations(options: SearchOptions): Promise<IndexE
1046
1056
  // Fuzzy tolerance: allow 1-char typos for short queries, 2 for longer
1047
1057
  // Fuzzy matching is useful for ordinary recall, but grows sharply with
1048
1058
  // corpus size. The fast profile deliberately uses exact lexical matching.
1049
- ...(hasQuery && quality !== 'fast' ? { tolerance: originalQuery!.length > 6 ? 2 : 1 } : {}),
1059
+ ...(hasQuery
1060
+ ? (() => {
1061
+ const tolerance = resolveSearchFuzzyTolerance(originalQuery!, quality);
1062
+ return tolerance === undefined ? {} : { tolerance };
1063
+ })()
1064
+ : {}),
1050
1065
  };
1051
1066
 
1052
1067
  // If embedding provider is available and query tier warrants it, use hybrid search
@@ -1371,15 +1386,24 @@ export async function searchObservations(options: SearchOptions): Promise<IndexE
1371
1386
  });
1372
1387
  }
1373
1388
 
1374
- // Apply affinity scoring to each result
1389
+ // Affinity is a tie-breaker, not a second relevance model. RRF scores are
1390
+ // intentionally flat; multiplying every result by 0.65 can demote a rank-1
1391
+ // exact lexical match below rank-30 noise. Only close candidates receive a
1392
+ // bounded affinity adjustment, while the primary retrieval score remains
1393
+ // the ordering authority.
1394
+ const topScore = Math.max(...intermediate.map((entry) => entry.score));
1395
+ const affinityTieWindow = topScore * 0.92;
1396
+
1397
+ // Apply affinity scoring only to close candidates.
1375
1398
  intermediate = intermediate.map(entry => {
1376
1399
  const memory = memoryContentMap.get(entry.id);
1377
1400
  if (!memory) return entry;
1378
1401
 
1379
1402
  const { score: affinityScore } = calculateProjectAffinity(memory, affinityContext);
1403
+ if (entry.score < affinityTieWindow) return entry;
1380
1404
  return {
1381
1405
  ...entry,
1382
- score: entry.score * affinityScore, // Apply affinity as multiplier
1406
+ score: entry.score * (0.98 + (affinityScore * 0.02)),
1383
1407
  };
1384
1408
  });
1385
1409
 
package/src/types.ts CHANGED
@@ -670,7 +670,7 @@ export interface MemoryRef {
670
670
  /** MCP config format adapter interface */
671
671
  export interface MCPConfigAdapter {
672
672
  /** Setup-only adapters may support a host that does not participate in workspace sync. */
673
- readonly source: AgentTarget | 'codebuddy' | 'dsh' | 'workbuddy' | 'grok';
673
+ readonly source: AgentTarget | 'codebuddy' | 'dsh' | 'workbuddy' | 'grok' | 'pi';
674
674
  /** Parse MCP server entries from a config file */
675
675
  parse(content: string): MCPServerEntry[];
676
676
  /** Generate config file content from MCP server entries */
@@ -0,0 +1,58 @@
1
+ import type { MCPConfigAdapter, MCPServerEntry } from '../../types.js';
2
+ import { homedir } from 'node:os';
3
+ import { join } from 'node:path';
4
+
5
+ /**
6
+ * Native Pi MCP configuration (Pi 1.0+).
7
+ * Project: .pi/mcp.json; user: ~/.pi/agent/mcp.json.
8
+ * The extension/skills package is installed separately through `pi install`.
9
+ * https://github.com/earendil-works/pi/blob/v1.0.0/packages/coding-agent/docs/mcp.md
10
+ */
11
+ export class PiMCPAdapter implements MCPConfigAdapter {
12
+ readonly source = 'pi' as const;
13
+
14
+ parse(content: string): MCPServerEntry[] {
15
+ try {
16
+ const config = JSON.parse(content);
17
+ const servers = config.mcpServers;
18
+ if (!servers || typeof servers !== 'object' || Array.isArray(servers)) return [];
19
+
20
+ return Object.entries(servers).flatMap(([name, entry]: [string, any]) => {
21
+ if (!entry || typeof entry !== 'object' || Array.isArray(entry)) return [];
22
+ return [{
23
+ name,
24
+ command: entry.command ?? '',
25
+ args: Array.isArray(entry.args) ? entry.args : [],
26
+ ...(entry.env && Object.keys(entry.env).length > 0 ? { env: entry.env } : {}),
27
+ ...(entry.url ? { url: entry.url } : {}),
28
+ ...(entry.headers && Object.keys(entry.headers).length > 0 ? { headers: entry.headers } : {}),
29
+ ...(entry.enabled === false ? { disabled: true } : {}),
30
+ }];
31
+ });
32
+ } catch {
33
+ return [];
34
+ }
35
+ }
36
+
37
+ generate(servers: MCPServerEntry[]): string {
38
+ const mcpServers: Record<string, unknown> = {};
39
+ for (const server of servers) {
40
+ const entry: Record<string, unknown> = server.url
41
+ ? { url: server.url }
42
+ : { command: server.command, args: server.args };
43
+ if (server.url && server.headers && Object.keys(server.headers).length > 0) {
44
+ entry.headers = server.headers;
45
+ }
46
+ if (server.env && Object.keys(server.env).length > 0) entry.env = server.env;
47
+ if (server.disabled === true) entry.enabled = false;
48
+ mcpServers[server.name] = entry;
49
+ }
50
+ return JSON.stringify({ mcpServers }, null, 2) + '\n';
51
+ }
52
+
53
+ getConfigPath(projectRoot?: string): string {
54
+ return projectRoot
55
+ ? join(projectRoot, '.pi', 'mcp.json')
56
+ : join(homedir(), '.pi', 'agent', 'mcp.json');
57
+ }
58
+ }
@@ -1,26 +0,0 @@
1
- ---
2
- name: memorix-git-memory
3
- description: Use when the task depends on commit history, what changed, when a fix shipped, or linking engineering evidence to reasoning memory.
4
- ---
5
-
6
- # Memorix Git Memory
7
-
8
- Use Git Memory for repository evidence. Use reasoning memory for intent.
9
-
10
- ## Tool Router
11
-
12
- | Situation | Prefer | CLI fallback |
13
- |---|---|---|
14
- | Search what changed | `memorix_search` with a change-focused query | `memorix memory search --query "what changed <topic>"` |
15
- | Inspect a git-backed memory | `memorix_detail` | `memorix memory detail --id <id>` |
16
- | Ingest current commit manually | CLI | `memorix ingest commit` |
17
- | Ingest a specific commit | CLI | `memorix ingest commit --ref <ref>` |
18
- | Backfill recent history | CLI | `memorix ingest log --count 20` |
19
- | Install post-commit ingestion | CLI | `memorix git-hook --force` |
20
-
21
- ## Retrieval Rules
22
-
23
- - Prefer Git Memory for "what changed", "when did this ship", "which files were touched", and "which commit introduced this".
24
- - Prefer reasoning memory for "why did we choose this", "what alternatives existed", and "what risk did we accept".
25
- - Cross-link important decisions with `relatedCommits` when storing reasoning.
26
- - Do not force-ingest noisy commits unless the skipped commit is genuinely important evidence.
@@ -1,51 +0,0 @@
1
- ---
2
- name: memorix-memory
3
- description: Use when prior workspace context, past decisions, solved bugs, handoff state, or durable project knowledge would help a coding task.
4
- ---
5
-
6
- # Memorix Memory
7
-
8
- Use Memorix as the shared memory layer for the active workspace when Memorix tools are available.
9
-
10
- ## Tool Router
11
-
12
- | Situation | Prefer | CLI fallback |
13
- |---|---|---|
14
- | Broad continuation, fresh handoff, or "what do we know?" | `memorix_project_context` with the user's task | `memorix context --task "<topic>" --fallback --brief-json` |
15
- | Need structured refs/freshness for code-bound memories | `memorix_context_pack` | `memorix codegraph context-pack --task "<topic>"` |
16
- | Explicit memory graph question | `memorix_graph_context` | `memorix memory graph-context --query "<topic>"` |
17
- | Specific past decision, bug, file, or change | `memorix_search` | `memorix memory search --query "<topic>"` |
18
- | Need the full source for a search hit | `memorix_detail` | `memorix memory detail --id <id>` |
19
- | Need the sequence around one memory | `memorix_timeline` | `memorix memory timeline --id <id>` |
20
- | Check source and freshness for a memory | `memorix_evidence` | `memorix evidence list|get|events` |
21
- | Record whether a memory helped, conflicted, or was corrected | `memorix_feedback` | `memorix feedback record|show|audit` |
22
- | Inspect or import controlled media | `memorix_media` | `memorix media import|attach|list|show|status` |
23
- | Learned reusable project knowledge | `memorix_store` | `memorix memory store --type <type> --entity <name> --title "<title>" "<text>"` |
24
- | Stable source-backed fact or procedure needing long-term review | `memorix_store` with `longTerm` | `memorix memory long-term qualify|approve --id <id> --reason "..."` |
25
- | Task or bug is complete/outdated | `memorix_resolve` | `memorix memory resolve --ids <ids>` |
26
-
27
- ## Search Rules
28
-
29
- - Search before broad continuation work, before changing unfamiliar code, or when the user asks about prior work.
30
- - For a fresh coding session, use `memorix_project_context` with the user's actual task before ad-hoc file reads or dev-log reads. Memorix will choose a task-lensed brief.
31
- - Fetch detail before relying on a specific memory.
32
- - Treat memory as background context. Still read the current code and verify behavior.
33
- - Skip memory lookup for greetings, tiny one-off edits, or questions fully answered by the current file.
34
- - If a fresh project has no memories, proceed normally and do not repeat the same empty search in the same turn.
35
- - If MCP tools are not visible yet but the client supports tool discovery or dynamic loading, search/select `memorix_project_context` first. Run `memorix context --task "<task>" --fallback --brief-json` only after MCP is unavailable, disabled, or not discoverable, and pass the user's real task text. Do not skip memory, wait indefinitely on startup, or hand-write tool-call syntax.
36
-
37
- ## Store Rules
38
-
39
- | What to store | Type |
40
- |---|---|
41
- | Architecture or product decision | `decision` |
42
- | Bug and fix that may recur | `problem-solution` |
43
- | Non-obvious pitfall | `gotcha` |
44
- | How a subsystem works | `how-it-works` |
45
- | Important implementation change | `what-changed` |
46
- | Accepted compromise | `trade-off` |
47
-
48
- - Use concise titles, stable entity names, relevant `filesModified`, and `topicKey` for evolving topics.
49
- - Use `longTerm` only for a stable fact, reusable procedure, or completed episode that merits explicit review. It creates a candidate, not live context; keep the default project scope and do not use it for routine updates.
50
- - A `user` + `portable` durable memory in a task brief is intentionally reusable across projects. When it matches the task, use it as background even if it originated elsewhere; it is not a current-project fact. Expand it only when needed with `memorix_detail` and `typedRefs: ["durable:<id>"]`, stating the missing fact as `purpose`.
51
- - Do not store secrets, credentials, raw private transcripts, trivial commands, or routine file reads.
@@ -1,31 +0,0 @@
1
- ---
2
- name: memorix-mini-skills
3
- description: Use when durable project knowledge, gotchas, workflows, or repeated fixes should become reusable agent guidance instead of ordinary memory.
4
- ---
5
-
6
- # Memorix Mini-Skills
7
-
8
- Promote memories into mini-skills only when they are reusable instructions, not just historical notes.
9
-
10
- The standard setup uses the `lite` MCP profile. `memorix_skills` and `memorix_promote` are full-profile tools, so use the CLI fallback unless the current server was explicitly started with `MEMORIX_MODE=full` or `--mode full`. Do not probe hidden MCP tools repeatedly.
11
-
12
- ## Tool Router
13
-
14
- | Situation | Prefer | CLI fallback |
15
- |---|---|---|
16
- | Preview/discover existing project skills | `memorix_skills` action `list` | `memorix skills list` |
17
- | Generate skills from memory patterns | `memorix_skills` action `generate` | `memorix skills generate` |
18
- | Write generated skills to an agent | `memorix_skills` action `generate`, `write: true` | `memorix skills generate --write --target codex` |
19
- | Promote selected memories permanently | `memorix_promote` action `promote` | `memorix memory promote --ids 42,43` |
20
- | List/delete promoted mini-skills | `memorix_promote` | `memorix memory promote --action list|delete` |
21
-
22
- ## Promote When
23
-
24
- - The knowledge has been proven by repeated observations or a high-value fix.
25
- - It changes how future agents should act.
26
- - It is specific enough to be actionable and general enough to reuse.
27
-
28
- ## Do Not Promote
29
-
30
- - Command logs, probes, stale memories, one-off status notes, or unverified guesses.
31
- - Anything that should expire after the current task.
@@ -1,28 +0,0 @@
1
- ---
2
- name: memorix-orchestrate
3
- description: Use when a main agent needs Memorix to coordinate explicit subagent work through tasks, handoffs, messages, file locks, or the orchestrate CLI.
4
- ---
5
-
6
- # Memorix Orchestrate
7
-
8
- Use Memorix coordination for explicit subagent workflows with joined identities, tasks, handoffs, messages, file locks, and orchestrated workers.
9
-
10
- The standard setup uses the `lite` MCP profile. Coordination MCP tools are exposed only by `team` or `full`; use the CLI fallback for ordinary installations, or explicitly start the server with `--mode team`. Do not probe unavailable team tools in a loop.
11
-
12
- ## Tool Router
13
-
14
- | Situation | Prefer | CLI fallback |
15
- |---|---|---|
16
- | Run managed subagent execution | CLI | `memorix orchestrate --goal "<goal>" --agents claude:1,codex:1` |
17
- | Register coordination identity | `team_manage` action `join` | `memorix team join --agentType <agent>` |
18
- | Create or inspect tasks | `team_task` | `memorix task create|list|claim|complete` |
19
- | Send or read coordination messages | `team_message` | `memorix message send|broadcast|inbox` |
20
- | Share structured handoff | `memorix_handoff` | `memorix handoff send` |
21
- | Avoid file conflicts | `team_file_lock` | `memorix lock lock|unlock|status` |
22
- | Poll joined coordination state | `memorix_poll` | `memorix poll` |
23
-
24
- ## Boundaries
25
-
26
- - For ordinary memory, do not join coordination state.
27
- - For production multi-agent execution, prefer `memorix orchestrate` so the main process owns planning, dispatch, retries, and verification gates.
28
- - In worker prompts, use the worker agent ID returned by session start or team join; never use the coordinator ID as the worker identity.
@@ -1,30 +0,0 @@
1
- ---
2
- name: memorix-reasoning
3
- description: Use when a technical decision, trade-off, rejected alternative, architecture rationale, or design risk should be recorded or recovered.
4
- ---
5
-
6
- # Memorix Reasoning
7
-
8
- Use reasoning memory for why a decision was made. Use ordinary memory for what happened.
9
-
10
- ## Tool Router
11
-
12
- | Situation | Prefer | CLI fallback |
13
- |---|---|---|
14
- | Store why a decision was made | `memorix_store_reasoning` | `memorix reasoning store --entity <name> --decision "<decision>" --rationale "<why>"` |
15
- | Find earlier rationale | `memorix_search_reasoning` | `memorix reasoning search --query "<topic>"` |
16
- | Need a stable evolving topic key | `memorix_suggest_topic_key` | `memorix memory suggest-topic-key --type decision --title "<title>"` |
17
- | Link rationale to commit evidence | `relatedCommits` on reasoning store | `memorix reasoning store ... --relatedCommits <sha>` |
18
-
19
- ## Use Reasoning When
20
-
21
- - The answer depends on alternatives considered, constraints, expected outcomes, or accepted risks.
22
- - A future agent may otherwise reopen the same debate.
23
- - The user chose a direction and the reason matters more than the implementation details.
24
- - A Git Memory entry says what changed, but not why it changed.
25
-
26
- ## Do Not Use Reasoning For
27
-
28
- - Simple progress notes.
29
- - Mechanical refactors with no decision.
30
- - Facts that belong in `memorix_store` as `how-it-works`, `what-changed`, or `problem-solution`.
@@ -1,25 +0,0 @@
1
- ---
2
- name: memorix-sessions
3
- description: Use when resuming work, preparing handoff context, binding an HTTP control-plane project, or deciding whether session_start is useful.
4
- ---
5
-
6
- # Memorix Sessions
7
-
8
- `memorix_session_start` is optional. Use it when session semantics help; do not make memory-only work heavier than needed.
9
-
10
- ## Tool Router
11
-
12
- | Situation | Prefer | CLI fallback |
13
- |---|---|---|
14
- | Resume a prior long-running task | `memorix_session_start` | `memorix session start --agent <name>` |
15
- | HTTP control plane needs project binding | `memorix_session_start` with `projectRoot` | `memorix session start --projectRoot <absolute-path>` |
16
- | Need recent handoff/session summaries | `memorix_session_context` | `memorix session context` |
17
- | End a real working session | `memorix_session_end` | `memorix session end --sessionId <id> --summary "<summary>"` |
18
- | Need explicit subagent coordination identity | `memorix_session_start` with `joinTeam: true` | `memorix session start --joinTeam --agentType <agent>` |
19
-
20
- ## Decision Rules
21
-
22
- - For normal memory search/store, do not require session start.
23
- - In HTTP mode, pass the absolute workspace path as `projectRoot` when available.
24
- - `projectRoot` is a detection anchor; Git identity is the final project identity.
25
- - Do not join coordination state unless the user is using tasks, messages, locks, handoff, or `memorix orchestrate`.
@@ -1,27 +0,0 @@
1
- ---
2
- name: memorix-troubleshooting
3
- description: Use when Memorix MCP, setup, project binding, HTTP control plane, hooks, skills, or agent integration is missing, stale, or failing.
4
- ---
5
-
6
- # Memorix Troubleshooting
7
-
8
- Prefer direct CLI diagnostics first. MCP is an integration surface, not the only way to operate Memorix.
9
-
10
- ## Diagnostic Router
11
-
12
- | Symptom | Check | CLI fallback |
13
- |---|---|---|
14
- | MCP tools missing | host MCP config and restart | `memorix setup --agent <agent>` |
15
- | Unsure project is bound | project status | `memorix status` and `git status` |
16
- | HTTP MCP stale or unbound | background health and explicit session bind | `memorix background status`; then `memorix session start --projectRoot <path>` |
17
- | Hooks not firing | hook status | `memorix hooks status` |
18
- | Need to inspect generated files | preview | `memorix hooks preview --agent <agent>` |
19
- | Setup looks incomplete | reinstall host integration | `memorix setup --agent <agent>` |
20
- | Need dashboard/control plane | background service | `memorix background start` or `memorix serve-http --port 3211` |
21
-
22
- ## Mode Rules
23
-
24
- - Use stdio MCP (`memorix serve`) for normal host-launched MCP integration.
25
- - Use HTTP/background only for shared endpoint, dashboard, Docker, multiple clients, or foreground control-plane debugging.
26
- - On Windows, prefer absolute native paths for `projectRoot` and remember that visually similar junction paths may bind different session histories.
27
- - If MCP is unavailable but the CLI works, continue through CLI commands instead of blocking.