neuralbrain 0.0.1 → 0.1.0
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/.env.example +2 -2
- package/README.md +19 -4
- package/dist/ai/chat.d.ts +1 -2
- package/dist/ai/chat.d.ts.map +1 -1
- package/dist/ai/chat.js +1 -2
- package/dist/ai/chat.js.map +1 -1
- package/dist/ai/config.d.ts +1 -1
- package/dist/ai/config.js +2 -2
- package/dist/ai/config.js.map +1 -1
- package/dist/app.d.ts +1 -0
- package/dist/app.d.ts.map +1 -1
- package/dist/app.js +417 -50
- package/dist/app.js.map +1 -1
- package/dist/cli.d.ts +53 -2
- package/dist/cli.d.ts.map +1 -1
- package/dist/cli.js +437 -37
- package/dist/cli.js.map +1 -1
- package/dist/consolidation/candidates.d.ts.map +1 -1
- package/dist/consolidation/candidates.js +19 -4
- package/dist/consolidation/candidates.js.map +1 -1
- package/dist/consolidation/fixtures.js +1 -1
- package/dist/consolidation/fixtures.js.map +1 -1
- package/dist/consolidation/gate.d.ts.map +1 -1
- package/dist/consolidation/gate.js +145 -109
- package/dist/consolidation/gate.js.map +1 -1
- package/dist/consolidation/runner.d.ts +6 -0
- package/dist/consolidation/runner.d.ts.map +1 -1
- package/dist/consolidation/runner.js +22 -2
- package/dist/consolidation/runner.js.map +1 -1
- package/dist/dashboard/clientScript.d.ts +1 -1
- package/dist/dashboard/clientScript.d.ts.map +1 -1
- package/dist/dashboard/clientScript.js +3774 -905
- package/dist/dashboard/clientScript.js.map +1 -1
- package/dist/dashboard/html.d.ts.map +1 -1
- package/dist/dashboard/html.js +605 -101
- package/dist/dashboard/html.js.map +1 -1
- package/dist/dashboard/styles.d.ts +1 -1
- package/dist/dashboard/styles.d.ts.map +1 -1
- package/dist/dashboard/styles.js +1591 -359
- package/dist/dashboard/styles.js.map +1 -1
- package/dist/learning/embedWorker.d.ts +13 -0
- package/dist/learning/embedWorker.d.ts.map +1 -1
- package/dist/learning/embedWorker.js +329 -59
- package/dist/learning/embedWorker.js.map +1 -1
- package/dist/learning/embedding.d.ts +1 -0
- package/dist/learning/embedding.d.ts.map +1 -1
- package/dist/learning/embedding.js +101 -26
- package/dist/learning/embedding.js.map +1 -1
- package/dist/learning/engine.js +1 -1
- package/dist/learning/engine.js.map +1 -1
- package/dist/learning/search.d.ts +17 -1
- package/dist/learning/search.d.ts.map +1 -1
- package/dist/learning/search.js +2094 -354
- package/dist/learning/search.js.map +1 -1
- package/dist/learning/storeMeta.d.ts +9 -0
- package/dist/learning/storeMeta.d.ts.map +1 -1
- package/dist/learning/storeMeta.js +30 -24
- package/dist/learning/storeMeta.js.map +1 -1
- package/dist/learning/types.d.ts +57 -8
- package/dist/learning/types.d.ts.map +1 -1
- package/dist/lib/condenser.d.ts +112 -0
- package/dist/lib/condenser.d.ts.map +1 -0
- package/dist/lib/condenser.js +1337 -0
- package/dist/lib/condenser.js.map +1 -0
- package/dist/lib/db.d.ts +10 -0
- package/dist/lib/db.d.ts.map +1 -1
- package/dist/lib/db.js +654 -167
- package/dist/lib/db.js.map +1 -1
- package/dist/lib/logger.d.ts.map +1 -1
- package/dist/lib/logger.js +3 -2
- package/dist/lib/logger.js.map +1 -1
- package/dist/lib/projectSlug.d.ts +12 -5
- package/dist/lib/projectSlug.d.ts.map +1 -1
- package/dist/lib/projectSlug.js +62 -23
- package/dist/lib/projectSlug.js.map +1 -1
- package/dist/lib/recurrence.d.ts +16 -0
- package/dist/lib/recurrence.d.ts.map +1 -0
- package/dist/lib/recurrence.js +293 -0
- package/dist/lib/recurrence.js.map +1 -0
- package/dist/lib/scope.d.ts +36 -1
- package/dist/lib/scope.d.ts.map +1 -1
- package/dist/lib/scope.js +183 -19
- package/dist/lib/scope.js.map +1 -1
- package/dist/lib/signalTags.d.ts +39 -0
- package/dist/lib/signalTags.d.ts.map +1 -0
- package/dist/lib/signalTags.js +203 -0
- package/dist/lib/signalTags.js.map +1 -0
- package/dist/lib/spool.d.ts +2 -0
- package/dist/lib/spool.d.ts.map +1 -1
- package/dist/lib/spool.js +176 -65
- package/dist/lib/spool.js.map +1 -1
- package/dist/lib/storeDiagnostics.d.ts +41 -0
- package/dist/lib/storeDiagnostics.d.ts.map +1 -0
- package/dist/lib/storeDiagnostics.js +148 -0
- package/dist/lib/storeDiagnostics.js.map +1 -0
- package/dist/lib/temporal.d.ts +44 -0
- package/dist/lib/temporal.d.ts.map +1 -0
- package/dist/lib/temporal.js +1063 -0
- package/dist/lib/temporal.js.map +1 -0
- package/dist/mcp/server.d.ts +93 -3
- package/dist/mcp/server.d.ts.map +1 -1
- package/dist/mcp/server.js +499 -68
- package/dist/mcp/server.js.map +1 -1
- package/dist/memory/actionStore.d.ts +94 -3
- package/dist/memory/actionStore.d.ts.map +1 -1
- package/dist/memory/actionStore.js +412 -124
- package/dist/memory/actionStore.js.map +1 -1
- package/dist/memory/deadLetterStore.d.ts.map +1 -1
- package/dist/memory/deadLetterStore.js +4 -2
- package/dist/memory/deadLetterStore.js.map +1 -1
- package/dist/memory/embedQueueStore.d.ts +19 -8
- package/dist/memory/embedQueueStore.d.ts.map +1 -1
- package/dist/memory/embedQueueStore.js +55 -25
- package/dist/memory/embedQueueStore.js.map +1 -1
- package/dist/memory/failurePatternStore.d.ts +17 -1
- package/dist/memory/failurePatternStore.d.ts.map +1 -1
- package/dist/memory/failurePatternStore.js +54 -31
- package/dist/memory/failurePatternStore.js.map +1 -1
- package/dist/memory/graphStore.d.ts +133 -3
- package/dist/memory/graphStore.d.ts.map +1 -1
- package/dist/memory/graphStore.js +980 -155
- package/dist/memory/graphStore.js.map +1 -1
- package/dist/memory/noteStore.d.ts +27 -2
- package/dist/memory/noteStore.d.ts.map +1 -1
- package/dist/memory/noteStore.js +89 -26
- package/dist/memory/noteStore.js.map +1 -1
- package/dist/memory/observationStore.d.ts +11 -1
- package/dist/memory/observationStore.d.ts.map +1 -1
- package/dist/memory/observationStore.js +90 -15
- package/dist/memory/observationStore.js.map +1 -1
- package/dist/memory/projectRename.d.ts.map +1 -1
- package/dist/memory/projectRename.js +5 -1
- package/dist/memory/projectRename.js.map +1 -1
- package/dist/memory/rollupSweeper.d.ts.map +1 -1
- package/dist/memory/rollupSweeper.js +43 -23
- package/dist/memory/rollupSweeper.js.map +1 -1
- package/dist/memory/sessionStore.d.ts +25 -7
- package/dist/memory/sessionStore.d.ts.map +1 -1
- package/dist/memory/sessionStore.js +145 -33
- package/dist/memory/sessionStore.js.map +1 -1
- package/dist/memory/trajectoryStore.d.ts +8 -0
- package/dist/memory/trajectoryStore.d.ts.map +1 -1
- package/dist/memory/trajectoryStore.js +196 -130
- package/dist/memory/trajectoryStore.js.map +1 -1
- package/dist/middleware/rateLimiter.d.ts.map +1 -1
- package/dist/middleware/rateLimiter.js +24 -1
- package/dist/middleware/rateLimiter.js.map +1 -1
- package/dist/routes/dashboard.d.ts.map +1 -1
- package/dist/routes/dashboard.js +181 -8
- package/dist/routes/dashboard.js.map +1 -1
- package/dist/routes/mcp.d.ts.map +1 -1
- package/dist/routes/mcp.js +173 -21
- package/dist/routes/mcp.js.map +1 -1
- package/dist/routes/memories.js +9 -1
- package/dist/routes/memories.js.map +1 -1
- package/dist/scripts/doctor.d.ts +26 -2
- package/dist/scripts/doctor.d.ts.map +1 -1
- package/dist/scripts/doctor.js +371 -259
- package/dist/scripts/doctor.js.map +1 -1
- package/dist/scripts/installAgent.d.ts.map +1 -1
- package/dist/scripts/installAgent.js +101 -19
- package/dist/scripts/installAgent.js.map +1 -1
- package/dist/scripts/migrateAgentMemory.js +2 -2
- package/dist/scripts/smokeTest.js +1 -1
- package/dist/scripts/smokeTest.js.map +1 -1
- package/docker-compose.yml +1 -1
- package/npm-shrinkwrap.json +2 -2
- package/package.json +3 -2
- package/plugin/hooks/postToolUse.js +155 -50
- package/plugin/hooks/sessionStart.js +179 -27
- package/plugin/hooks/sessionStop.js +152 -37
- package/plugin/plugin.json +1 -1
- package/plugin/rules/AGENTS.md +10 -8
- package/plugin/skills/brain-memory/REFERENCE.md +15 -14
- package/plugin/skills/brain-memory/SKILL.md +2 -2
- package/plugin/skills/digest/SKILL.md +1 -1
- package/plugin/skills/handoff/SKILL.md +1 -1
- package/plugin/skills/save/SKILL.md +2 -2
- package/plugin/skills/search/SKILL.md +2 -2
- package/src/ai/chat.ts +1 -2
- package/src/ai/config.ts +2 -2
- package/src/app.ts +475 -54
- package/src/cli.ts +500 -38
- package/src/consolidation/candidates.ts +22 -4
- package/src/consolidation/fixtures.ts +1 -1
- package/src/consolidation/gate.ts +177 -140
- package/src/consolidation/runner.ts +26 -2
- package/src/dashboard/clientScript.ts +3774 -905
- package/src/dashboard/html.ts +605 -101
- package/src/dashboard/styles.ts +1591 -359
- package/src/learning/embedWorker.ts +350 -70
- package/src/learning/embedding.ts +141 -28
- package/src/learning/engine.ts +1 -1
- package/src/learning/search.ts +2533 -397
- package/src/learning/storeMeta.ts +36 -29
- package/src/learning/types.ts +66 -8
- package/src/lib/condenser.ts +1515 -0
- package/src/lib/db.ts +690 -171
- package/src/lib/logger.ts +4 -2
- package/src/lib/projectSlug.ts +77 -23
- package/src/lib/recurrence.ts +382 -0
- package/src/lib/scope.ts +220 -22
- package/src/lib/signalTags.ts +257 -0
- package/src/lib/spool.ts +181 -71
- package/src/lib/storeDiagnostics.ts +181 -0
- package/src/lib/temporal.ts +1250 -0
- package/src/mcp/server.ts +559 -88
- package/src/memory/actionStore.ts +642 -171
- package/src/memory/deadLetterStore.ts +4 -2
- package/src/memory/embedQueueStore.ts +63 -27
- package/src/memory/failurePatternStore.ts +84 -31
- package/src/memory/graphStore.ts +1396 -215
- package/src/memory/noteStore.ts +151 -30
- package/src/memory/observationStore.ts +117 -17
- package/src/memory/projectRename.ts +6 -2
- package/src/memory/rollupSweeper.ts +46 -23
- package/src/memory/sessionStore.ts +197 -38
- package/src/memory/trajectoryStore.ts +260 -140
- package/src/middleware/rateLimiter.ts +24 -1
- package/src/routes/dashboard.ts +194 -9
- package/src/routes/mcp.ts +185 -26
- package/src/routes/memories.ts +8 -1
- package/src/scripts/doctor.ts +461 -262
- package/src/scripts/installAgent.ts +106 -19
- package/src/scripts/migrateAgentMemory.ts +2 -2
- package/src/scripts/smokeTest.ts +1 -1
package/src/scripts/doctor.ts
CHANGED
|
@@ -1,11 +1,24 @@
|
|
|
1
|
-
import
|
|
2
|
-
import
|
|
3
|
-
import {
|
|
1
|
+
import fs from 'fs';
|
|
2
|
+
import path from 'path';
|
|
3
|
+
import { getDbPath, withIsolatedDb } from '../lib/db';
|
|
4
|
+
import { loadBrainEnv } from '../lib/brainHome';
|
|
5
|
+
import { openDatabase, type Database } from '../lib/sqlite';
|
|
6
|
+
import { createLocalTlsFetch } from '../lib/tls';
|
|
7
|
+
import {
|
|
8
|
+
countStoreRecords,
|
|
9
|
+
inspectDatabaseHealth,
|
|
10
|
+
inspectSchemaAlignment,
|
|
11
|
+
type StoreCounts,
|
|
12
|
+
} from '../lib/storeDiagnostics';
|
|
13
|
+
import { compareStoreMeta } from '../learning/storeMeta';
|
|
14
|
+
import { resolveEmbedderRecipe } from '../learning/embedding';
|
|
15
|
+
import type { StoreMetaRecord } from '../learning/types';
|
|
4
16
|
import {
|
|
5
17
|
runAiConformanceDiagnostics,
|
|
6
18
|
AiDiagnosticsReport,
|
|
7
19
|
} from '../consolidation/fixtures';
|
|
8
20
|
import { describeAiConfig } from '../ai/config';
|
|
21
|
+
import { resolveApiKey, resolveApiUrl } from './installAgent';
|
|
9
22
|
|
|
10
23
|
export interface DoctorCheck {
|
|
11
24
|
name: string;
|
|
@@ -13,8 +26,20 @@ export interface DoctorCheck {
|
|
|
13
26
|
message: string;
|
|
14
27
|
}
|
|
15
28
|
|
|
29
|
+
/**
|
|
30
|
+
* Where the doctor's answers came from.
|
|
31
|
+
* - `service`: the running brain service, over HTTP. The doctor never opens the
|
|
32
|
+
* database file, so the service stays its only writer.
|
|
33
|
+
* - `local`: the service was not reachable, so the database file was opened
|
|
34
|
+
* read-only (the sanctioned read-only diagnosis) and the AI conformance
|
|
35
|
+
* fixtures ran against a throwaway temp database.
|
|
36
|
+
*/
|
|
37
|
+
export type DoctorSource = 'service' | 'local';
|
|
38
|
+
|
|
16
39
|
export interface DoctorReport {
|
|
17
40
|
allPassing: boolean;
|
|
41
|
+
source: DoctorSource;
|
|
42
|
+
target: string;
|
|
18
43
|
dbOk: boolean;
|
|
19
44
|
schemaAligned: boolean;
|
|
20
45
|
storeMetaMatch: boolean;
|
|
@@ -27,308 +52,476 @@ export interface DoctorReport {
|
|
|
27
52
|
checks: DoctorCheck[];
|
|
28
53
|
}
|
|
29
54
|
|
|
30
|
-
export
|
|
55
|
+
export interface DoctorOptions {
|
|
31
56
|
ai?: boolean;
|
|
32
57
|
exitOnFinish?: boolean;
|
|
33
|
-
|
|
34
|
-
|
|
58
|
+
/** `auto` (default) uses the service when it answers /health, else `local`. */
|
|
59
|
+
mode?: 'auto' | 'service' | 'local';
|
|
60
|
+
apiUrl?: string;
|
|
61
|
+
apiKey?: string;
|
|
62
|
+
fetchFn?: typeof fetch;
|
|
63
|
+
/** Local mode: database file to open read-only (default: the configured path). */
|
|
64
|
+
dbPath?: string;
|
|
65
|
+
/** Local mode, tests only: inspect this already-open connection instead of opening dbPath. */
|
|
66
|
+
db?: Database;
|
|
67
|
+
/** Suppress the printed report (tests). */
|
|
68
|
+
quiet?: boolean;
|
|
69
|
+
}
|
|
35
70
|
|
|
36
|
-
|
|
37
|
-
|
|
38
|
-
|
|
39
|
-
|
|
40
|
-
|
|
41
|
-
|
|
42
|
-
|
|
43
|
-
|
|
44
|
-
|
|
45
|
-
|
|
46
|
-
|
|
47
|
-
|
|
48
|
-
|
|
49
|
-
|
|
50
|
-
|
|
51
|
-
|
|
52
|
-
|
|
53
|
-
|
|
54
|
-
|
|
55
|
-
|
|
56
|
-
|
|
57
|
-
|
|
58
|
-
|
|
59
|
-
|
|
60
|
-
|
|
71
|
+
const HEALTH_TIMEOUT_MS = 3000;
|
|
72
|
+
const REQUEST_TIMEOUT_MS = 60000;
|
|
73
|
+
|
|
74
|
+
const SKIPPED_AI: AiDiagnosticsReport = {
|
|
75
|
+
status: 'ok',
|
|
76
|
+
all_passing: true,
|
|
77
|
+
passed_count: 0,
|
|
78
|
+
total_count: 0,
|
|
79
|
+
results: [],
|
|
80
|
+
};
|
|
81
|
+
|
|
82
|
+
const FAILED_AI: AiDiagnosticsReport = {
|
|
83
|
+
status: 'failed',
|
|
84
|
+
all_passing: false,
|
|
85
|
+
passed_count: 0,
|
|
86
|
+
total_count: 0,
|
|
87
|
+
results: [],
|
|
88
|
+
};
|
|
89
|
+
|
|
90
|
+
const ZERO_COUNTS: StoreCounts = {
|
|
91
|
+
dead_letters: 0,
|
|
92
|
+
unknown_scope_notes: 0,
|
|
93
|
+
notes: 0,
|
|
94
|
+
trajectories: 0,
|
|
95
|
+
observations: 0,
|
|
96
|
+
};
|
|
97
|
+
|
|
98
|
+
interface Findings {
|
|
99
|
+
dbOk: boolean;
|
|
100
|
+
schemaAligned: boolean;
|
|
101
|
+
storeMetaMatch: boolean;
|
|
102
|
+
counts: StoreCounts;
|
|
103
|
+
aiDiagnostics: AiDiagnosticsReport;
|
|
104
|
+
checks: DoctorCheck[];
|
|
105
|
+
}
|
|
106
|
+
|
|
107
|
+
function errorMessage(err: unknown): string {
|
|
108
|
+
return err instanceof Error ? err.message : String(err);
|
|
109
|
+
}
|
|
110
|
+
|
|
111
|
+
function packageRoot(): string {
|
|
112
|
+
return path.resolve(__dirname, '..', '..');
|
|
113
|
+
}
|
|
114
|
+
|
|
115
|
+
function describeGenerativeConfig(aiConfig: Record<string, any>): DoctorCheck {
|
|
116
|
+
const broken = (['summarize', 'consolidate'] as const).filter((fn) => !aiConfig[fn]?.ok);
|
|
117
|
+
if (broken.length > 0) {
|
|
118
|
+
return {
|
|
119
|
+
name: 'Generative Producer Config',
|
|
61
120
|
pass: false,
|
|
62
|
-
message:
|
|
63
|
-
}
|
|
121
|
+
message: broken.map((fn) => `${fn}: ${aiConfig[fn]?.error ?? 'not resolved'}`).join(' | '),
|
|
122
|
+
};
|
|
64
123
|
}
|
|
124
|
+
const fmt = (fn: 'summarize' | 'consolidate') =>
|
|
125
|
+
`${aiConfig[fn].tier}${aiConfig[fn].model ? ` (${aiConfig[fn].model})` : ''}`;
|
|
126
|
+
return {
|
|
127
|
+
name: 'Generative Producer Config',
|
|
128
|
+
pass: true,
|
|
129
|
+
message: `summarize: ${fmt('summarize')}, consolidate: ${fmt('consolidate')}`,
|
|
130
|
+
};
|
|
131
|
+
}
|
|
65
132
|
|
|
66
|
-
|
|
67
|
-
|
|
68
|
-
|
|
69
|
-
|
|
70
|
-
|
|
71
|
-
|
|
72
|
-
|
|
73
|
-
// Foreign keys pragma
|
|
74
|
-
const fkRow = db.prepare('PRAGMA foreign_keys').get() as { foreign_keys?: number } | undefined;
|
|
75
|
-
if (fkRow?.foreign_keys !== 1) {
|
|
76
|
-
issues.push('PRAGMA foreign_keys is not active');
|
|
77
|
-
}
|
|
133
|
+
function aiCheck(report: AiDiagnosticsReport): DoctorCheck {
|
|
134
|
+
return {
|
|
135
|
+
name: 'AI Conformance Diagnostics',
|
|
136
|
+
pass: report.all_passing,
|
|
137
|
+
message: `${report.passed_count}/${report.total_count} assertions passed`,
|
|
138
|
+
};
|
|
139
|
+
}
|
|
78
140
|
|
|
79
|
-
|
|
80
|
-
|
|
81
|
-
|
|
82
|
-
|
|
83
|
-
|
|
84
|
-
|
|
85
|
-
|
|
86
|
-
|
|
87
|
-
|
|
88
|
-
|
|
89
|
-
|
|
90
|
-
|
|
91
|
-
|
|
92
|
-
|
|
93
|
-
const projCol = trajCols.get('project_id');
|
|
94
|
-
if (!projCol) issues.push('trajectories.project_id missing');
|
|
95
|
-
else if (projCol.notnull !== 0) issues.push('trajectories.project_id is not nullable (notnull=1)');
|
|
96
|
-
|
|
97
|
-
for (const col of ['session_id', 'rollup_source', 'tool_calls']) {
|
|
98
|
-
if (!trajCols.has(col)) issues.push(`trajectories.${col} missing`);
|
|
99
|
-
}
|
|
100
|
-
}
|
|
141
|
+
async function fetchWithTimeout(
|
|
142
|
+
fetchFn: typeof fetch,
|
|
143
|
+
url: string,
|
|
144
|
+
init: RequestInit,
|
|
145
|
+
timeoutMs: number
|
|
146
|
+
): Promise<Response> {
|
|
147
|
+
const controller = new AbortController();
|
|
148
|
+
const timer = setTimeout(() => controller.abort(), timeoutMs);
|
|
149
|
+
try {
|
|
150
|
+
return await fetchFn(url, { ...init, signal: controller.signal });
|
|
151
|
+
} finally {
|
|
152
|
+
clearTimeout(timer);
|
|
153
|
+
}
|
|
154
|
+
}
|
|
101
155
|
|
|
102
|
-
|
|
103
|
-
|
|
104
|
-
|
|
105
|
-
|
|
106
|
-
|
|
107
|
-
|
|
108
|
-
|
|
109
|
-
|
|
110
|
-
|
|
111
|
-
|
|
112
|
-
if (!projCol) issues.push('trajectory_archive.project_id missing');
|
|
113
|
-
else if (projCol.notnull !== 0) issues.push('trajectory_archive.project_id is not nullable (notnull=1)');
|
|
114
|
-
|
|
115
|
-
for (const col of ['session_id', 'rollup_source', 'tool_calls']) {
|
|
116
|
-
if (!trajArcCols.has(col)) issues.push(`trajectory_archive.${col} missing`);
|
|
117
|
-
}
|
|
118
|
-
}
|
|
156
|
+
/** Returns the parsed /health body, or null when nothing answered. */
|
|
157
|
+
async function probeHealth(fetchFn: typeof fetch, apiUrl: string): Promise<Record<string, any> | null> {
|
|
158
|
+
try {
|
|
159
|
+
const res = await fetchWithTimeout(fetchFn, `${apiUrl}/health`, {}, HEALTH_TIMEOUT_MS);
|
|
160
|
+
const body = (await res.json().catch(() => null)) as Record<string, any> | null;
|
|
161
|
+
return body && typeof body === 'object' ? body : null;
|
|
162
|
+
} catch {
|
|
163
|
+
return null;
|
|
164
|
+
}
|
|
165
|
+
}
|
|
119
166
|
|
|
120
|
-
|
|
121
|
-
|
|
122
|
-
|
|
123
|
-
|
|
124
|
-
|
|
125
|
-
|
|
126
|
-
|
|
127
|
-
|
|
128
|
-
|
|
167
|
+
async function runServiceChecks(
|
|
168
|
+
fetchFn: typeof fetch,
|
|
169
|
+
apiUrl: string,
|
|
170
|
+
apiKey: string | undefined,
|
|
171
|
+
health: Record<string, any>,
|
|
172
|
+
runAi: boolean
|
|
173
|
+
): Promise<Findings> {
|
|
174
|
+
const checks: DoctorCheck[] = [];
|
|
175
|
+
const headers: Record<string, string> = apiKey ? { Authorization: `Bearer ${apiKey}` } : {};
|
|
129
176
|
|
|
130
|
-
|
|
131
|
-
|
|
132
|
-
|
|
133
|
-
|
|
134
|
-
|
|
135
|
-
|
|
136
|
-
|
|
177
|
+
const getJson = async (
|
|
178
|
+
route: string
|
|
179
|
+
): Promise<{ ok: true; body: any } | { ok: false; error: string; status?: number }> => {
|
|
180
|
+
try {
|
|
181
|
+
const res = await fetchWithTimeout(fetchFn, `${apiUrl}${route}`, { headers }, REQUEST_TIMEOUT_MS);
|
|
182
|
+
if (res.status === 401) {
|
|
183
|
+
return {
|
|
184
|
+
ok: false,
|
|
185
|
+
error: `GET ${route} was rejected (401): set BRAIN_API_KEY to a valid key for this service`,
|
|
186
|
+
};
|
|
137
187
|
}
|
|
138
|
-
|
|
139
|
-
if (
|
|
140
|
-
|
|
141
|
-
|
|
142
|
-
|
|
143
|
-
|
|
144
|
-
|
|
145
|
-
});
|
|
146
|
-
} else {
|
|
147
|
-
checks.push({
|
|
148
|
-
name: 'Schema Alignment',
|
|
149
|
-
pass: false,
|
|
150
|
-
message: `Schema misalignment detected: ${issues.join('; ')}`,
|
|
151
|
-
});
|
|
188
|
+
const body = (await res.json().catch(() => null)) as any;
|
|
189
|
+
if (!res.ok || body === null) {
|
|
190
|
+
return {
|
|
191
|
+
ok: false,
|
|
192
|
+
status: res.status,
|
|
193
|
+
error: `GET ${route} returned ${res.status}${body?.error?.message ? `: ${body.error.message}` : ''}`,
|
|
194
|
+
};
|
|
152
195
|
}
|
|
196
|
+
return { ok: true, body };
|
|
153
197
|
} catch (err) {
|
|
154
|
-
|
|
155
|
-
name: 'Schema Alignment',
|
|
156
|
-
pass: false,
|
|
157
|
-
message: `Failed to inspect schema: ${err instanceof Error ? err.message : String(err)}`,
|
|
158
|
-
});
|
|
198
|
+
return { ok: false, error: `GET ${route} failed: ${errorMessage(err)}` };
|
|
159
199
|
}
|
|
160
|
-
}
|
|
200
|
+
};
|
|
201
|
+
|
|
202
|
+
// 1. Database health and schema, inspected by the service on its own connection.
|
|
203
|
+
let dbOk = false;
|
|
204
|
+
let schemaAligned = false;
|
|
205
|
+
let counts = ZERO_COUNTS;
|
|
206
|
+
const store = await getJson('/diagnostics/store');
|
|
207
|
+
if (!store.ok && store.status === 404) {
|
|
208
|
+
// A service older than this CLI: /health still answers for the database,
|
|
209
|
+
// but schema and counts need a restart on this version.
|
|
210
|
+
dbOk = health.db === 'ok';
|
|
211
|
+
checks.push({
|
|
212
|
+
name: 'Database Health',
|
|
213
|
+
pass: dbOk,
|
|
214
|
+
message: dbOk ? 'Database reported ok by /health' : `Database unhealthy: health reports db=${health.db}`,
|
|
215
|
+
});
|
|
161
216
|
checks.push({
|
|
162
217
|
name: 'Schema Alignment',
|
|
163
218
|
pass: false,
|
|
164
|
-
message:
|
|
219
|
+
message: `The service at ${apiUrl} predates GET /diagnostics/store; restart it on this version to check the schema`,
|
|
165
220
|
});
|
|
221
|
+
} else if (!store.ok) {
|
|
222
|
+
checks.push({ name: 'Database Health', pass: false, message: store.error });
|
|
223
|
+
checks.push({ name: 'Schema Alignment', pass: false, message: 'Skipped: store diagnostics unavailable' });
|
|
224
|
+
} else {
|
|
225
|
+
dbOk = store.body.db?.ok === true && health.db === 'ok';
|
|
226
|
+
checks.push(
|
|
227
|
+
dbOk
|
|
228
|
+
? {
|
|
229
|
+
name: 'Database Health',
|
|
230
|
+
pass: true,
|
|
231
|
+
message: `Database accessible and functional (journal_mode: ${store.body.db.journal_mode})`,
|
|
232
|
+
}
|
|
233
|
+
: {
|
|
234
|
+
name: 'Database Health',
|
|
235
|
+
pass: false,
|
|
236
|
+
message: `Database unhealthy: ${store.body.db?.error || `health reports db=${health.db}`}`,
|
|
237
|
+
}
|
|
238
|
+
);
|
|
239
|
+
const issues: string[] = store.body.schema?.issues ?? [];
|
|
240
|
+
schemaAligned = store.body.schema?.aligned === true;
|
|
241
|
+
checks.push(
|
|
242
|
+
schemaAligned
|
|
243
|
+
? { name: 'Schema Alignment', pass: true, message: 'Relational schema aligned and foreign keys enabled' }
|
|
244
|
+
: { name: 'Schema Alignment', pass: false, message: `Schema misalignment detected: ${issues.join('; ')}` }
|
|
245
|
+
);
|
|
246
|
+
counts = store.body.counts ?? ZERO_COUNTS;
|
|
166
247
|
}
|
|
167
248
|
|
|
168
|
-
// 2. Store
|
|
169
|
-
|
|
170
|
-
|
|
171
|
-
|
|
172
|
-
|
|
173
|
-
|
|
174
|
-
|
|
175
|
-
|
|
176
|
-
|
|
177
|
-
|
|
178
|
-
|
|
249
|
+
// 2. Store meta, as the service resolved it from its own environment. In
|
|
250
|
+
// Docker mode that environment is the container's, which can differ from the
|
|
251
|
+
// host shell the doctor runs in.
|
|
252
|
+
const meta = health.store_meta;
|
|
253
|
+
const storeMetaMatch = meta?.match === true;
|
|
254
|
+
checks.push(
|
|
255
|
+
storeMetaMatch
|
|
256
|
+
? {
|
|
257
|
+
name: 'Store Meta Consistency',
|
|
258
|
+
pass: true,
|
|
259
|
+
message: `Consistent with active config (tier: ${meta.embed_tier}, dim: ${meta.embed_dim})`,
|
|
260
|
+
}
|
|
261
|
+
: {
|
|
262
|
+
name: 'Store Meta Consistency',
|
|
263
|
+
pass: false,
|
|
264
|
+
message: `Mismatch detected: ${meta?.mismatch_reason || 'service reports store_meta mismatch'}`,
|
|
265
|
+
}
|
|
266
|
+
);
|
|
267
|
+
|
|
268
|
+
// 3. Generative producer configuration, as the service resolved it.
|
|
269
|
+
const aiConfig = await getJson('/diagnostics/ai-config');
|
|
270
|
+
checks.push(
|
|
271
|
+
aiConfig.ok
|
|
272
|
+
? describeGenerativeConfig(aiConfig.body)
|
|
273
|
+
: { name: 'Generative Producer Config', pass: false, message: aiConfig.error }
|
|
274
|
+
);
|
|
275
|
+
|
|
276
|
+
// 4. AI conformance fixtures, run by the service (the only writer) against its store.
|
|
277
|
+
let aiDiagnostics = SKIPPED_AI;
|
|
278
|
+
if (runAi) {
|
|
279
|
+
const ai = await getJson('/diagnostics/ai');
|
|
280
|
+
if (ai.ok) {
|
|
281
|
+
aiDiagnostics = ai.body as AiDiagnosticsReport;
|
|
282
|
+
checks.push(aiCheck(aiDiagnostics));
|
|
179
283
|
} else {
|
|
180
|
-
|
|
181
|
-
|
|
182
|
-
pass: false,
|
|
183
|
-
message: `Mismatch detected: ${metaRes.mismatchReason || 'configuration differs from store_meta'}`,
|
|
184
|
-
});
|
|
284
|
+
aiDiagnostics = FAILED_AI;
|
|
285
|
+
checks.push({ name: 'AI Conformance Diagnostics', pass: false, message: ai.error });
|
|
185
286
|
}
|
|
186
|
-
}
|
|
187
|
-
checks.push({
|
|
188
|
-
name: 'Store Meta Consistency',
|
|
189
|
-
pass: false,
|
|
190
|
-
message: `Failed to verify store_meta: ${err instanceof Error ? err.message : String(err)}`,
|
|
191
|
-
});
|
|
287
|
+
} else {
|
|
288
|
+
checks.push({ name: 'AI Conformance Diagnostics', pass: true, message: 'Skipped (--no-ai)' });
|
|
192
289
|
}
|
|
193
290
|
|
|
194
|
-
|
|
195
|
-
|
|
196
|
-
let unknownScopeCount = 0;
|
|
197
|
-
let noteCount = 0;
|
|
198
|
-
let trajectoryCount = 0;
|
|
199
|
-
let observationCount = 0;
|
|
200
|
-
|
|
201
|
-
if (dbOk) {
|
|
202
|
-
try {
|
|
203
|
-
const db = getDb();
|
|
204
|
-
const dl = db.prepare('SELECT COUNT(*) as count FROM dead_letters').get() as { count: number };
|
|
205
|
-
deadLetterCount = dl?.count ?? 0;
|
|
291
|
+
return { dbOk, schemaAligned, storeMetaMatch, counts, aiDiagnostics, checks };
|
|
292
|
+
}
|
|
206
293
|
|
|
207
|
-
|
|
208
|
-
|
|
294
|
+
function runLocalChecks(db: Database | null, dbLabel: string, openError: string | null, runAi: boolean): Findings {
|
|
295
|
+
const checks: DoctorCheck[] = [];
|
|
296
|
+
let dbOk = false;
|
|
297
|
+
let schemaAligned = false;
|
|
298
|
+
let storeMetaMatch = false;
|
|
299
|
+
let counts = ZERO_COUNTS;
|
|
209
300
|
|
|
210
|
-
|
|
211
|
-
|
|
301
|
+
if (!db) {
|
|
302
|
+
checks.push({ name: 'Database Health', pass: false, message: openError || `Could not open ${dbLabel}` });
|
|
303
|
+
checks.push({ name: 'Schema Alignment', pass: false, message: 'Database inaccessible, skipping schema alignment check' });
|
|
304
|
+
checks.push({ name: 'Store Meta Consistency', pass: false, message: 'Database inaccessible, skipping store_meta check' });
|
|
305
|
+
} else {
|
|
306
|
+
const health = inspectDatabaseHealth(db);
|
|
307
|
+
dbOk = health.ok;
|
|
308
|
+
checks.push(
|
|
309
|
+
dbOk
|
|
310
|
+
? {
|
|
311
|
+
name: 'Database Health',
|
|
312
|
+
pass: true,
|
|
313
|
+
message: `Database accessible read-only (journal_mode: ${health.journal_mode})`,
|
|
314
|
+
}
|
|
315
|
+
: {
|
|
316
|
+
name: 'Database Health',
|
|
317
|
+
pass: false,
|
|
318
|
+
message: `Database connection error: ${health.error}`,
|
|
319
|
+
}
|
|
320
|
+
);
|
|
321
|
+
|
|
322
|
+
if (dbOk) {
|
|
323
|
+
try {
|
|
324
|
+
// foreign_keys is per-connection; this read-only handle says nothing about the service's.
|
|
325
|
+
const schema = inspectSchemaAlignment(db, { checkForeignKeys: false });
|
|
326
|
+
schemaAligned = schema.aligned;
|
|
327
|
+
checks.push(
|
|
328
|
+
schemaAligned
|
|
329
|
+
? { name: 'Schema Alignment', pass: true, message: 'Relational schema aligned' }
|
|
330
|
+
: {
|
|
331
|
+
name: 'Schema Alignment',
|
|
332
|
+
pass: false,
|
|
333
|
+
message: `Schema misalignment detected: ${schema.issues.join('; ')} (the service migrates the schema on start)`,
|
|
334
|
+
}
|
|
335
|
+
);
|
|
336
|
+
} catch (err) {
|
|
337
|
+
checks.push({ name: 'Schema Alignment', pass: false, message: `Failed to inspect schema: ${errorMessage(err)}` });
|
|
338
|
+
}
|
|
212
339
|
|
|
213
|
-
|
|
214
|
-
|
|
340
|
+
try {
|
|
341
|
+
const existing = db.prepare('SELECT * FROM store_meta WHERE id = 1').get() as StoreMetaRecord | undefined;
|
|
342
|
+
const recipe = resolveEmbedderRecipe();
|
|
343
|
+
if (!existing) {
|
|
344
|
+
// A fresh store: the service commits store_meta on its first start.
|
|
345
|
+
storeMetaMatch = true;
|
|
346
|
+
checks.push({
|
|
347
|
+
name: 'Store Meta Consistency',
|
|
348
|
+
pass: true,
|
|
349
|
+
message: `Not yet initialized; the service will commit tier ${recipe.embed_tier}, dim ${recipe.embed_dim} on first start`,
|
|
350
|
+
});
|
|
351
|
+
} else {
|
|
352
|
+
const cmp = compareStoreMeta(existing, recipe);
|
|
353
|
+
storeMetaMatch = cmp.match;
|
|
354
|
+
checks.push(
|
|
355
|
+
cmp.match
|
|
356
|
+
? {
|
|
357
|
+
name: 'Store Meta Consistency',
|
|
358
|
+
pass: true,
|
|
359
|
+
message: `Consistent with active config (tier: ${recipe.embed_tier}, dim: ${recipe.embed_dim})`,
|
|
360
|
+
}
|
|
361
|
+
: { name: 'Store Meta Consistency', pass: false, message: `Mismatch detected: ${cmp.mismatchReason}` }
|
|
362
|
+
);
|
|
363
|
+
}
|
|
364
|
+
} catch (err) {
|
|
365
|
+
checks.push({ name: 'Store Meta Consistency', pass: false, message: `Failed to verify store_meta: ${errorMessage(err)}` });
|
|
366
|
+
}
|
|
215
367
|
|
|
216
|
-
|
|
217
|
-
|
|
218
|
-
|
|
219
|
-
|
|
368
|
+
counts = countStoreRecords(db);
|
|
369
|
+
} else {
|
|
370
|
+
checks.push({ name: 'Schema Alignment', pass: false, message: 'Database inaccessible, skipping schema alignment check' });
|
|
371
|
+
checks.push({ name: 'Store Meta Consistency', pass: false, message: 'Database inaccessible, skipping store_meta check' });
|
|
220
372
|
}
|
|
221
373
|
}
|
|
222
374
|
|
|
223
|
-
//
|
|
224
|
-
// an impossible combination (a `vendor` tier with no key, `local` named for
|
|
225
|
-
// a generative function), so it belongs in the doctor report rather than
|
|
226
|
-
// waiting for the first consolidation run.
|
|
375
|
+
// Generative config resolves from this process's environment (loadBrainEnv).
|
|
227
376
|
try {
|
|
228
|
-
|
|
229
|
-
const broken = (['summarize', 'consolidate'] as const).filter((fn) => !aiConfig[fn]?.ok);
|
|
230
|
-
if (broken.length === 0) {
|
|
231
|
-
checks.push({
|
|
232
|
-
name: 'Generative Producer Config',
|
|
233
|
-
pass: true,
|
|
234
|
-
message: `summarize: ${aiConfig.summarize.tier}${
|
|
235
|
-
aiConfig.summarize.model ? ` (${aiConfig.summarize.model})` : ''
|
|
236
|
-
}, consolidate: ${aiConfig.consolidate.tier}${
|
|
237
|
-
aiConfig.consolidate.model ? ` (${aiConfig.consolidate.model})` : ''
|
|
238
|
-
}`,
|
|
239
|
-
});
|
|
240
|
-
} else {
|
|
241
|
-
checks.push({
|
|
242
|
-
name: 'Generative Producer Config',
|
|
243
|
-
pass: false,
|
|
244
|
-
message: broken.map((fn) => `${fn}: ${aiConfig[fn].error}`).join(' | '),
|
|
245
|
-
});
|
|
246
|
-
}
|
|
377
|
+
checks.push(describeGenerativeConfig(describeAiConfig() as Record<string, any>));
|
|
247
378
|
} catch (err) {
|
|
248
379
|
checks.push({
|
|
249
380
|
name: 'Generative Producer Config',
|
|
250
381
|
pass: false,
|
|
251
|
-
message: `Failed to resolve generative config: ${
|
|
382
|
+
message: `Failed to resolve generative config: ${errorMessage(err)}`,
|
|
252
383
|
});
|
|
253
384
|
}
|
|
254
385
|
|
|
255
|
-
//
|
|
256
|
-
|
|
257
|
-
|
|
258
|
-
if (
|
|
386
|
+
// The fixtures seed and delete rows, so they never touch the real file:
|
|
387
|
+
// they run against a throwaway temp database.
|
|
388
|
+
let aiDiagnostics = SKIPPED_AI;
|
|
389
|
+
if (runAi) {
|
|
259
390
|
try {
|
|
260
|
-
aiDiagnostics = runAiConformanceDiagnostics();
|
|
261
|
-
checks.push(
|
|
262
|
-
name: 'AI Conformance Diagnostics',
|
|
263
|
-
pass: aiDiagnostics.all_passing,
|
|
264
|
-
message: `${aiDiagnostics.passed_count}/${aiDiagnostics.total_count} assertions passed`,
|
|
265
|
-
});
|
|
391
|
+
aiDiagnostics = withIsolatedDb(() => runAiConformanceDiagnostics());
|
|
392
|
+
checks.push(aiCheck(aiDiagnostics));
|
|
266
393
|
} catch (err) {
|
|
267
|
-
aiDiagnostics =
|
|
268
|
-
|
|
269
|
-
all_passing: false,
|
|
270
|
-
passed_count: 0,
|
|
271
|
-
total_count: 0,
|
|
272
|
-
results: [],
|
|
273
|
-
};
|
|
274
|
-
checks.push({
|
|
275
|
-
name: 'AI Conformance Diagnostics',
|
|
276
|
-
pass: false,
|
|
277
|
-
message: `Failed to run diagnostics: ${err instanceof Error ? err.message : String(err)}`,
|
|
278
|
-
});
|
|
394
|
+
aiDiagnostics = FAILED_AI;
|
|
395
|
+
checks.push({ name: 'AI Conformance Diagnostics', pass: false, message: `Failed to run diagnostics: ${errorMessage(err)}` });
|
|
279
396
|
}
|
|
280
397
|
} else {
|
|
281
|
-
|
|
282
|
-
status: 'ok',
|
|
283
|
-
all_passing: true,
|
|
284
|
-
passed_count: 0,
|
|
285
|
-
total_count: 0,
|
|
286
|
-
results: [],
|
|
287
|
-
};
|
|
288
|
-
checks.push({
|
|
289
|
-
name: 'AI Conformance Diagnostics',
|
|
290
|
-
pass: true,
|
|
291
|
-
message: 'Skipped (--no-ai)',
|
|
292
|
-
});
|
|
398
|
+
checks.push({ name: 'AI Conformance Diagnostics', pass: true, message: 'Skipped (--no-ai)' });
|
|
293
399
|
}
|
|
294
400
|
|
|
295
|
-
|
|
296
|
-
|
|
297
|
-
const passedChecks = checks.filter((c) => c.pass).length;
|
|
298
|
-
const allPassing = passedChecks === totalChecks && dbOk && schemaAligned && storeMetaMatch && aiDiagnostics.all_passing;
|
|
299
|
-
|
|
300
|
-
// Print Structured Report
|
|
301
|
-
console.log('\n╔══════════════════════════════════════════════════════════════╗');
|
|
302
|
-
console.log('║ NEURALBRAIN DOCTOR ║');
|
|
303
|
-
console.log('╚══════════════════════════════════════════════════════════════╝\n');
|
|
401
|
+
return { dbOk, schemaAligned, storeMetaMatch, counts, aiDiagnostics, checks };
|
|
402
|
+
}
|
|
304
403
|
|
|
305
|
-
|
|
306
|
-
|
|
307
|
-
|
|
404
|
+
function openReadOnly(dbPath: string): { db: Database | null; error: string | null } {
|
|
405
|
+
if (dbPath === ':memory:' || dbPath.startsWith('file::memory:')) {
|
|
406
|
+
return { db: null, error: 'DATABASE_URL is :memory:; there is no database file to inspect' };
|
|
407
|
+
}
|
|
408
|
+
const resolved = path.resolve(dbPath);
|
|
409
|
+
if (!fs.existsSync(resolved)) {
|
|
410
|
+
return {
|
|
411
|
+
db: null,
|
|
412
|
+
error: `No database at ${resolved}. Start the service once (neuralbrain start) to create it.`,
|
|
413
|
+
};
|
|
308
414
|
}
|
|
415
|
+
try {
|
|
416
|
+
return { db: openDatabase(resolved, { readOnly: true }), error: null };
|
|
417
|
+
} catch (err) {
|
|
418
|
+
return { db: null, error: `Could not open ${resolved} read-only: ${errorMessage(err)}` };
|
|
419
|
+
}
|
|
420
|
+
}
|
|
309
421
|
|
|
310
|
-
|
|
311
|
-
|
|
312
|
-
|
|
313
|
-
|
|
314
|
-
|
|
315
|
-
|
|
316
|
-
|
|
317
|
-
|
|
318
|
-
|
|
319
|
-
|
|
320
|
-
|
|
321
|
-
|
|
422
|
+
function isTestRun(): boolean {
|
|
423
|
+
return process.env.NODE_ENV === 'test' || Boolean(process.env.JEST_WORKER_ID);
|
|
424
|
+
}
|
|
425
|
+
|
|
426
|
+
export async function runDoctor(options: DoctorOptions = {}): Promise<DoctorReport> {
|
|
427
|
+
const mode = options.mode ?? 'auto';
|
|
428
|
+
// Mirrors db.ts refusing real database paths under test: a test must name the
|
|
429
|
+
// service it talks to, or it would probe (and authenticate against) a real
|
|
430
|
+
// brain on the default port.
|
|
431
|
+
if (isTestRun() && mode !== 'local' && !options.apiUrl && !options.fetchFn) {
|
|
432
|
+
throw new Error(
|
|
433
|
+
"runDoctor() under test must pass mode: 'local' or an explicit apiUrl/fetchFn; refusing to probe a real service."
|
|
434
|
+
);
|
|
435
|
+
}
|
|
436
|
+
const runAi = options.ai !== false;
|
|
437
|
+
const fetchFn = options.fetchFn ?? createLocalTlsFetch();
|
|
438
|
+
const apiUrl = (options.apiUrl ?? resolveApiUrl({}, packageRoot(), process.cwd())).replace(/\/+$/, '');
|
|
439
|
+
|
|
440
|
+
let source: DoctorSource = 'local';
|
|
441
|
+
let target = '';
|
|
442
|
+
let findings: Findings;
|
|
443
|
+
|
|
444
|
+
const health = mode === 'local' ? null : await probeHealth(fetchFn, apiUrl);
|
|
445
|
+
|
|
446
|
+
if (health) {
|
|
447
|
+
source = 'service';
|
|
448
|
+
target = apiUrl;
|
|
449
|
+
const apiKey = options.apiKey ?? resolveApiKey({}, packageRoot(), process.cwd());
|
|
450
|
+
findings = await runServiceChecks(fetchFn, apiUrl, apiKey, health, runAi);
|
|
451
|
+
} else if (mode === 'service') {
|
|
452
|
+
source = 'service';
|
|
453
|
+
target = apiUrl;
|
|
454
|
+
findings = {
|
|
455
|
+
dbOk: false,
|
|
456
|
+
schemaAligned: false,
|
|
457
|
+
storeMetaMatch: false,
|
|
458
|
+
counts: ZERO_COUNTS,
|
|
459
|
+
aiDiagnostics: runAi ? FAILED_AI : SKIPPED_AI,
|
|
460
|
+
checks: [{ name: 'Service Reachable', pass: false, message: `No response from ${apiUrl}/health` }],
|
|
461
|
+
};
|
|
462
|
+
} else if (options.db) {
|
|
463
|
+
target = 'provided connection';
|
|
464
|
+
findings = runLocalChecks(options.db, target, null, runAi);
|
|
465
|
+
} else {
|
|
466
|
+
const dbPath = options.dbPath ?? getDbPath();
|
|
467
|
+
target = path.resolve(dbPath);
|
|
468
|
+
const { db, error } = openReadOnly(dbPath);
|
|
469
|
+
try {
|
|
470
|
+
findings = runLocalChecks(db, target, error, runAi);
|
|
471
|
+
} finally {
|
|
472
|
+
db?.close();
|
|
322
473
|
}
|
|
323
474
|
}
|
|
324
475
|
|
|
325
|
-
|
|
326
|
-
|
|
327
|
-
|
|
328
|
-
|
|
329
|
-
|
|
476
|
+
const { checks, aiDiagnostics, counts } = findings;
|
|
477
|
+
const totalChecks = checks.length;
|
|
478
|
+
const passedChecks = checks.filter((c) => c.pass).length;
|
|
479
|
+
// One verdict, computed once, so the report can never say "N/M passing" and
|
|
480
|
+
// "all checks passing" at the same time.
|
|
481
|
+
const allPassing =
|
|
482
|
+
passedChecks === totalChecks &&
|
|
483
|
+
findings.dbOk &&
|
|
484
|
+
findings.schemaAligned &&
|
|
485
|
+
findings.storeMetaMatch &&
|
|
486
|
+
aiDiagnostics.all_passing;
|
|
487
|
+
|
|
488
|
+
if (!options.quiet) {
|
|
489
|
+
console.log('\n╔══════════════════════════════════════════════════════════════╗');
|
|
490
|
+
console.log('║ NEURALBRAIN DOCTOR ║');
|
|
491
|
+
console.log('╚══════════════════════════════════════════════════════════════╝\n');
|
|
492
|
+
console.log(
|
|
493
|
+
source === 'service'
|
|
494
|
+
? ` Source: running service at ${target}\n`
|
|
495
|
+
: ` Source: service not reachable at ${apiUrl}; inspected ${target} read-only\n`
|
|
496
|
+
);
|
|
497
|
+
|
|
498
|
+
for (const check of checks) {
|
|
499
|
+
const symbol = check.pass ? '✓ PASS' : '✗ FAIL';
|
|
500
|
+
console.log(` [${symbol}] ${check.name.padEnd(28)} : ${check.message}`);
|
|
501
|
+
}
|
|
502
|
+
|
|
503
|
+
console.log('\n Operational Metrics:');
|
|
504
|
+
console.log(` - Dead Letters Recorded : ${counts.dead_letters}`);
|
|
505
|
+
console.log(` - Unknown-Scope Notes : ${counts.unknown_scope_notes}`);
|
|
506
|
+
console.log(` - Total Notes : ${counts.notes}`);
|
|
507
|
+
console.log(` - Trajectories Stored : ${counts.trajectories}`);
|
|
508
|
+
console.log(` - Observations Stored : ${counts.observations}`);
|
|
509
|
+
|
|
510
|
+
if (aiDiagnostics.results && aiDiagnostics.results.length > 0) {
|
|
511
|
+
console.log('\n AI Diagnostics Breakdown:');
|
|
512
|
+
for (const r of aiDiagnostics.results) {
|
|
513
|
+
console.log(` ${r.pass ? '✓' : '✗'} ${r.name}`);
|
|
514
|
+
}
|
|
515
|
+
}
|
|
516
|
+
|
|
517
|
+
console.log('\n══════════════════════════════════════════════════════════════');
|
|
518
|
+
console.log(
|
|
519
|
+
allPassing
|
|
520
|
+
? ' Final Verdict: PASS (All checks passing)'
|
|
521
|
+
: ` Final Verdict: FAIL (${passedChecks}/${totalChecks} checks passing)`
|
|
522
|
+
);
|
|
523
|
+
console.log('══════════════════════════════════════════════════════════════\n');
|
|
330
524
|
}
|
|
331
|
-
console.log('══════════════════════════════════════════════════════════════\n');
|
|
332
525
|
|
|
333
526
|
if (options.exitOnFinish) {
|
|
334
527
|
process.exit(allPassing ? 0 : 1);
|
|
@@ -336,23 +529,29 @@ export async function runDoctor(options: {
|
|
|
336
529
|
|
|
337
530
|
return {
|
|
338
531
|
allPassing,
|
|
339
|
-
|
|
340
|
-
|
|
341
|
-
|
|
342
|
-
|
|
343
|
-
|
|
344
|
-
|
|
345
|
-
|
|
346
|
-
|
|
532
|
+
source,
|
|
533
|
+
target,
|
|
534
|
+
dbOk: findings.dbOk,
|
|
535
|
+
schemaAligned: findings.schemaAligned,
|
|
536
|
+
storeMetaMatch: findings.storeMetaMatch,
|
|
537
|
+
deadLetterCount: counts.dead_letters,
|
|
538
|
+
unknownScopeCount: counts.unknown_scope_notes,
|
|
539
|
+
noteCount: counts.notes,
|
|
540
|
+
trajectoryCount: counts.trajectories,
|
|
541
|
+
observationCount: counts.observations,
|
|
347
542
|
aiDiagnostics,
|
|
348
543
|
checks,
|
|
349
544
|
};
|
|
350
545
|
}
|
|
351
546
|
|
|
352
547
|
if (require.main === module) {
|
|
548
|
+
// `npm run doctor` runs this file directly; `neuralbrain doctor` has already
|
|
549
|
+
// loaded the env, and loadBrainEnv never clobbers what is set.
|
|
550
|
+
loadBrainEnv();
|
|
353
551
|
const isNoAi = process.argv.includes('--no-ai');
|
|
354
552
|
const isAi = (process.argv.includes('--ai') || process.argv.includes('--consolidator')) && !isNoAi;
|
|
355
|
-
|
|
553
|
+
const mode = process.argv.includes('--local') ? 'local' : process.argv.includes('--service') ? 'service' : 'auto';
|
|
554
|
+
runDoctor({ ai: isNoAi ? false : isAi, exitOnFinish: true, mode }).catch((err) => {
|
|
356
555
|
console.error('Doctor execution crashed:', err);
|
|
357
556
|
process.exit(1);
|
|
358
557
|
});
|