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/dist/store.js CHANGED
@@ -4,10 +4,12 @@ import { isAbsolute, join } from 'node:path';
4
4
  import { DatabaseSync } from 'node:sqlite';
5
5
  import { indexRevision, promptRole, SearchIndex } from "./search-index.js";
6
6
  import { EpisodeHistory, episodeBodyDays, episodeSchema } from "./maintenance-episodes.js";
7
- import { MaintenanceState, maintenanceSchema } from "./maintenance-store.js";
7
+ import { MaintenanceState, maintenanceSchema, sourceDetailPaths } from "./maintenance-store.js";
8
8
  import { ReviewLedger } from "./turn-review-store.js";
9
9
  import { ConsolidationStore } from "./consolidation-store.js";
10
- import { isMemorySlot, isSemanticSlot, normalizeLabel } from "./personal.js";
10
+ import { isMemorySlot, isPersonalSlot, isSemanticSlot, semanticSlot } from "./personal.js";
11
+ import { isImportScaffolding } from "./file-import.js";
12
+ import { FileImportStore, fileImportSchema } from "./file-import-store.js";
11
13
  export class StoreError extends Error {
12
14
  code;
13
15
  constructor(code, message = code) {
@@ -18,7 +20,8 @@ export class StoreError extends Error {
18
20
  const ttl = 14 * 24 * 60 * 60 * 1000;
19
21
  const uid = (prefix) => prefix + '-' + randomUUID();
20
22
  // Retain governance receipts for replay protection and idempotent exports.
21
- const prunableAudit = "event IN ('delivery','cite','attempt','tool_result','bash_result','search','ticket_offer','ticket_read','guard_attempt','guard_block')";
23
+ const prunableAudit = "event IN ('delivery','request_hint','request_body','cite','attempt','tool_result','bash_result','search','ticket_offer','ticket_read','guard_attempt','guard_block')";
24
+ const requestEvents = "event IN ('request_hint','request_body','cite','bash_result')";
22
25
  // Stable key order makes a retry independent of the JSON encoder used by the client.
23
26
  function sorted(value) {
24
27
  if (Array.isArray(value))
@@ -33,9 +36,19 @@ function sorted(value) {
33
36
  const hash = (value) => createHash('sha256')
34
37
  .update(JSON.stringify(sorted(value)))
35
38
  .digest('hex');
39
+ const narrowingKey = (ref, source, clarification) => 'narrow:' + hash([ref.id, ref.rev, source.storeId, source.sessionId, source.turnId, source.seq, clarification]);
36
40
  // Open topic labels may themselves reveal personal information. Source clocks survive a
37
41
  // content purge, so store a body-free topic key in both the primary and backup clock tables.
38
42
  const clockSlot = (slot) => isSemanticSlot(slot) ? hash(['semantic-clock', slot]) : slot;
43
+ // The source occurrence belongs to the submitted claim, even if a later semantic
44
+ // comparison selects a different target or extracts a different value from it.
45
+ export function inputClaimKey(source, proposed, item) {
46
+ const span = item.evidence;
47
+ if (!proposed || !span)
48
+ return;
49
+ return 'input:' + hash(['claim', source.storeId, source.sessionId, span.seq, span.start, span.end,
50
+ proposed, item.kind ?? 'preference', item.when, item.exceptions, [...item.paths].sort()]);
51
+ }
39
52
  function fields(item) {
40
53
  return [
41
54
  item.action,
@@ -81,6 +94,7 @@ function validateBatch(domain, session, source, items) {
81
94
  throw new StoreError('invalid_item');
82
95
  items.forEach(validateItem);
83
96
  }
97
+ const schemaVersion = 4;
84
98
  const schema = `
85
99
  CREATE TABLE memory_domains (
86
100
  domain TEXT PRIMARY KEY, epoch INTEGER NOT NULL DEFAULT 0
@@ -93,6 +107,7 @@ const schema = `
93
107
  answer TEXT, receipt TEXT, PRIMARY KEY(domain,id), UNIQUE(domain,session,idem)
94
108
  );
95
109
  CREATE INDEX proposals_inbox ON proposals(domain,session,created);
110
+ ${fileImportSchema}
96
111
  CREATE TABLE revisions (
97
112
  rid INTEGER PRIMARY KEY, proactive INTEGER,
98
113
  domain TEXT NOT NULL REFERENCES memory_domains(domain), id TEXT NOT NULL, rev INTEGER NOT NULL,
@@ -118,8 +133,10 @@ const schema = `
118
133
  );
119
134
  CREATE TABLE deliveries (
120
135
  domain TEXT NOT NULL, session TEXT NOT NULL, id TEXT NOT NULL, rev INTEGER NOT NULL,
136
+ last_delivered INTEGER NOT NULL, expanded INTEGER NOT NULL CHECK(expanded IN (0,1)),
121
137
  PRIMARY KEY(domain,session,id,rev), FOREIGN KEY(domain,id,rev) REFERENCES revisions(domain,id,rev)
122
138
  );
139
+ CREATE INDEX delivery_revision ON deliveries(domain,id,rev);
123
140
  CREATE TABLE audit (
124
141
  seq INTEGER PRIMARY KEY, domain TEXT NOT NULL REFERENCES memory_domains(domain), session TEXT NOT NULL,
125
142
  event TEXT NOT NULL, memory TEXT, rev INTEGER, meta TEXT NOT NULL, time INTEGER NOT NULL
@@ -136,9 +153,28 @@ const headQuery = `
136
153
  // Slot and fingerprint lookups have selective revision indexes; start there and check the live head.
137
154
  const selectedHead = `FROM revisions r CROSS JOIN heads h USING(domain,id,rev)
138
155
  WHERE r.domain=? AND r.state='confirmed'`;
139
- const ruleColumns = 'h.domain,h.id,h.rev,h.pinned,r.family,r.confirmed,r.payload,e.type,e.quote,e.source';
156
+ const baseColumns = 'h.domain,h.id,h.rev,h.pinned,r.family,r.confirmed,r.payload';
157
+ const ruleColumns = baseColumns + ',e.type,e.quote,e.source';
158
+ const rankColumns = baseColumns + ",'receipt' AS type,'' AS quote,'{}' AS source";
159
+ const knowledgeField = (path) => `json_extract(payload,'$.knowledge.${path}')`;
160
+ const commandFields = {
161
+ guard: ['match.command', 'match.workdir'],
162
+ runbook: ['steps.verify', 'steps.workdir'],
163
+ episode: ['failure.command', 'failure.workdir'],
164
+ trigger: ['trigger.command', 'trigger.workdir'],
165
+ };
166
+ const knowledgeTrigger = knowledgeField('trigger.text');
167
+ const triggerPrefix = `substr(${knowledgeTrigger},1,2)`;
168
+ const currentTextTrigger = `state='confirmed' AND ${knowledgeTrigger} IS NOT NULL`;
169
+ // Sparse expression indexes stay in sync with edits, withdrawals, imports and restores.
170
+ const knowledgeHookIndexes = Object.entries(commandFields).map(([key, [command, cwd]]) => `CREATE INDEX IF NOT EXISTS knowledge_${key}_command ON revisions(domain,${knowledgeField(command)},${knowledgeField(cwd)})
171
+ WHERE state='confirmed' AND ${knowledgeField(command)} IS NOT NULL;`).join('\n') +
172
+ `CREATE INDEX IF NOT EXISTS knowledge_text_trigger ON revisions(domain,${triggerPrefix},${knowledgeTrigger})
173
+ WHERE ${currentTextTrigger}`;
174
+ const knowledgeCandidateRows = `SELECT ${ruleColumns} FROM revisions r
175
+ CROSS JOIN heads h USING(domain,id,rev) CROSS JOIN evidence e USING(domain,id,rev)`;
140
176
  const parse = (v) => JSON.parse(String(v));
141
- function storedVector(row) {
177
+ export function storedVector(row) {
142
178
  const dimensions = Number(row.dimensions);
143
179
  if (!(row.vector instanceof Uint8Array) || dimensions < 1 || dimensions > 8192 ||
144
180
  row.vector.byteLength !== dimensions * 4)
@@ -194,6 +230,12 @@ function proposalFrom(row) {
194
230
  ...(row.receipt ? { receipt: parse(row.receipt) } : {}),
195
231
  };
196
232
  }
233
+ // Older imports may already have staged index entries and explanatory paragraphs.
234
+ // Omit them from the inbox without modifying an import batch or its review history.
235
+ function visibleProposal(p) {
236
+ const file = p.source.fileImport;
237
+ return !file || p.state !== 'pending' || p.items.some(item => !isImportScaffolding(item.action, item.when, file.path));
238
+ }
197
239
  export class MemoryStore {
198
240
  onHeadsChanged;
199
241
  onMemoryDisabled;
@@ -204,6 +246,7 @@ export class MemoryStore {
204
246
  db;
205
247
  directory;
206
248
  searchIndex;
249
+ fileImports;
207
250
  turnReviews;
208
251
  consolidation;
209
252
  maintenance;
@@ -238,7 +281,7 @@ export class MemoryStore {
238
281
  this.db.exec('PRAGMA busy_timeout=3000; PRAGMA foreign_keys=ON; PRAGMA secure_delete=ON; PRAGMA journal_mode=WAL; PRAGMA synchronous=FULL');
239
282
  this.tx(() => {
240
283
  const version = Number(this.db.prepare('PRAGMA user_version').get()?.user_version);
241
- if (version !== 1) {
284
+ if (version !== schemaVersion) {
242
285
  if (version !== 0 || this.db.prepare("SELECT 1 FROM sqlite_master WHERE type='table'").get())
243
286
  throw new StoreError('unsupported_schema');
244
287
  this.db.exec(schema);
@@ -258,12 +301,39 @@ export class MemoryStore {
258
301
  changed_at INTEGER NOT NULL
259
302
  );
260
303
  INSERT INTO memory_settings VALUES(0,1,0);
261
- ${maintenanceSchema}; ${episodeSchema}; PRAGMA user_version=1`);
304
+ ${maintenanceSchema}; ${episodeSchema}; PRAGMA user_version=${schemaVersion}`);
262
305
  this.searchIndex.create();
263
306
  }
307
+ this.db.exec(`DROP TRIGGER IF EXISTS release_proposal_evidence;
308
+ CREATE TRIGGER IF NOT EXISTS release_settled_evidence AFTER UPDATE OF state ON proposals
309
+ WHEN NEW.state<>'pending' AND NEW.source<>json_remove(NEW.source,${sourceDetailPaths}) BEGIN
310
+ UPDATE proposals SET source=json_remove(NEW.source,${sourceDetailPaths}) WHERE domain=NEW.domain AND id=NEW.id;
311
+ END;
312
+ CREATE INDEX IF NOT EXISTS proposal_turn ON proposals(domain,session,turn);
313
+ CREATE INDEX IF NOT EXISTS revision_batch ON revisions(domain,batch);
314
+ CREATE INDEX IF NOT EXISTS revision_domain_retirement ON revisions(domain,retired) WHERE retired IS NOT NULL;
315
+ CREATE INDEX IF NOT EXISTS proposal_domain_expiry ON proposals(domain,created) WHERE state='pending';
316
+ CREATE INDEX IF NOT EXISTS proposal_review_source ON proposals(domain,json_extract(source,'$.storeId'),
317
+ json_extract(source,'$.sessionId')) WHERE id NOT GLOB 'auto-*';
318
+ CREATE INDEX IF NOT EXISTS evidence_session ON evidence(domain,json_extract(source,'$.sessionId'));
319
+ CREATE INDEX IF NOT EXISTS audit_request ON audit(
320
+ domain,session,json_extract(meta,'$.store'),json_extract(meta,'$.turn'),json_extract(meta,'$.step')
321
+ ) WHERE ${requestEvents}`);
322
+ this.db.exec(knowledgeHookIndexes);
264
323
  this.maintenance.reconcileConsent(version === 0);
324
+ this.searchIndex.ensureTopicLabels();
265
325
  this.searchIndex.syncVectorFormat();
266
326
  });
327
+ this.fileImports = new FileImportStore(this.db, {
328
+ expire: domain => this.expire(domain),
329
+ tx: fn => this.tx(fn),
330
+ list: domain => this.list(domain),
331
+ create: (domain, session, source, item, idem) => {
332
+ validateBatch(domain, session, source, [item]);
333
+ return this.createBatch(domain, session, source, [item], source.turnId, idem, 'p');
334
+ },
335
+ revoke: (domain, id, rev, session) => this.revokeCurrent(domain, id, rev, session),
336
+ });
267
337
  this.turnReviews = new ReviewLedger(this.db);
268
338
  this.consolidation = new ConsolidationStore(this.db, {
269
339
  transaction: fn => this.tx(fn),
@@ -397,9 +467,12 @@ export class MemoryStore {
397
467
  const due = "state IN ('superseded','revoked') AND retired IS NOT NULL AND retired<=?" + scope;
398
468
  const pending = "state='pending' AND created<=?" + scope;
399
469
  const auditDue = 'time<=? AND ' + prunableAudit + scope;
400
- // Ordinary reads need no writer lock when no indexed deadline has elapsed.
401
- if (!this.db.prepare('SELECT 1 FROM revisions WHERE ' + due + ' LIMIT 1').get(cutoff, ...key) &&
402
- !this.db.prepare('SELECT 1 FROM proposals WHERE ' + pending + ' LIMIT 1').get(now - ttl, ...key) &&
470
+ // The usual case has no expired rows. Seek the deadline itself, even when a fresh
471
+ // database's planner has no statistics for the other domain-leading indexes.
472
+ const revisions = 'revisions INDEXED BY ' + (domain === undefined ? 'revision_retirement' : 'revision_domain_retirement');
473
+ const proposals = 'proposals INDEXED BY ' + (domain === undefined ? 'proposal_expiry' : 'proposal_domain_expiry');
474
+ if (!this.db.prepare(`SELECT 1 FROM ${revisions} WHERE ${due} LIMIT 1`).get(cutoff, ...key) &&
475
+ !this.db.prepare(`SELECT 1 FROM ${proposals} WHERE ${pending} LIMIT 1`).get(now - ttl, ...key) &&
403
476
  !this.db.prepare('SELECT 1 FROM audit WHERE ' + auditDue + ' LIMIT 1').get(cutoff, ...key))
404
477
  return;
405
478
  const clean = () => {
@@ -408,7 +481,7 @@ export class MemoryStore {
408
481
  // vice versa.
409
482
  this.db
410
483
  .prepare(`UPDATE evidence SET quote='',type='receipt',source='{}' WHERE (domain,id,rev) IN
411
- (SELECT domain,id,rev FROM revisions WHERE ${due})`)
484
+ (SELECT domain,id,rev FROM ${revisions} WHERE ${due})`)
412
485
  .run(cutoff, ...key);
413
486
  // A retired revision's own provenance row is redundant by this point: retire() (called when
414
487
  // it was superseded/revoked, always well before this cutoff) already folded its slot/stream
@@ -416,14 +489,14 @@ export class MemoryStore {
416
489
  // cross-stream slot check nor the per-occurrence dedup below needs the raw row to survive.
417
490
  this.db
418
491
  .prepare(`DELETE FROM automatic_sources WHERE (domain,id,rev) IN
419
- (SELECT domain,id,rev FROM revisions WHERE ${due})`)
492
+ (SELECT domain,id,rev FROM ${revisions} WHERE ${due})`)
420
493
  .run(cutoff, ...key);
421
494
  this.db
422
- .prepare(`UPDATE revisions SET action='',condition='',paths='[]',slot=NULL,payload='{}',proactive=NULL,
495
+ .prepare(`UPDATE ${revisions} SET action='',condition='',paths='[]',slot=NULL,payload='{}',proactive=NULL,
423
496
  fingerprint='',retired=NULL WHERE ${due}`)
424
497
  .run(cutoff, ...key);
425
498
  this.db
426
- .prepare("UPDATE proposals SET state='expired',items='[]' WHERE " + pending)
499
+ .prepare(`UPDATE ${proposals} SET state='expired',items='[]' WHERE ${pending}`)
427
500
  .run(now - ttl, ...key);
428
501
  this.db.prepare('DELETE FROM audit WHERE ' + auditDue).run(cutoff, ...key);
429
502
  };
@@ -440,8 +513,8 @@ export class MemoryStore {
440
513
  if (this.onHeadsChanged)
441
514
  this.changedDomains.add(domain);
442
515
  }
443
- /** The version that `rev` replaced, while its content is retained. A withdrawn version is not offered back. */
444
- previous(domain, id, rev, accept) {
516
+ /** Follow the retained predecessor chain, stopping at withdrawal, erasure or expiry. */
517
+ *previousVersions(domain, id, rev) {
445
518
  const predecessor = this.db.prepare(`SELECT p.domain,p.id,p.rev,0 AS pinned,p.family,p.confirmed,p.payload,e.type,e.quote,e.source
446
519
  FROM revisions r JOIN revisions p ON p.domain=r.domain AND p.id=r.id AND p.rev=r.previous
447
520
  JOIN evidence e ON e.domain=p.domain AND e.id=p.id AND e.rev=p.rev
@@ -453,11 +526,15 @@ export class MemoryStore {
453
526
  if (!row)
454
527
  return;
455
528
  const version = rule(row);
456
- if (!accept || accept(version))
457
- return version;
529
+ yield version;
458
530
  rev = version.rev;
459
531
  }
460
532
  }
533
+ previous(domain, id, rev, accept) {
534
+ for (const version of this.previousVersions(domain, id, rev))
535
+ if (!accept || accept(version))
536
+ return version;
537
+ }
461
538
  list(domain) {
462
539
  this.expireEpisodes(domain);
463
540
  return this.db
@@ -468,11 +545,69 @@ export class MemoryStore {
468
545
  hasCurrent(domain) {
469
546
  return Boolean(this.db.prepare('SELECT 1 ' + headQuery + ' LIMIT 1').get(domain));
470
547
  }
548
+ // Exact duplicate and conflict checks compare rule fields and do not need the source quotation.
549
+ comparisonHeads(domain, field, value) {
550
+ this.expireEpisodes(domain);
551
+ return this.db.prepare(`SELECT ${rankColumns} ${selectedHead} AND r.${field}=?`).all(domain, value).map(rule);
552
+ }
553
+ commandCandidates(domain, command, workdir, phase) {
554
+ this.expireEpisodes(domain);
555
+ const keys = phase === 'attempt' ? ['guard']
556
+ : phase === 'guard' ? ['guard', 'runbook', 'episode'] : ['trigger'];
557
+ const matches = keys.map(key => {
558
+ const [cmd, cwd] = commandFields[key];
559
+ return `SELECT rid FROM revisions INDEXED BY knowledge_${key}_command
560
+ WHERE domain=? AND state='confirmed' AND ${knowledgeField(cmd)}=? AND ${knowledgeField(cwd)}=?`;
561
+ }).join(' UNION ALL ');
562
+ return this.db.prepare(`${knowledgeCandidateRows} WHERE r.rid IN (${matches}) ORDER BY r.confirmed DESC,h.id`)
563
+ .all(...keys.flatMap(() => [domain, command, workdir])).map(rule);
564
+ }
565
+ messageCandidates(domain, messages) {
566
+ this.expireEpisodes(domain);
567
+ const triggers = `FROM revisions INDEXED BY knowledge_text_trigger WHERE domain=? AND ${currentTextTrigger}`;
568
+ if (!messages.length || !this.db.prepare(`SELECT 1 ${triggers} LIMIT 1`).get(domain))
569
+ return [];
570
+ // Match literal substrings within one message. Typical prompts probe the index by the
571
+ // first two code points. For large pasted inputs, scan only this domain's trigger keys.
572
+ const args = [domain];
573
+ let prefixFilter = '';
574
+ if (messages.reduce((length, text) => length + text.length, 0) <= 8192) {
575
+ const prefixes = new Set();
576
+ for (const message of messages) {
577
+ let previous = '';
578
+ for (const character of message) {
579
+ prefixes.add(character);
580
+ if (previous)
581
+ prefixes.add(previous + character);
582
+ previous = character;
583
+ }
584
+ }
585
+ prefixFilter = `AND ${triggerPrefix} IN (SELECT value FROM json_each(?))`;
586
+ args.push(JSON.stringify([...prefixes]));
587
+ }
588
+ args.push(JSON.stringify(messages));
589
+ const matches = `SELECT rid ${triggers} ${prefixFilter} AND EXISTS (
590
+ SELECT 1 FROM json_each(?) msg WHERE instr(msg.value,${knowledgeTrigger})>0)`;
591
+ return this.db.prepare(`${knowledgeCandidateRows} WHERE r.rid IN (${matches}) ORDER BY r.confirmed DESC,h.id`)
592
+ .all(...args).map(rule);
593
+ }
471
594
  read(domain, id, rev) {
472
595
  this.expireEpisodes(domain);
473
596
  const row = this.db.prepare('SELECT ' + ruleColumns + headQuery + ' AND h.id=?').get(domain, id);
474
597
  return row && (rev === undefined || rev === row.rev) ? rule(row) : undefined;
475
598
  }
599
+ replayedReplacement(domain, ref, source, item) {
600
+ const head = this.read(domain, ref.id, ref.rev + 1);
601
+ if (!head || head.channel !== 'automatic' || head.quoteType !== 'user_quote' ||
602
+ head.source.turnId !== source.turnId || !head.evidence || !item.evidence ||
603
+ quoteKey(head.source, head.evidence, head.user_quote) !== quoteKey(source, item.evidence, item.user_quote) ||
604
+ head.user_quote !== item.user_quote || head.action !== item.action || head.when !== item.when ||
605
+ head.exceptions !== item.exceptions || JSON.stringify(head.paths) !== JSON.stringify(item.paths) ||
606
+ head.kind !== item.kind || head.slot !== item.slot || Boolean(head.sensitive) !== Boolean(item.sensitive) ||
607
+ (head.usage ?? 'on_demand') !== (item.usage ?? 'on_demand'))
608
+ return;
609
+ return { id: head.id, rev: head.rev };
610
+ }
476
611
  readMany(domain, refs) {
477
612
  if (!refs.length)
478
613
  return [];
@@ -480,15 +615,27 @@ export class MemoryStore {
480
615
  const head = this.read(domain, refs[0].id, refs[0].rev);
481
616
  return head ? [head] : [];
482
617
  }
618
+ return this.rowsByRef(domain, refs, true);
619
+ }
620
+ // Only applicability and ranking fields are needed in the first pass. Retained quotes
621
+ // and provenance stay on disk until the caller rechecks a winning revision.
622
+ searchHeads(domain, refs, topicsOnly = false) {
623
+ if (refs)
624
+ return refs.length ? this.rowsByRef(domain, refs, false, topicsOnly) : [];
625
+ this.expireEpisodes(domain);
626
+ return this.db.prepare(`SELECT ${rankColumns} FROM heads h CROSS JOIN revisions r USING(domain,id,rev)
627
+ WHERE h.domain=? AND r.state='confirmed' ORDER BY r.confirmed DESC,h.id`).all(domain).map(rule);
628
+ }
629
+ rowsByRef(domain, refs, evidence, topicsOnly = false) {
483
630
  this.expireEpisodes(domain);
484
631
  // Drive indexed head lookups from the hit list, including when a broad term matches
485
632
  // hundreds of records in a much larger domain. json_each uses one bind parameter.
486
- return this.db.prepare(`SELECT ${ruleColumns} FROM json_each(?) wanted
633
+ return this.db.prepare(`SELECT ${evidence ? ruleColumns : rankColumns} FROM json_each(?) wanted
487
634
  CROSS JOIN heads h ON h.domain=? AND h.id=json_extract(wanted.value,'$.id')
488
635
  CROSS JOIN revisions r ON r.domain=h.domain AND r.id=h.id AND r.rev=h.rev
489
- CROSS JOIN evidence e ON e.domain=h.domain AND e.id=h.id AND e.rev=h.rev
490
- WHERE r.state='confirmed' AND (json_type(wanted.value,'$.rev') IS NULL
491
- OR h.rev=json_extract(wanted.value,'$.rev'))`)
636
+ ${evidence ? 'CROSS JOIN evidence e ON e.domain=h.domain AND e.id=h.id AND e.rev=h.rev' : ''}
637
+ WHERE r.state='confirmed' AND (json_type(wanted.value,'$.rev') IS NULL OR h.rev=json_extract(wanted.value,'$.rev'))
638
+ ${topicsOnly ? "AND json_type(r.payload,'$.semanticTopic')='text'" : ''}`)
492
639
  .all(JSON.stringify(refs), domain).map(rule);
493
640
  }
494
641
  getProposalRow(domain, session, id) {
@@ -506,7 +653,7 @@ export class MemoryStore {
506
653
  return this.db
507
654
  .prepare("SELECT * FROM proposals WHERE domain=? AND session=? AND state='pending' ORDER BY created,id")
508
655
  .all(domain, session)
509
- .map(proposalFrom);
656
+ .map(proposalFrom).filter(visibleProposal);
510
657
  }
511
658
  // turn cards are recovered by session + turn even if the user already answered the card.
512
659
  turn(domain, session, turnId) {
@@ -514,14 +661,15 @@ export class MemoryStore {
514
661
  return this.db
515
662
  .prepare("SELECT * FROM proposals WHERE domain=? AND session=? AND turn=? AND id NOT GLOB 'auto-*' ORDER BY created,id")
516
663
  .all(domain, session, turnId)
517
- .map(proposalFrom);
664
+ .map(proposalFrom).filter(visibleProposal);
518
665
  }
519
666
  propose(domain, session, source, items, displayTurn = source.turnId) {
520
667
  validateBatch(domain, session, source, items);
521
668
  // A batch can cite multiple genuine user messages. The representative seq on the envelope
522
669
  // changes when the model reorders such rows, so bind each row to its own source instead.
523
670
  const { seq, ...batchSource } = source;
524
- const idem = hash([batchSource, items.map((item) => hash([item, item.evidence?.seq ?? seq])).sort()]);
671
+ const idem = source.origin === 'tool' ? hash(['bash', source.storeId, source.sessionId, seq])
672
+ : hash([batchSource, items.map((item) => hash([item, item.evidence?.seq ?? seq])).sort()]);
525
673
  return this.tx(() => {
526
674
  this.expire(domain);
527
675
  const existing = this.db
@@ -607,14 +755,16 @@ export class MemoryStore {
607
755
  const proposed = proposedSlots?.[index];
608
756
  const meaning = (proposed ? 'input:' : '') + hash([stream, seq, 'content', proposed ?? slot,
609
757
  item.action, item.when, item.exceptions, [...item.paths].sort()]);
610
- if (proposed && this.maintenance.retiredInput(domain, meaning))
758
+ const claim = inputClaimKey(source, proposed, item);
759
+ const keys = claim ? [occurrence, meaning, claim] : [occurrence, meaning];
760
+ if (proposed && (this.maintenance.retiredInput(domain, meaning) ||
761
+ (claim && this.maintenance.retiredInput(domain, claim))))
611
762
  continue;
612
- const already = sourceKeys.get(occurrence);
613
- if (already && already.print !== print)
763
+ if (keys.some(key => sourceKeys.has(key) && sourceKeys.get(key).print !== print))
614
764
  throw new StoreError('ambiguous_source');
615
765
  const seen = this.db
616
- .prepare('SELECT DISTINCT id,rev FROM automatic_sources WHERE domain=? AND occurrence IN (?,?)')
617
- .all(domain, occurrence, meaning);
766
+ .prepare('SELECT DISTINCT id,rev FROM automatic_sources WHERE domain=? AND occurrence IN (?,?,?)')
767
+ .all(domain, occurrence, meaning, claim ?? null);
618
768
  // Each item in the batch is independent: a stale or blocked sibling must only drop itself,
619
769
  // never the other, unrelated items already resolved (or still to be resolved) in this call.
620
770
  if (seen.length > 1)
@@ -622,10 +772,16 @@ export class MemoryStore {
622
772
  if (seen.length) {
623
773
  const ref = { id: String(seen[0].id), rev: Number(seen[0].rev) };
624
774
  const live = this.read(domain, ref.id, ref.rev);
625
- if (!live)
775
+ // The occurrence identifies an event and slot, even if a subsequent extraction
776
+ // disagrees about its value. Only the committed content can reuse its receipt.
777
+ if (!live || hash(fields(live)) !== fingerprint)
626
778
  continue;
627
- if (proposed && slot && live.slot === slot && hash(fields(live)) === fingerprint)
628
- sourceKeys.set(meaning, { stream, seq, time, slot: clockSlot(slot), print });
779
+ if (proposed && slot) {
780
+ const bound = { stream, seq, time, slot: clockSlot(slot), print };
781
+ sourceKeys.set(meaning, bound);
782
+ if (claim)
783
+ sourceKeys.set(claim, bound);
784
+ }
629
785
  refs.set(print, ref);
630
786
  if (item.evidence)
631
787
  duplicateSpans.push(item.evidence);
@@ -665,8 +821,8 @@ export class MemoryStore {
665
821
  continue;
666
822
  }
667
823
  const observedKey = { stream, seq, time, slot: clock, print };
668
- sourceKeys.set(occurrence, observedKey);
669
- sourceKeys.set(meaning, observedKey);
824
+ for (const key of keys)
825
+ sourceKeys.set(key, observedKey);
670
826
  const repeated = this.duplicate(domain, fingerprint);
671
827
  if (repeated && (!slot || currentSlot?.id === repeated.id)) {
672
828
  refs.set(print, { id: String(repeated.id), rev: Number(repeated.rev) });
@@ -695,7 +851,7 @@ export class MemoryStore {
695
851
  }
696
852
  if (!refs.size)
697
853
  return stale;
698
- this.turnReviews.noteDuplicates(domain, source, duplicateSpans);
854
+ this.turnReviews.noteHandled(domain, source, duplicateSpans);
699
855
  const record = this.db.prepare('INSERT INTO automatic_sources(domain,occurrence,stream,seq,time,slot,id,rev) VALUES(?,?,?,?,?,?,?,?) ON CONFLICT(domain,occurrence) DO NOTHING');
700
856
  for (const [occurrence, key] of sourceKeys) {
701
857
  const ref = refs.get(key.print);
@@ -707,6 +863,70 @@ export class MemoryStore {
707
863
  };
708
864
  });
709
865
  }
866
+ narrowedProjectRef(project, ref, source, clarification) {
867
+ // Keep retries bound to the actual destination write. A restore, later revision, withdrawal or
868
+ // deletion of its source no longer attests this operation.
869
+ 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
870
+ 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
871
+ WHERE p.domain=? AND p.session=? AND p.idem=? AND p.state='confirmed' AND r.state='confirmed' AND e.type='user_quote'`)
872
+ .get(project, source.sessionId, narrowingKey(ref, source, clarification));
873
+ return row && { id: String(row.id), rev: Number(row.rev) };
874
+ }
875
+ soleTurnAgreement(domains, source, ref) {
876
+ if (!domains.length)
877
+ return false;
878
+ 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
879
+ WHERE p.domain IN (${domains.map(() => '?').join(',')}) AND p.session=? AND p.turn=? AND json_extract(p.source,'$.storeId')=?
880
+ AND p.state='confirmed' AND coalesce(json_extract(r.payload,'$.kind'),'preference') IN ('preference','rule') LIMIT 2`)
881
+ .all(...domains, source.sessionId, source.turnId, source.storeId);
882
+ return rows.length === 1 && rows[0].id === ref.id;
883
+ }
884
+ narrowToProject(project, ref, source, clarification, span, generation, epochs, projectConditions) {
885
+ const profile = 'profile:personal';
886
+ return this.tx(() => {
887
+ if (!project || project === profile || source.origin !== 'user' || source.seq !== span.seq ||
888
+ !Number.isSafeInteger(span.start) || span.start < 0 || span.end - span.start !== clarification.length || !clarification.trim())
889
+ throw new StoreError('invalid_source');
890
+ if (generation === undefined || this.enabledGeneration() !== generation)
891
+ throw new StoreError('memory_disabled');
892
+ const replay = this.narrowedProjectRef(project, ref, source, clarification);
893
+ if (replay)
894
+ return { status: 'duplicate', entries: [replay] };
895
+ if ([profile, project].some(domain => this.epoch(domain) !== epochs.get(domain)))
896
+ throw new StoreError('conflict');
897
+ const old = this.read(profile, ref.id, ref.rev);
898
+ if (!old || !isPersonalSlot(old.slot) || !old.semanticTopic || !['rule', 'preference'].includes(old.kind ?? '') || old.channel !== 'automatic' ||
899
+ old.quoteType !== 'user_quote' || !old.user_quote || !old.evidence || old.sensitive || old.pinned ||
900
+ old.usageOverride || old.localException || old.paths.length || old.source.origin !== 'user')
901
+ throw new StoreError('protected_revision');
902
+ if (old.source.storeId !== source.storeId || old.source.sessionId !== source.sessionId ||
903
+ old.evidence.seq >= source.seq || old.source.turnId === source.turnId)
904
+ throw new StoreError('invalid_source');
905
+ const slot = semanticSlot('project', old.semanticTopic, old.subject, old);
906
+ if (!slot || this.currentSlot(project, slot) ||
907
+ this.canonicalTopicHeads(project, 'project', old.semanticTopic, old.subject).length)
908
+ throw new StoreError('conflict');
909
+ const item = { ...revisionDraft(old), ...projectConditions(old), slot, source: {
910
+ ...old.source, scopeClarification: { ...span, turnId: source.turnId, previous: ref },
911
+ } };
912
+ const stream = hash([source.storeId, source.sessionId]);
913
+ if (this.maintenance.blockedHistory(project, old.source, item) ||
914
+ this.newerSlotObservation(project, clockSlot(slot), stream, source.seq, source.time ?? null))
915
+ throw new StoreError('conflict');
916
+ validateBatch(project, source.sessionId, source, [item]);
917
+ const idem = narrowingKey(ref, source, clarification);
918
+ const proposal = this.createBatch(project, source.sessionId, source, [item], source.turnId, idem, 'auto');
919
+ const { entries } = this.finishBatch(project, source.sessionId, proposal.id, proposal.revision, proposal.digest, [{ index: 0 }], { channel: 'automatic', decision: idem });
920
+ const target = entries[0];
921
+ this.db.prepare('INSERT INTO automatic_sources VALUES(?,?,?,?,?,?,?,?)')
922
+ .run(project, idem, stream, source.seq, source.time ?? null, clockSlot(slot), target.id, target.rev);
923
+ this.turnReviews.noteHandled(project, source, [span]);
924
+ this.revokeCurrent(profile, old.id, old.rev, source.sessionId);
925
+ this.maintenance.releaseTransferredRevision(profile, old.id, old.rev);
926
+ this.audit(project, source.sessionId, 'narrow_scope', { ...target, turn: source.turnId, seq: source.seq, store: source.storeId });
927
+ return { status: 'saved', entries };
928
+ });
929
+ }
710
930
  commitManual(domain, session, source, item, replace, channel = 'user_command') {
711
931
  if (source.origin !== 'manual')
712
932
  throw new StoreError('invalid_source');
@@ -733,7 +953,7 @@ export class MemoryStore {
733
953
  throw new StoreError('conflict');
734
954
  if (old.sensitive && usage === 'proactive')
735
955
  throw new StoreError('sensitive_on_demand');
736
- if (old.usage === usage && old.usageOverride)
956
+ if ((old.usage ?? 'on_demand') === usage && (old.usageOverride || old.kind === 'fact'))
737
957
  return ref;
738
958
  const item = { ...revisionDraft(old), usage, usageOverride: true };
739
959
  const decision = 'usage:' + old.id + '@' + old.rev + ':' + usage;
@@ -764,10 +984,23 @@ export class MemoryStore {
764
984
  onDemandHeads(domain) {
765
985
  return this.promptHeads(domain, false);
766
986
  }
767
- nextVectorJob() {
987
+ onDemandCandidates(domain, terms) {
988
+ if (!terms.length)
989
+ return [];
990
+ const expression = 'labels:(' + terms.map(word => Buffer.from(word).toString('hex')).join(' OR ') + ')';
991
+ const rows = this.db.prepare(`SELECT h.domain,h.id,h.rev,h.pinned,r.family,r.confirmed,r.payload,
992
+ 'receipt' AS type,'' AS quote,'{}' AS source FROM memory_fts
993
+ CROSS JOIN revisions r ON r.rid=memory_fts.rowid CROSS JOIN heads h USING(domain,id,rev)
994
+ WHERE memory_fts MATCH ? AND r.domain=? AND r.state='confirmed' AND r.proactive=0
995
+ AND json_extract(r.payload,'$.sensitive') IS NOT 1 AND json_extract(r.payload,'$.semanticTopic') IS NOT NULL
996
+ ORDER BY bm25(memory_fts,0,0,1),r.rid LIMIT 32`).all(expression, domain);
997
+ return rows.map(rule);
998
+ }
999
+ nextVectorJob(language) {
1000
+ const eligible = language ? 'AND j.language=?' : '';
768
1001
  const row = this.db.prepare(`SELECT j.rid,r.domain,r.id,r.rev FROM memory_vector_jobs j
769
- CROSS JOIN revisions r ON r.rid=j.rid WHERE j.available<=?
770
- ORDER BY j.available,j.rid LIMIT 1`).get(Date.now());
1002
+ CROSS JOIN revisions r ON r.rid=j.rid WHERE j.available<=? ${eligible}
1003
+ ORDER BY j.available,j.rid LIMIT 1`).get(Date.now(), ...(language ? [language] : []));
771
1004
  return row && { rid: Number(row.rid), domain: String(row.domain), id: String(row.id), rev: Number(row.rev) };
772
1005
  }
773
1006
  finishVectorJob(domain, id, rev) {
@@ -791,18 +1024,37 @@ export class MemoryStore {
791
1024
  yield { domain: String(row.domain), id: String(row.id), rev: Number(row.rev), vector };
792
1025
  }
793
1026
  }
1027
+ vectorRefs(domain, models) {
1028
+ if (!models.length)
1029
+ return [];
1030
+ return this.db.prepare(`SELECT DISTINCT id,rev FROM memory_vectors
1031
+ WHERE domain=? AND model IN (SELECT value FROM json_each(?))`)
1032
+ .all(domain, JSON.stringify(models)).map(row => ({ domain, id: String(row.id), rev: Number(row.rev) }));
1033
+ }
794
1034
  headVectors(domain, id, rev) {
1035
+ return this.headVectorsMany(domain, [{ id, rev }]).get(id) ?? new Map();
1036
+ }
1037
+ headVectorsMany(domain, refs) {
1038
+ const result = new Map();
1039
+ if (!refs.length)
1040
+ return result;
795
1041
  this.expireEpisodes(domain);
796
- const rows = this.db.prepare('SELECT v.model,v.content_hash,v.dimensions,v.vector ' +
797
- headQuery.replace('WHERE', 'JOIN memory_vectors v USING(domain,id,rev) WHERE') +
798
- ' AND h.id=? AND h.rev=?').all(domain, id, rev);
799
- const cached = new Map();
800
- for (const row of rows) {
1042
+ const rows = this.db.prepare(`SELECT h.id,v.model,v.content_hash,v.dimensions,v.vector FROM json_each(?) wanted
1043
+ CROSS JOIN heads h ON h.domain=? AND h.id=json_extract(wanted.value,'$.id') AND h.rev=json_extract(wanted.value,'$.rev')
1044
+ CROSS JOIN revisions r ON r.domain=h.domain AND r.id=h.id AND r.rev=h.rev
1045
+ CROSS JOIN memory_vectors v ON v.domain=h.domain AND v.id=h.id AND v.rev=h.rev
1046
+ WHERE r.state='confirmed'`);
1047
+ for (const row of rows.iterate(JSON.stringify(refs), domain)) {
801
1048
  const vector = storedVector(row);
802
- if (vector)
803
- cached.set(String(row.model), { digest: String(row.content_hash), vector });
1049
+ if (!vector)
1050
+ continue;
1051
+ const id = String(row.id);
1052
+ let cached = result.get(id);
1053
+ if (!cached)
1054
+ result.set(id, cached = new Map());
1055
+ cached.set(String(row.model), { digest: String(row.content_hash), vector });
804
1056
  }
805
- return cached;
1057
+ return result;
806
1058
  }
807
1059
  vector(domain, id, rev, model, contentHash) {
808
1060
  const entry = this.headVectors(domain, id, rev).get(model);
@@ -829,44 +1081,11 @@ export class MemoryStore {
829
1081
  WHERE r.domain=? AND r.state='confirmed' AND r.slot=?`).get(domain, slot);
830
1082
  return row ? rule(row) : undefined;
831
1083
  }
832
- semanticMatches(domain, scope, topic, subject) {
833
- return this.readMany(domain, this.topicRefs(domain, scope, topic, subject, false));
834
- }
835
- uniqueTopicPrefix(domain, scope, topic, subject) {
836
- return this.topicRefs(domain, scope, topic, subject, true).length === 1;
837
- }
838
- topicLabels(domain, scope) {
839
- const slots = scope === 'global' ? 'profile.topic.*' : 'project.topic.*';
840
- // Only fetch labels from current semantic revisions. Retrieve evidence for actual matches,
841
- // so unrelated quotes and the accumulated revision history never enter this write path.
842
- return this.db.prepare(`SELECT r.id,r.rev,json_extract(r.payload,'$.subject') AS subject,
843
- json_extract(r.payload,'$.semanticTopic') AS topic,json_extract(r.payload,'$.keywords') AS keywords
844
- FROM revisions r WHERE r.domain=? AND r.state='confirmed' AND r.slot GLOB ?`).iterate(domain, slots);
845
- }
846
- topicSubjects(domain, scope, topic) {
847
- const canonical = normalizeLabel(topic);
848
- const subjects = new Set();
849
- for (const row of this.topicLabels(domain, scope)) {
850
- if (typeof row.topic === 'string' && normalizeLabel(row.topic) === canonical && typeof row.subject === 'string')
851
- subjects.add(normalizeLabel(row.subject));
852
- }
853
- return subjects;
854
- }
855
- topicRefs(domain, scope, topic, subject, prefix) {
856
- const label = normalizeLabel(topic);
857
- const owner = subject === undefined ? undefined : normalizeLabel(subject);
858
- const matches = [];
859
- for (const row of this.topicLabels(domain, scope)) {
860
- if (typeof row.topic !== 'string' || (row.subject === null ? undefined : normalizeLabel(String(row.subject))) !== owner)
861
- continue;
862
- const aliases = row.keywords ? parse(row.keywords) : [];
863
- if ([row.topic, ...aliases].some(name => prefix ? normalizeLabel(name).startsWith(label) : normalizeLabel(name) === label)) {
864
- matches.push({ id: String(row.id), rev: Number(row.rev) });
865
- if (prefix && matches.length === 2)
866
- break;
867
- }
868
- }
869
- return matches;
1084
+ canonicalTopicHeads(domain, scope, topic, subject) {
1085
+ return this.readMany(domain, this.searchIndex.topicRefs(domain, topic, subject, scope));
1086
+ }
1087
+ topicRefs(domain, topic, subject) {
1088
+ return this.searchIndex.topicRefs(domain, topic, subject);
870
1089
  }
871
1090
  newerSlotObservation(domain, clock, stream, seq, time) {
872
1091
  return this.maintenance.staleSlot(domain, clock, stream, seq, time) || this.db.prepare(`SELECT 1 FROM automatic_sources WHERE domain=? AND slot=? AND
@@ -936,6 +1155,8 @@ export class MemoryStore {
936
1155
  throw new StoreError('conflict');
937
1156
  let item = edit ?? original;
938
1157
  validateItem(item);
1158
+ if (p.source.fileImport && replace)
1159
+ throw new StoreError('invalid_selection');
939
1160
  const old = replace && this.read(domain, replace.id, replace.rev);
940
1161
  if (replace && (!Number.isInteger(replace.rev) || !old || usedIds.has(replace.id)))
941
1162
  throw new StoreError('conflict');
@@ -947,6 +1168,8 @@ export class MemoryStore {
947
1168
  item = { ...item, slot: old.slot };
948
1169
  }
949
1170
  if (isMemorySlot(item.slot)) {
1171
+ if (item.kind === 'fact' && item.usage === 'proactive' && !(old?.kind === 'fact' && old.usage === 'proactive'))
1172
+ throw new StoreError('fact_on_demand');
950
1173
  const owner = this.currentSlot(domain, item.slot);
951
1174
  if (owner && owner.id !== old?.id)
952
1175
  throw new StoreError('conflict');
@@ -961,7 +1184,8 @@ export class MemoryStore {
961
1184
  let family = old?.familyId;
962
1185
  if (!family && item.slot) {
963
1186
  const related = this.db
964
- .prepare('SELECT r.family ' + selectedHead + ' AND r.slot=? AND r.paths=? ORDER BY r.family LIMIT 1')
1187
+ .prepare(`SELECT r.family FROM revisions r INDEXED BY revision_current_slot CROSS JOIN heads h USING(domain,id,rev)
1188
+ WHERE r.domain=? AND r.state='confirmed' AND r.slot=? AND r.paths=? ORDER BY r.family LIMIT 1`)
965
1189
  .get(domain, item.slot, paths);
966
1190
  if (related)
967
1191
  family = String(related.family);
@@ -979,13 +1203,13 @@ export class MemoryStore {
979
1203
  const { user_quote: quote, source: _ignored, channel: _channel, ...payload } = item;
980
1204
  if (options?.channel)
981
1205
  payload.channel = options.channel;
982
- const type = !quote
1206
+ const type = p.source.origin === 'tool' && p.source.toolResult ? 'tool_result' : !quote
983
1207
  ? 'receipt'
984
1208
  : p.source.origin === 'manual' || original.user_quote !== quote
985
1209
  ? 'confirmed_wording'
986
1210
  : 'user_quote';
987
1211
  const observed = original.source && typeof original.source === 'object' ? original.source : {};
988
- const source = type === 'user_quote'
1212
+ const source = type === 'tool_result' ? p.source : type === 'user_quote'
989
1213
  ? { ...p.source, ...observed, seq: original.evidence?.seq ?? p.source.seq }
990
1214
  : {
991
1215
  storeId: p.source.storeId,
@@ -993,6 +1217,7 @@ export class MemoryStore {
993
1217
  turnId: p.turnId,
994
1218
  seq: p.source.seq,
995
1219
  origin: 'manual',
1220
+ ...(p.source.fileImport ? { fileImport: p.source.fileImport } : {}),
996
1221
  };
997
1222
  if (type !== 'user_quote')
998
1223
  delete payload.evidence;
@@ -1000,7 +1225,7 @@ export class MemoryStore {
1000
1225
  .prepare(`INSERT INTO revisions(domain,id,rev,batch,previous,family,slot,action,condition,paths,payload,
1001
1226
  confirmed,state,fingerprint,proactive) VALUES(?,?,?,?,?,?,?,?,?,?,?,?,'confirmed',?,?)`)
1002
1227
  .run(domain, ref.id, ref.rev, id, old?.rev ?? null, family, payload.slot ?? null, item.action, item.when, paths, JSON.stringify(payload), now, print, promptRole(item));
1003
- indexRevision(this.db, saved.lastInsertRowid, item);
1228
+ indexRevision(this.db, domain, saved.lastInsertRowid, item);
1004
1229
  this.db
1005
1230
  .prepare('INSERT INTO evidence(domain,id,rev,type,quote,source) VALUES(?,?,?,?,?,?)')
1006
1231
  .run(domain, ref.id, ref.rev, type, quote, JSON.stringify(source));
@@ -1039,7 +1264,60 @@ export class MemoryStore {
1039
1264
  return this.db
1040
1265
  .prepare("SELECT * FROM proposals WHERE domain=? AND session=? AND id NOT GLOB 'auto-*' ORDER BY created,id")
1041
1266
  .all(domain, session)
1042
- .map(proposalFrom);
1267
+ .map(proposalFrom).filter(visibleProposal);
1268
+ }
1269
+ /** A conversation needs the suggestion count and confirmed references, without the review payload. */
1270
+ conversationCards(domain, session) {
1271
+ this.expire(domain);
1272
+ const rows = this.db.prepare(`SELECT p.id,p.turn,p.state,json_array_length(p.items) AS count,p.receipt
1273
+ FROM proposals p WHERE p.domain=? AND p.session=? AND p.id NOT GLOB 'auto-*'
1274
+ AND p.state IN ('pending','confirmed') AND p.turn NOT IN ('history','restore','settings')
1275
+ AND json_extract(p.source,'$.sessionId')=p.session
1276
+ AND NOT EXISTS (SELECT 1 FROM file_import_entries i WHERE i.domain=p.domain AND i.proposal=p.id)
1277
+ ORDER BY p.created,p.id`).all(domain, session);
1278
+ return rows.map(row => ({
1279
+ id: String(row.id), turnId: String(row.turn), state: String(row.state), count: Number(row.count),
1280
+ entries: row.receipt ? JSON.parse(String(row.receipt)).entries.map(({ id, rev }) => ({ id, rev })) : [],
1281
+ }));
1282
+ }
1283
+ /** Current revisions a conversation can display in its turn receipts. */
1284
+ chatHeads(domain, session, receipts) {
1285
+ const refs = this.db.prepare(`SELECT h.id,h.rev
1286
+ FROM evidence e CROSS JOIN heads h USING(domain,id,rev) CROSS JOIN revisions r USING(domain,id,rev)
1287
+ WHERE e.domain=? AND json_extract(e.source,'$.sessionId')=? AND r.state='confirmed'
1288
+ AND json_extract(r.payload,'$.channel')='automatic'
1289
+ UNION SELECT h.id,h.rev
1290
+ FROM deliveries d CROSS JOIN heads h USING(domain,id,rev) CROSS JOIN revisions r USING(domain,id,rev)
1291
+ WHERE d.domain=? AND d.session=? AND r.state='confirmed' AND r.proactive=1`).all(domain, session, domain, session);
1292
+ const wanted = new Map(receipts.map(ref => [ref.id + '@' + ref.rev, ref]));
1293
+ for (const row of refs)
1294
+ wanted.set(row.id + '@' + row.rev, { id: String(row.id), rev: Number(row.rev) });
1295
+ return this.readMany(domain, [...wanted.values()]);
1296
+ }
1297
+ observesUI = false;
1298
+ uiChangeStamp(domains) {
1299
+ if (!this.observesUI) {
1300
+ // Only desktop/web readers need this connection-local clock. Temp triggers share
1301
+ // the writer's transaction (including rollback) without growing the profile database.
1302
+ this.db.exec('CREATE TEMP TABLE IF NOT EXISTS ui_domain_changes(domain TEXT PRIMARY KEY, seq INTEGER NOT NULL) WITHOUT ROWID');
1303
+ for (const table of ['heads', 'revisions', 'evidence', 'proposals', 'deliveries', 'consolidation_pairs']) {
1304
+ for (const operation of ['INSERT', 'UPDATE', 'DELETE']) {
1305
+ const row = operation === 'DELETE' ? 'OLD' : 'NEW';
1306
+ this.db.exec(`CREATE TEMP TRIGGER IF NOT EXISTS ui_${table}_${operation} AFTER ${operation} ON main.${table}
1307
+ BEGIN UPDATE ui_domain_changes SET seq=seq+1 WHERE domain=${row}.domain; END`);
1308
+ }
1309
+ }
1310
+ this.observesUI = true;
1311
+ }
1312
+ const clocks = domains.map(domain => {
1313
+ const clock = this.db.prepare('SELECT seq FROM ui_domain_changes WHERE domain=?').get(domain);
1314
+ if (clock)
1315
+ return clock.seq;
1316
+ this.db.prepare('INSERT INTO ui_domain_changes VALUES(?,0)').run(domain);
1317
+ return 0;
1318
+ });
1319
+ // External processes may use a different release. Rebuild conservatively after any external commit.
1320
+ return [this.db.prepare('PRAGMA main.data_version').get().data_version, this.enabledGeneration(), ...clocks].join('/');
1043
1321
  }
1044
1322
  revoke(domain, id, rev, session = '') {
1045
1323
  return this.tx(() => this.revokeCurrent(domain, id, rev, session));
@@ -1171,8 +1449,11 @@ export class MemoryStore {
1171
1449
  });
1172
1450
  }
1173
1451
  recordDelivery(domain, session, refs, meta = {}) {
1174
- this.tx(() => {
1175
- for (const { id, rev } of refs) {
1452
+ return this.tx(() => {
1453
+ const now = Date.now();
1454
+ const accepted = [];
1455
+ for (const ref of refs) {
1456
+ const { id, rev, viaLookup, hintOnly } = ref;
1176
1457
  // An already admitted request may contain a revision which has since been replaced.
1177
1458
  // Keep that exposure so the session can receive the correct withdrawal.
1178
1459
  const known = this.db
@@ -1180,16 +1461,71 @@ export class MemoryStore {
1180
1461
  .get(domain, id, rev);
1181
1462
  if (!known)
1182
1463
  continue;
1464
+ accepted.push(ref);
1465
+ if (this.historyDays > 0 && meta.store && meta.turn && Number.isSafeInteger(meta.step) && Number.isSafeInteger(meta.retry))
1466
+ this.audit(domain, session, hintOnly ? 'request_hint' : 'request_body', { ...meta, id, rev });
1467
+ if (hintOnly)
1468
+ continue;
1183
1469
  const first = this.db
1184
- .prepare('INSERT OR IGNORE INTO deliveries(domain,session,id,rev) VALUES(?,?,?,?)')
1185
- .run(domain, session, id, rev);
1470
+ .prepare('INSERT OR IGNORE INTO deliveries(domain,session,id,rev,last_delivered,expanded) VALUES(?,?,?,?,?,?)')
1471
+ .run(domain, session, id, rev, now, viaLookup ? 1 : 0);
1186
1472
  // Retries of an already-recorded delivery (e.g. a retried model request re-exposing the
1187
1473
  // same index) need no second audit row; `deliveries` already dedupes the exposure itself.
1188
1474
  if (first.changes)
1189
1475
  this.audit(domain, session, 'delivery', { ...meta, id, rev });
1476
+ else
1477
+ this.db.prepare(`UPDATE deliveries SET last_delivered=max(last_delivered,?), expanded=max(expanded,?)
1478
+ WHERE domain=? AND session=? AND id=? AND rev=?`).run(now, viaLookup ? 1 : 0, domain, session, id, rev);
1190
1479
  }
1480
+ return accepted;
1191
1481
  });
1192
1482
  }
1483
+ turnReceipts(domains, session, storeId, turn, throughStep, topic) {
1484
+ if (!domains.length || !Number.isSafeInteger(throughStep) || throughStep < 0 || this.historyDays === 0)
1485
+ return [];
1486
+ const cutoff = Date.now() - this.historyDays * 86_400_000;
1487
+ const rows = this.db.prepare(`SELECT domain,memory AS id,rev,json_extract(meta,'$.step') AS step,
1488
+ json_extract(meta,'$.retry') AS retry, max(event='request_hint') AS hint, max(event='request_body') AS body,
1489
+ max(event='cite') AS cited, max(event='bash_result' AND json_type(meta,'$.outcome')='integer') AS executed
1490
+ FROM audit WHERE domain IN (${domains.map(() => '?').join(',')}) AND session=?
1491
+ AND json_extract(meta,'$.store')=? AND json_extract(meta,'$.turn')=? AND json_extract(meta,'$.step')<=?
1492
+ AND ${requestEvents} AND time>? AND json_type(meta,'$.retry')='integer'
1493
+ GROUP BY step,retry,domain,memory,rev HAVING hint OR body ORDER BY step,retry,domain,memory,rev`)
1494
+ .all(...domains, session, storeId, turn, throughStep, cutoff);
1495
+ const requests = [];
1496
+ const topics = new Map();
1497
+ for (const row of rows) {
1498
+ const step = Number(row.step), retry = Number(row.retry);
1499
+ let request = requests.at(-1);
1500
+ if (!request || request.step !== step || request.retry !== retry) {
1501
+ request = { step, retry, entries: [] };
1502
+ requests.push(request);
1503
+ }
1504
+ const ref = { id: String(row.id), rev: Number(row.rev) };
1505
+ const key = [row.domain, ref.id, ref.rev].join('\u0000');
1506
+ if (row.body && topic && !topics.has(key))
1507
+ topics.set(key, topic(String(row.domain), ref));
1508
+ const label = row.body && topics.get(key);
1509
+ request.entries.push({ ...ref, hint: Boolean(row.hint) && !row.body, body: Boolean(row.body),
1510
+ cited: Boolean(row.cited), executed: Boolean(row.executed), ...(label && { topic: label }) });
1511
+ }
1512
+ return requests;
1513
+ }
1514
+ usageSignals(domain, refs) {
1515
+ if (refs && !refs.length)
1516
+ return [];
1517
+ const heads = refs ? `json_each(?) wanted CROSS JOIN heads h ON h.domain=? AND
1518
+ h.id=json_extract(wanted.value,'$.id') AND h.rev=json_extract(wanted.value,'$.rev')` : 'heads h';
1519
+ const rows = this.db.prepare(`SELECT h.id,h.rev,count(d.session) AS delivered,
1520
+ coalesce(sum(d.expanded),0) AS opened,max(d.last_delivered) AS last
1521
+ FROM ${heads} CROSS JOIN revisions r ON r.domain=h.domain AND r.id=h.id AND r.rev=h.rev
1522
+ LEFT JOIN deliveries d ON d.domain=h.domain AND d.id=h.id AND d.rev=h.rev
1523
+ WHERE h.domain=? AND r.state='confirmed' GROUP BY h.id,h.rev`).all(...(refs ? [JSON.stringify(refs), domain] : []), domain);
1524
+ return rows.map(row => ({
1525
+ id: String(row.id), rev: Number(row.rev), delivered: Number(row.delivered), opened: Number(row.opened),
1526
+ lastDelivery: row.last === null ? null : Number(row.last),
1527
+ }));
1528
+ }
1193
1529
  delivered(domain, session) {
1194
1530
  return this.db
1195
1531
  .prepare('SELECT id,rev FROM deliveries WHERE domain=? AND session=? ORDER BY id,rev')
@@ -1225,7 +1561,7 @@ export class MemoryStore {
1225
1561
  .run(domain, session, event, meta.id ?? null, meta.rev ?? null, JSON.stringify(data), Date.now(), domain);
1226
1562
  }
1227
1563
  history(domain, id) {
1228
- const query = 'SELECT seq,event,session,memory,rev,meta,time FROM audit WHERE domain=?';
1564
+ const query = "SELECT seq,event,session,memory,rev,meta,time FROM audit WHERE domain=? AND event NOT IN ('request_hint','request_body')";
1229
1565
  const rows = id === undefined
1230
1566
  ? this.db.prepare(query + ' ORDER BY seq DESC LIMIT 256').all(domain)
1231
1567
  : this.db.prepare(query + ' AND memory=? ORDER BY seq DESC LIMIT 256').all(domain, id);