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,403 @@
|
|
|
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 { redactSecrets } from '../lib/redactSecrets';
|
|
6
|
+
import { enqueueForEmbedding } from './embedQueueStore';
|
|
7
|
+
import { transaction } from '../lib/sqlite';
|
|
8
|
+
|
|
9
|
+
export type NoteScope = 'project' | 'global' | 'unknown';
|
|
10
|
+
export type NoteType = 'fact' | 'architecture' | 'pattern' | 'workflow' | 'bug' | 'preference' | 'lesson';
|
|
11
|
+
export type AuthorKind = 'human' | 'agent';
|
|
12
|
+
|
|
13
|
+
export interface NoteRecord {
|
|
14
|
+
id: string;
|
|
15
|
+
scope: NoteScope;
|
|
16
|
+
project_id: string | null;
|
|
17
|
+
session_id: string | null;
|
|
18
|
+
type: NoteType;
|
|
19
|
+
title: string;
|
|
20
|
+
content: string;
|
|
21
|
+
author: string | null;
|
|
22
|
+
author_kind: AuthorKind | null;
|
|
23
|
+
version: number;
|
|
24
|
+
supersedes: string | null;
|
|
25
|
+
is_latest: number;
|
|
26
|
+
embedding: Buffer | null;
|
|
27
|
+
created_at: number;
|
|
28
|
+
updated_at: number;
|
|
29
|
+
}
|
|
30
|
+
|
|
31
|
+
export interface NoteWithRelations extends NoteRecord {
|
|
32
|
+
concepts: string[];
|
|
33
|
+
files: string[];
|
|
34
|
+
}
|
|
35
|
+
|
|
36
|
+
export interface CreateNoteInput {
|
|
37
|
+
id?: string;
|
|
38
|
+
scope: NoteScope;
|
|
39
|
+
projectId?: string | null;
|
|
40
|
+
project_id?: string | null;
|
|
41
|
+
sessionId?: string | null;
|
|
42
|
+
session_id?: string | null;
|
|
43
|
+
type: NoteType;
|
|
44
|
+
title: string;
|
|
45
|
+
content: string;
|
|
46
|
+
author?: string | null;
|
|
47
|
+
authorKind?: AuthorKind | null;
|
|
48
|
+
concepts?: string[];
|
|
49
|
+
files?: string[];
|
|
50
|
+
supersedes?: string | null;
|
|
51
|
+
createdAt?: number;
|
|
52
|
+
updatedAt?: number;
|
|
53
|
+
}
|
|
54
|
+
|
|
55
|
+
const VALID_TYPES = new Set<NoteType>([
|
|
56
|
+
'fact',
|
|
57
|
+
'architecture',
|
|
58
|
+
'pattern',
|
|
59
|
+
'workflow',
|
|
60
|
+
'bug',
|
|
61
|
+
'preference',
|
|
62
|
+
'lesson',
|
|
63
|
+
]);
|
|
64
|
+
|
|
65
|
+
export function createNote(input: CreateNoteInput): NoteWithRelations {
|
|
66
|
+
if (!input.scope) {
|
|
67
|
+
const err = new Error("Scope is required and must be 'project', 'global', or 'unknown'");
|
|
68
|
+
(err as any).code = 'SCOPE_REQUIRED';
|
|
69
|
+
throw err;
|
|
70
|
+
}
|
|
71
|
+
|
|
72
|
+
const rawProject = input.projectId ?? input.project_id;
|
|
73
|
+
const scoped = resolveScope(input.scope, rawProject);
|
|
74
|
+
if (!scoped.ok) {
|
|
75
|
+
const err = new Error(scoped.error);
|
|
76
|
+
(err as any).code = 'SCHEMA_INVALID';
|
|
77
|
+
throw err;
|
|
78
|
+
}
|
|
79
|
+
|
|
80
|
+
const scope: NoteScope = scoped.scope;
|
|
81
|
+
const projectId: string | null = scoped.projectId;
|
|
82
|
+
|
|
83
|
+
if (!VALID_TYPES.has(input.type)) {
|
|
84
|
+
const err = new Error(`Invalid note type '${String(input.type)}'`);
|
|
85
|
+
(err as any).code = 'SCHEMA_INVALID';
|
|
86
|
+
throw err;
|
|
87
|
+
}
|
|
88
|
+
|
|
89
|
+
if (!input.title || input.title.trim() === '') {
|
|
90
|
+
const err = new Error('title is required and cannot be empty');
|
|
91
|
+
(err as any).code = 'SCHEMA_INVALID';
|
|
92
|
+
throw err;
|
|
93
|
+
}
|
|
94
|
+
|
|
95
|
+
if (!input.content || input.content.trim() === '') {
|
|
96
|
+
const err = new Error('content is required and cannot be empty');
|
|
97
|
+
(err as any).code = 'SCHEMA_INVALID';
|
|
98
|
+
throw err;
|
|
99
|
+
}
|
|
100
|
+
|
|
101
|
+
const authorKind = input.authorKind ?? null;
|
|
102
|
+
if (authorKind !== null && authorKind !== 'human' && authorKind !== 'agent') {
|
|
103
|
+
const err = new Error(`Invalid authorKind '${String(authorKind)}'. Must be 'human', 'agent', or null`);
|
|
104
|
+
(err as any).code = 'SCHEMA_INVALID';
|
|
105
|
+
throw err;
|
|
106
|
+
}
|
|
107
|
+
|
|
108
|
+
const db = getDb();
|
|
109
|
+
const id = input.id?.trim() || `note_${randomUUID().replace(/-/g, '').slice(0, 16)}`;
|
|
110
|
+
const sessionId = (input.sessionId ?? input.session_id)?.trim() || null;
|
|
111
|
+
const now = Math.floor(Date.now() / 1000);
|
|
112
|
+
const createdAt = input.createdAt ?? now;
|
|
113
|
+
const updatedAt = input.updatedAt ?? now;
|
|
114
|
+
|
|
115
|
+
const result = transaction(db, () => {
|
|
116
|
+
let version = 1;
|
|
117
|
+
const supersedesId = input.supersedes?.trim() || null;
|
|
118
|
+
|
|
119
|
+
if (supersedesId) {
|
|
120
|
+
const parent = db.prepare('SELECT id, version FROM notes WHERE id = ?').get(supersedesId) as { id: string; version: number } | undefined;
|
|
121
|
+
if (!parent) {
|
|
122
|
+
const err = new Error(`Parent note '${supersedesId}' to supersede not found`);
|
|
123
|
+
(err as any).code = 'PARENT_NOT_FOUND';
|
|
124
|
+
throw err;
|
|
125
|
+
}
|
|
126
|
+
|
|
127
|
+
version = parent.version + 1;
|
|
128
|
+
|
|
129
|
+
// Mark parent as superseded (is_latest = 0)
|
|
130
|
+
db.prepare(`
|
|
131
|
+
UPDATE notes
|
|
132
|
+
SET is_latest = 0, updated_at = unixepoch()
|
|
133
|
+
WHERE id = ?
|
|
134
|
+
`).run(supersedesId);
|
|
135
|
+
}
|
|
136
|
+
|
|
137
|
+
const sanitizedTitle = redactSecrets(input.title.trim());
|
|
138
|
+
const sanitizedContent = redactSecrets(input.content);
|
|
139
|
+
|
|
140
|
+
db.prepare(`
|
|
141
|
+
INSERT INTO notes (
|
|
142
|
+
id, scope, project_id, session_id, type, title, content, author, author_kind,
|
|
143
|
+
version, supersedes, is_latest, embedding, created_at, updated_at
|
|
144
|
+
) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, 1, NULL, ?, ?)
|
|
145
|
+
`).run(
|
|
146
|
+
id,
|
|
147
|
+
scope,
|
|
148
|
+
projectId,
|
|
149
|
+
sessionId,
|
|
150
|
+
input.type,
|
|
151
|
+
sanitizedTitle,
|
|
152
|
+
sanitizedContent,
|
|
153
|
+
input.author?.trim() ?? null,
|
|
154
|
+
authorKind,
|
|
155
|
+
version,
|
|
156
|
+
supersedesId,
|
|
157
|
+
createdAt,
|
|
158
|
+
updatedAt
|
|
159
|
+
);
|
|
160
|
+
|
|
161
|
+
const concepts = Array.isArray(input.concepts)
|
|
162
|
+
? Array.from(new Set(input.concepts.map((c) => String(c).trim()).filter(Boolean)))
|
|
163
|
+
: [];
|
|
164
|
+
|
|
165
|
+
if (concepts.length > 0) {
|
|
166
|
+
const conceptStmt = db.prepare('INSERT OR IGNORE INTO note_concepts (note_id, concept) VALUES (?, ?)');
|
|
167
|
+
for (const concept of concepts) {
|
|
168
|
+
conceptStmt.run(id, concept);
|
|
169
|
+
}
|
|
170
|
+
}
|
|
171
|
+
|
|
172
|
+
const files = Array.isArray(input.files)
|
|
173
|
+
? Array.from(new Set(input.files.map((f) => String(f).trim()).filter(Boolean)))
|
|
174
|
+
: [];
|
|
175
|
+
|
|
176
|
+
if (files.length > 0) {
|
|
177
|
+
const fileStmt = db.prepare('INSERT OR IGNORE INTO note_files (note_id, file_path) VALUES (?, ?)');
|
|
178
|
+
for (const file of files) {
|
|
179
|
+
fileStmt.run(id, file);
|
|
180
|
+
}
|
|
181
|
+
}
|
|
182
|
+
|
|
183
|
+
// Call enqueueForEmbedding atomically inside the transaction
|
|
184
|
+
enqueueForEmbedding(id, 'note');
|
|
185
|
+
|
|
186
|
+
return {
|
|
187
|
+
id,
|
|
188
|
+
scope,
|
|
189
|
+
project_id: projectId,
|
|
190
|
+
session_id: sessionId,
|
|
191
|
+
type: input.type,
|
|
192
|
+
title: sanitizedTitle,
|
|
193
|
+
content: sanitizedContent,
|
|
194
|
+
author: input.author?.trim() ?? null,
|
|
195
|
+
author_kind: authorKind,
|
|
196
|
+
version,
|
|
197
|
+
supersedes: supersedesId,
|
|
198
|
+
is_latest: 1,
|
|
199
|
+
embedding: null,
|
|
200
|
+
created_at: createdAt,
|
|
201
|
+
updated_at: updatedAt,
|
|
202
|
+
concepts,
|
|
203
|
+
files,
|
|
204
|
+
};
|
|
205
|
+
})();
|
|
206
|
+
|
|
207
|
+
return result;
|
|
208
|
+
}
|
|
209
|
+
|
|
210
|
+
export function getNote(id: string): NoteWithRelations | undefined {
|
|
211
|
+
const db = getDb();
|
|
212
|
+
const note = db.prepare('SELECT * FROM notes WHERE id = ?').get(id) as NoteRecord | undefined;
|
|
213
|
+
if (!note) return undefined;
|
|
214
|
+
|
|
215
|
+
const conceptRows = db
|
|
216
|
+
.prepare('SELECT concept FROM note_concepts WHERE note_id = ? ORDER BY concept ASC')
|
|
217
|
+
.all(id) as Array<{ concept: string }>;
|
|
218
|
+
const fileRows = db
|
|
219
|
+
.prepare('SELECT file_path FROM note_files WHERE note_id = ? ORDER BY file_path ASC')
|
|
220
|
+
.all(id) as Array<{ file_path: string }>;
|
|
221
|
+
|
|
222
|
+
return {
|
|
223
|
+
...note,
|
|
224
|
+
concepts: conceptRows.map((r) => r.concept),
|
|
225
|
+
files: fileRows.map((r) => r.file_path),
|
|
226
|
+
};
|
|
227
|
+
}
|
|
228
|
+
|
|
229
|
+
function attachNoteRelations(notes: NoteRecord[], db: ReturnType<typeof getDb>): NoteWithRelations[] {
|
|
230
|
+
if (notes.length === 0) return [];
|
|
231
|
+
|
|
232
|
+
const noteIds = notes.map((n) => n.id);
|
|
233
|
+
const conceptsByNote = new Map<string, string[]>();
|
|
234
|
+
const filesByNote = new Map<string, string[]>();
|
|
235
|
+
|
|
236
|
+
for (const id of noteIds) {
|
|
237
|
+
conceptsByNote.set(id, []);
|
|
238
|
+
filesByNote.set(id, []);
|
|
239
|
+
}
|
|
240
|
+
|
|
241
|
+
const CHUNK_SIZE = 500;
|
|
242
|
+
for (let i = 0; i < noteIds.length; i += CHUNK_SIZE) {
|
|
243
|
+
const chunk = noteIds.slice(i, i + CHUNK_SIZE);
|
|
244
|
+
const placeholders = chunk.map(() => '?').join(',');
|
|
245
|
+
|
|
246
|
+
const conceptRows = db
|
|
247
|
+
.prepare(
|
|
248
|
+
`SELECT note_id, concept FROM note_concepts WHERE note_id IN (${placeholders}) ORDER BY concept ASC`
|
|
249
|
+
)
|
|
250
|
+
.all(...chunk) as Array<{ note_id: string; concept: string }>;
|
|
251
|
+
|
|
252
|
+
for (const row of conceptRows) {
|
|
253
|
+
conceptsByNote.get(row.note_id)?.push(row.concept);
|
|
254
|
+
}
|
|
255
|
+
|
|
256
|
+
const fileRows = db
|
|
257
|
+
.prepare(
|
|
258
|
+
`SELECT note_id, file_path FROM note_files WHERE note_id IN (${placeholders}) ORDER BY file_path ASC`
|
|
259
|
+
)
|
|
260
|
+
.all(...chunk) as Array<{ note_id: string; file_path: string }>;
|
|
261
|
+
|
|
262
|
+
for (const row of fileRows) {
|
|
263
|
+
filesByNote.get(row.note_id)?.push(row.file_path);
|
|
264
|
+
}
|
|
265
|
+
}
|
|
266
|
+
|
|
267
|
+
return notes.map((note) => ({
|
|
268
|
+
...note,
|
|
269
|
+
concepts: conceptsByNote.get(note.id) ?? [],
|
|
270
|
+
files: filesByNote.get(note.id) ?? [],
|
|
271
|
+
}));
|
|
272
|
+
}
|
|
273
|
+
|
|
274
|
+
export function getNotesByFile(filePath: string, projectId?: string): NoteWithRelations[] {
|
|
275
|
+
const db = getDb();
|
|
276
|
+
const cleanPath = filePath.trim();
|
|
277
|
+
|
|
278
|
+
let query = `
|
|
279
|
+
SELECT n.*
|
|
280
|
+
FROM notes n
|
|
281
|
+
JOIN note_files nf ON n.id = nf.note_id
|
|
282
|
+
WHERE nf.file_path = ? AND n.is_latest = 1
|
|
283
|
+
`;
|
|
284
|
+
const params: unknown[] = [cleanPath];
|
|
285
|
+
|
|
286
|
+
if (projectId) {
|
|
287
|
+
query += ` AND ((n.project_id = ? AND n.scope = 'project') OR n.scope = 'global')`;
|
|
288
|
+
params.push(projectId.trim());
|
|
289
|
+
}
|
|
290
|
+
|
|
291
|
+
query += ` ORDER BY n.updated_at DESC`;
|
|
292
|
+
|
|
293
|
+
const rows = db.prepare(query).all(...params) as NoteRecord[];
|
|
294
|
+
return attachNoteRelations(rows, db);
|
|
295
|
+
}
|
|
296
|
+
|
|
297
|
+
export function listNotes(filters?: {
|
|
298
|
+
scope?: string;
|
|
299
|
+
projectId?: string;
|
|
300
|
+
includeGlobal?: boolean;
|
|
301
|
+
type?: string[];
|
|
302
|
+
concept?: string;
|
|
303
|
+
filePath?: string;
|
|
304
|
+
onlyLatest?: boolean;
|
|
305
|
+
limit?: number;
|
|
306
|
+
offset?: number;
|
|
307
|
+
}): NoteWithRelations[] {
|
|
308
|
+
const db = getDb();
|
|
309
|
+
const conditions: string[] = [];
|
|
310
|
+
const params: unknown[] = [];
|
|
311
|
+
|
|
312
|
+
const onlyLatest = filters?.onlyLatest !== false;
|
|
313
|
+
if (onlyLatest) {
|
|
314
|
+
conditions.push('n.is_latest = 1');
|
|
315
|
+
}
|
|
316
|
+
|
|
317
|
+
if (filters?.scope) {
|
|
318
|
+
conditions.push('n.scope = ?');
|
|
319
|
+
params.push(filters.scope);
|
|
320
|
+
}
|
|
321
|
+
|
|
322
|
+
if (filters?.projectId) {
|
|
323
|
+
if (filters.includeGlobal) {
|
|
324
|
+
conditions.push("((n.project_id = ? AND n.scope = 'project') OR n.scope = 'global')");
|
|
325
|
+
params.push(filters.projectId.trim());
|
|
326
|
+
} else {
|
|
327
|
+
conditions.push("(n.project_id = ? AND n.scope = 'project')");
|
|
328
|
+
params.push(filters.projectId.trim());
|
|
329
|
+
}
|
|
330
|
+
}
|
|
331
|
+
|
|
332
|
+
if (Array.isArray(filters?.type) && filters.type.length > 0) {
|
|
333
|
+
const typePlaceholders = filters.type.map(() => '?').join(',');
|
|
334
|
+
conditions.push(`n.type IN (${typePlaceholders})`);
|
|
335
|
+
params.push(...filters.type);
|
|
336
|
+
}
|
|
337
|
+
|
|
338
|
+
if (filters?.concept) {
|
|
339
|
+
conditions.push(`EXISTS (SELECT 1 FROM note_concepts nc WHERE nc.note_id = n.id AND nc.concept = ?)`);
|
|
340
|
+
params.push(filters.concept.trim());
|
|
341
|
+
}
|
|
342
|
+
|
|
343
|
+
if (filters?.filePath) {
|
|
344
|
+
conditions.push(`EXISTS (SELECT 1 FROM note_files nf WHERE nf.note_id = n.id AND nf.file_path = ?)`);
|
|
345
|
+
params.push(filters.filePath.trim());
|
|
346
|
+
}
|
|
347
|
+
|
|
348
|
+
const whereClause = conditions.length > 0 ? `WHERE ${conditions.join(' AND ')}` : '';
|
|
349
|
+
const limit = filters?.limit ?? 50;
|
|
350
|
+
const offset = filters?.offset ?? 0;
|
|
351
|
+
params.push(limit, offset);
|
|
352
|
+
|
|
353
|
+
const rows = db
|
|
354
|
+
.prepare(`
|
|
355
|
+
SELECT n.*
|
|
356
|
+
FROM notes n
|
|
357
|
+
${whereClause}
|
|
358
|
+
ORDER BY n.updated_at DESC
|
|
359
|
+
LIMIT ? OFFSET ?
|
|
360
|
+
`)
|
|
361
|
+
.all(...params) as NoteRecord[];
|
|
362
|
+
|
|
363
|
+
return attachNoteRelations(rows, db);
|
|
364
|
+
}
|
|
365
|
+
|
|
366
|
+
export function updateNoteScope(
|
|
367
|
+
id: string,
|
|
368
|
+
scope: NoteScope,
|
|
369
|
+
projectId?: string | null
|
|
370
|
+
): NoteWithRelations {
|
|
371
|
+
if (!scope) {
|
|
372
|
+
const err = new Error("Scope is required and must be 'project', 'global', or 'unknown'");
|
|
373
|
+
(err as any).code = 'SCOPE_REQUIRED';
|
|
374
|
+
throw err;
|
|
375
|
+
}
|
|
376
|
+
|
|
377
|
+
const scoped = resolveScope(scope, projectId);
|
|
378
|
+
if (!scoped.ok) {
|
|
379
|
+
const err = new Error(scoped.error);
|
|
380
|
+
(err as any).code = 'SCHEMA_INVALID';
|
|
381
|
+
throw err;
|
|
382
|
+
}
|
|
383
|
+
|
|
384
|
+
const db = getDb();
|
|
385
|
+
const note = getNote(id);
|
|
386
|
+
if (!note) {
|
|
387
|
+
const err = new Error(`Note '${id}' not found`);
|
|
388
|
+
(err as any).code = 'NOT_FOUND';
|
|
389
|
+
throw err;
|
|
390
|
+
}
|
|
391
|
+
|
|
392
|
+
transaction(db, () => {
|
|
393
|
+
db.prepare(`
|
|
394
|
+
UPDATE notes
|
|
395
|
+
SET scope = ?, project_id = ?, updated_at = unixepoch()
|
|
396
|
+
WHERE id = ?
|
|
397
|
+
`).run(scoped.scope, scoped.projectId, id);
|
|
398
|
+
|
|
399
|
+
enqueueForEmbedding(id, 'note');
|
|
400
|
+
})();
|
|
401
|
+
|
|
402
|
+
return getNote(id)!;
|
|
403
|
+
}
|
|
@@ -0,0 +1,303 @@
|
|
|
1
|
+
import { randomUUID } from 'crypto';
|
|
2
|
+
import { getDb } from '../lib/db';
|
|
3
|
+
import { logger } from '../lib/logger';
|
|
4
|
+
import { enqueueForEmbedding } from './embedQueueStore';
|
|
5
|
+
import { recordDeadLetter } from './deadLetterStore';
|
|
6
|
+
import { resolveScope } from '../lib/scope';
|
|
7
|
+
import { redactOptional } from '../lib/redactSecrets';
|
|
8
|
+
import { transaction } from '../lib/sqlite';
|
|
9
|
+
|
|
10
|
+
export type ObservationScope = 'project' | 'global' | 'unknown';
|
|
11
|
+
export type ObservationKind = 'tool_call' | 'prompt';
|
|
12
|
+
|
|
13
|
+
export interface ObservationRecord {
|
|
14
|
+
id: string;
|
|
15
|
+
scope: ObservationScope;
|
|
16
|
+
project_id: string | null;
|
|
17
|
+
note_ref: string | null;
|
|
18
|
+
task_ref: string | null;
|
|
19
|
+
session_id: string | null;
|
|
20
|
+
agent: string | null;
|
|
21
|
+
kind: ObservationKind;
|
|
22
|
+
tool_name: string | null;
|
|
23
|
+
file_path: string | null;
|
|
24
|
+
input: string | null;
|
|
25
|
+
output: string | null;
|
|
26
|
+
duration_ms: number;
|
|
27
|
+
failed: number;
|
|
28
|
+
created_at: number;
|
|
29
|
+
archived_at: number | null;
|
|
30
|
+
}
|
|
31
|
+
|
|
32
|
+
export interface CaptureResult {
|
|
33
|
+
accepted: number;
|
|
34
|
+
ids: string[];
|
|
35
|
+
rejected: Array<{
|
|
36
|
+
index: number;
|
|
37
|
+
reason: string;
|
|
38
|
+
error: string;
|
|
39
|
+
}>;
|
|
40
|
+
}
|
|
41
|
+
|
|
42
|
+
interface ValidatedObservation {
|
|
43
|
+
id: string;
|
|
44
|
+
scope: ObservationScope;
|
|
45
|
+
projectId: string | null;
|
|
46
|
+
noteRef: string | null;
|
|
47
|
+
taskRef: string | null;
|
|
48
|
+
sessionId: string | null;
|
|
49
|
+
agent: string | null;
|
|
50
|
+
kind: ObservationKind;
|
|
51
|
+
toolName: string | null;
|
|
52
|
+
filePath: string | null;
|
|
53
|
+
input: string | null;
|
|
54
|
+
output: string | null;
|
|
55
|
+
durationMs: number;
|
|
56
|
+
failed: number;
|
|
57
|
+
createdAt: number;
|
|
58
|
+
}
|
|
59
|
+
|
|
60
|
+
function validateObservationItem(item: unknown, index: number): { valid: true; item: ValidatedObservation } | { valid: false; error: string } {
|
|
61
|
+
if (!item || typeof item !== 'object' || Array.isArray(item)) {
|
|
62
|
+
return { valid: false, error: 'Observation item must be a non-null object' };
|
|
63
|
+
}
|
|
64
|
+
|
|
65
|
+
const raw = item as Record<string, unknown>;
|
|
66
|
+
|
|
67
|
+
// Scope defaults to 'unknown' (NEVER 'global'); project_id is normalised so
|
|
68
|
+
// that two spellings of one name converge. See src/lib/scope.ts.
|
|
69
|
+
const scoped = resolveScope(raw.scope, raw.project_id ?? raw.projectId);
|
|
70
|
+
if (!scoped.ok) {
|
|
71
|
+
return { valid: false, error: scoped.error };
|
|
72
|
+
}
|
|
73
|
+
const scope: ObservationScope = scoped.scope;
|
|
74
|
+
const projectId: string | null = scoped.projectId;
|
|
75
|
+
|
|
76
|
+
// kind must be 'tool_call' or 'prompt'
|
|
77
|
+
if (raw.kind !== 'tool_call' && raw.kind !== 'prompt') {
|
|
78
|
+
return { valid: false, error: `Invalid kind '${String(raw.kind)}'. Must be 'tool_call' or 'prompt'` };
|
|
79
|
+
}
|
|
80
|
+
const kind = raw.kind as ObservationKind;
|
|
81
|
+
|
|
82
|
+
// failed: comes from client (0 or 1, or boolean converted to 0 or 1), never inferred
|
|
83
|
+
let failed = 0;
|
|
84
|
+
if (typeof raw.failed === 'boolean') {
|
|
85
|
+
failed = raw.failed ? 1 : 0;
|
|
86
|
+
} else if (raw.failed === 1 || raw.failed === '1') {
|
|
87
|
+
failed = 1;
|
|
88
|
+
} else if (raw.failed === 0 || raw.failed === '0' || raw.failed === undefined || raw.failed === null) {
|
|
89
|
+
failed = 0;
|
|
90
|
+
} else {
|
|
91
|
+
return { valid: false, error: `Invalid failed value '${String(raw.failed)}'. Must be 0, 1, or boolean` };
|
|
92
|
+
}
|
|
93
|
+
|
|
94
|
+
// duration_ms: non-negative integer
|
|
95
|
+
let durationMs = 0;
|
|
96
|
+
const rawDuration = raw.duration_ms ?? raw.durationMs;
|
|
97
|
+
if (rawDuration !== undefined && rawDuration !== null) {
|
|
98
|
+
const num = Number(rawDuration);
|
|
99
|
+
if (!Number.isFinite(num) || num < 0) {
|
|
100
|
+
return { valid: false, error: `duration_ms must be a non-negative number` };
|
|
101
|
+
}
|
|
102
|
+
durationMs = Math.round(num);
|
|
103
|
+
}
|
|
104
|
+
|
|
105
|
+
// id: client-provided or generate
|
|
106
|
+
const id = typeof raw.id === 'string' && raw.id.trim() !== ''
|
|
107
|
+
? raw.id.trim()
|
|
108
|
+
: `obs_${randomUUID().replace(/-/g, '').slice(0, 16)}`;
|
|
109
|
+
|
|
110
|
+
const toCleanString = (val: unknown): string | null =>
|
|
111
|
+
typeof val === 'string' && val.trim() !== '' ? val.trim() : null;
|
|
112
|
+
|
|
113
|
+
// Optional string fields
|
|
114
|
+
const noteRef = toCleanString(raw.note_ref ?? raw.noteRef);
|
|
115
|
+
const taskRef = toCleanString(raw.task_ref ?? raw.taskRef);
|
|
116
|
+
const sessionId = toCleanString(raw.session_id ?? raw.sessionId);
|
|
117
|
+
const agent = toCleanString(raw.agent);
|
|
118
|
+
const toolName = toCleanString(raw.tool_name ?? raw.toolName);
|
|
119
|
+
const filePath = toCleanString(raw.file_path ?? raw.filePath);
|
|
120
|
+
|
|
121
|
+
// input / output stored whole (no truncation!), with known secret patterns redacted
|
|
122
|
+
const input = raw.input !== undefined && raw.input !== null ? redactOptional(String(raw.input)) : null;
|
|
123
|
+
const output = raw.output !== undefined && raw.output !== null ? redactOptional(String(raw.output)) : null;
|
|
124
|
+
|
|
125
|
+
const rawCreatedAt = raw.created_at ?? raw.createdAt;
|
|
126
|
+
const createdAt = typeof rawCreatedAt === 'number' && Number.isFinite(rawCreatedAt)
|
|
127
|
+
? Math.floor(rawCreatedAt)
|
|
128
|
+
: Math.floor(Date.now() / 1000);
|
|
129
|
+
|
|
130
|
+
return {
|
|
131
|
+
valid: true,
|
|
132
|
+
item: {
|
|
133
|
+
id,
|
|
134
|
+
scope,
|
|
135
|
+
projectId,
|
|
136
|
+
noteRef,
|
|
137
|
+
taskRef,
|
|
138
|
+
sessionId,
|
|
139
|
+
agent,
|
|
140
|
+
kind,
|
|
141
|
+
toolName,
|
|
142
|
+
filePath,
|
|
143
|
+
input,
|
|
144
|
+
output,
|
|
145
|
+
durationMs,
|
|
146
|
+
failed,
|
|
147
|
+
createdAt,
|
|
148
|
+
},
|
|
149
|
+
};
|
|
150
|
+
}
|
|
151
|
+
|
|
152
|
+
export function captureObservations(rawItems: unknown[]): CaptureResult {
|
|
153
|
+
if (!Array.isArray(rawItems)) {
|
|
154
|
+
throw new Error('captureObservations expects an array of observation items');
|
|
155
|
+
}
|
|
156
|
+
|
|
157
|
+
const validItems: Array<{ item: ValidatedObservation; index: number; raw: unknown }> = [];
|
|
158
|
+
const rejected: Array<{ index: number; reason: string; error: string }> = [];
|
|
159
|
+
|
|
160
|
+
rawItems.forEach((rawItem, index) => {
|
|
161
|
+
const res = validateObservationItem(rawItem, index);
|
|
162
|
+
if (res.valid) {
|
|
163
|
+
validItems.push({ item: res.item, index, raw: rawItem });
|
|
164
|
+
} else {
|
|
165
|
+
recordDeadLetter({
|
|
166
|
+
source: 'capture',
|
|
167
|
+
reason: 'schema_invalid',
|
|
168
|
+
producer: (rawItem as any)?.agent ?? null,
|
|
169
|
+
payload: rawItem,
|
|
170
|
+
});
|
|
171
|
+
rejected.push({
|
|
172
|
+
index,
|
|
173
|
+
reason: 'schema_invalid',
|
|
174
|
+
error: res.error,
|
|
175
|
+
});
|
|
176
|
+
}
|
|
177
|
+
});
|
|
178
|
+
|
|
179
|
+
const ids: string[] = [];
|
|
180
|
+
if (validItems.length > 0) {
|
|
181
|
+
const db = getDb();
|
|
182
|
+
const insertStmt = db.prepare(`
|
|
183
|
+
INSERT INTO observations (
|
|
184
|
+
id, scope, project_id, note_ref, task_ref, session_id, agent,
|
|
185
|
+
kind, tool_name, file_path, input, output, duration_ms, failed,
|
|
186
|
+
created_at
|
|
187
|
+
) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
|
|
188
|
+
`);
|
|
189
|
+
|
|
190
|
+
const reactivateSessionStmt = db.prepare(`
|
|
191
|
+
UPDATE sessions
|
|
192
|
+
SET status = 'active',
|
|
193
|
+
ended_at = NULL
|
|
194
|
+
WHERE id = ? AND status != 'active'
|
|
195
|
+
`);
|
|
196
|
+
|
|
197
|
+
// Nested transaction() calls run as SAVEPOINTs (src/lib/sqlite.ts).
|
|
198
|
+
// If insertSingle throws, its savepoint is rolled back without aborting the outer transaction.
|
|
199
|
+
const insertSingle = transaction(db, (entry: { item: ValidatedObservation; index: number; raw: unknown }) => {
|
|
200
|
+
const item = entry.item;
|
|
201
|
+
insertStmt.run(
|
|
202
|
+
item.id,
|
|
203
|
+
item.scope,
|
|
204
|
+
item.projectId,
|
|
205
|
+
item.noteRef,
|
|
206
|
+
item.taskRef,
|
|
207
|
+
item.sessionId,
|
|
208
|
+
item.agent,
|
|
209
|
+
item.kind,
|
|
210
|
+
item.toolName,
|
|
211
|
+
item.filePath,
|
|
212
|
+
item.input,
|
|
213
|
+
item.output,
|
|
214
|
+
item.durationMs,
|
|
215
|
+
item.failed,
|
|
216
|
+
item.createdAt
|
|
217
|
+
);
|
|
218
|
+
if (item.sessionId) {
|
|
219
|
+
reactivateSessionStmt.run(item.sessionId);
|
|
220
|
+
}
|
|
221
|
+
enqueueForEmbedding(item.id, 'observation');
|
|
222
|
+
});
|
|
223
|
+
|
|
224
|
+
const batchTx = transaction(db, () => {
|
|
225
|
+
for (const entry of validItems) {
|
|
226
|
+
try {
|
|
227
|
+
insertSingle(entry);
|
|
228
|
+
ids.push(entry.item.id);
|
|
229
|
+
} catch (err) {
|
|
230
|
+
const errMsg = err instanceof Error ? err.message : String(err);
|
|
231
|
+
recordDeadLetter({
|
|
232
|
+
source: 'capture',
|
|
233
|
+
reason: 'schema_invalid',
|
|
234
|
+
producer: entry.item.agent ?? null,
|
|
235
|
+
payload: entry.raw,
|
|
236
|
+
});
|
|
237
|
+
rejected.push({
|
|
238
|
+
index: entry.index,
|
|
239
|
+
reason: 'schema_invalid',
|
|
240
|
+
error: errMsg,
|
|
241
|
+
});
|
|
242
|
+
}
|
|
243
|
+
}
|
|
244
|
+
});
|
|
245
|
+
|
|
246
|
+
batchTx();
|
|
247
|
+
}
|
|
248
|
+
|
|
249
|
+
return {
|
|
250
|
+
accepted: ids.length,
|
|
251
|
+
ids,
|
|
252
|
+
rejected,
|
|
253
|
+
};
|
|
254
|
+
}
|
|
255
|
+
|
|
256
|
+
export function getObservation(id: string): ObservationRecord | undefined {
|
|
257
|
+
const db = getDb();
|
|
258
|
+
return db.prepare('SELECT * FROM observations WHERE id = ?').get(id) as ObservationRecord | undefined;
|
|
259
|
+
}
|
|
260
|
+
|
|
261
|
+
export function listObservations(filters?: {
|
|
262
|
+
projectId?: string;
|
|
263
|
+
scope?: string;
|
|
264
|
+
sessionId?: string;
|
|
265
|
+
failed?: number;
|
|
266
|
+
limit?: number;
|
|
267
|
+
offset?: number;
|
|
268
|
+
}): ObservationRecord[] {
|
|
269
|
+
const db = getDb();
|
|
270
|
+
const conditions: string[] = [];
|
|
271
|
+
const queryParams: unknown[] = [];
|
|
272
|
+
|
|
273
|
+
if (filters?.projectId) {
|
|
274
|
+
conditions.push('project_id = ?');
|
|
275
|
+
queryParams.push(filters.projectId);
|
|
276
|
+
}
|
|
277
|
+
if (filters?.scope) {
|
|
278
|
+
conditions.push('scope = ?');
|
|
279
|
+
queryParams.push(filters.scope);
|
|
280
|
+
}
|
|
281
|
+
if (filters?.sessionId) {
|
|
282
|
+
conditions.push('session_id = ?');
|
|
283
|
+
queryParams.push(filters.sessionId);
|
|
284
|
+
}
|
|
285
|
+
if (filters?.failed !== undefined) {
|
|
286
|
+
conditions.push('failed = ?');
|
|
287
|
+
queryParams.push(filters.failed ? 1 : 0);
|
|
288
|
+
}
|
|
289
|
+
|
|
290
|
+
const whereClause = conditions.length > 0 ? `WHERE ${conditions.join(' AND ')}` : '';
|
|
291
|
+
const limit = filters?.limit ?? 50;
|
|
292
|
+
const offset = filters?.offset ?? 0;
|
|
293
|
+
queryParams.push(limit, offset);
|
|
294
|
+
|
|
295
|
+
return db
|
|
296
|
+
.prepare(`
|
|
297
|
+
SELECT * FROM observations
|
|
298
|
+
${whereClause}
|
|
299
|
+
ORDER BY created_at DESC
|
|
300
|
+
LIMIT ? OFFSET ?
|
|
301
|
+
`)
|
|
302
|
+
.all(...queryParams) as ObservationRecord[];
|
|
303
|
+
}
|