neuralbrain 0.0.0-stage → 0.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.
- package/.dockerignore +11 -0
- package/.env.example +245 -0
- package/Dockerfile +65 -0
- package/LICENSE +44 -0
- package/README.md +312 -2
- package/dist/ai/chat.d.ts +45 -0
- package/dist/ai/chat.d.ts.map +1 -0
- package/dist/ai/chat.js +153 -0
- package/dist/ai/chat.js.map +1 -0
- package/dist/ai/circuitBreaker.d.ts +35 -0
- package/dist/ai/circuitBreaker.d.ts.map +1 -0
- package/dist/ai/circuitBreaker.js +95 -0
- package/dist/ai/circuitBreaker.js.map +1 -0
- package/dist/ai/config.d.ts +88 -0
- package/dist/ai/config.d.ts.map +1 -0
- package/dist/ai/config.js +255 -0
- package/dist/ai/config.js.map +1 -0
- package/dist/ai/vendors.d.ts +58 -0
- package/dist/ai/vendors.d.ts.map +1 -0
- package/dist/ai/vendors.js +223 -0
- package/dist/ai/vendors.js.map +1 -0
- package/dist/app.d.ts +4 -0
- package/dist/app.d.ts.map +1 -0
- package/dist/app.js +1013 -0
- package/dist/app.js.map +1 -0
- package/dist/cli.d.ts +133 -0
- package/dist/cli.d.ts.map +1 -0
- package/dist/cli.js +912 -0
- package/dist/cli.js.map +1 -0
- package/dist/consolidation/candidates.d.ts +34 -0
- package/dist/consolidation/candidates.d.ts.map +1 -0
- package/dist/consolidation/candidates.js +150 -0
- package/dist/consolidation/candidates.js.map +1 -0
- package/dist/consolidation/fixtures.d.ts +25 -0
- package/dist/consolidation/fixtures.d.ts.map +1 -0
- package/dist/consolidation/fixtures.js +400 -0
- package/dist/consolidation/fixtures.js.map +1 -0
- package/dist/consolidation/gate.d.ts +39 -0
- package/dist/consolidation/gate.d.ts.map +1 -0
- package/dist/consolidation/gate.js +286 -0
- package/dist/consolidation/gate.js.map +1 -0
- package/dist/consolidation/runner.d.ts +63 -0
- package/dist/consolidation/runner.d.ts.map +1 -0
- package/dist/consolidation/runner.js +171 -0
- package/dist/consolidation/runner.js.map +1 -0
- package/dist/dashboard/clientScript.d.ts +2 -0
- package/dist/dashboard/clientScript.d.ts.map +1 -0
- package/dist/dashboard/clientScript.js +4212 -0
- package/dist/dashboard/clientScript.js.map +1 -0
- package/dist/dashboard/html.d.ts +2 -0
- package/dist/dashboard/html.d.ts.map +1 -0
- package/dist/dashboard/html.js +554 -0
- package/dist/dashboard/html.js.map +1 -0
- package/dist/dashboard/styles.d.ts +2 -0
- package/dist/dashboard/styles.d.ts.map +1 -0
- package/dist/dashboard/styles.js +1283 -0
- package/dist/dashboard/styles.js.map +1 -0
- package/dist/index.d.ts +3 -0
- package/dist/index.d.ts.map +1 -0
- package/dist/index.js +124 -0
- package/dist/index.js.map +1 -0
- package/dist/learning/embedWorker.d.ts +58 -0
- package/dist/learning/embedWorker.d.ts.map +1 -0
- package/dist/learning/embedWorker.js +552 -0
- package/dist/learning/embedWorker.js.map +1 -0
- package/dist/learning/embedding.d.ts +52 -0
- package/dist/learning/embedding.d.ts.map +1 -0
- package/dist/learning/embedding.js +511 -0
- package/dist/learning/embedding.js.map +1 -0
- package/dist/learning/engine.d.ts +20 -0
- package/dist/learning/engine.d.ts.map +1 -0
- package/dist/learning/engine.js +69 -0
- package/dist/learning/engine.js.map +1 -0
- package/dist/learning/search.d.ts +4 -0
- package/dist/learning/search.d.ts.map +1 -0
- package/dist/learning/search.js +509 -0
- package/dist/learning/search.js.map +1 -0
- package/dist/learning/storeMeta.d.ts +11 -0
- package/dist/learning/storeMeta.d.ts.map +1 -0
- package/dist/learning/storeMeta.js +100 -0
- package/dist/learning/storeMeta.js.map +1 -0
- package/dist/learning/types.d.ts +101 -0
- package/dist/learning/types.d.ts.map +1 -0
- package/dist/learning/types.js +3 -0
- package/dist/learning/types.js.map +1 -0
- package/dist/lib/brainHome.d.ts +28 -0
- package/dist/lib/brainHome.d.ts.map +1 -0
- package/dist/lib/brainHome.js +104 -0
- package/dist/lib/brainHome.js.map +1 -0
- package/dist/lib/db.d.ts +10 -0
- package/dist/lib/db.d.ts.map +1 -0
- package/dist/lib/db.js +589 -0
- package/dist/lib/db.js.map +1 -0
- package/dist/lib/logger.d.ts +3 -0
- package/dist/lib/logger.d.ts.map +1 -0
- package/dist/lib/logger.js +11 -0
- package/dist/lib/logger.js.map +1 -0
- package/dist/lib/projectSlug.d.ts +61 -0
- package/dist/lib/projectSlug.d.ts.map +1 -0
- package/dist/lib/projectSlug.js +273 -0
- package/dist/lib/projectSlug.js.map +1 -0
- package/dist/lib/redactSecrets.d.ts +7 -0
- package/dist/lib/redactSecrets.d.ts.map +1 -0
- package/dist/lib/redactSecrets.js +90 -0
- package/dist/lib/redactSecrets.js.map +1 -0
- package/dist/lib/scope.d.ts +54 -0
- package/dist/lib/scope.d.ts.map +1 -0
- package/dist/lib/scope.js +103 -0
- package/dist/lib/scope.js.map +1 -0
- package/dist/lib/spool.d.ts +23 -0
- package/dist/lib/spool.d.ts.map +1 -0
- package/dist/lib/spool.js +317 -0
- package/dist/lib/spool.js.map +1 -0
- package/dist/lib/sqlite.d.ts +50 -0
- package/dist/lib/sqlite.d.ts.map +1 -0
- package/dist/lib/sqlite.js +130 -0
- package/dist/lib/sqlite.js.map +1 -0
- package/dist/lib/tls.d.ts +34 -0
- package/dist/lib/tls.d.ts.map +1 -0
- package/dist/lib/tls.js +212 -0
- package/dist/lib/tls.js.map +1 -0
- package/dist/mcp/server.d.ts +231 -0
- package/dist/mcp/server.d.ts.map +1 -0
- package/dist/mcp/server.js +615 -0
- package/dist/mcp/server.js.map +1 -0
- package/dist/memory/actionStore.d.ts +75 -0
- package/dist/memory/actionStore.d.ts.map +1 -0
- package/dist/memory/actionStore.js +239 -0
- package/dist/memory/actionStore.js.map +1 -0
- package/dist/memory/deadLetterStore.d.ts +30 -0
- package/dist/memory/deadLetterStore.d.ts.map +1 -0
- package/dist/memory/deadLetterStore.js +91 -0
- package/dist/memory/deadLetterStore.js.map +1 -0
- package/dist/memory/embedQueueStore.d.ts +32 -0
- package/dist/memory/embedQueueStore.d.ts.map +1 -0
- package/dist/memory/embedQueueStore.js +143 -0
- package/dist/memory/embedQueueStore.js.map +1 -0
- package/dist/memory/failurePatternStore.d.ts +37 -0
- package/dist/memory/failurePatternStore.d.ts.map +1 -0
- package/dist/memory/failurePatternStore.js +179 -0
- package/dist/memory/failurePatternStore.js.map +1 -0
- package/dist/memory/graphStore.d.ts +38 -0
- package/dist/memory/graphStore.d.ts.map +1 -0
- package/dist/memory/graphStore.js +229 -0
- package/dist/memory/graphStore.js.map +1 -0
- package/dist/memory/noteStore.d.ts +58 -0
- package/dist/memory/noteStore.d.ts.map +1 -0
- package/dist/memory/noteStore.js +280 -0
- package/dist/memory/noteStore.js.map +1 -0
- package/dist/memory/observationStore.d.ts +40 -0
- package/dist/memory/observationStore.d.ts.map +1 -0
- package/dist/memory/observationStore.js +213 -0
- package/dist/memory/observationStore.js.map +1 -0
- package/dist/memory/projectRename.d.ts +14 -0
- package/dist/memory/projectRename.d.ts.map +1 -0
- package/dist/memory/projectRename.js +105 -0
- package/dist/memory/projectRename.js.map +1 -0
- package/dist/memory/rollupSweeper.d.ts +36 -0
- package/dist/memory/rollupSweeper.d.ts.map +1 -0
- package/dist/memory/rollupSweeper.js +235 -0
- package/dist/memory/rollupSweeper.js.map +1 -0
- package/dist/memory/sessionStore.d.ts +81 -0
- package/dist/memory/sessionStore.d.ts.map +1 -0
- package/dist/memory/sessionStore.js +285 -0
- package/dist/memory/sessionStore.js.map +1 -0
- package/dist/memory/trajectoryStore.d.ts +86 -0
- package/dist/memory/trajectoryStore.d.ts.map +1 -0
- package/dist/memory/trajectoryStore.js +528 -0
- package/dist/memory/trajectoryStore.js.map +1 -0
- package/dist/middleware/auth.d.ts +30 -0
- package/dist/middleware/auth.d.ts.map +1 -0
- package/dist/middleware/auth.js +387 -0
- package/dist/middleware/auth.js.map +1 -0
- package/dist/middleware/rateLimiter.d.ts +13 -0
- package/dist/middleware/rateLimiter.d.ts.map +1 -0
- package/dist/middleware/rateLimiter.js +153 -0
- package/dist/middleware/rateLimiter.js.map +1 -0
- package/dist/middleware/tracing.d.ts +15 -0
- package/dist/middleware/tracing.d.ts.map +1 -0
- package/dist/middleware/tracing.js +53 -0
- package/dist/middleware/tracing.js.map +1 -0
- package/dist/routes/dashboard.d.ts +2 -0
- package/dist/routes/dashboard.d.ts.map +1 -0
- package/dist/routes/dashboard.js +443 -0
- package/dist/routes/dashboard.js.map +1 -0
- package/dist/routes/learning.d.ts +2 -0
- package/dist/routes/learning.d.ts.map +1 -0
- package/dist/routes/learning.js +46 -0
- package/dist/routes/learning.js.map +1 -0
- package/dist/routes/mcp.d.ts +8 -0
- package/dist/routes/mcp.d.ts.map +1 -0
- package/dist/routes/mcp.js +316 -0
- package/dist/routes/mcp.js.map +1 -0
- package/dist/routes/memories.d.ts +2 -0
- package/dist/routes/memories.d.ts.map +1 -0
- package/dist/routes/memories.js +33 -0
- package/dist/routes/memories.js.map +1 -0
- package/dist/scripts/createApiKey.d.ts +2 -0
- package/dist/scripts/createApiKey.d.ts.map +1 -0
- package/dist/scripts/createApiKey.js +78 -0
- package/dist/scripts/createApiKey.js.map +1 -0
- package/dist/scripts/doctor.d.ts +24 -0
- package/dist/scripts/doctor.d.ts.map +1 -0
- package/dist/scripts/doctor.js +332 -0
- package/dist/scripts/doctor.js.map +1 -0
- package/dist/scripts/installAgent.d.ts +80 -0
- package/dist/scripts/installAgent.d.ts.map +1 -0
- package/dist/scripts/installAgent.js +1046 -0
- package/dist/scripts/installAgent.js.map +1 -0
- package/dist/scripts/migrateAgentMemory.d.ts +16 -0
- package/dist/scripts/migrateAgentMemory.d.ts.map +1 -0
- package/dist/scripts/migrateAgentMemory.js +209 -0
- package/dist/scripts/migrateAgentMemory.js.map +1 -0
- package/dist/scripts/smokeTest.d.ts +16 -0
- package/dist/scripts/smokeTest.d.ts.map +1 -0
- package/dist/scripts/smokeTest.js +150 -0
- package/dist/scripts/smokeTest.js.map +1 -0
- package/docker-compose.qdrant-port.yml +7 -0
- package/docker-compose.yml +107 -0
- package/npm-shrinkwrap.json +7635 -0
- package/package.json +106 -4
- package/plugin/hooks/postToolUse.js +513 -0
- package/plugin/hooks/sessionStart.js +416 -0
- package/plugin/hooks/sessionStop.js +346 -0
- package/plugin/hooks.json +30 -0
- package/plugin/mcp_config.json +13 -0
- package/plugin/plugin.json +15 -0
- package/plugin/rules/AGENTS.md +66 -0
- package/plugin/skills/brain-memory/REFERENCE.md +64 -0
- package/plugin/skills/brain-memory/SKILL.md +68 -0
- package/plugin/skills/brain-memory/TROUBLESHOOTING.md +24 -0
- package/plugin/skills/digest/SKILL.md +54 -0
- package/plugin/skills/digest/TROUBLESHOOTING.md +24 -0
- package/plugin/skills/handoff/SKILL.md +59 -0
- package/plugin/skills/handoff/TROUBLESHOOTING.md +24 -0
- package/plugin/skills/save/SKILL.md +76 -0
- package/plugin/skills/save/TROUBLESHOOTING.md +24 -0
- package/plugin/skills/search/SKILL.md +60 -0
- package/plugin/skills/search/TROUBLESHOOTING.md +24 -0
- package/src/ai/chat.ts +214 -0
- package/src/ai/circuitBreaker.ts +120 -0
- package/src/ai/config.ts +311 -0
- package/src/ai/vendors.ts +292 -0
- package/src/app.ts +1150 -0
- package/src/cli.ts +1080 -0
- package/src/consolidation/candidates.ts +219 -0
- package/src/consolidation/fixtures.ts +461 -0
- package/src/consolidation/gate.ts +408 -0
- package/src/consolidation/runner.ts +220 -0
- package/src/dashboard/clientScript.ts +4208 -0
- package/src/dashboard/html.ts +550 -0
- package/src/dashboard/styles.ts +1279 -0
- package/src/index.ts +139 -0
- package/src/learning/embedWorker.ts +651 -0
- package/src/learning/embedding.ts +522 -0
- package/src/learning/engine.ts +86 -0
- package/src/learning/search.ts +568 -0
- package/src/learning/storeMeta.ts +147 -0
- package/src/learning/types.ts +111 -0
- package/src/lib/brainHome.ts +101 -0
- package/src/lib/db.ts +627 -0
- package/src/lib/logger.ts +7 -0
- package/src/lib/projectSlug.ts +286 -0
- package/src/lib/redactSecrets.ts +87 -0
- package/src/lib/scope.ts +121 -0
- package/src/lib/spool.ts +372 -0
- package/src/lib/sqlite.ts +158 -0
- package/src/lib/tls.ts +252 -0
- package/src/mcp/server.ts +793 -0
- package/src/memory/actionStore.ts +378 -0
- package/src/memory/deadLetterStore.ts +141 -0
- package/src/memory/embedQueueStore.ts +176 -0
- package/src/memory/failurePatternStore.ts +221 -0
- package/src/memory/graphStore.ts +352 -0
- package/src/memory/noteStore.ts +403 -0
- package/src/memory/observationStore.ts +303 -0
- package/src/memory/projectRename.ts +147 -0
- package/src/memory/rollupSweeper.ts +309 -0
- package/src/memory/sessionStore.ts +410 -0
- package/src/memory/trajectoryStore.ts +775 -0
- package/src/middleware/auth.ts +450 -0
- package/src/middleware/rateLimiter.ts +186 -0
- package/src/middleware/tracing.ts +70 -0
- package/src/routes/dashboard.ts +496 -0
- package/src/routes/learning.ts +51 -0
- package/src/routes/mcp.ts +349 -0
- package/src/routes/memories.ts +33 -0
- package/src/scripts/createApiKey.ts +109 -0
- package/src/scripts/doctor.ts +359 -0
- package/src/scripts/installAgent.ts +1278 -0
- package/src/scripts/migrateAgentMemory.ts +263 -0
- package/src/scripts/smokeTest.ts +189 -0
- package/tsconfig.json +21 -0
|
@@ -0,0 +1,221 @@
|
|
|
1
|
+
import { randomUUID } from 'crypto';
|
|
2
|
+
import { getDb } from '../lib/db';
|
|
3
|
+
import { logger } from '../lib/logger';
|
|
4
|
+
import { resolveScope } from '../lib/scope';
|
|
5
|
+
import { transaction } from '../lib/sqlite';
|
|
6
|
+
|
|
7
|
+
export type FailureScope = 'project' | 'global' | 'unknown';
|
|
8
|
+
|
|
9
|
+
/**
|
|
10
|
+
* Sanitize error text to neutralize prompt injection, strip control characters,
|
|
11
|
+
* normalize line breaks, and truncate to 500 characters.
|
|
12
|
+
*/
|
|
13
|
+
export function sanitizeErrorText(raw: unknown): string {
|
|
14
|
+
if (raw === null || raw === undefined) return 'Unknown error';
|
|
15
|
+
let text = String(raw);
|
|
16
|
+
|
|
17
|
+
// 1. Normalize line breaks and tabs to single spaces
|
|
18
|
+
text = text.replace(/[\r\n\t]+/g, ' ');
|
|
19
|
+
|
|
20
|
+
// 2. Strip any remaining ASCII control characters (0x00-0x1F, 0x7F)
|
|
21
|
+
text = text.replace(/[\x00-\x1F\x7F]/g, '');
|
|
22
|
+
|
|
23
|
+
// 3. Neutralize prompt delimiter markers (e.g. [SYSTEM], <|...|>, <<SYS>>)
|
|
24
|
+
text = text
|
|
25
|
+
.replace(/<\|/g, '< |')
|
|
26
|
+
.replace(/\|>/g, '| >')
|
|
27
|
+
.replace(/\[\s*(system|assistant|user|inst|\/system|\/assistant|\/user|\/inst)\s*\]/gi, (match) => `(${match.slice(1, -1)})`)
|
|
28
|
+
.replace(/<<\s*(sys|\/sys)\s*>>/gi, (match) => `(${match.slice(2, -2)})`);
|
|
29
|
+
|
|
30
|
+
// 4. Collapse consecutive spaces and trim
|
|
31
|
+
text = text.replace(/\s+/g, ' ').trim();
|
|
32
|
+
|
|
33
|
+
// 5. Truncate to at most 500 characters
|
|
34
|
+
if (text.length > 500) {
|
|
35
|
+
text = text.slice(0, 500).trimEnd();
|
|
36
|
+
}
|
|
37
|
+
|
|
38
|
+
return text || 'Unknown error';
|
|
39
|
+
}
|
|
40
|
+
|
|
41
|
+
export interface FailurePattern {
|
|
42
|
+
id: string;
|
|
43
|
+
scope: FailureScope;
|
|
44
|
+
project_id: string | null;
|
|
45
|
+
session_id: string | null;
|
|
46
|
+
task_type: string;
|
|
47
|
+
error_text: string;
|
|
48
|
+
count: number;
|
|
49
|
+
first_seen_at: number;
|
|
50
|
+
last_seen_at: number;
|
|
51
|
+
}
|
|
52
|
+
|
|
53
|
+
export function upsertFailurePattern(params: {
|
|
54
|
+
scope: FailureScope;
|
|
55
|
+
projectId?: string | null;
|
|
56
|
+
sessionId?: string | null;
|
|
57
|
+
session_id?: string | null;
|
|
58
|
+
taskType?: string | null;
|
|
59
|
+
errorText: string;
|
|
60
|
+
}): string {
|
|
61
|
+
const { scope } = params;
|
|
62
|
+
const taskType = params.taskType?.trim() || 'unknown';
|
|
63
|
+
const cleanErrorText = sanitizeErrorText(params.errorText);
|
|
64
|
+
const sessionId = (params.sessionId ?? params.session_id)?.trim() || null;
|
|
65
|
+
|
|
66
|
+
// Normalised here too, or the UNIQUE(project_id, task_type, error_text) key
|
|
67
|
+
// would split one project's failure counts across spellings of its name —
|
|
68
|
+
// and the count is the whole value of this table.
|
|
69
|
+
const scoped = resolveScope(scope, params.projectId ?? null);
|
|
70
|
+
if (!scoped.ok) {
|
|
71
|
+
const err = new Error(scoped.error);
|
|
72
|
+
(err as any).code = 'SCHEMA_INVALID';
|
|
73
|
+
logger.error({ scope, projectId: params.projectId }, err.message);
|
|
74
|
+
throw err;
|
|
75
|
+
}
|
|
76
|
+
const projectId = scoped.projectId;
|
|
77
|
+
|
|
78
|
+
const db = getDb();
|
|
79
|
+
|
|
80
|
+
try {
|
|
81
|
+
if (projectId !== null) {
|
|
82
|
+
// For project-scoped rows, project_id is NOT NULL, so standard UNIQUE(project_id, task_type, error_text) applies
|
|
83
|
+
const newId = randomUUID();
|
|
84
|
+
const stmt = db.prepare(`
|
|
85
|
+
INSERT INTO failure_patterns (id, scope, project_id, session_id, task_type, error_text, count, first_seen_at, last_seen_at)
|
|
86
|
+
VALUES (?, ?, ?, ?, ?, ?, 1, unixepoch(), unixepoch())
|
|
87
|
+
ON CONFLICT(project_id, task_type, error_text) DO UPDATE SET
|
|
88
|
+
count = failure_patterns.count + 1,
|
|
89
|
+
session_id = COALESCE(excluded.session_id, failure_patterns.session_id),
|
|
90
|
+
last_seen_at = unixepoch()
|
|
91
|
+
RETURNING id
|
|
92
|
+
`);
|
|
93
|
+
|
|
94
|
+
const result = stmt.get(newId, scoped.scope, projectId, sessionId, taskType, cleanErrorText) as { id: string } | undefined;
|
|
95
|
+
return result?.id ?? newId;
|
|
96
|
+
} else {
|
|
97
|
+
// For global or unknown scope, project_id IS NULL.
|
|
98
|
+
// SQLite UNIQUE constraints treat NULL as distinct, so we use a transaction with check-and-update.
|
|
99
|
+
const tx = transaction(db, () => {
|
|
100
|
+
const existing = db
|
|
101
|
+
.prepare(`
|
|
102
|
+
SELECT id, count FROM failure_patterns
|
|
103
|
+
WHERE scope = ? AND project_id IS NULL AND task_type = ? AND error_text = ?
|
|
104
|
+
LIMIT 1
|
|
105
|
+
`)
|
|
106
|
+
.get(scoped.scope, taskType, cleanErrorText) as { id: string; count: number } | undefined;
|
|
107
|
+
|
|
108
|
+
if (existing) {
|
|
109
|
+
db.prepare(`
|
|
110
|
+
UPDATE failure_patterns
|
|
111
|
+
SET count = count + 1,
|
|
112
|
+
session_id = COALESCE(?, session_id),
|
|
113
|
+
last_seen_at = unixepoch()
|
|
114
|
+
WHERE id = ?
|
|
115
|
+
`).run(sessionId, existing.id);
|
|
116
|
+
return existing.id;
|
|
117
|
+
} else {
|
|
118
|
+
const newId = randomUUID();
|
|
119
|
+
db.prepare(`
|
|
120
|
+
INSERT INTO failure_patterns (id, scope, project_id, session_id, task_type, error_text, count, first_seen_at, last_seen_at)
|
|
121
|
+
VALUES (?, ?, NULL, ?, ?, ?, 1, unixepoch(), unixepoch())
|
|
122
|
+
`).run(newId, scoped.scope, sessionId, taskType, cleanErrorText);
|
|
123
|
+
return newId;
|
|
124
|
+
}
|
|
125
|
+
});
|
|
126
|
+
|
|
127
|
+
return tx();
|
|
128
|
+
}
|
|
129
|
+
} catch (error) {
|
|
130
|
+
logger.error(
|
|
131
|
+
{
|
|
132
|
+
scope,
|
|
133
|
+
projectId,
|
|
134
|
+
taskType,
|
|
135
|
+
errorText: cleanErrorText,
|
|
136
|
+
error: error instanceof Error ? error.message : String(error),
|
|
137
|
+
},
|
|
138
|
+
'failed to upsert failure pattern'
|
|
139
|
+
);
|
|
140
|
+
throw error;
|
|
141
|
+
}
|
|
142
|
+
}
|
|
143
|
+
|
|
144
|
+
export function getFailurePatterns(params: {
|
|
145
|
+
projectId?: string | null;
|
|
146
|
+
taskType?: string | null;
|
|
147
|
+
includeGlobal?: boolean;
|
|
148
|
+
limit?: number;
|
|
149
|
+
}): FailurePattern[] {
|
|
150
|
+
const db = getDb();
|
|
151
|
+
const conditions: string[] = [];
|
|
152
|
+
const queryParams: unknown[] = [];
|
|
153
|
+
|
|
154
|
+
const projectId = params.projectId?.trim() || null;
|
|
155
|
+
const includeGlobal = params.includeGlobal !== false;
|
|
156
|
+
|
|
157
|
+
if (projectId) {
|
|
158
|
+
if (includeGlobal) {
|
|
159
|
+
conditions.push("((project_id = ? AND scope = 'project') OR scope = 'global')");
|
|
160
|
+
queryParams.push(projectId);
|
|
161
|
+
} else {
|
|
162
|
+
conditions.push("(project_id = ? AND scope = 'project')");
|
|
163
|
+
queryParams.push(projectId);
|
|
164
|
+
}
|
|
165
|
+
} else if (!projectId) {
|
|
166
|
+
if (includeGlobal) {
|
|
167
|
+
conditions.push("(scope = 'global')");
|
|
168
|
+
} else {
|
|
169
|
+
conditions.push("1 = 0");
|
|
170
|
+
}
|
|
171
|
+
}
|
|
172
|
+
|
|
173
|
+
if (params.taskType) {
|
|
174
|
+
conditions.push('task_type = ?');
|
|
175
|
+
queryParams.push(params.taskType.trim());
|
|
176
|
+
}
|
|
177
|
+
|
|
178
|
+
const whereClause = conditions.length > 0 ? `WHERE ${conditions.join(' AND ')}` : '';
|
|
179
|
+
const limit = params.limit ?? 50;
|
|
180
|
+
queryParams.push(limit);
|
|
181
|
+
|
|
182
|
+
try {
|
|
183
|
+
return db
|
|
184
|
+
.prepare(`
|
|
185
|
+
SELECT id, scope, project_id, session_id, task_type, error_text, count, first_seen_at, last_seen_at
|
|
186
|
+
FROM failure_patterns
|
|
187
|
+
${whereClause}
|
|
188
|
+
ORDER BY count DESC, last_seen_at DESC
|
|
189
|
+
LIMIT ?
|
|
190
|
+
`)
|
|
191
|
+
.all(...queryParams) as FailurePattern[];
|
|
192
|
+
} catch (error) {
|
|
193
|
+
logger.error(
|
|
194
|
+
{
|
|
195
|
+
params,
|
|
196
|
+
error: error instanceof Error ? error.message : String(error),
|
|
197
|
+
},
|
|
198
|
+
'failed to query failure patterns'
|
|
199
|
+
);
|
|
200
|
+
throw error;
|
|
201
|
+
}
|
|
202
|
+
}
|
|
203
|
+
|
|
204
|
+
export function formatCriticalWarnings(
|
|
205
|
+
patterns: Array<{ task_type: string; error_text: string; count: number }>
|
|
206
|
+
): string {
|
|
207
|
+
if (!patterns || patterns.length === 0) {
|
|
208
|
+
return '';
|
|
209
|
+
}
|
|
210
|
+
|
|
211
|
+
const patternsText = patterns
|
|
212
|
+
.map((p) => {
|
|
213
|
+
const taskType = sanitizeErrorText(p.task_type || 'unknown');
|
|
214
|
+
const errorText = sanitizeErrorText(p.error_text || 'Unknown error');
|
|
215
|
+
const count = Number(p.count) || 1;
|
|
216
|
+
return `- Previous failure when attempting task type '${taskType}': ${errorText} (occurred ${count} times)`;
|
|
217
|
+
})
|
|
218
|
+
.join('\n');
|
|
219
|
+
|
|
220
|
+
return `CRITICAL WARNINGS (Learn from past failures in this project):\n${patternsText}`;
|
|
221
|
+
}
|
|
@@ -0,0 +1,352 @@
|
|
|
1
|
+
import { getDb } from '../lib/db';
|
|
2
|
+
|
|
3
|
+
export type GraphNodeType =
|
|
4
|
+
| 'note'
|
|
5
|
+
| 'lesson'
|
|
6
|
+
| 'concept'
|
|
7
|
+
| 'file'
|
|
8
|
+
| 'session'
|
|
9
|
+
| 'action'
|
|
10
|
+
| 'summary';
|
|
11
|
+
|
|
12
|
+
export type GraphEdgeType =
|
|
13
|
+
| 'has_concept'
|
|
14
|
+
| 'touches_file'
|
|
15
|
+
| 'supersedes'
|
|
16
|
+
| 'from_session'
|
|
17
|
+
| 'cites_source';
|
|
18
|
+
|
|
19
|
+
export interface GraphNode {
|
|
20
|
+
id: string;
|
|
21
|
+
type: GraphNodeType;
|
|
22
|
+
label: string;
|
|
23
|
+
scope?: string | null;
|
|
24
|
+
project_id?: string | null;
|
|
25
|
+
meta?: Record<string, unknown>;
|
|
26
|
+
}
|
|
27
|
+
|
|
28
|
+
export interface GraphEdge {
|
|
29
|
+
source: string;
|
|
30
|
+
target: string;
|
|
31
|
+
type: GraphEdgeType;
|
|
32
|
+
}
|
|
33
|
+
|
|
34
|
+
export interface KnowledgeGraph {
|
|
35
|
+
nodes: GraphNode[];
|
|
36
|
+
edges: GraphEdge[];
|
|
37
|
+
stats: {
|
|
38
|
+
nodeCount: number;
|
|
39
|
+
edgeCount: number;
|
|
40
|
+
};
|
|
41
|
+
}
|
|
42
|
+
|
|
43
|
+
export interface KnowledgeGraphOptions {
|
|
44
|
+
projectId?: string;
|
|
45
|
+
scope?: string;
|
|
46
|
+
limit?: number;
|
|
47
|
+
}
|
|
48
|
+
|
|
49
|
+
function clampLimit(raw?: number): number {
|
|
50
|
+
if (typeof raw !== 'number' || !Number.isFinite(raw) || raw <= 0) {
|
|
51
|
+
return 80;
|
|
52
|
+
}
|
|
53
|
+
return Math.min(Math.floor(raw), 200);
|
|
54
|
+
}
|
|
55
|
+
|
|
56
|
+
/**
|
|
57
|
+
* Parse and bound HTTP query parameters for knowledge graph endpoints.
|
|
58
|
+
*/
|
|
59
|
+
export function parseGraphQuery(query: Record<string, unknown>): KnowledgeGraphOptions {
|
|
60
|
+
const projectId =
|
|
61
|
+
typeof query.project_id === 'string'
|
|
62
|
+
? query.project_id
|
|
63
|
+
: typeof query.projectId === 'string'
|
|
64
|
+
? query.projectId
|
|
65
|
+
: undefined;
|
|
66
|
+
const scope = typeof query.scope === 'string' ? query.scope : undefined;
|
|
67
|
+
const rawLimit = query.limit;
|
|
68
|
+
const parsedLimit =
|
|
69
|
+
rawLimit !== undefined && rawLimit !== null && rawLimit !== ''
|
|
70
|
+
? parseInt(String(rawLimit), 10)
|
|
71
|
+
: undefined;
|
|
72
|
+
|
|
73
|
+
return {
|
|
74
|
+
projectId,
|
|
75
|
+
scope,
|
|
76
|
+
limit: clampLimit(parsedLimit),
|
|
77
|
+
};
|
|
78
|
+
}
|
|
79
|
+
|
|
80
|
+
function buildScopeFilter(
|
|
81
|
+
projectId?: string,
|
|
82
|
+
scope?: string
|
|
83
|
+
): { where: string; params: unknown[] } {
|
|
84
|
+
const conditions: string[] = [];
|
|
85
|
+
const params: unknown[] = [];
|
|
86
|
+
|
|
87
|
+
if (projectId !== undefined) {
|
|
88
|
+
conditions.push('project_id = ?');
|
|
89
|
+
params.push(projectId);
|
|
90
|
+
}
|
|
91
|
+
if (scope !== undefined) {
|
|
92
|
+
conditions.push('scope = ?');
|
|
93
|
+
params.push(scope);
|
|
94
|
+
}
|
|
95
|
+
|
|
96
|
+
return {
|
|
97
|
+
where: conditions.length > 0 ? `WHERE ${conditions.join(' AND ')}` : '',
|
|
98
|
+
params,
|
|
99
|
+
};
|
|
100
|
+
}
|
|
101
|
+
|
|
102
|
+
/**
|
|
103
|
+
* Build a scoped knowledge graph from notes, concepts, files, sessions,
|
|
104
|
+
* actions, summaries, and summary citations stored in SQLite.
|
|
105
|
+
*/
|
|
106
|
+
export function getKnowledgeGraph(options: KnowledgeGraphOptions = {}): KnowledgeGraph {
|
|
107
|
+
const db = getDb();
|
|
108
|
+
const limit = clampLimit(options.limit);
|
|
109
|
+
const projectId =
|
|
110
|
+
typeof options.projectId === 'string' && options.projectId.trim()
|
|
111
|
+
? options.projectId.trim()
|
|
112
|
+
: undefined;
|
|
113
|
+
const scope =
|
|
114
|
+
typeof options.scope === 'string' && options.scope.trim()
|
|
115
|
+
? options.scope.trim()
|
|
116
|
+
: undefined;
|
|
117
|
+
|
|
118
|
+
const { where, params } = buildScopeFilter(projectId, scope);
|
|
119
|
+
|
|
120
|
+
const nodeMap = new Map<string, GraphNode>();
|
|
121
|
+
const edgeKeys = new Set<string>();
|
|
122
|
+
const edges: GraphEdge[] = [];
|
|
123
|
+
|
|
124
|
+
const addNode = (node: GraphNode) => {
|
|
125
|
+
if (!nodeMap.has(node.id)) {
|
|
126
|
+
nodeMap.set(node.id, node);
|
|
127
|
+
}
|
|
128
|
+
};
|
|
129
|
+
|
|
130
|
+
const addEdge = (source: string, target: string, type: GraphEdgeType) => {
|
|
131
|
+
if (!nodeMap.has(source) || !nodeMap.has(target)) return;
|
|
132
|
+
const key = `${source}\0${type}\0${target}`;
|
|
133
|
+
if (!edgeKeys.has(key)) {
|
|
134
|
+
edgeKeys.add(key);
|
|
135
|
+
edges.push({ source, target, type });
|
|
136
|
+
}
|
|
137
|
+
};
|
|
138
|
+
|
|
139
|
+
const noteRows = db
|
|
140
|
+
.prepare(
|
|
141
|
+
`
|
|
142
|
+
SELECT id, scope, project_id, session_id, type, title, version, supersedes, is_latest, created_at
|
|
143
|
+
FROM notes
|
|
144
|
+
${where}
|
|
145
|
+
ORDER BY updated_at DESC
|
|
146
|
+
LIMIT ?
|
|
147
|
+
`
|
|
148
|
+
)
|
|
149
|
+
.all(...params, limit) as Array<{
|
|
150
|
+
id: string;
|
|
151
|
+
scope: string;
|
|
152
|
+
project_id: string | null;
|
|
153
|
+
session_id: string | null;
|
|
154
|
+
type: string;
|
|
155
|
+
title: string;
|
|
156
|
+
version: number;
|
|
157
|
+
supersedes: string | null;
|
|
158
|
+
is_latest: number;
|
|
159
|
+
created_at: number;
|
|
160
|
+
}>;
|
|
161
|
+
|
|
162
|
+
for (const note of noteRows) {
|
|
163
|
+
const nodeType: GraphNodeType = note.type === 'lesson' ? 'lesson' : 'note';
|
|
164
|
+
addNode({
|
|
165
|
+
id: note.id,
|
|
166
|
+
type: nodeType,
|
|
167
|
+
label: note.title,
|
|
168
|
+
scope: note.scope,
|
|
169
|
+
project_id: note.project_id,
|
|
170
|
+
meta: {
|
|
171
|
+
noteType: note.type,
|
|
172
|
+
version: note.version,
|
|
173
|
+
is_latest: note.is_latest,
|
|
174
|
+
created_at: note.created_at,
|
|
175
|
+
},
|
|
176
|
+
});
|
|
177
|
+
}
|
|
178
|
+
|
|
179
|
+
const sessionRows = db
|
|
180
|
+
.prepare(
|
|
181
|
+
`
|
|
182
|
+
SELECT id, scope, project_id, agent_name, status, started_at, ended_at
|
|
183
|
+
FROM sessions
|
|
184
|
+
${where}
|
|
185
|
+
ORDER BY started_at DESC
|
|
186
|
+
LIMIT ?
|
|
187
|
+
`
|
|
188
|
+
)
|
|
189
|
+
.all(...params, limit) as Array<{
|
|
190
|
+
id: string;
|
|
191
|
+
scope: string;
|
|
192
|
+
project_id: string | null;
|
|
193
|
+
agent_name: string | null;
|
|
194
|
+
status: string;
|
|
195
|
+
started_at: string;
|
|
196
|
+
ended_at: string | null;
|
|
197
|
+
}>;
|
|
198
|
+
|
|
199
|
+
for (const s of sessionRows) {
|
|
200
|
+
addNode({
|
|
201
|
+
id: s.id,
|
|
202
|
+
type: 'session',
|
|
203
|
+
label: s.agent_name ? `${s.agent_name} (${s.status})` : s.id,
|
|
204
|
+
scope: s.scope,
|
|
205
|
+
project_id: s.project_id,
|
|
206
|
+
meta: {
|
|
207
|
+
status: s.status,
|
|
208
|
+
agent_name: s.agent_name,
|
|
209
|
+
started_at: s.started_at,
|
|
210
|
+
ended_at: s.ended_at,
|
|
211
|
+
},
|
|
212
|
+
});
|
|
213
|
+
}
|
|
214
|
+
|
|
215
|
+
const actionRows = db
|
|
216
|
+
.prepare(
|
|
217
|
+
`
|
|
218
|
+
SELECT id, session_id, scope, project_id, title, status, priority, created_at
|
|
219
|
+
FROM actions
|
|
220
|
+
${where}
|
|
221
|
+
ORDER BY created_at DESC
|
|
222
|
+
LIMIT ?
|
|
223
|
+
`
|
|
224
|
+
)
|
|
225
|
+
.all(...params, limit) as Array<{
|
|
226
|
+
id: string;
|
|
227
|
+
session_id: string | null;
|
|
228
|
+
scope: string;
|
|
229
|
+
project_id: string | null;
|
|
230
|
+
title: string;
|
|
231
|
+
status: string;
|
|
232
|
+
priority: string;
|
|
233
|
+
created_at: string;
|
|
234
|
+
}>;
|
|
235
|
+
|
|
236
|
+
for (const a of actionRows) {
|
|
237
|
+
addNode({
|
|
238
|
+
id: a.id,
|
|
239
|
+
type: 'action',
|
|
240
|
+
label: a.title,
|
|
241
|
+
scope: a.scope,
|
|
242
|
+
project_id: a.project_id,
|
|
243
|
+
meta: {
|
|
244
|
+
status: a.status,
|
|
245
|
+
priority: a.priority,
|
|
246
|
+
created_at: a.created_at,
|
|
247
|
+
},
|
|
248
|
+
});
|
|
249
|
+
}
|
|
250
|
+
|
|
251
|
+
const summaryRows = db
|
|
252
|
+
.prepare(
|
|
253
|
+
`
|
|
254
|
+
SELECT id, scope, project_id, kind, outcome, producer_tier, verified, created_at
|
|
255
|
+
FROM summaries
|
|
256
|
+
${where}
|
|
257
|
+
ORDER BY created_at DESC
|
|
258
|
+
LIMIT ?
|
|
259
|
+
`
|
|
260
|
+
)
|
|
261
|
+
.all(...params, limit) as Array<{
|
|
262
|
+
id: string;
|
|
263
|
+
scope: string;
|
|
264
|
+
project_id: string | null;
|
|
265
|
+
kind: string;
|
|
266
|
+
outcome: string | null;
|
|
267
|
+
producer_tier: string;
|
|
268
|
+
verified: number;
|
|
269
|
+
created_at: number;
|
|
270
|
+
}>;
|
|
271
|
+
|
|
272
|
+
for (const sum of summaryRows) {
|
|
273
|
+
addNode({
|
|
274
|
+
id: sum.id,
|
|
275
|
+
type: 'summary',
|
|
276
|
+
label: `${sum.kind} (${sum.outcome ?? 'unknown'})`,
|
|
277
|
+
scope: sum.scope,
|
|
278
|
+
project_id: sum.project_id,
|
|
279
|
+
meta: {
|
|
280
|
+
kind: sum.kind,
|
|
281
|
+
outcome: sum.outcome,
|
|
282
|
+
producer_tier: sum.producer_tier,
|
|
283
|
+
verified: sum.verified,
|
|
284
|
+
created_at: sum.created_at,
|
|
285
|
+
},
|
|
286
|
+
});
|
|
287
|
+
}
|
|
288
|
+
|
|
289
|
+
if (noteRows.length > 0) {
|
|
290
|
+
const noteIds = noteRows.map((n) => n.id);
|
|
291
|
+
const placeholders = noteIds.map(() => '?').join(',');
|
|
292
|
+
|
|
293
|
+
const conceptRows = db
|
|
294
|
+
.prepare(`SELECT note_id, concept FROM note_concepts WHERE note_id IN (${placeholders})`)
|
|
295
|
+
.all(...noteIds) as Array<{ note_id: string; concept: string }>;
|
|
296
|
+
|
|
297
|
+
for (const row of conceptRows) {
|
|
298
|
+
const conceptId = `concept:${row.concept}`;
|
|
299
|
+
addNode({ id: conceptId, type: 'concept', label: row.concept });
|
|
300
|
+
addEdge(row.note_id, conceptId, 'has_concept');
|
|
301
|
+
}
|
|
302
|
+
|
|
303
|
+
const fileRows = db
|
|
304
|
+
.prepare(`SELECT note_id, file_path FROM note_files WHERE note_id IN (${placeholders})`)
|
|
305
|
+
.all(...noteIds) as Array<{ note_id: string; file_path: string }>;
|
|
306
|
+
|
|
307
|
+
for (const row of fileRows) {
|
|
308
|
+
const fileId = `file:${row.file_path}`;
|
|
309
|
+
addNode({ id: fileId, type: 'file', label: row.file_path });
|
|
310
|
+
addEdge(row.note_id, fileId, 'touches_file');
|
|
311
|
+
}
|
|
312
|
+
|
|
313
|
+
for (const note of noteRows) {
|
|
314
|
+
if (note.supersedes) {
|
|
315
|
+
addEdge(note.id, note.supersedes, 'supersedes');
|
|
316
|
+
}
|
|
317
|
+
if (note.session_id) {
|
|
318
|
+
addEdge(note.id, note.session_id, 'from_session');
|
|
319
|
+
}
|
|
320
|
+
}
|
|
321
|
+
}
|
|
322
|
+
|
|
323
|
+
for (const action of actionRows) {
|
|
324
|
+
if (action.session_id) {
|
|
325
|
+
addEdge(action.id, action.session_id, 'from_session');
|
|
326
|
+
}
|
|
327
|
+
}
|
|
328
|
+
|
|
329
|
+
if (summaryRows.length > 0) {
|
|
330
|
+
const summaryIds = summaryRows.map((s) => s.id);
|
|
331
|
+
const placeholders = summaryIds.map(() => '?').join(',');
|
|
332
|
+
const sourceRows = db
|
|
333
|
+
.prepare(
|
|
334
|
+
`SELECT DISTINCT summary_id, record_id FROM summary_sources WHERE summary_id IN (${placeholders})`
|
|
335
|
+
)
|
|
336
|
+
.all(...summaryIds) as Array<{ summary_id: string; record_id: string }>;
|
|
337
|
+
|
|
338
|
+
for (const row of sourceRows) {
|
|
339
|
+
addEdge(row.summary_id, row.record_id, 'cites_source');
|
|
340
|
+
}
|
|
341
|
+
}
|
|
342
|
+
|
|
343
|
+
const nodes = Array.from(nodeMap.values());
|
|
344
|
+
return {
|
|
345
|
+
nodes,
|
|
346
|
+
edges,
|
|
347
|
+
stats: {
|
|
348
|
+
nodeCount: nodes.length,
|
|
349
|
+
edgeCount: edges.length,
|
|
350
|
+
},
|
|
351
|
+
};
|
|
352
|
+
}
|