dsh-memory-bond 0.0.0-stage → 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 (126) hide show
  1. package/CHANGELOG.md +10 -0
  2. package/LICENSE +21 -0
  3. package/README.md +181 -2
  4. package/README.zh-CN.md +180 -0
  5. package/SECURITY.md +29 -0
  6. package/client/memory-icon.svg +21 -0
  7. package/cordis.patch.yml +3 -0
  8. package/dist/audit.js +286 -0
  9. package/dist/automatic.js +16 -0
  10. package/dist/cache.js +40 -0
  11. package/dist/client.js +2035 -0
  12. package/dist/command-scope.js +123 -0
  13. package/dist/commands.js +156 -0
  14. package/dist/consolidation-store.js +357 -0
  15. package/dist/consolidation.js +182 -0
  16. package/dist/domain.js +245 -0
  17. package/dist/encoder.js +138 -0
  18. package/dist/export-files.js +161 -0
  19. package/dist/file-import-store.js +120 -0
  20. package/dist/file-import.js +265 -0
  21. package/dist/foreground-attempts.js +91 -0
  22. package/dist/guidance.js +242 -0
  23. package/dist/host.js +19 -0
  24. package/dist/index-policy.js +191 -0
  25. package/dist/index.js +349 -0
  26. package/dist/knowledge-hooks.js +398 -0
  27. package/dist/knowledge.js +359 -0
  28. package/dist/maintenance-episodes.js +73 -0
  29. package/dist/maintenance-import.js +92 -0
  30. package/dist/maintenance-store.js +738 -0
  31. package/dist/maintenance.js +376 -0
  32. package/dist/model-review.js +16 -0
  33. package/dist/personal.js +60 -0
  34. package/dist/policy.js +382 -0
  35. package/dist/prompt-copy.js +93 -0
  36. package/dist/proposal-receipts.js +70 -0
  37. package/dist/proposal-review.js +656 -0
  38. package/dist/propose-contract.js +38 -0
  39. package/dist/question-answers.js +176 -0
  40. package/dist/retrieval.js +126 -0
  41. package/dist/scope-narrowing.js +49 -0
  42. package/dist/search-index.js +164 -0
  43. package/dist/search-words.js +5 -0
  44. package/dist/semantic.js +157 -0
  45. package/dist/service.js +1473 -0
  46. package/dist/sharing.js +289 -0
  47. package/dist/sources.js +149 -0
  48. package/dist/store.js +1578 -0
  49. package/dist/tool-experience.js +87 -0
  50. package/dist/turn-review-store.js +159 -0
  51. package/dist/turn-review.js +459 -0
  52. package/dist/ui.js +346 -0
  53. package/dist/vector-index.js +232 -0
  54. package/docs/architecture.zh-CN.md +52 -0
  55. package/docs/benchmark.zh-CN.md +60 -0
  56. package/docs/benchmarks/repository-tasks.json +5355 -0
  57. package/docs/images/bond-memory-principle-en.svg +644 -0
  58. package/docs/images/bond-memory-principle-zh.svg +644 -0
  59. package/docs/images/bond-memory-principle.drawio +644 -0
  60. package/docs/images/memory-settings-en.png +0 -0
  61. package/docs/images/memory-settings-zh.png +0 -0
  62. package/docs/images/memory-turn-recalled-en.png +0 -0
  63. package/docs/images/memory-turn-recalled-zh.png +0 -0
  64. package/docs/images/memory-turn-saved-en.png +0 -0
  65. package/docs/images/memory-turn-saved-zh.png +0 -0
  66. package/docs/media/memory-bond-name-en.gif +0 -0
  67. package/docs/media/memory-bond-name-en.mp4 +0 -0
  68. package/docs/media/memory-bond-name-zh.gif +0 -0
  69. package/docs/media/memory-bond-name-zh.mp4 +0 -0
  70. package/locale/detail.en.md +13 -0
  71. package/locale/detail.zh.md +13 -0
  72. package/locale/en.json +345 -0
  73. package/locale/zh.json +345 -0
  74. package/native/embeddings/NOTICE.md +12 -0
  75. package/package.json +117 -4
  76. package/scripts/benchmark-bond.mjs +72 -0
  77. package/scripts/benchmark-conditions.mjs +144 -0
  78. package/scripts/benchmark-example.mjs +37 -0
  79. package/scripts/benchmark-scale.mjs +119 -0
  80. package/scripts/benchmark-scenarios.mjs +57 -0
  81. package/scripts/benchmark-tasks.mjs +244 -0
  82. package/src/audit.ts +286 -0
  83. package/src/automatic.ts +21 -0
  84. package/src/cache.ts +38 -0
  85. package/src/command-scope.ts +125 -0
  86. package/src/commands.ts +159 -0
  87. package/src/consolidation-store.ts +350 -0
  88. package/src/consolidation.ts +176 -0
  89. package/src/domain.ts +254 -0
  90. package/src/encoder.ts +142 -0
  91. package/src/export-files.ts +178 -0
  92. package/src/file-import-store.ts +139 -0
  93. package/src/file-import.ts +256 -0
  94. package/src/foreground-attempts.ts +97 -0
  95. package/src/guidance.ts +265 -0
  96. package/src/host.ts +119 -0
  97. package/src/index-policy.ts +231 -0
  98. package/src/index.ts +333 -0
  99. package/src/knowledge-hooks.ts +456 -0
  100. package/src/knowledge.ts +432 -0
  101. package/src/maintenance-episodes.ts +76 -0
  102. package/src/maintenance-import.ts +107 -0
  103. package/src/maintenance-store.ts +868 -0
  104. package/src/maintenance.ts +380 -0
  105. package/src/model-review.ts +27 -0
  106. package/src/personal.ts +68 -0
  107. package/src/policy.ts +508 -0
  108. package/src/prompt-copy.ts +99 -0
  109. package/src/proposal-receipts.ts +59 -0
  110. package/src/proposal-review.ts +614 -0
  111. package/src/propose-contract.ts +39 -0
  112. package/src/question-answers.ts +181 -0
  113. package/src/retrieval.ts +133 -0
  114. package/src/scope-narrowing.ts +58 -0
  115. package/src/search-index.ts +177 -0
  116. package/src/search-words.ts +6 -0
  117. package/src/semantic.ts +178 -0
  118. package/src/service.ts +1488 -0
  119. package/src/sharing.ts +349 -0
  120. package/src/sources.ts +150 -0
  121. package/src/store.ts +1829 -0
  122. package/src/tool-experience.ts +93 -0
  123. package/src/turn-review-store.ts +158 -0
  124. package/src/turn-review.ts +418 -0
  125. package/src/ui.ts +385 -0
  126. package/src/vector-index.ts +228 -0
@@ -0,0 +1,868 @@
1
+ import { createHash, createHmac, randomUUID } from 'node:crypto'
2
+ import { chmodSync, mkdirSync } from 'node:fs'
3
+ import { join } from 'node:path'
4
+ import { DatabaseSync } from 'node:sqlite'
5
+ import { StoreError, type DraftItem, type Proposal, type Rule, type Source } from './store.ts'
6
+ import { episodeBodyDays } from './maintenance-episodes.ts'
7
+ import { isMemorySlot } from './personal.ts'
8
+ import { indexRevision, promptRole } from './search-index.ts'
9
+
10
+ // Settled proposal receipts need their event identity. Detailed evidence belongs only to
11
+ // the erasable revision and to managed snapshots that share its deletion policy.
12
+ export const sourceDetailPaths = "'$.toolResult','$.fileImport','$.formSelection','$.scopeClarification'"
13
+
14
+ export const maintenanceSchema = `
15
+ CREATE TABLE IF NOT EXISTS history_jobs (
16
+ domain TEXT NOT NULL, stream TEXT NOT NULL, session TEXT NOT NULL, seq INTEGER NOT NULL, kind TEXT NOT NULL,
17
+ source TEXT NOT NULL, proof TEXT NOT NULL, state TEXT NOT NULL, token TEXT, deadline INTEGER, epoch INTEGER,
18
+ recipient TEXT NOT NULL, PRIMARY KEY(domain,stream,session,seq,kind)
19
+ );
20
+ CREATE TABLE IF NOT EXISTS history_cursors (
21
+ domain TEXT NOT NULL, stream TEXT NOT NULL, session TEXT NOT NULL, kind TEXT NOT NULL, seq INTEGER NOT NULL,
22
+ PRIMARY KEY(domain,stream,session,kind)
23
+ );
24
+ CREATE TABLE IF NOT EXISTS history_budget (domain TEXT NOT NULL,day TEXT NOT NULL,used INTEGER NOT NULL,PRIMARY KEY(domain,day));
25
+ CREATE TABLE IF NOT EXISTS suppressions (domain TEXT NOT NULL, key TEXT NOT NULL,PRIMARY KEY(domain,key));
26
+ CREATE TABLE IF NOT EXISTS memory_vectors (
27
+ domain TEXT NOT NULL,id TEXT NOT NULL,rev INTEGER NOT NULL,model TEXT NOT NULL,dimensions INTEGER NOT NULL,
28
+ content_hash TEXT NOT NULL,vector BLOB NOT NULL,PRIMARY KEY(domain,id,rev,model),
29
+ FOREIGN KEY(domain,id,rev) REFERENCES revisions(domain,id,rev)
30
+ );
31
+ CREATE TRIGGER IF NOT EXISTS drop_retired_vectors AFTER UPDATE OF state ON revisions WHEN NEW.state <> 'confirmed'
32
+ BEGIN DELETE FROM memory_vectors WHERE domain=NEW.domain AND id=NEW.id AND rev=NEW.rev; END`
33
+
34
+ interface Operations {
35
+ transact<T>(work: () => T): T
36
+ epoch(domain: string): number
37
+ bump(domain: string): void
38
+ list(domain: string): Rule[]
39
+ validate(domain: string, session: string, source: Source, items: DraftItem[]): void
40
+ duplicate(domain: string, item: DraftItem): boolean
41
+ fingerprint(item: DraftItem): string
42
+ draft(domain: string, session: string, source: Source, items: DraftItem[], key: string): Proposal
43
+ }
44
+ export interface HistoryInput {
45
+ source: Source
46
+ proof: string
47
+ }
48
+ export interface HistoryLease extends HistoryInput {
49
+ domain: string
50
+ recipient: string
51
+ token: string
52
+ epoch: number
53
+ task?: string
54
+ }
55
+ type SqlRow = Record<string, unknown>
56
+ const sameConsent = (a: SqlRow, b: SqlRow) =>
57
+ a.generation === b.generation && a.enabled === b.enabled && a.changed_at === b.changed_at
58
+ const hash = (values: unknown[]) => createHash('sha256').update(JSON.stringify(values)).digest('hex')
59
+ const eventKey = (s: Source, seq = s.seq) => hash(['event', s.storeId, s.sessionId, seq])
60
+ function spanKey(s: Source, item: DraftItem) {
61
+ const e = item.evidence
62
+ return e ? hash(['span', s.storeId, s.sessionId, e.seq, e.start, e.end]) : undefined
63
+ }
64
+ function meaning(item: DraftItem) {
65
+ return hash([
66
+ 'meaning',
67
+ item.kind ?? 'preference',
68
+ item.action.trim(),
69
+ item.when.trim(),
70
+ item.exceptions.trim(),
71
+ [...item.paths].sort(),
72
+ ])
73
+ }
74
+ const kind = 'project-conventions-v1'
75
+ const decode = (value: unknown) => JSON.parse(String(value))
76
+
77
+ export class MaintenanceState {
78
+ private archive: DatabaseSync
79
+ private guards: (() => void)[] = []
80
+ private db: DatabaseSync
81
+ private ops: Operations
82
+ constructor(dir: string, db: DatabaseSync, ops: Operations) {
83
+ this.db = db
84
+ this.ops = ops
85
+ const folder = join(dir, 'backups')
86
+ mkdirSync(folder, { recursive: true, mode: 0o700 })
87
+ const path = join(folder, 'projects.sqlite')
88
+ this.archive = new DatabaseSync(path)
89
+ try {
90
+ chmodSync(path, 0o600)
91
+ this.archive.exec(`PRAGMA busy_timeout=3000; PRAGMA synchronous=FULL; PRAGMA secure_delete=ON;
92
+ CREATE TABLE IF NOT EXISTS consent_events(
93
+ generation INTEGER PRIMARY KEY,enabled INTEGER NOT NULL CHECK(enabled IN (0,1)),changed_at INTEGER NOT NULL,
94
+ pending INTEGER NOT NULL DEFAULT 0 CHECK(pending IN (0,1)));
95
+ CREATE TABLE IF NOT EXISTS snapshots(domain TEXT NOT NULL,id TEXT NOT NULL,created INTEGER NOT NULL,PRIMARY KEY(domain,id));
96
+ CREATE TABLE IF NOT EXISTS entries(domain TEXT NOT NULL,backup TEXT NOT NULL,id TEXT NOT NULL,rev INTEGER NOT NULL,rule TEXT NOT NULL,
97
+ PRIMARY KEY(domain,backup,id));
98
+ CREATE INDEX IF NOT EXISTS snapshot_memory ON entries(domain,id,rev);
99
+ CREATE TABLE IF NOT EXISTS snapshot_sources(domain TEXT NOT NULL,backup TEXT NOT NULL,occurrence TEXT NOT NULL,
100
+ stream TEXT NOT NULL,seq INTEGER NOT NULL,time INTEGER,slot TEXT,id TEXT NOT NULL,rev INTEGER NOT NULL,
101
+ PRIMARY KEY(domain,backup,occurrence));
102
+ CREATE TABLE IF NOT EXISTS profile_clocks(domain TEXT NOT NULL,slot TEXT NOT NULL,stream TEXT NOT NULL,
103
+ seq INTEGER NOT NULL,time INTEGER,PRIMARY KEY(domain,slot,stream));
104
+ CREATE TABLE IF NOT EXISTS fences(domain TEXT NOT NULL,id TEXT NOT NULL,rev INTEGER NOT NULL,PRIMARY KEY(domain,id));
105
+ CREATE TABLE IF NOT EXISTS transferred_revisions(domain TEXT NOT NULL,id TEXT NOT NULL,rev INTEGER NOT NULL,
106
+ PRIMARY KEY(domain,id,rev));
107
+ CREATE TABLE IF NOT EXISTS suppression_keys(domain TEXT PRIMARY KEY,secret BLOB NOT NULL);
108
+ CREATE TABLE IF NOT EXISTS purges(domain TEXT NOT NULL,id TEXT NOT NULL,mode TEXT NOT NULL,rev INTEGER NOT NULL,
109
+ PRIMARY KEY(domain,id,mode));
110
+ CREATE TABLE IF NOT EXISTS suppressions(domain TEXT NOT NULL,key TEXT NOT NULL,PRIMARY KEY(domain,key))`)
111
+ this.cleanArchivedEpisodes()
112
+ } catch (error) {
113
+ this.archive.close()
114
+ throw error
115
+ }
116
+ }
117
+ // Consent is profile-wide and has its own lifetime. Restoring an individual project's
118
+ // snapshot must never restore the permission that happened to apply when it was taken.
119
+ // The caller holds the primary writer lock before taking the archive writer lock.
120
+ private consentTransaction<T>(work: () => T): T {
121
+ this.archive.exec('BEGIN IMMEDIATE')
122
+ try {
123
+ const result = work()
124
+ this.archive.exec('COMMIT')
125
+ return result
126
+ } catch (error) {
127
+ if (this.archive.isTransaction) this.archive.exec('ROLLBACK')
128
+ throw error
129
+ }
130
+ }
131
+
132
+ reconcileConsent(rebuiltPrimary: boolean) {
133
+ return this.consentTransaction(() => {
134
+ const current = this.db.prepare('SELECT generation,enabled,changed_at FROM memory_settings ORDER BY generation').all()
135
+ // Publishing an enable writes the archive first. A pending enable whose primary commit
136
+ // failed or was lost must be resolved as disabled before accepting a new permission.
137
+ for (const pending of this.archive.prepare('SELECT generation,changed_at FROM consent_events WHERE pending=1').all()) {
138
+ const acknowledged = current.some(e => e.generation === pending.generation && e.enabled === 1 &&
139
+ e.changed_at === pending.changed_at)
140
+ this.archive.prepare('UPDATE consent_events SET enabled=?,pending=0 WHERE generation=?')
141
+ .run(Number(acknowledged), pending.generation)
142
+ }
143
+ const archived = this.archive.prepare('SELECT generation,enabled,changed_at FROM consent_events ORDER BY generation').all()
144
+ let events = archived
145
+ if (!archived.length) {
146
+ events = current
147
+ } else if (!rebuiltPrimary) {
148
+ const length = Math.min(current.length, archived.length)
149
+ let common = 0
150
+ while (common < length && sameConsent(current[common], archived[common])) common++
151
+ if (common === length) {
152
+ if (current.length > archived.length) events = current
153
+ } else {
154
+ // Independently edited copies have incomparable permission histories. Deny capture
155
+ // from the first disputed instant and allocate a generation unused by either branch.
156
+ const at = Math.min(Number(current[common].changed_at), Number(archived[common].changed_at))
157
+ const generation = Math.max(Number(current.at(-1)!.generation), Number(archived.at(-1)!.generation)) + 1
158
+ events = archived.slice(0, common)
159
+ if (!common) events.push({ generation: 0, enabled: 0, changed_at: 0 })
160
+ events.push({ generation, enabled: 0, changed_at: at })
161
+ }
162
+ }
163
+ if (events !== archived) {
164
+ this.archive.exec('DELETE FROM consent_events')
165
+ const insert = this.archive.prepare('INSERT INTO consent_events(generation,enabled,changed_at) VALUES(?,?,?)')
166
+ for (const e of events) insert.run(e.generation, e.enabled, e.changed_at)
167
+ }
168
+ if (current.length !== events.length || events.some((e,i) => !sameConsent(e,current[i]))) {
169
+ this.db.exec('DELETE FROM memory_settings')
170
+ const insert = this.db.prepare('INSERT INTO memory_settings VALUES(?,?,?)')
171
+ for (const e of events) insert.run(e.generation, e.enabled, e.changed_at)
172
+ }
173
+ return events.at(-1)
174
+ })
175
+ }
176
+
177
+ private latestConsent() {
178
+ const primary = this.db.prepare('SELECT * FROM memory_settings ORDER BY generation DESC LIMIT 1').get()
179
+ const archived = this.archive.prepare('SELECT * FROM consent_events ORDER BY generation DESC LIMIT 1').get()
180
+ if (primary && archived && sameConsent(primary, archived)) return archived
181
+ // Another writer may be between the archive commit and primary commit or have crashed.
182
+ // Reconcile under the primary writer lock before using the permission.
183
+ return this.db.isTransaction
184
+ ? this.reconcileConsent(false)
185
+ : this.ops.transact(() => this.reconcileConsent(false))
186
+ }
187
+
188
+ consentGeneration() {
189
+ const e = this.latestConsent()
190
+ return e?.enabled === 1 ? Number(e.generation) : undefined
191
+ }
192
+
193
+ consentAt(time: number) {
194
+ const latest = this.latestConsent()
195
+ if (!latest) return false
196
+ const e = this.archive.prepare(`SELECT generation,enabled,changed_at FROM consent_events
197
+ WHERE changed_at<=? AND generation<=? ORDER BY generation DESC LIMIT 1`).get(time, latest.generation)
198
+ return e?.enabled === 1 && (e.generation === 0 || Number(e.changed_at) < time)
199
+ }
200
+
201
+ setConsent(enabled: boolean) {
202
+ // Keep this permission change independent of indexing, backup cleanup and other queued
203
+ // maintenance. A failed primary write must roll back the archive permission as well.
204
+ this.db.exec('BEGIN IMMEDIATE')
205
+ try {
206
+ const latest = this.latestConsent()
207
+ if (!latest) throw new StoreError('settings_unavailable')
208
+ const value = Number(enabled)
209
+ if (latest.enabled === value) {
210
+ this.db.exec('COMMIT')
211
+ return false
212
+ }
213
+ const generation = Number(latest.generation) + 1
214
+ const time = Math.max(Date.now(), Number(latest.changed_at))
215
+ this.db.prepare('INSERT OR REPLACE INTO memory_settings VALUES(?,?,?)').run(generation, value, time)
216
+ this.consentTransaction(() => {
217
+ this.archive.prepare('INSERT INTO consent_events(generation,enabled,changed_at,pending) VALUES(?,?,?,?)')
218
+ .run(generation, value, time, value)
219
+ })
220
+ this.db.exec('COMMIT')
221
+ if (enabled) {
222
+ // Both copies have durably acknowledged this generation. Cleanup can be retried by
223
+ // reconciliation; failing to remove a marker cannot turn an unsuccessful grant on.
224
+ try {
225
+ this.archive.prepare('UPDATE consent_events SET pending=0 WHERE generation=? AND changed_at=?').run(generation, time)
226
+ } catch { /* Reconciliation checks the primary acknowledgement. */ }
227
+ }
228
+ return true
229
+ } catch (error) {
230
+ if (this.db.isTransaction) this.db.exec('ROLLBACK')
231
+ throw error
232
+ }
233
+ }
234
+
235
+ private cleanArchivedEpisodes() {
236
+ const due = this.archive
237
+ .prepare(
238
+ `SELECT domain,id,rev FROM entries WHERE json_extract(rule,'$.kind')='episode'
239
+ AND json_extract(rule,'$.confirmedAt')<=? GROUP BY domain,id,rev`,
240
+ )
241
+ .all(Date.now() - episodeBodyDays * 86400000)
242
+ for (const row of due) {
243
+ this.archive
244
+ .prepare('DELETE FROM entries WHERE domain=? AND id=? AND rev=?')
245
+ .run(row.domain, row.id, row.rev)
246
+ this.archive
247
+ .prepare('DELETE FROM snapshot_sources WHERE domain=? AND id=? AND rev=?')
248
+ .run(row.domain, row.id, row.rev)
249
+ }
250
+ }
251
+ close() {
252
+ this.archive.close()
253
+ }
254
+ discardGuards() {
255
+ this.guards = []
256
+ }
257
+ // The archive is outside the recoverable primary DB. Publish fences durably before the
258
+ // primary commit, after all semantic checks pass. A disk failure between commits may hide
259
+ // an old backup entry, but can never grant permission to resurrect it.
260
+ flushGuards() {
261
+ if (!this.guards.length) return
262
+ this.archive.exec('BEGIN IMMEDIATE')
263
+ try {
264
+ for (const work of this.guards) work()
265
+ this.archive.exec('COMMIT')
266
+ } catch (error) {
267
+ if (this.archive.isTransaction) this.archive.exec('ROLLBACK')
268
+ throw error
269
+ } finally {
270
+ this.discardGuards()
271
+ }
272
+ }
273
+ reconcileArchive() {
274
+ // A recovered primary may predate a later withdrawal or quote deletion. Never serve its
275
+ // stale head while waiting for a user to select a newer snapshot.
276
+ const changed = new Set<string>()
277
+ for (const f of this.archive.prepare('SELECT * FROM fences').all()) {
278
+ const head = this.db
279
+ .prepare(
280
+ `SELECT h.rev FROM heads h JOIN revisions r USING(domain,id,rev) WHERE
281
+ h.domain=? AND h.id=? AND h.rev<=? AND r.state='confirmed'`,
282
+ )
283
+ .get(f.domain, f.id, f.rev)
284
+ if (!head) continue
285
+ this.retire(String(f.domain), String(f.id), Number(head.rev))
286
+ this.db
287
+ .prepare("UPDATE revisions SET state='revoked',retired=? WHERE domain=? AND id=? AND rev=?")
288
+ .run(Date.now(), f.domain, f.id, head.rev)
289
+ changed.add(String(f.domain))
290
+ }
291
+ for (const row of this.archive.prepare('SELECT domain,id,rev FROM transferred_revisions').iterate())
292
+ this.eraseTransferredRevision(String(row.domain), String(row.id), Number(row.rev))
293
+ for (const f of this.archive.prepare('SELECT * FROM purges').all()) {
294
+ const args = [f.domain, f.id, f.rev] as const
295
+ if (f.mode === 'signature') {
296
+ if (this.db.prepare('SELECT 1 FROM heads WHERE domain=? AND id=? AND rev<=?').get(...args))
297
+ this.db.prepare('DELETE FROM episode_signatures WHERE domain=? AND id=?').run(f.domain, f.id)
298
+ continue
299
+ }
300
+ for (const row of this.db
301
+ .prepare(
302
+ `SELECT e.source,e.quote,r.payload,p.source AS batch FROM evidence e
303
+ JOIN revisions r USING(domain,id,rev) JOIN proposals p ON p.domain=r.domain AND p.id=r.batch
304
+ WHERE e.domain=? AND e.id=? AND e.rev<=? AND (e.quote<>'' OR e.source<>'{}')`,
305
+ )
306
+ .all(...args))
307
+ this.blockSource(String(f.domain), row, f.mode === 'body')
308
+ const redacted = this.db
309
+ .prepare(
310
+ "UPDATE evidence SET quote='',source='{}',type='receipt' WHERE domain=? AND id=? AND rev<=? AND (quote<>'' OR source<>'{}')",
311
+ )
312
+ .run(...args)
313
+ if (f.mode === 'body')
314
+ this.db
315
+ .prepare(
316
+ "UPDATE revisions SET action='',condition='',paths='[]',slot=NULL,payload='{}',proactive=NULL,fingerprint='',retired=NULL WHERE domain=? AND id=? AND rev<=?",
317
+ )
318
+ .run(...args)
319
+ else
320
+ this.db
321
+ .prepare(
322
+ "UPDATE revisions SET payload=json_remove(payload,'$.evidence') WHERE domain=? AND id=? AND rev<=? AND json_type(payload,'$.evidence') IS NOT NULL",
323
+ )
324
+ .run(...args)
325
+ if (redacted.changes) changed.add(String(f.domain))
326
+ }
327
+ for (const domain of changed) {
328
+ for (const p of this.db
329
+ .prepare("SELECT id,source,items FROM proposals WHERE domain=? AND state='pending'")
330
+ .all(domain))
331
+ if ((decode(p.items) as DraftItem[]).some((i) => this.blockedHistory(domain, decode(p.source), i)))
332
+ this.db
333
+ .prepare("UPDATE proposals SET state='cancelled',items='[]' WHERE domain=? AND id=?")
334
+ .run(domain, String(p.id))
335
+ this.ops.bump(domain)
336
+ }
337
+ }
338
+ // A scope correction moves the source and wording of exactly one revision. A
339
+ // purge-through fence would also erase unrelated, earlier versions of that ID.
340
+ releaseTransferredRevision(domain: string, id: string, rev: number) {
341
+ this.eraseTransferredRevision(domain, id, rev)
342
+ this.guards.push(() => {
343
+ this.archive.prepare('INSERT OR IGNORE INTO transferred_revisions VALUES(?,?,?)').run(domain, id, rev)
344
+ })
345
+ }
346
+ private eraseTransferredRevision(domain: string, id: string, rev: number) {
347
+ const versions = [domain, id, rev] as const
348
+ const old = this.db.prepare(`SELECT r.batch,r.payload,p.source FROM revisions r JOIN proposals p
349
+ ON p.domain=r.domain AND p.id=r.batch WHERE r.domain=? AND r.id=? AND r.rev=? AND r.state<>'confirmed'`).get(...versions)
350
+ if (!old) return
351
+ if (old.payload !== '{}') {
352
+ this.db.prepare("UPDATE evidence SET quote='',type='receipt',source='{}' WHERE domain=? AND id=? AND rev=?").run(...versions)
353
+ this.db.prepare(`UPDATE revisions SET action='',condition='',paths='[]',slot=NULL,payload='{}',
354
+ proactive=NULL,fingerprint='',retired=NULL WHERE domain=? AND id=? AND rev=?`).run(...versions)
355
+ // retire() already sealed the source clock and replay guards before the move.
356
+ this.db.prepare('DELETE FROM automatic_sources WHERE domain=? AND id=? AND rev=?').run(...versions)
357
+ }
358
+ if (old.source === '{}') return
359
+ this.db.prepare(`UPDATE proposals SET source='{}' WHERE domain=? AND id=? AND NOT EXISTS
360
+ (SELECT 1 FROM revisions WHERE domain=? AND batch=? AND (id<>? OR rev<>?))`)
361
+ .run(domain, old.batch, domain, old.batch, id, rev)
362
+ }
363
+ forgetSignature(domain: string, id: string, rev: number) {
364
+ this.db.prepare('DELETE FROM episode_signatures WHERE domain=? AND id=?').run(domain, id)
365
+ this.purgeThrough(domain, id, 'signature', rev)
366
+ }
367
+ private purgeThrough(domain: string, id: string, mode: 'quote' | 'body' | 'signature', rev: number) {
368
+ this.guards.push(() => {
369
+ this.archive
370
+ .prepare(
371
+ `INSERT INTO purges VALUES(?,?,?,?) ON CONFLICT(domain,id,mode)
372
+ DO UPDATE SET rev=max(rev,excluded.rev)`,
373
+ )
374
+ .run(domain, id, mode, rev)
375
+ })
376
+ }
377
+ private keyed(domain: string, key: string, create: boolean) {
378
+ let secret = this.archive
379
+ .prepare('SELECT secret FROM suppression_keys WHERE domain=?')
380
+ .get(domain)?.secret
381
+ if (!(secret instanceof Uint8Array) && create) {
382
+ this.archive.prepare('INSERT OR IGNORE INTO suppression_keys VALUES(?,randomblob(32))').run(domain)
383
+ secret = this.archive.prepare('SELECT secret FROM suppression_keys WHERE domain=?').get(domain)?.secret
384
+ }
385
+ return secret instanceof Uint8Array
386
+ ? 'h1:' + createHmac('sha256', secret).update(key).digest('hex')
387
+ : undefined
388
+ }
389
+ private suppress(domain: string, key: string) {
390
+ key = this.keyed(domain, key, true)!
391
+ this.db.prepare('INSERT OR IGNORE INTO suppressions VALUES(?,?)').run(domain, key)
392
+ this.guards.push(() => {
393
+ this.archive.prepare('INSERT OR IGNORE INTO suppressions VALUES(?,?)').run(domain, key)
394
+ })
395
+ }
396
+ private suppressed(domain: string, key: string) {
397
+ const q = 'SELECT 1 FROM suppressions WHERE domain=? AND key=?'
398
+ const keyed = this.keyed(domain, key, false)
399
+ return !!(keyed && (this.db.prepare(q).get(domain, keyed) || this.archive.prepare(q).get(domain, keyed)))
400
+ }
401
+ retiredInput(domain: string, key: string) {
402
+ return this.suppressed(domain, key)
403
+ }
404
+ blockedOccurrence(domain: string, source: Source, item: DraftItem) {
405
+ const span = spanKey(source, item)
406
+ return (
407
+ this.suppressed(domain, eventKey(source, item.evidence?.seq)) ||
408
+ (!!span && this.suppressed(domain, span)) ||
409
+ this.suppressed(domain, hash(['occurrence', eventKey(source, item.evidence?.seq), meaning(item)]))
410
+ )
411
+ }
412
+ blockedHistory(domain: string, source: Source, item: DraftItem) {
413
+ return this.blockedOccurrence(domain, source, item) || this.suppressed(domain, meaning(item))
414
+ }
415
+ staleSlot(domain: string, slot: string, stream: string, seq: number, time: number | null) {
416
+ return !!this.archive
417
+ .prepare(
418
+ `SELECT 1 FROM profile_clocks WHERE domain=? AND slot=? AND
419
+ ((stream=? AND seq>?) OR (stream<>? AND (time>? OR (time=? AND stream>?)))) LIMIT 1`,
420
+ )
421
+ .get(domain, slot, stream, seq, stream, time, time, stream)
422
+ }
423
+ rejectDrafts(domain: string, s: Source, items: DraftItem[]) {
424
+ for (const item of items) {
425
+ const observed = { ...s, ...(item.source as Partial<Source> | undefined) }
426
+ const span = spanKey(observed, item)
427
+ if (span) this.suppress(domain, span)
428
+ this.suppress(domain, hash(['occurrence', eventKey(observed, item.evidence?.seq), meaning(item)]))
429
+ }
430
+ }
431
+ private revisions(domain: string, id: string, rev?: number) {
432
+ const q = `SELECT e.source,e.quote,r.payload,r.fingerprint,p.source AS batch FROM evidence e
433
+ JOIN revisions r USING(domain,id,rev) JOIN proposals p ON p.domain=r.domain AND p.id=r.batch WHERE e.domain=? AND e.id=?`
434
+ return rev === undefined
435
+ ? this.db.prepare(q).all(domain, id)
436
+ : this.db.prepare(q + ' AND r.rev=?').all(domain, id, rev)
437
+ }
438
+ private blockSource(domain: string, row: SqlRow, allowMeaning: boolean) {
439
+ const item = decode(row.payload) as DraftItem
440
+ const observed = decode(row.source) as Source
441
+ const s = observed.storeId ? observed : (decode(row.batch) as Source)
442
+ if (s.storeId) {
443
+ const span = spanKey(s, item)
444
+ if (span) this.suppress(domain, span)
445
+ else if (!item.action || s.origin !== 'manual') this.suppress(domain, eventKey(s))
446
+ if (item.action)
447
+ this.suppress(domain, hash(['occurrence', eventKey(s, item.evidence?.seq), meaning(item)]))
448
+ }
449
+ if (allowMeaning && item.action) this.suppress(domain, meaning(item))
450
+ }
451
+ retire(domain: string, id: string, rev: number) {
452
+ for (const row of this.revisions(domain, id, rev)) this.blockSource(domain, row, true)
453
+ // A duplicate can be the only occurrence that used this alias. Keep its body-free input key
454
+ // even when a backup predates that occurrence or the retired revision ages out of the database.
455
+ for (const row of this.db.prepare(`SELECT occurrence FROM automatic_sources
456
+ WHERE domain=? AND id=? AND rev=? AND occurrence GLOB 'input:*'`).iterate(domain, id, rev))
457
+ this.suppress(domain, String(row.occurrence))
458
+ for (const p of this.db
459
+ .prepare(
460
+ "SELECT id,source,items FROM proposals WHERE domain=? AND state='pending' AND idem LIKE 'history:%'",
461
+ )
462
+ .all(domain)) {
463
+ if ((decode(p.items) as DraftItem[]).some((i) => this.blockedHistory(domain, decode(p.source), i)))
464
+ this.db
465
+ .prepare("UPDATE proposals SET state='cancelled',items='[]' WHERE domain=? AND id=?")
466
+ .run(domain, String(p.id))
467
+ }
468
+ const clocks = this.db
469
+ .prepare(
470
+ `SELECT slot,stream,max(seq) AS seq,max(time) AS time FROM automatic_sources
471
+ WHERE domain=? AND id=? AND rev=? AND slot IS NOT NULL GROUP BY slot,stream`,
472
+ )
473
+ .all(domain, id, rev)
474
+ this.guards.push(() => {
475
+ for (const clock of clocks)
476
+ this.archive
477
+ .prepare(
478
+ `INSERT INTO profile_clocks VALUES(?,?,?,?,?)
479
+ ON CONFLICT(domain,slot,stream) DO UPDATE SET seq=max(seq,excluded.seq),
480
+ time=CASE WHEN time IS NULL OR excluded.time>time THEN excluded.time ELSE time END`,
481
+ )
482
+ .run(domain, clock.slot, clock.stream, clock.seq, clock.time)
483
+ this.archive
484
+ .prepare('DELETE FROM snapshot_sources WHERE domain=? AND id=? AND rev<=?')
485
+ .run(domain, id, rev)
486
+ this.archive
487
+ .prepare(
488
+ 'INSERT INTO fences VALUES(?,?,?) ON CONFLICT(domain,id) DO UPDATE SET rev=max(fences.rev,excluded.rev)',
489
+ )
490
+ .run(domain, id, rev)
491
+ this.archive.prepare('DELETE FROM entries WHERE domain=? AND id=? AND rev<=?').run(domain, id, rev)
492
+ })
493
+ }
494
+ hasRetainedQuote(domain: string, id: string): boolean {
495
+ const quote = this.db.prepare("SELECT 1 FROM evidence WHERE domain=? AND id=? AND (quote<>'' OR type='tool_result') LIMIT 1")
496
+ if (quote.get(domain, id)) return true
497
+ return !!this.archive
498
+ .prepare("SELECT 1 FROM entries WHERE domain=? AND id=? AND (json_extract(rule,'$.user_quote')<>'' OR json_extract(rule,'$.quoteType')='tool_result') LIMIT 1")
499
+ .get(domain, id)
500
+ }
501
+ suppressQuotes(domain: string, id: string) {
502
+ const head = this.db.prepare('SELECT rev FROM heads WHERE domain=? AND id=?').get(domain, id)
503
+ if (head) this.purgeThrough(domain, id, 'quote', Number(head.rev))
504
+ for (const row of this.revisions(domain, id)) this.blockSource(domain, row, false)
505
+ this.guards.push(() => {
506
+ for (const row of this.archive
507
+ .prepare('SELECT backup,rule FROM entries WHERE domain=? AND id=?')
508
+ .all(domain, id)) {
509
+ const rule: Rule = decode(row.rule)
510
+ rule.user_quote = ''
511
+ rule.quoteType = 'receipt'
512
+ delete rule.evidence
513
+ this.archive
514
+ .prepare('UPDATE entries SET rule=? WHERE domain=? AND backup=? AND id=?')
515
+ .run(JSON.stringify({ ...rule, source: {} }), domain, String(row.backup), id)
516
+ }
517
+ })
518
+ }
519
+ expireEpisode(domain: string, id: string, rev: number) {
520
+ this.retire(domain, id, rev)
521
+ for (const raw of this.db
522
+ .prepare("SELECT id,source,items FROM proposals WHERE domain=? AND state='pending'")
523
+ .all(domain)) {
524
+ const s = decode(raw.source) as Source
525
+ if (
526
+ (decode(raw.items) as DraftItem[]).some(
527
+ (item) =>
528
+ (item.replace as { id?: string } | undefined)?.id === id || this.blockedHistory(domain, s, item),
529
+ )
530
+ )
531
+ this.db
532
+ .prepare("UPDATE proposals SET items='[]',state='cancelled' WHERE domain=? AND id=?")
533
+ .run(domain, String(raw.id))
534
+ }
535
+ const from = this.db
536
+ .prepare('SELECT batch FROM revisions WHERE domain=? AND id=? AND rev=?')
537
+ .get(domain, id, rev)
538
+ if (
539
+ from &&
540
+ !this.db
541
+ .prepare('SELECT 1 FROM revisions WHERE domain=? AND batch=? AND (id<>? OR rev<>?)')
542
+ .get(domain, from.batch, id, rev)
543
+ ) {
544
+ this.db
545
+ .prepare("UPDATE proposals SET source='{}',idem=id WHERE domain=? AND id=?")
546
+ .run(domain, from.batch)
547
+ }
548
+ }
549
+ erase(domain: string, id: string, rev: number) {
550
+ this.purgeThrough(domain, id, 'body', rev)
551
+ for (const row of this.revisions(domain, id)) this.blockSource(domain, row, true)
552
+ this.retire(domain, id, rev)
553
+ this.db
554
+ .prepare("UPDATE evidence SET source='{}',quote='',type='receipt' WHERE domain=? AND id=?")
555
+ .run(domain, id)
556
+ this.db
557
+ .prepare(
558
+ "UPDATE revisions SET action='',condition='',paths='[]',payload='{}',proactive=NULL,slot=NULL,fingerprint='',retired=NULL WHERE domain=? AND id=?",
559
+ )
560
+ .run(domain, id)
561
+ this.db.prepare('DELETE FROM memory_vectors WHERE domain=? AND id=?').run(domain, id)
562
+ // A queued draft can refer to an older revision's exact utterance even after a correction.
563
+ for (const row of this.db
564
+ .prepare("SELECT id,source,items FROM proposals WHERE domain=? AND state='pending'")
565
+ .all(domain)) {
566
+ const s = decode(row.source)
567
+ if (
568
+ (decode(row.items) as DraftItem[]).some(
569
+ (i) => this.blockedOccurrence(domain, s, i) || this.suppressed(domain, meaning(i)),
570
+ )
571
+ )
572
+ this.db
573
+ .prepare("UPDATE proposals SET items='[]',state='cancelled' WHERE domain=? AND id=?")
574
+ .run(domain, String(row.id))
575
+ }
576
+ }
577
+ backup(domain: string) {
578
+ return this.ops.transact(() => {
579
+ const id = 'backup-' + randomUUID(),
580
+ rules = this.ops.list(domain)
581
+ this.guards.push(() => {
582
+ this.archive.prepare('INSERT INTO snapshots VALUES(?,?,?)').run(domain, id, Date.now())
583
+ const save = this.archive.prepare('INSERT INTO entries VALUES(?,?,?,?,?)')
584
+ for (const rule of rules) {
585
+ if (this.fenced(domain, rule.id, rule.rev)) continue
586
+ save.run(domain, id, rule.id, rule.rev, JSON.stringify(rule))
587
+ for (const s of this.db
588
+ .prepare('SELECT * FROM automatic_sources WHERE domain=? AND id=? AND rev=?')
589
+ .all(domain, rule.id, rule.rev))
590
+ this.archive
591
+ .prepare('INSERT INTO snapshot_sources VALUES(?,?,?,?,?,?,?,?,?)')
592
+ .run(domain, id, s.occurrence, s.stream, s.seq, s.time, s.slot, rule.id, rule.rev)
593
+ }
594
+ })
595
+ return { id, entries: rules.filter((r) => !this.fenced(domain, r.id, r.rev)).length }
596
+ })
597
+ }
598
+ private fenced(domain: string, id: string, rev: number) {
599
+ return !!this.archive
600
+ .prepare('SELECT 1 FROM fences WHERE domain=? AND id=? AND rev>=?')
601
+ .get(domain, id, rev)
602
+ }
603
+ restore(domain: string, id: string, session: string) {
604
+ return this.ops.transact(() => {
605
+ this.cleanArchivedEpisodes()
606
+ if (!this.archive.prepare('SELECT 1 FROM snapshots WHERE domain=? AND id=?').get(domain, id))
607
+ throw new StoreError('not_found')
608
+ const rows = this.archive
609
+ .prepare('SELECT rule FROM entries WHERE domain=? AND backup=?')
610
+ .all(domain, id)
611
+ this.db.prepare('INSERT OR IGNORE INTO memory_domains(domain) VALUES(?)').run(domain)
612
+ let restored = 0,
613
+ skipped = 0
614
+ for (const row of rows) {
615
+ const r = decode(row.rule) as Rule
616
+ const prior = this.db.prepare('SELECT rev FROM heads WHERE domain=? AND id=?').get(domain, r.id)
617
+ const protectedHead =
618
+ prior && (Number(prior.rev) >= r.rev || !this.fenced(domain, r.id, Number(prior.rev)))
619
+ if (
620
+ this.fenced(domain, r.id, r.rev) ||
621
+ protectedHead ||
622
+ this.ops.duplicate(domain, r) ||
623
+ (isMemorySlot(r.slot) && this.ops.list(domain).some((x) => x.slot === r.slot))
624
+ ) {
625
+ skipped++
626
+ continue
627
+ }
628
+ const {
629
+ id: memory,
630
+ domainId: _domainId,
631
+ rev,
632
+ familyId,
633
+ confirmedAt,
634
+ pinned,
635
+ source,
636
+ quoteType,
637
+ user_quote,
638
+ ...payload
639
+ } = r
640
+ const batch = 'auto-' + randomUUID(),
641
+ receipt = JSON.stringify({ state: 'confirmed', entries: [{ id: memory, rev }] })
642
+ this.db
643
+ .prepare(
644
+ `INSERT INTO proposals(domain,id,session,turn,source,items,created,rev,epoch,digest,idem,state,receipt)
645
+ VALUES(?,?,?,'restore',json_remove(?,${sourceDetailPaths}),'[]',?,1,?,'',?,'confirmed',?)`,
646
+ )
647
+ .run(
648
+ domain,
649
+ batch,
650
+ session,
651
+ JSON.stringify(source),
652
+ Date.now(),
653
+ this.ops.epoch(domain),
654
+ batch,
655
+ receipt,
656
+ )
657
+ const saved = this.db
658
+ .prepare(
659
+ `INSERT INTO revisions(domain,id,rev,batch,family,slot,action,condition,paths,payload,confirmed,state,fingerprint,proactive)
660
+ VALUES(?,?,?,?,?,?,?,?,?,?,?,'confirmed',?,?)`,
661
+ )
662
+ .run(
663
+ domain,
664
+ memory,
665
+ rev,
666
+ batch,
667
+ familyId,
668
+ r.slot ?? null,
669
+ r.action,
670
+ r.when,
671
+ JSON.stringify(r.paths),
672
+ JSON.stringify(payload),
673
+ confirmedAt,
674
+ this.ops.fingerprint(r),
675
+ promptRole(r),
676
+ )
677
+ indexRevision(this.db, domain, saved.lastInsertRowid, r)
678
+ this.db
679
+ .prepare('INSERT INTO evidence VALUES(?,?,?,?,?,?)')
680
+ .run(domain, memory, rev, quoteType, user_quote, JSON.stringify(source))
681
+ this.db
682
+ .prepare(
683
+ 'INSERT INTO heads VALUES(?,?,?,?) ON CONFLICT(domain,id) DO UPDATE SET rev=excluded.rev,pinned=excluded.pinned',
684
+ )
685
+ .run(domain, memory, rev, +pinned)
686
+ this.db
687
+ .prepare(
688
+ "INSERT INTO audit(domain,session,event,memory,rev,meta,time) VALUES(?,?,'restore',?,?,'{}',?)",
689
+ )
690
+ .run(domain, session, memory, rev, Date.now())
691
+ for (const s of this.archive
692
+ .prepare('SELECT * FROM snapshot_sources WHERE domain=? AND backup=? AND id=? AND rev=?')
693
+ .all(domain, id, memory, rev))
694
+ this.db
695
+ .prepare('INSERT OR IGNORE INTO automatic_sources VALUES(?,?,?,?,?,?,?,?)')
696
+ .run(domain, s.occurrence, s.stream, s.seq, s.time, s.slot, memory, rev)
697
+ restored++
698
+ }
699
+ if (restored) this.ops.bump(domain)
700
+ return { restored, skipped }
701
+ })
702
+ }
703
+ cursor(domain: string, stream: string, session: string) {
704
+ return Number(
705
+ this.db
706
+ .prepare('SELECT seq FROM history_cursors WHERE domain=? AND stream=? AND session=? AND kind=?')
707
+ .get(domain, stream, session, kind)?.seq ?? -1,
708
+ )
709
+ }
710
+ enqueue(
711
+ domain: string,
712
+ stream: string,
713
+ session: string,
714
+ events: readonly HistoryInput[],
715
+ lastBinding: number,
716
+ recipient: string,
717
+ task = kind,
718
+ ) {
719
+ return this.ops.transact(() => {
720
+ const previous = this.db
721
+ .prepare('SELECT seq FROM history_cursors WHERE domain=? AND stream=? AND session=? AND kind=?')
722
+ .get(domain, stream, session, task)
723
+ if (lastBinding <= Number(previous?.seq ?? -1)) return 0
724
+ let inserted = 0
725
+ this.db.prepare('INSERT OR IGNORE INTO memory_domains(domain) VALUES(?)').run(domain)
726
+ for (const { source, proof } of events) {
727
+ if (
728
+ source.storeId !== stream ||
729
+ source.sessionId !== session ||
730
+ source.origin !== 'user' ||
731
+ !proof ||
732
+ !Number.isSafeInteger(source.seq)
733
+ )
734
+ throw new StoreError('invalid_source')
735
+ inserted += Number(
736
+ this.db
737
+ .prepare(
738
+ `INSERT OR IGNORE INTO history_jobs(domain,stream,session,seq,kind,source,proof,state,recipient)
739
+ VALUES(?,?,?,?,?,?,?,'queued',?)`,
740
+ )
741
+ .run(domain, stream, session, source.seq, task, JSON.stringify(source), proof, recipient).changes,
742
+ )
743
+ }
744
+ this.db
745
+ .prepare(
746
+ `INSERT INTO history_cursors VALUES(?,?,?,?,?) ON CONFLICT(domain,stream,session,kind)
747
+ DO UPDATE SET seq=max(history_cursors.seq,excluded.seq)`,
748
+ )
749
+ .run(domain, stream, session, task, lastBinding)
750
+ return inserted
751
+ })
752
+ }
753
+ claim(
754
+ domain: string,
755
+ stream: string,
756
+ session: string,
757
+ recipient: string,
758
+ budget: number | undefined,
759
+ now = Date.now(),
760
+ task = kind,
761
+ ): HistoryLease | undefined {
762
+ return this.ops.transact(() => {
763
+ const row = this.db
764
+ .prepare(
765
+ `SELECT source,proof FROM history_jobs WHERE domain=? AND stream=? AND session=? AND kind=? AND
766
+ (state='queued' OR (state='leased' AND deadline<=?)) ORDER BY seq LIMIT 1`,
767
+ )
768
+ .get(domain, stream, session, task, now)
769
+ if (!row) return
770
+ if (budget !== undefined) {
771
+ if (!Number.isSafeInteger(budget) || budget <= 0) return
772
+ const day = new Date(now).toISOString().slice(0, 10)
773
+ if (
774
+ Number(
775
+ this.db.prepare('SELECT used FROM history_budget WHERE domain=? AND day=?').get(domain, day)
776
+ ?.used ?? 0,
777
+ ) >= budget
778
+ )
779
+ return
780
+ this.db
781
+ .prepare(
782
+ 'INSERT INTO history_budget VALUES(?,?,1) ON CONFLICT(domain,day) DO UPDATE SET used=used+1',
783
+ )
784
+ .run(domain, day)
785
+ }
786
+ const source = decode(row.source) as Source,
787
+ token = randomUUID(),
788
+ epoch = this.ops.epoch(domain)
789
+ this.db
790
+ .prepare(
791
+ "UPDATE history_jobs SET state='leased',recipient=?,token=?,deadline=?,epoch=? WHERE domain=? AND stream=? AND session=? AND seq=? AND kind=?",
792
+ )
793
+ .run(recipient, token, now + 60000, epoch, domain, stream, session, source.seq, task)
794
+ return { domain, source, proof: String(row.proof), epoch, recipient, token, task }
795
+ })
796
+ }
797
+ defer(lease: HistoryLease) {
798
+ this.db.prepare(`UPDATE history_jobs SET state='queued',token=NULL,deadline=NULL
799
+ WHERE domain=? AND stream=? AND session=? AND seq=? AND kind=? AND token=? AND state='leased'`)
800
+ .run(lease.domain, lease.source.storeId, lease.source.sessionId, lease.source.seq, lease.task ?? kind, lease.token)
801
+ }
802
+ complete(lease: HistoryLease, proof: string | undefined, candidates: DraftItem[], now = Date.now()) {
803
+ return this.ops.transact(() => {
804
+ const { domain, source, token, recipient } = lease
805
+ const task = lease.task ?? kind
806
+ const args = [domain, source.storeId, source.sessionId, source.seq, task, token] as const
807
+ const where = "domain=? AND stream=? AND session=? AND seq=? AND kind=? AND token=? AND state='leased'"
808
+ const row = this.db
809
+ .prepare('SELECT proof,epoch,deadline,recipient FROM history_jobs WHERE ' + where)
810
+ .get(...args)
811
+ if (!row || Number(row.deadline) <= now) return { state: 'stale' as const }
812
+ let card: Proposal | undefined
813
+ if (
814
+ proof === row.proof &&
815
+ row.epoch === this.ops.epoch(domain) &&
816
+ row.recipient === recipient &&
817
+ !this.db
818
+ .prepare('SELECT 1 FROM proposals WHERE domain=? AND idem=?')
819
+ .get(domain, 'history:' + eventKey(source))
820
+ ) {
821
+ const seen = new Set<string>()
822
+ const items = candidates.filter((item) => {
823
+ const key = meaning(item)
824
+ const target = item.replace as { id: string; rev: number } | undefined
825
+ if (
826
+ target &&
827
+ !this.db
828
+ .prepare(
829
+ `SELECT 1 FROM heads h JOIN revisions r USING(domain,id,rev)
830
+ WHERE h.domain=? AND h.id=? AND h.rev=? AND r.state='confirmed'`,
831
+ )
832
+ .get(domain, target.id, target.rev)
833
+ )
834
+ return false
835
+ // A still-open review, including a human revision card, owns its source until settled.
836
+ if (
837
+ this.db
838
+ .prepare(
839
+ `SELECT 1 FROM proposals p WHERE domain=? AND state='pending' AND
840
+ json_extract(p.source,'$.storeId')=? AND json_extract(p.source,'$.sessionId')=? AND
841
+ (json_extract(p.source,'$.seq')=? OR EXISTS (SELECT 1 FROM json_each(p.items) i
842
+ WHERE json_extract(i.value,'$.evidence.seq')=?)) LIMIT 1`,
843
+ )
844
+ .get(domain, source.storeId, source.sessionId, source.seq, source.seq)
845
+ )
846
+ return false
847
+ if (
848
+ seen.has(key) ||
849
+ this.ops.duplicate(domain, item) ||
850
+ this.blockedOccurrence(domain, source, item) ||
851
+ this.suppressed(domain, key)
852
+ )
853
+ return false
854
+ seen.add(key)
855
+ return true
856
+ })
857
+ if (items.length) {
858
+ this.ops.validate(domain, recipient, source, items)
859
+ card = this.ops.draft(domain, recipient, source, items, 'history:' + eventKey(source))
860
+ }
861
+ }
862
+ this.db
863
+ .prepare("UPDATE history_jobs SET state='done',token=NULL,deadline=NULL WHERE " + where)
864
+ .run(...args)
865
+ return card ? { state: 'pending' as const, id: card.id } : { state: 'skipped' as const }
866
+ })
867
+ }
868
+ }