akbo-cli 1.9.4 → 2.0.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.
package/dist/index.d.ts CHANGED
@@ -13,5 +13,8 @@ export { SchemaGenerator } from './schema_generator.js';
13
13
  export { InitService, type InitOptions, type InitResult } from './init_service.js';
14
14
  export { CodebaseWatcher, type WatchOptions } from './watcher.js';
15
15
  export { KnowledgePoolResolver, type PoolConfig, type ResolveOptions } from './pool_resolver.js';
16
+ export { CatalogStore, type UpsertUnitsOptions, type UpsertResult, type GetUnitResult, type DeleteUnitResult } from './catalog_store.js';
17
+ export { DreamEngine, type DreamOptions, type DreamResult } from './dream_engine.js';
18
+ export { GuardService, type GuardEvaluationResult, type GuardViolation, type CheckStagedResult } from './guard_service.js';
16
19
  export { VERSION, getVersion } from './version.js';
17
20
  export * from './extractors/index.js';
package/dist/index.js CHANGED
@@ -13,5 +13,8 @@ export { SchemaGenerator } from './schema_generator.js';
13
13
  export { InitService } from './init_service.js';
14
14
  export { CodebaseWatcher } from './watcher.js';
15
15
  export { KnowledgePoolResolver } from './pool_resolver.js';
16
+ export { CatalogStore } from './catalog_store.js';
17
+ export { DreamEngine } from './dream_engine.js';
18
+ export { GuardService } from './guard_service.js';
16
19
  export { VERSION, getVersion } from './version.js';
17
20
  export * from './extractors/index.js';
@@ -3,6 +3,7 @@ import { StdioServerTransport } from '@modelcontextprotocol/sdk/server/stdio.js'
3
3
  import { z } from 'zod';
4
4
  import path from 'node:path';
5
5
  import fs from 'node:fs';
6
+ import vm from 'node:vm';
6
7
  import { Harvester } from './harvester.js';
7
8
  import { GraphBuilder } from './graph_builder.js';
8
9
  import { KnowledgeValidator } from './validator.js';
@@ -10,6 +11,8 @@ import { QueryService } from './query_service.js';
10
11
  import { SkillImporter } from './importers/skill_importer.js';
11
12
  import { KnowledgePoolResolver } from './pool_resolver.js';
12
13
  import { CatalogStore } from './catalog_store.js';
14
+ import { DreamEngine } from './dream_engine.js';
15
+ import { GuardService } from './guard_service.js';
13
16
  import { VERSION } from './version.js';
14
17
  export function createMcpServer(repoRoot = process.cwd(), poolDirOrConfig) {
15
18
  const root = path.resolve(repoRoot);
@@ -420,6 +423,217 @@ export function createMcpServer(repoRoot = process.cwd(), poolDirOrConfig) {
420
423
  };
421
424
  });
422
425
  }
426
+ // Tool 8b: akbo_filter (In-Memory Sandboxed Graph Projection & Filtering)
427
+ if (!disabledTools.has('akbo_filter')) {
428
+ server.tool('akbo_filter', 'Execute a fast, in-memory sandboxed JavaScript projection or filter against CKG nodes, edges, or invariants without flooding the context window', {
429
+ target: z.enum(['nodes', 'edges', 'invariants']).describe('Dataset to filter: nodes, edges, or invariants'),
430
+ predicate: z.string().describe('JavaScript predicate expression evaluated per item (variable is item, n, e, or inv), e.g. "n.type === \'endpoint\' && n.domain === \'billing\'"'),
431
+ fields: z.array(z.string()).optional().describe('Optional list of properties to project in the output, e.g. ["id", "label", "file"]'),
432
+ limit: z.number().optional().default(50).describe('Maximum items to return (default: 50, max: 500)'),
433
+ dir: z.string().optional().describe('Codebase directory (default: workspace root)'),
434
+ pool: z.string().optional().describe('External knowledge base pool directory')
435
+ }, async ({ target, predicate, fields, limit = 50, dir, pool }) => {
436
+ const targetDir = path.resolve(dir || root);
437
+ const scanError = checkScanAllowed(targetDir);
438
+ if (scanError) {
439
+ return { content: [{ type: 'text', text: scanError }], isError: true };
440
+ }
441
+ const poolConfig = KnowledgePoolResolver.resolve(targetDir, { explicitPoolDir: pool });
442
+ let dataset = [];
443
+ if (target === 'invariants') {
444
+ const graphBuilder = new GraphBuilder(targetDir, poolConfig.poolDir);
445
+ dataset = graphBuilder.loadKnowledgeUnits();
446
+ }
447
+ else {
448
+ const harvester = new Harvester(targetDir, undefined, poolConfig.poolDir);
449
+ const skeleton = await harvester.harvest({ useCache: true });
450
+ const graphBuilder = new GraphBuilder(targetDir, poolConfig.poolDir);
451
+ const graph = await graphBuilder.buildGraph(skeleton, undefined, { useCache: true });
452
+ dataset = target === 'nodes' ? graph.nodes : graph.edges;
453
+ }
454
+ const safeLimit = Math.min(Math.max(1, limit), 500);
455
+ const cleanPred = predicate.trim();
456
+ const fnCode = cleanPred.startsWith('(') || cleanPred.startsWith('function')
457
+ ? `(${cleanPred})`
458
+ : `(function(item) { var n = item, e = item, inv = item; return Boolean(${cleanPred}); })`;
459
+ let filterFn;
460
+ try {
461
+ const sandbox = Object.create(null);
462
+ const script = new vm.Script(fnCode);
463
+ filterFn = script.runInNewContext(sandbox, { timeout: 200 });
464
+ }
465
+ catch (err) {
466
+ return {
467
+ content: [{ type: 'text', text: `Invalid filter predicate: ${err.message}` }],
468
+ isError: true
469
+ };
470
+ }
471
+ const matches = [];
472
+ let totalMatched = 0;
473
+ for (const item of dataset) {
474
+ let matched = false;
475
+ try {
476
+ matched = Boolean(filterFn(item));
477
+ }
478
+ catch {
479
+ matched = false;
480
+ }
481
+ if (matched) {
482
+ totalMatched++;
483
+ if (matches.length < safeLimit) {
484
+ if (fields && fields.length > 0) {
485
+ const projected = {};
486
+ for (const f of fields) {
487
+ if (item[f] !== undefined) {
488
+ projected[f] = item[f];
489
+ }
490
+ }
491
+ matches.push(projected);
492
+ }
493
+ else {
494
+ matches.push(item);
495
+ }
496
+ }
497
+ }
498
+ }
499
+ const payload = {
500
+ target,
501
+ totalDatasetSize: dataset.length,
502
+ totalMatched,
503
+ returnedCount: matches.length,
504
+ truncated: totalMatched > matches.length,
505
+ results: matches
506
+ };
507
+ return {
508
+ content: [
509
+ {
510
+ type: 'text',
511
+ text: JSON.stringify(payload, null, 2)
512
+ }
513
+ ]
514
+ };
515
+ });
516
+ }
517
+ // Tool 8c: akbo_record_observation (Runtime Observation Logging for Compounding Memory)
518
+ if (!disabledTools.has('akbo_record_observation')) {
519
+ server.tool('akbo_record_observation', 'Record an ephemeral runtime finding, bug workaround, or convention discovered during task execution for offline consolidation ("Dreaming")', {
520
+ topic: z.string().describe('Target subsystem, endpoint, file, or library'),
521
+ finding: z.string().describe('The discovered insight, trap, or bug workaround'),
522
+ reproducible_fix: z.string().optional().describe('Actionable do/dont solution or pattern to adhere to'),
523
+ associated_files: z.array(z.string()).optional().describe('Relevant file paths involved in this finding'),
524
+ agent_id: z.string().optional().describe('Identifier or role of the reporting agent (e.g. "gemini-refactor", "claude-debugger")'),
525
+ dir: z.string().optional().describe('Codebase directory (default: workspace root)'),
526
+ pool: z.string().optional().describe('External knowledge base pool directory')
527
+ }, async ({ topic, finding, reproducible_fix, associated_files, agent_id, dir, pool }) => {
528
+ const targetDir = path.resolve(dir || root);
529
+ const obs = CatalogStore.recordObservation({
530
+ targetDir,
531
+ poolDir: pool,
532
+ agentId: agent_id,
533
+ topic,
534
+ finding,
535
+ reproducible_fix,
536
+ associated_files
537
+ });
538
+ return {
539
+ content: [
540
+ {
541
+ type: 'text',
542
+ text: `Observation recorded successfully [ID: ${obs.id}] in session "${obs.agentId}". It will be consolidated during offline dreaming.`
543
+ }
544
+ ]
545
+ };
546
+ });
547
+ }
548
+ // Tool 8d: akbo_scratchpad (Multi-Agent Isolated Session Scratchpad)
549
+ if (!disabledTools.has('akbo_scratchpad')) {
550
+ server.tool('akbo_scratchpad', 'Read or write an isolated session scratchpad (.akb/sessions/<agent_id>/scratchpad.md) to store working notes without write collisions or long-term repo pollution', {
551
+ action: z.enum(['get', 'set', 'append']).describe('Action: get current notes, set/overwrite, or append notes'),
552
+ content: z.string().optional().describe('Markdown content to set or append'),
553
+ agent_id: z.string().optional().describe('Identifier or role of the agent (default: "default")'),
554
+ dir: z.string().optional().describe('Codebase directory (default: workspace root)'),
555
+ pool: z.string().optional().describe('External knowledge base pool directory')
556
+ }, async ({ action, content, agent_id, dir, pool }) => {
557
+ const targetDir = path.resolve(dir || root);
558
+ if (action === 'get') {
559
+ const notes = CatalogStore.getScratchpad({ targetDir, poolDir: pool, agentId: agent_id });
560
+ return {
561
+ content: [{ type: 'text', text: notes || '(Scratchpad is empty)' }]
562
+ };
563
+ }
564
+ else {
565
+ if (!content) {
566
+ return { content: [{ type: 'text', text: 'Error: content is required for set/append actions' }], isError: true };
567
+ }
568
+ const updated = CatalogStore.updateScratchpad({
569
+ targetDir,
570
+ poolDir: pool,
571
+ agentId: agent_id,
572
+ content,
573
+ append: action === 'append'
574
+ });
575
+ return {
576
+ content: [{ type: 'text', text: `Scratchpad updated for agent "${agent_id || 'default'}". Current length: ${updated.length} chars.` }]
577
+ };
578
+ }
579
+ });
580
+ }
581
+ // Tool 8e: akbo_dream (Run Out-of-Band Memory Consolidation)
582
+ if (!disabledTools.has('akbo_dream')) {
583
+ server.tool('akbo_dream', 'Run out-of-band memory consolidation ("Dreaming") to process session observations and synthesize durable compounding knowledge units or staged proposals', {
584
+ sinceHours: z.number().optional().describe('Filter observations recorded within the last N hours'),
585
+ stageOnly: z.boolean().optional().default(false).describe('If true, stage proposals in .akb/staged/ without directly updating knowledge/index.yaml'),
586
+ dir: z.string().optional().describe('Codebase directory (default: workspace root)'),
587
+ pool: z.string().optional().describe('External knowledge base pool directory')
588
+ }, async ({ sinceHours, stageOnly = false, dir, pool }) => {
589
+ const targetDir = path.resolve(dir || root);
590
+ const scanError = checkScanAllowed(targetDir);
591
+ if (scanError) {
592
+ return { content: [{ type: 'text', text: scanError }], isError: true };
593
+ }
594
+ const dreamEngine = new DreamEngine(targetDir, pool);
595
+ const result = await dreamEngine.dream({
596
+ targetDir,
597
+ poolDir: pool,
598
+ sinceHours,
599
+ stageOnly,
600
+ autoApprove: !stageOnly
601
+ });
602
+ return {
603
+ content: [
604
+ {
605
+ type: 'text',
606
+ text: JSON.stringify(result, null, 2)
607
+ }
608
+ ]
609
+ };
610
+ });
611
+ }
612
+ // Tool 8f: akbo_guard (Active Runtime Guardrail & Invariant Pre-Tool Interceptor)
613
+ if (!disabledTools.has('akbo_guard')) {
614
+ server.tool('akbo_guard', 'Evaluate proposed code changes, snippets, or diffs against active invariants and standards before editing files (pre-tool execution rail)', {
615
+ file: z.string().describe('Target file path to evaluate against active invariants'),
616
+ content: z.string().describe('Proposed code content, new snippet, or diff string'),
617
+ dir: z.string().optional().describe('Codebase directory (default: workspace root)'),
618
+ pool: z.string().optional().describe('External knowledge base pool directory')
619
+ }, async ({ file, content, dir, pool }) => {
620
+ const targetDir = path.resolve(dir || root);
621
+ const scanError = checkScanAllowed(targetDir);
622
+ if (scanError) {
623
+ return { content: [{ type: 'text', text: scanError }], isError: true };
624
+ }
625
+ const guardService = new GuardService(targetDir, pool);
626
+ const evalResult = guardService.evaluate(file, content);
627
+ return {
628
+ content: [
629
+ {
630
+ type: 'text',
631
+ text: JSON.stringify(evalResult, null, 2)
632
+ }
633
+ ]
634
+ };
635
+ });
636
+ }
423
637
  // Tool 9: akbo_upsert_unit (Write or Update Knowledge Unit)
424
638
  if (!disabledTools.has('akbo_upsert_unit')) {
425
639
  server.tool('akbo_upsert_unit', 'Add or update knowledge standards or decisions in the external pool. Supports single unit or batch array, validates schema, writes YAML, and updates index.yaml', {
package/dist/types.d.ts CHANGED
@@ -111,6 +111,15 @@ export declare const StandardKnowledgeUnitSchema: z.ZodObject<{
111
111
  skill_file: z.ZodOptional<z.ZodString>;
112
112
  reference_files: z.ZodOptional<z.ZodArray<z.ZodString>>;
113
113
  workflow_gates: z.ZodOptional<z.ZodArray<z.ZodString>>;
114
+ supersedes: z.ZodOptional<z.ZodString>;
115
+ superseded_by: z.ZodOptional<z.ZodString>;
116
+ valid_from: z.ZodOptional<z.ZodString>;
117
+ deprecated_since: z.ZodOptional<z.ZodString>;
118
+ lifecycle: z.ZodOptional<z.ZodObject<{
119
+ status: z.ZodOptional<z.ZodOptional<z.ZodString>>;
120
+ migration_target: z.ZodOptional<z.ZodOptional<z.ZodString>>;
121
+ notes: z.ZodOptional<z.ZodOptional<z.ZodString>>;
122
+ }, z.core.$strip>>;
114
123
  }, z.core.$strip>;
115
124
  export declare const DecisionKnowledgeUnitSchema: z.ZodObject<{
116
125
  id: z.ZodString;
@@ -140,6 +149,15 @@ export declare const DecisionKnowledgeUnitSchema: z.ZodObject<{
140
149
  skill_file: z.ZodOptional<z.ZodString>;
141
150
  reference_files: z.ZodOptional<z.ZodArray<z.ZodString>>;
142
151
  workflow_gates: z.ZodOptional<z.ZodArray<z.ZodString>>;
152
+ supersedes: z.ZodOptional<z.ZodString>;
153
+ superseded_by: z.ZodOptional<z.ZodString>;
154
+ valid_from: z.ZodOptional<z.ZodString>;
155
+ deprecated_since: z.ZodOptional<z.ZodString>;
156
+ lifecycle: z.ZodOptional<z.ZodObject<{
157
+ status: z.ZodOptional<z.ZodOptional<z.ZodString>>;
158
+ migration_target: z.ZodOptional<z.ZodOptional<z.ZodString>>;
159
+ notes: z.ZodOptional<z.ZodOptional<z.ZodString>>;
160
+ }, z.core.$strip>>;
143
161
  }, z.core.$strip>;
144
162
  export declare const MasterIndexEntrySchema: z.ZodObject<{
145
163
  id: z.ZodString;
@@ -202,9 +220,49 @@ export interface KnowledgeUnitContent {
202
220
  skill_file?: string;
203
221
  reference_files?: string[];
204
222
  workflow_gates?: string[];
223
+ supersedes?: string;
224
+ superseded_by?: string;
225
+ valid_from?: string;
226
+ deprecated_since?: string;
227
+ lifecycle?: {
228
+ status?: string;
229
+ migration_target?: string;
230
+ notes?: string;
231
+ };
232
+ }
233
+ export interface AgentObservation {
234
+ id: string;
235
+ timestamp: string;
236
+ agentId?: string;
237
+ topic: string;
238
+ finding: string;
239
+ reproducible_fix?: string;
240
+ associated_files: string[];
241
+ status?: 'recorded' | 'consolidated' | 'discarded';
242
+ }
243
+ export interface SessionScratchpad {
244
+ agentId: string;
245
+ lastUpdated: string;
246
+ content: string;
247
+ }
248
+ export interface StagedKnowledgeUnitProposal {
249
+ id: string;
250
+ targetUnitId?: string;
251
+ domain: string;
252
+ action: 'create' | 'append_rules' | 'deprecate' | 'record_decision';
253
+ title?: string;
254
+ proposed_rule?: string;
255
+ proposed_do?: string[];
256
+ proposed_dont?: string[];
257
+ proposed_decision?: string;
258
+ reason: string;
259
+ origin_observations?: string[];
260
+ agent_id?: string;
261
+ timestamp: string;
262
+ status: 'staged' | 'approved' | 'rejected';
205
263
  }
206
264
  export type GraphNodeType = 'domain' | 'project' | 'endpoint' | 'message' | 'handler' | 'schema' | 'invariant';
207
- export type GraphEdgeType = 'CONTAINS' | 'EXPOSES' | 'DISPATCHES' | 'HANDLES' | 'PERSISTS' | 'DEPENDS_ON' | 'CONSTRAINS' | 'RELATES_TO' | 'VALIDATES' | 'CONSUMES_EVENT' | 'CALLS_HTTP' | 'CALLS_GRPC' | 'CALLS_RPC' | 'IMPLEMENTS';
265
+ export type GraphEdgeType = 'CONTAINS' | 'EXPOSES' | 'DISPATCHES' | 'HANDLES' | 'PERSISTS' | 'DEPENDS_ON' | 'CONSTRAINS' | 'RELATES_TO' | 'VALIDATES' | 'CONSUMES_EVENT' | 'CALLS_HTTP' | 'CALLS_GRPC' | 'CALLS_RPC' | 'IMPLEMENTS' | 'SUPERSEDES';
208
266
  export interface GraphNode {
209
267
  id: string;
210
268
  type: GraphNodeType;
package/dist/types.js CHANGED
@@ -48,7 +48,16 @@ export const StandardKnowledgeUnitSchema = z.object({
48
48
  related_items: z.array(z.string()).default([]),
49
49
  skill_file: z.string().optional(),
50
50
  reference_files: z.array(z.string()).optional(),
51
- workflow_gates: z.array(z.string()).optional()
51
+ workflow_gates: z.array(z.string()).optional(),
52
+ supersedes: z.string().optional(),
53
+ superseded_by: z.string().optional(),
54
+ valid_from: z.string().optional(),
55
+ deprecated_since: z.string().optional(),
56
+ lifecycle: z.object({
57
+ status: z.string().optional(),
58
+ migration_target: z.string().optional(),
59
+ notes: z.string().optional()
60
+ }).partial().optional()
52
61
  });
53
62
  export const DecisionKnowledgeUnitSchema = z.object({
54
63
  id: z.string().min(1, 'Missing required field "id"'),
@@ -65,7 +74,16 @@ export const DecisionKnowledgeUnitSchema = z.object({
65
74
  related_items: z.array(z.string()).default([]),
66
75
  skill_file: z.string().optional(),
67
76
  reference_files: z.array(z.string()).optional(),
68
- workflow_gates: z.array(z.string()).optional()
77
+ workflow_gates: z.array(z.string()).optional(),
78
+ supersedes: z.string().optional(),
79
+ superseded_by: z.string().optional(),
80
+ valid_from: z.string().optional(),
81
+ deprecated_since: z.string().optional(),
82
+ lifecycle: z.object({
83
+ status: z.string().optional(),
84
+ migration_target: z.string().optional(),
85
+ notes: z.string().optional()
86
+ }).partial().optional()
69
87
  });
70
88
  export const MasterIndexEntrySchema = z.object({
71
89
  id: z.string().min(1, 'Master index entry missing "id"'),
package/dist/version.js CHANGED
@@ -7,10 +7,10 @@ export function getVersion() {
7
7
  try {
8
8
  const pkgPath = new URL('../package.json', import.meta.url);
9
9
  const content = fs.readFileSync(pkgPath, 'utf-8');
10
- return JSON.parse(content).version || '1.9.4';
10
+ return JSON.parse(content).version || '2.0.0';
11
11
  }
12
12
  catch {
13
- return '1.9.4';
13
+ return '2.0.0';
14
14
  }
15
15
  }
16
16
  export const VERSION = getVersion();
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "akbo-cli",
3
- "version": "1.9.4",
4
- "description": "AI-Native Knowledge Base Oracle & Operator (AKBO) - Deterministic AST/Manifest Harvester & Agent Invariant Synthesizer",
3
+ "version": "2.0.0",
4
+ "description": "AI-Native Knowledge Base Oracle & Operator (AKBO) - Deterministic AST Harvester, Agent Memory Consolidation (Dreaming), CKG Engine & Runtime Guardrails",
5
5
  "type": "module",
6
6
  "main": "dist/index.js",
7
7
  "types": "dist/index.d.ts",
@@ -13,7 +13,7 @@
13
13
  "id": {
14
14
  "type": "string",
15
15
  "description": "Unique immutable identifier for this knowledge unit (e.g. ARCH-SYS-001, DEV-TS-001, ADR-001).",
16
- "pattern": "^[A-Z0-9]+(-[A-Z0-9]+)*$"
16
+ "pattern": "^[A-Za-z0-9]+([_-][A-Za-z0-9]+)*$"
17
17
  },
18
18
  "type": {
19
19
  "type": "string",