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,147 @@
|
|
|
1
|
+
import { getDb } from '../lib/db';
|
|
2
|
+
import { logger } from '../lib/logger';
|
|
3
|
+
import { normalizeProjectId } from '../lib/scope';
|
|
4
|
+
import { getQdrantClient } from '../learning/embedWorker';
|
|
5
|
+
import { getStoreMeta } from '../learning/storeMeta';
|
|
6
|
+
import { transaction } from '../lib/sqlite';
|
|
7
|
+
|
|
8
|
+
export interface RenameProjectResult {
|
|
9
|
+
from_project_id: string;
|
|
10
|
+
to_project_id: string;
|
|
11
|
+
updated_counts: Record<string, number>;
|
|
12
|
+
total_updated: number;
|
|
13
|
+
qdrant_updated: boolean;
|
|
14
|
+
qdrant_error?: string;
|
|
15
|
+
}
|
|
16
|
+
|
|
17
|
+
const STANDARD_PROJECT_TABLES = [
|
|
18
|
+
'notes',
|
|
19
|
+
'trajectories',
|
|
20
|
+
'trajectory_archive',
|
|
21
|
+
'observations',
|
|
22
|
+
'observations_archive',
|
|
23
|
+
'sessions',
|
|
24
|
+
'actions',
|
|
25
|
+
'summaries',
|
|
26
|
+
'consolidation_leases',
|
|
27
|
+
] as const;
|
|
28
|
+
|
|
29
|
+
/**
|
|
30
|
+
* Atomically renames `project_id` across all SQLite tables (merging conflicting
|
|
31
|
+
* failure_patterns counts) and updates matching Qdrant vector payloads if active.
|
|
32
|
+
*/
|
|
33
|
+
export async function renameProject(
|
|
34
|
+
rawFromProjectId: string,
|
|
35
|
+
rawToProjectId: string
|
|
36
|
+
): Promise<RenameProjectResult> {
|
|
37
|
+
const fromNorm = normalizeProjectId(rawFromProjectId);
|
|
38
|
+
if (!fromNorm.ok) {
|
|
39
|
+
throw new Error(`Invalid from_project_id: ${fromNorm.error}`);
|
|
40
|
+
}
|
|
41
|
+
const toNorm = normalizeProjectId(rawToProjectId);
|
|
42
|
+
if (!toNorm.ok) {
|
|
43
|
+
throw new Error(`Invalid to_project_id: ${toNorm.error}`);
|
|
44
|
+
}
|
|
45
|
+
|
|
46
|
+
const fromId = fromNorm.projectId;
|
|
47
|
+
const toId = toNorm.projectId;
|
|
48
|
+
if (fromId === toId) {
|
|
49
|
+
throw new Error('from_project_id and to_project_id must be different');
|
|
50
|
+
}
|
|
51
|
+
|
|
52
|
+
const db = getDb();
|
|
53
|
+
const updatedCounts: Record<string, number> = {};
|
|
54
|
+
|
|
55
|
+
const tx = transaction(db, () => {
|
|
56
|
+
for (const table of STANDARD_PROJECT_TABLES) {
|
|
57
|
+
const info = db
|
|
58
|
+
.prepare(`UPDATE ${table} SET project_id = ? WHERE project_id = ?`)
|
|
59
|
+
.run(toId, fromId);
|
|
60
|
+
updatedCounts[table] = info.changes;
|
|
61
|
+
}
|
|
62
|
+
|
|
63
|
+
// failure_patterns has UNIQUE(project_id, task_type, error_text), so merge counts on conflict
|
|
64
|
+
const fpRows = db
|
|
65
|
+
.prepare(
|
|
66
|
+
`SELECT id, scope, task_type, error_text, count, last_seen_at
|
|
67
|
+
FROM failure_patterns
|
|
68
|
+
WHERE project_id = ?`
|
|
69
|
+
)
|
|
70
|
+
.all(fromId) as Array<{
|
|
71
|
+
id: string;
|
|
72
|
+
scope: string;
|
|
73
|
+
task_type: string;
|
|
74
|
+
error_text: string;
|
|
75
|
+
count: number;
|
|
76
|
+
last_seen_at: number;
|
|
77
|
+
}>;
|
|
78
|
+
|
|
79
|
+
const findExistingFp = db.prepare(
|
|
80
|
+
`SELECT id FROM failure_patterns
|
|
81
|
+
WHERE project_id = ? AND task_type = ? AND error_text = ?`
|
|
82
|
+
);
|
|
83
|
+
const mergeExistingFp = db.prepare(
|
|
84
|
+
`UPDATE failure_patterns
|
|
85
|
+
SET count = count + ?, last_seen_at = MAX(last_seen_at, ?)
|
|
86
|
+
WHERE id = ?`
|
|
87
|
+
);
|
|
88
|
+
const deleteFpById = db.prepare(`DELETE FROM failure_patterns WHERE id = ?`);
|
|
89
|
+
const renameFpById = db.prepare(`UPDATE failure_patterns SET project_id = ? WHERE id = ?`);
|
|
90
|
+
|
|
91
|
+
for (const row of fpRows) {
|
|
92
|
+
const existing = findExistingFp.get(toId, row.task_type, row.error_text) as
|
|
93
|
+
| { id: string }
|
|
94
|
+
| undefined;
|
|
95
|
+
if (existing) {
|
|
96
|
+
mergeExistingFp.run(row.count, row.last_seen_at, existing.id);
|
|
97
|
+
deleteFpById.run(row.id);
|
|
98
|
+
} else {
|
|
99
|
+
renameFpById.run(toId, row.id);
|
|
100
|
+
}
|
|
101
|
+
}
|
|
102
|
+
|
|
103
|
+
updatedCounts.failure_patterns = fpRows.length;
|
|
104
|
+
});
|
|
105
|
+
|
|
106
|
+
tx();
|
|
107
|
+
|
|
108
|
+
const totalUpdated = Object.values(updatedCounts).reduce((sum, n) => sum + n, 0);
|
|
109
|
+
|
|
110
|
+
let qdrantUpdated = false;
|
|
111
|
+
let qdrantError: string | undefined;
|
|
112
|
+
|
|
113
|
+
const qdrant = getQdrantClient();
|
|
114
|
+
if (qdrant) {
|
|
115
|
+
const collection = getStoreMeta()?.qdrant_alias || 'brain';
|
|
116
|
+
try {
|
|
117
|
+
await qdrant.setPayload(collection, {
|
|
118
|
+
payload: { project_id: toId },
|
|
119
|
+
filter: {
|
|
120
|
+
must: [{ key: 'project_id', match: { value: fromId } }],
|
|
121
|
+
},
|
|
122
|
+
wait: true,
|
|
123
|
+
});
|
|
124
|
+
qdrantUpdated = true;
|
|
125
|
+
} catch (err: any) {
|
|
126
|
+
qdrantError = err?.message || String(err);
|
|
127
|
+
logger.warn(
|
|
128
|
+
{ collection, fromId, toId, error: qdrantError },
|
|
129
|
+
'Qdrant setPayload failed during renameProject'
|
|
130
|
+
);
|
|
131
|
+
}
|
|
132
|
+
}
|
|
133
|
+
|
|
134
|
+
logger.info(
|
|
135
|
+
{ from_project_id: fromId, to_project_id: toId, total_updated: totalUpdated, qdrant_updated: qdrantUpdated },
|
|
136
|
+
'project_id rename complete'
|
|
137
|
+
);
|
|
138
|
+
|
|
139
|
+
return {
|
|
140
|
+
from_project_id: fromId,
|
|
141
|
+
to_project_id: toId,
|
|
142
|
+
updated_counts: updatedCounts,
|
|
143
|
+
total_updated: totalUpdated,
|
|
144
|
+
qdrant_updated: qdrantUpdated,
|
|
145
|
+
...(qdrantError ? { qdrant_error: qdrantError } : {}),
|
|
146
|
+
};
|
|
147
|
+
}
|
|
@@ -0,0 +1,309 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The idle-session rollup sweeper.
|
|
3
|
+
*
|
|
4
|
+
* A trajectory is normally produced when a client finishes a task and posts
|
|
5
|
+
* the observation ids it wants rolled up. A client that crashes, is killed, or
|
|
6
|
+
* simply never reaches that call sends no such signal — and its observations
|
|
7
|
+
* then sit in the store until the 90-day delete without ever becoming a
|
|
8
|
+
* trajectory. They were captured and then wasted: never part of a failure
|
|
9
|
+
* pattern, never part of a prior outcome, never injected at task start. The
|
|
10
|
+
* write was accepted and then thrown away, which is the failure class this
|
|
11
|
+
* project exists to remove.
|
|
12
|
+
*
|
|
13
|
+
* This is the safety net alongside that explicit path, not a replacement for
|
|
14
|
+
* it. Three properties matter:
|
|
15
|
+
*
|
|
16
|
+
* 1. **Arithmetic only** (rule 1). Counts, sums, a first prompt and a mode.
|
|
17
|
+
* No model is called here, directly or indirectly.
|
|
18
|
+
* 2. **It never invents an outcome.** A swept rollup's `success` is NULL —
|
|
19
|
+
* unknown — unless a source observation records a failure (0) or records
|
|
20
|
+
* completion (1). See `deriveSuccess` in trajectoryStore.
|
|
21
|
+
* 3. **Idempotent.** The candidate query selects sessions with no trajectory,
|
|
22
|
+
* so a second run finds nothing to do.
|
|
23
|
+
*/
|
|
24
|
+
import { getDb } from '../lib/db';
|
|
25
|
+
import { logger } from '../lib/logger';
|
|
26
|
+
import { resolveScope } from '../lib/scope';
|
|
27
|
+
import { logTrajectory } from './trajectoryStore';
|
|
28
|
+
import { endSession } from './sessionStore';
|
|
29
|
+
|
|
30
|
+
export const DEFAULT_IDLE_MINUTES = 30;
|
|
31
|
+
|
|
32
|
+
export interface SweepOptions {
|
|
33
|
+
/** A session is idle when its newest observation is older than this. */
|
|
34
|
+
idleMinutes?: number;
|
|
35
|
+
/** Cap on sessions rolled up in one pass. */
|
|
36
|
+
limit?: number;
|
|
37
|
+
/** Test seam: treat this unix timestamp as "now". */
|
|
38
|
+
now?: number;
|
|
39
|
+
}
|
|
40
|
+
|
|
41
|
+
export interface SweptSession {
|
|
42
|
+
session_id: string;
|
|
43
|
+
trajectory_id: string;
|
|
44
|
+
observation_count: number;
|
|
45
|
+
tool_calls: number;
|
|
46
|
+
duration_ms: number;
|
|
47
|
+
scope: string;
|
|
48
|
+
project_id: string | null;
|
|
49
|
+
success: 0 | 1 | null;
|
|
50
|
+
}
|
|
51
|
+
|
|
52
|
+
export interface SweepResult {
|
|
53
|
+
idle_minutes: number;
|
|
54
|
+
cutoff: number;
|
|
55
|
+
candidates: number;
|
|
56
|
+
swept: number;
|
|
57
|
+
skipped: number;
|
|
58
|
+
sessions: SweptSession[];
|
|
59
|
+
}
|
|
60
|
+
|
|
61
|
+
interface CandidateRow {
|
|
62
|
+
session_id: string;
|
|
63
|
+
last_seen: number;
|
|
64
|
+
obs_count: number;
|
|
65
|
+
}
|
|
66
|
+
|
|
67
|
+
interface SourceRow {
|
|
68
|
+
id: string;
|
|
69
|
+
scope: string;
|
|
70
|
+
project_id: string | null;
|
|
71
|
+
agent: string | null;
|
|
72
|
+
kind: string;
|
|
73
|
+
tool_name: string | null;
|
|
74
|
+
input: string | null;
|
|
75
|
+
output: string | null;
|
|
76
|
+
duration_ms: number;
|
|
77
|
+
failed: number;
|
|
78
|
+
created_at: number;
|
|
79
|
+
}
|
|
80
|
+
|
|
81
|
+
export function resolveIdleMinutes(override?: number): number {
|
|
82
|
+
if (override !== undefined && Number.isFinite(override) && override >= 0) {
|
|
83
|
+
return Math.floor(override);
|
|
84
|
+
}
|
|
85
|
+
const configured = parseInt(process.env.BRAIN_ROLLUP_IDLE_MINUTES || '', 10);
|
|
86
|
+
if (Number.isFinite(configured) && configured >= 0) return configured;
|
|
87
|
+
return DEFAULT_IDLE_MINUTES;
|
|
88
|
+
}
|
|
89
|
+
|
|
90
|
+
/** The most frequent value in `values`, counting null as its own value. */
|
|
91
|
+
function modeOf<T extends string | null>(values: T[]): T | undefined {
|
|
92
|
+
const counts = new Map<string, { value: T; count: number }>();
|
|
93
|
+
for (const value of values) {
|
|
94
|
+
const key = value === null ? '\u0000null' : `v:${value}`;
|
|
95
|
+
const entry = counts.get(key);
|
|
96
|
+
if (entry) entry.count++;
|
|
97
|
+
else counts.set(key, { value, count: 1 });
|
|
98
|
+
}
|
|
99
|
+
let best: { value: T; count: number } | undefined;
|
|
100
|
+
for (const entry of counts.values()) {
|
|
101
|
+
if (!best || entry.count > best.count) best = entry;
|
|
102
|
+
}
|
|
103
|
+
return best?.value;
|
|
104
|
+
}
|
|
105
|
+
|
|
106
|
+
/**
|
|
107
|
+
* Roll up every idle session that has no trajectory yet.
|
|
108
|
+
*
|
|
109
|
+
* Safe to call repeatedly and from an interval: the second pass sees the
|
|
110
|
+
* trajectories the first one wrote and selects nothing.
|
|
111
|
+
*/
|
|
112
|
+
export function sweepIdleSessions(options?: SweepOptions): SweepResult {
|
|
113
|
+
const db = getDb();
|
|
114
|
+
const idleMinutes = resolveIdleMinutes(options?.idleMinutes);
|
|
115
|
+
const now = options?.now ?? Math.floor(Date.now() / 1000);
|
|
116
|
+
const cutoff = now - idleMinutes * 60;
|
|
117
|
+
const limit = Math.max(1, Math.floor(options?.limit ?? 200));
|
|
118
|
+
|
|
119
|
+
// Candidate sessions: idle, and not already rolled up. The NOT EXISTS is
|
|
120
|
+
// what makes this re-runnable — it covers both the signalled rollups a
|
|
121
|
+
// client posted and the swept ones an earlier pass wrote.
|
|
122
|
+
// Inspects both observations and observations_archive so sessions unrolled
|
|
123
|
+
// past 30 days can still be swept.
|
|
124
|
+
const candidates = db
|
|
125
|
+
.prepare(
|
|
126
|
+
`
|
|
127
|
+
WITH all_obs AS (
|
|
128
|
+
SELECT session_id, created_at FROM observations WHERE session_id IS NOT NULL
|
|
129
|
+
UNION ALL
|
|
130
|
+
SELECT session_id, created_at FROM observations_archive WHERE session_id IS NOT NULL
|
|
131
|
+
)
|
|
132
|
+
SELECT o.session_id AS session_id,
|
|
133
|
+
MAX(o.created_at) AS last_seen,
|
|
134
|
+
COUNT(*) AS obs_count
|
|
135
|
+
FROM all_obs o
|
|
136
|
+
WHERE NOT EXISTS (
|
|
137
|
+
SELECT 1 FROM trajectories t WHERE t.session_id = o.session_id
|
|
138
|
+
)
|
|
139
|
+
AND NOT EXISTS (
|
|
140
|
+
SELECT 1 FROM trajectory_archive ta WHERE ta.session_id = o.session_id
|
|
141
|
+
)
|
|
142
|
+
GROUP BY o.session_id
|
|
143
|
+
HAVING MAX(o.created_at) <= ?
|
|
144
|
+
ORDER BY last_seen ASC
|
|
145
|
+
LIMIT ?
|
|
146
|
+
`
|
|
147
|
+
)
|
|
148
|
+
.all(cutoff, limit) as CandidateRow[];
|
|
149
|
+
|
|
150
|
+
const sessions: SweptSession[] = [];
|
|
151
|
+
let skipped = 0;
|
|
152
|
+
|
|
153
|
+
for (const candidate of candidates) {
|
|
154
|
+
const rows = db
|
|
155
|
+
.prepare(
|
|
156
|
+
`
|
|
157
|
+
SELECT id, scope, project_id, agent, kind, tool_name, input, output,
|
|
158
|
+
duration_ms, failed, created_at
|
|
159
|
+
FROM (
|
|
160
|
+
SELECT id, scope, project_id, agent, kind, tool_name, input, output,
|
|
161
|
+
duration_ms, failed, created_at
|
|
162
|
+
FROM observations
|
|
163
|
+
WHERE session_id = ?
|
|
164
|
+
UNION ALL
|
|
165
|
+
SELECT original_observation_id AS id, scope, project_id, agent, kind, tool_name, input, output,
|
|
166
|
+
duration_ms, failed, created_at
|
|
167
|
+
FROM observations_archive
|
|
168
|
+
WHERE session_id = ?
|
|
169
|
+
)
|
|
170
|
+
ORDER BY created_at ASC, id ASC
|
|
171
|
+
`
|
|
172
|
+
)
|
|
173
|
+
.all(candidate.session_id, candidate.session_id) as SourceRow[];
|
|
174
|
+
|
|
175
|
+
if (rows.length === 0) {
|
|
176
|
+
skipped++;
|
|
177
|
+
continue;
|
|
178
|
+
}
|
|
179
|
+
|
|
180
|
+
// Scope and project_id are carried from the sources, never invented. When
|
|
181
|
+
// the sources disagree the most common pair wins; the pair is kept
|
|
182
|
+
// together because scope and project_id are only valid as a pair, and it
|
|
183
|
+
// is validated through the shared helper rather than trusted.
|
|
184
|
+
const scopeMode = modeOf(rows.map((r) => r.scope)) ?? 'unknown';
|
|
185
|
+
const projectMode =
|
|
186
|
+
modeOf(rows.filter((r) => r.scope === scopeMode).map((r) => r.project_id)) ?? null;
|
|
187
|
+
|
|
188
|
+
const scoped = resolveScope(scopeMode, scopeMode === 'project' ? projectMode : null);
|
|
189
|
+
if (!scoped.ok) {
|
|
190
|
+
// Only reachable if a stored row's scope pair is already invalid. Say so
|
|
191
|
+
// rather than guessing a scope for it.
|
|
192
|
+
logger.error(
|
|
193
|
+
{ sessionId: candidate.session_id, scope: scopeMode, projectId: projectMode, error: scoped.error },
|
|
194
|
+
'rollup sweep: refusing to roll up a session whose observations have an invalid scope'
|
|
195
|
+
);
|
|
196
|
+
skipped++;
|
|
197
|
+
continue;
|
|
198
|
+
}
|
|
199
|
+
|
|
200
|
+
const durationMs = rows.reduce((sum, r) => sum + (r.duration_ms || 0), 0);
|
|
201
|
+
const toolCalls = rows.filter((r) => r.kind === 'tool_call').length;
|
|
202
|
+
|
|
203
|
+
let trajectoryId: string;
|
|
204
|
+
try {
|
|
205
|
+
trajectoryId = logTrajectory({
|
|
206
|
+
scope: scoped.scope,
|
|
207
|
+
projectId: scoped.projectId,
|
|
208
|
+
sessionId: candidate.session_id,
|
|
209
|
+
agent: modeOf(rows.map((r) => r.agent)) ?? null,
|
|
210
|
+
// taskType is not derivable from observations, and guessing one would
|
|
211
|
+
// pollute the failure-pattern grouping key.
|
|
212
|
+
taskType: 'unknown',
|
|
213
|
+
rollupSource: 'swept',
|
|
214
|
+
observationIds: rows.map((r) => r.id),
|
|
215
|
+
preFetchedObservations: rows,
|
|
216
|
+
toolCalls,
|
|
217
|
+
durationMs,
|
|
218
|
+
// success is deliberately omitted: trajectoryStore derives it from the
|
|
219
|
+
// cited rows under the 'swept' contract, which yields NULL (unknown)
|
|
220
|
+
// unless a source row recorded a failure or a completion.
|
|
221
|
+
// The attempt happened when its observations happened, not when the
|
|
222
|
+
// sweeper noticed, so retention sees it in the right place in time.
|
|
223
|
+
createdAt: rows[rows.length - 1].created_at,
|
|
224
|
+
});
|
|
225
|
+
} catch (err) {
|
|
226
|
+
logger.error(
|
|
227
|
+
{
|
|
228
|
+
sessionId: candidate.session_id,
|
|
229
|
+
error: err instanceof Error ? err.message : String(err),
|
|
230
|
+
},
|
|
231
|
+
'rollup sweep: failed to roll up session'
|
|
232
|
+
);
|
|
233
|
+
skipped++;
|
|
234
|
+
continue;
|
|
235
|
+
}
|
|
236
|
+
|
|
237
|
+
const stored = db
|
|
238
|
+
.prepare('SELECT success FROM trajectories WHERE id = ?')
|
|
239
|
+
.get(trajectoryId) as { success: 0 | 1 | null } | undefined;
|
|
240
|
+
|
|
241
|
+
sessions.push({
|
|
242
|
+
session_id: candidate.session_id,
|
|
243
|
+
trajectory_id: trajectoryId,
|
|
244
|
+
observation_count: rows.length,
|
|
245
|
+
tool_calls: toolCalls,
|
|
246
|
+
duration_ms: durationMs,
|
|
247
|
+
scope: scoped.scope,
|
|
248
|
+
project_id: scoped.projectId,
|
|
249
|
+
success: stored?.success ?? null,
|
|
250
|
+
});
|
|
251
|
+
}
|
|
252
|
+
|
|
253
|
+
// Close any 'active' sessions whose latest activity is at or before cutoff
|
|
254
|
+
const idleActiveSessions = db
|
|
255
|
+
.prepare(
|
|
256
|
+
`
|
|
257
|
+
SELECT s.id
|
|
258
|
+
FROM sessions s
|
|
259
|
+
WHERE s.status = 'active'
|
|
260
|
+
AND COALESCE(
|
|
261
|
+
(
|
|
262
|
+
SELECT MAX(created_at)
|
|
263
|
+
FROM (
|
|
264
|
+
SELECT created_at FROM observations WHERE session_id = s.id
|
|
265
|
+
UNION ALL
|
|
266
|
+
SELECT created_at FROM observations_archive WHERE session_id = s.id
|
|
267
|
+
)
|
|
268
|
+
),
|
|
269
|
+
CAST(strftime('%s', s.started_at) AS INTEGER)
|
|
270
|
+
) <= ?
|
|
271
|
+
LIMIT ?
|
|
272
|
+
`
|
|
273
|
+
)
|
|
274
|
+
.all(cutoff, limit) as Array<{ id: string }>;
|
|
275
|
+
|
|
276
|
+
for (const row of idleActiveSessions) {
|
|
277
|
+
try {
|
|
278
|
+
endSession(row.id, { status: 'completed' });
|
|
279
|
+
} catch (err) {
|
|
280
|
+
logger.warn(
|
|
281
|
+
{
|
|
282
|
+
sessionId: row.id,
|
|
283
|
+
error: err instanceof Error ? err.message : String(err),
|
|
284
|
+
},
|
|
285
|
+
'rollup sweep: failed to close idle active session'
|
|
286
|
+
);
|
|
287
|
+
}
|
|
288
|
+
}
|
|
289
|
+
|
|
290
|
+
const result: SweepResult = {
|
|
291
|
+
idle_minutes: idleMinutes,
|
|
292
|
+
cutoff,
|
|
293
|
+
candidates: candidates.length,
|
|
294
|
+
swept: sessions.length,
|
|
295
|
+
skipped,
|
|
296
|
+
sessions,
|
|
297
|
+
};
|
|
298
|
+
|
|
299
|
+
if (result.swept > 0 || result.skipped > 0) {
|
|
300
|
+
logger.info(
|
|
301
|
+
{ idleMinutes, candidates: result.candidates, swept: result.swept, skipped: result.skipped },
|
|
302
|
+
'rollup sweep complete'
|
|
303
|
+
);
|
|
304
|
+
} else {
|
|
305
|
+
logger.debug({ idleMinutes }, 'rollup sweep found no idle sessions');
|
|
306
|
+
}
|
|
307
|
+
|
|
308
|
+
return result;
|
|
309
|
+
}
|