neuralbrain 0.0.0-stage → 0.0.2
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 +107 -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,219 @@
|
|
|
1
|
+
import { randomUUID } from 'crypto';
|
|
2
|
+
import { getDb } from '../lib/db';
|
|
3
|
+
import { logger } from '../lib/logger';
|
|
4
|
+
import type { ObservationRecord } from '../memory/observationStore';
|
|
5
|
+
import { transaction } from '../lib/sqlite';
|
|
6
|
+
|
|
7
|
+
export interface ConsolidationCandidate {
|
|
8
|
+
lease_id: string;
|
|
9
|
+
kind: string;
|
|
10
|
+
scope: string;
|
|
11
|
+
project_id: string | null;
|
|
12
|
+
session_id: string;
|
|
13
|
+
observation_ids: string[];
|
|
14
|
+
observations: ObservationRecord[];
|
|
15
|
+
expires_at: number;
|
|
16
|
+
}
|
|
17
|
+
|
|
18
|
+
export function getConsolidationCandidates(params?: {
|
|
19
|
+
projectId?: string;
|
|
20
|
+
limit?: number;
|
|
21
|
+
leaseDurationSec?: number;
|
|
22
|
+
}): { candidates: ConsolidationCandidate[] } {
|
|
23
|
+
const db = getDb();
|
|
24
|
+
const limit = Math.max(params?.limit ?? 5, 1);
|
|
25
|
+
const leaseDurationSec = Math.max(params?.leaseDurationSec ?? 300, 30);
|
|
26
|
+
const now = Math.floor(Date.now() / 1000);
|
|
27
|
+
|
|
28
|
+
return transaction(db, () => {
|
|
29
|
+
// Find candidate sessions
|
|
30
|
+
let query = `
|
|
31
|
+
SELECT session_id, scope, project_id, COUNT(*) as obs_count, MIN(created_at) as first_seen
|
|
32
|
+
FROM observations o
|
|
33
|
+
WHERE session_id IS NOT NULL
|
|
34
|
+
AND NOT EXISTS (
|
|
35
|
+
SELECT 1 FROM consolidation_leases cl
|
|
36
|
+
WHERE cl.session_id = o.session_id
|
|
37
|
+
AND cl.completed_at IS NULL
|
|
38
|
+
AND cl.expires_at > ?
|
|
39
|
+
)
|
|
40
|
+
AND NOT EXISTS (
|
|
41
|
+
SELECT 1 FROM summary_sources ss
|
|
42
|
+
JOIN summaries s ON ss.summary_id = s.id
|
|
43
|
+
WHERE ss.record_id = o.id AND s.verified = 1
|
|
44
|
+
)
|
|
45
|
+
`;
|
|
46
|
+
const queryParams: unknown[] = [now];
|
|
47
|
+
|
|
48
|
+
if (params?.projectId) {
|
|
49
|
+
query += ` AND project_id = ?`;
|
|
50
|
+
queryParams.push(params.projectId.trim());
|
|
51
|
+
}
|
|
52
|
+
|
|
53
|
+
query += `
|
|
54
|
+
GROUP BY session_id, scope, project_id
|
|
55
|
+
ORDER BY first_seen ASC
|
|
56
|
+
LIMIT ?
|
|
57
|
+
`;
|
|
58
|
+
queryParams.push(limit);
|
|
59
|
+
|
|
60
|
+
const candidateSessions = db.prepare(query).all(...queryParams) as Array<{
|
|
61
|
+
session_id: string;
|
|
62
|
+
scope: string;
|
|
63
|
+
project_id: string | null;
|
|
64
|
+
obs_count: number;
|
|
65
|
+
}>;
|
|
66
|
+
|
|
67
|
+
const candidates: ConsolidationCandidate[] = [];
|
|
68
|
+
|
|
69
|
+
for (const sess of candidateSessions) {
|
|
70
|
+
const obsRows = db
|
|
71
|
+
.prepare(`
|
|
72
|
+
SELECT * FROM observations
|
|
73
|
+
WHERE session_id = ?
|
|
74
|
+
ORDER BY created_at ASC
|
|
75
|
+
`)
|
|
76
|
+
.all(sess.session_id) as ObservationRecord[];
|
|
77
|
+
|
|
78
|
+
if (obsRows.length === 0) continue;
|
|
79
|
+
|
|
80
|
+
const leaseId = `l-${randomUUID()}`;
|
|
81
|
+
const obsIds = obsRows.map((o) => o.id);
|
|
82
|
+
const expiresAt = now + leaseDurationSec;
|
|
83
|
+
|
|
84
|
+
try {
|
|
85
|
+
db.prepare(`
|
|
86
|
+
INSERT INTO consolidation_leases (
|
|
87
|
+
lease_id, kind, scope, project_id, session_id, observation_ids, created_at, expires_at, completed_at
|
|
88
|
+
) VALUES (?, 'session', ?, ?, ?, ?, ?, ?, NULL)
|
|
89
|
+
`).run(
|
|
90
|
+
leaseId,
|
|
91
|
+
sess.scope,
|
|
92
|
+
sess.project_id,
|
|
93
|
+
sess.session_id,
|
|
94
|
+
JSON.stringify(obsIds),
|
|
95
|
+
now,
|
|
96
|
+
expiresAt
|
|
97
|
+
);
|
|
98
|
+
|
|
99
|
+
candidates.push({
|
|
100
|
+
lease_id: leaseId,
|
|
101
|
+
kind: 'session',
|
|
102
|
+
scope: sess.scope,
|
|
103
|
+
project_id: sess.project_id,
|
|
104
|
+
session_id: sess.session_id,
|
|
105
|
+
observation_ids: obsIds,
|
|
106
|
+
observations: obsRows,
|
|
107
|
+
expires_at: expiresAt,
|
|
108
|
+
});
|
|
109
|
+
} catch (err) {
|
|
110
|
+
logger.error(
|
|
111
|
+
{ leaseId, sessionId: sess.session_id, error: err instanceof Error ? err.message : String(err) },
|
|
112
|
+
'failed to create consolidation lease'
|
|
113
|
+
);
|
|
114
|
+
}
|
|
115
|
+
}
|
|
116
|
+
|
|
117
|
+
return { candidates };
|
|
118
|
+
})();
|
|
119
|
+
}
|
|
120
|
+
|
|
121
|
+
export interface ConsolidationStatus {
|
|
122
|
+
unconsolidated_sessions: number;
|
|
123
|
+
unconsolidated_observations: number;
|
|
124
|
+
oldest_unconsolidated_at: number | null;
|
|
125
|
+
last_consolidated_at: number | null;
|
|
126
|
+
}
|
|
127
|
+
|
|
128
|
+
const CONSOLIDATION_SESSION_THRESHOLD = 3;
|
|
129
|
+
const CONSOLIDATION_OBS_THRESHOLD = 50;
|
|
130
|
+
const CONSOLIDATION_STALE_SECONDS = 3 * 86400;
|
|
131
|
+
|
|
132
|
+
/**
|
|
133
|
+
* Computes un-consolidated observation/session counts and last verified summary timestamp.
|
|
134
|
+
*/
|
|
135
|
+
export function getConsolidationStatus(projectId?: string): ConsolidationStatus {
|
|
136
|
+
const db = getDb();
|
|
137
|
+
const trimmedProject = projectId?.trim() || undefined;
|
|
138
|
+
|
|
139
|
+
let obsSql = `
|
|
140
|
+
SELECT COUNT(DISTINCT o.session_id) AS session_count,
|
|
141
|
+
COUNT(*) AS obs_count,
|
|
142
|
+
MIN(o.created_at) AS oldest_at
|
|
143
|
+
FROM observations o
|
|
144
|
+
WHERE o.session_id IS NOT NULL
|
|
145
|
+
AND NOT EXISTS (
|
|
146
|
+
SELECT 1 FROM summary_sources ss
|
|
147
|
+
JOIN summaries s ON ss.summary_id = s.id
|
|
148
|
+
WHERE ss.record_id = o.id AND s.verified = 1
|
|
149
|
+
)
|
|
150
|
+
`;
|
|
151
|
+
const obsParams: unknown[] = [];
|
|
152
|
+
if (trimmedProject) {
|
|
153
|
+
obsSql += ` AND o.project_id = ?`;
|
|
154
|
+
obsParams.push(trimmedProject);
|
|
155
|
+
}
|
|
156
|
+
|
|
157
|
+
const obsRow = db.prepare(obsSql).get(...obsParams) as {
|
|
158
|
+
session_count: number;
|
|
159
|
+
obs_count: number;
|
|
160
|
+
oldest_at: number | null;
|
|
161
|
+
};
|
|
162
|
+
|
|
163
|
+
let sumSql = `SELECT MAX(created_at) AS last_at FROM summaries WHERE verified = 1`;
|
|
164
|
+
const sumParams: unknown[] = [];
|
|
165
|
+
if (trimmedProject) {
|
|
166
|
+
sumSql += ` AND project_id = ?`;
|
|
167
|
+
sumParams.push(trimmedProject);
|
|
168
|
+
}
|
|
169
|
+
|
|
170
|
+
const sumRow = db.prepare(sumSql).get(...sumParams) as { last_at: number | null };
|
|
171
|
+
|
|
172
|
+
return {
|
|
173
|
+
unconsolidated_sessions: obsRow?.session_count ?? 0,
|
|
174
|
+
unconsolidated_observations: obsRow?.obs_count ?? 0,
|
|
175
|
+
oldest_unconsolidated_at: obsRow?.oldest_at ?? null,
|
|
176
|
+
last_consolidated_at: sumRow?.last_at ?? null,
|
|
177
|
+
};
|
|
178
|
+
}
|
|
179
|
+
|
|
180
|
+
/**
|
|
181
|
+
* Returns a SessionStart /inject reminder when un-consolidated observations have
|
|
182
|
+
* accumulated or gone stale, or null if consolidation is up to date.
|
|
183
|
+
*/
|
|
184
|
+
export function formatConsolidationWarning(
|
|
185
|
+
status: ConsolidationStatus,
|
|
186
|
+
projectId?: string,
|
|
187
|
+
nowSec?: number
|
|
188
|
+
): string | null {
|
|
189
|
+
const { unconsolidated_sessions, unconsolidated_observations, oldest_unconsolidated_at, last_consolidated_at } =
|
|
190
|
+
status;
|
|
191
|
+
if (unconsolidated_sessions <= 0 || unconsolidated_observations <= 0) {
|
|
192
|
+
return null;
|
|
193
|
+
}
|
|
194
|
+
|
|
195
|
+
const now = nowSec ?? Math.floor(Date.now() / 1000);
|
|
196
|
+
const isStale =
|
|
197
|
+
oldest_unconsolidated_at !== null && now - oldest_unconsolidated_at >= CONSOLIDATION_STALE_SECONDS;
|
|
198
|
+
|
|
199
|
+
if (
|
|
200
|
+
unconsolidated_sessions < CONSOLIDATION_SESSION_THRESHOLD &&
|
|
201
|
+
unconsolidated_observations < CONSOLIDATION_OBS_THRESHOLD &&
|
|
202
|
+
!isStale
|
|
203
|
+
) {
|
|
204
|
+
return null;
|
|
205
|
+
}
|
|
206
|
+
|
|
207
|
+
const target = projectId?.trim() ? `project '${projectId.trim()}'` : 'this workspace';
|
|
208
|
+
let lastDesc = 'never';
|
|
209
|
+
if (last_consolidated_at !== null) {
|
|
210
|
+
const daysAgo = Math.max(0, Math.floor((now - last_consolidated_at) / 86400));
|
|
211
|
+
lastDesc = daysAgo === 0 ? 'earlier today' : `${daysAgo}d ago`;
|
|
212
|
+
}
|
|
213
|
+
|
|
214
|
+
return (
|
|
215
|
+
`CONSOLIDATION REMINDER: ${unconsolidated_sessions} un-consolidated session(s) ` +
|
|
216
|
+
`(${unconsolidated_observations} observations) for ${target} (last consolidated: ${lastDesc}). ` +
|
|
217
|
+
`Let the user know and suggest they start a new session with an example prompt such as: "Consolidate the brain observations for this project."`
|
|
218
|
+
);
|
|
219
|
+
}
|
|
@@ -0,0 +1,461 @@
|
|
|
1
|
+
import { randomUUID } from 'crypto';
|
|
2
|
+
import OpenAI from 'openai';
|
|
3
|
+
import { getDb } from '../lib/db';
|
|
4
|
+
import { logger } from '../lib/logger';
|
|
5
|
+
import { verifyAndStoreSummary, type ConsolidationSubmission } from './gate';
|
|
6
|
+
|
|
7
|
+
export interface ConformanceCheckResult {
|
|
8
|
+
name: string;
|
|
9
|
+
pass: boolean;
|
|
10
|
+
expected: string;
|
|
11
|
+
actual: string;
|
|
12
|
+
details?: Record<string, any>;
|
|
13
|
+
}
|
|
14
|
+
|
|
15
|
+
export interface AiDiagnosticsReport {
|
|
16
|
+
status: 'ok' | 'failed';
|
|
17
|
+
all_passing: boolean;
|
|
18
|
+
passed_count: number;
|
|
19
|
+
total_count: number;
|
|
20
|
+
results: ConformanceCheckResult[];
|
|
21
|
+
}
|
|
22
|
+
|
|
23
|
+
export function seedFixtureObservations(
|
|
24
|
+
sessionId: string,
|
|
25
|
+
fixtureKey: 'fx1' | 'fx2' | 'fx3'
|
|
26
|
+
): { leaseId: string; obsIds: string[] } {
|
|
27
|
+
const db = getDb();
|
|
28
|
+
const now = Math.floor(Date.now() / 1000);
|
|
29
|
+
const leaseId = `l-${fixtureKey}-${randomUUID().slice(0, 8)}`;
|
|
30
|
+
|
|
31
|
+
let obsDefs: Array<{
|
|
32
|
+
id: string;
|
|
33
|
+
kind: 'tool_call' | 'prompt';
|
|
34
|
+
tool_name: string | null;
|
|
35
|
+
file_path: string | null;
|
|
36
|
+
input: string | null;
|
|
37
|
+
output: string | null;
|
|
38
|
+
duration_ms: number;
|
|
39
|
+
failed: number;
|
|
40
|
+
}> = [];
|
|
41
|
+
|
|
42
|
+
if (fixtureKey === 'fx1') {
|
|
43
|
+
obsDefs = [
|
|
44
|
+
{
|
|
45
|
+
id: `obs_${fixtureKey}_1_${randomUUID().slice(0, 6)}`,
|
|
46
|
+
kind: 'tool_call',
|
|
47
|
+
tool_name: 'ExecuteCommand',
|
|
48
|
+
file_path: null,
|
|
49
|
+
input: 'npm test -- memories',
|
|
50
|
+
output:
|
|
51
|
+
"FAIL src/tests/memory/trajectoryStore.test.ts\nTypeError: Cannot read properties of undefined (reading 'id')\n at src/routes/memories.ts:18:34",
|
|
52
|
+
duration_ms: 500,
|
|
53
|
+
failed: 1,
|
|
54
|
+
},
|
|
55
|
+
{
|
|
56
|
+
id: `obs_${fixtureKey}_2_${randomUUID().slice(0, 6)}`,
|
|
57
|
+
kind: 'tool_call',
|
|
58
|
+
tool_name: 'Edit',
|
|
59
|
+
file_path: 'src/routes/memories.ts',
|
|
60
|
+
input: 'fix optional chaining',
|
|
61
|
+
output: 'saved file src/routes/memories.ts',
|
|
62
|
+
duration_ms: 120,
|
|
63
|
+
failed: 0,
|
|
64
|
+
},
|
|
65
|
+
{
|
|
66
|
+
id: `obs_${fixtureKey}_3_${randomUUID().slice(0, 6)}`,
|
|
67
|
+
kind: 'tool_call',
|
|
68
|
+
tool_name: 'ExecuteCommand',
|
|
69
|
+
file_path: null,
|
|
70
|
+
input: 'npm test -- memories',
|
|
71
|
+
output:
|
|
72
|
+
"FAIL src/tests/memory/trajectoryStore.test.ts\nTypeError: Cannot read properties of undefined (reading 'id')\n at src/routes/memories.ts:18:34",
|
|
73
|
+
duration_ms: 480,
|
|
74
|
+
failed: 1,
|
|
75
|
+
},
|
|
76
|
+
{
|
|
77
|
+
id: `obs_${fixtureKey}_4_${randomUUID().slice(0, 6)}`,
|
|
78
|
+
kind: 'tool_call',
|
|
79
|
+
tool_name: 'ExecuteCommand',
|
|
80
|
+
file_path: null,
|
|
81
|
+
input: 'npm test -- memories',
|
|
82
|
+
output:
|
|
83
|
+
"FAIL src/tests/memory/trajectoryStore.test.ts\nTypeError: Cannot read properties of undefined (reading 'id')\n at src/routes/memories.ts:18:34",
|
|
84
|
+
duration_ms: 490,
|
|
85
|
+
failed: 1,
|
|
86
|
+
},
|
|
87
|
+
];
|
|
88
|
+
} else if (fixtureKey === 'fx2') {
|
|
89
|
+
obsDefs = [
|
|
90
|
+
{
|
|
91
|
+
id: `obs_${fixtureKey}_1_${randomUUID().slice(0, 6)}`,
|
|
92
|
+
kind: 'tool_call',
|
|
93
|
+
tool_name: 'Edit',
|
|
94
|
+
file_path: 'src/learning/embedding.ts',
|
|
95
|
+
input: 'edit embedder',
|
|
96
|
+
output: 'saved',
|
|
97
|
+
duration_ms: 200,
|
|
98
|
+
failed: 0,
|
|
99
|
+
},
|
|
100
|
+
{
|
|
101
|
+
id: `obs_${fixtureKey}_2_${randomUUID().slice(0, 6)}`,
|
|
102
|
+
kind: 'tool_call',
|
|
103
|
+
tool_name: 'Edit',
|
|
104
|
+
file_path: 'src/learning/engine.ts',
|
|
105
|
+
input: 'edit engine',
|
|
106
|
+
output: 'saved',
|
|
107
|
+
duration_ms: 210,
|
|
108
|
+
failed: 0,
|
|
109
|
+
},
|
|
110
|
+
{
|
|
111
|
+
id: `obs_${fixtureKey}_3_${randomUUID().slice(0, 6)}`,
|
|
112
|
+
kind: 'tool_call',
|
|
113
|
+
tool_name: 'Edit',
|
|
114
|
+
file_path: 'src/memory/trajectoryStore.ts',
|
|
115
|
+
input: 'edit trajectory',
|
|
116
|
+
output: 'saved',
|
|
117
|
+
duration_ms: 180,
|
|
118
|
+
failed: 0,
|
|
119
|
+
},
|
|
120
|
+
{
|
|
121
|
+
id: `obs_${fixtureKey}_4_${randomUUID().slice(0, 6)}`,
|
|
122
|
+
kind: 'tool_call',
|
|
123
|
+
tool_name: 'Edit',
|
|
124
|
+
file_path: 'src/tests/learning/engine.test.ts',
|
|
125
|
+
input: 'edit tests',
|
|
126
|
+
output: 'saved',
|
|
127
|
+
duration_ms: 190,
|
|
128
|
+
failed: 0,
|
|
129
|
+
},
|
|
130
|
+
{
|
|
131
|
+
id: `obs_${fixtureKey}_5_${randomUUID().slice(0, 6)}`,
|
|
132
|
+
kind: 'tool_call',
|
|
133
|
+
tool_name: 'ExecuteCommand',
|
|
134
|
+
file_path: null,
|
|
135
|
+
input: 'npm test',
|
|
136
|
+
output: 'PASS src/tests/learning/engine.test.ts\n127 passed, 127 total',
|
|
137
|
+
duration_ms: 1200,
|
|
138
|
+
failed: 0,
|
|
139
|
+
},
|
|
140
|
+
];
|
|
141
|
+
} else {
|
|
142
|
+
// fx3 sparse
|
|
143
|
+
obsDefs = [
|
|
144
|
+
{
|
|
145
|
+
id: `obs_${fixtureKey}_1_${randomUUID().slice(0, 6)}`,
|
|
146
|
+
kind: 'tool_call',
|
|
147
|
+
tool_name: 'Read',
|
|
148
|
+
file_path: 'src/middleware/rateLimiter.ts',
|
|
149
|
+
input: 'path: src/middleware/rateLimiter.ts',
|
|
150
|
+
output: '<101 lines returned>',
|
|
151
|
+
duration_ms: 45,
|
|
152
|
+
failed: 0,
|
|
153
|
+
},
|
|
154
|
+
];
|
|
155
|
+
}
|
|
156
|
+
|
|
157
|
+
const obsIds = obsDefs.map((o) => o.id);
|
|
158
|
+
|
|
159
|
+
const insertObs = db.prepare(`
|
|
160
|
+
INSERT INTO observations (
|
|
161
|
+
id, scope, project_id, session_id, kind, tool_name, file_path, input, output, duration_ms, failed, created_at
|
|
162
|
+
) VALUES (?, 'project', 'fixture-test', ?, ?, ?, ?, ?, ?, ?, ?, ?)
|
|
163
|
+
`);
|
|
164
|
+
|
|
165
|
+
for (const o of obsDefs) {
|
|
166
|
+
insertObs.run(
|
|
167
|
+
o.id,
|
|
168
|
+
sessionId,
|
|
169
|
+
o.kind,
|
|
170
|
+
o.tool_name,
|
|
171
|
+
o.file_path,
|
|
172
|
+
o.input,
|
|
173
|
+
o.output,
|
|
174
|
+
o.duration_ms,
|
|
175
|
+
o.failed,
|
|
176
|
+
now
|
|
177
|
+
);
|
|
178
|
+
}
|
|
179
|
+
|
|
180
|
+
db.prepare(`
|
|
181
|
+
INSERT INTO consolidation_leases (
|
|
182
|
+
lease_id, kind, scope, project_id, session_id, observation_ids, created_at, expires_at
|
|
183
|
+
) VALUES (?, 'session', 'project', 'fixture-test', ?, ?, ?, ?)
|
|
184
|
+
`).run(leaseId, sessionId, JSON.stringify(obsIds), now, now + 600);
|
|
185
|
+
|
|
186
|
+
return { leaseId, obsIds };
|
|
187
|
+
}
|
|
188
|
+
|
|
189
|
+
export async function probeReasoningTokens(): Promise<{ probed: boolean; reasoningTokens: number; model?: string }> {
|
|
190
|
+
if (process.env.BRAIN_CHAT_PROBE === '0') {
|
|
191
|
+
return { probed: false, reasoningTokens: 0 };
|
|
192
|
+
}
|
|
193
|
+
|
|
194
|
+
const endpoint = process.env.BRAIN_ENDPOINT;
|
|
195
|
+
const model = process.env.BRAIN_CHAT_MODEL;
|
|
196
|
+
|
|
197
|
+
if (!endpoint || !model) {
|
|
198
|
+
return { probed: false, reasoningTokens: 0 };
|
|
199
|
+
}
|
|
200
|
+
|
|
201
|
+
try {
|
|
202
|
+
const client = new OpenAI({
|
|
203
|
+
baseURL: endpoint.replace(/\/$/, ''),
|
|
204
|
+
apiKey: process.env.BRAIN_ENDPOINT_API_KEY || 'no-key',
|
|
205
|
+
timeout: 10000,
|
|
206
|
+
});
|
|
207
|
+
|
|
208
|
+
const completion = await client.chat.completions.create({
|
|
209
|
+
model,
|
|
210
|
+
messages: [{ role: 'user', content: 'Say hello in 1 word.' }],
|
|
211
|
+
max_tokens: 100,
|
|
212
|
+
});
|
|
213
|
+
|
|
214
|
+
const usage = completion.usage as any;
|
|
215
|
+
// Return the ACTUAL count, not a 0/1 flag. `??` binds tighter than `?:`, so
|
|
216
|
+
// the previous form parsed as `(reasoning_tokens ?? length) ? 1 : 0` and a
|
|
217
|
+
// model reporting 5820 reasoning tokens yielded 1. Callers size the budget
|
|
218
|
+
// as a multiple of this value, so that silently reduced the headroom to
|
|
219
|
+
// near-zero — defeating the one safeguard built from the measured failure
|
|
220
|
+
// where 5820 of 6000 tokens went to reasoning and the reply came back empty.
|
|
221
|
+
const reportedReasoning = usage?.completion_tokens_details?.reasoning_tokens;
|
|
222
|
+
const reasoningTokens =
|
|
223
|
+
typeof reportedReasoning === 'number' && Number.isFinite(reportedReasoning)
|
|
224
|
+
? reportedReasoning
|
|
225
|
+
: // No usage field: fall back to the length of any reasoning_content the
|
|
226
|
+
// endpoint exposed, which is a lower bound rather than a token count.
|
|
227
|
+
((completion.choices[0]?.message as any)?.reasoning_content?.length ?? 0);
|
|
228
|
+
|
|
229
|
+
if (reasoningTokens > 0) {
|
|
230
|
+
logger.warn(
|
|
231
|
+
{ model, reasoningTokens },
|
|
232
|
+
'AI reasoning probe detected reasoning tokens. Ensure BRAIN_CHAT_MAX_TOKENS is sized with adequate headroom.'
|
|
233
|
+
);
|
|
234
|
+
}
|
|
235
|
+
|
|
236
|
+
return { probed: true, reasoningTokens, model };
|
|
237
|
+
} catch (err) {
|
|
238
|
+
logger.warn({ error: err instanceof Error ? err.message : String(err) }, 'reasoning tokens probe skipped or failed');
|
|
239
|
+
return { probed: false, reasoningTokens: 0, model };
|
|
240
|
+
}
|
|
241
|
+
}
|
|
242
|
+
|
|
243
|
+
export function runAiConformanceDiagnostics(): AiDiagnosticsReport {
|
|
244
|
+
const results: ConformanceCheckResult[] = [];
|
|
245
|
+
const allLeaseIds: string[] = [];
|
|
246
|
+
const allObsIds: string[] = [];
|
|
247
|
+
const allSummaryIds: string[] = [];
|
|
248
|
+
|
|
249
|
+
const trackSeed = (seeded: { leaseId: string; obsIds: string[] }) => {
|
|
250
|
+
allLeaseIds.push(seeded.leaseId);
|
|
251
|
+
allObsIds.push(...seeded.obsIds);
|
|
252
|
+
return seeded;
|
|
253
|
+
};
|
|
254
|
+
|
|
255
|
+
try {
|
|
256
|
+
// Check 1: fx1-failure arithmetic outcome derivation and verbatim check
|
|
257
|
+
const fx1 = trackSeed(seedFixtureObservations(`sess-fx1-${randomUUID().slice(0, 6)}`, 'fx1'));
|
|
258
|
+
const fx1Submission: ConsolidationSubmission = {
|
|
259
|
+
lease_id: fx1.leaseId,
|
|
260
|
+
files_touched: ['src/routes/memories.ts'],
|
|
261
|
+
error_verbatim:
|
|
262
|
+
"TypeError: Cannot read properties of undefined (reading 'id')\n at src/routes/memories.ts:18:34",
|
|
263
|
+
claims: [
|
|
264
|
+
{
|
|
265
|
+
text: 'npm test -- memories failed with TypeError',
|
|
266
|
+
source_ids: [fx1.obsIds[0], fx1.obsIds[2]],
|
|
267
|
+
},
|
|
268
|
+
{
|
|
269
|
+
text: 'The file src/routes/memories.ts was edited',
|
|
270
|
+
source_ids: [fx1.obsIds[1]],
|
|
271
|
+
},
|
|
272
|
+
],
|
|
273
|
+
producer_tier: 'agent',
|
|
274
|
+
};
|
|
275
|
+
const fx1Res = verifyAndStoreSummary(fx1Submission);
|
|
276
|
+
if (fx1Res.ok && (fx1Res as any).summary_id) {
|
|
277
|
+
allSummaryIds.push((fx1Res as any).summary_id);
|
|
278
|
+
}
|
|
279
|
+
results.push({
|
|
280
|
+
name: 'fx1-failure: arithmetic outcome and verification',
|
|
281
|
+
pass: fx1Res.ok === true && (fx1Res as any).outcome === 'failure',
|
|
282
|
+
expected: "ok: true, outcome: 'failure'",
|
|
283
|
+
actual: fx1Res.ok ? `ok: true, outcome: ${(fx1Res as any).outcome}` : `failed: ${(fx1Res as any).reason}`,
|
|
284
|
+
});
|
|
285
|
+
|
|
286
|
+
// Check 2: fx2-success outcome and multi-file files_touched
|
|
287
|
+
const fx2 = trackSeed(seedFixtureObservations(`sess-fx2-${randomUUID().slice(0, 6)}`, 'fx2'));
|
|
288
|
+
const fx2Submission: ConsolidationSubmission = {
|
|
289
|
+
lease_id: fx2.leaseId,
|
|
290
|
+
files_touched: [
|
|
291
|
+
'src/learning/embedding.ts',
|
|
292
|
+
'src/learning/engine.ts',
|
|
293
|
+
'src/memory/trajectoryStore.ts',
|
|
294
|
+
'src/tests/learning/engine.test.ts',
|
|
295
|
+
],
|
|
296
|
+
error_verbatim: null,
|
|
297
|
+
claims: [
|
|
298
|
+
{
|
|
299
|
+
text: 'Edited 4 files and tests passed with 127 passed',
|
|
300
|
+
source_ids: [fx2.obsIds[0], fx2.obsIds[4]],
|
|
301
|
+
},
|
|
302
|
+
],
|
|
303
|
+
producer_tier: 'agent',
|
|
304
|
+
};
|
|
305
|
+
const fx2Res = verifyAndStoreSummary(fx2Submission);
|
|
306
|
+
if (fx2Res.ok && (fx2Res as any).summary_id) {
|
|
307
|
+
allSummaryIds.push((fx2Res as any).summary_id);
|
|
308
|
+
}
|
|
309
|
+
results.push({
|
|
310
|
+
name: 'fx2-success: arithmetic outcome success and 4 paths',
|
|
311
|
+
pass: fx2Res.ok === true && (fx2Res as any).outcome === 'success',
|
|
312
|
+
expected: "ok: true, outcome: 'success'",
|
|
313
|
+
actual: fx2Res.ok ? `ok: true, outcome: ${(fx2Res as any).outcome}` : `failed: ${(fx2Res as any).reason}`,
|
|
314
|
+
});
|
|
315
|
+
|
|
316
|
+
// Check 3: fx3-sparse outcome is 'unknown'
|
|
317
|
+
const fx3 = trackSeed(seedFixtureObservations(`sess-fx3-${randomUUID().slice(0, 6)}`, 'fx3'));
|
|
318
|
+
const fx3Submission: ConsolidationSubmission = {
|
|
319
|
+
lease_id: fx3.leaseId,
|
|
320
|
+
files_touched: ['src/middleware/rateLimiter.ts'],
|
|
321
|
+
error_verbatim: null,
|
|
322
|
+
claims: [
|
|
323
|
+
{
|
|
324
|
+
text: 'Read src/middleware/rateLimiter.ts',
|
|
325
|
+
source_ids: [fx3.obsIds[0]],
|
|
326
|
+
},
|
|
327
|
+
],
|
|
328
|
+
producer_tier: 'agent',
|
|
329
|
+
};
|
|
330
|
+
const fx3Res = verifyAndStoreSummary(fx3Submission);
|
|
331
|
+
if (fx3Res.ok && (fx3Res as any).summary_id) {
|
|
332
|
+
allSummaryIds.push((fx3Res as any).summary_id);
|
|
333
|
+
}
|
|
334
|
+
results.push({
|
|
335
|
+
name: 'fx3-sparse: single bare read yields outcome unknown',
|
|
336
|
+
pass: fx3Res.ok === true && (fx3Res as any).outcome === 'unknown',
|
|
337
|
+
expected: "ok: true, outcome: 'unknown'",
|
|
338
|
+
actual: fx3Res.ok ? `ok: true, outcome: ${(fx3Res as any).outcome}` : `failed: ${(fx3Res as any).reason}`,
|
|
339
|
+
});
|
|
340
|
+
|
|
341
|
+
// Check 4: Unresolved citation rejection
|
|
342
|
+
const fx4 = trackSeed(seedFixtureObservations(`sess-fx3-chk4-${randomUUID().slice(0, 6)}`, 'fx3'));
|
|
343
|
+
const badCitationSubmission: ConsolidationSubmission = {
|
|
344
|
+
lease_id: fx4.leaseId,
|
|
345
|
+
claims: [{ text: 'Fake citation claim', source_ids: ['obs_fake_nonexistent_id'] }],
|
|
346
|
+
producer_tier: 'agent',
|
|
347
|
+
};
|
|
348
|
+
const badCitRes = verifyAndStoreSummary(badCitationSubmission);
|
|
349
|
+
results.push({
|
|
350
|
+
name: 'gate: reject unresolved citation with 422',
|
|
351
|
+
pass: badCitRes.ok === false && (badCitRes as any).reason === 'citation_unresolved',
|
|
352
|
+
expected: "ok: false, reason: 'citation_unresolved'",
|
|
353
|
+
actual: badCitRes.ok ? 'ok: true' : `reason: ${(badCitRes as any).reason}`,
|
|
354
|
+
});
|
|
355
|
+
|
|
356
|
+
// Check 5: Non-verbatim error string rejection
|
|
357
|
+
const fx5 = trackSeed(seedFixtureObservations(`sess-fx1-chk5-${randomUUID().slice(0, 6)}`, 'fx1'));
|
|
358
|
+
const badErrorSubmission: ConsolidationSubmission = {
|
|
359
|
+
lease_id: fx5.leaseId,
|
|
360
|
+
error_verbatim: 'This error text never existed in the log anywhere!',
|
|
361
|
+
claims: [{ text: 'Some claim', source_ids: [fx5.obsIds[0]] }],
|
|
362
|
+
producer_tier: 'agent',
|
|
363
|
+
};
|
|
364
|
+
const badErrRes = verifyAndStoreSummary(badErrorSubmission);
|
|
365
|
+
results.push({
|
|
366
|
+
name: 'gate: reject non-verbatim error string with 422',
|
|
367
|
+
pass: badErrRes.ok === false && (badErrRes as any).reason === 'not_verbatim',
|
|
368
|
+
expected: "ok: false, reason: 'not_verbatim'",
|
|
369
|
+
actual: badErrRes.ok ? 'ok: true' : `reason: ${(badErrRes as any).reason}`,
|
|
370
|
+
});
|
|
371
|
+
|
|
372
|
+
// Check 6: Output-only path in files_touched rejection
|
|
373
|
+
// In fx1, 'src/tests/memory/trajectoryStore.test.ts' appeared in command output, but NEVER as tool target file_path!
|
|
374
|
+
const fx6 = trackSeed(seedFixtureObservations(`sess-fx1-chk6-${randomUUID().slice(0, 6)}`, 'fx1'));
|
|
375
|
+
const outputOnlyPathSubmission: ConsolidationSubmission = {
|
|
376
|
+
lease_id: fx6.leaseId,
|
|
377
|
+
files_touched: ['src/tests/memory/trajectoryStore.test.ts'],
|
|
378
|
+
claims: [{ text: 'Some claim', source_ids: [fx6.obsIds[0]] }],
|
|
379
|
+
producer_tier: 'agent',
|
|
380
|
+
};
|
|
381
|
+
const outPathRes = verifyAndStoreSummary(outputOnlyPathSubmission);
|
|
382
|
+
results.push({
|
|
383
|
+
name: 'gate: reject output-only path in files_touched with 422 not_verbatim',
|
|
384
|
+
pass: outPathRes.ok === false && (outPathRes as any).reason === 'not_verbatim',
|
|
385
|
+
expected: "ok: false, reason: 'not_verbatim'",
|
|
386
|
+
actual: outPathRes.ok ? 'ok: true' : `reason: ${(outPathRes as any).reason}`,
|
|
387
|
+
});
|
|
388
|
+
|
|
389
|
+
// Check 7: Truncated finish_reason rejection
|
|
390
|
+
const fx7 = trackSeed(seedFixtureObservations(`sess-fx2-chk7-${randomUUID().slice(0, 6)}`, 'fx2'));
|
|
391
|
+
const truncatedSubmission: ConsolidationSubmission = {
|
|
392
|
+
lease_id: fx7.leaseId,
|
|
393
|
+
finish_reason: 'length',
|
|
394
|
+
claims: [{ text: 'Truncated claim', source_ids: [fx7.obsIds[0]] }],
|
|
395
|
+
producer_tier: 'agent',
|
|
396
|
+
};
|
|
397
|
+
const truncRes = verifyAndStoreSummary(truncatedSubmission);
|
|
398
|
+
results.push({
|
|
399
|
+
name: 'gate: reject truncated finish_reason length with 422',
|
|
400
|
+
pass: truncRes.ok === false && (truncRes as any).reason === 'truncated',
|
|
401
|
+
expected: "ok: false, reason: 'truncated'",
|
|
402
|
+
actual: truncRes.ok ? 'ok: true' : `reason: ${(truncRes as any).reason}`,
|
|
403
|
+
});
|
|
404
|
+
|
|
405
|
+
// Check 8: Forbidden field (narrative / importance) rejection
|
|
406
|
+
const fx8 = trackSeed(seedFixtureObservations(`sess-fx2-chk8-${randomUUID().slice(0, 6)}`, 'fx2'));
|
|
407
|
+
const forbiddenSubmission: any = {
|
|
408
|
+
lease_id: fx8.leaseId,
|
|
409
|
+
narrative: 'This was an audit process to understand logic',
|
|
410
|
+
claims: [{ text: 'Valid claim', source_ids: [fx8.obsIds[0]] }],
|
|
411
|
+
producer_tier: 'agent',
|
|
412
|
+
};
|
|
413
|
+
const forbRes = verifyAndStoreSummary(forbiddenSubmission);
|
|
414
|
+
results.push({
|
|
415
|
+
name: 'gate: reject forbidden narrative/importance fields with 422 schema_invalid',
|
|
416
|
+
pass: forbRes.ok === false && (forbRes as any).reason === 'schema_invalid',
|
|
417
|
+
expected: "ok: false, reason: 'schema_invalid'",
|
|
418
|
+
actual: forbRes.ok ? 'ok: true' : `reason: ${(forbRes as any).reason}`,
|
|
419
|
+
});
|
|
420
|
+
} finally {
|
|
421
|
+
// [CR-01] Clean up all synthetic rows created by diagnostics so production SQLite and embed_queue are never polluted
|
|
422
|
+
try {
|
|
423
|
+
const db = getDb();
|
|
424
|
+
if (allSummaryIds.length > 0) {
|
|
425
|
+
const placeholders = allSummaryIds.map(() => '?').join(',');
|
|
426
|
+
db.prepare(`DELETE FROM embed_queue WHERE grain = 'summary' AND record_id IN (${placeholders})`).run(...allSummaryIds);
|
|
427
|
+
db.prepare(`DELETE FROM summary_claims WHERE summary_id IN (${placeholders})`).run(...allSummaryIds);
|
|
428
|
+
db.prepare(`DELETE FROM summary_sources WHERE summary_id IN (${placeholders})`).run(...allSummaryIds);
|
|
429
|
+
db.prepare(`DELETE FROM summaries WHERE id IN (${placeholders})`).run(...allSummaryIds);
|
|
430
|
+
}
|
|
431
|
+
if (allLeaseIds.length > 0) {
|
|
432
|
+
const placeholders = allLeaseIds.map(() => '?').join(',');
|
|
433
|
+
db.prepare(`DELETE FROM consolidation_leases WHERE lease_id IN (${placeholders})`).run(...allLeaseIds);
|
|
434
|
+
for (const leaseId of allLeaseIds) {
|
|
435
|
+
db.prepare(`DELETE FROM dead_letters WHERE source = 'consolidate' AND payload LIKE ?`).run(`%${leaseId}%`);
|
|
436
|
+
}
|
|
437
|
+
}
|
|
438
|
+
if (allObsIds.length > 0) {
|
|
439
|
+
const placeholders = allObsIds.map(() => '?').join(',');
|
|
440
|
+
db.prepare(`DELETE FROM observations WHERE id IN (${placeholders})`).run(...allObsIds);
|
|
441
|
+
}
|
|
442
|
+
db.prepare(`DELETE FROM observations WHERE project_id = 'fixture-test'`).run();
|
|
443
|
+
db.prepare(`DELETE FROM consolidation_leases WHERE project_id = 'fixture-test'`).run();
|
|
444
|
+
db.prepare(`DELETE FROM dead_letters WHERE source = 'consolidate' AND (payload LIKE '%fixture-test%' OR payload LIKE '%sess-fx%')`).run();
|
|
445
|
+
} catch (cleanupErr: any) {
|
|
446
|
+
logger.warn({ error: cleanupErr instanceof Error ? cleanupErr.message : String(cleanupErr) }, 'error cleaning up AI conformance diagnostics fixtures');
|
|
447
|
+
}
|
|
448
|
+
}
|
|
449
|
+
|
|
450
|
+
const totalCount = results.length;
|
|
451
|
+
const passedCount = results.filter((r) => r.pass).length;
|
|
452
|
+
const allPassing = passedCount === totalCount;
|
|
453
|
+
|
|
454
|
+
return {
|
|
455
|
+
status: allPassing ? 'ok' : 'failed',
|
|
456
|
+
all_passing: allPassing,
|
|
457
|
+
passed_count: passedCount,
|
|
458
|
+
total_count: totalCount,
|
|
459
|
+
results,
|
|
460
|
+
};
|
|
461
|
+
}
|