@soleri/core 2.8.0 → 2.9.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (119) hide show
  1. package/dist/extensions/index.d.ts +3 -0
  2. package/dist/extensions/index.d.ts.map +1 -0
  3. package/dist/extensions/index.js +2 -0
  4. package/dist/extensions/index.js.map +1 -0
  5. package/dist/extensions/middleware.d.ts +13 -0
  6. package/dist/extensions/middleware.d.ts.map +1 -0
  7. package/dist/extensions/middleware.js +47 -0
  8. package/dist/extensions/middleware.js.map +1 -0
  9. package/dist/extensions/types.d.ts +64 -0
  10. package/dist/extensions/types.d.ts.map +1 -0
  11. package/dist/extensions/types.js +2 -0
  12. package/dist/extensions/types.js.map +1 -0
  13. package/dist/index.d.ts +8 -16
  14. package/dist/index.d.ts.map +1 -1
  15. package/dist/index.js +7 -16
  16. package/dist/index.js.map +1 -1
  17. package/dist/runtime/core-ops.d.ts +1 -1
  18. package/dist/runtime/core-ops.js +1 -1
  19. package/dist/runtime/facades/admin-facade.d.ts +8 -0
  20. package/dist/runtime/facades/admin-facade.d.ts.map +1 -0
  21. package/dist/runtime/facades/admin-facade.js +90 -0
  22. package/dist/runtime/facades/admin-facade.js.map +1 -0
  23. package/dist/runtime/facades/brain-facade.d.ts +8 -0
  24. package/dist/runtime/facades/brain-facade.d.ts.map +1 -0
  25. package/dist/runtime/facades/brain-facade.js +294 -0
  26. package/dist/runtime/facades/brain-facade.js.map +1 -0
  27. package/dist/runtime/facades/cognee-facade.d.ts +8 -0
  28. package/dist/runtime/facades/cognee-facade.d.ts.map +1 -0
  29. package/dist/runtime/facades/cognee-facade.js +154 -0
  30. package/dist/runtime/facades/cognee-facade.js.map +1 -0
  31. package/dist/runtime/facades/control-facade.d.ts +8 -0
  32. package/dist/runtime/facades/control-facade.d.ts.map +1 -0
  33. package/dist/runtime/facades/control-facade.js +244 -0
  34. package/dist/runtime/facades/control-facade.js.map +1 -0
  35. package/dist/runtime/facades/curator-facade.d.ts +8 -0
  36. package/dist/runtime/facades/curator-facade.d.ts.map +1 -0
  37. package/dist/runtime/facades/curator-facade.js +117 -0
  38. package/dist/runtime/facades/curator-facade.js.map +1 -0
  39. package/dist/runtime/facades/index.d.ts +10 -0
  40. package/dist/runtime/facades/index.d.ts.map +1 -0
  41. package/dist/runtime/facades/index.js +71 -0
  42. package/dist/runtime/facades/index.js.map +1 -0
  43. package/dist/runtime/facades/loop-facade.d.ts +8 -0
  44. package/dist/runtime/facades/loop-facade.d.ts.map +1 -0
  45. package/dist/runtime/facades/loop-facade.js +9 -0
  46. package/dist/runtime/facades/loop-facade.js.map +1 -0
  47. package/dist/runtime/facades/memory-facade.d.ts +8 -0
  48. package/dist/runtime/facades/memory-facade.d.ts.map +1 -0
  49. package/dist/runtime/facades/memory-facade.js +108 -0
  50. package/dist/runtime/facades/memory-facade.js.map +1 -0
  51. package/dist/runtime/facades/orchestrate-facade.d.ts +8 -0
  52. package/dist/runtime/facades/orchestrate-facade.d.ts.map +1 -0
  53. package/dist/runtime/facades/orchestrate-facade.js +58 -0
  54. package/dist/runtime/facades/orchestrate-facade.js.map +1 -0
  55. package/dist/runtime/facades/plan-facade.d.ts +8 -0
  56. package/dist/runtime/facades/plan-facade.d.ts.map +1 -0
  57. package/dist/runtime/facades/plan-facade.js +110 -0
  58. package/dist/runtime/facades/plan-facade.js.map +1 -0
  59. package/dist/runtime/facades/vault-facade.d.ts +8 -0
  60. package/dist/runtime/facades/vault-facade.d.ts.map +1 -0
  61. package/dist/runtime/facades/vault-facade.js +194 -0
  62. package/dist/runtime/facades/vault-facade.js.map +1 -0
  63. package/dist/runtime/vault-extra-ops.d.ts +2 -2
  64. package/dist/runtime/vault-extra-ops.d.ts.map +1 -1
  65. package/dist/runtime/vault-extra-ops.js +37 -2
  66. package/dist/runtime/vault-extra-ops.js.map +1 -1
  67. package/dist/streams/index.d.ts +4 -0
  68. package/dist/streams/index.d.ts.map +1 -0
  69. package/dist/streams/index.js +3 -0
  70. package/dist/streams/index.js.map +1 -0
  71. package/dist/streams/normalize.d.ts +14 -0
  72. package/dist/streams/normalize.d.ts.map +1 -0
  73. package/dist/streams/normalize.js +43 -0
  74. package/dist/streams/normalize.js.map +1 -0
  75. package/dist/streams/replayable-stream.d.ts +19 -0
  76. package/dist/streams/replayable-stream.d.ts.map +1 -0
  77. package/dist/streams/replayable-stream.js +90 -0
  78. package/dist/streams/replayable-stream.js.map +1 -0
  79. package/dist/vault/content-hash.d.ts +16 -0
  80. package/dist/vault/content-hash.d.ts.map +1 -0
  81. package/dist/vault/content-hash.js +21 -0
  82. package/dist/vault/content-hash.js.map +1 -0
  83. package/dist/vault/vault.d.ts +9 -0
  84. package/dist/vault/vault.d.ts.map +1 -1
  85. package/dist/vault/vault.js +49 -3
  86. package/dist/vault/vault.js.map +1 -1
  87. package/package.json +1 -1
  88. package/src/__tests__/content-hash.test.ts +60 -0
  89. package/src/__tests__/core-ops.test.ts +10 -7
  90. package/src/__tests__/extensions.test.ts +233 -0
  91. package/src/__tests__/grading-ops.test.ts +2 -2
  92. package/src/__tests__/memory-cross-project-ops.test.ts +2 -2
  93. package/src/__tests__/normalize.test.ts +75 -0
  94. package/src/__tests__/playbook.test.ts +4 -4
  95. package/src/__tests__/replayable-stream.test.ts +66 -0
  96. package/src/__tests__/vault-extra-ops.test.ts +1 -1
  97. package/src/__tests__/vault.test.ts +72 -0
  98. package/src/extensions/index.ts +2 -0
  99. package/src/extensions/middleware.ts +53 -0
  100. package/src/extensions/types.ts +64 -0
  101. package/src/index.ts +14 -17
  102. package/src/runtime/facades/admin-facade.ts +101 -0
  103. package/src/runtime/facades/brain-facade.ts +331 -0
  104. package/src/runtime/facades/cognee-facade.ts +162 -0
  105. package/src/runtime/facades/control-facade.ts +279 -0
  106. package/src/runtime/facades/curator-facade.ts +132 -0
  107. package/src/runtime/facades/index.ts +74 -0
  108. package/src/runtime/facades/loop-facade.ts +12 -0
  109. package/src/runtime/facades/memory-facade.ts +114 -0
  110. package/src/runtime/facades/orchestrate-facade.ts +68 -0
  111. package/src/runtime/facades/plan-facade.ts +119 -0
  112. package/src/runtime/facades/vault-facade.ts +223 -0
  113. package/src/runtime/vault-extra-ops.ts +38 -2
  114. package/src/streams/index.ts +3 -0
  115. package/src/streams/normalize.ts +56 -0
  116. package/src/streams/replayable-stream.ts +92 -0
  117. package/src/vault/content-hash.ts +31 -0
  118. package/src/vault/vault.ts +73 -3
  119. package/src/runtime/core-ops.ts +0 -1443
@@ -1,1443 +0,0 @@
1
- /**
2
- * Generic core operations factory — 207 ops that every agent gets.
3
- *
4
- * These ops are agent-agnostic (no persona, no activation).
5
- * The 5 agent-specific ops (health, identity, activate, inject_claude_md, setup)
6
- * stay in generated code because they reference agent-specific modules.
7
- */
8
-
9
- import { z } from 'zod';
10
- import type { OpDefinition } from '../facades/types.js';
11
- import type { IntelligenceEntry } from '../intelligence/types.js';
12
- import type { AgentRuntime } from './types.js';
13
- import type { GuidelineCategory, OperationalMode } from '../control/types.js';
14
- import type { PolicyType, PolicyPreset } from '../governance/types.js';
15
- import type { CogneeSearchType } from '../cognee/types.js';
16
- import { createPlanningExtraOps } from './planning-extra-ops.js';
17
- import { createMemoryExtraOps } from './memory-extra-ops.js';
18
- import { createVaultExtraOps } from './vault-extra-ops.js';
19
- import { createAdminOps } from './admin-ops.js';
20
- import { createAdminExtraOps } from './admin-extra-ops.js';
21
- import { createLoopOps } from './loop-ops.js';
22
- import { createOrchestrateOps } from './orchestrate-ops.js';
23
- import { createGradingOps } from './grading-ops.js';
24
- import { createCaptureOps } from './capture-ops.js';
25
- import { createCuratorExtraOps } from './curator-extra-ops.js';
26
- import { createProjectOps } from './project-ops.js';
27
- import { createMemoryCrossProjectOps } from './memory-cross-project-ops.js';
28
- import { createPlaybookOps } from './playbook-ops.js';
29
- import { createCogneeSyncOps } from './cognee-sync-ops.js';
30
- import { createIntakeOps } from './intake-ops.js';
31
-
32
- /**
33
- * Create the 207 generic core operations for an agent runtime.
34
- *
35
- * Groups: search/vault (4), memory (4), export (1), planning (5),
36
- * brain (8), brain intelligence (11), cognee (5),
37
- * llm (2), curator (8), control (8), governance (5),
38
- * playbook (5), prompt templates (2),
39
- * planning-extra (22), memory-extra (8), vault-extra (23),
40
- * admin (8), admin-extra (24), loop (9), orchestrate (5),
41
- * grading (5), capture (4), curator-extra (5), project (12),
42
- * cognee-sync (3), intake (4).
43
- */
44
- export function createCoreOps(runtime: AgentRuntime): OpDefinition[] {
45
- const {
46
- vault,
47
- brain,
48
- brainIntelligence,
49
- planner,
50
- curator,
51
- governance,
52
- cognee,
53
- identityManager,
54
- intentRouter,
55
- llmClient,
56
- keyPool,
57
- syncManager,
58
- intakePipeline,
59
- } = runtime;
60
-
61
- return [
62
- // ─── Search / Vault ──────────────────────────────────────────
63
- {
64
- name: 'search',
65
- description:
66
- 'Search across all knowledge domains. Results ranked by TF-IDF + severity + recency + tag overlap + domain match.',
67
- auth: 'read',
68
- schema: z.object({
69
- query: z.string(),
70
- domain: z.string().optional(),
71
- type: z.enum(['pattern', 'anti-pattern', 'rule', 'playbook']).optional(),
72
- severity: z.enum(['critical', 'warning', 'suggestion']).optional(),
73
- tags: z.array(z.string()).optional(),
74
- limit: z.number().optional(),
75
- }),
76
- handler: async (params) => {
77
- return brain.intelligentSearch(params.query as string, {
78
- domain: params.domain as string | undefined,
79
- type: params.type as string | undefined,
80
- severity: params.severity as string | undefined,
81
- tags: params.tags as string[] | undefined,
82
- limit: (params.limit as number) ?? 10,
83
- });
84
- },
85
- },
86
- {
87
- name: 'vault_stats',
88
- description: 'Get vault statistics — entry counts by type, domain, severity.',
89
- auth: 'read',
90
- handler: async () => vault.stats(),
91
- },
92
- {
93
- name: 'list_all',
94
- description: 'List all knowledge entries with optional filters.',
95
- auth: 'read',
96
- schema: z.object({
97
- domain: z.string().optional(),
98
- type: z.enum(['pattern', 'anti-pattern', 'rule', 'playbook']).optional(),
99
- severity: z.enum(['critical', 'warning', 'suggestion']).optional(),
100
- tags: z.array(z.string()).optional(),
101
- limit: z.number().optional(),
102
- offset: z.number().optional(),
103
- }),
104
- handler: async (params) => {
105
- return vault.list({
106
- domain: params.domain as string | undefined,
107
- type: params.type as string | undefined,
108
- severity: params.severity as string | undefined,
109
- tags: params.tags as string[] | undefined,
110
- limit: (params.limit as number) ?? 50,
111
- offset: (params.offset as number) ?? 0,
112
- });
113
- },
114
- },
115
- {
116
- name: 'register',
117
- description:
118
- 'Register a project for this session. Call on every new session to track usage and get context.',
119
- auth: 'write',
120
- schema: z.object({
121
- projectPath: z.string().optional().default('.'),
122
- name: z.string().optional().describe('Project display name (derived from path if omitted)'),
123
- }),
124
- handler: async (params) => {
125
- const { resolve } = await import('node:path');
126
- const projectPath = resolve((params.projectPath as string) ?? '.');
127
- const project = vault.registerProject(projectPath, params.name as string | undefined);
128
- // Also track in project registry for cross-project features
129
- runtime.projectRegistry.register(projectPath, params.name as string | undefined);
130
- const stats = vault.stats();
131
- const isNew = project.sessionCount === 1;
132
-
133
- // Expire stale proposals on session start (fire-and-forget)
134
- const policy = governance.getPolicy(projectPath);
135
- const expired = governance.expireStaleProposals(policy.autoCapture.autoExpireDays);
136
-
137
- const proposalStats = governance.getProposalStats(projectPath);
138
- const quotaStatus = governance.getQuotaStatus(projectPath);
139
-
140
- return {
141
- project,
142
- is_new: isNew,
143
- message: isNew
144
- ? 'Welcome! New project registered.'
145
- : 'Welcome back! Session #' + project.sessionCount + ' for ' + project.name + '.',
146
- vault: { entries: stats.totalEntries, domains: Object.keys(stats.byDomain) },
147
- governance: {
148
- pendingProposals: proposalStats.pending,
149
- quotaPercent:
150
- quotaStatus.maxTotal > 0
151
- ? Math.round((quotaStatus.total / quotaStatus.maxTotal) * 100)
152
- : 0,
153
- isQuotaWarning: quotaStatus.isWarning,
154
- expiredThisSession: expired,
155
- },
156
- };
157
- },
158
- },
159
-
160
- // ─── Memory ──────────────────────────────────────────────────
161
- {
162
- name: 'memory_search',
163
- description: 'Search memories using full-text search.',
164
- auth: 'read',
165
- schema: z.object({
166
- query: z.string(),
167
- type: z.enum(['session', 'lesson', 'preference']).optional(),
168
- projectPath: z.string().optional(),
169
- limit: z.number().optional(),
170
- }),
171
- handler: async (params) => {
172
- return vault.searchMemories(params.query as string, {
173
- type: params.type as string | undefined,
174
- projectPath: params.projectPath as string | undefined,
175
- limit: (params.limit as number) ?? 10,
176
- });
177
- },
178
- },
179
- {
180
- name: 'memory_capture',
181
- description: 'Capture a memory — session summary, lesson learned, or preference.',
182
- auth: 'write',
183
- schema: z.object({
184
- projectPath: z.string(),
185
- type: z.enum(['session', 'lesson', 'preference']),
186
- context: z.string(),
187
- summary: z.string(),
188
- topics: z.array(z.string()).optional().default([]),
189
- filesModified: z.array(z.string()).optional().default([]),
190
- toolsUsed: z.array(z.string()).optional().default([]),
191
- }),
192
- handler: async (params) => {
193
- const memory = vault.captureMemory({
194
- projectPath: params.projectPath as string,
195
- type: params.type as 'session' | 'lesson' | 'preference',
196
- context: params.context as string,
197
- summary: params.summary as string,
198
- topics: (params.topics as string[]) ?? [],
199
- filesModified: (params.filesModified as string[]) ?? [],
200
- toolsUsed: (params.toolsUsed as string[]) ?? [],
201
- });
202
- return { captured: true, memory };
203
- },
204
- },
205
- {
206
- name: 'memory_list',
207
- description: 'List memories with optional filters.',
208
- auth: 'read',
209
- schema: z.object({
210
- type: z.enum(['session', 'lesson', 'preference']).optional(),
211
- projectPath: z.string().optional(),
212
- limit: z.number().optional(),
213
- offset: z.number().optional(),
214
- }),
215
- handler: async (params) => {
216
- const memories = vault.listMemories({
217
- type: params.type as string | undefined,
218
- projectPath: params.projectPath as string | undefined,
219
- limit: (params.limit as number) ?? 50,
220
- offset: (params.offset as number) ?? 0,
221
- });
222
- const stats = vault.memoryStats();
223
- return { memories, stats };
224
- },
225
- },
226
- {
227
- name: 'session_capture',
228
- description:
229
- 'Capture a session summary before context compaction. Called automatically by PreCompact hook.',
230
- auth: 'write',
231
- schema: z.object({
232
- projectPath: z.string().optional().default('.'),
233
- summary: z.string().describe('Brief summary of what was accomplished in this session'),
234
- topics: z.array(z.string()).optional().default([]),
235
- filesModified: z.array(z.string()).optional().default([]),
236
- toolsUsed: z.array(z.string()).optional().default([]),
237
- }),
238
- handler: async (params) => {
239
- const { resolve } = await import('node:path');
240
- const projectPath = resolve((params.projectPath as string) ?? '.');
241
- const memory = vault.captureMemory({
242
- projectPath,
243
- type: 'session',
244
- context: 'Auto-captured before context compaction',
245
- summary: params.summary as string,
246
- topics: (params.topics as string[]) ?? [],
247
- filesModified: (params.filesModified as string[]) ?? [],
248
- toolsUsed: (params.toolsUsed as string[]) ?? [],
249
- });
250
- return { captured: true, memory, message: 'Session summary saved to memory.' };
251
- },
252
- },
253
-
254
- // ─── Export ───────────────────────────────────────────────────
255
- {
256
- name: 'export',
257
- description:
258
- 'Export vault entries as JSON intelligence bundles — one per domain. Enables version control and sharing.',
259
- auth: 'read',
260
- schema: z.object({
261
- domain: z.string().optional().describe('Export only this domain. Omit to export all.'),
262
- }),
263
- handler: async (params) => {
264
- const stats = vault.stats();
265
- const domains = params.domain ? [params.domain as string] : Object.keys(stats.byDomain);
266
- const bundles: Array<{ domain: string; version: string; entries: IntelligenceEntry[] }> =
267
- [];
268
- for (const d of domains) {
269
- const entries = vault.list({ domain: d, limit: 10000 });
270
- bundles.push({ domain: d, version: '1.0.0', entries });
271
- }
272
- return {
273
- exported: true,
274
- bundles,
275
- totalEntries: bundles.reduce((sum, b) => sum + b.entries.length, 0),
276
- domains: bundles.map((b) => b.domain),
277
- };
278
- },
279
- },
280
-
281
- // ─── Planning ────────────────────────────────────────────────
282
- {
283
- name: 'create_plan',
284
- description:
285
- 'Create a new plan in draft status. Plans track multi-step tasks with decisions and sub-tasks.',
286
- auth: 'write',
287
- schema: z.object({
288
- objective: z.string().describe('What the plan aims to achieve'),
289
- scope: z.string().describe('Which parts of the codebase are affected'),
290
- decisions: z.array(z.string()).optional().default([]),
291
- tasks: z
292
- .array(z.object({ title: z.string(), description: z.string() }))
293
- .optional()
294
- .default([]),
295
- }),
296
- handler: async (params) => {
297
- const plan = planner.create({
298
- objective: params.objective as string,
299
- scope: params.scope as string,
300
- decisions: (params.decisions as string[]) ?? [],
301
- tasks: (params.tasks as Array<{ title: string; description: string }>) ?? [],
302
- });
303
- return { created: true, plan };
304
- },
305
- },
306
- {
307
- name: 'get_plan',
308
- description: 'Get a plan by ID, or list all active plans if no ID provided.',
309
- auth: 'read',
310
- schema: z.object({
311
- planId: z.string().optional().describe('Plan ID. Omit to list all active plans.'),
312
- }),
313
- handler: async (params) => {
314
- if (params.planId) {
315
- const plan = planner.get(params.planId as string);
316
- if (!plan) return { error: 'Plan not found: ' + params.planId };
317
- return plan;
318
- }
319
- return { active: planner.getActive(), executing: planner.getExecuting() };
320
- },
321
- },
322
- {
323
- name: 'approve_plan',
324
- description: 'Approve a draft plan and optionally start execution.',
325
- auth: 'write',
326
- schema: z.object({
327
- planId: z.string(),
328
- startExecution: z
329
- .boolean()
330
- .optional()
331
- .default(false)
332
- .describe('If true, immediately start execution after approval'),
333
- }),
334
- handler: async (params) => {
335
- let plan = planner.approve(params.planId as string);
336
- if (params.startExecution) {
337
- plan = planner.startExecution(plan.id);
338
- }
339
- return { approved: true, executing: plan.status === 'executing', plan };
340
- },
341
- },
342
- {
343
- name: 'update_task',
344
- description: 'Update a task status within an executing plan.',
345
- auth: 'write',
346
- schema: z.object({
347
- planId: z.string(),
348
- taskId: z.string(),
349
- status: z.enum(['pending', 'in_progress', 'completed', 'skipped', 'failed']),
350
- }),
351
- handler: async (params) => {
352
- const plan = planner.updateTask(
353
- params.planId as string,
354
- params.taskId as string,
355
- params.status as 'pending' | 'in_progress' | 'completed' | 'skipped' | 'failed',
356
- );
357
- const task = plan.tasks.find((t) => t.id === params.taskId);
358
- return { updated: true, task, plan: { id: plan.id, status: plan.status } };
359
- },
360
- },
361
- {
362
- name: 'complete_plan',
363
- description: 'Mark an executing plan as completed.',
364
- auth: 'write',
365
- schema: z.object({
366
- planId: z.string(),
367
- }),
368
- handler: async (params) => {
369
- const plan = planner.complete(params.planId as string);
370
- const taskSummary = {
371
- completed: plan.tasks.filter((t) => t.status === 'completed').length,
372
- skipped: plan.tasks.filter((t) => t.status === 'skipped').length,
373
- failed: plan.tasks.filter((t) => t.status === 'failed').length,
374
- total: plan.tasks.length,
375
- };
376
- return { completed: true, plan, taskSummary };
377
- },
378
- },
379
-
380
- // ─── Brain ───────────────────────────────────────────────────
381
- {
382
- name: 'record_feedback',
383
- description:
384
- 'Record feedback on a search result — accepted or dismissed. Used for adaptive weight tuning.',
385
- auth: 'write',
386
- schema: z.object({
387
- query: z.string().describe('The original search query'),
388
- entryId: z.string().describe('The entry ID that was accepted or dismissed'),
389
- action: z.enum(['accepted', 'dismissed']),
390
- }),
391
- handler: async (params) => {
392
- brain.recordFeedback(
393
- params.query as string,
394
- params.entryId as string,
395
- params.action as 'accepted' | 'dismissed',
396
- );
397
- return {
398
- recorded: true,
399
- query: params.query,
400
- entryId: params.entryId,
401
- action: params.action,
402
- };
403
- },
404
- },
405
- {
406
- name: 'brain_feedback',
407
- description:
408
- 'Enhanced feedback with typed actions (accepted/dismissed/modified/failed), source tracking, confidence, duration, and reason.',
409
- auth: 'write',
410
- schema: z.object({
411
- query: z.string().describe('The original search query'),
412
- entryId: z.string().describe('The entry ID'),
413
- action: z.enum(['accepted', 'dismissed', 'modified', 'failed']),
414
- source: z
415
- .enum(['search', 'recommendation', 'tool-execution', 'explicit'])
416
- .optional()
417
- .describe("Feedback source. Default 'search'."),
418
- confidence: z.number().optional().describe('Confidence 0-1. Default 0.6.'),
419
- duration: z.number().optional().describe('Duration in ms.'),
420
- context: z.string().optional().describe("JSON context string. Default '{}'."),
421
- reason: z.string().optional().describe('Human-readable reason.'),
422
- }),
423
- handler: async (params) => {
424
- const entry = brain.recordFeedback({
425
- query: params.query as string,
426
- entryId: params.entryId as string,
427
- action: params.action as 'accepted' | 'dismissed' | 'modified' | 'failed',
428
- source: params.source as
429
- | 'search'
430
- | 'recommendation'
431
- | 'tool-execution'
432
- | 'explicit'
433
- | undefined,
434
- confidence: params.confidence as number | undefined,
435
- duration: params.duration as number | undefined,
436
- context: params.context as string | undefined,
437
- reason: params.reason as string | undefined,
438
- });
439
- return entry;
440
- },
441
- },
442
- {
443
- name: 'brain_feedback_stats',
444
- description:
445
- 'Feedback statistics — counts by action and source, acceptance rate, average confidence.',
446
- auth: 'read',
447
- handler: async () => {
448
- return brain.getFeedbackStats();
449
- },
450
- },
451
- {
452
- name: 'rebuild_vocabulary',
453
- description: 'Force rebuild the TF-IDF vocabulary from all vault entries.',
454
- auth: 'write',
455
- handler: async () => {
456
- brain.rebuildVocabulary();
457
- return { rebuilt: true, vocabularySize: brain.getVocabularySize() };
458
- },
459
- },
460
- {
461
- name: 'brain_stats',
462
- description:
463
- 'Get brain intelligence stats — vocabulary size, feedback count, current scoring weights, intelligence pipeline stats.',
464
- auth: 'read',
465
- handler: async () => {
466
- const base = brain.getStats();
467
- const intelligence = brainIntelligence.getStats();
468
- return { ...base, intelligence };
469
- },
470
- },
471
- {
472
- name: 'brain_decay_report',
473
- description:
474
- 'Show temporal decay scores for entries matching a query — reveals which entries are expiring, active, or expired.',
475
- auth: 'read',
476
- schema: z.object({
477
- query: z.string().describe('Search query to find entries'),
478
- limit: z.number().optional().describe('Max results (default 10)'),
479
- }),
480
- handler: async (params) => {
481
- const results = await brain.getDecayReport(
482
- params.query as string,
483
- (params.limit as number | undefined) ?? 10,
484
- );
485
- return { results, count: results.length };
486
- },
487
- },
488
- {
489
- name: 'llm_status',
490
- description:
491
- 'LLM client status — provider availability, key pool status, model routing config.',
492
- auth: 'read',
493
- handler: async () => {
494
- const available = llmClient.isAvailable();
495
- return {
496
- providers: {
497
- openai: {
498
- available: available.openai,
499
- keyPool: keyPool.openai.hasKeys ? keyPool.openai.getStatus() : null,
500
- },
501
- anthropic: {
502
- available: available.anthropic,
503
- keyPool: keyPool.anthropic.hasKeys ? keyPool.anthropic.getStatus() : null,
504
- },
505
- },
506
- routes: llmClient.getRoutes(),
507
- };
508
- },
509
- },
510
-
511
- // ─── Brain Intelligence ───────────────────────────────────────
512
- {
513
- name: 'brain_session_context',
514
- description:
515
- 'Get recent session context — sessions, tool usage frequency, file change frequency.',
516
- auth: 'read',
517
- schema: z.object({
518
- limit: z.number().optional().describe('Number of recent sessions. Default 10.'),
519
- }),
520
- handler: async (params) => {
521
- return brainIntelligence.getSessionContext((params.limit as number) ?? 10);
522
- },
523
- },
524
- {
525
- name: 'brain_strengths',
526
- description:
527
- 'Get pattern strength scores. 4-signal scoring: usage (0-25) + spread (0-25) + success (0-25) + recency (0-25).',
528
- auth: 'read',
529
- schema: z.object({
530
- domain: z.string().optional(),
531
- minStrength: z.number().optional().describe('Minimum strength score (0-100).'),
532
- limit: z.number().optional(),
533
- }),
534
- handler: async (params) => {
535
- return brainIntelligence.getStrengths({
536
- domain: params.domain as string | undefined,
537
- minStrength: params.minStrength as number | undefined,
538
- limit: (params.limit as number) ?? 50,
539
- });
540
- },
541
- },
542
- {
543
- name: 'brain_global_patterns',
544
- description:
545
- 'Get cross-domain pattern registry — patterns that appear across multiple domains.',
546
- auth: 'read',
547
- schema: z.object({
548
- limit: z.number().optional(),
549
- }),
550
- handler: async (params) => {
551
- return brainIntelligence.getGlobalPatterns((params.limit as number) ?? 20);
552
- },
553
- },
554
- {
555
- name: 'brain_recommend',
556
- description:
557
- 'Get pattern recommendations for a task context. Matches domain, task terms, and source-specific acceptance rates against known strengths.',
558
- auth: 'read',
559
- schema: z.object({
560
- domain: z.string().optional(),
561
- task: z.string().optional().describe('Task description for contextual matching.'),
562
- source: z
563
- .string()
564
- .optional()
565
- .describe(
566
- 'Feedback source to boost by (search, recommendation, tool-execution, explicit).',
567
- ),
568
- limit: z.number().optional(),
569
- }),
570
- handler: async (params) => {
571
- return brainIntelligence.recommend({
572
- domain: params.domain as string | undefined,
573
- task: params.task as string | undefined,
574
- source: params.source as string | undefined,
575
- limit: (params.limit as number) ?? 5,
576
- });
577
- },
578
- },
579
- {
580
- name: 'brain_build_intelligence',
581
- description:
582
- 'Run the full intelligence pipeline: compute strengths → build global registry → build domain profiles.',
583
- auth: 'write',
584
- handler: async () => {
585
- return brainIntelligence.buildIntelligence();
586
- },
587
- },
588
- {
589
- name: 'brain_export',
590
- description:
591
- 'Export all brain intelligence data — strengths, sessions, proposals, global patterns, domain profiles.',
592
- auth: 'read',
593
- handler: async () => {
594
- return brainIntelligence.exportData();
595
- },
596
- },
597
- {
598
- name: 'brain_import',
599
- description: 'Import brain intelligence data from a previous export.',
600
- auth: 'write',
601
- schema: z.object({
602
- data: z.any().describe('BrainExportData object from brain_export.'),
603
- }),
604
- handler: async (params) => {
605
- return brainIntelligence.importData(
606
- params.data as import('../brain/types.js').BrainExportData,
607
- );
608
- },
609
- },
610
- {
611
- name: 'brain_extract_knowledge',
612
- description:
613
- 'Extract knowledge proposals from a session using 6 heuristic rules (repeated tools, multi-file edits, long sessions, plan outcomes, feedback ratios).',
614
- auth: 'write',
615
- schema: z.object({
616
- sessionId: z.string().describe('Session ID to extract knowledge from.'),
617
- }),
618
- handler: async (params) => {
619
- return brainIntelligence.extractKnowledge(params.sessionId as string);
620
- },
621
- },
622
- {
623
- name: 'brain_archive_sessions',
624
- description: 'Archive (delete) completed sessions older than N days.',
625
- auth: 'write',
626
- schema: z.object({
627
- olderThanDays: z.number().optional().describe('Days threshold. Default 30.'),
628
- }),
629
- handler: async (params) => {
630
- return brainIntelligence.archiveSessions((params.olderThanDays as number) ?? 30);
631
- },
632
- },
633
- {
634
- name: 'brain_promote_proposals',
635
- description:
636
- 'Promote knowledge proposals to vault entries. Creates intelligence entries from auto-extracted patterns. Gated by governance policies.',
637
- auth: 'write',
638
- schema: z.object({
639
- proposalIds: z.array(z.string()).describe('IDs of proposals to promote.'),
640
- projectPath: z.string().optional().default('.'),
641
- }),
642
- handler: async (params) => {
643
- const pp = (params.projectPath as string | undefined) ?? '.';
644
- return brainIntelligence.promoteProposals(params.proposalIds as string[], governance, pp);
645
- },
646
- },
647
- {
648
- name: 'brain_lifecycle',
649
- description:
650
- 'Start or end a brain session. Sessions track tool usage, file changes, and plan context.',
651
- auth: 'write',
652
- schema: z.object({
653
- action: z.enum(['start', 'end']),
654
- sessionId: z
655
- .string()
656
- .optional()
657
- .describe('Required for end. Auto-generated for start if omitted.'),
658
- domain: z.string().optional(),
659
- context: z.string().optional(),
660
- toolsUsed: z.array(z.string()).optional(),
661
- filesModified: z.array(z.string()).optional(),
662
- planId: z.string().optional(),
663
- planOutcome: z.string().optional(),
664
- }),
665
- handler: async (params) => {
666
- return brainIntelligence.lifecycle({
667
- action: params.action as 'start' | 'end',
668
- sessionId: params.sessionId as string | undefined,
669
- domain: params.domain as string | undefined,
670
- context: params.context as string | undefined,
671
- toolsUsed: params.toolsUsed as string[] | undefined,
672
- filesModified: params.filesModified as string[] | undefined,
673
- planId: params.planId as string | undefined,
674
- planOutcome: params.planOutcome as string | undefined,
675
- });
676
- },
677
- },
678
-
679
- {
680
- name: 'brain_reset_extracted',
681
- description:
682
- 'Reset extraction status on brain sessions, allowing re-extraction. Filter by sessionId, since date, or all.',
683
- auth: 'write',
684
- schema: z.object({
685
- sessionId: z.string().optional().describe('Reset a specific session.'),
686
- since: z.string().optional().describe('Reset sessions extracted since this ISO date.'),
687
- all: z.boolean().optional().describe('Reset all extracted sessions.'),
688
- }),
689
- handler: async (params) => {
690
- return brainIntelligence.resetExtracted({
691
- sessionId: params.sessionId as string | undefined,
692
- since: params.since as string | undefined,
693
- all: params.all as boolean | undefined,
694
- });
695
- },
696
- },
697
-
698
- // ─── Cognee ──────────────────────────────────────────────────
699
- {
700
- name: 'cognee_status',
701
- description:
702
- 'Cognee vector search health — availability, URL, latency. Checks the Cognee API endpoint.',
703
- auth: 'read',
704
- handler: async () => {
705
- return cognee.healthCheck();
706
- },
707
- },
708
- {
709
- name: 'cognee_search',
710
- description:
711
- 'Vector similarity search via Cognee. Complements TF-IDF vault search with semantic understanding.',
712
- auth: 'read',
713
- schema: z.object({
714
- query: z.string(),
715
- searchType: z
716
- .enum([
717
- 'SUMMARIES',
718
- 'CHUNKS',
719
- 'RAG_COMPLETION',
720
- 'TRIPLET_COMPLETION',
721
- 'GRAPH_COMPLETION',
722
- 'GRAPH_SUMMARY_COMPLETION',
723
- 'NATURAL_LANGUAGE',
724
- 'GRAPH_COMPLETION_COT',
725
- 'FEELING_LUCKY',
726
- 'CHUNKS_LEXICAL',
727
- ])
728
- .optional()
729
- .describe('Cognee search type. Default CHUNKS (pure vector similarity).'),
730
- limit: z.number().optional(),
731
- }),
732
- handler: async (params) => {
733
- return cognee.search(params.query as string, {
734
- searchType: params.searchType as CogneeSearchType | undefined,
735
- limit: (params.limit as number) ?? 10,
736
- });
737
- },
738
- },
739
- {
740
- name: 'cognee_add',
741
- description:
742
- 'Ingest vault entries into Cognee for vector indexing. Auto-schedules cognify after ingest.',
743
- auth: 'write',
744
- schema: z.object({
745
- entryIds: z.array(z.string()).describe('Vault entry IDs to ingest into Cognee.'),
746
- }),
747
- handler: async (params) => {
748
- const ids = params.entryIds as string[];
749
- const entries = ids
750
- .map((id) => vault.get(id))
751
- .filter((e): e is IntelligenceEntry => e !== null && e !== undefined);
752
- if (entries.length === 0) return { added: 0, error: 'No matching vault entries found' };
753
- return cognee.addEntries(entries);
754
- },
755
- },
756
- {
757
- name: 'cognee_cognify',
758
- description:
759
- 'Trigger Cognee knowledge graph processing on the vault dataset. Usually auto-scheduled after add.',
760
- auth: 'write',
761
- handler: async () => {
762
- return cognee.cognify();
763
- },
764
- },
765
- {
766
- name: 'cognee_config',
767
- description: 'Get current Cognee client configuration and cached health status.',
768
- auth: 'read',
769
- handler: async () => {
770
- return { config: cognee.getConfig(), cachedStatus: cognee.getStatus() };
771
- },
772
- },
773
- // ─── Cognee Graph (#156) ──────────────────────────────────────
774
- {
775
- name: 'cognee_get_node',
776
- description: 'Get a specific Cognee graph node by UUID with all properties and connections.',
777
- auth: 'read',
778
- schema: z.object({
779
- nodeId: z.string().describe('UUID of the graph node'),
780
- }),
781
- handler: async (params) => {
782
- try {
783
- // Use Cognee search with specific ID query — the graph node API is accessed via search
784
- const results = await cognee.search(params.nodeId as string, {
785
- searchType: 'GRAPH_COMPLETION' as CogneeSearchType,
786
- limit: 1,
787
- });
788
- if (!results || (Array.isArray(results) && results.length === 0)) {
789
- return { found: false, nodeId: params.nodeId };
790
- }
791
- return {
792
- found: true,
793
- nodeId: params.nodeId,
794
- node: Array.isArray(results) ? results[0] : results,
795
- };
796
- } catch (err) {
797
- return { error: (err as Error).message };
798
- }
799
- },
800
- },
801
- {
802
- name: 'cognee_graph_stats',
803
- description:
804
- 'Cognee graph statistics — availability, endpoint, latency from last health check.',
805
- auth: 'read',
806
- handler: async () => {
807
- try {
808
- const status = cognee.getStatus();
809
- const health = await cognee.healthCheck();
810
- return {
811
- available: status?.available ?? false,
812
- url: status?.url ?? cognee.getConfig().baseUrl,
813
- latencyMs: status?.latencyMs ?? health.latencyMs ?? null,
814
- error: status?.error ?? health.error ?? null,
815
- };
816
- } catch (err) {
817
- return { error: (err as Error).message };
818
- }
819
- },
820
- },
821
- {
822
- name: 'cognee_export_status',
823
- description: 'Check Cognee dataset and processing status — availability, pending operations.',
824
- auth: 'read',
825
- handler: async () => {
826
- try {
827
- const status = cognee.getStatus();
828
- const config = cognee.getConfig();
829
- return {
830
- available: status?.available ?? false,
831
- dataset: config.dataset ?? 'default',
832
- pendingCognify: false, // CogneeClient tracks internally via flushPendingCognify
833
- url: status?.url ?? config.baseUrl,
834
- };
835
- } catch (err) {
836
- return { error: (err as Error).message };
837
- }
838
- },
839
- },
840
-
841
- // ─── Enriched Capture (#154) ─────────────────────────────────
842
- {
843
- name: 'capture_enriched',
844
- description:
845
- 'Unified LLM-enriched capture — accepts minimal fields (title, description, type), uses LLM to auto-infer tags, category, and severity.',
846
- auth: 'write',
847
- schema: z.object({
848
- title: z.string().describe('Knowledge title'),
849
- description: z.string().describe('Knowledge description'),
850
- type: z
851
- .enum(['pattern', 'anti-pattern', 'rule', 'playbook'])
852
- .optional()
853
- .describe('Entry type. If omitted, LLM infers from content.'),
854
- domain: z.string().optional().describe('Domain. If omitted, LLM infers.'),
855
- tags: z.array(z.string()).optional().describe('Tags. LLM adds more if needed.'),
856
- }),
857
- handler: async (params) => {
858
- try {
859
- const title = params.title as string;
860
- const description = params.description as string;
861
-
862
- // Try LLM enrichment for auto-tagging
863
- let inferredTags: string[] = (params.tags as string[] | undefined) ?? [];
864
- let inferredType = (params.type as IntelligenceEntry['type'] | undefined) ?? 'pattern';
865
- const inferredDomain = (params.domain as string | undefined) ?? 'general';
866
- let inferredSeverity: IntelligenceEntry['severity'] = 'suggestion';
867
- const enriched = false;
868
-
869
- try {
870
- const captureId = `enriched-${Date.now()}-${Math.random().toString(36).slice(2, 6)}`;
871
- const enrichResult = brain.enrichAndCapture({
872
- id: captureId,
873
- title,
874
- description,
875
- type: inferredType,
876
- domain: inferredDomain,
877
- severity: inferredSeverity,
878
- tags: inferredTags,
879
- });
880
-
881
- if (enrichResult.captured) {
882
- return {
883
- captured: true,
884
- enriched: true,
885
- entryId: enrichResult.id,
886
- autoTags: enrichResult.autoTags,
887
- duplicate: enrichResult.duplicate ?? null,
888
- };
889
- }
890
- } catch {
891
- // LLM enrichment failed — fall back to basic capture
892
- }
893
-
894
- // Fallback: basic capture without LLM enrichment
895
- // Infer type from keywords
896
- const lowerDesc = description.toLowerCase();
897
- if (!params.type) {
898
- if (
899
- lowerDesc.includes('avoid') ||
900
- lowerDesc.includes("don't") ||
901
- lowerDesc.includes('anti-pattern')
902
- )
903
- inferredType = 'anti-pattern';
904
- else if (
905
- lowerDesc.includes('rule') ||
906
- lowerDesc.includes('must') ||
907
- lowerDesc.includes('always')
908
- )
909
- inferredType = 'rule';
910
- }
911
-
912
- // Infer severity from keywords
913
- if (
914
- lowerDesc.includes('critical') ||
915
- lowerDesc.includes('security') ||
916
- lowerDesc.includes('breaking')
917
- )
918
- inferredSeverity = 'critical';
919
- else if (
920
- lowerDesc.includes('warning') ||
921
- lowerDesc.includes('careful') ||
922
- lowerDesc.includes('avoid')
923
- )
924
- inferredSeverity = 'warning';
925
-
926
- // Auto-generate tags from title words
927
- if (inferredTags.length === 0) {
928
- inferredTags = title
929
- .toLowerCase()
930
- .split(/\s+/)
931
- .filter(
932
- (w) =>
933
- w.length > 3 && !['with', 'from', 'that', 'this', 'have', 'been'].includes(w),
934
- )
935
- .slice(0, 5);
936
- }
937
-
938
- const entry: IntelligenceEntry = {
939
- id: `enriched-${Date.now()}-${Math.random().toString(36).slice(2, 6)}`,
940
- type: inferredType,
941
- domain: inferredDomain,
942
- title,
943
- severity: inferredSeverity,
944
- description,
945
- tags: inferredTags,
946
- };
947
-
948
- vault.add(entry);
949
-
950
- return {
951
- captured: true,
952
- enriched,
953
- entry,
954
- autoTags: inferredTags,
955
- };
956
- } catch (err) {
957
- return { error: (err as Error).message };
958
- }
959
- },
960
- },
961
-
962
- // ─── LLM ─────────────────────────────────────────────────────
963
- {
964
- name: 'llm_rotate',
965
- description:
966
- 'Force rotate the active API key for a provider. Useful when rate-limited or key is failing.',
967
- auth: 'write',
968
- schema: z.object({
969
- provider: z.enum(['openai', 'anthropic']),
970
- }),
971
- handler: async (params) => {
972
- const provider = params.provider as 'openai' | 'anthropic';
973
- const pool = keyPool[provider];
974
- if (!pool.hasKeys) return { rotated: false, error: `No ${provider} keys configured` };
975
- const newKey = pool.rotateOnError();
976
- return {
977
- rotated: newKey !== null,
978
- activeKeyIndex: pool.activeKeyIndex,
979
- poolSize: pool.poolSize,
980
- exhausted: pool.exhausted,
981
- };
982
- },
983
- },
984
- {
985
- name: 'llm_call',
986
- description: 'Make an LLM completion call. Uses model routing config and key pool rotation.',
987
- auth: 'write',
988
- schema: z.object({
989
- systemPrompt: z.string().describe('System prompt for the LLM.'),
990
- userPrompt: z.string().describe('User prompt / task input.'),
991
- model: z
992
- .string()
993
- .optional()
994
- .describe('Model name. Routed via model-routing.json if omitted.'),
995
- temperature: z.number().optional().describe('Sampling temperature (0-2). Default 0.3.'),
996
- maxTokens: z.number().optional().describe('Max output tokens. Default 500.'),
997
- caller: z.string().optional().describe('Caller name for routing. Default "core-ops".'),
998
- task: z.string().optional().describe('Task name for routing.'),
999
- }),
1000
- handler: async (params) => {
1001
- return llmClient.complete({
1002
- provider: 'openai',
1003
- model: (params.model as string) ?? '',
1004
- systemPrompt: params.systemPrompt as string,
1005
- userPrompt: params.userPrompt as string,
1006
- temperature: params.temperature as number | undefined,
1007
- maxTokens: params.maxTokens as number | undefined,
1008
- caller: (params.caller as string) ?? 'core-ops',
1009
- task: params.task as string | undefined,
1010
- });
1011
- },
1012
- },
1013
-
1014
- // ─── Curator ─────────────────────────────────────────────────
1015
- {
1016
- name: 'curator_status',
1017
- description: 'Curator status — table row counts, last groomed timestamp.',
1018
- auth: 'read',
1019
- handler: async () => {
1020
- return curator.getStatus();
1021
- },
1022
- },
1023
- {
1024
- name: 'curator_detect_duplicates',
1025
- description: 'Detect duplicate entries using TF-IDF cosine similarity.',
1026
- auth: 'read',
1027
- schema: z.object({
1028
- entryId: z.string().optional().describe('Check a specific entry. Omit to scan all.'),
1029
- threshold: z.number().optional().describe('Similarity threshold (0-1). Default 0.45.'),
1030
- }),
1031
- handler: async (params) => {
1032
- return curator.detectDuplicates(
1033
- params.entryId as string | undefined,
1034
- params.threshold as number | undefined,
1035
- );
1036
- },
1037
- },
1038
- {
1039
- name: 'curator_contradictions',
1040
- description: 'List or detect contradictions between patterns and anti-patterns.',
1041
- auth: 'read',
1042
- schema: z.object({
1043
- status: z.enum(['open', 'resolved', 'dismissed']).optional().describe('Filter by status.'),
1044
- detect: z.boolean().optional().describe('If true, run detection before listing.'),
1045
- }),
1046
- handler: async (params) => {
1047
- if (params.detect) {
1048
- curator.detectContradictions();
1049
- }
1050
- return curator.getContradictions(
1051
- params.status as 'open' | 'resolved' | 'dismissed' | undefined,
1052
- );
1053
- },
1054
- },
1055
- {
1056
- name: 'curator_resolve_contradiction',
1057
- description: 'Resolve or dismiss a contradiction.',
1058
- auth: 'write',
1059
- schema: z.object({
1060
- id: z.number().describe('Contradiction ID.'),
1061
- resolution: z.enum(['resolved', 'dismissed']),
1062
- }),
1063
- handler: async (params) => {
1064
- return curator.resolveContradiction(
1065
- params.id as number,
1066
- params.resolution as 'resolved' | 'dismissed',
1067
- );
1068
- },
1069
- },
1070
- {
1071
- name: 'curator_groom',
1072
- description: 'Groom a single entry — normalize tags, check staleness.',
1073
- auth: 'write',
1074
- schema: z.object({
1075
- entryId: z.string().describe('Entry ID to groom.'),
1076
- }),
1077
- handler: async (params) => {
1078
- return curator.groomEntry(params.entryId as string);
1079
- },
1080
- },
1081
- {
1082
- name: 'curator_groom_all',
1083
- description: 'Groom all vault entries — normalize tags, detect staleness.',
1084
- auth: 'write',
1085
- handler: async () => {
1086
- return curator.groomAll();
1087
- },
1088
- },
1089
- {
1090
- name: 'curator_consolidate',
1091
- description:
1092
- 'Consolidate vault — find duplicates, stale entries, contradictions. Dry-run by default.',
1093
- auth: 'write',
1094
- schema: z.object({
1095
- dryRun: z.boolean().optional().describe('Default true. Set false to apply mutations.'),
1096
- staleDaysThreshold: z
1097
- .number()
1098
- .optional()
1099
- .describe('Days before entry is stale. Default 90.'),
1100
- duplicateThreshold: z
1101
- .number()
1102
- .optional()
1103
- .describe('Cosine similarity threshold. Default 0.45.'),
1104
- contradictionThreshold: z
1105
- .number()
1106
- .optional()
1107
- .describe('Contradiction threshold. Default 0.4.'),
1108
- }),
1109
- handler: async (params) => {
1110
- return curator.consolidate({
1111
- dryRun: params.dryRun as boolean | undefined,
1112
- staleDaysThreshold: params.staleDaysThreshold as number | undefined,
1113
- duplicateThreshold: params.duplicateThreshold as number | undefined,
1114
- contradictionThreshold: params.contradictionThreshold as number | undefined,
1115
- });
1116
- },
1117
- },
1118
- {
1119
- name: 'curator_health_audit',
1120
- description:
1121
- 'Audit vault health — score (0-100), coverage, freshness, quality, tag health, recommendations.',
1122
- auth: 'read',
1123
- handler: async () => {
1124
- return curator.healthAudit();
1125
- },
1126
- },
1127
-
1128
- // ─── Control ──────────────────────────────────────────────────────
1129
- {
1130
- name: 'get_identity',
1131
- description: 'Get current agent identity with guidelines.',
1132
- auth: 'read',
1133
- schema: z.object({
1134
- agentId: z.string().describe('Agent identifier.'),
1135
- }),
1136
- handler: async (params) => {
1137
- const identity = identityManager.getIdentity(params.agentId as string);
1138
- if (!identity) return { found: false, agentId: params.agentId };
1139
- return identity;
1140
- },
1141
- },
1142
- {
1143
- name: 'update_identity',
1144
- description: 'Update identity fields. Auto-versions and snapshots previous state.',
1145
- auth: 'write',
1146
- schema: z.object({
1147
- agentId: z.string(),
1148
- name: z.string().optional(),
1149
- role: z.string().optional(),
1150
- description: z.string().optional(),
1151
- personality: z.array(z.string()).optional(),
1152
- changedBy: z.string().optional(),
1153
- changeReason: z.string().optional(),
1154
- }),
1155
- handler: async (params) => {
1156
- const identity = identityManager.setIdentity(params.agentId as string, {
1157
- name: params.name as string | undefined,
1158
- role: params.role as string | undefined,
1159
- description: params.description as string | undefined,
1160
- personality: params.personality as string[] | undefined,
1161
- changedBy: params.changedBy as string | undefined,
1162
- changeReason: params.changeReason as string | undefined,
1163
- });
1164
- return { updated: true, identity };
1165
- },
1166
- },
1167
- {
1168
- name: 'add_guideline',
1169
- description: 'Add a behavioral guideline (behavior/preference/restriction/style).',
1170
- auth: 'write',
1171
- schema: z.object({
1172
- agentId: z.string(),
1173
- category: z.enum(['behavior', 'preference', 'restriction', 'style']),
1174
- text: z.string(),
1175
- priority: z.number().optional(),
1176
- }),
1177
- handler: async (params) => {
1178
- const guideline = identityManager.addGuideline(params.agentId as string, {
1179
- category: params.category as GuidelineCategory,
1180
- text: params.text as string,
1181
- priority: params.priority as number | undefined,
1182
- });
1183
- return { added: true, guideline };
1184
- },
1185
- },
1186
- {
1187
- name: 'remove_guideline',
1188
- description: 'Remove a guideline by ID.',
1189
- auth: 'write',
1190
- schema: z.object({
1191
- guidelineId: z.string(),
1192
- }),
1193
- handler: async (params) => {
1194
- const removed = identityManager.removeGuideline(params.guidelineId as string);
1195
- return { removed };
1196
- },
1197
- },
1198
- {
1199
- name: 'rollback_identity',
1200
- description: 'Restore a previous identity version. Creates a new version with the old data.',
1201
- auth: 'write',
1202
- schema: z.object({
1203
- agentId: z.string(),
1204
- version: z.number().describe('Version number to roll back to.'),
1205
- }),
1206
- handler: async (params) => {
1207
- const identity = identityManager.rollback(
1208
- params.agentId as string,
1209
- params.version as number,
1210
- );
1211
- return { rolledBack: true, identity };
1212
- },
1213
- },
1214
- {
1215
- name: 'route_intent',
1216
- description: 'Classify a prompt into intent + operational mode via keyword matching.',
1217
- auth: 'read',
1218
- schema: z.object({
1219
- prompt: z.string().describe('The user prompt to classify.'),
1220
- }),
1221
- handler: async (params) => {
1222
- return intentRouter.routeIntent(params.prompt as string);
1223
- },
1224
- },
1225
- {
1226
- name: 'morph',
1227
- description: 'Switch operational mode manually.',
1228
- auth: 'write',
1229
- schema: z.object({
1230
- mode: z
1231
- .string()
1232
- .describe('The operational mode to switch to (e.g., BUILD-MODE, FIX-MODE).'),
1233
- }),
1234
- handler: async (params) => {
1235
- return intentRouter.morph(params.mode as OperationalMode);
1236
- },
1237
- },
1238
- {
1239
- name: 'get_behavior_rules',
1240
- description: 'Get behavior rules for current or specified mode.',
1241
- auth: 'read',
1242
- schema: z.object({
1243
- mode: z.string().optional().describe('Mode to get rules for. Defaults to current mode.'),
1244
- }),
1245
- handler: async (params) => {
1246
- const mode = params.mode as OperationalMode | undefined;
1247
- const rules = intentRouter.getBehaviorRules(mode);
1248
- const currentMode = intentRouter.getCurrentMode();
1249
- return { mode: mode ?? currentMode, rules };
1250
- },
1251
- },
1252
-
1253
- // ─── Governance ─────────────────────────────────────────────────
1254
- {
1255
- name: 'governance_policy',
1256
- description:
1257
- 'Get, set, or apply a preset to vault governance policies (quota, retention, auto-capture).',
1258
- auth: 'write',
1259
- schema: z.object({
1260
- action: z.enum(['get', 'set', 'applyPreset']),
1261
- projectPath: z.string(),
1262
- policyType: z.enum(['quota', 'retention', 'auto-capture']).optional(),
1263
- config: z.record(z.unknown()).optional(),
1264
- preset: z.enum(['strict', 'moderate', 'permissive']).optional(),
1265
- changedBy: z.string().optional(),
1266
- }),
1267
- handler: async (params) => {
1268
- const action = params.action as string;
1269
- const projectPath = params.projectPath as string;
1270
- if (action === 'get') {
1271
- return governance.getPolicy(projectPath);
1272
- }
1273
- if (action === 'set') {
1274
- governance.setPolicy(
1275
- projectPath,
1276
- params.policyType as PolicyType,
1277
- params.config as Record<string, unknown>,
1278
- params.changedBy as string | undefined,
1279
- );
1280
- return { updated: true, policy: governance.getPolicy(projectPath) };
1281
- }
1282
- if (action === 'applyPreset') {
1283
- governance.applyPreset(
1284
- projectPath,
1285
- params.preset as PolicyPreset,
1286
- params.changedBy as string | undefined,
1287
- );
1288
- return {
1289
- applied: true,
1290
- preset: params.preset,
1291
- policy: governance.getPolicy(projectPath),
1292
- };
1293
- }
1294
- return { error: 'Unknown action: ' + action };
1295
- },
1296
- },
1297
- {
1298
- name: 'governance_proposals',
1299
- description:
1300
- 'Manage knowledge capture proposals — list, approve, reject, modify, get stats, or expire stale.',
1301
- auth: 'write',
1302
- schema: z.object({
1303
- action: z.enum(['list', 'approve', 'reject', 'modify', 'stats', 'expire']),
1304
- projectPath: z.string().optional(),
1305
- proposalId: z.number().optional(),
1306
- decidedBy: z.string().optional(),
1307
- note: z.string().optional(),
1308
- modifications: z.record(z.unknown()).optional(),
1309
- maxAgeDays: z.number().optional(),
1310
- limit: z.number().optional(),
1311
- }),
1312
- handler: async (params) => {
1313
- const action = params.action as string;
1314
- if (action === 'list') {
1315
- return governance.listPendingProposals(
1316
- params.projectPath as string | undefined,
1317
- params.limit as number | undefined,
1318
- );
1319
- }
1320
- if (action === 'approve') {
1321
- return governance.approveProposal(
1322
- params.proposalId as number,
1323
- params.decidedBy as string | undefined,
1324
- );
1325
- }
1326
- if (action === 'reject') {
1327
- return governance.rejectProposal(
1328
- params.proposalId as number,
1329
- params.decidedBy as string | undefined,
1330
- params.note as string | undefined,
1331
- );
1332
- }
1333
- if (action === 'modify') {
1334
- return governance.modifyProposal(
1335
- params.proposalId as number,
1336
- params.modifications as Record<string, unknown>,
1337
- params.decidedBy as string | undefined,
1338
- );
1339
- }
1340
- if (action === 'stats') {
1341
- return governance.getProposalStats(params.projectPath as string | undefined);
1342
- }
1343
- if (action === 'expire') {
1344
- const expired = governance.expireStaleProposals(params.maxAgeDays as number | undefined);
1345
- return { expired };
1346
- }
1347
- return { error: 'Unknown action: ' + action };
1348
- },
1349
- },
1350
- {
1351
- name: 'governance_stats',
1352
- description: 'Get governance statistics — quota status and proposal stats for a project.',
1353
- auth: 'read',
1354
- schema: z.object({
1355
- projectPath: z.string(),
1356
- }),
1357
- handler: async (params) => {
1358
- const projectPath = params.projectPath as string;
1359
- return {
1360
- quotaStatus: governance.getQuotaStatus(projectPath),
1361
- proposalStats: governance.getProposalStats(projectPath),
1362
- };
1363
- },
1364
- },
1365
- {
1366
- name: 'governance_expire',
1367
- description: 'Expire stale pending proposals older than a threshold.',
1368
- auth: 'write',
1369
- schema: z.object({
1370
- projectPath: z.string().optional(),
1371
- maxAgeDays: z.number().optional().describe('Days threshold. Default 14.'),
1372
- }),
1373
- handler: async (params) => {
1374
- const expired = governance.expireStaleProposals(params.maxAgeDays as number | undefined);
1375
- return { expired };
1376
- },
1377
- },
1378
- {
1379
- name: 'governance_dashboard',
1380
- description:
1381
- 'Get governance dashboard — vault size, quota usage, pending proposals, acceptance rate, evaluation trend.',
1382
- auth: 'read',
1383
- schema: z.object({
1384
- projectPath: z.string(),
1385
- }),
1386
- handler: async (params) => {
1387
- return governance.getDashboard(params.projectPath as string);
1388
- },
1389
- },
1390
-
1391
- // ─── Playbook ops (from dedicated module) ─────────────────────────
1392
- ...createPlaybookOps(runtime),
1393
-
1394
- // ─── Extra Ops (from dedicated modules) ─────────────────────────
1395
- ...createPlanningExtraOps(runtime),
1396
- ...createMemoryExtraOps(runtime),
1397
- ...createVaultExtraOps(runtime),
1398
- ...createAdminOps(runtime),
1399
- ...createAdminExtraOps(runtime),
1400
- ...createLoopOps(runtime),
1401
- ...createOrchestrateOps(runtime),
1402
- ...createGradingOps(runtime),
1403
- ...createCaptureOps(runtime),
1404
- ...createCuratorExtraOps(runtime),
1405
- ...createProjectOps(runtime),
1406
- ...createMemoryCrossProjectOps(runtime),
1407
-
1408
- // ─── Cognee Sync ──────────────────────────────────────────────
1409
- ...createCogneeSyncOps(syncManager),
1410
-
1411
- // ─── Intake Pipeline ──────────────────────────────────────────
1412
- ...createIntakeOps(intakePipeline),
1413
-
1414
- // ─── Prompt Templates ─────────────────────────────────────────
1415
- {
1416
- name: 'render_prompt',
1417
- description:
1418
- 'Render a prompt template with variable substitution. Templates are .prompt files loaded from the templates directory.',
1419
- auth: 'read' as const,
1420
- schema: z.object({
1421
- template: z.string().describe('Template name (without .prompt extension)'),
1422
- variables: z.record(z.string()).optional().default({}),
1423
- strict: z.boolean().optional().default(true),
1424
- }),
1425
- handler: async (params) => {
1426
- const rendered = runtime.templateManager.render(
1427
- params.template as string,
1428
- (params.variables ?? {}) as Record<string, string>,
1429
- { strict: params.strict as boolean },
1430
- );
1431
- return { rendered };
1432
- },
1433
- },
1434
- {
1435
- name: 'list_templates',
1436
- description: 'List all loaded prompt templates.',
1437
- auth: 'read' as const,
1438
- handler: async () => ({
1439
- templates: runtime.templateManager.listTemplates(),
1440
- }),
1441
- },
1442
- ];
1443
- }