neuralbrain 0.0.0-stage → 0.0.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (293) hide show
  1. package/.dockerignore +11 -0
  2. package/.env.example +245 -0
  3. package/Dockerfile +65 -0
  4. package/LICENSE +44 -0
  5. package/README.md +312 -2
  6. package/dist/ai/chat.d.ts +45 -0
  7. package/dist/ai/chat.d.ts.map +1 -0
  8. package/dist/ai/chat.js +153 -0
  9. package/dist/ai/chat.js.map +1 -0
  10. package/dist/ai/circuitBreaker.d.ts +35 -0
  11. package/dist/ai/circuitBreaker.d.ts.map +1 -0
  12. package/dist/ai/circuitBreaker.js +95 -0
  13. package/dist/ai/circuitBreaker.js.map +1 -0
  14. package/dist/ai/config.d.ts +88 -0
  15. package/dist/ai/config.d.ts.map +1 -0
  16. package/dist/ai/config.js +255 -0
  17. package/dist/ai/config.js.map +1 -0
  18. package/dist/ai/vendors.d.ts +58 -0
  19. package/dist/ai/vendors.d.ts.map +1 -0
  20. package/dist/ai/vendors.js +223 -0
  21. package/dist/ai/vendors.js.map +1 -0
  22. package/dist/app.d.ts +4 -0
  23. package/dist/app.d.ts.map +1 -0
  24. package/dist/app.js +1013 -0
  25. package/dist/app.js.map +1 -0
  26. package/dist/cli.d.ts +133 -0
  27. package/dist/cli.d.ts.map +1 -0
  28. package/dist/cli.js +912 -0
  29. package/dist/cli.js.map +1 -0
  30. package/dist/consolidation/candidates.d.ts +34 -0
  31. package/dist/consolidation/candidates.d.ts.map +1 -0
  32. package/dist/consolidation/candidates.js +150 -0
  33. package/dist/consolidation/candidates.js.map +1 -0
  34. package/dist/consolidation/fixtures.d.ts +25 -0
  35. package/dist/consolidation/fixtures.d.ts.map +1 -0
  36. package/dist/consolidation/fixtures.js +400 -0
  37. package/dist/consolidation/fixtures.js.map +1 -0
  38. package/dist/consolidation/gate.d.ts +39 -0
  39. package/dist/consolidation/gate.d.ts.map +1 -0
  40. package/dist/consolidation/gate.js +286 -0
  41. package/dist/consolidation/gate.js.map +1 -0
  42. package/dist/consolidation/runner.d.ts +63 -0
  43. package/dist/consolidation/runner.d.ts.map +1 -0
  44. package/dist/consolidation/runner.js +171 -0
  45. package/dist/consolidation/runner.js.map +1 -0
  46. package/dist/dashboard/clientScript.d.ts +2 -0
  47. package/dist/dashboard/clientScript.d.ts.map +1 -0
  48. package/dist/dashboard/clientScript.js +4212 -0
  49. package/dist/dashboard/clientScript.js.map +1 -0
  50. package/dist/dashboard/html.d.ts +2 -0
  51. package/dist/dashboard/html.d.ts.map +1 -0
  52. package/dist/dashboard/html.js +554 -0
  53. package/dist/dashboard/html.js.map +1 -0
  54. package/dist/dashboard/styles.d.ts +2 -0
  55. package/dist/dashboard/styles.d.ts.map +1 -0
  56. package/dist/dashboard/styles.js +1283 -0
  57. package/dist/dashboard/styles.js.map +1 -0
  58. package/dist/index.d.ts +3 -0
  59. package/dist/index.d.ts.map +1 -0
  60. package/dist/index.js +124 -0
  61. package/dist/index.js.map +1 -0
  62. package/dist/learning/embedWorker.d.ts +58 -0
  63. package/dist/learning/embedWorker.d.ts.map +1 -0
  64. package/dist/learning/embedWorker.js +552 -0
  65. package/dist/learning/embedWorker.js.map +1 -0
  66. package/dist/learning/embedding.d.ts +52 -0
  67. package/dist/learning/embedding.d.ts.map +1 -0
  68. package/dist/learning/embedding.js +511 -0
  69. package/dist/learning/embedding.js.map +1 -0
  70. package/dist/learning/engine.d.ts +20 -0
  71. package/dist/learning/engine.d.ts.map +1 -0
  72. package/dist/learning/engine.js +69 -0
  73. package/dist/learning/engine.js.map +1 -0
  74. package/dist/learning/search.d.ts +4 -0
  75. package/dist/learning/search.d.ts.map +1 -0
  76. package/dist/learning/search.js +509 -0
  77. package/dist/learning/search.js.map +1 -0
  78. package/dist/learning/storeMeta.d.ts +11 -0
  79. package/dist/learning/storeMeta.d.ts.map +1 -0
  80. package/dist/learning/storeMeta.js +100 -0
  81. package/dist/learning/storeMeta.js.map +1 -0
  82. package/dist/learning/types.d.ts +101 -0
  83. package/dist/learning/types.d.ts.map +1 -0
  84. package/dist/learning/types.js +3 -0
  85. package/dist/learning/types.js.map +1 -0
  86. package/dist/lib/brainHome.d.ts +28 -0
  87. package/dist/lib/brainHome.d.ts.map +1 -0
  88. package/dist/lib/brainHome.js +104 -0
  89. package/dist/lib/brainHome.js.map +1 -0
  90. package/dist/lib/db.d.ts +10 -0
  91. package/dist/lib/db.d.ts.map +1 -0
  92. package/dist/lib/db.js +589 -0
  93. package/dist/lib/db.js.map +1 -0
  94. package/dist/lib/logger.d.ts +3 -0
  95. package/dist/lib/logger.d.ts.map +1 -0
  96. package/dist/lib/logger.js +11 -0
  97. package/dist/lib/logger.js.map +1 -0
  98. package/dist/lib/projectSlug.d.ts +61 -0
  99. package/dist/lib/projectSlug.d.ts.map +1 -0
  100. package/dist/lib/projectSlug.js +273 -0
  101. package/dist/lib/projectSlug.js.map +1 -0
  102. package/dist/lib/redactSecrets.d.ts +7 -0
  103. package/dist/lib/redactSecrets.d.ts.map +1 -0
  104. package/dist/lib/redactSecrets.js +90 -0
  105. package/dist/lib/redactSecrets.js.map +1 -0
  106. package/dist/lib/scope.d.ts +54 -0
  107. package/dist/lib/scope.d.ts.map +1 -0
  108. package/dist/lib/scope.js +103 -0
  109. package/dist/lib/scope.js.map +1 -0
  110. package/dist/lib/spool.d.ts +23 -0
  111. package/dist/lib/spool.d.ts.map +1 -0
  112. package/dist/lib/spool.js +317 -0
  113. package/dist/lib/spool.js.map +1 -0
  114. package/dist/lib/sqlite.d.ts +50 -0
  115. package/dist/lib/sqlite.d.ts.map +1 -0
  116. package/dist/lib/sqlite.js +130 -0
  117. package/dist/lib/sqlite.js.map +1 -0
  118. package/dist/lib/tls.d.ts +34 -0
  119. package/dist/lib/tls.d.ts.map +1 -0
  120. package/dist/lib/tls.js +212 -0
  121. package/dist/lib/tls.js.map +1 -0
  122. package/dist/mcp/server.d.ts +231 -0
  123. package/dist/mcp/server.d.ts.map +1 -0
  124. package/dist/mcp/server.js +615 -0
  125. package/dist/mcp/server.js.map +1 -0
  126. package/dist/memory/actionStore.d.ts +75 -0
  127. package/dist/memory/actionStore.d.ts.map +1 -0
  128. package/dist/memory/actionStore.js +239 -0
  129. package/dist/memory/actionStore.js.map +1 -0
  130. package/dist/memory/deadLetterStore.d.ts +30 -0
  131. package/dist/memory/deadLetterStore.d.ts.map +1 -0
  132. package/dist/memory/deadLetterStore.js +91 -0
  133. package/dist/memory/deadLetterStore.js.map +1 -0
  134. package/dist/memory/embedQueueStore.d.ts +32 -0
  135. package/dist/memory/embedQueueStore.d.ts.map +1 -0
  136. package/dist/memory/embedQueueStore.js +143 -0
  137. package/dist/memory/embedQueueStore.js.map +1 -0
  138. package/dist/memory/failurePatternStore.d.ts +37 -0
  139. package/dist/memory/failurePatternStore.d.ts.map +1 -0
  140. package/dist/memory/failurePatternStore.js +179 -0
  141. package/dist/memory/failurePatternStore.js.map +1 -0
  142. package/dist/memory/graphStore.d.ts +38 -0
  143. package/dist/memory/graphStore.d.ts.map +1 -0
  144. package/dist/memory/graphStore.js +229 -0
  145. package/dist/memory/graphStore.js.map +1 -0
  146. package/dist/memory/noteStore.d.ts +58 -0
  147. package/dist/memory/noteStore.d.ts.map +1 -0
  148. package/dist/memory/noteStore.js +280 -0
  149. package/dist/memory/noteStore.js.map +1 -0
  150. package/dist/memory/observationStore.d.ts +40 -0
  151. package/dist/memory/observationStore.d.ts.map +1 -0
  152. package/dist/memory/observationStore.js +213 -0
  153. package/dist/memory/observationStore.js.map +1 -0
  154. package/dist/memory/projectRename.d.ts +14 -0
  155. package/dist/memory/projectRename.d.ts.map +1 -0
  156. package/dist/memory/projectRename.js +105 -0
  157. package/dist/memory/projectRename.js.map +1 -0
  158. package/dist/memory/rollupSweeper.d.ts +36 -0
  159. package/dist/memory/rollupSweeper.d.ts.map +1 -0
  160. package/dist/memory/rollupSweeper.js +235 -0
  161. package/dist/memory/rollupSweeper.js.map +1 -0
  162. package/dist/memory/sessionStore.d.ts +81 -0
  163. package/dist/memory/sessionStore.d.ts.map +1 -0
  164. package/dist/memory/sessionStore.js +285 -0
  165. package/dist/memory/sessionStore.js.map +1 -0
  166. package/dist/memory/trajectoryStore.d.ts +86 -0
  167. package/dist/memory/trajectoryStore.d.ts.map +1 -0
  168. package/dist/memory/trajectoryStore.js +528 -0
  169. package/dist/memory/trajectoryStore.js.map +1 -0
  170. package/dist/middleware/auth.d.ts +30 -0
  171. package/dist/middleware/auth.d.ts.map +1 -0
  172. package/dist/middleware/auth.js +387 -0
  173. package/dist/middleware/auth.js.map +1 -0
  174. package/dist/middleware/rateLimiter.d.ts +13 -0
  175. package/dist/middleware/rateLimiter.d.ts.map +1 -0
  176. package/dist/middleware/rateLimiter.js +153 -0
  177. package/dist/middleware/rateLimiter.js.map +1 -0
  178. package/dist/middleware/tracing.d.ts +15 -0
  179. package/dist/middleware/tracing.d.ts.map +1 -0
  180. package/dist/middleware/tracing.js +53 -0
  181. package/dist/middleware/tracing.js.map +1 -0
  182. package/dist/routes/dashboard.d.ts +2 -0
  183. package/dist/routes/dashboard.d.ts.map +1 -0
  184. package/dist/routes/dashboard.js +443 -0
  185. package/dist/routes/dashboard.js.map +1 -0
  186. package/dist/routes/learning.d.ts +2 -0
  187. package/dist/routes/learning.d.ts.map +1 -0
  188. package/dist/routes/learning.js +46 -0
  189. package/dist/routes/learning.js.map +1 -0
  190. package/dist/routes/mcp.d.ts +8 -0
  191. package/dist/routes/mcp.d.ts.map +1 -0
  192. package/dist/routes/mcp.js +316 -0
  193. package/dist/routes/mcp.js.map +1 -0
  194. package/dist/routes/memories.d.ts +2 -0
  195. package/dist/routes/memories.d.ts.map +1 -0
  196. package/dist/routes/memories.js +33 -0
  197. package/dist/routes/memories.js.map +1 -0
  198. package/dist/scripts/createApiKey.d.ts +2 -0
  199. package/dist/scripts/createApiKey.d.ts.map +1 -0
  200. package/dist/scripts/createApiKey.js +78 -0
  201. package/dist/scripts/createApiKey.js.map +1 -0
  202. package/dist/scripts/doctor.d.ts +24 -0
  203. package/dist/scripts/doctor.d.ts.map +1 -0
  204. package/dist/scripts/doctor.js +332 -0
  205. package/dist/scripts/doctor.js.map +1 -0
  206. package/dist/scripts/installAgent.d.ts +80 -0
  207. package/dist/scripts/installAgent.d.ts.map +1 -0
  208. package/dist/scripts/installAgent.js +1046 -0
  209. package/dist/scripts/installAgent.js.map +1 -0
  210. package/dist/scripts/migrateAgentMemory.d.ts +16 -0
  211. package/dist/scripts/migrateAgentMemory.d.ts.map +1 -0
  212. package/dist/scripts/migrateAgentMemory.js +209 -0
  213. package/dist/scripts/migrateAgentMemory.js.map +1 -0
  214. package/dist/scripts/smokeTest.d.ts +16 -0
  215. package/dist/scripts/smokeTest.d.ts.map +1 -0
  216. package/dist/scripts/smokeTest.js +150 -0
  217. package/dist/scripts/smokeTest.js.map +1 -0
  218. package/docker-compose.qdrant-port.yml +7 -0
  219. package/docker-compose.yml +107 -0
  220. package/npm-shrinkwrap.json +7635 -0
  221. package/package.json +107 -4
  222. package/plugin/hooks/postToolUse.js +513 -0
  223. package/plugin/hooks/sessionStart.js +416 -0
  224. package/plugin/hooks/sessionStop.js +346 -0
  225. package/plugin/hooks.json +30 -0
  226. package/plugin/mcp_config.json +13 -0
  227. package/plugin/plugin.json +15 -0
  228. package/plugin/rules/AGENTS.md +66 -0
  229. package/plugin/skills/brain-memory/REFERENCE.md +64 -0
  230. package/plugin/skills/brain-memory/SKILL.md +68 -0
  231. package/plugin/skills/brain-memory/TROUBLESHOOTING.md +24 -0
  232. package/plugin/skills/digest/SKILL.md +54 -0
  233. package/plugin/skills/digest/TROUBLESHOOTING.md +24 -0
  234. package/plugin/skills/handoff/SKILL.md +59 -0
  235. package/plugin/skills/handoff/TROUBLESHOOTING.md +24 -0
  236. package/plugin/skills/save/SKILL.md +76 -0
  237. package/plugin/skills/save/TROUBLESHOOTING.md +24 -0
  238. package/plugin/skills/search/SKILL.md +60 -0
  239. package/plugin/skills/search/TROUBLESHOOTING.md +24 -0
  240. package/src/ai/chat.ts +214 -0
  241. package/src/ai/circuitBreaker.ts +120 -0
  242. package/src/ai/config.ts +311 -0
  243. package/src/ai/vendors.ts +292 -0
  244. package/src/app.ts +1150 -0
  245. package/src/cli.ts +1080 -0
  246. package/src/consolidation/candidates.ts +219 -0
  247. package/src/consolidation/fixtures.ts +461 -0
  248. package/src/consolidation/gate.ts +408 -0
  249. package/src/consolidation/runner.ts +220 -0
  250. package/src/dashboard/clientScript.ts +4208 -0
  251. package/src/dashboard/html.ts +550 -0
  252. package/src/dashboard/styles.ts +1279 -0
  253. package/src/index.ts +139 -0
  254. package/src/learning/embedWorker.ts +651 -0
  255. package/src/learning/embedding.ts +522 -0
  256. package/src/learning/engine.ts +86 -0
  257. package/src/learning/search.ts +568 -0
  258. package/src/learning/storeMeta.ts +147 -0
  259. package/src/learning/types.ts +111 -0
  260. package/src/lib/brainHome.ts +101 -0
  261. package/src/lib/db.ts +627 -0
  262. package/src/lib/logger.ts +7 -0
  263. package/src/lib/projectSlug.ts +286 -0
  264. package/src/lib/redactSecrets.ts +87 -0
  265. package/src/lib/scope.ts +121 -0
  266. package/src/lib/spool.ts +372 -0
  267. package/src/lib/sqlite.ts +158 -0
  268. package/src/lib/tls.ts +252 -0
  269. package/src/mcp/server.ts +793 -0
  270. package/src/memory/actionStore.ts +378 -0
  271. package/src/memory/deadLetterStore.ts +141 -0
  272. package/src/memory/embedQueueStore.ts +176 -0
  273. package/src/memory/failurePatternStore.ts +221 -0
  274. package/src/memory/graphStore.ts +352 -0
  275. package/src/memory/noteStore.ts +403 -0
  276. package/src/memory/observationStore.ts +303 -0
  277. package/src/memory/projectRename.ts +147 -0
  278. package/src/memory/rollupSweeper.ts +309 -0
  279. package/src/memory/sessionStore.ts +410 -0
  280. package/src/memory/trajectoryStore.ts +775 -0
  281. package/src/middleware/auth.ts +450 -0
  282. package/src/middleware/rateLimiter.ts +186 -0
  283. package/src/middleware/tracing.ts +70 -0
  284. package/src/routes/dashboard.ts +496 -0
  285. package/src/routes/learning.ts +51 -0
  286. package/src/routes/mcp.ts +349 -0
  287. package/src/routes/memories.ts +33 -0
  288. package/src/scripts/createApiKey.ts +109 -0
  289. package/src/scripts/doctor.ts +359 -0
  290. package/src/scripts/installAgent.ts +1278 -0
  291. package/src/scripts/migrateAgentMemory.ts +263 -0
  292. package/src/scripts/smokeTest.ts +189 -0
  293. package/tsconfig.json +21 -0
@@ -0,0 +1,378 @@
1
+ import { randomUUID } from 'crypto';
2
+ import { getDb } from '../lib/db';
3
+ import { resolveScope, ScopeValue } from '../lib/scope';
4
+
5
+ export type ActionStatus = 'ready' | 'blocked' | 'in_progress' | 'done' | 'dismissed';
6
+ export type ActionPriority = 'low' | 'normal' | 'high' | 'urgent';
7
+
8
+ const VALID_STATUSES = new Set<ActionStatus>([
9
+ 'ready',
10
+ 'blocked',
11
+ 'in_progress',
12
+ 'done',
13
+ 'dismissed',
14
+ ]);
15
+
16
+ const VALID_PRIORITIES = new Set<ActionPriority>([
17
+ 'low',
18
+ 'normal',
19
+ 'high',
20
+ 'urgent',
21
+ ]);
22
+
23
+ export interface ActionRecord {
24
+ id: string;
25
+ session_id: string | null;
26
+ scope: ScopeValue;
27
+ project_id: string | null;
28
+ title: string;
29
+ description: string | null;
30
+ status: ActionStatus;
31
+ priority: ActionPriority;
32
+ blocked_reason: string | null;
33
+ files_json: string | null;
34
+ created_at: string;
35
+ updated_at: string;
36
+ resolved_at: string | null;
37
+ resolved_by_session_id: string | null;
38
+ }
39
+
40
+ export interface CreateActionInput {
41
+ id?: string;
42
+ session_id?: string | null;
43
+ sessionId?: string | null;
44
+ scope?: ScopeValue;
45
+ project_id?: string | null;
46
+ projectId?: string | null;
47
+ title: string;
48
+ description?: string | null;
49
+ status?: ActionStatus;
50
+ priority?: ActionPriority;
51
+ blocked_reason?: string | null;
52
+ blockedReason?: string | null;
53
+ files?: string[];
54
+ files_json?: string | null;
55
+ }
56
+
57
+ export interface UpdateActionPatch {
58
+ scope?: ScopeValue;
59
+ project_id?: string | null;
60
+ projectId?: string | null;
61
+ title?: string;
62
+ description?: string | null;
63
+ status?: ActionStatus;
64
+ priority?: ActionPriority;
65
+ blocked_reason?: string | null;
66
+ blockedReason?: string | null;
67
+ files?: string[];
68
+ files_json?: string | null;
69
+ resolved_by_session_id?: string | null;
70
+ resolvedBySessionId?: string | null;
71
+ }
72
+
73
+ function makeSchemaError(message: string): Error {
74
+ const err = new Error(message);
75
+ (err as any).code = 'SCHEMA_INVALID';
76
+ return err;
77
+ }
78
+
79
+ function optionalString(value: unknown, field: string): string | null {
80
+ if (value === undefined || value === null) return null;
81
+ if (typeof value !== 'string') {
82
+ throw makeSchemaError(`${field} must be a string`);
83
+ }
84
+ return value.trim() || null;
85
+ }
86
+
87
+ /**
88
+ * Create a new next-action record with explicit 3-state scope validation.
89
+ */
90
+ export function createAction(input: CreateActionInput): ActionRecord {
91
+ const rawProject = input.projectId !== undefined ? input.projectId : input.project_id;
92
+ const scoped = resolveScope(input.scope, rawProject);
93
+ if (!scoped.ok) {
94
+ throw makeSchemaError(scoped.error);
95
+ }
96
+
97
+ if (!input.title || typeof input.title !== 'string' || input.title.trim() === '') {
98
+ throw makeSchemaError('title is required and cannot be empty');
99
+ }
100
+
101
+ const status: ActionStatus = input.status ?? 'ready';
102
+ if (!VALID_STATUSES.has(status)) {
103
+ throw makeSchemaError(
104
+ `Invalid action status '${String(status)}'. Must be one of: ready, blocked, in_progress, done, dismissed`
105
+ );
106
+ }
107
+
108
+ const priority: ActionPriority = input.priority ?? 'normal';
109
+ if (!VALID_PRIORITIES.has(priority)) {
110
+ throw makeSchemaError(
111
+ `Invalid action priority '${String(priority)}'. Must be one of: low, normal, high, urgent`
112
+ );
113
+ }
114
+
115
+ const db = getDb();
116
+ const customId = optionalString(input.id, 'id');
117
+ const id = customId || `act_${randomUUID().replace(/-/g, '').slice(0, 16)}`;
118
+ const rawSession = input.sessionId !== undefined ? input.sessionId : input.session_id;
119
+ const sessionId = optionalString(rawSession, 'session_id');
120
+ const description = optionalString(input.description, 'description');
121
+ const rawBlockedReason =
122
+ input.blockedReason !== undefined ? input.blockedReason : input.blocked_reason;
123
+ const blockedReason = optionalString(rawBlockedReason, 'blocked_reason');
124
+ const filesJson = Array.isArray(input.files)
125
+ ? JSON.stringify(input.files)
126
+ : input.files_json ?? null;
127
+
128
+ const isResolved = status === 'done' || status === 'dismissed';
129
+
130
+ db.prepare(
131
+ `
132
+ INSERT INTO actions (
133
+ id, session_id, scope, project_id, title, description,
134
+ status, priority, blocked_reason, files_json, resolved_at
135
+ ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, CASE WHEN ? = 1 THEN datetime('now') ELSE NULL END)
136
+ `
137
+ ).run(
138
+ id,
139
+ sessionId,
140
+ scoped.scope,
141
+ scoped.projectId,
142
+ input.title.trim(),
143
+ description,
144
+ status,
145
+ priority,
146
+ blockedReason,
147
+ filesJson,
148
+ isResolved ? 1 : 0
149
+ );
150
+
151
+ return getAction(id)!;
152
+ }
153
+
154
+ export function getAction(id: string): ActionRecord | undefined {
155
+ const db = getDb();
156
+ return db.prepare('SELECT * FROM actions WHERE id = ?').get(id) as
157
+ | ActionRecord
158
+ | undefined;
159
+ }
160
+
161
+ export function listActions(filters?: {
162
+ projectId?: string;
163
+ includeGlobal?: boolean;
164
+ status?: string | string[];
165
+ sessionId?: string;
166
+ limit?: number;
167
+ }): ActionRecord[] {
168
+ const db = getDb();
169
+ const conditions: string[] = [];
170
+ const params: unknown[] = [];
171
+
172
+ const projectId = typeof filters?.projectId === 'string' ? filters.projectId.trim() || null : null;
173
+ const includeGlobal = filters?.includeGlobal !== false;
174
+
175
+ if (projectId) {
176
+ if (includeGlobal) {
177
+ conditions.push("((project_id = ? AND scope = 'project') OR scope = 'global')");
178
+ params.push(projectId);
179
+ } else {
180
+ conditions.push("(project_id = ? AND scope = 'project')");
181
+ params.push(projectId);
182
+ }
183
+ } else if (filters?.includeGlobal === false) {
184
+ conditions.push("scope != 'global'");
185
+ }
186
+
187
+ if (filters?.status) {
188
+ const statuses = Array.isArray(filters.status)
189
+ ? filters.status
190
+ : [filters.status];
191
+ if (statuses.length > 0) {
192
+ const placeholders = statuses.map(() => '?').join(',');
193
+ conditions.push(`status IN (${placeholders})`);
194
+ params.push(...statuses);
195
+ }
196
+ }
197
+
198
+ if (typeof filters?.sessionId === 'string' && filters.sessionId.trim()) {
199
+ conditions.push('session_id = ?');
200
+ params.push(filters.sessionId.trim());
201
+ }
202
+
203
+ const whereClause = conditions.length > 0 ? `WHERE ${conditions.join(' AND ')}` : '';
204
+ const limit = filters?.limit ?? 50;
205
+ params.push(limit);
206
+
207
+ return db
208
+ .prepare(
209
+ `
210
+ SELECT * FROM actions
211
+ ${whereClause}
212
+ ORDER BY
213
+ CASE priority
214
+ WHEN 'urgent' THEN 0
215
+ WHEN 'high' THEN 1
216
+ WHEN 'normal' THEN 2
217
+ WHEN 'low' THEN 3
218
+ ELSE 4
219
+ END ASC,
220
+ created_at DESC,
221
+ rowid DESC
222
+ LIMIT ?
223
+ `
224
+ )
225
+ .all(...params) as ActionRecord[];
226
+ }
227
+
228
+ /**
229
+ * Return open ('ready' or 'in_progress') actions for a project plus global actions.
230
+ */
231
+ export function getReadyActions(params?: {
232
+ projectId?: string;
233
+ limit?: number;
234
+ }): ActionRecord[] {
235
+ return listActions({
236
+ projectId: params?.projectId,
237
+ includeGlobal: true,
238
+ status: ['ready', 'in_progress'],
239
+ limit: params?.limit ?? 10,
240
+ });
241
+ }
242
+
243
+ /**
244
+ * Update an action record. Automatically sets resolved_at when status becomes
245
+ * 'done' or 'dismissed', and always updates updated_at.
246
+ */
247
+ export function updateAction(
248
+ id: string,
249
+ patch: UpdateActionPatch
250
+ ): ActionRecord | undefined {
251
+ const existing = getAction(id);
252
+ if (!existing) return undefined;
253
+
254
+ let nextScope = existing.scope;
255
+ let nextProjectId = existing.project_id;
256
+ if (
257
+ patch.scope !== undefined ||
258
+ patch.projectId !== undefined ||
259
+ patch.project_id !== undefined
260
+ ) {
261
+ const rawScope = patch.scope !== undefined ? patch.scope : existing.scope;
262
+ const rawProject =
263
+ patch.projectId !== undefined
264
+ ? patch.projectId
265
+ : patch.project_id !== undefined
266
+ ? patch.project_id
267
+ : existing.project_id;
268
+ const scoped = resolveScope(rawScope, rawProject);
269
+ if (!scoped.ok) {
270
+ throw makeSchemaError(scoped.error);
271
+ }
272
+ nextScope = scoped.scope;
273
+ nextProjectId = scoped.projectId;
274
+ }
275
+
276
+ let nextTitle = existing.title;
277
+ if (patch.title !== undefined) {
278
+ if (typeof patch.title !== 'string' || patch.title.trim() === '') {
279
+ throw makeSchemaError('title cannot be empty');
280
+ }
281
+ nextTitle = patch.title.trim();
282
+ }
283
+
284
+ let nextStatus = existing.status;
285
+ if (patch.status !== undefined) {
286
+ if (!VALID_STATUSES.has(patch.status)) {
287
+ throw makeSchemaError(
288
+ `Invalid action status '${String(patch.status)}'. Must be one of: ready, blocked, in_progress, done, dismissed`
289
+ );
290
+ }
291
+ nextStatus = patch.status;
292
+ }
293
+
294
+ let nextPriority = existing.priority;
295
+ if (patch.priority !== undefined) {
296
+ if (!VALID_PRIORITIES.has(patch.priority)) {
297
+ throw makeSchemaError(
298
+ `Invalid action priority '${String(patch.priority)}'. Must be one of: low, normal, high, urgent`
299
+ );
300
+ }
301
+ nextPriority = patch.priority;
302
+ }
303
+
304
+ const nextDescription =
305
+ patch.description !== undefined
306
+ ? optionalString(patch.description, 'description')
307
+ : existing.description;
308
+
309
+ const rawBlockedReason =
310
+ patch.blockedReason !== undefined ? patch.blockedReason : patch.blocked_reason;
311
+ const nextBlockedReason =
312
+ rawBlockedReason !== undefined
313
+ ? optionalString(rawBlockedReason, 'blocked_reason')
314
+ : existing.blocked_reason;
315
+
316
+ const nextFilesJson = Array.isArray(patch.files)
317
+ ? JSON.stringify(patch.files)
318
+ : patch.files_json !== undefined
319
+ ? optionalString(patch.files_json, 'files_json')
320
+ : existing.files_json;
321
+
322
+ const rawResolvedBy =
323
+ patch.resolvedBySessionId !== undefined
324
+ ? patch.resolvedBySessionId
325
+ : patch.resolved_by_session_id;
326
+ const nextResolvedBy =
327
+ rawResolvedBy !== undefined
328
+ ? optionalString(rawResolvedBy, 'resolved_by_session_id')
329
+ : existing.resolved_by_session_id;
330
+
331
+ const shouldSetResolvedAt =
332
+ (nextStatus === 'done' || nextStatus === 'dismissed') &&
333
+ existing.status !== 'done' &&
334
+ existing.status !== 'dismissed';
335
+
336
+ const shouldClearResolvedAt =
337
+ nextStatus !== 'done' &&
338
+ nextStatus !== 'dismissed' &&
339
+ (existing.status === 'done' || existing.status === 'dismissed');
340
+
341
+ const db = getDb();
342
+ db.prepare(
343
+ `
344
+ UPDATE actions
345
+ SET scope = ?,
346
+ project_id = ?,
347
+ title = ?,
348
+ description = ?,
349
+ status = ?,
350
+ priority = ?,
351
+ blocked_reason = ?,
352
+ files_json = ?,
353
+ resolved_by_session_id = ?,
354
+ resolved_at = CASE
355
+ WHEN ? = 1 THEN datetime('now')
356
+ WHEN ? = 1 THEN NULL
357
+ ELSE resolved_at
358
+ END,
359
+ updated_at = datetime('now')
360
+ WHERE id = ?
361
+ `
362
+ ).run(
363
+ nextScope,
364
+ nextProjectId,
365
+ nextTitle,
366
+ nextDescription,
367
+ nextStatus,
368
+ nextPriority,
369
+ nextBlockedReason,
370
+ nextFilesJson,
371
+ nextResolvedBy,
372
+ shouldSetResolvedAt ? 1 : 0,
373
+ shouldClearResolvedAt ? 1 : 0,
374
+ id
375
+ );
376
+
377
+ return getAction(id)!;
378
+ }
@@ -0,0 +1,141 @@
1
+ import { randomUUID } from 'crypto';
2
+ import { getDb } from '../lib/db';
3
+ import { logger } from '../lib/logger';
4
+
5
+ export type DeadLetterSource = 'capture' | 'summarize' | 'consolidate';
6
+ export type DeadLetterReason =
7
+ | 'schema_invalid'
8
+ | 'unparseable'
9
+ | 'empty_content'
10
+ | 'truncated'
11
+ | 'citation_unresolved'
12
+ | 'not_verbatim';
13
+
14
+ export interface DeadLetterRecord {
15
+ id: string;
16
+ source: DeadLetterSource;
17
+ reason: DeadLetterReason;
18
+ producer: string | null;
19
+ payload: string;
20
+ created_at: number;
21
+ }
22
+
23
+ export function recordDeadLetter(params: {
24
+ source: DeadLetterSource;
25
+ reason: DeadLetterReason;
26
+ producer?: string | null;
27
+ payload: unknown;
28
+ }): string {
29
+ const db = getDb();
30
+ const id = `dl_${randomUUID().replace(/-/g, '').slice(0, 16)}`;
31
+ const payloadStr =
32
+ typeof params.payload === 'string'
33
+ ? params.payload
34
+ : JSON.stringify(params.payload);
35
+
36
+ try {
37
+ db.prepare(`
38
+ INSERT INTO dead_letters (id, source, reason, producer, payload, created_at)
39
+ VALUES (?, ?, ?, ?, ?, unixepoch())
40
+ `).run(id, params.source, params.reason, params.producer ?? null, payloadStr);
41
+
42
+ logger.warn(
43
+ {
44
+ id,
45
+ source: params.source,
46
+ reason: params.reason,
47
+ producer: params.producer,
48
+ },
49
+ 'dead letter recorded'
50
+ );
51
+
52
+ return id;
53
+ } catch (error) {
54
+ logger.error(
55
+ {
56
+ id,
57
+ error: error instanceof Error ? error.message : String(error),
58
+ },
59
+ 'failed to record dead letter'
60
+ );
61
+ throw error;
62
+ }
63
+ }
64
+
65
+ export function listDeadLetters(filters?: {
66
+ source?: string;
67
+ reason?: string;
68
+ producer?: string;
69
+ limit?: number;
70
+ offset?: number;
71
+ }): DeadLetterRecord[] {
72
+ const db = getDb();
73
+ const conditions: string[] = [];
74
+ const params: unknown[] = [];
75
+
76
+ if (filters?.source) {
77
+ conditions.push('source = ?');
78
+ params.push(filters.source);
79
+ }
80
+ if (filters?.reason) {
81
+ conditions.push('reason = ?');
82
+ params.push(filters.reason);
83
+ }
84
+ if (filters?.producer) {
85
+ conditions.push('producer = ?');
86
+ params.push(filters.producer);
87
+ }
88
+
89
+ const whereClause = conditions.length > 0 ? `WHERE ${conditions.join(' AND ')}` : '';
90
+ const limit = filters?.limit ?? 50;
91
+ const offset = filters?.offset ?? 0;
92
+ params.push(limit, offset);
93
+
94
+ return db
95
+ .prepare(
96
+ `SELECT id, source, reason, producer, payload, created_at
97
+ FROM dead_letters
98
+ ${whereClause}
99
+ ORDER BY created_at DESC
100
+ LIMIT ? OFFSET ?`
101
+ )
102
+ .all(...params) as DeadLetterRecord[];
103
+ }
104
+
105
+ export function getDeadLetterStats(): {
106
+ total: number;
107
+ byReason: Record<string, number>;
108
+ byProducer: Record<string, number>;
109
+ bySource: Record<string, number>;
110
+ } {
111
+ const db = getDb();
112
+
113
+ const totalRow = db.prepare('SELECT COUNT(*) as count FROM dead_letters').get() as { count: number };
114
+ const total = totalRow?.count ?? 0;
115
+
116
+ const reasonRows = db
117
+ .prepare('SELECT reason, COUNT(*) as count FROM dead_letters GROUP BY reason')
118
+ .all() as Array<{ reason: string; count: number }>;
119
+ const byReason: Record<string, number> = {};
120
+ for (const row of reasonRows) {
121
+ byReason[row.reason] = row.count;
122
+ }
123
+
124
+ const producerRows = db
125
+ .prepare('SELECT COALESCE(producer, "unknown") as producer, COUNT(*) as count FROM dead_letters GROUP BY producer')
126
+ .all() as Array<{ producer: string; count: number }>;
127
+ const byProducer: Record<string, number> = {};
128
+ for (const row of producerRows) {
129
+ byProducer[row.producer] = row.count;
130
+ }
131
+
132
+ const sourceRows = db
133
+ .prepare('SELECT source, COUNT(*) as count FROM dead_letters GROUP BY source')
134
+ .all() as Array<{ source: string; count: number }>;
135
+ const bySource: Record<string, number> = {};
136
+ for (const row of sourceRows) {
137
+ bySource[row.source] = row.count;
138
+ }
139
+
140
+ return { total, byReason, byProducer, bySource };
141
+ }
@@ -0,0 +1,176 @@
1
+ import { getDb } from '../lib/db';
2
+ import { logger } from '../lib/logger';
3
+ import { Database, Statement, transaction } from '../lib/sqlite';
4
+
5
+ export type EmbedGrain = 'observation' | 'trajectory' | 'note' | 'summary';
6
+ export type EmbedStatus = 'pending' | 'running' | 'done' | 'failed';
7
+
8
+ export interface EmbedQueueItem {
9
+ record_id: string;
10
+ grain: EmbedGrain;
11
+ status: EmbedStatus;
12
+ attempts: number;
13
+ last_error: string | null;
14
+ target: string;
15
+ queued_at: number;
16
+ }
17
+
18
+ const insertStmtCache = new WeakMap<Database, Statement>();
19
+
20
+ function getEnqueueStatement(db: Database): Statement {
21
+ let stmt = insertStmtCache.get(db);
22
+ if (!stmt) {
23
+ stmt = db.prepare(`
24
+ INSERT INTO embed_queue (record_id, grain, status, attempts, last_error, target, queued_at)
25
+ VALUES (?, ?, 'pending', 0, NULL, ?, unixepoch())
26
+ ON CONFLICT(record_id, grain, target) DO UPDATE SET
27
+ status = 'pending',
28
+ attempts = 0,
29
+ last_error = NULL,
30
+ queued_at = unixepoch()
31
+ `);
32
+ insertStmtCache.set(db, stmt);
33
+ }
34
+ return stmt;
35
+ }
36
+
37
+ export function enqueueForEmbedding(
38
+ recordId: string,
39
+ grain: EmbedGrain,
40
+ target = 'live'
41
+ ): void {
42
+ const db = getDb();
43
+ try {
44
+ getEnqueueStatement(db).run(recordId, grain, target);
45
+ } catch (error) {
46
+ logger.error(
47
+ { recordId, grain, target, error: error instanceof Error ? error.message : String(error) },
48
+ 'failed to enqueue record for embedding'
49
+ );
50
+ throw error;
51
+ }
52
+ }
53
+
54
+ export function batchEnqueueForEmbedding(
55
+ ids: string[],
56
+ grain: EmbedGrain,
57
+ targetCollection = 'live'
58
+ ): void {
59
+ if (!ids || ids.length === 0) return;
60
+ const db = getDb();
61
+ const stmt = getEnqueueStatement(db);
62
+ const tx = transaction(db, () => {
63
+ for (const id of ids) {
64
+ stmt.run(id, grain, targetCollection);
65
+ }
66
+ });
67
+ try {
68
+ tx();
69
+ } catch (error) {
70
+ logger.error(
71
+ {
72
+ count: ids.length,
73
+ grain,
74
+ target: targetCollection,
75
+ error: error instanceof Error ? error.message : String(error),
76
+ },
77
+ 'failed to batch enqueue records for embedding'
78
+ );
79
+ throw error;
80
+ }
81
+ }
82
+
83
+ export function getPendingEmbedCount(target = 'live'): number {
84
+ const db = getDb();
85
+ const row = db
86
+ .prepare('SELECT COUNT(*) as count FROM embed_queue WHERE target = ? AND status = ?')
87
+ .get(target, 'pending') as { count: number } | undefined;
88
+ return row?.count ?? 0;
89
+ }
90
+
91
+ export function claimEmbedQueue(target = 'live', limit = 32): EmbedQueueItem[] {
92
+ const db = getDb();
93
+ const tx = transaction(db, () => {
94
+ const rows = db
95
+ .prepare(`
96
+ SELECT record_id, grain, status, attempts, last_error, target, queued_at
97
+ FROM embed_queue
98
+ WHERE target = ? AND status = 'pending'
99
+ ORDER BY queued_at ASC
100
+ LIMIT ?
101
+ `)
102
+ .all(target, limit) as EmbedQueueItem[];
103
+
104
+ if (rows.length === 0) {
105
+ return [];
106
+ }
107
+
108
+ const updateStmt = db.prepare(`
109
+ UPDATE embed_queue
110
+ SET status = 'running', attempts = attempts + 1
111
+ WHERE record_id = ? AND grain = ? AND target = ?
112
+ `);
113
+
114
+ for (const row of rows) {
115
+ updateStmt.run(row.record_id, row.grain, row.target);
116
+ row.status = 'running';
117
+ row.attempts += 1;
118
+ }
119
+
120
+ return rows;
121
+ });
122
+
123
+ return tx();
124
+ }
125
+
126
+ export function markEmbedDone(recordId: string, grain: EmbedGrain, target = 'live'): void {
127
+ const db = getDb();
128
+ db.prepare(`
129
+ UPDATE embed_queue
130
+ SET status = 'done', last_error = NULL
131
+ WHERE record_id = ? AND grain = ? AND target = ?
132
+ `).run(recordId, grain, target);
133
+ }
134
+
135
+ /**
136
+ * Remove every queue entry for a record, across all targets.
137
+ *
138
+ * Only for a record the service has deleted: leaving the entry behind means
139
+ * the worker keeps claiming a row that no longer exists.
140
+ */
141
+ export function dequeueRecord(recordId: string, grain: EmbedGrain): number {
142
+ const db = getDb();
143
+ const result = db
144
+ .prepare('DELETE FROM embed_queue WHERE record_id = ? AND grain = ?')
145
+ .run(recordId, grain);
146
+ return result.changes;
147
+ }
148
+
149
+ /**
150
+ * Returns a claimed ('running') item to 'pending' without counting it as a
151
+ * failure. Used when embedding cannot run at all (the embedder is not
152
+ * installed or not configured): that is a dependency outage, not a bad record,
153
+ * so the record waits for the embedder instead of being marked failed (rule 3).
154
+ */
155
+ export function releaseEmbedClaim(recordId: string, grain: EmbedGrain, target = 'live', reason?: string): void {
156
+ const db = getDb();
157
+ db.prepare(`
158
+ UPDATE embed_queue
159
+ SET status = 'pending', last_error = ?
160
+ WHERE record_id = ? AND grain = ? AND target = ? AND status = 'running'
161
+ `).run(reason ?? null, recordId, grain, target);
162
+ }
163
+
164
+ export function markEmbedFailed(
165
+ recordId: string,
166
+ grain: EmbedGrain,
167
+ target = 'live',
168
+ error?: string
169
+ ): void {
170
+ const db = getDb();
171
+ db.prepare(`
172
+ UPDATE embed_queue
173
+ SET status = 'failed', last_error = ?
174
+ WHERE record_id = ? AND grain = ? AND target = ?
175
+ `).run(error ?? 'Unknown embedding error', recordId, grain, target);
176
+ }