dsh-memory-bond 0.3.0-beta.0 → 1.0.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 (145) hide show
  1. package/CHANGELOG.md +6 -7
  2. package/README.md +125 -91
  3. package/README.zh-CN.md +122 -92
  4. package/SECURITY.md +29 -0
  5. package/dist/audit.js +155 -80
  6. package/dist/automatic.js +10 -2
  7. package/dist/client.js +2035 -0
  8. package/dist/command-scope.js +4 -4
  9. package/dist/commands.js +15 -9
  10. package/dist/consolidation-store.js +87 -20
  11. package/dist/consolidation.js +2 -6
  12. package/dist/domain.js +8 -4
  13. package/dist/encoder.js +46 -5
  14. package/dist/file-import-store.js +120 -0
  15. package/dist/file-import.js +265 -0
  16. package/dist/foreground-attempts.js +91 -0
  17. package/dist/guidance.js +133 -92
  18. package/dist/host.js +13 -0
  19. package/dist/index-policy.js +91 -48
  20. package/dist/index.js +102 -40
  21. package/dist/knowledge-hooks.js +70 -27
  22. package/dist/knowledge.js +2 -3
  23. package/dist/maintenance-store.js +38 -4
  24. package/dist/maintenance.js +29 -5
  25. package/dist/personal.js +37 -0
  26. package/dist/policy.js +45 -47
  27. package/dist/prompt-copy.js +93 -0
  28. package/dist/proposal-receipts.js +70 -0
  29. package/dist/proposal-review.js +656 -0
  30. package/dist/propose-contract.js +32 -36
  31. package/dist/question-answers.js +86 -29
  32. package/dist/retrieval.js +25 -8
  33. package/dist/scope-narrowing.js +49 -0
  34. package/dist/search-index.js +93 -13
  35. package/dist/semantic.js +69 -207
  36. package/dist/service.js +633 -204
  37. package/dist/sharing.js +7 -13
  38. package/dist/sources.js +28 -3
  39. package/dist/store.js +432 -96
  40. package/dist/tool-experience.js +87 -0
  41. package/dist/turn-review-store.js +83 -16
  42. package/dist/turn-review.js +155 -59
  43. package/dist/ui.js +128 -26
  44. package/dist/vector-index.js +69 -33
  45. package/docs/architecture.zh-CN.md +52 -0
  46. package/docs/benchmark.zh-CN.md +60 -0
  47. package/docs/benchmarks/repository-tasks.json +5355 -0
  48. package/docs/images/bond-memory-principle-en.svg +644 -0
  49. package/docs/images/bond-memory-principle-zh.svg +644 -0
  50. package/docs/images/bond-memory-principle.drawio +644 -0
  51. package/docs/images/memory-settings-en.png +0 -0
  52. package/docs/images/memory-settings-zh.png +0 -0
  53. package/docs/images/memory-turn-recalled-en.png +0 -0
  54. package/docs/images/memory-turn-recalled-zh.png +0 -0
  55. package/docs/images/memory-turn-saved-en.png +0 -0
  56. package/docs/images/memory-turn-saved-zh.png +0 -0
  57. package/docs/media/memory-bond-name-en.gif +0 -0
  58. package/docs/media/memory-bond-name-en.mp4 +0 -0
  59. package/docs/media/memory-bond-name-zh.gif +0 -0
  60. package/docs/media/memory-bond-name-zh.mp4 +0 -0
  61. package/locale/detail.en.md +5 -1
  62. package/locale/detail.zh.md +5 -1
  63. package/locale/en.json +338 -0
  64. package/locale/zh.json +338 -0
  65. package/native/embeddings/NOTICE.md +2 -2
  66. package/package.json +39 -19
  67. package/scripts/benchmark-bond.mjs +72 -0
  68. package/scripts/benchmark-conditions.mjs +144 -0
  69. package/scripts/benchmark-example.mjs +37 -0
  70. package/scripts/benchmark-scale.mjs +119 -0
  71. package/scripts/benchmark-scenarios.mjs +57 -0
  72. package/scripts/benchmark-tasks.mjs +244 -0
  73. package/src/audit.ts +144 -85
  74. package/src/automatic.ts +12 -2
  75. package/src/command-scope.ts +4 -4
  76. package/src/commands.ts +12 -8
  77. package/src/consolidation-store.ts +80 -18
  78. package/src/consolidation.ts +2 -6
  79. package/src/domain.ts +9 -4
  80. package/src/encoder.ts +46 -6
  81. package/src/file-import-store.ts +139 -0
  82. package/src/file-import.ts +256 -0
  83. package/src/foreground-attempts.ts +97 -0
  84. package/src/guidance.ts +138 -102
  85. package/src/host.ts +22 -2
  86. package/src/index-policy.ts +93 -46
  87. package/src/index.ts +87 -43
  88. package/src/knowledge-hooks.ts +71 -29
  89. package/src/knowledge.ts +2 -3
  90. package/src/maintenance-store.ts +37 -4
  91. package/src/maintenance.ts +25 -5
  92. package/src/personal.ts +36 -0
  93. package/src/policy.ts +55 -52
  94. package/src/prompt-copy.ts +99 -0
  95. package/src/proposal-receipts.ts +59 -0
  96. package/src/proposal-review.ts +614 -0
  97. package/src/propose-contract.ts +31 -35
  98. package/src/question-answers.ts +99 -29
  99. package/src/retrieval.ts +26 -9
  100. package/src/scope-narrowing.ts +58 -0
  101. package/src/search-index.ts +94 -14
  102. package/src/semantic.ts +67 -188
  103. package/src/service.ts +595 -210
  104. package/src/sharing.ts +7 -14
  105. package/src/sources.ts +26 -4
  106. package/src/store.ts +434 -97
  107. package/src/tool-experience.ts +93 -0
  108. package/src/turn-review-store.ts +86 -15
  109. package/src/turn-review.ts +142 -60
  110. package/src/ui.ts +122 -27
  111. package/src/vector-index.ts +57 -29
  112. package/client/index.js +0 -1186
  113. package/design/dsh-memory-plugin-design.md +0 -46
  114. package/design/dsh-memory-plugin-evaluation.md +0 -135
  115. package/design/evaluations/locomo-conv-26-2026-12-03.json +0 -252
  116. package/design/evaluations/locomo-conv-26-paired-2026-12-03.json +0 -549
  117. package/design/evaluations/locomo-conv-26-write-replay-2026-12-03.json +0 -289
  118. package/design/evaluations/project-memory-tasks-2026-12-03.json +0 -1059
  119. package/design/memory-lifecycle-consolidation.excalidraw +0 -1212
  120. package/design/memory-lifecycle-consolidation.mobile.excalidraw +0 -1083
  121. package/design/memory-lifecycle-consolidation.mobile.svg +0 -2
  122. package/design/memory-lifecycle-consolidation.mobile.zh-CN.excalidraw +0 -1083
  123. package/design/memory-lifecycle-consolidation.mobile.zh-CN.svg +0 -94
  124. package/design/memory-lifecycle-consolidation.svg +0 -2
  125. package/design/memory-lifecycle-consolidation.zh-CN.excalidraw +0 -1212
  126. package/design/memory-lifecycle-consolidation.zh-CN.svg +0 -94
  127. package/design/memory-lifecycle.excalidraw +0 -2105
  128. package/design/memory-lifecycle.mobile.excalidraw +0 -1896
  129. package/design/memory-lifecycle.mobile.svg +0 -95
  130. package/design/memory-lifecycle.mobile.zh-CN.excalidraw +0 -1896
  131. package/design/memory-lifecycle.mobile.zh-CN.svg +0 -97
  132. package/design/memory-lifecycle.svg +0 -95
  133. package/design/memory-lifecycle.zh-CN.excalidraw +0 -2105
  134. package/design/memory-lifecycle.zh-CN.svg +0 -97
  135. package/native/embeddings/LICENSE +0 -21
  136. package/native/embeddings/en/model.onnx +0 -4
  137. package/native/embeddings/en/vocab.txt +0 -30522
  138. package/native/embeddings/runtime/LICENSE +0 -21
  139. package/native/embeddings/runtime/ThirdPartyNotices.txt +0 -6156
  140. package/native/embeddings/runtime/ort-wasm-simd-threaded.mjs +0 -70
  141. package/native/embeddings/runtime/ort-wasm-simd-threaded.wasm +0 -0
  142. package/native/embeddings/runtime/ort.wasm.min.mjs +0 -7
  143. package/native/embeddings/worker.mjs +0 -97
  144. package/native/embeddings/zh/model.onnx +0 -0
  145. package/native/embeddings/zh/vocab.txt +0 -21128
package/src/store.ts CHANGED
@@ -4,18 +4,27 @@ import { isAbsolute, join } from 'node:path'
4
4
  import { DatabaseSync } from 'node:sqlite'
5
5
  import { indexRevision, promptRole, SearchIndex } from './search-index.ts'
6
6
  import { EpisodeHistory, episodeBodyDays, episodeSchema } from './maintenance-episodes.ts'
7
- import { MaintenanceState, maintenanceSchema } from './maintenance-store.ts'
7
+ import { MaintenanceState, maintenanceSchema, sourceDetailPaths } from './maintenance-store.ts'
8
8
  import { ReviewLedger } from './turn-review-store.ts'
9
9
  import { ConsolidationStore } from './consolidation-store.ts'
10
- import { isMemorySlot, isSemanticSlot, normalizeLabel, type MemorySlot } from './personal.ts'
10
+ import { isMemorySlot, isPersonalSlot, isSemanticSlot, semanticSlot, type MemorySlot } from './personal.ts'
11
+
12
+ import { isImportScaffolding, type ImportFile } from './file-import.ts'
13
+ import { FileImportStore, fileImportSchema } from './file-import-store.ts'
14
+
15
+ import type { SubmittedOption } from './question-answers.ts'
11
16
 
12
17
  export interface Source {
18
+ formSelection?: SubmittedOption
19
+ fileImport?: ImportFile
20
+ scopeClarification?: { turnId: string; seq: number; start: number; end: number; previous: Ref }
13
21
  storeId: string
14
22
  sessionId: string
15
23
  turnId: string
16
24
  seq: number
17
25
  time?: number
18
- origin?: 'user' | 'manual'
26
+ origin?: 'user' | 'manual' | 'tool'
27
+ toolResult?: { callId: string; callSeq: number; resultSeq: number; command: string; workdir: string; exitCode: number }
19
28
  }
20
29
 
21
30
  export type MemoryUsage = 'proactive' | 'on_demand'
@@ -50,7 +59,7 @@ export interface Rule extends DraftItem, Ref {
50
59
  channel?: SaveChannel
51
60
  pinned: boolean
52
61
  source: Source
53
- quoteType: 'user_quote' | 'confirmed_wording' | 'receipt'
62
+ quoteType: 'user_quote' | 'confirmed_wording' | 'receipt' | 'tool_result'
54
63
  }
55
64
  export type ProposalState = 'pending' | 'confirmed' | 'rejected' | 'expired' | 'cancelled'
56
65
  export type ReviewChannel = 'owner_card' | 'user_command' | 'in_process'
@@ -100,6 +109,11 @@ export interface AuditMeta {
100
109
  outcome?: string | number
101
110
  retry?: number
102
111
  }
112
+ export interface RequestReceipt {
113
+ step: number
114
+ retry: number
115
+ entries: (Ref & { hint: boolean; body: boolean; cited: boolean; executed: boolean; topic?: string })[]
116
+ }
103
117
  export class StoreError extends Error {
104
118
  code: string
105
119
  constructor(code: string, message = code) {
@@ -112,7 +126,8 @@ const ttl = 14 * 24 * 60 * 60 * 1000
112
126
  const uid = (prefix: string) => prefix + '-' + randomUUID()
113
127
  // Retain governance receipts for replay protection and idempotent exports.
114
128
  const prunableAudit =
115
- "event IN ('delivery','cite','attempt','tool_result','bash_result','search','ticket_offer','ticket_read','guard_attempt','guard_block')"
129
+ "event IN ('delivery','request_hint','request_body','cite','attempt','tool_result','bash_result','search','ticket_offer','ticket_read','guard_attempt','guard_block')"
130
+ const requestEvents = "event IN ('request_hint','request_body','cite','bash_result')"
116
131
 
117
132
  // Stable key order makes a retry independent of the JSON encoder used by the client.
118
133
  function sorted(value: unknown): unknown {
@@ -130,9 +145,20 @@ const hash = (value: unknown) =>
130
145
  createHash('sha256')
131
146
  .update(JSON.stringify(sorted(value)))
132
147
  .digest('hex')
148
+ type SourcePosition = Pick<Source, 'storeId' | 'sessionId' | 'turnId' | 'seq'>
149
+ const narrowingKey = (ref: Ref, source: SourcePosition, clarification: string) =>
150
+ 'narrow:' + hash([ref.id, ref.rev, source.storeId, source.sessionId, source.turnId, source.seq, clarification])
133
151
  // Open topic labels may themselves reveal personal information. Source clocks survive a
134
152
  // content purge, so store a body-free topic key in both the primary and backup clock tables.
135
153
  const clockSlot = (slot: MemorySlot) => isSemanticSlot(slot) ? hash(['semantic-clock', slot]) : slot
154
+ // The source occurrence belongs to the submitted claim, even if a later semantic
155
+ // comparison selects a different target or extracts a different value from it.
156
+ export function inputClaimKey(source: Source, proposed: MemorySlot | undefined, item: DraftItem) {
157
+ const span = item.evidence
158
+ if (!proposed || !span) return
159
+ return 'input:' + hash(['claim', source.storeId, source.sessionId, span.seq, span.start, span.end,
160
+ proposed, item.kind ?? 'preference', item.when, item.exceptions, [...item.paths].sort()])
161
+ }
136
162
  function fields(item: DraftItem) {
137
163
  return [
138
164
  item.action,
@@ -183,6 +209,7 @@ function validateBatch(domain: string, session: string, source: Source, items: D
183
209
  items.forEach(validateItem)
184
210
  }
185
211
 
212
+ const schemaVersion = 4
186
213
  const schema = `
187
214
  CREATE TABLE memory_domains (
188
215
  domain TEXT PRIMARY KEY, epoch INTEGER NOT NULL DEFAULT 0
@@ -195,6 +222,7 @@ const schema = `
195
222
  answer TEXT, receipt TEXT, PRIMARY KEY(domain,id), UNIQUE(domain,session,idem)
196
223
  );
197
224
  CREATE INDEX proposals_inbox ON proposals(domain,session,created);
225
+ ${fileImportSchema}
198
226
  CREATE TABLE revisions (
199
227
  rid INTEGER PRIMARY KEY, proactive INTEGER,
200
228
  domain TEXT NOT NULL REFERENCES memory_domains(domain), id TEXT NOT NULL, rev INTEGER NOT NULL,
@@ -220,8 +248,10 @@ const schema = `
220
248
  );
221
249
  CREATE TABLE deliveries (
222
250
  domain TEXT NOT NULL, session TEXT NOT NULL, id TEXT NOT NULL, rev INTEGER NOT NULL,
251
+ last_delivered INTEGER NOT NULL, expanded INTEGER NOT NULL CHECK(expanded IN (0,1)),
223
252
  PRIMARY KEY(domain,session,id,rev), FOREIGN KEY(domain,id,rev) REFERENCES revisions(domain,id,rev)
224
253
  );
254
+ CREATE INDEX delivery_revision ON deliveries(domain,id,rev);
225
255
  CREATE TABLE audit (
226
256
  seq INTEGER PRIMARY KEY, domain TEXT NOT NULL REFERENCES memory_domains(domain), session TEXT NOT NULL,
227
257
  event TEXT NOT NULL, memory TEXT, rev INTEGER, meta TEXT NOT NULL, time INTEGER NOT NULL
@@ -238,10 +268,30 @@ const headQuery = `
238
268
  // Slot and fingerprint lookups have selective revision indexes; start there and check the live head.
239
269
  const selectedHead = `FROM revisions r CROSS JOIN heads h USING(domain,id,rev)
240
270
  WHERE r.domain=? AND r.state='confirmed'`
241
- const ruleColumns = 'h.domain,h.id,h.rev,h.pinned,r.family,r.confirmed,r.payload,e.type,e.quote,e.source'
271
+ const baseColumns = 'h.domain,h.id,h.rev,h.pinned,r.family,r.confirmed,r.payload'
272
+ const ruleColumns = baseColumns + ',e.type,e.quote,e.source'
273
+ const rankColumns = baseColumns + ",'receipt' AS type,'' AS quote,'{}' AS source"
274
+ const knowledgeField = (path: string) => `json_extract(payload,'$.knowledge.${path}')`
275
+ const commandFields = {
276
+ guard: ['match.command', 'match.workdir'],
277
+ runbook: ['steps.verify', 'steps.workdir'],
278
+ episode: ['failure.command', 'failure.workdir'],
279
+ trigger: ['trigger.command', 'trigger.workdir'],
280
+ } as const
281
+ const knowledgeTrigger = knowledgeField('trigger.text')
282
+ const triggerPrefix = `substr(${knowledgeTrigger},1,2)`
283
+ const currentTextTrigger = `state='confirmed' AND ${knowledgeTrigger} IS NOT NULL`
284
+ // Sparse expression indexes stay in sync with edits, withdrawals, imports and restores.
285
+ const knowledgeHookIndexes = Object.entries(commandFields).map(([key, [command, cwd]]) =>
286
+ `CREATE INDEX IF NOT EXISTS knowledge_${key}_command ON revisions(domain,${knowledgeField(command)},${knowledgeField(cwd)})
287
+ WHERE state='confirmed' AND ${knowledgeField(command)} IS NOT NULL;`).join('\n') +
288
+ `CREATE INDEX IF NOT EXISTS knowledge_text_trigger ON revisions(domain,${triggerPrefix},${knowledgeTrigger})
289
+ WHERE ${currentTextTrigger}`
290
+ const knowledgeCandidateRows = `SELECT ${ruleColumns} FROM revisions r
291
+ CROSS JOIN heads h USING(domain,id,rev) CROSS JOIN evidence e USING(domain,id,rev)`
242
292
  type Row = Record<string, unknown>
243
293
  const parse = (v: unknown) => JSON.parse(String(v))
244
- function storedVector(row: Row) {
294
+ export function storedVector(row: Row) {
245
295
  const dimensions = Number(row.dimensions)
246
296
  if (!(row.vector instanceof Uint8Array) || dimensions < 1 || dimensions > 8192 ||
247
297
  row.vector.byteLength !== dimensions * 4) return
@@ -296,6 +346,13 @@ function proposalFrom(row: Row): Proposal {
296
346
  }
297
347
  }
298
348
 
349
+ // Older imports may already have staged index entries and explanatory paragraphs.
350
+ // Omit them from the inbox without modifying an import batch or its review history.
351
+ function visibleProposal(p: Proposal): boolean {
352
+ const file = p.source.fileImport
353
+ return !file || p.state !== 'pending' || p.items.some(item => !isImportScaffolding(item.action, item.when, file.path))
354
+ }
355
+
299
356
  export class MemoryStore {
300
357
  onHeadsChanged?: (domain: string) => void
301
358
  onMemoryDisabled?: () => void
@@ -307,6 +364,7 @@ export class MemoryStore {
307
364
  private db: DatabaseSync
308
365
  readonly directory: string
309
366
  private readonly searchIndex: SearchIndex
367
+ readonly fileImports: FileImportStore
310
368
  readonly turnReviews: ReviewLedger
311
369
  readonly consolidation: ConsolidationStore
312
370
  readonly maintenance: MaintenanceState
@@ -341,7 +399,7 @@ export class MemoryStore {
341
399
  this.db.exec('PRAGMA busy_timeout=3000; PRAGMA foreign_keys=ON; PRAGMA secure_delete=ON; PRAGMA journal_mode=WAL; PRAGMA synchronous=FULL')
342
400
  this.tx(() => {
343
401
  const version = Number(this.db.prepare('PRAGMA user_version').get()?.user_version)
344
- if (version !== 1) {
402
+ if (version !== schemaVersion) {
345
403
  if (version !== 0 || this.db.prepare("SELECT 1 FROM sqlite_master WHERE type='table'").get())
346
404
  throw new StoreError('unsupported_schema')
347
405
  this.db.exec(schema)
@@ -361,12 +419,39 @@ export class MemoryStore {
361
419
  changed_at INTEGER NOT NULL
362
420
  );
363
421
  INSERT INTO memory_settings VALUES(0,1,0);
364
- ${maintenanceSchema}; ${episodeSchema}; PRAGMA user_version=1`)
422
+ ${maintenanceSchema}; ${episodeSchema}; PRAGMA user_version=${schemaVersion}`)
365
423
  this.searchIndex.create()
366
424
  }
425
+ this.db.exec(`DROP TRIGGER IF EXISTS release_proposal_evidence;
426
+ CREATE TRIGGER IF NOT EXISTS release_settled_evidence AFTER UPDATE OF state ON proposals
427
+ WHEN NEW.state<>'pending' AND NEW.source<>json_remove(NEW.source,${sourceDetailPaths}) BEGIN
428
+ UPDATE proposals SET source=json_remove(NEW.source,${sourceDetailPaths}) WHERE domain=NEW.domain AND id=NEW.id;
429
+ END;
430
+ CREATE INDEX IF NOT EXISTS proposal_turn ON proposals(domain,session,turn);
431
+ CREATE INDEX IF NOT EXISTS revision_batch ON revisions(domain,batch);
432
+ CREATE INDEX IF NOT EXISTS revision_domain_retirement ON revisions(domain,retired) WHERE retired IS NOT NULL;
433
+ CREATE INDEX IF NOT EXISTS proposal_domain_expiry ON proposals(domain,created) WHERE state='pending';
434
+ CREATE INDEX IF NOT EXISTS proposal_review_source ON proposals(domain,json_extract(source,'$.storeId'),
435
+ json_extract(source,'$.sessionId')) WHERE id NOT GLOB 'auto-*';
436
+ CREATE INDEX IF NOT EXISTS evidence_session ON evidence(domain,json_extract(source,'$.sessionId'));
437
+ CREATE INDEX IF NOT EXISTS audit_request ON audit(
438
+ domain,session,json_extract(meta,'$.store'),json_extract(meta,'$.turn'),json_extract(meta,'$.step')
439
+ ) WHERE ${requestEvents}`)
440
+ this.db.exec(knowledgeHookIndexes)
367
441
  this.maintenance.reconcileConsent(version === 0)
442
+ this.searchIndex.ensureTopicLabels()
368
443
  this.searchIndex.syncVectorFormat()
369
444
  })
445
+ this.fileImports = new FileImportStore(this.db, {
446
+ expire: domain => this.expire(domain),
447
+ tx: fn => this.tx(fn),
448
+ list: domain => this.list(domain),
449
+ create: (domain, session, source, item, idem) => {
450
+ validateBatch(domain, session, source, [item])
451
+ return this.createBatch(domain, session, source, [item], source.turnId, idem, 'p')
452
+ },
453
+ revoke: (domain, id, rev, session) => this.revokeCurrent(domain, id, rev, session),
454
+ })
370
455
  this.turnReviews = new ReviewLedger(this.db)
371
456
  this.consolidation = new ConsolidationStore(this.db, {
372
457
  transaction: fn => this.tx(fn),
@@ -510,10 +595,13 @@ export class MemoryStore {
510
595
  const due = "state IN ('superseded','revoked') AND retired IS NOT NULL AND retired<=?" + scope
511
596
  const pending = "state='pending' AND created<=?" + scope
512
597
  const auditDue = 'time<=? AND ' + prunableAudit + scope
513
- // Ordinary reads need no writer lock when no indexed deadline has elapsed.
598
+ // The usual case has no expired rows. Seek the deadline itself, even when a fresh
599
+ // database's planner has no statistics for the other domain-leading indexes.
600
+ const revisions = 'revisions INDEXED BY ' + (domain === undefined ? 'revision_retirement' : 'revision_domain_retirement')
601
+ const proposals = 'proposals INDEXED BY ' + (domain === undefined ? 'proposal_expiry' : 'proposal_domain_expiry')
514
602
  if (
515
- !this.db.prepare('SELECT 1 FROM revisions WHERE ' + due + ' LIMIT 1').get(cutoff, ...key) &&
516
- !this.db.prepare('SELECT 1 FROM proposals WHERE ' + pending + ' LIMIT 1').get(now - ttl, ...key) &&
603
+ !this.db.prepare(`SELECT 1 FROM ${revisions} WHERE ${due} LIMIT 1`).get(cutoff, ...key) &&
604
+ !this.db.prepare(`SELECT 1 FROM ${proposals} WHERE ${pending} LIMIT 1`).get(now - ttl, ...key) &&
517
605
  !this.db.prepare('SELECT 1 FROM audit WHERE ' + auditDue + ' LIMIT 1').get(cutoff, ...key)
518
606
  )
519
607
  return
@@ -524,7 +612,7 @@ export class MemoryStore {
524
612
  this.db
525
613
  .prepare(
526
614
  `UPDATE evidence SET quote='',type='receipt',source='{}' WHERE (domain,id,rev) IN
527
- (SELECT domain,id,rev FROM revisions WHERE ${due})`,
615
+ (SELECT domain,id,rev FROM ${revisions} WHERE ${due})`,
528
616
  )
529
617
  .run(cutoff, ...key)
530
618
  // A retired revision's own provenance row is redundant by this point: retire() (called when
@@ -534,17 +622,17 @@ export class MemoryStore {
534
622
  this.db
535
623
  .prepare(
536
624
  `DELETE FROM automatic_sources WHERE (domain,id,rev) IN
537
- (SELECT domain,id,rev FROM revisions WHERE ${due})`,
625
+ (SELECT domain,id,rev FROM ${revisions} WHERE ${due})`,
538
626
  )
539
627
  .run(cutoff, ...key)
540
628
  this.db
541
629
  .prepare(
542
- `UPDATE revisions SET action='',condition='',paths='[]',slot=NULL,payload='{}',proactive=NULL,
630
+ `UPDATE ${revisions} SET action='',condition='',paths='[]',slot=NULL,payload='{}',proactive=NULL,
543
631
  fingerprint='',retired=NULL WHERE ${due}`,
544
632
  )
545
633
  .run(cutoff, ...key)
546
634
  this.db
547
- .prepare("UPDATE proposals SET state='expired',items='[]' WHERE " + pending)
635
+ .prepare(`UPDATE ${proposals} SET state='expired',items='[]' WHERE ${pending}`)
548
636
  .run(now - ttl, ...key)
549
637
  this.db.prepare('DELETE FROM audit WHERE ' + auditDue).run(cutoff, ...key)
550
638
  }
@@ -558,8 +646,8 @@ export class MemoryStore {
558
646
  this.db.prepare('UPDATE memory_domains SET epoch=epoch+1 WHERE domain=?').run(domain)
559
647
  if (this.onHeadsChanged) this.changedDomains.add(domain)
560
648
  }
561
- /** The version that `rev` replaced, while its content is retained. A withdrawn version is not offered back. */
562
- previous(domain: string, id: string, rev: number, accept?: (version: Rule) => boolean): Rule | undefined {
649
+ /** Follow the retained predecessor chain, stopping at withdrawal, erasure or expiry. */
650
+ *previousVersions(domain: string, id: string, rev: number): IterableIterator<Rule> {
563
651
  const predecessor = this.db.prepare(
564
652
  `SELECT p.domain,p.id,p.rev,0 AS pinned,p.family,p.confirmed,p.payload,e.type,e.quote,e.source
565
653
  FROM revisions r JOIN revisions p ON p.domain=r.domain AND p.id=r.id AND p.rev=r.previous
@@ -572,10 +660,14 @@ export class MemoryStore {
572
660
  const row = predecessor.get(domain, id, rev, cutoff)
573
661
  if (!row) return
574
662
  const version = rule(row)
575
- if (!accept || accept(version)) return version
663
+ yield version
576
664
  rev = version.rev
577
665
  }
578
666
  }
667
+ previous(domain: string, id: string, rev: number, accept?: (version: Rule) => boolean): Rule | undefined {
668
+ for (const version of this.previousVersions(domain, id, rev))
669
+ if (!accept || accept(version)) return version
670
+ }
579
671
  list(domain: string): Rule[] {
580
672
  this.expireEpisodes(domain)
581
673
  return this.db
@@ -586,26 +678,92 @@ export class MemoryStore {
586
678
  hasCurrent(domain: string): boolean {
587
679
  return Boolean(this.db.prepare('SELECT 1 ' + headQuery + ' LIMIT 1').get(domain))
588
680
  }
681
+ // Exact duplicate and conflict checks compare rule fields and do not need the source quotation.
682
+ comparisonHeads(domain: string, field: 'action' | 'condition' | 'slot', value: string): Rule[] {
683
+ this.expireEpisodes(domain)
684
+ return this.db.prepare(`SELECT ${rankColumns} ${selectedHead} AND r.${field}=?`).all(domain, value).map(rule)
685
+ }
686
+ commandCandidates(domain: string, command: string, workdir: string, phase: 'attempt' | 'guard' | 'failure'): Rule[] {
687
+ this.expireEpisodes(domain)
688
+ const keys: (keyof typeof commandFields)[] = phase === 'attempt' ? ['guard']
689
+ : phase === 'guard' ? ['guard', 'runbook', 'episode'] : ['trigger']
690
+ const matches = keys.map(key => {
691
+ const [cmd, cwd] = commandFields[key]
692
+ return `SELECT rid FROM revisions INDEXED BY knowledge_${key}_command
693
+ WHERE domain=? AND state='confirmed' AND ${knowledgeField(cmd)}=? AND ${knowledgeField(cwd)}=?`
694
+ }).join(' UNION ALL ')
695
+ return this.db.prepare(`${knowledgeCandidateRows} WHERE r.rid IN (${matches}) ORDER BY r.confirmed DESC,h.id`)
696
+ .all(...keys.flatMap(() => [domain, command, workdir])).map(rule)
697
+ }
698
+ messageCandidates(domain: string, messages: string[]): Rule[] {
699
+ this.expireEpisodes(domain)
700
+ const triggers = `FROM revisions INDEXED BY knowledge_text_trigger WHERE domain=? AND ${currentTextTrigger}`
701
+ if (!messages.length || !this.db.prepare(`SELECT 1 ${triggers} LIMIT 1`).get(domain)) return []
702
+ // Match literal substrings within one message. Typical prompts probe the index by the
703
+ // first two code points. For large pasted inputs, scan only this domain's trigger keys.
704
+ const args = [domain]
705
+ let prefixFilter = ''
706
+ if (messages.reduce((length, text) => length + text.length, 0) <= 8192) {
707
+ const prefixes = new Set<string>()
708
+ for (const message of messages) {
709
+ let previous = ''
710
+ for (const character of message) {
711
+ prefixes.add(character)
712
+ if (previous) prefixes.add(previous + character)
713
+ previous = character
714
+ }
715
+ }
716
+ prefixFilter = `AND ${triggerPrefix} IN (SELECT value FROM json_each(?))`
717
+ args.push(JSON.stringify([...prefixes]))
718
+ }
719
+ args.push(JSON.stringify(messages))
720
+ const matches = `SELECT rid ${triggers} ${prefixFilter} AND EXISTS (
721
+ SELECT 1 FROM json_each(?) msg WHERE instr(msg.value,${knowledgeTrigger})>0)`
722
+ return this.db.prepare(`${knowledgeCandidateRows} WHERE r.rid IN (${matches}) ORDER BY r.confirmed DESC,h.id`)
723
+ .all(...args).map(rule)
724
+ }
589
725
  read(domain: string, id: string, rev?: number): Rule | undefined {
590
726
  this.expireEpisodes(domain)
591
727
  const row = this.db.prepare('SELECT ' + ruleColumns + headQuery + ' AND h.id=?').get(domain, id)
592
728
  return row && (rev === undefined || rev === row.rev) ? rule(row) : undefined
593
729
  }
730
+ replayedReplacement(domain: string, ref: Ref, source: Source, item: DraftItem): Ref | undefined {
731
+ const head = this.read(domain, ref.id, ref.rev + 1)
732
+ if (!head || head.channel !== 'automatic' || head.quoteType !== 'user_quote' ||
733
+ head.source.turnId !== source.turnId || !head.evidence || !item.evidence ||
734
+ quoteKey(head.source, head.evidence, head.user_quote) !== quoteKey(source, item.evidence, item.user_quote) ||
735
+ head.user_quote !== item.user_quote || head.action !== item.action || head.when !== item.when ||
736
+ head.exceptions !== item.exceptions || JSON.stringify(head.paths) !== JSON.stringify(item.paths) ||
737
+ head.kind !== item.kind || head.slot !== item.slot || Boolean(head.sensitive) !== Boolean(item.sensitive) ||
738
+ (head.usage ?? 'on_demand') !== (item.usage ?? 'on_demand')) return
739
+ return { id: head.id, rev: head.rev }
740
+ }
594
741
  readMany(domain: string, refs: readonly { id: string; rev?: number }[]): Rule[] {
595
742
  if (!refs.length) return []
596
743
  if (refs.length === 1) {
597
744
  const head = this.read(domain, refs[0].id, refs[0].rev)
598
745
  return head ? [head] : []
599
746
  }
747
+ return this.rowsByRef(domain, refs, true)
748
+ }
749
+ // Only applicability and ranking fields are needed in the first pass. Retained quotes
750
+ // and provenance stay on disk until the caller rechecks a winning revision.
751
+ searchHeads(domain: string, refs?: readonly { id: string; rev?: number }[], topicsOnly = false): Rule[] {
752
+ if (refs) return refs.length ? this.rowsByRef(domain, refs, false, topicsOnly) : []
753
+ this.expireEpisodes(domain)
754
+ return this.db.prepare(`SELECT ${rankColumns} FROM heads h CROSS JOIN revisions r USING(domain,id,rev)
755
+ WHERE h.domain=? AND r.state='confirmed' ORDER BY r.confirmed DESC,h.id`).all(domain).map(rule)
756
+ }
757
+ private rowsByRef(domain: string, refs: readonly { id: string; rev?: number }[], evidence: boolean, topicsOnly = false) {
600
758
  this.expireEpisodes(domain)
601
759
  // Drive indexed head lookups from the hit list, including when a broad term matches
602
760
  // hundreds of records in a much larger domain. json_each uses one bind parameter.
603
- return this.db.prepare(`SELECT ${ruleColumns} FROM json_each(?) wanted
761
+ return this.db.prepare(`SELECT ${evidence ? ruleColumns : rankColumns} FROM json_each(?) wanted
604
762
  CROSS JOIN heads h ON h.domain=? AND h.id=json_extract(wanted.value,'$.id')
605
763
  CROSS JOIN revisions r ON r.domain=h.domain AND r.id=h.id AND r.rev=h.rev
606
- CROSS JOIN evidence e ON e.domain=h.domain AND e.id=h.id AND e.rev=h.rev
607
- WHERE r.state='confirmed' AND (json_type(wanted.value,'$.rev') IS NULL
608
- OR h.rev=json_extract(wanted.value,'$.rev'))`)
764
+ ${evidence ? 'CROSS JOIN evidence e ON e.domain=h.domain AND e.id=h.id AND e.rev=h.rev' : ''}
765
+ WHERE r.state='confirmed' AND (json_type(wanted.value,'$.rev') IS NULL OR h.rev=json_extract(wanted.value,'$.rev'))
766
+ ${topicsOnly ? "AND json_type(r.payload,'$.semanticTopic')='text'" : ''}`)
609
767
  .all(JSON.stringify(refs), domain).map(rule)
610
768
  }
611
769
  private getProposalRow(domain: string, session: string, id: string) {
@@ -623,7 +781,7 @@ export class MemoryStore {
623
781
  return this.db
624
782
  .prepare("SELECT * FROM proposals WHERE domain=? AND session=? AND state='pending' ORDER BY created,id")
625
783
  .all(domain, session)
626
- .map(proposalFrom)
784
+ .map(proposalFrom).filter(visibleProposal)
627
785
  }
628
786
  // turn cards are recovered by session + turn even if the user already answered the card.
629
787
  turn(domain: string, session: string, turnId: string): Proposal[] {
@@ -633,7 +791,7 @@ export class MemoryStore {
633
791
  "SELECT * FROM proposals WHERE domain=? AND session=? AND turn=? AND id NOT GLOB 'auto-*' ORDER BY created,id",
634
792
  )
635
793
  .all(domain, session, turnId)
636
- .map(proposalFrom)
794
+ .map(proposalFrom).filter(visibleProposal)
637
795
  }
638
796
  propose(
639
797
  domain: string,
@@ -646,7 +804,8 @@ export class MemoryStore {
646
804
  // A batch can cite multiple genuine user messages. The representative seq on the envelope
647
805
  // changes when the model reorders such rows, so bind each row to its own source instead.
648
806
  const { seq, ...batchSource } = source
649
- const idem = hash([batchSource, items.map((item) => hash([item, item.evidence?.seq ?? seq])).sort()])
807
+ const idem = source.origin === 'tool' ? hash(['bash', source.storeId, source.sessionId, seq])
808
+ : hash([batchSource, items.map((item) => hash([item, item.evidence?.seq ?? seq])).sort()])
650
809
  return this.tx(() => {
651
810
  this.expire(domain)
652
811
  const existing = this.db
@@ -765,21 +924,29 @@ export class MemoryStore {
765
924
  const proposed = proposedSlots?.[index]
766
925
  const meaning = (proposed ? 'input:' : '') + hash([stream, seq, 'content', proposed ?? slot,
767
926
  item.action, item.when, item.exceptions, [...item.paths].sort()])
768
- if (proposed && this.maintenance.retiredInput(domain, meaning)) continue
769
- const already = sourceKeys.get(occurrence)
770
- if (already && already.print !== print) throw new StoreError('ambiguous_source')
927
+ const claim = inputClaimKey(source, proposed, item)
928
+ const keys = claim ? [occurrence, meaning, claim] : [occurrence, meaning]
929
+ if (proposed && (this.maintenance.retiredInput(domain, meaning) ||
930
+ (claim && this.maintenance.retiredInput(domain, claim)))) continue
931
+ if (keys.some(key => sourceKeys.has(key) && sourceKeys.get(key)!.print !== print))
932
+ throw new StoreError('ambiguous_source')
771
933
  const seen = this.db
772
- .prepare('SELECT DISTINCT id,rev FROM automatic_sources WHERE domain=? AND occurrence IN (?,?)')
773
- .all(domain, occurrence, meaning)
934
+ .prepare('SELECT DISTINCT id,rev FROM automatic_sources WHERE domain=? AND occurrence IN (?,?,?)')
935
+ .all(domain, occurrence, meaning, claim ?? null)
774
936
  // Each item in the batch is independent: a stale or blocked sibling must only drop itself,
775
937
  // never the other, unrelated items already resolved (or still to be resolved) in this call.
776
938
  if (seen.length > 1) continue
777
939
  if (seen.length) {
778
940
  const ref = { id: String(seen[0].id), rev: Number(seen[0].rev) }
779
941
  const live = this.read(domain, ref.id, ref.rev)
780
- if (!live) continue
781
- if (proposed && slot && live.slot === slot && hash(fields(live)) === fingerprint)
782
- sourceKeys.set(meaning, { stream, seq, time, slot: clockSlot(slot), print })
942
+ // The occurrence identifies an event and slot, even if a subsequent extraction
943
+ // disagrees about its value. Only the committed content can reuse its receipt.
944
+ if (!live || hash(fields(live)) !== fingerprint) continue
945
+ if (proposed && slot) {
946
+ const bound = { stream, seq, time, slot: clockSlot(slot), print }
947
+ sourceKeys.set(meaning, bound)
948
+ if (claim) sourceKeys.set(claim, bound)
949
+ }
783
950
  refs.set(print, ref)
784
951
  if (item.evidence) duplicateSpans.push(item.evidence)
785
952
  continue
@@ -825,8 +992,7 @@ export class MemoryStore {
825
992
  continue
826
993
  }
827
994
  const observedKey = { stream, seq, time, slot: clock, print }
828
- sourceKeys.set(occurrence, observedKey)
829
- sourceKeys.set(meaning, observedKey)
995
+ for (const key of keys) sourceKeys.set(key, observedKey)
830
996
  const repeated = this.duplicate(domain, fingerprint)
831
997
  if (repeated && (!slot || currentSlot?.id === repeated.id)) {
832
998
  refs.set(print, { id: String(repeated.id), rev: Number(repeated.rev) })
@@ -866,7 +1032,7 @@ export class MemoryStore {
866
1032
  writes.forEach((print, index) => refs.set(print, answer.entries[index]))
867
1033
  }
868
1034
  if (!refs.size) return stale
869
- this.turnReviews.noteDuplicates(domain, source, duplicateSpans)
1035
+ this.turnReviews.noteHandled(domain, source, duplicateSpans)
870
1036
  const record = this.db.prepare(
871
1037
  'INSERT INTO automatic_sources(domain,occurrence,stream,seq,time,slot,id,rev) VALUES(?,?,?,?,?,?,?,?) ON CONFLICT(domain,occurrence) DO NOTHING',
872
1038
  )
@@ -880,6 +1046,71 @@ export class MemoryStore {
880
1046
  }
881
1047
  })
882
1048
  }
1049
+ narrowedProjectRef(project: string, ref: Ref, source: SourcePosition, clarification: string): Ref | undefined {
1050
+ // Keep retries bound to the actual destination write. A restore, later revision, withdrawal or
1051
+ // deletion of its source no longer attests this operation.
1052
+ const row = this.db.prepare(`SELECT r.id,r.rev FROM proposals p JOIN revisions r ON r.domain=p.domain AND r.batch=p.id
1053
+ JOIN heads h ON h.domain=r.domain AND h.id=r.id AND h.rev=r.rev JOIN evidence e ON e.domain=r.domain AND e.id=r.id AND e.rev=r.rev
1054
+ WHERE p.domain=? AND p.session=? AND p.idem=? AND p.state='confirmed' AND r.state='confirmed' AND e.type='user_quote'`)
1055
+ .get(project, source.sessionId, narrowingKey(ref, source, clarification))
1056
+ return row && { id: String(row.id), rev: Number(row.rev) }
1057
+ }
1058
+ soleTurnAgreement(domains: string[], source: Source, ref: Ref): boolean {
1059
+ if (!domains.length) return false
1060
+ const rows = this.db.prepare(`SELECT DISTINCT r.id FROM proposals p JOIN revisions r ON r.domain=p.domain AND r.batch=p.id
1061
+ WHERE p.domain IN (${domains.map(() => '?').join(',')}) AND p.session=? AND p.turn=? AND json_extract(p.source,'$.storeId')=?
1062
+ AND p.state='confirmed' AND coalesce(json_extract(r.payload,'$.kind'),'preference') IN ('preference','rule') LIMIT 2`)
1063
+ .all(...domains, source.sessionId, source.turnId, source.storeId)
1064
+ return rows.length === 1 && rows[0].id === ref.id
1065
+ }
1066
+ narrowToProject(project: string, ref: Ref, source: Source, clarification: string,
1067
+ span: NonNullable<DraftItem['evidence']>, generation: number, epochs: ReadonlyMap<string, number>,
1068
+ projectConditions: (old: Rule) => Pick<DraftItem, 'guidance' | 'hard'>) {
1069
+ const profile = 'profile:personal'
1070
+ return this.tx(() => {
1071
+ if (!project || project === profile || source.origin !== 'user' || source.seq !== span.seq ||
1072
+ !Number.isSafeInteger(span.start) || span.start < 0 || span.end - span.start !== clarification.length || !clarification.trim())
1073
+ throw new StoreError('invalid_source')
1074
+ if (generation === undefined || this.enabledGeneration() !== generation) throw new StoreError('memory_disabled')
1075
+ const replay = this.narrowedProjectRef(project, ref, source, clarification)
1076
+ if (replay) return { status: 'duplicate' as const, entries: [replay] }
1077
+ if ([profile, project].some(domain => this.epoch(domain) !== epochs.get(domain)))
1078
+ throw new StoreError('conflict')
1079
+ const old = this.read(profile, ref.id, ref.rev)
1080
+ if (!old || !isPersonalSlot(old.slot) || !old.semanticTopic || !['rule', 'preference'].includes(old.kind ?? '') || old.channel !== 'automatic' ||
1081
+ old.quoteType !== 'user_quote' || !old.user_quote || !old.evidence || old.sensitive || old.pinned ||
1082
+ old.usageOverride || old.localException || old.paths.length || old.source.origin !== 'user')
1083
+ throw new StoreError('protected_revision')
1084
+ if (old.source.storeId !== source.storeId || old.source.sessionId !== source.sessionId ||
1085
+ old.evidence.seq >= source.seq || old.source.turnId === source.turnId)
1086
+ throw new StoreError('invalid_source')
1087
+ const slot = semanticSlot('project', old.semanticTopic, old.subject, old)
1088
+ if (!slot || this.currentSlot(project, slot) ||
1089
+ this.canonicalTopicHeads(project, 'project', old.semanticTopic, old.subject).length)
1090
+ throw new StoreError('conflict')
1091
+ const item = { ...revisionDraft(old), ...projectConditions(old), slot, source: {
1092
+ ...old.source, scopeClarification: { ...span, turnId: source.turnId, previous: ref },
1093
+ } }
1094
+ const stream = hash([source.storeId, source.sessionId])
1095
+ if (this.maintenance.blockedHistory(project, old.source, item) ||
1096
+ this.newerSlotObservation(project, clockSlot(slot), stream, source.seq, source.time ?? null))
1097
+ throw new StoreError('conflict')
1098
+ validateBatch(project, source.sessionId, source, [item])
1099
+ const idem = narrowingKey(ref, source, clarification)
1100
+ const proposal = this.createBatch(project, source.sessionId, source, [item], source.turnId, idem, 'auto')
1101
+ const { entries } = this.finishBatch(project, source.sessionId, proposal.id, proposal.revision, proposal.digest,
1102
+ [{ index: 0 }], { channel: 'automatic', decision: idem })
1103
+ const target = entries[0]
1104
+ this.db.prepare('INSERT INTO automatic_sources VALUES(?,?,?,?,?,?,?,?)')
1105
+ .run(project, idem, stream, source.seq, source.time ?? null,
1106
+ clockSlot(slot), target.id, target.rev)
1107
+ this.turnReviews.noteHandled(project, source, [span])
1108
+ this.revokeCurrent(profile, old.id, old.rev, source.sessionId)
1109
+ this.maintenance.releaseTransferredRevision(profile, old.id, old.rev)
1110
+ this.audit(project, source.sessionId, 'narrow_scope', { ...target, turn: source.turnId, seq: source.seq, store: source.storeId })
1111
+ return { status: 'saved' as const, entries }
1112
+ })
1113
+ }
883
1114
  commitManual(
884
1115
  domain: string,
885
1116
  session: string,
@@ -910,7 +1141,7 @@ export class MemoryStore {
910
1141
  const old = this.read(domain, ref.id, ref.rev)
911
1142
  if (!old) throw new StoreError('conflict')
912
1143
  if (old.sensitive && usage === 'proactive') throw new StoreError('sensitive_on_demand')
913
- if (old.usage === usage && old.usageOverride) return ref
1144
+ if ((old.usage ?? 'on_demand') === usage && (old.usageOverride || old.kind === 'fact')) return ref
914
1145
  const item: DraftItem = { ...revisionDraft(old), usage, usageOverride: true }
915
1146
  const decision = 'usage:' + old.id + '@' + old.rev + ':' + usage
916
1147
  const batch = this.createBatch(domain, session, old.source, [item], old.source.turnId || '0', decision, 'auto')
@@ -942,10 +1173,23 @@ export class MemoryStore {
942
1173
  return this.promptHeads(domain, false)
943
1174
  }
944
1175
 
945
- nextVectorJob() {
1176
+ onDemandCandidates(domain: string, terms: string[]): Rule[] {
1177
+ if (!terms.length) return []
1178
+ const expression = 'labels:(' + terms.map(word => Buffer.from(word).toString('hex')).join(' OR ') + ')'
1179
+ const rows = this.db.prepare(`SELECT h.domain,h.id,h.rev,h.pinned,r.family,r.confirmed,r.payload,
1180
+ 'receipt' AS type,'' AS quote,'{}' AS source FROM memory_fts
1181
+ CROSS JOIN revisions r ON r.rid=memory_fts.rowid CROSS JOIN heads h USING(domain,id,rev)
1182
+ WHERE memory_fts MATCH ? AND r.domain=? AND r.state='confirmed' AND r.proactive=0
1183
+ AND json_extract(r.payload,'$.sensitive') IS NOT 1 AND json_extract(r.payload,'$.semanticTopic') IS NOT NULL
1184
+ ORDER BY bm25(memory_fts,0,0,1),r.rid LIMIT 32`).all(expression, domain)
1185
+ return rows.map(rule)
1186
+ }
1187
+
1188
+ nextVectorJob(language?: 'en' | 'zh') {
1189
+ const eligible = language ? 'AND j.language=?' : ''
946
1190
  const row = this.db.prepare(`SELECT j.rid,r.domain,r.id,r.rev FROM memory_vector_jobs j
947
- CROSS JOIN revisions r ON r.rid=j.rid WHERE j.available<=?
948
- ORDER BY j.available,j.rid LIMIT 1`).get(Date.now())
1191
+ CROSS JOIN revisions r ON r.rid=j.rid WHERE j.available<=? ${eligible}
1192
+ ORDER BY j.available,j.rid LIMIT 1`).get(Date.now(), ...(language ? [language] : []))
949
1193
  return row && { rid: Number(row.rid), domain: String(row.domain), id: String(row.id), rev: Number(row.rev) }
950
1194
  }
951
1195
  finishVectorJob(domain: string, id: string, rev: number) {
@@ -968,20 +1212,34 @@ export class MemoryStore {
968
1212
  if (vector) yield { domain: String(row.domain), id: String(row.id), rev: Number(row.rev), vector }
969
1213
  }
970
1214
  }
1215
+ vectorRefs(domain: string, models: string[]) {
1216
+ if (!models.length) return []
1217
+ return this.db.prepare(`SELECT DISTINCT id,rev FROM memory_vectors
1218
+ WHERE domain=? AND model IN (SELECT value FROM json_each(?))`)
1219
+ .all(domain, JSON.stringify(models)).map(row => ({ domain, id: String(row.id), rev: Number(row.rev) }))
1220
+ }
971
1221
 
972
1222
  headVectors(domain: string, id: string, rev: number) {
1223
+ return this.headVectorsMany(domain, [{ id, rev }]).get(id) ?? new Map<string, { digest: string; vector: Float32Array }>()
1224
+ }
1225
+ headVectorsMany(domain: string, refs: readonly Ref[]) {
1226
+ const result = new Map<string, Map<string, { digest: string; vector: Float32Array }>>()
1227
+ if (!refs.length) return result
973
1228
  this.expireEpisodes(domain)
974
- const rows = this.db.prepare(
975
- 'SELECT v.model,v.content_hash,v.dimensions,v.vector ' +
976
- headQuery.replace('WHERE', 'JOIN memory_vectors v USING(domain,id,rev) WHERE') +
977
- ' AND h.id=? AND h.rev=?',
978
- ).all(domain, id, rev)
979
- const cached = new Map<string, { digest: string; vector: Float32Array }>()
980
- for (const row of rows) {
1229
+ const rows = this.db.prepare(`SELECT h.id,v.model,v.content_hash,v.dimensions,v.vector FROM json_each(?) wanted
1230
+ CROSS JOIN heads h ON h.domain=? AND h.id=json_extract(wanted.value,'$.id') AND h.rev=json_extract(wanted.value,'$.rev')
1231
+ CROSS JOIN revisions r ON r.domain=h.domain AND r.id=h.id AND r.rev=h.rev
1232
+ CROSS JOIN memory_vectors v ON v.domain=h.domain AND v.id=h.id AND v.rev=h.rev
1233
+ WHERE r.state='confirmed'`)
1234
+ for (const row of rows.iterate(JSON.stringify(refs), domain)) {
981
1235
  const vector = storedVector(row)
982
- if (vector) cached.set(String(row.model), { digest: String(row.content_hash), vector })
1236
+ if (!vector) continue
1237
+ const id = String(row.id)
1238
+ let cached = result.get(id)
1239
+ if (!cached) result.set(id, cached = new Map())
1240
+ cached.set(String(row.model), { digest: String(row.content_hash), vector })
983
1241
  }
984
- return cached
1242
+ return result
985
1243
  }
986
1244
  vector(domain: string, id: string, rev: number, model: string, contentHash: string) {
987
1245
  const entry = this.headVectors(domain, id, rev).get(model)
@@ -1027,42 +1285,11 @@ export class MemoryStore {
1027
1285
  WHERE r.domain=? AND r.state='confirmed' AND r.slot=?`).get(domain, slot)
1028
1286
  return row ? rule(row) : undefined
1029
1287
  }
1030
- semanticMatches(domain: string, scope: 'global' | 'project', topic: string, subject?: string): Rule[] {
1031
- return this.readMany(domain, this.topicRefs(domain, scope, topic, subject, false))
1032
- }
1033
- uniqueTopicPrefix(domain: string, scope: 'global' | 'project', topic: string, subject?: string): boolean {
1034
- return this.topicRefs(domain, scope, topic, subject, true).length === 1
1035
- }
1036
- private topicLabels(domain: string, scope: 'global' | 'project') {
1037
- const slots = scope === 'global' ? 'profile.topic.*' : 'project.topic.*'
1038
- // Only fetch labels from current semantic revisions. Retrieve evidence for actual matches,
1039
- // so unrelated quotes and the accumulated revision history never enter this write path.
1040
- return this.db.prepare(`SELECT r.id,r.rev,json_extract(r.payload,'$.subject') AS subject,
1041
- json_extract(r.payload,'$.semanticTopic') AS topic,json_extract(r.payload,'$.keywords') AS keywords
1042
- FROM revisions r WHERE r.domain=? AND r.state='confirmed' AND r.slot GLOB ?`).iterate(domain, slots)
1043
- }
1044
- topicSubjects(domain: string, scope: 'global' | 'project', topic: string) {
1045
- const canonical = normalizeLabel(topic)
1046
- const subjects = new Set<string>()
1047
- for (const row of this.topicLabels(domain, scope)) {
1048
- if (typeof row.topic === 'string' && normalizeLabel(row.topic) === canonical && typeof row.subject === 'string')
1049
- subjects.add(normalizeLabel(row.subject))
1050
- }
1051
- return subjects
1052
- }
1053
- private topicRefs(domain: string, scope: 'global' | 'project', topic: string, subject: string | undefined, prefix: boolean): Ref[] {
1054
- const label = normalizeLabel(topic)
1055
- const owner = subject === undefined ? undefined : normalizeLabel(subject)
1056
- const matches: Ref[] = []
1057
- for (const row of this.topicLabels(domain, scope)) {
1058
- if (typeof row.topic !== 'string' || (row.subject === null ? undefined : normalizeLabel(String(row.subject))) !== owner) continue
1059
- const aliases: string[] = row.keywords ? parse(row.keywords) : []
1060
- if ([row.topic, ...aliases].some(name => prefix ? normalizeLabel(name).startsWith(label) : normalizeLabel(name) === label)) {
1061
- matches.push({ id: String(row.id), rev: Number(row.rev) })
1062
- if (prefix && matches.length === 2) break
1063
- }
1064
- }
1065
- return matches
1288
+ canonicalTopicHeads(domain: string, scope: 'global' | 'project', topic: string, subject?: string): Rule[] {
1289
+ return this.readMany(domain, this.searchIndex.topicRefs(domain, topic, subject, scope))
1290
+ }
1291
+ topicRefs(domain: string, topic: string, subject?: string) {
1292
+ return this.searchIndex.topicRefs(domain, topic, subject)
1066
1293
  }
1067
1294
  private newerSlotObservation(domain: string, clock: string, stream: string, seq: number, time: number | null) {
1068
1295
  return this.maintenance.staleSlot(domain, clock, stream, seq, time) || this.db.prepare(
@@ -1151,6 +1378,7 @@ export class MemoryStore {
1151
1378
  throw new StoreError('conflict')
1152
1379
  let item = edit ?? original
1153
1380
  validateItem(item)
1381
+ if (p.source.fileImport && replace) throw new StoreError('invalid_selection')
1154
1382
  const old = replace && this.read(domain, replace.id, replace.rev)
1155
1383
  if (replace && (!Number.isInteger(replace.rev) || !old || usedIds.has(replace.id)))
1156
1384
  throw new StoreError('conflict')
@@ -1161,6 +1389,8 @@ export class MemoryStore {
1161
1389
  item = { ...item, slot: old.slot }
1162
1390
  }
1163
1391
  if (isMemorySlot(item.slot)) {
1392
+ if (item.kind === 'fact' && item.usage === 'proactive' && !(old?.kind === 'fact' && old.usage === 'proactive'))
1393
+ throw new StoreError('fact_on_demand')
1164
1394
  const owner = this.currentSlot(domain, item.slot)
1165
1395
  if (owner && owner.id !== old?.id) throw new StoreError('conflict')
1166
1396
  }
@@ -1173,7 +1403,8 @@ export class MemoryStore {
1173
1403
  let family = old?.familyId
1174
1404
  if (!family && item.slot) {
1175
1405
  const related = this.db
1176
- .prepare('SELECT r.family ' + selectedHead + ' AND r.slot=? AND r.paths=? ORDER BY r.family LIMIT 1')
1406
+ .prepare(`SELECT r.family FROM revisions r INDEXED BY revision_current_slot CROSS JOIN heads h USING(domain,id,rev)
1407
+ WHERE r.domain=? AND r.state='confirmed' AND r.slot=? AND r.paths=? ORDER BY r.family LIMIT 1`)
1177
1408
  .get(domain, item.slot, paths)
1178
1409
  if (related) family = String(related.family)
1179
1410
  }
@@ -1187,14 +1418,14 @@ export class MemoryStore {
1187
1418
  // The evidence record is the only copy of a retained quote on a confirmed revision.
1188
1419
  const { user_quote: quote, source: _ignored, channel: _channel, ...payload } = item
1189
1420
  if (options?.channel) payload.channel = options.channel
1190
- const type = !quote
1421
+ const type = p.source.origin === 'tool' && p.source.toolResult ? 'tool_result' : !quote
1191
1422
  ? 'receipt'
1192
1423
  : p.source.origin === 'manual' || original.user_quote !== quote
1193
1424
  ? 'confirmed_wording'
1194
1425
  : 'user_quote'
1195
1426
  const observed = original.source && typeof original.source === 'object' ? original.source : {}
1196
1427
  const source =
1197
- type === 'user_quote'
1428
+ type === 'tool_result' ? p.source : type === 'user_quote'
1198
1429
  ? { ...p.source, ...observed, seq: original.evidence?.seq ?? p.source.seq }
1199
1430
  : {
1200
1431
  storeId: p.source.storeId,
@@ -1202,6 +1433,7 @@ export class MemoryStore {
1202
1433
  turnId: p.turnId,
1203
1434
  seq: p.source.seq,
1204
1435
  origin: 'manual',
1436
+ ...(p.source.fileImport ? { fileImport: p.source.fileImport } : {}),
1205
1437
  }
1206
1438
  if (type !== 'user_quote') delete payload.evidence
1207
1439
  const saved = this.db
@@ -1225,7 +1457,7 @@ export class MemoryStore {
1225
1457
  print,
1226
1458
  promptRole(item),
1227
1459
  )
1228
- indexRevision(this.db, saved.lastInsertRowid, item)
1460
+ indexRevision(this.db, domain, saved.lastInsertRowid, item)
1229
1461
  this.db
1230
1462
  .prepare('INSERT INTO evidence(domain,id,rev,type,quote,source) VALUES(?,?,?,?,?,?)')
1231
1463
  .run(domain, ref.id, ref.rev, type, quote, JSON.stringify(source))
@@ -1271,7 +1503,58 @@ export class MemoryStore {
1271
1503
  "SELECT * FROM proposals WHERE domain=? AND session=? AND id NOT GLOB 'auto-*' ORDER BY created,id",
1272
1504
  )
1273
1505
  .all(domain, session)
1274
- .map(proposalFrom)
1506
+ .map(proposalFrom).filter(visibleProposal)
1507
+ }
1508
+ /** A conversation needs the suggestion count and confirmed references, without the review payload. */
1509
+ conversationCards(domain: string, session: string) {
1510
+ this.expire(domain)
1511
+ const rows = this.db.prepare(`SELECT p.id,p.turn,p.state,json_array_length(p.items) AS count,p.receipt
1512
+ FROM proposals p WHERE p.domain=? AND p.session=? AND p.id NOT GLOB 'auto-*'
1513
+ AND p.state IN ('pending','confirmed') AND p.turn NOT IN ('history','restore','settings')
1514
+ AND json_extract(p.source,'$.sessionId')=p.session
1515
+ AND NOT EXISTS (SELECT 1 FROM file_import_entries i WHERE i.domain=p.domain AND i.proposal=p.id)
1516
+ ORDER BY p.created,p.id`).all(domain, session)
1517
+ return rows.map(row => ({
1518
+ id: String(row.id), turnId: String(row.turn), state: String(row.state), count: Number(row.count),
1519
+ entries: row.receipt ? (JSON.parse(String(row.receipt)) as Receipt).entries.map(({ id, rev }) => ({ id, rev })) : [],
1520
+ }))
1521
+ }
1522
+ /** Current revisions a conversation can display in its turn receipts. */
1523
+ chatHeads(domain: string, session: string, receipts: readonly Ref[]) {
1524
+ const refs = this.db.prepare(`SELECT h.id,h.rev
1525
+ FROM evidence e CROSS JOIN heads h USING(domain,id,rev) CROSS JOIN revisions r USING(domain,id,rev)
1526
+ WHERE e.domain=? AND json_extract(e.source,'$.sessionId')=? AND r.state='confirmed'
1527
+ AND json_extract(r.payload,'$.channel')='automatic'
1528
+ UNION SELECT h.id,h.rev
1529
+ FROM deliveries d CROSS JOIN heads h USING(domain,id,rev) CROSS JOIN revisions r USING(domain,id,rev)
1530
+ WHERE d.domain=? AND d.session=? AND r.state='confirmed' AND r.proactive=1`).all(domain, session, domain, session)
1531
+ const wanted = new Map(receipts.map(ref => [ref.id + '@' + ref.rev, ref]))
1532
+ for (const row of refs) wanted.set(row.id + '@' + row.rev, { id: String(row.id), rev: Number(row.rev) })
1533
+ return this.readMany(domain, [...wanted.values()])
1534
+ }
1535
+ private observesUI = false
1536
+ uiChangeStamp(domains: readonly string[]) {
1537
+ if (!this.observesUI) {
1538
+ // Only desktop/web readers need this connection-local clock. Temp triggers share
1539
+ // the writer's transaction (including rollback) without growing the profile database.
1540
+ this.db.exec('CREATE TEMP TABLE IF NOT EXISTS ui_domain_changes(domain TEXT PRIMARY KEY, seq INTEGER NOT NULL) WITHOUT ROWID')
1541
+ for (const table of ['heads', 'revisions', 'evidence', 'proposals', 'deliveries', 'consolidation_pairs']) {
1542
+ for (const operation of ['INSERT', 'UPDATE', 'DELETE']) {
1543
+ const row = operation === 'DELETE' ? 'OLD' : 'NEW'
1544
+ this.db.exec(`CREATE TEMP TRIGGER IF NOT EXISTS ui_${table}_${operation} AFTER ${operation} ON main.${table}
1545
+ BEGIN UPDATE ui_domain_changes SET seq=seq+1 WHERE domain=${row}.domain; END`)
1546
+ }
1547
+ }
1548
+ this.observesUI = true
1549
+ }
1550
+ const clocks = domains.map(domain => {
1551
+ const clock = this.db.prepare('SELECT seq FROM ui_domain_changes WHERE domain=?').get(domain)
1552
+ if (clock) return clock.seq
1553
+ this.db.prepare('INSERT INTO ui_domain_changes VALUES(?,0)').run(domain)
1554
+ return 0
1555
+ })
1556
+ // External processes may use a different release. Rebuild conservatively after any external commit.
1557
+ return [this.db.prepare('PRAGMA main.data_version').get()!.data_version, this.enabledGeneration(), ...clocks].join('/')
1275
1558
  }
1276
1559
  revoke(domain: string, id: string, rev: number, session = ''): Ref {
1277
1560
  return this.tx(() => this.revokeCurrent(domain, id, rev, session))
@@ -1405,24 +1688,78 @@ export class MemoryStore {
1405
1688
  })
1406
1689
  }
1407
1690
 
1408
- recordDelivery(domain: string, session: string, refs: Ref[], meta: AuditMeta = {}) {
1409
- this.tx(() => {
1410
- for (const { id, rev } of refs) {
1691
+ recordDelivery<T extends Ref & { viaLookup?: boolean; hintOnly?: boolean }>(domain: string, session: string, refs: T[], meta: AuditMeta = {}) {
1692
+ return this.tx(() => {
1693
+ const now = Date.now()
1694
+ const accepted = []
1695
+ for (const ref of refs) {
1696
+ const { id, rev, viaLookup, hintOnly } = ref
1411
1697
  // An already admitted request may contain a revision which has since been replaced.
1412
1698
  // Keep that exposure so the session can receive the correct withdrawal.
1413
1699
  const known = this.db
1414
1700
  .prepare('SELECT 1 FROM revisions WHERE domain=? AND id=? AND rev=?')
1415
1701
  .get(domain, id, rev)
1416
1702
  if (!known) continue
1703
+ accepted.push(ref)
1704
+ if (this.historyDays > 0 && meta.store && meta.turn && Number.isSafeInteger(meta.step) && Number.isSafeInteger(meta.retry))
1705
+ this.audit(domain, session, hintOnly ? 'request_hint' : 'request_body', { ...meta, id, rev })
1706
+ if (hintOnly) continue
1417
1707
  const first = this.db
1418
- .prepare('INSERT OR IGNORE INTO deliveries(domain,session,id,rev) VALUES(?,?,?,?)')
1419
- .run(domain, session, id, rev)
1708
+ .prepare('INSERT OR IGNORE INTO deliveries(domain,session,id,rev,last_delivered,expanded) VALUES(?,?,?,?,?,?)')
1709
+ .run(domain, session, id, rev, now, viaLookup ? 1 : 0)
1420
1710
  // Retries of an already-recorded delivery (e.g. a retried model request re-exposing the
1421
1711
  // same index) need no second audit row; `deliveries` already dedupes the exposure itself.
1422
1712
  if (first.changes) this.audit(domain, session, 'delivery', { ...meta, id, rev })
1713
+ else this.db.prepare(`UPDATE deliveries SET last_delivered=max(last_delivered,?), expanded=max(expanded,?)
1714
+ WHERE domain=? AND session=? AND id=? AND rev=?`).run(now, viaLookup ? 1 : 0, domain, session, id, rev)
1423
1715
  }
1716
+ return accepted
1424
1717
  })
1425
1718
  }
1719
+ turnReceipts(domains: string[], session: string, storeId: string, turn: string, throughStep: number,
1720
+ topic?: (domain: string, ref: Ref) => string | undefined): RequestReceipt[] {
1721
+ if (!domains.length || !Number.isSafeInteger(throughStep) || throughStep < 0 || this.historyDays === 0) return []
1722
+ const cutoff = Date.now() - this.historyDays * 86_400_000
1723
+ const rows = this.db.prepare(`SELECT domain,memory AS id,rev,json_extract(meta,'$.step') AS step,
1724
+ json_extract(meta,'$.retry') AS retry, max(event='request_hint') AS hint, max(event='request_body') AS body,
1725
+ max(event='cite') AS cited, max(event='bash_result' AND json_type(meta,'$.outcome')='integer') AS executed
1726
+ FROM audit WHERE domain IN (${domains.map(() => '?').join(',')}) AND session=?
1727
+ AND json_extract(meta,'$.store')=? AND json_extract(meta,'$.turn')=? AND json_extract(meta,'$.step')<=?
1728
+ AND ${requestEvents} AND time>? AND json_type(meta,'$.retry')='integer'
1729
+ GROUP BY step,retry,domain,memory,rev HAVING hint OR body ORDER BY step,retry,domain,memory,rev`)
1730
+ .all(...domains, session, storeId, turn, throughStep, cutoff)
1731
+ const requests: RequestReceipt[] = []
1732
+ const topics = new Map<string, string | undefined>()
1733
+ for (const row of rows) {
1734
+ const step = Number(row.step), retry = Number(row.retry)
1735
+ let request = requests.at(-1)
1736
+ if (!request || request.step !== step || request.retry !== retry) {
1737
+ request = { step, retry, entries: [] }
1738
+ requests.push(request)
1739
+ }
1740
+ const ref = { id: String(row.id), rev: Number(row.rev) }
1741
+ const key = [row.domain, ref.id, ref.rev].join('\u0000')
1742
+ if (row.body && topic && !topics.has(key)) topics.set(key, topic(String(row.domain), ref))
1743
+ const label = row.body && topics.get(key)
1744
+ request.entries.push({ ...ref, hint: Boolean(row.hint) && !row.body, body: Boolean(row.body),
1745
+ cited: Boolean(row.cited), executed: Boolean(row.executed), ...(label && { topic: label }) })
1746
+ }
1747
+ return requests
1748
+ }
1749
+ usageSignals(domain: string, refs?: readonly Ref[]) {
1750
+ if (refs && !refs.length) return []
1751
+ const heads = refs ? `json_each(?) wanted CROSS JOIN heads h ON h.domain=? AND
1752
+ h.id=json_extract(wanted.value,'$.id') AND h.rev=json_extract(wanted.value,'$.rev')` : 'heads h'
1753
+ const rows = this.db.prepare(`SELECT h.id,h.rev,count(d.session) AS delivered,
1754
+ coalesce(sum(d.expanded),0) AS opened,max(d.last_delivered) AS last
1755
+ FROM ${heads} CROSS JOIN revisions r ON r.domain=h.domain AND r.id=h.id AND r.rev=h.rev
1756
+ LEFT JOIN deliveries d ON d.domain=h.domain AND d.id=h.id AND d.rev=h.rev
1757
+ WHERE h.domain=? AND r.state='confirmed' GROUP BY h.id,h.rev`).all(...(refs ? [JSON.stringify(refs), domain] : []), domain)
1758
+ return rows.map(row => ({
1759
+ id: String(row.id), rev: Number(row.rev), delivered: Number(row.delivered), opened: Number(row.opened),
1760
+ lastDelivery: row.last === null ? null : Number(row.last),
1761
+ }))
1762
+ }
1426
1763
  delivered(domain: string, session: string): Ref[] {
1427
1764
  return this.db
1428
1765
  .prepare('SELECT id,rev FROM deliveries WHERE domain=? AND session=? ORDER BY id,rev')
@@ -1474,7 +1811,7 @@ export class MemoryStore {
1474
1811
  )
1475
1812
  }
1476
1813
  history(domain: string, id?: string) {
1477
- const query = 'SELECT seq,event,session,memory,rev,meta,time FROM audit WHERE domain=?'
1814
+ const query = "SELECT seq,event,session,memory,rev,meta,time FROM audit WHERE domain=? AND event NOT IN ('request_hint','request_body')"
1478
1815
  const rows =
1479
1816
  id === undefined
1480
1817
  ? this.db.prepare(query + ' ORDER BY seq DESC LIMIT 256').all(domain)