neuralbrain 0.0.2 → 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.
Files changed (226) hide show
  1. package/.env.example +2 -2
  2. package/README.md +19 -4
  3. package/dist/ai/chat.d.ts +1 -2
  4. package/dist/ai/chat.d.ts.map +1 -1
  5. package/dist/ai/chat.js +1 -2
  6. package/dist/ai/chat.js.map +1 -1
  7. package/dist/ai/config.d.ts +1 -1
  8. package/dist/ai/config.js +2 -2
  9. package/dist/ai/config.js.map +1 -1
  10. package/dist/app.d.ts +1 -0
  11. package/dist/app.d.ts.map +1 -1
  12. package/dist/app.js +417 -50
  13. package/dist/app.js.map +1 -1
  14. package/dist/cli.d.ts +53 -2
  15. package/dist/cli.d.ts.map +1 -1
  16. package/dist/cli.js +437 -37
  17. package/dist/cli.js.map +1 -1
  18. package/dist/consolidation/candidates.d.ts.map +1 -1
  19. package/dist/consolidation/candidates.js +19 -4
  20. package/dist/consolidation/candidates.js.map +1 -1
  21. package/dist/consolidation/fixtures.js +1 -1
  22. package/dist/consolidation/fixtures.js.map +1 -1
  23. package/dist/consolidation/gate.d.ts.map +1 -1
  24. package/dist/consolidation/gate.js +145 -109
  25. package/dist/consolidation/gate.js.map +1 -1
  26. package/dist/consolidation/runner.d.ts +6 -0
  27. package/dist/consolidation/runner.d.ts.map +1 -1
  28. package/dist/consolidation/runner.js +22 -2
  29. package/dist/consolidation/runner.js.map +1 -1
  30. package/dist/dashboard/clientScript.d.ts +1 -1
  31. package/dist/dashboard/clientScript.d.ts.map +1 -1
  32. package/dist/dashboard/clientScript.js +3774 -905
  33. package/dist/dashboard/clientScript.js.map +1 -1
  34. package/dist/dashboard/html.d.ts.map +1 -1
  35. package/dist/dashboard/html.js +605 -101
  36. package/dist/dashboard/html.js.map +1 -1
  37. package/dist/dashboard/styles.d.ts +1 -1
  38. package/dist/dashboard/styles.d.ts.map +1 -1
  39. package/dist/dashboard/styles.js +1591 -359
  40. package/dist/dashboard/styles.js.map +1 -1
  41. package/dist/learning/embedWorker.d.ts +13 -0
  42. package/dist/learning/embedWorker.d.ts.map +1 -1
  43. package/dist/learning/embedWorker.js +329 -59
  44. package/dist/learning/embedWorker.js.map +1 -1
  45. package/dist/learning/embedding.d.ts +1 -0
  46. package/dist/learning/embedding.d.ts.map +1 -1
  47. package/dist/learning/embedding.js +101 -26
  48. package/dist/learning/embedding.js.map +1 -1
  49. package/dist/learning/engine.js +1 -1
  50. package/dist/learning/engine.js.map +1 -1
  51. package/dist/learning/search.d.ts +17 -1
  52. package/dist/learning/search.d.ts.map +1 -1
  53. package/dist/learning/search.js +2094 -354
  54. package/dist/learning/search.js.map +1 -1
  55. package/dist/learning/storeMeta.d.ts +9 -0
  56. package/dist/learning/storeMeta.d.ts.map +1 -1
  57. package/dist/learning/storeMeta.js +30 -24
  58. package/dist/learning/storeMeta.js.map +1 -1
  59. package/dist/learning/types.d.ts +57 -8
  60. package/dist/learning/types.d.ts.map +1 -1
  61. package/dist/lib/condenser.d.ts +112 -0
  62. package/dist/lib/condenser.d.ts.map +1 -0
  63. package/dist/lib/condenser.js +1337 -0
  64. package/dist/lib/condenser.js.map +1 -0
  65. package/dist/lib/db.d.ts +10 -0
  66. package/dist/lib/db.d.ts.map +1 -1
  67. package/dist/lib/db.js +654 -167
  68. package/dist/lib/db.js.map +1 -1
  69. package/dist/lib/logger.d.ts.map +1 -1
  70. package/dist/lib/logger.js +3 -2
  71. package/dist/lib/logger.js.map +1 -1
  72. package/dist/lib/projectSlug.d.ts +12 -5
  73. package/dist/lib/projectSlug.d.ts.map +1 -1
  74. package/dist/lib/projectSlug.js +62 -23
  75. package/dist/lib/projectSlug.js.map +1 -1
  76. package/dist/lib/recurrence.d.ts +16 -0
  77. package/dist/lib/recurrence.d.ts.map +1 -0
  78. package/dist/lib/recurrence.js +293 -0
  79. package/dist/lib/recurrence.js.map +1 -0
  80. package/dist/lib/scope.d.ts +36 -1
  81. package/dist/lib/scope.d.ts.map +1 -1
  82. package/dist/lib/scope.js +183 -19
  83. package/dist/lib/scope.js.map +1 -1
  84. package/dist/lib/signalTags.d.ts +39 -0
  85. package/dist/lib/signalTags.d.ts.map +1 -0
  86. package/dist/lib/signalTags.js +203 -0
  87. package/dist/lib/signalTags.js.map +1 -0
  88. package/dist/lib/spool.d.ts +2 -0
  89. package/dist/lib/spool.d.ts.map +1 -1
  90. package/dist/lib/spool.js +176 -65
  91. package/dist/lib/spool.js.map +1 -1
  92. package/dist/lib/storeDiagnostics.d.ts +41 -0
  93. package/dist/lib/storeDiagnostics.d.ts.map +1 -0
  94. package/dist/lib/storeDiagnostics.js +148 -0
  95. package/dist/lib/storeDiagnostics.js.map +1 -0
  96. package/dist/lib/temporal.d.ts +44 -0
  97. package/dist/lib/temporal.d.ts.map +1 -0
  98. package/dist/lib/temporal.js +1063 -0
  99. package/dist/lib/temporal.js.map +1 -0
  100. package/dist/mcp/server.d.ts +93 -3
  101. package/dist/mcp/server.d.ts.map +1 -1
  102. package/dist/mcp/server.js +499 -68
  103. package/dist/mcp/server.js.map +1 -1
  104. package/dist/memory/actionStore.d.ts +94 -3
  105. package/dist/memory/actionStore.d.ts.map +1 -1
  106. package/dist/memory/actionStore.js +412 -124
  107. package/dist/memory/actionStore.js.map +1 -1
  108. package/dist/memory/deadLetterStore.d.ts.map +1 -1
  109. package/dist/memory/deadLetterStore.js +4 -2
  110. package/dist/memory/deadLetterStore.js.map +1 -1
  111. package/dist/memory/embedQueueStore.d.ts +19 -8
  112. package/dist/memory/embedQueueStore.d.ts.map +1 -1
  113. package/dist/memory/embedQueueStore.js +55 -25
  114. package/dist/memory/embedQueueStore.js.map +1 -1
  115. package/dist/memory/failurePatternStore.d.ts +17 -1
  116. package/dist/memory/failurePatternStore.d.ts.map +1 -1
  117. package/dist/memory/failurePatternStore.js +54 -31
  118. package/dist/memory/failurePatternStore.js.map +1 -1
  119. package/dist/memory/graphStore.d.ts +133 -3
  120. package/dist/memory/graphStore.d.ts.map +1 -1
  121. package/dist/memory/graphStore.js +980 -155
  122. package/dist/memory/graphStore.js.map +1 -1
  123. package/dist/memory/noteStore.d.ts +27 -2
  124. package/dist/memory/noteStore.d.ts.map +1 -1
  125. package/dist/memory/noteStore.js +89 -26
  126. package/dist/memory/noteStore.js.map +1 -1
  127. package/dist/memory/observationStore.d.ts +11 -1
  128. package/dist/memory/observationStore.d.ts.map +1 -1
  129. package/dist/memory/observationStore.js +90 -15
  130. package/dist/memory/observationStore.js.map +1 -1
  131. package/dist/memory/projectRename.d.ts.map +1 -1
  132. package/dist/memory/projectRename.js +5 -1
  133. package/dist/memory/projectRename.js.map +1 -1
  134. package/dist/memory/rollupSweeper.d.ts.map +1 -1
  135. package/dist/memory/rollupSweeper.js +43 -23
  136. package/dist/memory/rollupSweeper.js.map +1 -1
  137. package/dist/memory/sessionStore.d.ts +25 -7
  138. package/dist/memory/sessionStore.d.ts.map +1 -1
  139. package/dist/memory/sessionStore.js +145 -33
  140. package/dist/memory/sessionStore.js.map +1 -1
  141. package/dist/memory/trajectoryStore.d.ts +8 -0
  142. package/dist/memory/trajectoryStore.d.ts.map +1 -1
  143. package/dist/memory/trajectoryStore.js +196 -130
  144. package/dist/memory/trajectoryStore.js.map +1 -1
  145. package/dist/middleware/rateLimiter.d.ts.map +1 -1
  146. package/dist/middleware/rateLimiter.js +24 -1
  147. package/dist/middleware/rateLimiter.js.map +1 -1
  148. package/dist/routes/dashboard.d.ts.map +1 -1
  149. package/dist/routes/dashboard.js +181 -8
  150. package/dist/routes/dashboard.js.map +1 -1
  151. package/dist/routes/mcp.d.ts.map +1 -1
  152. package/dist/routes/mcp.js +173 -21
  153. package/dist/routes/mcp.js.map +1 -1
  154. package/dist/routes/memories.js +9 -1
  155. package/dist/routes/memories.js.map +1 -1
  156. package/dist/scripts/doctor.d.ts +26 -2
  157. package/dist/scripts/doctor.d.ts.map +1 -1
  158. package/dist/scripts/doctor.js +371 -259
  159. package/dist/scripts/doctor.js.map +1 -1
  160. package/dist/scripts/installAgent.d.ts.map +1 -1
  161. package/dist/scripts/installAgent.js +101 -19
  162. package/dist/scripts/installAgent.js.map +1 -1
  163. package/dist/scripts/migrateAgentMemory.js +2 -2
  164. package/dist/scripts/smokeTest.js +1 -1
  165. package/dist/scripts/smokeTest.js.map +1 -1
  166. package/docker-compose.yml +1 -1
  167. package/npm-shrinkwrap.json +2 -2
  168. package/package.json +1 -1
  169. package/plugin/hooks/postToolUse.js +155 -50
  170. package/plugin/hooks/sessionStart.js +179 -27
  171. package/plugin/hooks/sessionStop.js +152 -37
  172. package/plugin/plugin.json +1 -1
  173. package/plugin/rules/AGENTS.md +10 -8
  174. package/plugin/skills/brain-memory/REFERENCE.md +15 -14
  175. package/plugin/skills/brain-memory/SKILL.md +2 -2
  176. package/plugin/skills/digest/SKILL.md +1 -1
  177. package/plugin/skills/handoff/SKILL.md +1 -1
  178. package/plugin/skills/save/SKILL.md +2 -2
  179. package/plugin/skills/search/SKILL.md +2 -2
  180. package/src/ai/chat.ts +1 -2
  181. package/src/ai/config.ts +2 -2
  182. package/src/app.ts +475 -54
  183. package/src/cli.ts +500 -38
  184. package/src/consolidation/candidates.ts +22 -4
  185. package/src/consolidation/fixtures.ts +1 -1
  186. package/src/consolidation/gate.ts +177 -140
  187. package/src/consolidation/runner.ts +26 -2
  188. package/src/dashboard/clientScript.ts +3774 -905
  189. package/src/dashboard/html.ts +605 -101
  190. package/src/dashboard/styles.ts +1591 -359
  191. package/src/learning/embedWorker.ts +350 -70
  192. package/src/learning/embedding.ts +141 -28
  193. package/src/learning/engine.ts +1 -1
  194. package/src/learning/search.ts +2533 -397
  195. package/src/learning/storeMeta.ts +36 -29
  196. package/src/learning/types.ts +66 -8
  197. package/src/lib/condenser.ts +1515 -0
  198. package/src/lib/db.ts +690 -171
  199. package/src/lib/logger.ts +4 -2
  200. package/src/lib/projectSlug.ts +77 -23
  201. package/src/lib/recurrence.ts +382 -0
  202. package/src/lib/scope.ts +220 -22
  203. package/src/lib/signalTags.ts +257 -0
  204. package/src/lib/spool.ts +181 -71
  205. package/src/lib/storeDiagnostics.ts +181 -0
  206. package/src/lib/temporal.ts +1250 -0
  207. package/src/mcp/server.ts +559 -88
  208. package/src/memory/actionStore.ts +642 -171
  209. package/src/memory/deadLetterStore.ts +4 -2
  210. package/src/memory/embedQueueStore.ts +63 -27
  211. package/src/memory/failurePatternStore.ts +84 -31
  212. package/src/memory/graphStore.ts +1396 -215
  213. package/src/memory/noteStore.ts +151 -30
  214. package/src/memory/observationStore.ts +117 -17
  215. package/src/memory/projectRename.ts +6 -2
  216. package/src/memory/rollupSweeper.ts +46 -23
  217. package/src/memory/sessionStore.ts +197 -38
  218. package/src/memory/trajectoryStore.ts +260 -140
  219. package/src/middleware/rateLimiter.ts +24 -1
  220. package/src/routes/dashboard.ts +194 -9
  221. package/src/routes/mcp.ts +185 -26
  222. package/src/routes/memories.ts +8 -1
  223. package/src/scripts/doctor.ts +461 -262
  224. package/src/scripts/installAgent.ts +106 -19
  225. package/src/scripts/migrateAgentMemory.ts +2 -2
  226. package/src/scripts/smokeTest.ts +1 -1
@@ -1,11 +1,24 @@
1
- import { getDb } from '../lib/db';
2
- import { logger } from '../lib/logger';
3
- import { verifyOrCreateStoreMeta } from '../learning/storeMeta';
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 async function runDoctor(options: {
55
+ export interface DoctorOptions {
31
56
  ai?: boolean;
32
57
  exitOnFinish?: boolean;
33
- } = {}): Promise<DoctorReport> {
34
- const checks: DoctorCheck[] = [];
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
- // 1. Database Health Check
37
- let dbOk = false;
38
- let journalMode = 'unknown';
39
- try {
40
- const db = getDb();
41
- const row = db.prepare('SELECT 1 as val').get() as { val: number } | undefined;
42
- const pragmaRow = db.prepare('PRAGMA journal_mode').get() as { journal_mode: string } | undefined;
43
- journalMode = pragmaRow?.journal_mode || 'unknown';
44
- if (row?.val === 1) {
45
- dbOk = true;
46
- checks.push({
47
- name: 'Database Health',
48
- pass: true,
49
- message: `Database accessible and functional (journal_mode: ${journalMode})`,
50
- });
51
- } else {
52
- checks.push({
53
- name: 'Database Health',
54
- pass: false,
55
- message: 'Database query returned unexpected result',
56
- });
57
- }
58
- } catch (err) {
59
- checks.push({
60
- name: 'Database Health',
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: `Database connection error: ${err instanceof Error ? err.message : String(err)}`,
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
- // 1b. Schema Alignment Check (Q27)
67
- let schemaAligned = false;
68
- if (dbOk) {
69
- try {
70
- const db = getDb();
71
- const issues: string[] = [];
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
- const getTableColumns = (tableName: string): Map<string, { name: string; notnull: number; type: string }> => {
80
- const rows = db.prepare(`PRAGMA table_info(${tableName})`).all() as Array<{ name: string; notnull: number; type: string }>;
81
- return new Map(rows.map((r) => [r.name, r]));
82
- };
83
-
84
- // trajectories check
85
- const trajCols = getTableColumns('trajectories');
86
- if (trajCols.size === 0) {
87
- issues.push('table trajectories does not exist');
88
- } else {
89
- const successCol = trajCols.get('success');
90
- if (!successCol) issues.push('trajectories.success missing');
91
- else if (successCol.notnull !== 0) issues.push('trajectories.success is not nullable (notnull=1)');
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
- // trajectory_archive check
103
- const trajArcCols = getTableColumns('trajectory_archive');
104
- if (trajArcCols.size === 0) {
105
- issues.push('table trajectory_archive does not exist');
106
- } else {
107
- const successCol = trajArcCols.get('success');
108
- if (!successCol) issues.push('trajectory_archive.success missing');
109
- else if (successCol.notnull !== 0) issues.push('trajectory_archive.success is not nullable (notnull=1)');
110
-
111
- const projCol = trajArcCols.get('project_id');
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
- // observations and observations_archive project_id check
121
- const obsCols = getTableColumns('observations');
122
- if (obsCols.size === 0) {
123
- issues.push('table observations does not exist');
124
- } else {
125
- const projCol = obsCols.get('project_id');
126
- if (!projCol) issues.push('observations.project_id missing');
127
- else if (projCol.notnull !== 0) issues.push('observations.project_id is not nullable (notnull=1)');
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
- const obsArcCols = getTableColumns('observations_archive');
131
- if (obsArcCols.size === 0) {
132
- issues.push('table observations_archive does not exist');
133
- } else {
134
- const projCol = obsArcCols.get('project_id');
135
- if (!projCol) issues.push('observations_archive.project_id missing');
136
- else if (projCol.notnull !== 0) issues.push('observations_archive.project_id is not nullable (notnull=1)');
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 (issues.length === 0) {
140
- schemaAligned = true;
141
- checks.push({
142
- name: 'Schema Alignment',
143
- pass: true,
144
- message: 'Relational schema aligned and foreign keys enabled',
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
- checks.push({
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
- } else {
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: 'Database inaccessible, skipping schema alignment check',
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 Meta Consistency Check
169
- let storeMetaMatch = false;
170
- try {
171
- const metaRes = verifyOrCreateStoreMeta();
172
- storeMetaMatch = metaRes.match;
173
- if (metaRes.match) {
174
- checks.push({
175
- name: 'Store Meta Consistency',
176
- pass: true,
177
- message: `Consistent with active config (tier: ${metaRes.recipe.embed_tier}, dim: ${metaRes.recipe.embed_dim})`,
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
- checks.push({
181
- name: 'Store Meta Consistency',
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
- } catch (err) {
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
- // 3. Operational Counts (Dead Letters, Notes, Trajectories, Observations)
195
- let deadLetterCount = 0;
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
- const unk = db.prepare("SELECT COUNT(*) as count FROM notes WHERE scope = 'unknown'").get() as { count: number };
208
- unknownScopeCount = unk?.count ?? 0;
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
- const notes = db.prepare('SELECT COUNT(*) as count FROM notes').get() as { count: number };
211
- noteCount = notes?.count ?? 0;
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
- const traj = db.prepare('SELECT COUNT(*) as count FROM trajectories').get() as { count: number };
214
- trajectoryCount = traj?.count ?? 0;
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
- const obs = db.prepare('SELECT COUNT(*) as count FROM observations').get() as { count: number };
217
- observationCount = obs?.count ?? 0;
218
- } catch (err) {
219
- logger.warn({ error: err }, 'failed to query operational counts');
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
- // 3b. Generative producer configuration. Resolving a tier is what surfaces
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
- const aiConfig = describeAiConfig() as Record<string, any>;
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: ${err instanceof Error ? err.message : String(err)}`,
382
+ message: `Failed to resolve generative config: ${errorMessage(err)}`,
252
383
  });
253
384
  }
254
385
 
255
- // 4. AI Conformance Diagnostics (runs conformance fixtures)
256
- let aiDiagnostics: AiDiagnosticsReport;
257
- const shouldRunAi = options?.ai !== false;
258
- if (shouldRunAi) {
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
- status: 'failed',
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
- aiDiagnostics = {
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
- // Compute single definitive boolean to prevent contradiction
296
- const totalChecks = checks.length;
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
- for (const check of checks) {
306
- const symbol = check.pass ? '✓ PASS' : '✗ FAIL';
307
- console.log(` [${symbol}] ${check.name.padEnd(28)} : ${check.message}`);
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
- console.log('\n Operational Metrics:');
311
- console.log(` - Dead Letters Recorded : ${deadLetterCount}`);
312
- console.log(` - Unknown-Scope Notes : ${unknownScopeCount}`);
313
- console.log(` - Total Notes : ${noteCount}`);
314
- console.log(` - Trajectories Stored : ${trajectoryCount}`);
315
- console.log(` - Observations Stored : ${observationCount}`);
316
-
317
- if (aiDiagnostics.results && aiDiagnostics.results.length > 0) {
318
- console.log('\n AI Diagnostics Breakdown:');
319
- for (const r of aiDiagnostics.results) {
320
- const sym = r.pass ? '✓' : '✗';
321
- console.log(` ${sym} ${r.name}`);
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
- console.log('\n══════════════════════════════════════════════════════════════');
326
- if (allPassing) {
327
- console.log(' Final Verdict: PASS (All checks passing)');
328
- } else {
329
- console.log(` Final Verdict: FAIL (${passedChecks}/${totalChecks} checks passing)`);
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
- dbOk,
340
- schemaAligned,
341
- storeMetaMatch,
342
- deadLetterCount,
343
- unknownScopeCount,
344
- noteCount,
345
- trajectoryCount,
346
- observationCount,
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
- runDoctor({ ai: isNoAi ? false : isAi, exitOnFinish: true }).catch((err) => {
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
  });