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.
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 +3 -2
  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
package/src/cli.ts CHANGED
@@ -16,8 +16,9 @@ import {
16
16
  getDefaultSpoolDir,
17
17
  loadBrainEnv,
18
18
  } from './lib/brainHome';
19
- import { ensureLocalTlsCerts, getDefaultCertsDir } from './lib/tls';
19
+ import { createLocalTlsFetch, ensureLocalTlsCerts, getDefaultCertsDir } from './lib/tls';
20
20
  import { resolveCanonicalProjectId, writeBrainRc } from './lib/projectSlug';
21
+ import { parseDurationMs } from './lib/recurrence';
21
22
  import { normalizeProjectId } from './lib/scope';
22
23
  import {
23
24
  installAgentIntegration,
@@ -210,6 +211,9 @@ export function parseInstallArgs(argv: string[]): InstallCliOptions {
210
211
  opts.yes = true;
211
212
  } else if (arg === '--mode') {
212
213
  const val = argv[++i];
214
+ if (!val || val.startsWith('--')) {
215
+ throw new Error('Missing value for --mode. Expected: docker | qdrant-docker | local-only');
216
+ }
213
217
  if (val === 'docker' || val === 'qdrant-docker' || val === 'local-only') {
214
218
  opts.mode = val;
215
219
  } else {
@@ -224,7 +228,11 @@ export function parseInstallArgs(argv: string[]): InstallCliOptions {
224
228
  } else if (arg === '--agents') {
225
229
  opts.agents = true;
226
230
  } else if (arg === '--port') {
227
- const p = parseInt(argv[++i], 10);
231
+ const rawPort = argv[++i];
232
+ if (!rawPort || rawPort.startsWith('--')) {
233
+ throw new Error('Missing value for --port');
234
+ }
235
+ const p = parseInt(rawPort, 10);
228
236
  if (Number.isNaN(p) || p <= 0) {
229
237
  throw new Error(`Invalid --port value`);
230
238
  }
@@ -286,7 +294,12 @@ function startHostDaemon(packageRoot: string, envPath: string): number {
286
294
  }
287
295
 
288
296
  const logPath = getLogFilePath();
289
- const out = fs.openSync(logPath, 'a');
297
+ const out = fs.openSync(logPath, 'a', 0o600);
298
+ try {
299
+ fs.chmodSync(logPath, 0o600);
300
+ } catch {
301
+ // ignore chmod errors on unsupported platforms
302
+ }
290
303
  const entryJs = path.join(packageRoot, 'dist', 'index.js');
291
304
 
292
305
  const parsedEnv = dotenv.parse(fs.readFileSync(envPath, 'utf8'));
@@ -295,15 +308,15 @@ function startHostDaemon(packageRoot: string, envPath: string): number {
295
308
  detached: true,
296
309
  stdio: ['ignore', out, out],
297
310
  env: {
298
- ...process.env,
299
311
  ...parsedEnv,
300
- NODE_ENV: process.env.NODE_ENV || 'production',
312
+ ...process.env,
313
+ NODE_ENV: process.env.NODE_ENV || parsedEnv.NODE_ENV || 'production',
301
314
  },
302
315
  });
303
316
 
304
317
  child.unref();
305
318
  if (child.pid) {
306
- fs.writeFileSync(pidFile, `${child.pid}\n`, 'utf8');
319
+ fs.writeFileSync(pidFile, `${child.pid}\n`, { encoding: 'utf8', mode: 0o600 });
307
320
  }
308
321
  return child.pid ?? 0;
309
322
  }
@@ -313,17 +326,21 @@ function stopHostDaemon(): boolean {
313
326
  if (!fs.existsSync(pidFile)) return false;
314
327
 
315
328
  const pid = parseInt(fs.readFileSync(pidFile, 'utf8').trim(), 10);
316
- fs.rmSync(pidFile, { force: true });
329
+ if (Number.isNaN(pid) || pid <= 0) {
330
+ fs.rmSync(pidFile, { force: true });
331
+ return false;
332
+ }
317
333
 
318
- if (!Number.isNaN(pid) && isPidAlive(pid)) {
319
- try {
320
- process.kill(pid, 'SIGTERM');
321
- return true;
322
- } catch {
323
- return false;
334
+ try {
335
+ process.kill(pid, 'SIGTERM');
336
+ fs.rmSync(pidFile, { force: true });
337
+ return true;
338
+ } catch (err: any) {
339
+ if (err?.code === 'ESRCH') {
340
+ fs.rmSync(pidFile, { force: true });
324
341
  }
342
+ return false;
325
343
  }
326
- return false;
327
344
  }
328
345
 
329
346
  function isHttpsEnabled(): boolean {
@@ -612,6 +629,37 @@ function readPackageVersion(packageRoot: string): string | null {
612
629
  }
613
630
  }
614
631
 
632
+ /**
633
+ * Finds the globally installed copy on disk.
634
+ *
635
+ * `npm root -g` alone is not trusted: npm masks anything that looks like a
636
+ * UUID in its output (legacy npm tokens were UUIDs), so a global folder whose
637
+ * path contains one is printed with `***` and points nowhere. Candidates, first
638
+ * existing one wins: npm's answer (unless masked), the configured global
639
+ * prefix, then the folder next to the running node binary (nvm and standard
640
+ * installs).
641
+ */
642
+ export function locateInstalledCopy(
643
+ reportedRoot: string,
644
+ exists: (p: string) => boolean = fs.existsSync
645
+ ): string | null {
646
+ const roots: string[] = [];
647
+ if (reportedRoot && !reportedRoot.includes('***')) roots.push(reportedRoot);
648
+ const prefix = process.env.npm_config_prefix || process.env.NPM_CONFIG_PREFIX;
649
+ if (prefix) {
650
+ roots.push(process.platform === 'win32' ? path.join(prefix, 'node_modules') : path.join(prefix, 'lib', 'node_modules'));
651
+ }
652
+ const binDir = path.dirname(process.execPath);
653
+ roots.push(
654
+ process.platform === 'win32' ? path.join(binDir, 'node_modules') : path.join(path.dirname(binDir), 'lib', 'node_modules')
655
+ );
656
+ for (const root of roots) {
657
+ const candidate = path.join(root, 'neuralbrain');
658
+ if (exists(path.join(candidate, 'package.json'))) return candidate;
659
+ }
660
+ return null;
661
+ }
662
+
615
663
  export function installGlobalPackage(
616
664
  packageRoot: string,
617
665
  run: SpawnFn = spawnSync as unknown as SpawnFn
@@ -621,11 +669,19 @@ export function installGlobalPackage(
621
669
  }
622
670
 
623
671
  const rootRes = run('npm', ['root', '-g'], { encoding: 'utf8', stdio: 'pipe' });
624
- const globalRoot = rootRes.status === 0 ? String(rootRes.stdout || '').trim() : '';
625
- if (!globalRoot) {
626
- return { ok: false, installedRoot: null, alreadyInstalled: false, error: '`npm root -g` failed' };
627
- }
628
- const installedRoot = path.join(globalRoot, 'neuralbrain');
672
+ const reportedRoot = rootRes.status === 0 ? String(rootRes.stdout || '').trim() : '';
673
+ // The real location is confirmed on disk after installing (see locateInstalledCopy).
674
+ const located = (): GlobalInstallResult => {
675
+ const root = locateInstalledCopy(reportedRoot);
676
+ return root
677
+ ? { ok: true, installedRoot: root, alreadyInstalled: false }
678
+ : {
679
+ ok: false,
680
+ installedRoot: null,
681
+ alreadyInstalled: false,
682
+ error: 'installed, but could not find the global copy (check `npm root -g`)',
683
+ };
684
+ };
629
685
  // onnxruntime-node's script only fetches the CUDA add-on, which the host never
630
686
  // uses; with CUDA present it can 404 and fail the whole install. Skip it in
631
687
  // case npm runs the script anyway (npm 10 and older run every script).
@@ -643,7 +699,7 @@ export function installGlobalPackage(
643
699
  if (installRes.status !== 0) {
644
700
  return { ok: false, installedRoot: null, alreadyInstalled: false, error: '`npm install -g` failed' };
645
701
  }
646
- return { ok: true, installedRoot, alreadyInstalled: false };
702
+ return located();
647
703
  }
648
704
 
649
705
  const packDir = fs.mkdtempSync(path.join(os.tmpdir(), 'neuralbrain-pack-'));
@@ -677,7 +733,7 @@ export function installGlobalPackage(
677
733
  if (installRes.status !== 0) {
678
734
  return { ok: false, installedRoot: null, alreadyInstalled: false, error: '`npm install -g` failed' };
679
735
  }
680
- return { ok: true, installedRoot, alreadyInstalled: false };
736
+ return located();
681
737
  } finally {
682
738
  fs.rmSync(packDir, { recursive: true, force: true });
683
739
  }
@@ -787,7 +843,9 @@ async function cmdStart(): Promise<void> {
787
843
  const protocol = useHttps ? 'https' : 'http';
788
844
  console.log(`Starting neuralbrain (mode: ${mode})...`);
789
845
  startForMode(mode, envPath, packageRoot);
790
- const healthy = await waitForHealth(port, 30000, useHttps);
846
+ // Docker mode builds the image first (`up --build`), so give it the same
847
+ // headroom install does.
848
+ const healthy = await waitForHealth(port, mode === 'docker' ? 90000 : 30000, useHttps);
791
849
  console.log(healthy ? `Ready at ${protocol}://127.0.0.1:${port}` : 'Started, waiting for health check...');
792
850
  }
793
851
 
@@ -819,6 +877,51 @@ function cmdStop(): void {
819
877
  }
820
878
  }
821
879
 
880
+ /**
881
+ * Polls `isUp` until it reports false (the old service has let go of its port)
882
+ * or `timeoutMs` passes. Returns true once the service is down.
883
+ *
884
+ * `stop` returns as soon as SIGTERM is sent to a host daemon, which then takes
885
+ * a moment to drain and exit. Starting before it has gone would either fail on
886
+ * the port or, worse, let the new start's health wait be answered by the old
887
+ * process.
888
+ */
889
+ export async function waitForShutdown(
890
+ isUp: () => Promise<boolean>,
891
+ timeoutMs = 15000,
892
+ intervalMs = 250
893
+ ): Promise<boolean> {
894
+ const deadline = Date.now() + timeoutMs;
895
+ while (true) {
896
+ if (!(await isUp())) return true;
897
+ if (Date.now() >= deadline) return false;
898
+ await new Promise((r) => setTimeout(r, intervalMs));
899
+ }
900
+ }
901
+
902
+ async function cmdRestart(): Promise<void> {
903
+ loadBrainEnv();
904
+ const envPath = getBrainEnvPath();
905
+ if (!fs.existsSync(envPath)) {
906
+ throw new Error(`Not initialized. Run \`neuralbrain install\` first (missing ${envPath}).`);
907
+ }
908
+ const port = parseInt(process.env.PORT || '3737', 10);
909
+ const useHttps = isHttpsEnabled();
910
+
911
+ console.log('Stopping neuralbrain...');
912
+ cmdStop();
913
+
914
+ const down = await waitForShutdown(async () => (await checkHealth(port, useHttps)) !== null);
915
+ if (!down) {
916
+ throw new Error(
917
+ `Something is still answering on port ${port} after stopping. ` +
918
+ 'Not starting a second copy; check `neuralbrain status`.'
919
+ );
920
+ }
921
+
922
+ await cmdStart();
923
+ }
924
+
822
925
  async function cmdStatus(): Promise<void> {
823
926
  loadBrainEnv();
824
927
  const brainHome = getBrainHomeDir();
@@ -876,25 +979,33 @@ export interface InitResult {
876
979
  }
877
980
 
878
981
  /**
879
- * `neuralbrain init [project-id] [--force]`: writes .brainrc in `cwd` so every
880
- * agent working anywhere below it records the same project_id.
982
+ * `neuralbrain init [project-id] [--force] [--auto-subproject] [--max-depth <n>]`:
983
+ * writes .brainrc in `cwd` so every agent working anywhere below it records the same project_id.
881
984
  *
882
985
  * Defaults to the folder's own name. An existing .brainrc is kept unless
883
986
  * `force` is set. An explicit id that is not a valid project_id is an error,
884
987
  * never silently replaced.
885
988
  */
886
- export function runInit(options: { cwd: string; projectId?: string; force?: boolean }): InitResult {
989
+ export function runInit(options: {
990
+ cwd: string;
991
+ projectId?: string;
992
+ force?: boolean;
993
+ autoSubproject?: boolean;
994
+ maxDepth?: number;
995
+ }): InitResult {
887
996
  const cwd = path.resolve(options.cwd);
888
997
  const filePath = path.join(cwd, '.brainrc');
889
998
 
999
+ if (
1000
+ options.maxDepth !== undefined &&
1001
+ (!Number.isInteger(options.maxDepth) || options.maxDepth <= 0)
1002
+ ) {
1003
+ throw new Error('--max-depth must be a positive integer');
1004
+ }
1005
+
890
1006
  let explicit: string | undefined;
891
1007
  if (options.projectId !== undefined) {
892
- const sanitized = options.projectId
893
- .trim()
894
- .toLowerCase()
895
- .replace(/[^a-z0-9._-]+/g, '-')
896
- .replace(/^-+|-+$/g, '');
897
- const norm = normalizeProjectId(sanitized);
1008
+ const norm = normalizeProjectId(options.projectId);
898
1009
  if (!norm.ok) {
899
1010
  throw new Error(`'${options.projectId}' is not a valid project id: ${norm.error}`);
900
1011
  }
@@ -912,21 +1023,59 @@ export function runInit(options: { cwd: string; projectId?: string; force?: bool
912
1023
  return { filePath, projectId: existing ?? '', written: false, enclosingProjectId: null };
913
1024
  }
914
1025
 
915
- const written = writeBrainRc(cwd, explicit);
1026
+ const written = writeBrainRc(cwd, explicit, {
1027
+ autoSubproject: options.autoSubproject,
1028
+ maxDepth: options.maxDepth,
1029
+ });
916
1030
  const enclosingProjectId = gitOrParent && gitOrParent !== written.projectId ? gitOrParent : null;
917
1031
  return { filePath: written.filePath, projectId: written.projectId, written: true, enclosingProjectId };
918
1032
  }
919
1033
 
920
1034
  function cmdInit(argv: string[]): void {
921
- const force = argv.includes('--force') || argv.includes('-f');
922
- const positional = argv.filter((a) => !a.startsWith('-'));
1035
+ let force = false;
1036
+ let autoSubproject = false;
1037
+ let maxDepth: number | undefined;
1038
+ const positional: string[] = [];
1039
+
1040
+ for (let i = 0; i < argv.length; i++) {
1041
+ const arg = argv[i];
1042
+ if (arg === '--force' || arg === '-f') {
1043
+ force = true;
1044
+ } else if (arg === '--auto-subproject') {
1045
+ autoSubproject = true;
1046
+ } else if (arg === '--max-depth' || arg.startsWith('--max-depth=')) {
1047
+ const raw = arg.startsWith('--max-depth=') ? arg.slice('--max-depth='.length) : argv[++i];
1048
+ if (!raw || raw.startsWith('-')) {
1049
+ console.error('Missing value for --max-depth');
1050
+ process.exit(1);
1051
+ }
1052
+ const parsed = Number(raw);
1053
+ if (!Number.isInteger(parsed) || parsed <= 0) {
1054
+ console.error(`Invalid --max-depth '${raw}': must be a positive integer`);
1055
+ process.exit(1);
1056
+ }
1057
+ maxDepth = parsed;
1058
+ } else if (arg.startsWith('-')) {
1059
+ console.error(`Unknown option for init: ${arg}`);
1060
+ process.exit(1);
1061
+ } else {
1062
+ positional.push(arg);
1063
+ }
1064
+ }
1065
+
923
1066
  if (positional.length > 1) {
924
- console.error('Usage: neuralbrain init [project-id] [--force]');
1067
+ console.error('Usage: neuralbrain init [project-id] [--force] [--auto-subproject] [--max-depth <n>]');
925
1068
  process.exit(1);
926
1069
  }
927
1070
  let result: InitResult;
928
1071
  try {
929
- result = runInit({ cwd: process.cwd(), projectId: positional[0], force });
1072
+ result = runInit({
1073
+ cwd: process.cwd(),
1074
+ projectId: positional[0],
1075
+ force,
1076
+ autoSubproject,
1077
+ maxDepth,
1078
+ });
930
1079
  } catch (err) {
931
1080
  console.error(err instanceof Error ? err.message : String(err));
932
1081
  process.exit(1);
@@ -938,6 +1087,11 @@ function cmdInit(argv: string[]): void {
938
1087
  }
939
1088
  console.log(`Wrote ${result.filePath}`);
940
1089
  console.log(`project_id: ${result.projectId}`);
1090
+ if (autoSubproject) {
1091
+ console.log(
1092
+ `auto_subproject: true${maxDepth !== undefined ? ` (max_depth: ${maxDepth})` : ''}`
1093
+ );
1094
+ }
941
1095
  if (result.enclosingProjectId) {
942
1096
  console.log(
943
1097
  `Note: this folder was part of project "${result.enclosingProjectId}". ` +
@@ -947,6 +1101,292 @@ function cmdInit(argv: string[]): void {
947
1101
  }
948
1102
  }
949
1103
 
1104
+ export interface RemindersCheckOptions {
1105
+ json?: boolean;
1106
+ webhookUrl?: string;
1107
+ webhook?: string;
1108
+ projectId?: string;
1109
+ project?: string;
1110
+ includeAncestors?: boolean;
1111
+ includeChildren?: boolean;
1112
+ includeGlobal?: boolean;
1113
+ cooldownMs?: number;
1114
+ cooldown?: string;
1115
+ dryRun?: boolean;
1116
+ limit?: number;
1117
+ apiUrl?: string;
1118
+ apiKey?: string;
1119
+ fetchFn?: typeof fetch;
1120
+ }
1121
+
1122
+ export interface RemindersCheckResult {
1123
+ checked_at: string;
1124
+ reminders: any[];
1125
+ marked_count: number;
1126
+ acked_count?: number;
1127
+ webhook_delivered?: boolean;
1128
+ webhook_status?: number;
1129
+ output: string;
1130
+ }
1131
+
1132
+ function validateWebhookUrl(raw: string): string {
1133
+ const val = raw.trim();
1134
+ if (!/^https?:\/\//i.test(val)) {
1135
+ throw new Error(`Invalid --webhook URL '${val}': must start with http:// or https://`);
1136
+ }
1137
+ try {
1138
+ new URL(val);
1139
+ } catch {
1140
+ throw new Error(`Invalid --webhook URL '${val}'`);
1141
+ }
1142
+ return val;
1143
+ }
1144
+
1145
+ export function parseRemindersArgs(argv: string[]): RemindersCheckOptions {
1146
+ const opts: RemindersCheckOptions = {
1147
+ json: false,
1148
+ includeAncestors: true,
1149
+ includeChildren: false,
1150
+ includeGlobal: true,
1151
+ dryRun: false,
1152
+ };
1153
+
1154
+ for (let i = 0; i < argv.length; i++) {
1155
+ const arg = argv[i];
1156
+ const eqIdx = arg.indexOf('=');
1157
+ const flag = eqIdx !== -1 ? arg.slice(0, eqIdx) : arg;
1158
+ const inlineVal = eqIdx !== -1 ? arg.slice(eqIdx + 1) : undefined;
1159
+
1160
+ const takeValue = (name: string): string => {
1161
+ if (inlineVal !== undefined) {
1162
+ if (!inlineVal) throw new Error(`Missing value for ${name}`);
1163
+ return inlineVal;
1164
+ }
1165
+ const next = argv[++i];
1166
+ if (!next || next.startsWith('--')) {
1167
+ throw new Error(`Missing value for ${name}`);
1168
+ }
1169
+ return next;
1170
+ };
1171
+
1172
+ if (flag === '--json') {
1173
+ opts.json = true;
1174
+ } else if (flag === '--include-children') {
1175
+ opts.includeChildren = true;
1176
+ } else if (flag === '--no-ancestors') {
1177
+ opts.includeAncestors = false;
1178
+ } else if (flag === '--no-global') {
1179
+ opts.includeGlobal = false;
1180
+ } else if (flag === '--dry-run') {
1181
+ opts.dryRun = true;
1182
+ } else if (flag === '--webhook') {
1183
+ opts.webhookUrl = validateWebhookUrl(takeValue('--webhook'));
1184
+ } else if (flag === '--project') {
1185
+ const val = takeValue('--project').trim();
1186
+ const norm = normalizeProjectId(val);
1187
+ if (!norm.ok) {
1188
+ throw new Error(`Invalid --project '${val}': ${norm.error}`);
1189
+ }
1190
+ opts.projectId = norm.projectId;
1191
+ } else if (flag === '--cooldown') {
1192
+ const val = takeValue('--cooldown').trim();
1193
+ const ms = parseDurationMs(val);
1194
+ if (ms === null) {
1195
+ throw new Error(`Invalid --cooldown duration '${val}' (examples: 30m, 2h, 1d, PT15M)`);
1196
+ }
1197
+ opts.cooldownMs = ms;
1198
+ opts.cooldown = val;
1199
+ } else if (flag === '--limit') {
1200
+ const val = takeValue('--limit').trim();
1201
+ const parsed = Number(val);
1202
+ if (!Number.isInteger(parsed) || parsed <= 0) {
1203
+ throw new Error(`Invalid --limit '${val}': must be a positive integer`);
1204
+ }
1205
+ opts.limit = parsed;
1206
+ } else {
1207
+ throw new Error(`Unknown option: ${arg}`);
1208
+ }
1209
+ }
1210
+
1211
+ return opts;
1212
+ }
1213
+
1214
+ function formatRemindersHuman(result: Omit<RemindersCheckResult, 'output'>): string {
1215
+ if (result.reminders.length === 0) {
1216
+ return `No due reminders (checked at ${result.checked_at}).`;
1217
+ }
1218
+ const lines = [`Due reminders (${result.reminders.length}, checked at ${result.checked_at}):`];
1219
+ for (const r of result.reminders) {
1220
+ const overdueTag = r.overdue ? '[OVERDUE] ' : '';
1221
+ const prio = r.priority ? `[${String(r.priority).toUpperCase()}] ` : '';
1222
+ const when = r.due_at ? `due ${r.due_at}` : r.remind_at ? `remind ${r.remind_at}` : '';
1223
+ const loc = r.project_id ? `${r.scope}:${r.project_id}` : r.scope;
1224
+ const tier = r.match_tier ? ` [${r.match_tier}]` : '';
1225
+ lines.push(`- ${overdueTag}${prio}${r.title} (${r.id}, ${loc}${tier}${when ? `, ${when}` : ''})`);
1226
+ }
1227
+ const statusBits = [`marked=${result.marked_count}`];
1228
+ if (result.webhook_delivered !== undefined) {
1229
+ statusBits.push(`webhook_delivered=${result.webhook_delivered}`);
1230
+ }
1231
+ if (result.acked_count !== undefined) {
1232
+ statusBits.push(`acked=${result.acked_count}`);
1233
+ }
1234
+ lines.push(`Summary: ${statusBits.join(', ')}`);
1235
+ return lines.join('\n');
1236
+ }
1237
+
1238
+ export async function runRemindersCheck(
1239
+ options: RemindersCheckOptions = {}
1240
+ ): Promise<RemindersCheckResult> {
1241
+ const rawWebhook = options.webhookUrl !== undefined ? options.webhookUrl : options.webhook;
1242
+ const webhookUrl = rawWebhook !== undefined && rawWebhook !== null ? validateWebhookUrl(rawWebhook) : undefined;
1243
+
1244
+ let projectId: string | undefined;
1245
+ const rawProject = options.projectId !== undefined ? options.projectId : options.project;
1246
+ if (rawProject !== undefined && rawProject !== null && rawProject.trim() !== '') {
1247
+ const norm = normalizeProjectId(rawProject.trim());
1248
+ if (!norm.ok) {
1249
+ throw new Error(`Invalid project_id '${rawProject}': ${norm.error}`);
1250
+ }
1251
+ projectId = norm.projectId;
1252
+ }
1253
+
1254
+ let cooldownMs: number | undefined = options.cooldownMs;
1255
+ if (cooldownMs !== undefined) {
1256
+ if (typeof cooldownMs !== 'number' || !Number.isFinite(cooldownMs) || cooldownMs < 0) {
1257
+ throw new Error('cooldownMs must be a non-negative finite number');
1258
+ }
1259
+ } else if (options.cooldown !== undefined) {
1260
+ const parsed = parseDurationMs(options.cooldown);
1261
+ if (parsed === null) {
1262
+ throw new Error(`Invalid --cooldown duration '${options.cooldown}'`);
1263
+ }
1264
+ cooldownMs = parsed;
1265
+ }
1266
+
1267
+ if (options.limit !== undefined && (!Number.isInteger(options.limit) || options.limit <= 0)) {
1268
+ throw new Error('limit must be a positive integer');
1269
+ }
1270
+
1271
+ const packageRoot = getPackageRoot();
1272
+ const apiUrl = (
1273
+ options.apiUrl || resolveApiUrl({}, packageRoot, process.cwd(), os.homedir())
1274
+ ).replace(/\/+$/, '');
1275
+ const apiKey =
1276
+ options.apiKey !== undefined
1277
+ ? options.apiKey
1278
+ : resolveApiKey({}, packageRoot, process.cwd(), os.homedir());
1279
+ const fetchFn = options.fetchFn || createLocalTlsFetch();
1280
+
1281
+ const headers: Record<string, string> = { 'Content-Type': 'application/json' };
1282
+ if (apiKey) {
1283
+ headers.Authorization = `Bearer ${apiKey}`;
1284
+ }
1285
+
1286
+ const dryRun = Boolean(options.dryRun);
1287
+ const checkPayload: Record<string, unknown> = {
1288
+ include_ancestors: options.includeAncestors ?? true,
1289
+ include_children: options.includeChildren ?? false,
1290
+ include_global: options.includeGlobal ?? true,
1291
+ dry_run: webhookUrl ? true : dryRun,
1292
+ };
1293
+ if (projectId) checkPayload.project_id = projectId;
1294
+ if (cooldownMs !== undefined) checkPayload.cooldown_ms = cooldownMs;
1295
+ if (options.limit !== undefined) checkPayload.limit = options.limit;
1296
+
1297
+ const checkRes = await fetchFn(`${apiUrl}/actions/reminders/check`, {
1298
+ method: 'POST',
1299
+ headers,
1300
+ body: JSON.stringify(checkPayload),
1301
+ });
1302
+
1303
+ const checkData = (await checkRes.json().catch(() => ({}))) as any;
1304
+ if (!checkRes.ok) {
1305
+ throw new Error(
1306
+ `Reminders check failed (${checkRes.status}): ${checkData?.error?.message || JSON.stringify(checkData)}`
1307
+ );
1308
+ }
1309
+
1310
+ const checkedAt = typeof checkData.checked_at === 'string' ? checkData.checked_at : new Date().toISOString();
1311
+ const reminders = Array.isArray(checkData.reminders) ? checkData.reminders : [];
1312
+ let markedCount = typeof checkData.marked_count === 'number' ? checkData.marked_count : 0;
1313
+ let ackedCount: number | undefined;
1314
+ let webhookDelivered: boolean | undefined;
1315
+ let webhookStatus: number | undefined;
1316
+
1317
+ if (webhookUrl && reminders.length > 0) {
1318
+ const webhookRes = await fetchFn(webhookUrl, {
1319
+ method: 'POST',
1320
+ headers: { 'Content-Type': 'application/json' },
1321
+ body: JSON.stringify({
1322
+ event: 'neuralbrain.reminders.due',
1323
+ checked_at: checkedAt,
1324
+ count: reminders.length,
1325
+ reminders,
1326
+ }),
1327
+ signal: AbortSignal.timeout(10_000),
1328
+ });
1329
+
1330
+ webhookStatus = webhookRes.status;
1331
+ if (!webhookRes.ok) {
1332
+ throw new Error(`Webhook delivery failed with status ${webhookRes.status}`);
1333
+ }
1334
+ webhookDelivered = true;
1335
+
1336
+ if (!dryRun) {
1337
+ const ackRes = await fetchFn(`${apiUrl}/actions/reminders/ack`, {
1338
+ method: 'POST',
1339
+ headers,
1340
+ body: JSON.stringify({ ids: reminders.map((r: any) => r.id) }),
1341
+ });
1342
+ const ackData = (await ackRes.json().catch(() => ({}))) as any;
1343
+ if (!ackRes.ok) {
1344
+ throw new Error(
1345
+ `Reminders ack failed (${ackRes.status}): ${ackData?.error?.message || JSON.stringify(ackData)}`
1346
+ );
1347
+ }
1348
+ ackedCount = typeof ackData.updated === 'number' ? ackData.updated : reminders.length;
1349
+ markedCount = ackedCount ?? reminders.length;
1350
+ }
1351
+ } else if (webhookUrl) {
1352
+ webhookDelivered = false;
1353
+ }
1354
+
1355
+ const summaryData: Omit<RemindersCheckResult, 'output'> = {
1356
+ checked_at: checkedAt,
1357
+ reminders,
1358
+ marked_count: markedCount,
1359
+ ...(ackedCount !== undefined ? { acked_count: ackedCount } : {}),
1360
+ ...(webhookDelivered !== undefined ? { webhook_delivered: webhookDelivered } : {}),
1361
+ ...(webhookStatus !== undefined ? { webhook_status: webhookStatus } : {}),
1362
+ };
1363
+
1364
+ const output = options.json
1365
+ ? JSON.stringify(summaryData, null, 2)
1366
+ : formatRemindersHuman(summaryData);
1367
+
1368
+ return {
1369
+ ...summaryData,
1370
+ output,
1371
+ };
1372
+ }
1373
+
1374
+ async function cmdReminders(argv: string[]): Promise<void> {
1375
+ const action = argv[0];
1376
+ if (!action || action === '-h' || action === '--help' || action === 'help') {
1377
+ printHelp();
1378
+ return;
1379
+ }
1380
+ if (action !== 'check') {
1381
+ console.error(`Unknown reminders subcommand '${action}'. Expected: check`);
1382
+ process.exit(1);
1383
+ }
1384
+ loadBrainEnv();
1385
+ const opts = parseRemindersArgs(argv.slice(1));
1386
+ const result = await runRemindersCheck(opts);
1387
+ console.log(result.output);
1388
+ }
1389
+
950
1390
  function printHelp(): void {
951
1391
  console.log(`
952
1392
  Usage: neuralbrain <command> [options]
@@ -962,13 +1402,26 @@ Commands:
962
1402
  --no-agents Skip configuring coding agents
963
1403
  start Start the configured Brain service
964
1404
  stop Stop running Brain / Docker containers
1405
+ restart Stop, wait for the port to free, then start (docker mode rebuilds the image)
965
1406
  status Show service and health status
966
1407
  logs Tail Brain service logs
967
1408
  doctor Run health and AI conformance diagnostics
968
1409
  install-agent Configure Antigravity, Claude Code, Cursor, or project rules
969
1410
  init Write .brainrc here so agents use one project_id for this folder
970
- [project-id] Defaults to this folder's name
1411
+ [project-id] Defaults to this folder's name (supports hierarchical a/b/c)
971
1412
  --force, -f Replace an existing .brainrc
1413
+ --auto-subproject Derive subproject segments from subfolder path below .brainrc
1414
+ --max-depth <n> Limit auto-subproject depth below .brainrc
1415
+ reminders check Check due/overdue action reminders via Brain HTTP API
1416
+ --json Print machine-readable JSON output
1417
+ --webhook <url> POST due reminders payload to http(s) webhook before acking
1418
+ --project <id> Filter reminders to project_id
1419
+ --include-children Include child subprojects under --project
1420
+ --no-ancestors Exclude ancestor projects when --project is set
1421
+ --no-global Exclude global-scoped actions
1422
+ --cooldown <d> Minimum interval before re-notifying (e.g. 30m, 2h, PT15M)
1423
+ --dry-run Evaluate without stamping last_reminded_at
1424
+ --limit <n> Max reminders to return
972
1425
  rename-project Rename a project_id across SQLite and Qdrant (<from> <to>)
973
1426
  mcp Start the stdio MCP server
974
1427
  `);
@@ -995,6 +1448,10 @@ async function main(): Promise<void> {
995
1448
  cmdStop();
996
1449
  return;
997
1450
  }
1451
+ if (sub === 'restart') {
1452
+ await cmdRestart();
1453
+ return;
1454
+ }
998
1455
  if (sub === 'status') {
999
1456
  await cmdStatus();
1000
1457
  return;
@@ -1023,6 +1480,10 @@ async function main(): Promise<void> {
1023
1480
  cmdInit(args.slice(1));
1024
1481
  return;
1025
1482
  }
1483
+ if (sub === 'reminders') {
1484
+ await cmdReminders(args.slice(1));
1485
+ return;
1486
+ }
1026
1487
  if (sub === 'rename-project') {
1027
1488
  loadBrainEnv();
1028
1489
  const [fromId, toId] = args.slice(1);
@@ -1035,7 +1496,8 @@ async function main(): Promise<void> {
1035
1496
  const headers: Record<string, string> = { 'Content-Type': 'application/json' };
1036
1497
  if (apiKey) headers.Authorization = `Bearer ${apiKey}`;
1037
1498
 
1038
- const res = await fetch(`${apiUrl}/maintenance/rename-project`, {
1499
+ const tlsFetch = createLocalTlsFetch();
1500
+ const res = await tlsFetch(`${apiUrl}/maintenance/rename-project`, {
1039
1501
  method: 'POST',
1040
1502
  headers,
1041
1503
  body: JSON.stringify({ from_project_id: fromId, to_project_id: toId }),