@soleri/core 8.1.0 → 9.0.1

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 (143) hide show
  1. package/dist/brain/brain.d.ts +1 -8
  2. package/dist/brain/brain.d.ts.map +1 -1
  3. package/dist/brain/brain.js +5 -134
  4. package/dist/brain/brain.js.map +1 -1
  5. package/dist/cognee/client.d.ts +5 -0
  6. package/dist/cognee/client.d.ts.map +1 -1
  7. package/dist/cognee/client.js +83 -16
  8. package/dist/cognee/client.js.map +1 -1
  9. package/dist/cognee/sync-manager.d.ts +67 -8
  10. package/dist/cognee/sync-manager.d.ts.map +1 -1
  11. package/dist/cognee/sync-manager.js +129 -32
  12. package/dist/cognee/sync-manager.js.map +1 -1
  13. package/dist/cognee/types.d.ts +16 -0
  14. package/dist/cognee/types.d.ts.map +1 -1
  15. package/dist/context/context-engine.d.ts +2 -5
  16. package/dist/context/context-engine.d.ts.map +1 -1
  17. package/dist/context/context-engine.js +4 -31
  18. package/dist/context/context-engine.js.map +1 -1
  19. package/dist/curator/curator.d.ts +2 -5
  20. package/dist/curator/curator.d.ts.map +1 -1
  21. package/dist/curator/curator.js +4 -23
  22. package/dist/curator/curator.js.map +1 -1
  23. package/dist/engine/bin/soleri-engine.js +6 -5
  24. package/dist/engine/bin/soleri-engine.js.map +1 -1
  25. package/dist/engine/core-ops.d.ts.map +1 -1
  26. package/dist/engine/core-ops.js +11 -6
  27. package/dist/engine/core-ops.js.map +1 -1
  28. package/dist/engine/module-manifest.d.ts +1 -1
  29. package/dist/engine/module-manifest.d.ts.map +1 -1
  30. package/dist/engine/module-manifest.js +1 -7
  31. package/dist/engine/module-manifest.js.map +1 -1
  32. package/dist/engine/register-engine.d.ts.map +1 -1
  33. package/dist/engine/register-engine.js +0 -7
  34. package/dist/engine/register-engine.js.map +1 -1
  35. package/dist/index.d.ts +5 -5
  36. package/dist/index.d.ts.map +1 -1
  37. package/dist/index.js +3 -4
  38. package/dist/index.js.map +1 -1
  39. package/dist/intelligence/types.d.ts +7 -0
  40. package/dist/intelligence/types.d.ts.map +1 -1
  41. package/dist/persona/defaults.d.ts +16 -0
  42. package/dist/persona/defaults.d.ts.map +1 -0
  43. package/dist/persona/defaults.js +78 -0
  44. package/dist/persona/defaults.js.map +1 -0
  45. package/dist/persona/index.d.ts +5 -0
  46. package/dist/persona/index.d.ts.map +1 -0
  47. package/dist/persona/index.js +4 -0
  48. package/dist/persona/index.js.map +1 -0
  49. package/dist/persona/loader.d.ts +11 -0
  50. package/dist/persona/loader.d.ts.map +1 -0
  51. package/dist/persona/loader.js +45 -0
  52. package/dist/persona/loader.js.map +1 -0
  53. package/dist/persona/prompt-generator.d.ts +13 -0
  54. package/dist/persona/prompt-generator.d.ts.map +1 -0
  55. package/dist/persona/prompt-generator.js +89 -0
  56. package/dist/persona/prompt-generator.js.map +1 -0
  57. package/dist/persona/types.d.ts +56 -0
  58. package/dist/persona/types.d.ts.map +1 -0
  59. package/dist/persona/types.js +9 -0
  60. package/dist/persona/types.js.map +1 -0
  61. package/dist/plugins/types.d.ts +13 -13
  62. package/dist/runtime/admin-extra-ops.d.ts.map +1 -1
  63. package/dist/runtime/admin-extra-ops.js +5 -27
  64. package/dist/runtime/admin-extra-ops.js.map +1 -1
  65. package/dist/runtime/admin-ops.d.ts.map +1 -1
  66. package/dist/runtime/admin-ops.js +5 -37
  67. package/dist/runtime/admin-ops.js.map +1 -1
  68. package/dist/runtime/capture-ops.d.ts.map +1 -1
  69. package/dist/runtime/capture-ops.js +32 -16
  70. package/dist/runtime/capture-ops.js.map +1 -1
  71. package/dist/runtime/cognee-sync-ops.d.ts +2 -2
  72. package/dist/runtime/cognee-sync-ops.d.ts.map +1 -1
  73. package/dist/runtime/cognee-sync-ops.js +45 -7
  74. package/dist/runtime/cognee-sync-ops.js.map +1 -1
  75. package/dist/runtime/facades/index.d.ts +1 -1
  76. package/dist/runtime/facades/index.d.ts.map +1 -1
  77. package/dist/runtime/facades/index.js +1 -10
  78. package/dist/runtime/facades/index.js.map +1 -1
  79. package/dist/runtime/runtime.d.ts.map +1 -1
  80. package/dist/runtime/runtime.js +14 -53
  81. package/dist/runtime/runtime.js.map +1 -1
  82. package/dist/runtime/types.d.ts +6 -8
  83. package/dist/runtime/types.d.ts.map +1 -1
  84. package/dist/runtime/vault-linking-ops.d.ts.map +1 -1
  85. package/dist/runtime/vault-linking-ops.js +40 -0
  86. package/dist/runtime/vault-linking-ops.js.map +1 -1
  87. package/dist/runtime/vault-sharing-ops.d.ts.map +1 -1
  88. package/dist/runtime/vault-sharing-ops.js +53 -3
  89. package/dist/runtime/vault-sharing-ops.js.map +1 -1
  90. package/dist/vault/linking.d.ts +37 -0
  91. package/dist/vault/linking.d.ts.map +1 -1
  92. package/dist/vault/linking.js +73 -0
  93. package/dist/vault/linking.js.map +1 -1
  94. package/dist/vault/vault.d.ts +0 -2
  95. package/dist/vault/vault.d.ts.map +1 -1
  96. package/dist/vault/vault.js +0 -13
  97. package/dist/vault/vault.js.map +1 -1
  98. package/package.json +1 -1
  99. package/src/__tests__/admin-extra-ops.test.ts +0 -3
  100. package/src/__tests__/admin-ops.test.ts +1 -5
  101. package/src/__tests__/brain.test.ts +1 -225
  102. package/src/__tests__/context-engine.test.ts +1 -6
  103. package/src/__tests__/core-ops.test.ts +1 -8
  104. package/src/__tests__/curator-extra-ops.test.ts +0 -2
  105. package/src/__tests__/curator-pipeline-e2e.test.ts +3 -28
  106. package/src/__tests__/feature-flags.test.ts +0 -1
  107. package/src/__tests__/health-registry.test.ts +18 -18
  108. package/src/__tests__/replayable-stream.test.ts +3 -3
  109. package/src/brain/brain.ts +4 -157
  110. package/src/context/context-engine.ts +3 -31
  111. package/src/curator/curator.ts +5 -28
  112. package/src/engine/bin/soleri-engine.ts +6 -5
  113. package/src/engine/core-ops.ts +11 -6
  114. package/src/engine/module-manifest.ts +1 -7
  115. package/src/engine/register-engine.ts +0 -7
  116. package/src/index.ts +20 -16
  117. package/src/intelligence/types.ts +8 -0
  118. package/src/persona/defaults.ts +96 -0
  119. package/src/persona/index.ts +9 -0
  120. package/src/persona/loader.ts +50 -0
  121. package/src/persona/prompt-generator.ts +109 -0
  122. package/src/persona/types.ts +72 -0
  123. package/src/runtime/admin-extra-ops.ts +5 -28
  124. package/src/runtime/admin-ops.ts +5 -38
  125. package/src/runtime/capture-ops.ts +33 -14
  126. package/src/runtime/facades/index.ts +1 -11
  127. package/src/runtime/runtime.ts +14 -54
  128. package/src/runtime/types.ts +6 -8
  129. package/src/runtime/vault-linking-ops.ts +41 -0
  130. package/src/runtime/vault-sharing-ops.ts +63 -4
  131. package/src/vault/linking.ts +94 -0
  132. package/src/vault/vault.ts +0 -14
  133. package/src/__tests__/cognee-client-gaps.test.ts +0 -474
  134. package/src/__tests__/cognee-client.test.ts +0 -524
  135. package/src/__tests__/cognee-hybrid-search.test.ts +0 -492
  136. package/src/__tests__/cognee-integration.test.ts +0 -80
  137. package/src/__tests__/cognee-sync-manager-deep.test.ts +0 -654
  138. package/src/__tests__/cognee-sync-manager.test.ts +0 -104
  139. package/src/cognee/client.ts +0 -370
  140. package/src/cognee/sync-manager.ts +0 -389
  141. package/src/cognee/types.ts +0 -62
  142. package/src/runtime/cognee-sync-ops.ts +0 -63
  143. package/src/runtime/facades/cognee-facade.ts +0 -164
@@ -14,7 +14,6 @@ import { BrainIntelligence } from '../brain/intelligence.js';
14
14
  import { Planner } from '../planning/planner.js';
15
15
  import { Curator } from '../curator/curator.js';
16
16
  import { Governance } from '../governance/governance.js';
17
- import { CogneeClient } from '../cognee/client.js';
18
17
  import { LoopManager } from '../loop/loop-manager.js';
19
18
  import { IdentityManager } from '../control/identity-manager.js';
20
19
  import { IntentRouter } from '../control/intent-router.js';
@@ -22,7 +21,6 @@ import { KeyPool, loadKeyPoolConfig } from '../llm/key-pool.js';
22
21
  import { discoverAnthropicToken } from '../llm/oauth-discovery.js';
23
22
  import { loadIntelligenceData } from '../intelligence/loader.js';
24
23
  import { LLMClient } from '../llm/llm-client.js';
25
- import { CogneeSyncManager } from '../cognee/sync-manager.js';
26
24
  import { IntakePipeline } from '../intake/intake-pipeline.js';
27
25
  import { TextIngester } from '../intake/text-ingester.js';
28
26
  import { Telemetry } from '../telemetry/telemetry.js';
@@ -50,6 +48,8 @@ import { PipelineRunner } from '../queue/pipeline-runner.js';
50
48
  import { evaluateQuality } from '../curator/quality-gate.js';
51
49
  import { classifyEntry } from '../curator/classifier.js';
52
50
  import type { AgentRuntimeConfig, AgentRuntime } from './types.js';
51
+ import { loadPersona } from '../persona/loader.js';
52
+ import { generatePersonaInstructions } from '../persona/prompt-generator.js';
53
53
 
54
54
  /**
55
55
  * Create a fully initialized agent runtime.
@@ -95,25 +95,15 @@ export function createAgentRuntime(config: AgentRuntimeConfig): AgentRuntime {
95
95
  // Planner — multi-step task tracking
96
96
  const planner = new Planner(plansPath);
97
97
 
98
- // Cognee — vector search client (opt-in, graceful degradation if Cognee is down)
99
- let cognee: CogneeClient | null = null;
100
- if (config.cognee) {
101
- const cogneePartial: Partial<import('../cognee/types.js').CogneeConfig> = { dataset: agentId };
102
- if (process.env.COGNEE_BASE_URL) cogneePartial.baseUrl = process.env.COGNEE_BASE_URL;
103
- if (process.env.COGNEE_API_TOKEN) cogneePartial.apiToken = process.env.COGNEE_API_TOKEN;
104
- if (process.env.COGNEE_DATASET) cogneePartial.dataset = process.env.COGNEE_DATASET;
105
- cognee = new CogneeClient(cogneePartial);
106
- }
107
-
108
98
  // Brain — intelligence layer (TF-IDF scoring, auto-tagging, dedup)
109
99
  // Pass vaultManager so intelligentSearch queries all connected sources (not just agent tier)
110
- const brain = new Brain(vault, cognee ?? undefined, vaultManager);
100
+ const brain = new Brain(vault, vaultManager);
111
101
 
112
102
  // Brain Intelligence — pattern strengths, session knowledge, intelligence pipeline
113
103
  const brainIntelligence = new BrainIntelligence(vault, brain);
114
104
 
115
105
  // Curator — vault self-maintenance (dedup, contradictions, grooming, health)
116
- const curator = new Curator(vault, cognee ?? undefined);
106
+ const curator = new Curator(vault);
117
107
 
118
108
  // Governance — policy engine + proposal tracker for gated knowledge capture
119
109
  const governance = new Governance(vault);
@@ -152,17 +142,6 @@ export function createAgentRuntime(config: AgentRuntimeConfig): AgentRuntime {
152
142
  const anthropicKeyPool = new KeyPool(anthropicConfig);
153
143
  const llmClient = new LLMClient(openaiKeyPool, anthropicKeyPool, agentId);
154
144
 
155
- // Cognee Sync Manager — queue-based dirty tracking with offline resilience (only when Cognee enabled)
156
- let syncManager: CogneeSyncManager | null = null;
157
- if (cognee) {
158
- syncManager = new CogneeSyncManager(
159
- vault.getProvider(),
160
- cognee,
161
- process.env.COGNEE_DATASET ?? agentId,
162
- );
163
- vault.setSyncManager(syncManager);
164
- }
165
-
166
145
  // Link Manager — Zettelkasten auto-linking on vault ingestion
167
146
  const linkManager = new LinkManager(vault.getProvider());
168
147
  vault.setLinkManager(linkManager, { enabled: true, maxLinks: 3 });
@@ -184,7 +163,7 @@ export function createAgentRuntime(config: AgentRuntimeConfig): AgentRuntime {
184
163
  const vaultBranching = new VaultBranching(vault);
185
164
 
186
165
  // Context Engine — entity extraction, knowledge retrieval, confidence scoring
187
- const contextEngine = new ContextEngine(vault, brain, brainIntelligence, cognee);
166
+ const contextEngine = new ContextEngine(vault, brain, brainIntelligence);
188
167
 
189
168
  // Agency Manager — proactive file watching, pattern surfacing (disabled by default)
190
169
  const agencyManager = new AgencyManager(vault);
@@ -196,10 +175,6 @@ export function createAgentRuntime(config: AgentRuntimeConfig): AgentRuntime {
196
175
  const health = new HealthRegistry();
197
176
  health.register('vault', 'healthy');
198
177
  health.register('brain', 'healthy');
199
- health.register(
200
- 'cognee',
201
- cognee ? (cognee.getStatus()?.available ? 'healthy' : 'degraded') : 'down',
202
- );
203
178
  health.register(
204
179
  'llm',
205
180
  llmClient.isAvailable().openai || llmClient.isAvailable().anthropic ? 'healthy' : 'degraded',
@@ -228,7 +203,6 @@ export function createAgentRuntime(config: AgentRuntimeConfig): AgentRuntime {
228
203
  planner,
229
204
  curator,
230
205
  governance,
231
- cognee,
232
206
  loop,
233
207
  identityManager,
234
208
  intentRouter,
@@ -237,7 +211,6 @@ export function createAgentRuntime(config: AgentRuntimeConfig): AgentRuntime {
237
211
  telemetry,
238
212
  projectRegistry,
239
213
  templateManager,
240
- syncManager,
241
214
  intakePipeline,
242
215
  textIngester,
243
216
  authPolicy: { mode: 'permissive', callerLevel: 'admin' },
@@ -335,26 +308,6 @@ export function createAgentRuntime(config: AgentRuntimeConfig): AgentRuntime {
335
308
  const result = curator.consolidate({ dryRun: false, staleDaysThreshold: 90 });
336
309
  return { archived: result.staleEntries.length, result };
337
310
  });
338
- pr.registerHandler('cognee-ingest', async (job) => {
339
- if (!cognee) return { skipped: true, reason: 'cognee not available' };
340
- const entry = vault.get(job.entryId ?? '');
341
- if (!entry) return { skipped: true, reason: 'entry not found' };
342
- try {
343
- const result = await cognee.addEntries([entry]);
344
- return { ingested: result.added };
345
- } catch {
346
- return { skipped: true, reason: 'cognee ingestion failed' };
347
- }
348
- });
349
- pr.registerHandler('cognee-cognify', async (_job) => {
350
- if (!cognee) return { skipped: true, reason: 'cognee not available' };
351
- try {
352
- const result = await cognee.cognify();
353
- return result;
354
- } catch {
355
- return { skipped: true, reason: 'cognee cognify failed' };
356
- }
357
- });
358
311
  pr.registerHandler('verify-searchable', async (job) => {
359
312
  const entry = vault.get(job.entryId ?? '');
360
313
  if (!entry) return { skipped: true, reason: 'entry not found' };
@@ -364,10 +317,17 @@ export function createAgentRuntime(config: AgentRuntimeConfig): AgentRuntime {
364
317
  });
365
318
  return pr;
366
319
  })(),
320
+ persona: (() => {
321
+ const p = loadPersona(agentId, config.persona ?? undefined);
322
+ logger.info(`[Persona] Loaded: ${p.name} (${p.template})`);
323
+ return p;
324
+ })(),
325
+ personaInstructions: (() => {
326
+ const p = loadPersona(agentId, config.persona ?? undefined);
327
+ return generatePersonaInstructions(p);
328
+ })(),
367
329
  createdAt: Date.now(),
368
330
  close: () => {
369
- syncManager?.close();
370
- cognee?.resetPendingCognify();
371
331
  vaultManager.close();
372
332
  },
373
333
  };
@@ -4,7 +4,6 @@ import type { BrainIntelligence } from '../brain/intelligence.js';
4
4
  import type { Planner } from '../planning/planner.js';
5
5
  import type { Curator } from '../curator/curator.js';
6
6
  import type { Governance } from '../governance/governance.js';
7
- import type { CogneeClient } from '../cognee/client.js';
8
7
  import type { KeyPool } from '../llm/key-pool.js';
9
8
  import type { LLMClient } from '../llm/llm-client.js';
10
9
  import type { IdentityManager } from '../control/identity-manager.js';
@@ -13,7 +12,6 @@ import type { LoopManager } from '../loop/loop-manager.js';
13
12
  import type { Telemetry } from '../telemetry/telemetry.js';
14
13
  import type { ProjectRegistry } from '../project/project-registry.js';
15
14
  import type { TemplateManager } from '../prompts/template-manager.js';
16
- import type { CogneeSyncManager } from '../cognee/sync-manager.js';
17
15
  import type { IntakePipeline } from '../intake/intake-pipeline.js';
18
16
  import type { Logger } from '../logging/logger.js';
19
17
  import type { LogLevel } from '../logging/types.js';
@@ -55,10 +53,10 @@ export interface AgentRuntimeConfig {
55
53
  logLevel?: LogLevel;
56
54
  /** Path to shared global vault. Default: ~/.soleri/vault.db */
57
55
  sharedVaultPath?: string;
58
- /** Enable Cognee vector search integration. Default: false (opt-in). */
59
- cognee?: boolean;
60
56
  /** Path to the agent's root directory (containing agent.yaml, instructions/, etc.). Optional — set by engine binary. */
61
57
  agentDir?: string;
58
+ /** Persona configuration from agent.yaml. If omitted, Italian Craftsperson default is used. */
59
+ persona?: Partial<import('../persona/types.js').PersonaConfig>;
62
60
  }
63
61
 
64
62
  /**
@@ -74,8 +72,6 @@ export interface AgentRuntime {
74
72
  planner: Planner;
75
73
  curator: Curator;
76
74
  governance: Governance;
77
- /** Cognee vector search client. Null when Cognee integration is disabled. */
78
- cognee: CogneeClient | null;
79
75
  loop: LoopManager;
80
76
  identityManager: IdentityManager;
81
77
  intentRouter: IntentRouter;
@@ -84,8 +80,6 @@ export interface AgentRuntime {
84
80
  telemetry: Telemetry;
85
81
  projectRegistry: ProjectRegistry;
86
82
  templateManager: TemplateManager;
87
- /** Cognee sync manager. Null when Cognee integration is disabled. */
88
- syncManager: CogneeSyncManager | null;
89
83
  intakePipeline: IntakePipeline;
90
84
  /** Mutable auth policy — controls facade dispatch enforcement. */
91
85
  authPolicy: AuthPolicy;
@@ -123,6 +117,10 @@ export interface AgentRuntime {
123
117
  jobQueue: JobQueue;
124
118
  /** Pipeline runner — background polling loop for job execution. */
125
119
  pipelineRunner: PipelineRunner;
120
+ /** Agent persona — defines character, voice, and cultural texture. */
121
+ persona: import('../persona/types.js').PersonaConfig;
122
+ /** Generated persona system instructions for LLM context. */
123
+ personaInstructions: import('../persona/types.js').PersonaSystemInstructions;
126
124
  /** Timestamp (ms since epoch) when this runtime was created. */
127
125
  createdAt: number;
128
126
  /** Close the vault database connection. Call on shutdown. */
@@ -400,6 +400,47 @@ export function createVaultLinkingOps(runtime: AgentRuntime): OpDefinition[] {
400
400
  };
401
401
  },
402
402
  },
403
+ {
404
+ name: 'backfill_links',
405
+ description:
406
+ 'Generate Zettelkasten links for orphan entries using FTS5 suggestions. One-time backfill for vaults with entries but no links.',
407
+ auth: 'write',
408
+ schema: z.object({
409
+ threshold: z.coerce
410
+ .number()
411
+ .min(0)
412
+ .max(1)
413
+ .default(0.7)
414
+ .describe('Min suggestion score to create link (default: 0.7)'),
415
+ maxLinks: z.coerce
416
+ .number()
417
+ .int()
418
+ .min(1)
419
+ .max(10)
420
+ .default(3)
421
+ .describe('Max links per entry (default: 3)'),
422
+ dryRun: z.boolean().optional().default(false).describe('Preview without creating links'),
423
+ batchSize: z.coerce
424
+ .number()
425
+ .int()
426
+ .min(1)
427
+ .max(200)
428
+ .default(50)
429
+ .describe('Entries per batch (default: 50)'),
430
+ }),
431
+ handler: async (params) => {
432
+ const result = linkManager.backfillLinks({
433
+ threshold: params.threshold as number,
434
+ maxLinks: params.maxLinks as number,
435
+ dryRun: params.dryRun as boolean,
436
+ batchSize: params.batchSize as number,
437
+ });
438
+ return {
439
+ ...result,
440
+ ...(result.preview ? { previewSample: result.preview.slice(0, 20) } : {}),
441
+ };
442
+ },
443
+ },
403
444
  {
404
445
  name: 'link_stats',
405
446
  description:
@@ -13,7 +13,12 @@ import type { OpDefinition } from '../facades/types.js';
13
13
  import type { AgentRuntime } from './types.js';
14
14
  import { detectScope, type ScopeInput } from '../vault/scope-detector.js';
15
15
  import { GitVaultSync, type GitVaultSyncConfig } from '../vault/git-vault-sync.js';
16
- import type { IntelligenceEntry, IntelligenceBundle } from '../intelligence/types.js';
16
+ import type {
17
+ IntelligenceEntry,
18
+ IntelligenceBundle,
19
+ IntelligenceBundleLink,
20
+ } from '../intelligence/types.js';
21
+ import { LinkManager } from '../vault/linking.js';
17
22
 
18
23
  export function createVaultSharingOps(runtime: AgentRuntime): OpDefinition[] {
19
24
  const { vault, knowledgeReview } = runtime;
@@ -147,10 +152,38 @@ export function createVaultSharingOps(runtime: AgentRuntime): OpDefinition[] {
147
152
  byDomain.get(d)!.push(entry);
148
153
  }
149
154
 
155
+ // Collect links for exported entries (Zettelkasten edge export)
156
+ const entryIds = new Set(entries.map((e) => e.id));
157
+ const linkManager = new LinkManager(vault.getProvider());
158
+ const allLinks = linkManager.getAllLinksForEntries([...entryIds]);
159
+ // Only include links where BOTH endpoints are in the export set
160
+ const exportLinks = allLinks.filter(
161
+ (l) => entryIds.has(l.sourceId) && entryIds.has(l.targetId),
162
+ );
163
+
164
+ // Build a domain→links map (group by source entry's domain)
165
+ const entryDomainMap = new Map(entries.map((e) => [e.id, e.domain]));
166
+ const linksByDomain = new Map<string, IntelligenceBundleLink[]>();
167
+ for (const link of exportLinks) {
168
+ const linkDomain = entryDomainMap.get(link.sourceId) ?? 'unknown';
169
+ if (!linksByDomain.has(linkDomain)) linksByDomain.set(linkDomain, []);
170
+ linksByDomain.get(linkDomain)!.push({
171
+ sourceId: link.sourceId,
172
+ targetId: link.targetId,
173
+ linkType: link.linkType,
174
+ note: link.note,
175
+ });
176
+ }
177
+
150
178
  const version = (params.version as string) ?? '1.0.0';
151
179
  const bundles: IntelligenceBundle[] = [];
152
180
  for (const [d, domainEntries] of byDomain) {
153
- bundles.push({ domain: d, version, entries: domainEntries });
181
+ bundles.push({
182
+ domain: d,
183
+ version,
184
+ entries: domainEntries,
185
+ links: linksByDomain.get(d) ?? [],
186
+ });
154
187
  }
155
188
 
156
189
  return {
@@ -158,6 +191,7 @@ export function createVaultSharingOps(runtime: AgentRuntime): OpDefinition[] {
158
191
  version,
159
192
  bundles,
160
193
  totalEntries: entries.length,
194
+ totalLinks: exportLinks.length,
161
195
  domains: [...byDomain.keys()],
162
196
  };
163
197
  },
@@ -187,10 +221,17 @@ export function createVaultSharingOps(runtime: AgentRuntime): OpDefinition[] {
187
221
  domain: string;
188
222
  version: string;
189
223
  entries: IntelligenceEntry[];
224
+ links?: IntelligenceBundleLink[];
190
225
  }>;
191
226
  const forceTier = params.tier as 'agent' | 'project' | 'team' | undefined;
192
227
  let imported = 0;
193
228
  let duplicates = 0;
229
+ let linksCreated = 0;
230
+ let linksSkipped = 0;
231
+
232
+ // Track ID remapping: bundle entry ID → actual vault entry ID
233
+ const idRemap = new Map<string, string>();
234
+ const linkManager = new LinkManager(vault.getProvider());
194
235
 
195
236
  for (const bundle of bundles) {
196
237
  const entries = bundle.entries.map((e) => ({
@@ -198,13 +239,31 @@ export function createVaultSharingOps(runtime: AgentRuntime): OpDefinition[] {
198
239
  tier: forceTier ?? e.tier ?? 'project',
199
240
  }));
200
241
  const results = vault.seedDedup(entries);
201
- for (const r of results) {
242
+ for (let i = 0; i < results.length; i++) {
243
+ const r = results[i];
244
+ const originalId = bundle.entries[i].id;
245
+ // For duplicates, map to the existing vault entry; for inserts, keep original ID
246
+ idRemap.set(originalId, r.existingId ?? r.id);
202
247
  if (r.action === 'inserted') imported++;
203
248
  else duplicates++;
204
249
  }
250
+
251
+ // Import links if present
252
+ if (bundle.links && bundle.links.length > 0) {
253
+ for (const link of bundle.links) {
254
+ const sourceId = idRemap.get(link.sourceId);
255
+ const targetId = idRemap.get(link.targetId);
256
+ if (sourceId && targetId) {
257
+ linkManager.addLink(sourceId, targetId, link.linkType, link.note);
258
+ linksCreated++;
259
+ } else {
260
+ linksSkipped++;
261
+ }
262
+ }
263
+ }
205
264
  }
206
265
 
207
- return { imported, duplicates, total: imported + duplicates };
266
+ return { imported, duplicates, linksCreated, linksSkipped, total: imported + duplicates };
208
267
  },
209
268
  },
210
269
 
@@ -169,6 +169,28 @@ export class LinkManager {
169
169
  return result;
170
170
  }
171
171
 
172
+ // ===========================================================================
173
+ // BULK QUERIES
174
+ // ===========================================================================
175
+
176
+ /**
177
+ * Get all links where either source or target is in the given ID set.
178
+ * Used for pack export — to find links within an export set.
179
+ */
180
+ getAllLinksForEntries(entryIds: string[]): VaultLink[] {
181
+ if (entryIds.length === 0) return [];
182
+ try {
183
+ const placeholders = entryIds.map(() => '?').join(',');
184
+ const rows = this.provider.all<VaultLinkRow>(
185
+ `SELECT * FROM vault_links WHERE source_id IN (${placeholders}) OR target_id IN (${placeholders})`,
186
+ [...entryIds, ...entryIds],
187
+ );
188
+ return rows.map(rowToVaultLink);
189
+ } catch {
190
+ return [];
191
+ }
192
+ }
193
+
172
194
  // ===========================================================================
173
195
  // ORPHAN DETECTION
174
196
  // ===========================================================================
@@ -292,6 +314,78 @@ export class LinkManager {
292
314
  }
293
315
  }
294
316
 
317
+ // ===========================================================================
318
+ // BACKFILL — one-time link generation for existing entries
319
+ // ===========================================================================
320
+
321
+ /**
322
+ * Generate links for orphan entries using FTS5 suggestions.
323
+ * Processes orphans in batches and creates links above the threshold.
324
+ *
325
+ * @param opts.threshold Minimum suggestion score to auto-create link (default: 0.7)
326
+ * @param opts.maxLinks Max links per entry (default: 3)
327
+ * @param opts.dryRun Preview without creating links (default: false)
328
+ * @param opts.batchSize Entries per batch (default: 50)
329
+ * @param opts.onProgress Progress callback
330
+ * @returns Stats: processed, linksCreated, durationMs
331
+ */
332
+ backfillLinks(opts?: {
333
+ threshold?: number;
334
+ maxLinks?: number;
335
+ dryRun?: boolean;
336
+ batchSize?: number;
337
+ onProgress?: (stats: { processed: number; total: number; linksCreated: number }) => void;
338
+ }): {
339
+ processed: number;
340
+ linksCreated: number;
341
+ durationMs: number;
342
+ preview?: Array<{ sourceId: string; targetId: string; linkType: string; score: number }>;
343
+ } {
344
+ const threshold = opts?.threshold ?? 0.7;
345
+ const maxLinks = opts?.maxLinks ?? 3;
346
+ const dryRun = opts?.dryRun ?? false;
347
+ const batchSize = opts?.batchSize ?? 50;
348
+ const start = Date.now();
349
+
350
+ const orphans = this.getOrphans(10000);
351
+ let processed = 0;
352
+ let linksCreated = 0;
353
+ const preview: Array<{ sourceId: string; targetId: string; linkType: string; score: number }> =
354
+ [];
355
+
356
+ for (let i = 0; i < orphans.length; i += batchSize) {
357
+ const batch = orphans.slice(i, i + batchSize);
358
+ for (const entry of batch) {
359
+ const suggestions = this.suggestLinks(entry.id, maxLinks + 2);
360
+ const qualifying = suggestions.filter((s) => s.score >= threshold).slice(0, maxLinks);
361
+
362
+ for (const s of qualifying) {
363
+ if (dryRun) {
364
+ preview.push({
365
+ sourceId: entry.id,
366
+ targetId: s.entryId,
367
+ linkType: s.suggestedType,
368
+ score: s.score,
369
+ });
370
+ } else {
371
+ this.addLink(entry.id, s.entryId, s.suggestedType);
372
+ }
373
+ linksCreated++;
374
+ }
375
+ processed++;
376
+ }
377
+
378
+ opts?.onProgress?.({ processed, total: orphans.length, linksCreated });
379
+ }
380
+
381
+ return {
382
+ processed,
383
+ linksCreated,
384
+ durationMs: Date.now() - start,
385
+ ...(dryRun ? { preview } : {}),
386
+ };
387
+ }
388
+
295
389
  // ===========================================================================
296
390
  // PRIVATE
297
391
  // ===========================================================================
@@ -52,7 +52,6 @@ export interface MemoryStats {
52
52
  export class Vault {
53
53
  private provider: PersistenceProvider;
54
54
  private sqliteProvider: SQLitePersistenceProvider | null;
55
- private syncManager: import('../cognee/sync-manager.js').CogneeSyncManager | null = null;
56
55
  private linkManager: LinkManager | null = null;
57
56
  private autoLinkEnabled = true;
58
57
  /** Minimum number of FTS5 suggestions to auto-link. Top N are linked. */
@@ -104,10 +103,6 @@ export class Vault {
104
103
  // current < FORMAT_VERSION → future: run migration scripts here
105
104
  }
106
105
 
107
- setSyncManager(mgr: import('../cognee/sync-manager.js').CogneeSyncManager): void {
108
- this.syncManager = mgr;
109
- }
110
-
111
106
  setLinkManager(mgr: LinkManager, opts?: { enabled?: boolean; maxLinks?: number }): void {
112
107
  this.linkManager = mgr;
113
108
  if (opts?.enabled !== undefined) this.autoLinkEnabled = opts.enabled;
@@ -414,9 +409,6 @@ export class Vault {
414
409
  origin: entry.origin ?? 'agent',
415
410
  });
416
411
  count++;
417
- if (this.syncManager) {
418
- this.syncManager.enqueue('ingest', entry.id, entry);
419
- }
420
412
  }
421
413
  // Auto-link after all entries are inserted (so they can link to each other).
422
414
  // Skip for large batches (>100) — use relink_vault for bulk imports.
@@ -608,9 +600,6 @@ export class Vault {
608
600
  }
609
601
  remove(id: string): boolean {
610
602
  const deleted = this.provider.run('DELETE FROM entries WHERE id = ?', [id]).changes > 0;
611
- if (deleted && this.syncManager) {
612
- this.syncManager.enqueue('delete', id);
613
- }
614
603
  return deleted;
615
604
  }
616
605
 
@@ -684,9 +673,6 @@ export class Vault {
684
673
  let count = 0;
685
674
  for (const id of ids) {
686
675
  count += this.provider.run('DELETE FROM entries WHERE id = ?', [id]).changes;
687
- if (this.syncManager) {
688
- this.syncManager.enqueue('delete', id);
689
- }
690
676
  }
691
677
  return count;
692
678
  });