@kognai/orchestrator-core 0.1.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 (144) hide show
  1. package/README.md +44 -0
  2. package/dist/index.d.ts +63 -0
  3. package/dist/index.js +175 -0
  4. package/dist/lib/aar-middleware.d.ts +6 -0
  5. package/dist/lib/aar-middleware.js +70 -0
  6. package/dist/lib/aar-types.d.ts +34 -0
  7. package/dist/lib/aar-types.js +4 -0
  8. package/dist/lib/acp-engine.d.ts +68 -0
  9. package/dist/lib/acp-engine.js +123 -0
  10. package/dist/lib/acp.d.ts +61 -0
  11. package/dist/lib/acp.js +425 -0
  12. package/dist/lib/agent-registry.d.ts +50 -0
  13. package/dist/lib/agent-registry.js +137 -0
  14. package/dist/lib/anthropic-direct.d.ts +27 -0
  15. package/dist/lib/anthropic-direct.js +109 -0
  16. package/dist/lib/asmr-extractor.d.ts +40 -0
  17. package/dist/lib/asmr-extractor.js +151 -0
  18. package/dist/lib/asmr-retrieval.d.ts +76 -0
  19. package/dist/lib/asmr-retrieval.js +311 -0
  20. package/dist/lib/asmr.d.ts +8 -0
  21. package/dist/lib/asmr.js +24 -0
  22. package/dist/lib/brainx-client.d.ts +72 -0
  23. package/dist/lib/brainx-client.js +200 -0
  24. package/dist/lib/brainx-embed.d.ts +14 -0
  25. package/dist/lib/brainx-embed.js +139 -0
  26. package/dist/lib/brainx-swarm-bridge.d.ts +93 -0
  27. package/dist/lib/brainx-swarm-bridge.js +242 -0
  28. package/dist/lib/byterover-client.d.ts +19 -0
  29. package/dist/lib/byterover-client.js +59 -0
  30. package/dist/lib/ceo-wallet.d.ts +37 -0
  31. package/dist/lib/ceo-wallet.js +176 -0
  32. package/dist/lib/chomsky-gate.d.ts +24 -0
  33. package/dist/lib/chomsky-gate.js +178 -0
  34. package/dist/lib/chomsky-runner.d.ts +29 -0
  35. package/dist/lib/chomsky-runner.js +157 -0
  36. package/dist/lib/citizen-score-contract.d.ts +72 -0
  37. package/dist/lib/citizen-score-contract.js +16 -0
  38. package/dist/lib/citizen-score-registry.d.ts +25 -0
  39. package/dist/lib/citizen-score-registry.js +65 -0
  40. package/dist/lib/citizenship.d.ts +103 -0
  41. package/dist/lib/citizenship.js +272 -0
  42. package/dist/lib/clawrouter-client.d.ts +37 -0
  43. package/dist/lib/clawrouter-client.js +148 -0
  44. package/dist/lib/code-asset-crystalliser.d.ts +41 -0
  45. package/dist/lib/code-asset-crystalliser.js +181 -0
  46. package/dist/lib/code-failure-logger.d.ts +27 -0
  47. package/dist/lib/code-failure-logger.js +42 -0
  48. package/dist/lib/cto-approval-gate.d.ts +45 -0
  49. package/dist/lib/cto-approval-gate.js +478 -0
  50. package/dist/lib/cto-gate-types.d.ts +28 -0
  51. package/dist/lib/cto-gate-types.js +8 -0
  52. package/dist/lib/decomposer-feedback.d.ts +54 -0
  53. package/dist/lib/decomposer-feedback.js +115 -0
  54. package/dist/lib/emotional-safety-gate.d.ts +48 -0
  55. package/dist/lib/emotional-safety-gate.js +97 -0
  56. package/dist/lib/engine-paths.d.ts +13 -0
  57. package/dist/lib/engine-paths.js +32 -0
  58. package/dist/lib/event-bus-listener.d.ts +8 -0
  59. package/dist/lib/event-bus-listener.js +144 -0
  60. package/dist/lib/event-bus-publisher.d.ts +25 -0
  61. package/dist/lib/event-bus-publisher.js +188 -0
  62. package/dist/lib/event-bus-types.d.ts +73 -0
  63. package/dist/lib/event-bus-types.js +23 -0
  64. package/dist/lib/failure-library.d.ts +178 -0
  65. package/dist/lib/failure-library.js +349 -0
  66. package/dist/lib/ksl/error-log.d.ts +28 -0
  67. package/dist/lib/ksl/error-log.js +43 -0
  68. package/dist/lib/ksl/index.d.ts +9 -0
  69. package/dist/lib/ksl/index.js +25 -0
  70. package/dist/lib/ksl/orchestrator-tap.d.ts +16 -0
  71. package/dist/lib/ksl/orchestrator-tap.js +85 -0
  72. package/dist/lib/ksl/record-writer.d.ts +46 -0
  73. package/dist/lib/ksl/record-writer.js +45 -0
  74. package/dist/lib/llm-cost-table.d.ts +36 -0
  75. package/dist/lib/llm-cost-table.js +90 -0
  76. package/dist/lib/local-model-router.d.ts +27 -0
  77. package/dist/lib/local-model-router.js +61 -0
  78. package/dist/lib/mc-client.d.ts +51 -0
  79. package/dist/lib/mc-client.js +249 -0
  80. package/dist/lib/model-router-contract.d.ts +91 -0
  81. package/dist/lib/model-router-contract.js +19 -0
  82. package/dist/lib/model-router-registry.d.ts +24 -0
  83. package/dist/lib/model-router-registry.js +52 -0
  84. package/dist/lib/model-router.d.ts +20 -0
  85. package/dist/lib/model-router.js +79 -0
  86. package/dist/lib/monotask-state-machine.d.ts +19 -0
  87. package/dist/lib/monotask-state-machine.js +131 -0
  88. package/dist/lib/neutral-prompt-checker.d.ts +22 -0
  89. package/dist/lib/neutral-prompt-checker.js +130 -0
  90. package/dist/lib/notion-direct.d.ts +92 -0
  91. package/dist/lib/notion-direct.js +381 -0
  92. package/dist/lib/ollama-client.d.ts +37 -0
  93. package/dist/lib/ollama-client.js +158 -0
  94. package/dist/lib/omel/credential-vault.d.ts +57 -0
  95. package/dist/lib/omel/credential-vault.js +324 -0
  96. package/dist/lib/omel/human-brake.d.ts +32 -0
  97. package/dist/lib/omel/human-brake.js +289 -0
  98. package/dist/lib/omel/index.d.ts +10 -0
  99. package/dist/lib/omel/index.js +26 -0
  100. package/dist/lib/omel/phantom-workspace.d.ts +31 -0
  101. package/dist/lib/omel/phantom-workspace.js +256 -0
  102. package/dist/lib/omel/wipe-witness.d.ts +75 -0
  103. package/dist/lib/omel/wipe-witness.js +398 -0
  104. package/dist/lib/orchestrate-engine.d.ts +25 -0
  105. package/dist/lib/orchestrate-engine.js +4436 -0
  106. package/dist/lib/perm-judge.d.ts +46 -0
  107. package/dist/lib/perm-judge.js +173 -0
  108. package/dist/lib/plumber/conformance.d.ts +54 -0
  109. package/dist/lib/plumber/conformance.js +121 -0
  110. package/dist/lib/plumber/index.d.ts +9 -0
  111. package/dist/lib/plumber/index.js +25 -0
  112. package/dist/lib/plumber/observer.d.ts +52 -0
  113. package/dist/lib/plumber/observer.js +180 -0
  114. package/dist/lib/plumber/types.d.ts +78 -0
  115. package/dist/lib/plumber/types.js +29 -0
  116. package/dist/lib/research-impl-gate.d.ts +16 -0
  117. package/dist/lib/research-impl-gate.js +105 -0
  118. package/dist/lib/sherlock-memory.d.ts +29 -0
  119. package/dist/lib/sherlock-memory.js +105 -0
  120. package/dist/lib/skill-crystalliser.d.ts +44 -0
  121. package/dist/lib/skill-crystalliser.js +60 -0
  122. package/dist/lib/sprint-runner-engine.d.ts +27 -0
  123. package/dist/lib/sprint-runner-engine.js +1042 -0
  124. package/dist/lib/sprint-state.d.ts +71 -0
  125. package/dist/lib/sprint-state.js +202 -0
  126. package/dist/lib/stuck-handler.d.ts +17 -0
  127. package/dist/lib/stuck-handler.js +249 -0
  128. package/dist/lib/task-contract-checker.d.ts +17 -0
  129. package/dist/lib/task-contract-checker.js +29 -0
  130. package/dist/lib/task-router/index.d.ts +17 -0
  131. package/dist/lib/task-router/index.js +52 -0
  132. package/dist/lib/task-router/router/generate-execution-id.d.ts +10 -0
  133. package/dist/lib/task-router/router/generate-execution-id.js +24 -0
  134. package/dist/lib/task-router/router/resolve-route.d.ts +2 -0
  135. package/dist/lib/task-router/router/resolve-route.js +49 -0
  136. package/dist/lib/task-router/types.d.ts +79 -0
  137. package/dist/lib/task-router/types.js +39 -0
  138. package/dist/lib/token-budget-validator.d.ts +44 -0
  139. package/dist/lib/token-budget-validator.js +84 -0
  140. package/dist/lib/trust-score-updater.d.ts +30 -0
  141. package/dist/lib/trust-score-updater.js +107 -0
  142. package/dist/lib/wallet-state.d.ts +26 -0
  143. package/dist/lib/wallet-state.js +85 -0
  144. package/package.json +27 -0
@@ -0,0 +1,8 @@
1
+ /**
2
+ * ASMR episodic memory cluster (TICKET-215 Wave D) — extract → retrieve +
3
+ * Sherlock supervisor-memory context. Namespaced ('asmr.*') to keep generic
4
+ * names (e.g. RetrievalResult) off the package's flat surface.
5
+ */
6
+ export * from './asmr-extractor';
7
+ export * from './asmr-retrieval';
8
+ export * from './sherlock-memory';
@@ -0,0 +1,24 @@
1
+ "use strict";
2
+ var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
3
+ if (k2 === undefined) k2 = k;
4
+ var desc = Object.getOwnPropertyDescriptor(m, k);
5
+ if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
6
+ desc = { enumerable: true, get: function() { return m[k]; } };
7
+ }
8
+ Object.defineProperty(o, k2, desc);
9
+ }) : (function(o, m, k, k2) {
10
+ if (k2 === undefined) k2 = k;
11
+ o[k2] = m[k];
12
+ }));
13
+ var __exportStar = (this && this.__exportStar) || function(m, exports) {
14
+ for (var p in m) if (p !== "default" && !Object.prototype.hasOwnProperty.call(exports, p)) __createBinding(exports, m, p);
15
+ };
16
+ Object.defineProperty(exports, "__esModule", { value: true });
17
+ /**
18
+ * ASMR episodic memory cluster (TICKET-215 Wave D) — extract → retrieve +
19
+ * Sherlock supervisor-memory context. Namespaced ('asmr.*') to keep generic
20
+ * names (e.g. RetrievalResult) off the package's flat surface.
21
+ */
22
+ __exportStar(require("./asmr-extractor"), exports);
23
+ __exportStar(require("./asmr-retrieval"), exports);
24
+ __exportStar(require("./sherlock-memory"), exports);
@@ -0,0 +1,72 @@
1
+ export type MemoryType = 'fact' | 'procedure' | 'episode' | 'preference' | 'error' | 'success' | 'reflection' | 'skill_rental_gotcha' | 'skill_rental_learning';
2
+ export type MemoryTier = 'HOT' | 'WARM' | 'COLD' | 'ARCHIVE' | 'RENTAL_EXPIRED';
3
+ export interface BrainXMemory {
4
+ id: string;
5
+ agent_id: string;
6
+ sprint?: string;
7
+ content: string;
8
+ summary?: string;
9
+ embedding: number[];
10
+ memory_type: MemoryType;
11
+ tier: MemoryTier;
12
+ importance: number;
13
+ tags: string[];
14
+ access_count: number;
15
+ last_accessed_at?: Date;
16
+ created_at: Date;
17
+ rental_id?: string;
18
+ skill_id?: string;
19
+ rental_swarm_id?: string;
20
+ rental_expires_at?: Date;
21
+ propagated_from?: string;
22
+ is_rental_expired: boolean;
23
+ feedback_included: boolean;
24
+ anonymised_content?: string;
25
+ }
26
+ export interface StoreOptions {
27
+ sprint?: string;
28
+ memory_type?: MemoryType;
29
+ importance?: number;
30
+ tags?: string[];
31
+ rental_id?: string;
32
+ skill_id?: string;
33
+ rental_swarm_id?: string;
34
+ rental_expires_at?: Date;
35
+ }
36
+ export interface RetrieveOptions {
37
+ topK?: number;
38
+ minImportance?: number;
39
+ tiers?: MemoryTier[];
40
+ sprint?: string;
41
+ excludeExpired?: boolean;
42
+ }
43
+ export declare class BrainXClient {
44
+ private agentId;
45
+ private pg;
46
+ constructor(agentId: string);
47
+ /**
48
+ * Lazily initialise pg pool. Requires pg to be installed.
49
+ * Falls back gracefully if DATABASE_URL / PG* env vars are missing.
50
+ */
51
+ private getPool;
52
+ /**
53
+ * Store a memory. Generates embedding automatically.
54
+ * Returns the new memory ID, or null if DB unavailable.
55
+ */
56
+ store(content: string, opts?: StoreOptions): Promise<string | null>;
57
+ /**
58
+ * Retrieve memories by semantic similarity to a query.
59
+ * Uses pgvector cosine distance for native GPU-accelerated search.
60
+ */
61
+ retrieve(query: string, opts?: RetrieveOptions): Promise<BrainXMemory[]>;
62
+ /**
63
+ * Promote a memory's access_count and last_accessed_at on retrieval.
64
+ */
65
+ touch(id: string): Promise<void>;
66
+ /**
67
+ * Inject HOT-tier memories as context prefix for the agent's next prompt.
68
+ * Returns formatted text block, empty string if no HOT memories.
69
+ */
70
+ injectContext(sprintHint?: string): Promise<string>;
71
+ close(): Promise<void>;
72
+ }
@@ -0,0 +1,200 @@
1
+ "use strict";
2
+ // BrainX memory client — AMD-02 Addendum (P0-MEM2)
3
+ // Wraps PostgreSQL + pgvector for episodic memory store/retrieve.
4
+ // Requires: npm install pg @types/pg
5
+ // Requires: PostgreSQL + pgvector running locally (see brainx-schema.sql)
6
+ var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
7
+ if (k2 === undefined) k2 = k;
8
+ var desc = Object.getOwnPropertyDescriptor(m, k);
9
+ if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
10
+ desc = { enumerable: true, get: function() { return m[k]; } };
11
+ }
12
+ Object.defineProperty(o, k2, desc);
13
+ }) : (function(o, m, k, k2) {
14
+ if (k2 === undefined) k2 = k;
15
+ o[k2] = m[k];
16
+ }));
17
+ var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
18
+ Object.defineProperty(o, "default", { enumerable: true, value: v });
19
+ }) : function(o, v) {
20
+ o["default"] = v;
21
+ });
22
+ var __importStar = (this && this.__importStar) || (function () {
23
+ var ownKeys = function(o) {
24
+ ownKeys = Object.getOwnPropertyNames || function (o) {
25
+ var ar = [];
26
+ for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k;
27
+ return ar;
28
+ };
29
+ return ownKeys(o);
30
+ };
31
+ return function (mod) {
32
+ if (mod && mod.__esModule) return mod;
33
+ var result = {};
34
+ if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]);
35
+ __setModuleDefault(result, mod);
36
+ return result;
37
+ };
38
+ })();
39
+ Object.defineProperty(exports, "__esModule", { value: true });
40
+ exports.BrainXClient = void 0;
41
+ const brainx_embed_1 = require("./brainx-embed");
42
+ // ── Client ───────────────────────────────────────────────────────────────────
43
+ class BrainXClient {
44
+ agentId;
45
+ pg = null;
46
+ constructor(agentId) {
47
+ this.agentId = agentId;
48
+ }
49
+ /**
50
+ * Lazily initialise pg pool. Requires pg to be installed.
51
+ * Falls back gracefully if DATABASE_URL / PG* env vars are missing.
52
+ */
53
+ async getPool() {
54
+ if (this.pg)
55
+ return this.pg;
56
+ if (!process.env.DATABASE_URL && !process.env.PGHOST) {
57
+ process.stderr.write('[brainx] No DB config — memory ops are no-ops\n');
58
+ return null;
59
+ }
60
+ try {
61
+ const { Pool } = await Promise.resolve().then(() => __importStar(require('pg')));
62
+ this.pg = new Pool({
63
+ connectionString: process.env.DATABASE_URL,
64
+ max: 5,
65
+ idleTimeoutMillis: 30000,
66
+ });
67
+ return this.pg;
68
+ }
69
+ catch {
70
+ process.stderr.write('[brainx] pg not installed — run: npm install pg\n');
71
+ return null;
72
+ }
73
+ }
74
+ /**
75
+ * Store a memory. Generates embedding automatically.
76
+ * Returns the new memory ID, or null if DB unavailable.
77
+ */
78
+ async store(content, opts = {}) {
79
+ const pool = await this.getPool();
80
+ if (!pool)
81
+ return null;
82
+ const vec = await (0, brainx_embed_1.embed)(content);
83
+ const sql = `
84
+ INSERT INTO brainx_memories
85
+ (agent_id, sprint, content, embedding, memory_type, importance, tags,
86
+ rental_id, skill_id, rental_swarm_id, rental_expires_at)
87
+ VALUES ($1,$2,$3,$4::vector,$5,$6,$7,$8,$9,$10,$11)
88
+ RETURNING id
89
+ `;
90
+ const vals = [
91
+ this.agentId,
92
+ opts.sprint ?? null,
93
+ content,
94
+ `[${vec.join(',')}]`,
95
+ opts.memory_type ?? 'episode',
96
+ opts.importance ?? 5,
97
+ opts.tags ?? [],
98
+ opts.rental_id ?? null,
99
+ opts.skill_id ?? null,
100
+ opts.rental_swarm_id ?? null,
101
+ opts.rental_expires_at ?? null,
102
+ ];
103
+ const res = await pool.query(sql, vals);
104
+ return res.rows[0].id;
105
+ }
106
+ /**
107
+ * Retrieve memories by semantic similarity to a query.
108
+ * Uses pgvector cosine distance for native GPU-accelerated search.
109
+ */
110
+ async retrieve(query, opts = {}) {
111
+ const pool = await this.getPool();
112
+ if (!pool)
113
+ return [];
114
+ const topK = opts.topK ?? 5;
115
+ const minImp = opts.minImportance ?? 1;
116
+ const tiers = opts.tiers ?? ['HOT', 'WARM', 'COLD'];
117
+ const excludeExpired = opts.excludeExpired ?? true;
118
+ const vec = await (0, brainx_embed_1.embed)(query);
119
+ const sql = `
120
+ SELECT *, 1 - (embedding <=> $1::vector) AS similarity
121
+ FROM brainx_memories
122
+ WHERE agent_id = $2
123
+ AND importance >= $3
124
+ AND tier = ANY($4::memory_tier_enum[])
125
+ AND ($5::boolean = FALSE OR is_rental_expired = FALSE)
126
+ AND ($6::text IS NULL OR sprint = $6)
127
+ ORDER BY embedding <=> $1::vector
128
+ LIMIT $7
129
+ `;
130
+ const vals = [
131
+ `[${vec.join(',')}]`,
132
+ this.agentId,
133
+ minImp,
134
+ tiers,
135
+ excludeExpired,
136
+ opts.sprint ?? null,
137
+ topK,
138
+ ];
139
+ const res = await pool.query(sql, vals);
140
+ return res.rows;
141
+ }
142
+ /**
143
+ * Promote a memory's access_count and last_accessed_at on retrieval.
144
+ */
145
+ async touch(id) {
146
+ const pool = await this.getPool();
147
+ if (!pool)
148
+ return;
149
+ await pool.query(`UPDATE brainx_memories
150
+ SET access_count = access_count + 1, last_accessed_at = NOW()
151
+ WHERE id = $1`, [id]);
152
+ }
153
+ /**
154
+ * Inject HOT-tier memories as context prefix for the agent's next prompt.
155
+ * Returns formatted text block, empty string if no HOT memories.
156
+ */
157
+ async injectContext(sprintHint) {
158
+ const pool = await this.getPool();
159
+ if (!pool)
160
+ return '';
161
+ const sql = `
162
+ SELECT content FROM brainx_memories
163
+ WHERE agent_id = $1 AND tier = 'HOT'
164
+ AND ($2::text IS NULL OR sprint = $2)
165
+ ORDER BY importance DESC, created_at DESC
166
+ LIMIT 10
167
+ `;
168
+ const res = await pool.query(sql, [this.agentId, sprintHint ?? null]);
169
+ if (res.rows.length === 0)
170
+ return '';
171
+ const lines = res.rows.map(r => `- ${r.content}`).join('\n');
172
+ return `## Episodic Memory (HOT)\n${lines}\n`;
173
+ }
174
+ async close() {
175
+ if (this.pg) {
176
+ await this.pg.end();
177
+ this.pg = null;
178
+ }
179
+ }
180
+ }
181
+ exports.BrainXClient = BrainXClient;
182
+ // ── Smoke test ───────────────────────────────────────────────────────────────
183
+ if (require.main === module) {
184
+ (async () => {
185
+ const client = new BrainXClient('smoke-test-agent');
186
+ console.log('\n🧠 BrainX Client Smoke Test');
187
+ const id = await client.store('Agents must seek knowledge before acting.', {
188
+ memory_type: 'reflection', importance: 8, tags: ['five-principles'],
189
+ });
190
+ if (id) {
191
+ console.log(`✅ store() → id: ${id}`);
192
+ const results = await client.retrieve('what should agents do before starting?');
193
+ console.log(`✅ retrieve() → ${results.length} results`);
194
+ }
195
+ else {
196
+ console.log('⚠️ DB not configured — graceful no-op confirmed');
197
+ }
198
+ await client.close();
199
+ })();
200
+ }
@@ -0,0 +1,14 @@
1
+ export declare function embed(text: string): Promise<number[]>;
2
+ export declare function cosineSimilarity(a: number[], b: number[]): number;
3
+ export interface EmbeddedItem {
4
+ id: string;
5
+ embedding: number[];
6
+ }
7
+ export interface RankedItem extends EmbeddedItem {
8
+ similarity: number;
9
+ }
10
+ /**
11
+ * Given a query string, rank a list of pre-embedded items by cosine similarity.
12
+ * Returns items sorted descending, optionally limited to topK.
13
+ */
14
+ export declare function rankBySimilarity(query: string, items: EmbeddedItem[], topK?: number): Promise<RankedItem[]>;
@@ -0,0 +1,139 @@
1
+ "use strict";
2
+ // BrainX local embedding adapter — AMD-02 Addendum (P0-MEM1)
3
+ // Replaces OpenAI text-embedding-3-small (1536 dims) with nomic-embed-text via Ollama (768 dims)
4
+ // All embeddings are generated locally on Mac Mini M4 — zero cost, no data leaves the vault.
5
+ var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
6
+ if (k2 === undefined) k2 = k;
7
+ var desc = Object.getOwnPropertyDescriptor(m, k);
8
+ if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
9
+ desc = { enumerable: true, get: function() { return m[k]; } };
10
+ }
11
+ Object.defineProperty(o, k2, desc);
12
+ }) : (function(o, m, k, k2) {
13
+ if (k2 === undefined) k2 = k;
14
+ o[k2] = m[k];
15
+ }));
16
+ var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
17
+ Object.defineProperty(o, "default", { enumerable: true, value: v });
18
+ }) : function(o, v) {
19
+ o["default"] = v;
20
+ });
21
+ var __importStar = (this && this.__importStar) || (function () {
22
+ var ownKeys = function(o) {
23
+ ownKeys = Object.getOwnPropertyNames || function (o) {
24
+ var ar = [];
25
+ for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k;
26
+ return ar;
27
+ };
28
+ return ownKeys(o);
29
+ };
30
+ return function (mod) {
31
+ if (mod && mod.__esModule) return mod;
32
+ var result = {};
33
+ if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]);
34
+ __setModuleDefault(result, mod);
35
+ return result;
36
+ };
37
+ })();
38
+ Object.defineProperty(exports, "__esModule", { value: true });
39
+ exports.embed = embed;
40
+ exports.cosineSimilarity = cosineSimilarity;
41
+ exports.rankBySimilarity = rankBySimilarity;
42
+ const https = __importStar(require("https"));
43
+ const http = __importStar(require("http"));
44
+ const OLLAMA_BASE = process.env.OLLAMA_BASE || 'http://127.0.0.1:11434'; // SEC1: loopback-only default
45
+ const EMBED_MODEL = 'nomic-embed-text';
46
+ const EMBED_DIMS = 768;
47
+ // ── Core embedding ──────────────────────────────────────────────────────────
48
+ async function embed(text) {
49
+ const body = JSON.stringify({ model: EMBED_MODEL, input: text });
50
+ return new Promise((resolve, reject) => {
51
+ const url = new URL(`${OLLAMA_BASE}/api/embed`);
52
+ const mod = url.protocol === 'https:' ? https : http;
53
+ const req = mod.request({
54
+ hostname: url.hostname,
55
+ port: url.port || (url.protocol === 'https:' ? 443 : 80),
56
+ path: url.pathname,
57
+ method: 'POST',
58
+ headers: { 'Content-Type': 'application/json', 'Content-Length': Buffer.byteLength(body) },
59
+ timeout: 10000,
60
+ }, (res) => {
61
+ let data = '';
62
+ res.on('data', (chunk) => (data += chunk));
63
+ res.on('end', () => {
64
+ try {
65
+ const json = JSON.parse(data);
66
+ const vec = json.embeddings?.[0];
67
+ if (!vec || vec.length !== EMBED_DIMS) {
68
+ reject(new Error(`embed: expected ${EMBED_DIMS}-dim vector, got ${vec?.length ?? 'none'}`));
69
+ }
70
+ else {
71
+ resolve(vec);
72
+ }
73
+ }
74
+ catch (e) {
75
+ reject(new Error(`embed: JSON parse error — ${e.message}`));
76
+ }
77
+ });
78
+ });
79
+ req.on('error', reject);
80
+ req.on('timeout', () => { req.destroy(); reject(new Error('embed: Ollama timeout')); });
81
+ req.write(body);
82
+ req.end();
83
+ });
84
+ }
85
+ // ── Math helpers ────────────────────────────────────────────────────────────
86
+ function cosineSimilarity(a, b) {
87
+ if (a.length !== b.length)
88
+ throw new Error('cosineSimilarity: dimension mismatch');
89
+ let dot = 0, normA = 0, normB = 0;
90
+ for (let i = 0; i < a.length; i++) {
91
+ dot += a[i] * b[i];
92
+ normA += a[i] * a[i];
93
+ normB += b[i] * b[i];
94
+ }
95
+ const denom = Math.sqrt(normA) * Math.sqrt(normB);
96
+ return denom === 0 ? 0 : dot / denom;
97
+ }
98
+ /**
99
+ * Given a query string, rank a list of pre-embedded items by cosine similarity.
100
+ * Returns items sorted descending, optionally limited to topK.
101
+ */
102
+ async function rankBySimilarity(query, items, topK = 5) {
103
+ const queryVec = await embed(query);
104
+ return items
105
+ .map(item => ({ ...item, similarity: cosineSimilarity(queryVec, item.embedding) }))
106
+ .sort((a, b) => b.similarity - a.similarity)
107
+ .slice(0, topK);
108
+ }
109
+ // ── Smoke test ──────────────────────────────────────────────────────────────
110
+ if (require.main === module) {
111
+ (async () => {
112
+ console.log(`\n🧠 BrainX Embed Smoke Test`);
113
+ console.log(` Model: ${EMBED_MODEL} (${EMBED_DIMS} dims)`);
114
+ console.log(` Ollama: ${OLLAMA_BASE}\n`);
115
+ try {
116
+ const t0 = Date.now();
117
+ const vec = await embed('The five principles bind every agent in the Kognai swarm.');
118
+ console.log(`✅ embed() — ${vec.length} dims in ${Date.now() - t0}ms`);
119
+ console.log(` First 5 values: [${vec.slice(0, 5).map(v => v.toFixed(4)).join(', ')}...]\n`);
120
+ const items = [
121
+ { id: 'a', embedding: await embed('Seek knowledge before acting') },
122
+ { id: 'b', embedding: await embed('Protect user data and dignity') },
123
+ { id: 'c', embedding: await embed('Benefit others through your output') },
124
+ ];
125
+ const ranked = await rankBySimilarity('what does it mean to act ethically?', items, 3);
126
+ console.log('✅ rankBySimilarity() results:');
127
+ for (const r of ranked) {
128
+ console.log(` [${r.id}] similarity=${r.similarity.toFixed(4)}`);
129
+ }
130
+ console.log('\n✅ PASS — nomic-embed-text local adapter working\n');
131
+ }
132
+ catch (err) {
133
+ console.error('❌ FAIL:', err.message);
134
+ console.error(' Is Ollama running? Is nomic-embed-text pulled?');
135
+ console.error(' Run: ollama pull nomic-embed-text');
136
+ process.exit(1);
137
+ }
138
+ })();
139
+ }
@@ -0,0 +1,93 @@
1
+ /**
2
+ * BrainX Swarm Bridge — Memory Integration for Agent Orchestrator
3
+ *
4
+ * Wires BrainX episodic memory into the swarm orchestrator:
5
+ *
6
+ * 1. Pre-task: inject relevant HOT memories into agent context
7
+ * 2. Post-task: store task outcomes as episodic memories
8
+ * 3. Rental governance: propagate memories within active swarm during rental,
9
+ * expire copies on rental end (originator retains WARM)
10
+ * 4. Distillation: use qwen3:4b to compress verbose memories
11
+ *
12
+ * AMD-02 Addendum — Rental Memory Governance Rule:
13
+ * - During rental period: propagate skill memories to active swarm agents
14
+ * - On rental expiry: originating agent retains memory as WARM tier
15
+ * - Copies held by other agents → RENTAL_EXPIRED tier (queryable but deprioritized)
16
+ * - Anonymised content generated for expired rentals
17
+ *
18
+ * Sprint 652
19
+ */
20
+ import { type MemoryType } from './brainx-client';
21
+ export interface SwarmContext {
22
+ swarm_id: string;
23
+ sprint_id: string;
24
+ agent_ids: string[];
25
+ rental_id?: string;
26
+ rental_expires_at?: Date;
27
+ }
28
+ export interface TaskMemoryInput {
29
+ agent_id: string;
30
+ task_id: string;
31
+ task_title: string;
32
+ outcome: 'success' | 'failure' | 'partial';
33
+ summary: string;
34
+ files_modified: string[];
35
+ score?: number;
36
+ error_message?: string;
37
+ }
38
+ export interface MemoryInjection {
39
+ agent_id: string;
40
+ context_text: string;
41
+ memory_count: number;
42
+ }
43
+ export interface GovernanceResult {
44
+ expired_count: number;
45
+ retained_count: number;
46
+ errors: string[];
47
+ }
48
+ export declare class BrainXSwarmBridge {
49
+ private clients;
50
+ private swarmCtx;
51
+ constructor(ctx: SwarmContext);
52
+ /** Get or create a BrainX client for an agent */
53
+ private getClient;
54
+ /**
55
+ * Inject relevant memories into an agent's context before task execution.
56
+ * Returns formatted text to prepend to the agent's prompt.
57
+ */
58
+ injectMemories(agentId: string): Promise<MemoryInjection>;
59
+ /**
60
+ * Inject memories for all agents in the swarm.
61
+ */
62
+ injectAll(): Promise<MemoryInjection[]>;
63
+ /**
64
+ * Store a task outcome as an episodic memory.
65
+ * Includes distillation for verbose summaries.
66
+ */
67
+ storeTaskMemory(input: TaskMemoryInput): Promise<string | null>;
68
+ /**
69
+ * Propagate a memory to all agents in the active swarm during rental period.
70
+ * Each agent gets a copy with propagated_from set to the originator.
71
+ */
72
+ propagateToSwarm(originatorId: string, content: string, memoryType?: MemoryType, importance?: number): Promise<string[]>;
73
+ /**
74
+ * Execute Rental Memory Governance Rule on rental expiry:
75
+ * - Originating agent: retain as WARM tier
76
+ * - Other agents: move to RENTAL_EXPIRED tier
77
+ * - Generate anonymised content for expired memories
78
+ *
79
+ * Should be called when a rental period ends.
80
+ */
81
+ expireRentalMemories(rentalId: string, originatorId: string): Promise<GovernanceResult>;
82
+ /**
83
+ * Distill verbose memory content using qwen3:4b.
84
+ * Returns compressed version, or null if distillation fails.
85
+ */
86
+ distill(content: string): Promise<string | null>;
87
+ close(): Promise<void>;
88
+ }
89
+ /**
90
+ * Create a BrainX swarm bridge for a sprint execution.
91
+ * Call this at the start of each swarm run.
92
+ */
93
+ export declare function createSwarmBridge(swarmId: string, sprintId: string, agentIds: string[], rentalId?: string, rentalExpiresAt?: Date): BrainXSwarmBridge;