opc-agent 2.1.0 → 3.0.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (144) hide show
  1. package/README.md +603 -545
  2. package/dist/channels/voice.d.ts +59 -0
  3. package/dist/channels/voice.js +351 -1
  4. package/dist/cli.js +172 -1
  5. package/dist/core/agent.d.ts +4 -0
  6. package/dist/core/agent.js +35 -0
  7. package/dist/core/collaboration.d.ts +89 -0
  8. package/dist/core/collaboration.js +201 -0
  9. package/dist/deploy/index.d.ts +40 -0
  10. package/dist/deploy/index.js +261 -0
  11. package/dist/index.d.ts +7 -1
  12. package/dist/index.js +47 -3
  13. package/dist/mcp/servers/calculator-mcp.d.ts +3 -0
  14. package/dist/mcp/servers/calculator-mcp.js +65 -0
  15. package/dist/mcp/servers/crypto-mcp.d.ts +3 -0
  16. package/dist/mcp/servers/crypto-mcp.js +108 -0
  17. package/dist/mcp/servers/database-mcp.d.ts +3 -0
  18. package/dist/mcp/servers/database-mcp.js +73 -0
  19. package/dist/mcp/servers/datetime-mcp.d.ts +3 -0
  20. package/dist/mcp/servers/datetime-mcp.js +71 -0
  21. package/dist/mcp/servers/filesystem.d.ts +3 -0
  22. package/dist/mcp/servers/filesystem.js +101 -0
  23. package/dist/mcp/servers/github-mcp.d.ts +3 -0
  24. package/dist/mcp/servers/github-mcp.js +60 -0
  25. package/dist/mcp/servers/index.d.ts +21 -0
  26. package/dist/mcp/servers/index.js +50 -0
  27. package/dist/mcp/servers/json-mcp.d.ts +3 -0
  28. package/dist/mcp/servers/json-mcp.js +126 -0
  29. package/dist/mcp/servers/memory-mcp.d.ts +3 -0
  30. package/dist/mcp/servers/memory-mcp.js +60 -0
  31. package/dist/mcp/servers/regex-mcp.d.ts +3 -0
  32. package/dist/mcp/servers/regex-mcp.js +56 -0
  33. package/dist/mcp/servers/web-mcp.d.ts +3 -0
  34. package/dist/mcp/servers/web-mcp.js +51 -0
  35. package/dist/schema/oad.d.ts +292 -12
  36. package/dist/schema/oad.js +12 -1
  37. package/dist/security/guardrails.d.ts +50 -0
  38. package/dist/security/guardrails.js +197 -0
  39. package/dist/studio/server.d.ts +31 -1
  40. package/dist/studio/server.js +154 -3
  41. package/dist/studio-ui/index.html +1278 -662
  42. package/dist/tools/integrations/calendar.d.ts +3 -0
  43. package/dist/tools/integrations/calendar.js +73 -0
  44. package/dist/tools/integrations/code-exec.d.ts +3 -0
  45. package/dist/tools/integrations/code-exec.js +42 -0
  46. package/dist/tools/integrations/csv-analyzer.d.ts +3 -0
  47. package/dist/tools/integrations/csv-analyzer.js +142 -0
  48. package/dist/tools/integrations/database.d.ts +3 -0
  49. package/dist/tools/integrations/database.js +44 -0
  50. package/dist/tools/integrations/email-send.d.ts +3 -0
  51. package/dist/tools/integrations/email-send.js +104 -0
  52. package/dist/tools/integrations/git-tool.d.ts +3 -0
  53. package/dist/tools/integrations/git-tool.js +49 -0
  54. package/dist/tools/integrations/github-tool.d.ts +3 -0
  55. package/dist/tools/integrations/github-tool.js +77 -0
  56. package/dist/tools/integrations/image-gen.d.ts +3 -0
  57. package/dist/tools/integrations/image-gen.js +58 -0
  58. package/dist/tools/integrations/index.d.ts +30 -0
  59. package/dist/tools/integrations/index.js +107 -0
  60. package/dist/tools/integrations/jira.d.ts +3 -0
  61. package/dist/tools/integrations/jira.js +85 -0
  62. package/dist/tools/integrations/notion.d.ts +3 -0
  63. package/dist/tools/integrations/notion.js +71 -0
  64. package/dist/tools/integrations/npm-tool.d.ts +3 -0
  65. package/dist/tools/integrations/npm-tool.js +49 -0
  66. package/dist/tools/integrations/pdf-reader.d.ts +3 -0
  67. package/dist/tools/integrations/pdf-reader.js +91 -0
  68. package/dist/tools/integrations/slack.d.ts +3 -0
  69. package/dist/tools/integrations/slack.js +67 -0
  70. package/dist/tools/integrations/summarizer.d.ts +3 -0
  71. package/dist/tools/integrations/summarizer.js +49 -0
  72. package/dist/tools/integrations/translator.d.ts +3 -0
  73. package/dist/tools/integrations/translator.js +48 -0
  74. package/dist/tools/integrations/trello.d.ts +3 -0
  75. package/dist/tools/integrations/trello.js +60 -0
  76. package/dist/tools/integrations/vector-search.d.ts +3 -0
  77. package/dist/tools/integrations/vector-search.js +44 -0
  78. package/dist/tools/integrations/web-scraper.d.ts +3 -0
  79. package/dist/tools/integrations/web-scraper.js +48 -0
  80. package/dist/tools/integrations/web-search.d.ts +3 -0
  81. package/dist/tools/integrations/web-search.js +60 -0
  82. package/dist/tools/integrations/webhook.d.ts +3 -0
  83. package/dist/tools/integrations/webhook.js +39 -0
  84. package/dist/ui/components.d.ts +10 -0
  85. package/dist/ui/components.js +123 -0
  86. package/package.json +3 -3
  87. package/src/channels/voice.ts +365 -0
  88. package/src/cli.ts +176 -2
  89. package/src/core/agent.ts +38 -0
  90. package/src/core/collaboration.ts +275 -0
  91. package/src/deploy/index.ts +255 -0
  92. package/src/index.ts +21 -1
  93. package/src/mcp/servers/calculator-mcp.ts +65 -0
  94. package/src/mcp/servers/crypto-mcp.ts +73 -0
  95. package/src/mcp/servers/database-mcp.ts +72 -0
  96. package/src/mcp/servers/datetime-mcp.ts +69 -0
  97. package/src/mcp/servers/filesystem.ts +66 -0
  98. package/src/mcp/servers/github-mcp.ts +58 -0
  99. package/src/mcp/servers/index.ts +63 -0
  100. package/src/mcp/servers/json-mcp.ts +102 -0
  101. package/src/mcp/servers/memory-mcp.ts +56 -0
  102. package/src/mcp/servers/regex-mcp.ts +53 -0
  103. package/src/mcp/servers/web-mcp.ts +49 -0
  104. package/src/schema/oad.ts +13 -0
  105. package/src/security/guardrails.ts +248 -0
  106. package/src/studio/server.ts +166 -4
  107. package/src/studio-ui/index.html +1278 -662
  108. package/src/tools/integrations/calendar.ts +73 -0
  109. package/src/tools/integrations/code-exec.ts +39 -0
  110. package/src/tools/integrations/csv-analyzer.ts +92 -0
  111. package/src/tools/integrations/database.ts +44 -0
  112. package/src/tools/integrations/email-send.ts +76 -0
  113. package/src/tools/integrations/git-tool.ts +42 -0
  114. package/src/tools/integrations/github-tool.ts +76 -0
  115. package/src/tools/integrations/image-gen.ts +56 -0
  116. package/src/tools/integrations/index.ts +92 -0
  117. package/src/tools/integrations/jira.ts +83 -0
  118. package/src/tools/integrations/notion.ts +71 -0
  119. package/src/tools/integrations/npm-tool.ts +48 -0
  120. package/src/tools/integrations/pdf-reader.ts +58 -0
  121. package/src/tools/integrations/slack.ts +65 -0
  122. package/src/tools/integrations/summarizer.ts +49 -0
  123. package/src/tools/integrations/translator.ts +48 -0
  124. package/src/tools/integrations/trello.ts +60 -0
  125. package/src/tools/integrations/vector-search.ts +42 -0
  126. package/src/tools/integrations/web-scraper.ts +47 -0
  127. package/src/tools/integrations/web-search.ts +58 -0
  128. package/src/tools/integrations/webhook.ts +38 -0
  129. package/src/ui/components.ts +127 -0
  130. package/tests/brain-seed-extended.test.ts +490 -0
  131. package/tests/collaboration.test.ts +319 -0
  132. package/tests/deploy-and-dag.test.ts +196 -0
  133. package/tests/guardrails.test.ts +177 -0
  134. package/tests/integrations.test.ts +249 -0
  135. package/tests/mcp-servers.test.ts +260 -0
  136. package/tests/voice-enhanced.test.ts +169 -0
  137. package/dist/dtv/data.d.ts +0 -18
  138. package/dist/dtv/data.js +0 -25
  139. package/dist/dtv/trust.d.ts +0 -19
  140. package/dist/dtv/trust.js +0 -40
  141. package/dist/dtv/value.d.ts +0 -23
  142. package/dist/dtv/value.js +0 -38
  143. package/dist/marketplace/index.d.ts +0 -34
  144. package/dist/marketplace/index.js +0 -202
@@ -0,0 +1,38 @@
1
+ import type { MCPTool, MCPToolResult } from '../mcp';
2
+
3
+ export const WebhookTool: MCPTool = {
4
+ name: 'webhook',
5
+ description: 'Send HTTP requests to arbitrary webhook URLs. Supports POST and GET.',
6
+ inputSchema: {
7
+ type: 'object',
8
+ properties: {
9
+ url: { type: 'string', description: 'Webhook URL' },
10
+ method: { type: 'string', enum: ['GET', 'POST', 'PUT', 'PATCH', 'DELETE'], description: 'HTTP method (default: POST)' },
11
+ headers: { type: 'object', description: 'Custom headers as key-value pairs' },
12
+ body: { type: 'string', description: 'Request body (JSON string)' },
13
+ },
14
+ required: ['url'],
15
+ },
16
+
17
+ async execute(input: Record<string, unknown>): Promise<MCPToolResult> {
18
+ const url = String(input.url ?? '');
19
+ if (!url) return { content: 'Error: url is required', isError: true };
20
+
21
+ const method = String(input.method ?? 'POST').toUpperCase();
22
+ const customHeaders = (input.headers ?? {}) as Record<string, string>;
23
+ const headers: Record<string, string> = { 'Content-Type': 'application/json', ...customHeaders };
24
+
25
+ try {
26
+ const opts: RequestInit = { method, headers };
27
+ if (method !== 'GET' && method !== 'HEAD' && input.body) {
28
+ opts.body = String(input.body);
29
+ }
30
+ const res = await fetch(url, opts);
31
+ const text = await res.text();
32
+ const truncated = text.length > 4000 ? text.slice(0, 4000) + '...(truncated)' : text;
33
+ return { content: `Status: ${res.status}\n${truncated}`, metadata: { status: res.status } };
34
+ } catch (err) {
35
+ return { content: `Webhook error: ${(err as Error).message}`, isError: true };
36
+ }
37
+ },
38
+ };
@@ -0,0 +1,127 @@
1
+ /**
2
+ * Chat Widget — self-contained HTML+CSS+JS for embedding
3
+ */
4
+
5
+ export interface ChatWidgetConfig {
6
+ endpoint: string;
7
+ theme?: 'dark' | 'light';
8
+ title?: string;
9
+ }
10
+
11
+ export function generateChatWidget(config: ChatWidgetConfig): string {
12
+ const { endpoint, theme = 'dark', title = 'OPC Chat' } = config;
13
+ const isDark = theme === 'dark';
14
+ const bg = isDark ? '#1a1a2e' : '#ffffff';
15
+ const fg = isDark ? '#e0e0e0' : '#1a1a2e';
16
+ const inputBg = isDark ? '#16213e' : '#f0f0f0';
17
+ const msgUser = isDark ? '#0f3460' : '#e3f2fd';
18
+ const msgBot = isDark ? '#1a1a2e' : '#f5f5f5';
19
+ const accent = '#00d2ff';
20
+
21
+ return `<!DOCTYPE html>
22
+ <html lang="en">
23
+ <head>
24
+ <meta charset="UTF-8">
25
+ <meta name="viewport" content="width=device-width, initial-scale=1.0">
26
+ <title>${title}</title>
27
+ <style>
28
+ * { margin: 0; padding: 0; box-sizing: border-box; }
29
+ body { font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', sans-serif; background: ${bg}; color: ${fg}; height: 100vh; display: flex; flex-direction: column; }
30
+ .chat-header { padding: 16px 20px; background: ${isDark ? '#16213e' : '#fafafa'}; border-bottom: 1px solid ${isDark ? '#2a2a4a' : '#e0e0e0'}; font-weight: 600; font-size: 16px; display: flex; align-items: center; gap: 8px; }
31
+ .chat-header::before { content: '💬'; }
32
+ .chat-messages { flex: 1; overflow-y: auto; padding: 16px; display: flex; flex-direction: column; gap: 12px; }
33
+ .msg { max-width: 80%; padding: 10px 14px; border-radius: 12px; line-height: 1.5; font-size: 14px; white-space: pre-wrap; word-wrap: break-word; }
34
+ .msg.user { align-self: flex-end; background: ${msgUser}; border-bottom-right-radius: 4px; }
35
+ .msg.assistant { align-self: flex-start; background: ${msgBot}; border: 1px solid ${isDark ? '#2a2a4a' : '#e0e0e0'}; border-bottom-left-radius: 4px; }
36
+ .msg.streaming::after { content: '▊'; animation: blink 0.7s infinite; }
37
+ @keyframes blink { 50% { opacity: 0; } }
38
+ .chat-input { display: flex; gap: 8px; padding: 12px 16px; border-top: 1px solid ${isDark ? '#2a2a4a' : '#e0e0e0'}; background: ${isDark ? '#16213e' : '#fafafa'}; }
39
+ .chat-input textarea { flex: 1; resize: none; border: 1px solid ${isDark ? '#2a2a4a' : '#ccc'}; border-radius: 8px; padding: 10px; font-size: 14px; background: ${inputBg}; color: ${fg}; outline: none; font-family: inherit; min-height: 42px; max-height: 120px; }
40
+ .chat-input textarea:focus { border-color: ${accent}; }
41
+ .chat-input button { background: ${accent}; color: #000; border: none; border-radius: 8px; padding: 0 20px; cursor: pointer; font-weight: 600; font-size: 14px; }
42
+ .chat-input button:hover { opacity: 0.85; }
43
+ .chat-input button:disabled { opacity: 0.4; cursor: not-allowed; }
44
+ </style>
45
+ </head>
46
+ <body>
47
+ <div class="chat-header">${title}</div>
48
+ <div class="chat-messages" id="messages"></div>
49
+ <div class="chat-input">
50
+ <textarea id="input" rows="1" placeholder="Type a message..." onkeydown="if(event.key==='Enter'&&!event.shiftKey){event.preventDefault();sendMessage()}"></textarea>
51
+ <button id="sendBtn" onclick="sendMessage()">Send</button>
52
+ </div>
53
+ <script>
54
+ const ENDPOINT = ${JSON.stringify(endpoint)};
55
+ const messages = [];
56
+ const $msgs = document.getElementById('messages');
57
+ const $input = document.getElementById('input');
58
+ const $btn = document.getElementById('sendBtn');
59
+
60
+ function addMsg(role, text) {
61
+ const div = document.createElement('div');
62
+ div.className = 'msg ' + role;
63
+ div.textContent = text;
64
+ $msgs.appendChild(div);
65
+ $msgs.scrollTop = $msgs.scrollHeight;
66
+ return div;
67
+ }
68
+
69
+ async function sendMessage() {
70
+ const text = $input.value.trim();
71
+ if (!text) return;
72
+ $input.value = '';
73
+ $btn.disabled = true;
74
+ messages.push({ role: 'user', content: text });
75
+ addMsg('user', text);
76
+
77
+ const div = addMsg('assistant', '');
78
+ div.classList.add('streaming');
79
+ let full = '';
80
+
81
+ try {
82
+ const res = await fetch(ENDPOINT, {
83
+ method: 'POST',
84
+ headers: { 'Content-Type': 'application/json' },
85
+ body: JSON.stringify({ messages }),
86
+ });
87
+
88
+ if (res.headers.get('content-type')?.includes('text/event-stream')) {
89
+ const reader = res.body.getReader();
90
+ const decoder = new TextDecoder();
91
+ let buf = '';
92
+ while (true) {
93
+ const { done, value } = await reader.read();
94
+ if (done) break;
95
+ buf += decoder.decode(value, { stream: true });
96
+ const lines = buf.split('\\n');
97
+ buf = lines.pop() || '';
98
+ for (const line of lines) {
99
+ if (line.startsWith('data: ')) {
100
+ const data = line.slice(6);
101
+ if (data === '[DONE]') break;
102
+ try { const j = JSON.parse(data); full += j.content || j.delta || ''; div.textContent = full; } catch {}
103
+ }
104
+ }
105
+ $msgs.scrollTop = $msgs.scrollHeight;
106
+ }
107
+ } else {
108
+ const data = await res.json();
109
+ full = data.content || data.message || JSON.stringify(data);
110
+ div.textContent = full;
111
+ }
112
+ } catch (e) {
113
+ full = 'Error: ' + e.message;
114
+ div.textContent = full;
115
+ }
116
+
117
+ div.classList.remove('streaming');
118
+ messages.push({ role: 'assistant', content: full });
119
+ $btn.disabled = false;
120
+ $input.focus();
121
+ }
122
+
123
+ $input.focus();
124
+ </script>
125
+ </body>
126
+ </html>`;
127
+ }
@@ -0,0 +1,490 @@
1
+ import { describe, it, expect, beforeEach, afterEach, vi } from 'vitest';
2
+ import * as fs from 'fs';
3
+ import * as path from 'path';
4
+ import * as os from 'os';
5
+ import { BrainSeedLoader, KnowledgeEvolver } from '../src/memory/seed-loader';
6
+ import { BaseAgent } from '../src/core/agent';
7
+
8
+ function makeTmpDir(): string {
9
+ return fs.mkdtempSync(path.join(os.tmpdir(), 'opc-seed-ext-'));
10
+ }
11
+
12
+ // ─── BrainSeedLoader Edge Cases ────────────────────────────────────
13
+
14
+ describe('BrainSeedLoader edge cases', () => {
15
+ let tmpDir: string;
16
+
17
+ beforeEach(() => {
18
+ tmpDir = makeTmpDir();
19
+ fs.mkdirSync(path.join(tmpDir, 'brain-seeds'), { recursive: true });
20
+ });
21
+
22
+ afterEach(() => {
23
+ fs.rmSync(tmpDir, { recursive: true, force: true });
24
+ });
25
+
26
+ it('handles empty seed file gracefully', () => {
27
+ const seedFile = path.join(tmpDir, 'brain-seeds', 'empty.md');
28
+ fs.writeFileSync(seedFile, '');
29
+ const loader = new BrainSeedLoader(tmpDir, { seeds: ['brain-seeds/empty.md'], autoSeed: true });
30
+ const pages = loader.parseSeedFile(seedFile, 'workstation');
31
+ expect(pages).toHaveLength(0);
32
+ });
33
+
34
+ it('handles seed file with only whitespace', () => {
35
+ const seedFile = path.join(tmpDir, 'brain-seeds', 'ws.md');
36
+ fs.writeFileSync(seedFile, ' \n\n \n');
37
+ const loader = new BrainSeedLoader(tmpDir, { seeds: ['brain-seeds/ws.md'], autoSeed: true });
38
+ const pages = loader.parseSeedFile(seedFile, 'workstation');
39
+ expect(pages).toHaveLength(0);
40
+ });
41
+
42
+ it('handles seed file with only H1 header (no ## sections)', () => {
43
+ const seedFile = path.join(tmpDir, 'brain-seeds', 'h1only.md');
44
+ fs.writeFileSync(seedFile, '# Just a Title\n\nSome intro text without any ## sections.\n');
45
+ const loader = new BrainSeedLoader(tmpDir, { seeds: ['brain-seeds/h1only.md'], autoSeed: true });
46
+ const pages = loader.parseSeedFile(seedFile, 'workstation');
47
+ expect(pages).toHaveLength(0);
48
+ });
49
+
50
+ it('handles malformed seed with ## but no title text', () => {
51
+ const seedFile = path.join(tmpDir, 'brain-seeds', 'malformed.md');
52
+ fs.writeFileSync(seedFile, '## \n\nContent without a title.\n');
53
+ const loader = new BrainSeedLoader(tmpDir, { seeds: ['brain-seeds/malformed.md'], autoSeed: true });
54
+ const pages = loader.parseSeedFile(seedFile, 'workstation');
55
+ // Should still produce a page (possibly with empty slug segment)
56
+ expect(pages.length).toBeGreaterThanOrEqual(0);
57
+ });
58
+
59
+ it('handles unicode section titles (Chinese)', () => {
60
+ const seedFile = path.join(tmpDir, 'brain-seeds', 'industry.md');
61
+ fs.writeFileSync(seedFile, '## 电子商务基础\n\n在线零售基础知识。\n\n## 支付系统\n\n支付如何运作。\n');
62
+ const loader = new BrainSeedLoader(tmpDir, { seeds: ['brain-seeds/industry.md'], autoSeed: true });
63
+ const pages = loader.parseSeedFile(seedFile, 'industry');
64
+ expect(pages).toHaveLength(2);
65
+ expect(pages[0].slug).toContain('seed/industry/');
66
+ expect(pages[0].content).toContain('电子商务基础');
67
+ expect(pages[1].content).toContain('支付系统');
68
+ });
69
+
70
+ it('handles unicode section titles (Japanese/Korean)', () => {
71
+ const seedFile = path.join(tmpDir, 'brain-seeds', 'job.md');
72
+ fs.writeFileSync(seedFile, '## カスタマーサポート\n\nお客様対応の基本。\n');
73
+ const loader = new BrainSeedLoader(tmpDir, { seeds: ['brain-seeds/job.md'], autoSeed: true });
74
+ const pages = loader.parseSeedFile(seedFile, 'job');
75
+ expect(pages).toHaveLength(1);
76
+ expect(pages[0].content).toContain('カスタマーサポート');
77
+ });
78
+
79
+ it('handles deeply nested ### subsections within ## sections', () => {
80
+ const seedFile = path.join(tmpDir, 'brain-seeds', 'industry.md');
81
+ fs.writeFileSync(seedFile, `## Main Topic
82
+
83
+ Intro text.
84
+
85
+ ### Subtopic A
86
+
87
+ Detail A.
88
+
89
+ ### Subtopic B
90
+
91
+ Detail B.
92
+
93
+ ## Another Topic
94
+
95
+ More content.
96
+ `);
97
+ const loader = new BrainSeedLoader(tmpDir, { seeds: ['brain-seeds/industry.md'], autoSeed: true });
98
+ const pages = loader.parseSeedFile(seedFile, 'industry');
99
+ expect(pages).toHaveLength(2);
100
+ // Nested ### should be included in the parent ## section's content
101
+ expect(pages[0].content).toContain('Subtopic A');
102
+ expect(pages[0].content).toContain('Subtopic B');
103
+ });
104
+
105
+ it('handles seed file with Windows line endings (CRLF)', () => {
106
+ const seedFile = path.join(tmpDir, 'brain-seeds', 'industry.md');
107
+ fs.writeFileSync(seedFile, '## Topic One\r\n\r\nContent one.\r\n\r\n## Topic Two\r\n\r\nContent two.\r\n');
108
+ const loader = new BrainSeedLoader(tmpDir, { seeds: ['brain-seeds/industry.md'], autoSeed: true });
109
+ const pages = loader.parseSeedFile(seedFile, 'industry');
110
+ expect(pages).toHaveLength(2);
111
+ });
112
+
113
+ it('seedBrain with multiple seed files aggregates all pages', async () => {
114
+ fs.writeFileSync(path.join(tmpDir, 'brain-seeds', 'industry.md'), '## Ind1\n\nContent.\n');
115
+ fs.writeFileSync(path.join(tmpDir, 'brain-seeds', 'job.md'), '## Job1\n\nContent.\n\n## Job2\n\nContent.\n');
116
+
117
+ const learned: any[] = [];
118
+ const mockBrain = { learn: async (_c: string, m: any) => { learned.push(m); } };
119
+
120
+ const loader = new BrainSeedLoader(tmpDir, {
121
+ seeds: ['brain-seeds/industry.md', 'brain-seeds/job.md'],
122
+ autoSeed: true,
123
+ });
124
+ const result = await loader.seedBrain(mockBrain);
125
+ expect(result.imported).toBe(3);
126
+ expect(result.pages).toHaveLength(3);
127
+ });
128
+
129
+ it('seedBrain with null brain does not throw', async () => {
130
+ fs.writeFileSync(path.join(tmpDir, 'brain-seeds', 'industry.md'), '## Topic\n\nContent.\n');
131
+ const loader = new BrainSeedLoader(tmpDir, { seeds: ['brain-seeds/industry.md'], autoSeed: true });
132
+ const result = await loader.seedBrain(null);
133
+ // Pages are parsed but nothing stored since brain is null
134
+ expect(result.imported).toBe(1);
135
+ });
136
+
137
+ it('seedBrain with brain having neither learn nor store still counts pages', async () => {
138
+ fs.writeFileSync(path.join(tmpDir, 'brain-seeds', 'industry.md'), '## Topic\n\nContent.\n');
139
+ const loader = new BrainSeedLoader(tmpDir, { seeds: ['brain-seeds/industry.md'], autoSeed: true });
140
+ const result = await loader.seedBrain({});
141
+ expect(result.imported).toBe(1);
142
+ });
143
+
144
+ it('inferTier defaults to workstation for unknown filenames', () => {
145
+ fs.writeFileSync(path.join(tmpDir, 'brain-seeds', 'custom.md'), '## Custom\n\nContent.\n');
146
+ const loader = new BrainSeedLoader(tmpDir, { seeds: ['brain-seeds/custom.md'], autoSeed: true });
147
+ const pages = loader.parseSeedFile(path.join(tmpDir, 'brain-seeds', 'custom.md'), 'workstation');
148
+ expect(pages[0].tier).toBe('workstation');
149
+ });
150
+
151
+ it('handles very large section content', () => {
152
+ const bigContent = 'x'.repeat(10000);
153
+ const seedFile = path.join(tmpDir, 'brain-seeds', 'industry.md');
154
+ fs.writeFileSync(seedFile, `## Big Section\n\n${bigContent}\n`);
155
+ const loader = new BrainSeedLoader(tmpDir, { seeds: ['brain-seeds/industry.md'], autoSeed: true });
156
+ const pages = loader.parseSeedFile(seedFile, 'industry');
157
+ expect(pages).toHaveLength(1);
158
+ expect(pages[0].content.length).toBeGreaterThan(10000);
159
+ });
160
+
161
+ it('section with title only and no body', () => {
162
+ const seedFile = path.join(tmpDir, 'brain-seeds', 'industry.md');
163
+ fs.writeFileSync(seedFile, '## Title Only\n');
164
+ const loader = new BrainSeedLoader(tmpDir, { seeds: ['brain-seeds/industry.md'], autoSeed: true });
165
+ const pages = loader.parseSeedFile(seedFile, 'industry');
166
+ expect(pages).toHaveLength(1);
167
+ expect(pages[0].slug).toBe('seed/industry/title-only');
168
+ });
169
+ });
170
+
171
+ // ─── KnowledgeEvolver Extended ─────────────────────────────────────
172
+
173
+ describe('KnowledgeEvolver extended', () => {
174
+ it('checkPromotion with custom thresholds (industry→job)', async () => {
175
+ const evolver = new KnowledgeEvolver();
176
+ const mockBrain = {
177
+ search: async () => [
178
+ { id: 'seed/industry/topic1', content: 'stuff', metadata: { tier: 'industry', usageCount: 30 } },
179
+ ],
180
+ };
181
+ // minInteractions=20 means 30 >= 20 qualifies; confidence = 30/40 = 0.75
182
+ const result = await evolver.checkPromotion(mockBrain, { minInteractions: 20, confidenceThreshold: 0.7 });
183
+ expect(result.candidates).toHaveLength(1);
184
+ expect(result.candidates[0].fromTier).toBe('industry');
185
+ expect(result.candidates[0].toTier).toBe('job');
186
+ expect(result.candidates[0].confidence).toBeCloseTo(0.75);
187
+ });
188
+
189
+ it('checkPromotion skips pages below confidence threshold', async () => {
190
+ const evolver = new KnowledgeEvolver();
191
+ const mockBrain = {
192
+ search: async () => [
193
+ { id: 'seed/workstation/low', content: 'stuff', metadata: { tier: 'workstation', usageCount: 51 } },
194
+ ],
195
+ };
196
+ // Default: minInteractions=50, threshold=0.8. confidence = 51/100 = 0.51 < 0.8
197
+ const result = await evolver.checkPromotion(mockBrain);
198
+ expect(result.candidates).toHaveLength(0);
199
+ });
200
+
201
+ it('checkPromotion promotes job→workstation tier transition', async () => {
202
+ const evolver = new KnowledgeEvolver();
203
+ const mockBrain = {
204
+ search: async () => [
205
+ { id: 'seed/job/important', content: 'knowledge', metadata: { tier: 'job', usageCount: 200 } },
206
+ ],
207
+ };
208
+ const result = await evolver.checkPromotion(mockBrain, { minInteractions: 50, confidenceThreshold: 0.8 });
209
+ expect(result.candidates).toHaveLength(1);
210
+ expect(result.candidates[0].fromTier).toBe('job');
211
+ expect(result.candidates[0].toTier).toBe('workstation');
212
+ });
213
+
214
+ it('checkPromotion skips pages already at workstation tier (highest)', async () => {
215
+ const evolver = new KnowledgeEvolver();
216
+ const mockBrain = {
217
+ search: async () => [
218
+ { id: 'seed/workstation/top', content: 'top', metadata: { tier: 'workstation', usageCount: 500 } },
219
+ ],
220
+ };
221
+ // workstation is tierIdx=0, which is skipped by tierIdx <= 0
222
+ const result = await evolver.checkPromotion(mockBrain, { minInteractions: 10, confidenceThreshold: 0.1 });
223
+ expect(result.candidates).toHaveLength(0);
224
+ });
225
+
226
+ it('checkPromotion handles brain.search throwing', async () => {
227
+ const evolver = new KnowledgeEvolver();
228
+ const mockBrain = { search: async () => { throw new Error('DB error'); } };
229
+ const result = await evolver.checkPromotion(mockBrain);
230
+ expect(result.candidates).toHaveLength(0);
231
+ expect(result.promoted).toBe(0);
232
+ });
233
+
234
+ it('checkPromotion handles brain.search returning non-array', async () => {
235
+ const evolver = new KnowledgeEvolver();
236
+ const mockBrain = { search: async () => null };
237
+ const result = await evolver.checkPromotion(mockBrain);
238
+ expect(result.candidates).toHaveLength(0);
239
+ });
240
+
241
+ it('concurrent promoteToJob calls do not conflict', async () => {
242
+ const stored: any[] = [];
243
+ const mockBrain = {
244
+ store: async (_c: string, slug: string, content: string, meta: any) => {
245
+ await new Promise(r => setTimeout(r, 10));
246
+ stored.push({ slug, content, meta });
247
+ },
248
+ };
249
+ const evolver = new KnowledgeEvolver();
250
+ await Promise.all([
251
+ evolver.promoteToJob(mockBrain, 'K1', 'seed/job/p1'),
252
+ evolver.promoteToJob(mockBrain, 'K2', 'seed/job/p2'),
253
+ evolver.promoteToJob(mockBrain, 'K3', 'seed/job/p3'),
254
+ ]);
255
+ expect(stored).toHaveLength(3);
256
+ expect(stored.map(s => s.slug).sort()).toEqual(['seed/job/p1', 'seed/job/p2', 'seed/job/p3']);
257
+ });
258
+
259
+ it('confidence caps at 1.0', async () => {
260
+ const evolver = new KnowledgeEvolver();
261
+ const mockBrain = {
262
+ search: async () => [
263
+ { id: 'seed/industry/hot', content: 'hot', metadata: { tier: 'industry', usageCount: 9999 } },
264
+ ],
265
+ };
266
+ const result = await evolver.checkPromotion(mockBrain, { minInteractions: 50, confidenceThreshold: 0.5 });
267
+ expect(result.candidates).toHaveLength(1);
268
+ expect(result.candidates[0].confidence).toBe(1.0);
269
+ });
270
+ });
271
+
272
+ // ─── Seed Integration with BaseAgent ───────────────────────────────
273
+
274
+ describe('BaseAgent brain seed integration', () => {
275
+ let tmpDir: string;
276
+
277
+ beforeEach(() => {
278
+ tmpDir = makeTmpDir();
279
+ fs.mkdirSync(path.join(tmpDir, 'brain-seeds'), { recursive: true });
280
+ fs.writeFileSync(path.join(tmpDir, 'brain-seeds', 'industry.md'), '## Test Topic\n\nSeed content.\n');
281
+ });
282
+
283
+ afterEach(() => {
284
+ fs.rmSync(tmpDir, { recursive: true, force: true });
285
+ });
286
+
287
+ it('auto-seeds brain on first init when configured', async () => {
288
+ const learned: any[] = [];
289
+ const mockBrain = {
290
+ learn: async (content: string, meta: any) => { learned.push({ content, meta }); },
291
+ };
292
+
293
+ const agent = new BaseAgent({
294
+ name: 'test-agent',
295
+ model: 'test',
296
+ systemPrompt: 'You are a test agent.',
297
+ agentDir: tmpDir,
298
+ brainSeedConfig: {
299
+ seeds: ['brain-seeds/industry.md'],
300
+ autoSeed: true,
301
+ },
302
+ });
303
+ agent.setLongTermMemory(mockBrain);
304
+
305
+ await agent.init();
306
+
307
+ expect(learned).toHaveLength(1);
308
+ expect(learned[0].meta.tags).toContain('brain-seed');
309
+ expect(fs.existsSync(path.join(tmpDir, '.brain-seeded'))).toBe(true);
310
+ });
311
+
312
+ it('skips seeding on re-init when already seeded', async () => {
313
+ const learned: any[] = [];
314
+ const mockBrain = {
315
+ learn: async (content: string, meta: any) => { learned.push({ content, meta }); },
316
+ };
317
+
318
+ // Pre-mark as seeded
319
+ fs.writeFileSync(path.join(tmpDir, '.brain-seeded'), JSON.stringify({ seededAt: new Date().toISOString() }));
320
+
321
+ const agent = new BaseAgent({
322
+ name: 'test-agent',
323
+ model: 'test',
324
+ systemPrompt: 'You are a test agent.',
325
+ agentDir: tmpDir,
326
+ brainSeedConfig: {
327
+ seeds: ['brain-seeds/industry.md'],
328
+ autoSeed: true,
329
+ },
330
+ });
331
+ agent.setLongTermMemory(mockBrain);
332
+ await agent.init();
333
+
334
+ expect(learned).toHaveLength(0);
335
+ });
336
+
337
+ it('does not seed when autoSeed is false', async () => {
338
+ const learned: any[] = [];
339
+ const mockBrain = {
340
+ learn: async (content: string, meta: any) => { learned.push({ content, meta }); },
341
+ };
342
+
343
+ const agent = new BaseAgent({
344
+ name: 'test-agent',
345
+ model: 'test',
346
+ systemPrompt: 'You are a test agent.',
347
+ agentDir: tmpDir,
348
+ brainSeedConfig: {
349
+ seeds: ['brain-seeds/industry.md'],
350
+ autoSeed: false,
351
+ },
352
+ });
353
+ agent.setLongTermMemory(mockBrain);
354
+ await agent.init();
355
+
356
+ expect(learned).toHaveLength(0);
357
+ });
358
+
359
+ it('does not seed when no long-term memory set', async () => {
360
+ const agent = new BaseAgent({
361
+ name: 'test-agent',
362
+ model: 'test',
363
+ systemPrompt: 'You are a test agent.',
364
+ agentDir: tmpDir,
365
+ brainSeedConfig: {
366
+ seeds: ['brain-seeds/industry.md'],
367
+ autoSeed: true,
368
+ },
369
+ });
370
+ // No setLongTermMemory call
371
+ await agent.init();
372
+ // Should not throw, and no marker file since nothing was seeded
373
+ expect(fs.existsSync(path.join(tmpDir, '.brain-seeded'))).toBe(false);
374
+ });
375
+ });
376
+
377
+ // ─── OAD spec.brain.seeds config parsing extended ──────────────────
378
+
379
+ describe('OAD spec.brain.seeds config parsing extended', () => {
380
+ it('parses minimal brain config (seeds only)', () => {
381
+ const yaml = require('js-yaml');
382
+ const config = yaml.load(`
383
+ spec:
384
+ brain:
385
+ seeds:
386
+ - brain-seeds/industry.md
387
+ `) as any;
388
+ expect(config.spec.brain.seeds).toHaveLength(1);
389
+ expect(config.spec.brain.autoSeed).toBeUndefined();
390
+ });
391
+
392
+ it('parses brain config with evolve disabled', () => {
393
+ const yaml = require('js-yaml');
394
+ const config = yaml.load(`
395
+ spec:
396
+ brain:
397
+ seeds: []
398
+ autoSeed: false
399
+ evolve:
400
+ enabled: false
401
+ direction: top-down
402
+ `) as any;
403
+ expect(config.spec.brain.seeds).toHaveLength(0);
404
+ expect(config.spec.brain.autoSeed).toBe(false);
405
+ expect(config.spec.brain.evolve.enabled).toBe(false);
406
+ expect(config.spec.brain.evolve.direction).toBe('top-down');
407
+ });
408
+
409
+ it('handles missing brain section gracefully', () => {
410
+ const yaml = require('js-yaml');
411
+ const config = yaml.load(`
412
+ spec:
413
+ model: gpt-4
414
+ `) as any;
415
+ expect(config.spec.brain).toBeUndefined();
416
+ });
417
+
418
+ it('handles brain seeds with custom marker file', () => {
419
+ const yaml = require('js-yaml');
420
+ const config = yaml.load(`
421
+ spec:
422
+ brain:
423
+ seeds:
424
+ - seeds/custom.md
425
+ seedMarkerFile: .my-marker
426
+ autoSeed: true
427
+ `) as any;
428
+ expect(config.spec.brain.seedMarkerFile).toBe('.my-marker');
429
+ });
430
+ });
431
+
432
+ // ─── CLI brain commands (unit-level) ───────────────────────────────
433
+
434
+ describe('CLI brain commands parsing', () => {
435
+ it('BrainSeedLoader can be constructed from OAD-style config', () => {
436
+ const tmpDir2 = makeTmpDir();
437
+ try {
438
+ fs.mkdirSync(path.join(tmpDir2, 'brain-seeds'), { recursive: true });
439
+ const config = {
440
+ seeds: ['brain-seeds/industry.md', 'brain-seeds/job.md'],
441
+ autoSeed: true,
442
+ };
443
+ const loader = new BrainSeedLoader(tmpDir2, config);
444
+ expect(loader).toBeDefined();
445
+ } finally {
446
+ fs.rmSync(tmpDir2, { recursive: true, force: true });
447
+ }
448
+ });
449
+
450
+ it('seed --status checks isSeeded correctly', async () => {
451
+ const tmpDir2 = makeTmpDir();
452
+ try {
453
+ const loader = new BrainSeedLoader(tmpDir2, { seeds: [], autoSeed: true });
454
+ expect(await loader.isSeeded()).toBe(false);
455
+ await loader.markSeeded();
456
+ expect(await loader.isSeeded()).toBe(true);
457
+ } finally {
458
+ fs.rmSync(tmpDir2, { recursive: true, force: true });
459
+ }
460
+ });
461
+
462
+ it('seed --reset clears marker and allows re-seed', async () => {
463
+ const tmpDir2 = makeTmpDir();
464
+ try {
465
+ fs.mkdirSync(path.join(tmpDir2, 'brain-seeds'), { recursive: true });
466
+ fs.writeFileSync(path.join(tmpDir2, 'brain-seeds', 'industry.md'), '## Re\n\nContent.\n');
467
+
468
+ const loader = new BrainSeedLoader(tmpDir2, { seeds: ['brain-seeds/industry.md'], autoSeed: true });
469
+ await loader.markSeeded();
470
+ expect(await loader.isSeeded()).toBe(true);
471
+
472
+ // Simulate --reset: remove marker
473
+ fs.unlinkSync(path.join(tmpDir2, '.brain-seeded'));
474
+ expect(await loader.isSeeded()).toBe(false);
475
+
476
+ // Re-seed
477
+ const mockBrain = { learn: async () => {} };
478
+ const result = await loader.seedBrain(mockBrain);
479
+ expect(result.imported).toBe(1);
480
+ } finally {
481
+ fs.rmSync(tmpDir2, { recursive: true, force: true });
482
+ }
483
+ });
484
+
485
+ it('evolve command with no brain returns empty candidates', async () => {
486
+ const evolver = new KnowledgeEvolver();
487
+ const result = await evolver.checkPromotion(null);
488
+ expect(result.candidates).toHaveLength(0);
489
+ });
490
+ });