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,330 +1,442 @@
1
1
  "use strict";
2
+ var __importDefault = (this && this.__importDefault) || function (mod) {
3
+ return (mod && mod.__esModule) ? mod : { "default": mod };
4
+ };
2
5
  Object.defineProperty(exports, "__esModule", { value: true });
3
6
  exports.runDoctor = runDoctor;
7
+ const fs_1 = __importDefault(require("fs"));
8
+ const path_1 = __importDefault(require("path"));
4
9
  const db_1 = require("../lib/db");
5
- const logger_1 = require("../lib/logger");
10
+ const brainHome_1 = require("../lib/brainHome");
11
+ const sqlite_1 = require("../lib/sqlite");
12
+ const tls_1 = require("../lib/tls");
13
+ const storeDiagnostics_1 = require("../lib/storeDiagnostics");
6
14
  const storeMeta_1 = require("../learning/storeMeta");
15
+ const embedding_1 = require("../learning/embedding");
7
16
  const fixtures_1 = require("../consolidation/fixtures");
8
17
  const config_1 = require("../ai/config");
9
- async function runDoctor(options = {}) {
10
- const checks = [];
11
- // 1. Database Health Check
12
- let dbOk = false;
13
- let journalMode = 'unknown';
18
+ const installAgent_1 = require("./installAgent");
19
+ const HEALTH_TIMEOUT_MS = 3000;
20
+ const REQUEST_TIMEOUT_MS = 60000;
21
+ const SKIPPED_AI = {
22
+ status: 'ok',
23
+ all_passing: true,
24
+ passed_count: 0,
25
+ total_count: 0,
26
+ results: [],
27
+ };
28
+ const FAILED_AI = {
29
+ status: 'failed',
30
+ all_passing: false,
31
+ passed_count: 0,
32
+ total_count: 0,
33
+ results: [],
34
+ };
35
+ const ZERO_COUNTS = {
36
+ dead_letters: 0,
37
+ unknown_scope_notes: 0,
38
+ notes: 0,
39
+ trajectories: 0,
40
+ observations: 0,
41
+ };
42
+ function errorMessage(err) {
43
+ return err instanceof Error ? err.message : String(err);
44
+ }
45
+ function packageRoot() {
46
+ return path_1.default.resolve(__dirname, '..', '..');
47
+ }
48
+ function describeGenerativeConfig(aiConfig) {
49
+ const broken = ['summarize', 'consolidate'].filter((fn) => !aiConfig[fn]?.ok);
50
+ if (broken.length > 0) {
51
+ return {
52
+ name: 'Generative Producer Config',
53
+ pass: false,
54
+ message: broken.map((fn) => `${fn}: ${aiConfig[fn]?.error ?? 'not resolved'}`).join(' | '),
55
+ };
56
+ }
57
+ const fmt = (fn) => `${aiConfig[fn].tier}${aiConfig[fn].model ? ` (${aiConfig[fn].model})` : ''}`;
58
+ return {
59
+ name: 'Generative Producer Config',
60
+ pass: true,
61
+ message: `summarize: ${fmt('summarize')}, consolidate: ${fmt('consolidate')}`,
62
+ };
63
+ }
64
+ function aiCheck(report) {
65
+ return {
66
+ name: 'AI Conformance Diagnostics',
67
+ pass: report.all_passing,
68
+ message: `${report.passed_count}/${report.total_count} assertions passed`,
69
+ };
70
+ }
71
+ async function fetchWithTimeout(fetchFn, url, init, timeoutMs) {
72
+ const controller = new AbortController();
73
+ const timer = setTimeout(() => controller.abort(), timeoutMs);
14
74
  try {
15
- const db = (0, db_1.getDb)();
16
- const row = db.prepare('SELECT 1 as val').get();
17
- const pragmaRow = db.prepare('PRAGMA journal_mode').get();
18
- journalMode = pragmaRow?.journal_mode || 'unknown';
19
- if (row?.val === 1) {
20
- dbOk = true;
21
- checks.push({
22
- name: 'Database Health',
23
- pass: true,
24
- message: `Database accessible and functional (journal_mode: ${journalMode})`,
25
- });
26
- }
27
- else {
28
- checks.push({
29
- name: 'Database Health',
30
- pass: false,
31
- message: 'Database query returned unexpected result',
32
- });
33
- }
75
+ return await fetchFn(url, { ...init, signal: controller.signal });
34
76
  }
35
- catch (err) {
36
- checks.push({
37
- name: 'Database Health',
38
- pass: false,
39
- message: `Database connection error: ${err instanceof Error ? err.message : String(err)}`,
40
- });
77
+ finally {
78
+ clearTimeout(timer);
41
79
  }
42
- // 1b. Schema Alignment Check (Q27)
43
- let schemaAligned = false;
44
- if (dbOk) {
80
+ }
81
+ /** Returns the parsed /health body, or null when nothing answered. */
82
+ async function probeHealth(fetchFn, apiUrl) {
83
+ try {
84
+ const res = await fetchWithTimeout(fetchFn, `${apiUrl}/health`, {}, HEALTH_TIMEOUT_MS);
85
+ const body = (await res.json().catch(() => null));
86
+ return body && typeof body === 'object' ? body : null;
87
+ }
88
+ catch {
89
+ return null;
90
+ }
91
+ }
92
+ async function runServiceChecks(fetchFn, apiUrl, apiKey, health, runAi) {
93
+ const checks = [];
94
+ const headers = apiKey ? { Authorization: `Bearer ${apiKey}` } : {};
95
+ const getJson = async (route) => {
45
96
  try {
46
- const db = (0, db_1.getDb)();
47
- const issues = [];
48
- // Foreign keys pragma
49
- const fkRow = db.prepare('PRAGMA foreign_keys').get();
50
- if (fkRow?.foreign_keys !== 1) {
51
- issues.push('PRAGMA foreign_keys is not active');
52
- }
53
- const getTableColumns = (tableName) => {
54
- const rows = db.prepare(`PRAGMA table_info(${tableName})`).all();
55
- return new Map(rows.map((r) => [r.name, r]));
56
- };
57
- // trajectories check
58
- const trajCols = getTableColumns('trajectories');
59
- if (trajCols.size === 0) {
60
- issues.push('table trajectories does not exist');
61
- }
62
- else {
63
- const successCol = trajCols.get('success');
64
- if (!successCol)
65
- issues.push('trajectories.success missing');
66
- else if (successCol.notnull !== 0)
67
- issues.push('trajectories.success is not nullable (notnull=1)');
68
- const projCol = trajCols.get('project_id');
69
- if (!projCol)
70
- issues.push('trajectories.project_id missing');
71
- else if (projCol.notnull !== 0)
72
- issues.push('trajectories.project_id is not nullable (notnull=1)');
73
- for (const col of ['session_id', 'rollup_source', 'tool_calls']) {
74
- if (!trajCols.has(col))
75
- issues.push(`trajectories.${col} missing`);
76
- }
77
- }
78
- // trajectory_archive check
79
- const trajArcCols = getTableColumns('trajectory_archive');
80
- if (trajArcCols.size === 0) {
81
- issues.push('table trajectory_archive does not exist');
82
- }
83
- else {
84
- const successCol = trajArcCols.get('success');
85
- if (!successCol)
86
- issues.push('trajectory_archive.success missing');
87
- else if (successCol.notnull !== 0)
88
- issues.push('trajectory_archive.success is not nullable (notnull=1)');
89
- const projCol = trajArcCols.get('project_id');
90
- if (!projCol)
91
- issues.push('trajectory_archive.project_id missing');
92
- else if (projCol.notnull !== 0)
93
- issues.push('trajectory_archive.project_id is not nullable (notnull=1)');
94
- for (const col of ['session_id', 'rollup_source', 'tool_calls']) {
95
- if (!trajArcCols.has(col))
96
- issues.push(`trajectory_archive.${col} missing`);
97
- }
97
+ const res = await fetchWithTimeout(fetchFn, `${apiUrl}${route}`, { headers }, REQUEST_TIMEOUT_MS);
98
+ if (res.status === 401) {
99
+ return {
100
+ ok: false,
101
+ error: `GET ${route} was rejected (401): set BRAIN_API_KEY to a valid key for this service`,
102
+ };
98
103
  }
99
- // observations and observations_archive project_id check
100
- const obsCols = getTableColumns('observations');
101
- if (obsCols.size === 0) {
102
- issues.push('table observations does not exist');
103
- }
104
- else {
105
- const projCol = obsCols.get('project_id');
106
- if (!projCol)
107
- issues.push('observations.project_id missing');
108
- else if (projCol.notnull !== 0)
109
- issues.push('observations.project_id is not nullable (notnull=1)');
110
- }
111
- const obsArcCols = getTableColumns('observations_archive');
112
- if (obsArcCols.size === 0) {
113
- issues.push('table observations_archive does not exist');
114
- }
115
- else {
116
- const projCol = obsArcCols.get('project_id');
117
- if (!projCol)
118
- issues.push('observations_archive.project_id missing');
119
- else if (projCol.notnull !== 0)
120
- issues.push('observations_archive.project_id is not nullable (notnull=1)');
121
- }
122
- if (issues.length === 0) {
123
- schemaAligned = true;
124
- checks.push({
125
- name: 'Schema Alignment',
126
- pass: true,
127
- message: 'Relational schema aligned and foreign keys enabled',
128
- });
129
- }
130
- else {
131
- checks.push({
132
- name: 'Schema Alignment',
133
- pass: false,
134
- message: `Schema misalignment detected: ${issues.join('; ')}`,
135
- });
104
+ const body = (await res.json().catch(() => null));
105
+ if (!res.ok || body === null) {
106
+ return {
107
+ ok: false,
108
+ status: res.status,
109
+ error: `GET ${route} returned ${res.status}${body?.error?.message ? `: ${body.error.message}` : ''}`,
110
+ };
136
111
  }
112
+ return { ok: true, body };
137
113
  }
138
114
  catch (err) {
139
- checks.push({
140
- name: 'Schema Alignment',
141
- pass: false,
142
- message: `Failed to inspect schema: ${err instanceof Error ? err.message : String(err)}`,
143
- });
115
+ return { ok: false, error: `GET ${route} failed: ${errorMessage(err)}` };
144
116
  }
145
- }
146
- else {
117
+ };
118
+ // 1. Database health and schema, inspected by the service on its own connection.
119
+ let dbOk = false;
120
+ let schemaAligned = false;
121
+ let counts = ZERO_COUNTS;
122
+ const store = await getJson('/diagnostics/store');
123
+ if (!store.ok && store.status === 404) {
124
+ // A service older than this CLI: /health still answers for the database,
125
+ // but schema and counts need a restart on this version.
126
+ dbOk = health.db === 'ok';
127
+ checks.push({
128
+ name: 'Database Health',
129
+ pass: dbOk,
130
+ message: dbOk ? 'Database reported ok by /health' : `Database unhealthy: health reports db=${health.db}`,
131
+ });
147
132
  checks.push({
148
133
  name: 'Schema Alignment',
149
134
  pass: false,
150
- message: 'Database inaccessible, skipping schema alignment check',
135
+ message: `The service at ${apiUrl} predates GET /diagnostics/store; restart it on this version to check the schema`,
151
136
  });
152
137
  }
153
- // 2. Store Meta Consistency Check
154
- let storeMetaMatch = false;
155
- try {
156
- const metaRes = (0, storeMeta_1.verifyOrCreateStoreMeta)();
157
- storeMetaMatch = metaRes.match;
158
- if (metaRes.match) {
159
- checks.push({
160
- name: 'Store Meta Consistency',
138
+ else if (!store.ok) {
139
+ checks.push({ name: 'Database Health', pass: false, message: store.error });
140
+ checks.push({ name: 'Schema Alignment', pass: false, message: 'Skipped: store diagnostics unavailable' });
141
+ }
142
+ else {
143
+ dbOk = store.body.db?.ok === true && health.db === 'ok';
144
+ checks.push(dbOk
145
+ ? {
146
+ name: 'Database Health',
161
147
  pass: true,
162
- message: `Consistent with active config (tier: ${metaRes.recipe.embed_tier}, dim: ${metaRes.recipe.embed_dim})`,
163
- });
164
- }
165
- else {
166
- checks.push({
167
- name: 'Store Meta Consistency',
148
+ message: `Database accessible and functional (journal_mode: ${store.body.db.journal_mode})`,
149
+ }
150
+ : {
151
+ name: 'Database Health',
168
152
  pass: false,
169
- message: `Mismatch detected: ${metaRes.mismatchReason || 'configuration differs from store_meta'}`,
153
+ message: `Database unhealthy: ${store.body.db?.error || `health reports db=${health.db}`}`,
170
154
  });
171
- }
155
+ const issues = store.body.schema?.issues ?? [];
156
+ schemaAligned = store.body.schema?.aligned === true;
157
+ checks.push(schemaAligned
158
+ ? { name: 'Schema Alignment', pass: true, message: 'Relational schema aligned and foreign keys enabled' }
159
+ : { name: 'Schema Alignment', pass: false, message: `Schema misalignment detected: ${issues.join('; ')}` });
160
+ counts = store.body.counts ?? ZERO_COUNTS;
172
161
  }
173
- catch (err) {
174
- checks.push({
162
+ // 2. Store meta, as the service resolved it from its own environment. In
163
+ // Docker mode that environment is the container's, which can differ from the
164
+ // host shell the doctor runs in.
165
+ const meta = health.store_meta;
166
+ const storeMetaMatch = meta?.match === true;
167
+ checks.push(storeMetaMatch
168
+ ? {
169
+ name: 'Store Meta Consistency',
170
+ pass: true,
171
+ message: `Consistent with active config (tier: ${meta.embed_tier}, dim: ${meta.embed_dim})`,
172
+ }
173
+ : {
175
174
  name: 'Store Meta Consistency',
176
175
  pass: false,
177
- message: `Failed to verify store_meta: ${err instanceof Error ? err.message : String(err)}`,
176
+ message: `Mismatch detected: ${meta?.mismatch_reason || 'service reports store_meta mismatch'}`,
178
177
  });
179
- }
180
- // 3. Operational Counts (Dead Letters, Notes, Trajectories, Observations)
181
- let deadLetterCount = 0;
182
- let unknownScopeCount = 0;
183
- let noteCount = 0;
184
- let trajectoryCount = 0;
185
- let observationCount = 0;
186
- if (dbOk) {
187
- try {
188
- const db = (0, db_1.getDb)();
189
- const dl = db.prepare('SELECT COUNT(*) as count FROM dead_letters').get();
190
- deadLetterCount = dl?.count ?? 0;
191
- const unk = db.prepare("SELECT COUNT(*) as count FROM notes WHERE scope = 'unknown'").get();
192
- unknownScopeCount = unk?.count ?? 0;
193
- const notes = db.prepare('SELECT COUNT(*) as count FROM notes').get();
194
- noteCount = notes?.count ?? 0;
195
- const traj = db.prepare('SELECT COUNT(*) as count FROM trajectories').get();
196
- trajectoryCount = traj?.count ?? 0;
197
- const obs = db.prepare('SELECT COUNT(*) as count FROM observations').get();
198
- observationCount = obs?.count ?? 0;
178
+ // 3. Generative producer configuration, as the service resolved it.
179
+ const aiConfig = await getJson('/diagnostics/ai-config');
180
+ checks.push(aiConfig.ok
181
+ ? describeGenerativeConfig(aiConfig.body)
182
+ : { name: 'Generative Producer Config', pass: false, message: aiConfig.error });
183
+ // 4. AI conformance fixtures, run by the service (the only writer) against its store.
184
+ let aiDiagnostics = SKIPPED_AI;
185
+ if (runAi) {
186
+ const ai = await getJson('/diagnostics/ai');
187
+ if (ai.ok) {
188
+ aiDiagnostics = ai.body;
189
+ checks.push(aiCheck(aiDiagnostics));
199
190
  }
200
- catch (err) {
201
- logger_1.logger.warn({ error: err }, 'failed to query operational counts');
191
+ else {
192
+ aiDiagnostics = FAILED_AI;
193
+ checks.push({ name: 'AI Conformance Diagnostics', pass: false, message: ai.error });
202
194
  }
203
195
  }
204
- // 3b. Generative producer configuration. Resolving a tier is what surfaces
205
- // an impossible combination (a `vendor` tier with no key, `local` named for
206
- // a generative function), so it belongs in the doctor report rather than
207
- // waiting for the first consolidation run.
208
- try {
209
- const aiConfig = (0, config_1.describeAiConfig)();
210
- const broken = ['summarize', 'consolidate'].filter((fn) => !aiConfig[fn]?.ok);
211
- if (broken.length === 0) {
212
- checks.push({
213
- name: 'Generative Producer Config',
196
+ else {
197
+ checks.push({ name: 'AI Conformance Diagnostics', pass: true, message: 'Skipped (--no-ai)' });
198
+ }
199
+ return { dbOk, schemaAligned, storeMetaMatch, counts, aiDiagnostics, checks };
200
+ }
201
+ function runLocalChecks(db, dbLabel, openError, runAi) {
202
+ const checks = [];
203
+ let dbOk = false;
204
+ let schemaAligned = false;
205
+ let storeMetaMatch = false;
206
+ let counts = ZERO_COUNTS;
207
+ if (!db) {
208
+ checks.push({ name: 'Database Health', pass: false, message: openError || `Could not open ${dbLabel}` });
209
+ checks.push({ name: 'Schema Alignment', pass: false, message: 'Database inaccessible, skipping schema alignment check' });
210
+ checks.push({ name: 'Store Meta Consistency', pass: false, message: 'Database inaccessible, skipping store_meta check' });
211
+ }
212
+ else {
213
+ const health = (0, storeDiagnostics_1.inspectDatabaseHealth)(db);
214
+ dbOk = health.ok;
215
+ checks.push(dbOk
216
+ ? {
217
+ name: 'Database Health',
214
218
  pass: true,
215
- message: `summarize: ${aiConfig.summarize.tier}${aiConfig.summarize.model ? ` (${aiConfig.summarize.model})` : ''}, consolidate: ${aiConfig.consolidate.tier}${aiConfig.consolidate.model ? ` (${aiConfig.consolidate.model})` : ''}`,
219
+ message: `Database accessible read-only (journal_mode: ${health.journal_mode})`,
220
+ }
221
+ : {
222
+ name: 'Database Health',
223
+ pass: false,
224
+ message: `Database connection error: ${health.error}`,
216
225
  });
226
+ if (dbOk) {
227
+ try {
228
+ // foreign_keys is per-connection; this read-only handle says nothing about the service's.
229
+ const schema = (0, storeDiagnostics_1.inspectSchemaAlignment)(db, { checkForeignKeys: false });
230
+ schemaAligned = schema.aligned;
231
+ checks.push(schemaAligned
232
+ ? { name: 'Schema Alignment', pass: true, message: 'Relational schema aligned' }
233
+ : {
234
+ name: 'Schema Alignment',
235
+ pass: false,
236
+ message: `Schema misalignment detected: ${schema.issues.join('; ')} (the service migrates the schema on start)`,
237
+ });
238
+ }
239
+ catch (err) {
240
+ checks.push({ name: 'Schema Alignment', pass: false, message: `Failed to inspect schema: ${errorMessage(err)}` });
241
+ }
242
+ try {
243
+ const existing = db.prepare('SELECT * FROM store_meta WHERE id = 1').get();
244
+ const recipe = (0, embedding_1.resolveEmbedderRecipe)();
245
+ if (!existing) {
246
+ // A fresh store: the service commits store_meta on its first start.
247
+ storeMetaMatch = true;
248
+ checks.push({
249
+ name: 'Store Meta Consistency',
250
+ pass: true,
251
+ message: `Not yet initialized; the service will commit tier ${recipe.embed_tier}, dim ${recipe.embed_dim} on first start`,
252
+ });
253
+ }
254
+ else {
255
+ const cmp = (0, storeMeta_1.compareStoreMeta)(existing, recipe);
256
+ storeMetaMatch = cmp.match;
257
+ checks.push(cmp.match
258
+ ? {
259
+ name: 'Store Meta Consistency',
260
+ pass: true,
261
+ message: `Consistent with active config (tier: ${recipe.embed_tier}, dim: ${recipe.embed_dim})`,
262
+ }
263
+ : { name: 'Store Meta Consistency', pass: false, message: `Mismatch detected: ${cmp.mismatchReason}` });
264
+ }
265
+ }
266
+ catch (err) {
267
+ checks.push({ name: 'Store Meta Consistency', pass: false, message: `Failed to verify store_meta: ${errorMessage(err)}` });
268
+ }
269
+ counts = (0, storeDiagnostics_1.countStoreRecords)(db);
217
270
  }
218
271
  else {
219
- checks.push({
220
- name: 'Generative Producer Config',
221
- pass: false,
222
- message: broken.map((fn) => `${fn}: ${aiConfig[fn].error}`).join(' | '),
223
- });
272
+ checks.push({ name: 'Schema Alignment', pass: false, message: 'Database inaccessible, skipping schema alignment check' });
273
+ checks.push({ name: 'Store Meta Consistency', pass: false, message: 'Database inaccessible, skipping store_meta check' });
224
274
  }
225
275
  }
276
+ // Generative config resolves from this process's environment (loadBrainEnv).
277
+ try {
278
+ checks.push(describeGenerativeConfig((0, config_1.describeAiConfig)()));
279
+ }
226
280
  catch (err) {
227
281
  checks.push({
228
282
  name: 'Generative Producer Config',
229
283
  pass: false,
230
- message: `Failed to resolve generative config: ${err instanceof Error ? err.message : String(err)}`,
284
+ message: `Failed to resolve generative config: ${errorMessage(err)}`,
231
285
  });
232
286
  }
233
- // 4. AI Conformance Diagnostics (runs conformance fixtures)
234
- let aiDiagnostics;
235
- const shouldRunAi = options?.ai !== false;
236
- if (shouldRunAi) {
287
+ // The fixtures seed and delete rows, so they never touch the real file:
288
+ // they run against a throwaway temp database.
289
+ let aiDiagnostics = SKIPPED_AI;
290
+ if (runAi) {
237
291
  try {
238
- aiDiagnostics = (0, fixtures_1.runAiConformanceDiagnostics)();
239
- checks.push({
240
- name: 'AI Conformance Diagnostics',
241
- pass: aiDiagnostics.all_passing,
242
- message: `${aiDiagnostics.passed_count}/${aiDiagnostics.total_count} assertions passed`,
243
- });
292
+ aiDiagnostics = (0, db_1.withIsolatedDb)(() => (0, fixtures_1.runAiConformanceDiagnostics)());
293
+ checks.push(aiCheck(aiDiagnostics));
244
294
  }
245
295
  catch (err) {
246
- aiDiagnostics = {
247
- status: 'failed',
248
- all_passing: false,
249
- passed_count: 0,
250
- total_count: 0,
251
- results: [],
252
- };
253
- checks.push({
254
- name: 'AI Conformance Diagnostics',
255
- pass: false,
256
- message: `Failed to run diagnostics: ${err instanceof Error ? err.message : String(err)}`,
257
- });
296
+ aiDiagnostics = FAILED_AI;
297
+ checks.push({ name: 'AI Conformance Diagnostics', pass: false, message: `Failed to run diagnostics: ${errorMessage(err)}` });
258
298
  }
259
299
  }
260
300
  else {
261
- aiDiagnostics = {
262
- status: 'ok',
263
- all_passing: true,
264
- passed_count: 0,
265
- total_count: 0,
266
- results: [],
301
+ checks.push({ name: 'AI Conformance Diagnostics', pass: true, message: 'Skipped (--no-ai)' });
302
+ }
303
+ return { dbOk, schemaAligned, storeMetaMatch, counts, aiDiagnostics, checks };
304
+ }
305
+ function openReadOnly(dbPath) {
306
+ if (dbPath === ':memory:' || dbPath.startsWith('file::memory:')) {
307
+ return { db: null, error: 'DATABASE_URL is :memory:; there is no database file to inspect' };
308
+ }
309
+ const resolved = path_1.default.resolve(dbPath);
310
+ if (!fs_1.default.existsSync(resolved)) {
311
+ return {
312
+ db: null,
313
+ error: `No database at ${resolved}. Start the service once (neuralbrain start) to create it.`,
267
314
  };
268
- checks.push({
269
- name: 'AI Conformance Diagnostics',
270
- pass: true,
271
- message: 'Skipped (--no-ai)',
272
- });
273
315
  }
274
- // Compute single definitive boolean to prevent contradiction
275
- const totalChecks = checks.length;
276
- const passedChecks = checks.filter((c) => c.pass).length;
277
- const allPassing = passedChecks === totalChecks && dbOk && schemaAligned && storeMetaMatch && aiDiagnostics.all_passing;
278
- // Print Structured Report
279
- console.log('\n╔══════════════════════════════════════════════════════════════╗');
280
- console.log('║ NEURALBRAIN DOCTOR ║');
281
- console.log('╚══════════════════════════════════════════════════════════════╝\n');
282
- for (const check of checks) {
283
- const symbol = check.pass ? '✓ PASS' : '✗ FAIL';
284
- console.log(` [${symbol}] ${check.name.padEnd(28)} : ${check.message}`);
316
+ try {
317
+ return { db: (0, sqlite_1.openDatabase)(resolved, { readOnly: true }), error: null };
285
318
  }
286
- console.log('\n Operational Metrics:');
287
- console.log(` - Dead Letters Recorded : ${deadLetterCount}`);
288
- console.log(` - Unknown-Scope Notes : ${unknownScopeCount}`);
289
- console.log(` - Total Notes : ${noteCount}`);
290
- console.log(` - Trajectories Stored : ${trajectoryCount}`);
291
- console.log(` - Observations Stored : ${observationCount}`);
292
- if (aiDiagnostics.results && aiDiagnostics.results.length > 0) {
293
- console.log('\n AI Diagnostics Breakdown:');
294
- for (const r of aiDiagnostics.results) {
295
- const sym = r.pass ? '✓' : '✗';
296
- console.log(` ${sym} ${r.name}`);
297
- }
319
+ catch (err) {
320
+ return { db: null, error: `Could not open ${resolved} read-only: ${errorMessage(err)}` };
298
321
  }
299
- console.log('\n══════════════════════════════════════════════════════════════');
300
- if (allPassing) {
301
- console.log(' Final Verdict: PASS (All checks passing)');
322
+ }
323
+ function isTestRun() {
324
+ return process.env.NODE_ENV === 'test' || Boolean(process.env.JEST_WORKER_ID);
325
+ }
326
+ async function runDoctor(options = {}) {
327
+ const mode = options.mode ?? 'auto';
328
+ // Mirrors db.ts refusing real database paths under test: a test must name the
329
+ // service it talks to, or it would probe (and authenticate against) a real
330
+ // brain on the default port.
331
+ if (isTestRun() && mode !== 'local' && !options.apiUrl && !options.fetchFn) {
332
+ throw new Error("runDoctor() under test must pass mode: 'local' or an explicit apiUrl/fetchFn; refusing to probe a real service.");
333
+ }
334
+ const runAi = options.ai !== false;
335
+ const fetchFn = options.fetchFn ?? (0, tls_1.createLocalTlsFetch)();
336
+ const apiUrl = (options.apiUrl ?? (0, installAgent_1.resolveApiUrl)({}, packageRoot(), process.cwd())).replace(/\/+$/, '');
337
+ let source = 'local';
338
+ let target = '';
339
+ let findings;
340
+ const health = mode === 'local' ? null : await probeHealth(fetchFn, apiUrl);
341
+ if (health) {
342
+ source = 'service';
343
+ target = apiUrl;
344
+ const apiKey = options.apiKey ?? (0, installAgent_1.resolveApiKey)({}, packageRoot(), process.cwd());
345
+ findings = await runServiceChecks(fetchFn, apiUrl, apiKey, health, runAi);
346
+ }
347
+ else if (mode === 'service') {
348
+ source = 'service';
349
+ target = apiUrl;
350
+ findings = {
351
+ dbOk: false,
352
+ schemaAligned: false,
353
+ storeMetaMatch: false,
354
+ counts: ZERO_COUNTS,
355
+ aiDiagnostics: runAi ? FAILED_AI : SKIPPED_AI,
356
+ checks: [{ name: 'Service Reachable', pass: false, message: `No response from ${apiUrl}/health` }],
357
+ };
358
+ }
359
+ else if (options.db) {
360
+ target = 'provided connection';
361
+ findings = runLocalChecks(options.db, target, null, runAi);
302
362
  }
303
363
  else {
304
- console.log(` Final Verdict: FAIL (${passedChecks}/${totalChecks} checks passing)`);
364
+ const dbPath = options.dbPath ?? (0, db_1.getDbPath)();
365
+ target = path_1.default.resolve(dbPath);
366
+ const { db, error } = openReadOnly(dbPath);
367
+ try {
368
+ findings = runLocalChecks(db, target, error, runAi);
369
+ }
370
+ finally {
371
+ db?.close();
372
+ }
373
+ }
374
+ const { checks, aiDiagnostics, counts } = findings;
375
+ const totalChecks = checks.length;
376
+ const passedChecks = checks.filter((c) => c.pass).length;
377
+ // One verdict, computed once, so the report can never say "N/M passing" and
378
+ // "all checks passing" at the same time.
379
+ const allPassing = passedChecks === totalChecks &&
380
+ findings.dbOk &&
381
+ findings.schemaAligned &&
382
+ findings.storeMetaMatch &&
383
+ aiDiagnostics.all_passing;
384
+ if (!options.quiet) {
385
+ console.log('\n╔══════════════════════════════════════════════════════════════╗');
386
+ console.log('║ NEURALBRAIN DOCTOR ║');
387
+ console.log('╚══════════════════════════════════════════════════════════════╝\n');
388
+ console.log(source === 'service'
389
+ ? ` Source: running service at ${target}\n`
390
+ : ` Source: service not reachable at ${apiUrl}; inspected ${target} read-only\n`);
391
+ for (const check of checks) {
392
+ const symbol = check.pass ? '✓ PASS' : '✗ FAIL';
393
+ console.log(` [${symbol}] ${check.name.padEnd(28)} : ${check.message}`);
394
+ }
395
+ console.log('\n Operational Metrics:');
396
+ console.log(` - Dead Letters Recorded : ${counts.dead_letters}`);
397
+ console.log(` - Unknown-Scope Notes : ${counts.unknown_scope_notes}`);
398
+ console.log(` - Total Notes : ${counts.notes}`);
399
+ console.log(` - Trajectories Stored : ${counts.trajectories}`);
400
+ console.log(` - Observations Stored : ${counts.observations}`);
401
+ if (aiDiagnostics.results && aiDiagnostics.results.length > 0) {
402
+ console.log('\n AI Diagnostics Breakdown:');
403
+ for (const r of aiDiagnostics.results) {
404
+ console.log(` ${r.pass ? '✓' : '✗'} ${r.name}`);
405
+ }
406
+ }
407
+ console.log('\n══════════════════════════════════════════════════════════════');
408
+ console.log(allPassing
409
+ ? ' Final Verdict: PASS (All checks passing)'
410
+ : ` Final Verdict: FAIL (${passedChecks}/${totalChecks} checks passing)`);
411
+ console.log('══════════════════════════════════════════════════════════════\n');
305
412
  }
306
- console.log('══════════════════════════════════════════════════════════════\n');
307
413
  if (options.exitOnFinish) {
308
414
  process.exit(allPassing ? 0 : 1);
309
415
  }
310
416
  return {
311
417
  allPassing,
312
- dbOk,
313
- schemaAligned,
314
- storeMetaMatch,
315
- deadLetterCount,
316
- unknownScopeCount,
317
- noteCount,
318
- trajectoryCount,
319
- observationCount,
418
+ source,
419
+ target,
420
+ dbOk: findings.dbOk,
421
+ schemaAligned: findings.schemaAligned,
422
+ storeMetaMatch: findings.storeMetaMatch,
423
+ deadLetterCount: counts.dead_letters,
424
+ unknownScopeCount: counts.unknown_scope_notes,
425
+ noteCount: counts.notes,
426
+ trajectoryCount: counts.trajectories,
427
+ observationCount: counts.observations,
320
428
  aiDiagnostics,
321
429
  checks,
322
430
  };
323
431
  }
324
432
  if (require.main === module) {
433
+ // `npm run doctor` runs this file directly; `neuralbrain doctor` has already
434
+ // loaded the env, and loadBrainEnv never clobbers what is set.
435
+ (0, brainHome_1.loadBrainEnv)();
325
436
  const isNoAi = process.argv.includes('--no-ai');
326
437
  const isAi = (process.argv.includes('--ai') || process.argv.includes('--consolidator')) && !isNoAi;
327
- runDoctor({ ai: isNoAi ? false : isAi, exitOnFinish: true }).catch((err) => {
438
+ const mode = process.argv.includes('--local') ? 'local' : process.argv.includes('--service') ? 'service' : 'auto';
439
+ runDoctor({ ai: isNoAi ? false : isAi, exitOnFinish: true, mode }).catch((err) => {
328
440
  console.error('Doctor execution crashed:', err);
329
441
  process.exit(1);
330
442
  });