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
@@ -15,6 +15,8 @@ export interface ConsolidationCandidate {
15
15
  expires_at: number;
16
16
  }
17
17
 
18
+ const MAX_OBSERVATIONS_PER_LEASE = 200;
19
+
18
20
  export function getConsolidationCandidates(params?: {
19
21
  projectId?: string;
20
22
  limit?: number;
@@ -67,13 +69,29 @@ export function getConsolidationCandidates(params?: {
67
69
  const candidates: ConsolidationCandidate[] = [];
68
70
 
69
71
  for (const sess of candidateSessions) {
72
+ const projectClause =
73
+ sess.project_id === null ? 'o.project_id IS NULL' : 'o.project_id = ?';
74
+ const obsParams: unknown[] = [sess.session_id, sess.scope];
75
+ if (sess.project_id !== null) {
76
+ obsParams.push(sess.project_id);
77
+ }
78
+ obsParams.push(MAX_OBSERVATIONS_PER_LEASE);
79
+
70
80
  const obsRows = db
71
81
  .prepare(`
72
- SELECT * FROM observations
73
- WHERE session_id = ?
74
- ORDER BY created_at ASC
82
+ SELECT o.* FROM observations o
83
+ WHERE o.session_id = ?
84
+ AND o.scope = ?
85
+ AND ${projectClause}
86
+ AND NOT EXISTS (
87
+ SELECT 1 FROM summary_sources ss
88
+ JOIN summaries s ON ss.summary_id = s.id
89
+ WHERE ss.record_id = o.id AND s.verified = 1
90
+ )
91
+ ORDER BY o.created_at ASC, o.id ASC
92
+ LIMIT ?
75
93
  `)
76
- .all(sess.session_id) as ObservationRecord[];
94
+ .all(...obsParams) as ObservationRecord[];
77
95
 
78
96
  if (obsRows.length === 0) continue;
79
97
 
@@ -423,7 +423,7 @@ export function runAiConformanceDiagnostics(): AiDiagnosticsReport {
423
423
  const db = getDb();
424
424
  if (allSummaryIds.length > 0) {
425
425
  const placeholders = allSummaryIds.map(() => '?').join(',');
426
- db.prepare(`DELETE FROM embed_queue WHERE grain = 'summary' AND record_id IN (${placeholders})`).run(...allSummaryIds);
426
+ db.prepare(`DELETE FROM embed_queue WHERE record_type = 'summary' AND record_id IN (${placeholders})`).run(...allSummaryIds);
427
427
  db.prepare(`DELETE FROM summary_claims WHERE summary_id IN (${placeholders})`).run(...allSummaryIds);
428
428
  db.prepare(`DELETE FROM summary_sources WHERE summary_id IN (${placeholders})`).run(...allSummaryIds);
429
429
  db.prepare(`DELETE FROM summaries WHERE id IN (${placeholders})`).run(...allSummaryIds);
@@ -1,6 +1,7 @@
1
1
  import { randomUUID } from 'crypto';
2
2
  import { getDb } from '../lib/db';
3
3
  import { logger } from '../lib/logger';
4
+ import { redactSecrets } from '../lib/redactSecrets';
4
5
  import { recordDeadLetter, type DeadLetterReason } from '../memory/deadLetterStore';
5
6
  import { enqueueForEmbedding } from '../memory/embedQueueStore';
6
7
  import type { ObservationRecord } from '../memory/observationStore';
@@ -144,6 +145,9 @@ export function verifyAndStoreSummary(
144
145
  error: err instanceof Error ? err.message : String(err),
145
146
  });
146
147
  }
148
+ if (!parsedPayload || typeof parsedPayload !== 'object' || Array.isArray(parsedPayload)) {
149
+ return reject('schema_invalid', 'Parsed response must be a JSON object');
150
+ }
147
151
  }
148
152
 
149
153
  // 4. schema_invalid
@@ -154,7 +158,8 @@ export function verifyAndStoreSummary(
154
158
  }
155
159
  }
156
160
 
157
- const claims = parsedPayload.claims ?? submission.claims;
161
+ // Validate strictly against parsedPayload when raw_response is provided (no fallback to submission.*)
162
+ const claims = parsedPayload.claims;
158
163
  if (!Array.isArray(claims)) {
159
164
  return reject('schema_invalid', 'Submission must contain a claims array');
160
165
  }
@@ -175,163 +180,194 @@ export function verifyAndStoreSummary(
175
180
  }
176
181
  }
177
182
 
178
- const filesTouched = parsedPayload.files_touched ?? submission.files_touched;
183
+ const filesTouched = parsedPayload.files_touched;
179
184
  if (filesTouched !== undefined && !Array.isArray(filesTouched)) {
180
185
  return reject('schema_invalid', 'files_touched must be an array of strings if provided');
181
186
  }
182
187
 
183
- const errorVerbatim = parsedPayload.error_verbatim ?? submission.error_verbatim;
184
- if (errorVerbatim !== undefined && errorVerbatim !== null && typeof errorVerbatim !== 'string') {
188
+ const rawErrorVerbatim = parsedPayload.error_verbatim;
189
+ if (rawErrorVerbatim !== undefined && rawErrorVerbatim !== null && typeof rawErrorVerbatim !== 'string') {
185
190
  return reject('schema_invalid', 'error_verbatim must be a string or null');
186
191
  }
192
+ const errorVerbatim =
193
+ typeof rawErrorVerbatim === 'string' ? redactSecrets(rawErrorVerbatim) : rawErrorVerbatim;
187
194
 
188
- // 5. Verify lease
195
+ // 5. Verify lease & store inside a single transaction to prevent TOCTOU races
189
196
  const leaseId = submission.lease_id?.trim();
190
197
  if (!leaseId) {
191
198
  return reject('schema_invalid', 'lease_id is required');
192
199
  }
193
200
 
194
- const now = Math.floor(Date.now() / 1000);
195
- const lease = db
196
- .prepare('SELECT * FROM consolidation_leases WHERE lease_id = ?')
197
- .get(leaseId) as
198
- | {
199
- lease_id: string;
200
- kind: string;
201
- scope: string;
202
- project_id: string | null;
203
- session_id: string;
204
- observation_ids: string;
205
- expires_at: number;
206
- completed_at: number | null;
207
- }
208
- | undefined;
201
+ try {
202
+ return transaction(db, (): GateVerificationResult => {
203
+ const now = Math.floor(Date.now() / 1000);
204
+ const lease = db
205
+ .prepare('SELECT * FROM consolidation_leases WHERE lease_id = ?')
206
+ .get(leaseId) as
207
+ | {
208
+ lease_id: string;
209
+ kind: string;
210
+ scope: string;
211
+ project_id: string | null;
212
+ session_id: string;
213
+ observation_ids: string;
214
+ expires_at: number;
215
+ completed_at: number | null;
216
+ }
217
+ | undefined;
209
218
 
210
- if (!lease) {
211
- return reject('schema_invalid', `Lease '${leaseId}' not found`);
212
- }
219
+ if (!lease) {
220
+ return reject('schema_invalid', `Lease '${leaseId}' not found`);
221
+ }
213
222
 
214
- if (lease.completed_at !== null) {
215
- return reject('schema_invalid', `Lease '${leaseId}' has already been completed`);
216
- }
223
+ if (lease.completed_at !== null) {
224
+ return reject('schema_invalid', `Lease '${leaseId}' has already been completed`);
225
+ }
217
226
 
218
- if (lease.expires_at < now) {
219
- return reject('schema_invalid', `Lease '${leaseId}' has expired`);
220
- }
227
+ if (lease.expires_at <= now) {
228
+ return reject('schema_invalid', `Lease '${leaseId}' has expired`);
229
+ }
221
230
 
222
- let leaseObsIds: string[] = [];
223
- try {
224
- leaseObsIds = JSON.parse(lease.observation_ids);
225
- } catch {
226
- return reject('schema_invalid', `Lease '${leaseId}' has invalid observation_ids`);
227
- }
228
- const validObsIdSet = new Set(leaseObsIds);
229
-
230
- // Load source observations
231
- const placeholders = leaseObsIds.map(() => '?').join(',');
232
- const sourceObservations = (
233
- placeholders
234
- ? db.prepare(`SELECT * FROM observations WHERE id IN (${placeholders})`).all(...leaseObsIds)
235
- : []
236
- ) as ObservationRecord[];
237
-
238
- // 6. citation_unresolved
239
- for (const claim of claims) {
240
- if (!claim.source_ids || claim.source_ids.length === 0) {
241
- return reject('citation_unresolved', `Claim '${claim.text}' has no source_ids citations`);
242
- }
243
- for (const srcId of claim.source_ids) {
244
- if (!validObsIdSet.has(srcId)) {
245
- return reject(
246
- 'citation_unresolved',
247
- `Citation id '${srcId}' in claim '${claim.text}' does not resolve to an observation in lease '${leaseId}'`
248
- );
231
+ let leaseObsIds: string[] = [];
232
+ try {
233
+ leaseObsIds = JSON.parse(lease.observation_ids);
234
+ } catch {
235
+ return reject('schema_invalid', `Lease '${leaseId}' has invalid observation_ids`);
236
+ }
237
+ const validObsIdSet = new Set(leaseObsIds);
238
+
239
+ // Load source observations in chunks (checking observations_archive if needed)
240
+ const sourceObservations: ObservationRecord[] = [];
241
+ const foundIds = new Set<string>();
242
+ const CHUNK_SIZE = 500;
243
+
244
+ for (let i = 0; i < leaseObsIds.length; i += CHUNK_SIZE) {
245
+ const chunk = leaseObsIds.slice(i, i + CHUNK_SIZE);
246
+ const placeholders = chunk.map(() => '?').join(',');
247
+ const rows = db
248
+ .prepare(`SELECT * FROM observations WHERE id IN (${placeholders})`)
249
+ .all(...chunk) as ObservationRecord[];
250
+ for (const r of rows) {
251
+ sourceObservations.push(r);
252
+ foundIds.add(r.id);
253
+ }
249
254
  }
250
- }
251
- }
252
255
 
253
- // 7. not_verbatim on error_verbatim
254
- if (errorVerbatim && typeof errorVerbatim === 'string' && errorVerbatim.trim() !== '') {
255
- const errorStr = errorVerbatim.trim();
256
- const appearsInLog = sourceObservations.some((obs) => {
257
- const inInput = obs.input ? obs.input.includes(errorStr) : false;
258
- const inOutput = obs.output ? obs.output.includes(errorStr) : false;
259
- return inInput || inOutput;
260
- });
261
-
262
- if (!appearsInLog) {
263
- return reject(
264
- 'not_verbatim',
265
- `error_verbatim string does not appear verbatim in any source observation input/output`
266
- );
267
- }
268
- }
256
+ const missingIds = leaseObsIds.filter((id) => !foundIds.has(id));
257
+ if (missingIds.length > 0) {
258
+ for (let i = 0; i < missingIds.length; i += CHUNK_SIZE) {
259
+ const chunk = missingIds.slice(i, i + CHUNK_SIZE);
260
+ const placeholders = chunk.map(() => '?').join(',');
261
+ const archivedRows = db
262
+ .prepare(`
263
+ SELECT original_observation_id AS id, scope, project_id, note_ref, task_ref,
264
+ session_id, agent, kind, tool_name, file_path, input, output,
265
+ duration_ms, failed, created_at, archived_at
266
+ FROM observations_archive
267
+ WHERE original_observation_id IN (${placeholders})
268
+ `)
269
+ .all(...chunk) as ObservationRecord[];
270
+ for (const r of archivedRows) {
271
+ sourceObservations.push(r);
272
+ }
273
+ }
274
+ }
269
275
 
270
- // 8. not_verbatim on files_touched
271
- if (Array.isArray(filesTouched) && filesTouched.length > 0) {
272
- // files_touched means a path that appeared as a tool call's TARGET file_path.
273
- // A path merely mentioned in command output does NOT count.
274
- const targetPaths = new Set<string>();
275
- for (const obs of sourceObservations) {
276
- if (obs.file_path && obs.file_path.trim() !== '') {
277
- targetPaths.add(obs.file_path.trim());
276
+ // 6. citation_unresolved
277
+ for (const claim of claims) {
278
+ if (!claim.source_ids || claim.source_ids.length === 0) {
279
+ return reject('citation_unresolved', `Claim '${claim.text}' has no source_ids citations`);
280
+ }
281
+ for (const srcId of claim.source_ids) {
282
+ if (!validObsIdSet.has(srcId)) {
283
+ return reject(
284
+ 'citation_unresolved',
285
+ `Citation id '${srcId}' in claim '${claim.text}' does not resolve to an observation in lease '${leaseId}'`
286
+ );
287
+ }
288
+ }
278
289
  }
279
- }
280
290
 
281
- for (const path of filesTouched) {
282
- const cleanPath = String(path).trim();
283
- if (!targetPaths.has(cleanPath)) {
284
- return reject(
285
- 'not_verbatim',
286
- `Path '${cleanPath}' in files_touched did not appear as a tool call target file_path`
287
- );
291
+ // 7. not_verbatim on error_verbatim
292
+ if (errorVerbatim && typeof errorVerbatim === 'string' && errorVerbatim.trim() !== '') {
293
+ const errorStr = errorVerbatim.trim();
294
+ const appearsInLog = sourceObservations.some((obs) => {
295
+ const inInput = obs.input ? obs.input.includes(errorStr) : false;
296
+ const inOutput = obs.output ? obs.output.includes(errorStr) : false;
297
+ return inInput || inOutput;
298
+ });
299
+
300
+ if (!appearsInLog) {
301
+ return reject(
302
+ 'not_verbatim',
303
+ `error_verbatim string does not appear verbatim in any source observation input/output`
304
+ );
305
+ }
288
306
  }
289
- }
290
- }
291
307
 
292
- // 9. Check quotes in claim texts
293
- for (const claim of claims) {
294
- const quotes = claim.text.match(/"([^"]+)"/g);
295
- if (quotes) {
296
- for (const q of quotes) {
297
- const quoteContent = q.slice(1, -1);
298
- if (quoteContent.length > 5) {
299
- const found = sourceObservations.some((obs) => {
300
- const inInput = obs.input ? obs.input.includes(quoteContent) : false;
301
- const inOutput = obs.output ? obs.output.includes(quoteContent) : false;
302
- const inFile = obs.file_path ? obs.file_path.includes(quoteContent) : false;
303
- return inInput || inOutput || inFile;
304
- });
305
- if (!found) {
308
+ // 8. not_verbatim on files_touched
309
+ if (Array.isArray(filesTouched) && filesTouched.length > 0) {
310
+ // files_touched means a path that appeared as a tool call's TARGET file_path.
311
+ // A path merely mentioned in command output does NOT count.
312
+ const targetPaths = new Set<string>();
313
+ for (const obs of sourceObservations) {
314
+ if (obs.file_path && obs.file_path.trim() !== '') {
315
+ targetPaths.add(obs.file_path.trim());
316
+ }
317
+ }
318
+
319
+ for (const path of filesTouched) {
320
+ const cleanPath = String(path).trim();
321
+ if (!targetPaths.has(cleanPath)) {
306
322
  return reject(
307
323
  'not_verbatim',
308
- `Quoted string '${quoteContent}' in claim does not appear in source observations`
324
+ `Path '${cleanPath}' in files_touched did not appear as a tool call target file_path`
309
325
  );
310
326
  }
311
327
  }
312
328
  }
313
- }
314
- }
315
329
 
316
- // PASSED: Compute outcome arithmetically
317
- const outcome = computeArithmeticOutcome(sourceObservations);
330
+ // 9. Check quotes in claim texts
331
+ for (const claim of claims) {
332
+ const quotes = claim.text.match(/"([^"]+)"/g);
333
+ if (quotes) {
334
+ for (const q of quotes) {
335
+ const quoteContent = q.slice(1, -1);
336
+ if (quoteContent.length > 5) {
337
+ const found = sourceObservations.some((obs) => {
338
+ const inInput = obs.input ? obs.input.includes(quoteContent) : false;
339
+ const inOutput = obs.output ? obs.output.includes(quoteContent) : false;
340
+ const inFile = obs.file_path ? obs.file_path.includes(quoteContent) : false;
341
+ return inInput || inOutput || inFile;
342
+ });
343
+ if (!found) {
344
+ return reject(
345
+ 'not_verbatim',
346
+ `Quoted string '${quoteContent}' in claim does not appear in source observations`
347
+ );
348
+ }
349
+ }
350
+ }
351
+ }
352
+ }
318
353
 
319
- const windowFrom =
320
- sourceObservations.length > 0
321
- ? Math.min(...sourceObservations.map((o) => o.created_at))
322
- : now;
323
- const windowTo =
324
- sourceObservations.length > 0
325
- ? Math.max(...sourceObservations.map((o) => o.created_at))
326
- : now;
354
+ // PASSED: Compute outcome arithmetically
355
+ const outcome = computeArithmeticOutcome(sourceObservations);
327
356
 
328
- const summaryId = `sum_${randomUUID().replace(/-/g, '').slice(0, 16)}`;
329
- const producerTier = submission.producer_tier || 'agent';
330
- const producerModel = submission.producer_model || null;
331
- const promptVersion = submission.prompt_version || 'extract-v1';
357
+ const windowFrom =
358
+ sourceObservations.length > 0
359
+ ? Math.min(...sourceObservations.map((o) => o.created_at))
360
+ : now;
361
+ const windowTo =
362
+ sourceObservations.length > 0
363
+ ? Math.max(...sourceObservations.map((o) => o.created_at))
364
+ : now;
365
+
366
+ const summaryId = `sum_${randomUUID().replace(/-/g, '').slice(0, 16)}`;
367
+ const producerTier = submission.producer_tier || 'agent';
368
+ const producerModel = submission.producer_model || null;
369
+ const promptVersion = submission.prompt_version || 'extract-v1';
332
370
 
333
- try {
334
- transaction(db, () => {
335
371
  db.prepare(`
336
372
  INSERT INTO summaries (
337
373
  id, scope, project_id, kind, window_from, window_to, outcome,
@@ -357,16 +393,17 @@ export function verifyAndStoreSummary(
357
393
  `);
358
394
 
359
395
  const sourceStmt = db.prepare(`
360
- INSERT INTO summary_sources (summary_id, claim_id, record_id, grain)
396
+ INSERT INTO summary_sources (summary_id, claim_id, record_id, record_type)
361
397
  VALUES (?, ?, ?, 'observation')
362
398
  `);
363
399
 
364
400
  for (let i = 0; i < claims.length; i++) {
365
401
  const claim = claims[i];
366
402
  const claimId = `clm_${randomUUID().replace(/-/g, '').slice(0, 16)}`;
367
- claimStmt.run(claimId, summaryId, claim.text.trim(), i);
403
+ claimStmt.run(claimId, summaryId, redactSecrets(claim.text.trim()), i);
368
404
 
369
- for (const srcId of claim.source_ids) {
405
+ const uniqueSourceIds = Array.from(new Set<string>(claim.source_ids));
406
+ for (const srcId of uniqueSourceIds) {
370
407
  sourceStmt.run(summaryId, claimId, srcId);
371
408
  }
372
409
  }
@@ -384,20 +421,20 @@ export function verifyAndStoreSummary(
384
421
 
385
422
  // Enqueue summary for embedding inside write transaction (Rule 2)
386
423
  enqueueForEmbedding(summaryId, 'summary');
387
- })();
388
424
 
389
- logger.info(
390
- { summaryId, outcome, claimsCount: claims.length, leaseId },
391
- 'summary successfully verified and stored'
392
- );
425
+ logger.info(
426
+ { summaryId, outcome, claimsCount: claims.length, leaseId },
427
+ 'summary successfully verified and stored'
428
+ );
393
429
 
394
- return {
395
- ok: true,
396
- status: 201,
397
- summary_id: summaryId,
398
- outcome,
399
- claims_count: claims.length,
400
- };
430
+ return {
431
+ ok: true,
432
+ status: 201,
433
+ summary_id: summaryId,
434
+ outcome,
435
+ claims_count: claims.length,
436
+ };
437
+ })();
401
438
  } catch (err) {
402
439
  logger.error(
403
440
  { leaseId, error: err instanceof Error ? err.message : String(err) },
@@ -71,6 +71,29 @@ export function releaseLease(leaseId: string): void {
71
71
  ).run(leaseId);
72
72
  }
73
73
 
74
+ /**
75
+ * Extends a rejected lease's expiration with exponential backoff based on prior
76
+ * uncompleted leases for the session, preventing a tight re-lease/dead-letter loop
77
+ * on deterministic gate rejections.
78
+ */
79
+ export function backoffLease(leaseId: string, sessionId: string): void {
80
+ const db = getDb();
81
+ const row = db
82
+ .prepare(
83
+ `SELECT COUNT(*) AS attempts
84
+ FROM consolidation_leases
85
+ WHERE session_id = ? AND completed_at IS NULL`
86
+ )
87
+ .get(sessionId) as { attempts: number } | undefined;
88
+ const attempts = Math.max(row?.attempts ?? 1, 1);
89
+ const backoffSec = Math.min(86400, 300 * Math.pow(2, Math.min(attempts - 1, 8)));
90
+ db.prepare(
91
+ `UPDATE consolidation_leases
92
+ SET expires_at = MAX(expires_at, unixepoch() + ?)
93
+ WHERE lease_id = ? AND completed_at IS NULL`
94
+ ).run(backoffSec, leaseId);
95
+ }
96
+
74
97
  export interface ConsolidationRunReport {
75
98
  status: 'ok' | 'disabled' | 'agent' | 'unavailable' | 'misconfigured';
76
99
  tier: GenerativeTier | null;
@@ -202,8 +225,9 @@ export async function runConsolidation(params?: {
202
225
  producer_tier: completion.producer_tier,
203
226
  producer_model: completion.producer_model,
204
227
  });
205
- // The lease goes back so a better producer can retry the same session.
206
- releaseLease(candidate.lease_id);
228
+ // Back off the lease instead of releasing it immediately so a deterministic
229
+ // gate rejection does not cause a tight re-lease/dead-letter loop.
230
+ backoffLease(candidate.lease_id, candidate.session_id);
207
231
  }
208
232
  }
209
233