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
@@ -1,10 +1,12 @@
1
+ import { prompts } from './prompt-copy.ts'
1
2
  import { randomUUID } from 'node:crypto'
2
- import { relative } from 'node:path'
3
3
  import { bashScope } from './command-scope.ts'
4
- import { type AccessDomain } from './domain.ts'
5
- import { isKnowledge, knowledgeValid, recordSuccess, runbookBasis } from './knowledge.ts'
4
+ import { originalBashCall } from './tool-experience.ts'
5
+ import { projectRelative, type AccessDomain } from './domain.ts'
6
+ import { isKnowledge, knowledgeValid, recordSuccess, runbookBasis, type AnchorCache } from './knowledge.ts'
6
7
  import {
7
8
  messageText,
9
+ registerConditionalTool,
8
10
  type Agent,
9
11
  type Host,
10
12
  type Execution,
@@ -15,7 +17,7 @@ import {
15
17
  import type { ProjectMemory } from './service.ts'
16
18
  import type { Ref, Rule } from './store.ts'
17
19
 
18
- type Lookup = (agent: Agent, domain: AccessDomain, call: string, refs: Ref[]) => void
20
+ type Lookup = (agent: Agent, domain: AccessDomain, call: string, rows: (Ref & { action: string })[]) => void
19
21
  interface Ticket {
20
22
  generation: number
21
23
  scope: string
@@ -66,7 +68,7 @@ function issue(memory: ProjectMemory, agent: Agent, d: AccessDomain, position: s
66
68
  content: [
67
69
  {
68
70
  type: 'text',
69
- text: '如需查阅本次相关的项目知识,可调用 project_memory_ticket,参数 ticket 为 ' + ticket + '。',
71
+ text: prompts[memory.promptLanguage(agent)].ticketOffer + ticket,
70
72
  },
71
73
  ],
72
74
  }
@@ -115,7 +117,7 @@ export function readTicket(
115
117
  agent,
116
118
  d,
117
119
  call,
118
- rows.map(({ id, rev }) => ({ id, rev })),
120
+ rows,
119
121
  )
120
122
  memory.store.audit(d.id, agent.id, 'ticket_read', { call, outcome: rows.length })
121
123
  return { items: rows }
@@ -129,6 +131,7 @@ interface Invocation {
129
131
  workdir: string
130
132
  revisions: { ref: Ref; basis: string }[]
131
133
  rawExit?: number
134
+ evidence?: { callSeq: number; turnStart: number; storeId: string }
132
135
  episodes: Ref[]
133
136
  }
134
137
  function invocation(memory: ProjectMemory, exec: Execution): Invocation | undefined {
@@ -151,7 +154,7 @@ function invocation(memory: ProjectMemory, exec: Execution): Invocation | undefi
151
154
  d,
152
155
  command: scope.command,
153
156
  cwd: scope.cwd,
154
- workdir: relative(d.root, scope.cwd) || '.',
157
+ workdir: projectRelative(d.root, scope.cwd) || '.',
155
158
  revisions: [],
156
159
  episodes: [],
157
160
  }
@@ -186,7 +189,7 @@ function exitStatus(result: { isError?: boolean; value?: unknown }, invocation:
186
189
  return Number(value.exitCode)
187
190
  }
188
191
 
189
- function guardMatches(row: Rule, item: Invocation) {
192
+ function guardMatches(row: Rule, item: Invocation, anchors: AnchorCache) {
190
193
  if (
191
194
  !isKnowledge(row) ||
192
195
  row.kind !== 'guard' ||
@@ -194,14 +197,22 @@ function guardMatches(row: Rule, item: Invocation) {
194
197
  )
195
198
  return false
196
199
  const match = row.knowledge?.match
197
- return match?.command === item.command && match.workdir === item.workdir && knowledgeValid(item.d, row).ok
200
+ return match?.command === item.command && match.workdir === item.workdir && knowledgeValid(item.d, row, anchors).ok
198
201
  }
199
202
 
200
- export function registerKnowledge(ctx: Host, memory: ProjectMemory, lookup?: Lookup) {
203
+ export function registerKnowledge(ctx: Host, memory: ProjectMemory, lookup?: Lookup,
204
+ receipts?: {
205
+ executed(exec: Execution, command: string, cwd: string, exitCode: number): void
206
+ blocked(agent: Agent, domain: AccessDomain, call: string, ref: Ref, reason: string): void
207
+ }) {
201
208
  // Guard is called only after native ask/cancel/deny resolution. Returning undefined can never allow a denied call.
202
- const tools = ctx.tools as Host['tools'] & { guard(fn: (exec: Execution) => string | undefined): unknown }
203
209
  const attempts = new WeakMap<Agent, Map<string, Invocation>>()
204
210
  ctx.on('session/event', (session: Session, event: HostEvent) => {
211
+ if (event.type === 'turn/end') {
212
+ const agent = ctx.agents.get(session.id)
213
+ if (agent?.session === session) memory.bashEvidence.endTurn(agent)
214
+ return
215
+ }
205
216
  if (
206
217
  event.type !== 'tool/call' ||
207
218
  event.data.name !== 'bash' ||
@@ -220,8 +231,9 @@ export function registerKnowledge(ctx: Host, memory: ProjectMemory, lookup?: Loo
220
231
  const item = invocation(memory, { agent, name: 'bash', arguments: args, callId: event.data.callId })
221
232
  if (!item) return
222
233
  // A downstream ask/cancel/deny may prevent the monotonic guard from ever running.
223
- for (const row of memory.store.list(item.d.id)) {
224
- if (guardMatches(row, item))
234
+ const anchors: AnchorCache = new Map()
235
+ for (const row of memory.store.commandCandidates(item.d.id, item.command, item.workdir, 'attempt')) {
236
+ if (guardMatches(row, item, anchors))
225
237
  memory.store.audit(item.d.id, agent.id, 'guard_attempt', {
226
238
  id: row.id,
227
239
  rev: row.rev,
@@ -230,22 +242,30 @@ export function registerKnowledge(ctx: Host, memory: ProjectMemory, lookup?: Loo
230
242
  })
231
243
  }
232
244
  })
233
- tools.guard((exec) => {
245
+ ctx.tools.guard((exec) => {
234
246
  const item = invocation(memory, exec)
235
247
  if (!item || !exec.agent) return
236
248
  let calls = attempts.get(exec.agent)
237
249
  if (!calls) attempts.set(exec.agent, (calls = new Map()))
238
250
  calls.set(exec.callId, item)
239
251
  if (calls.size > 128) calls.delete(calls.keys().next().value!)
252
+ if (exec.agent.session.header.origin !== 'subagent') {
253
+ try {
254
+ memory.rootDomain(exec.agent, true)
255
+ const call = originalBashCall(exec.agent, exec.callId)
256
+ if (call) item.evidence = { ...call, storeId: memory.storeId(exec.agent.session) }
257
+ } catch { /* A read-only session cannot offer a memory proposal. */ }
258
+ }
240
259
  try {
241
260
  const runbookMatches: Invocation['revisions'] = []
242
- for (const row of memory.store.list(item.d.id)) {
261
+ const anchors: AnchorCache = new Map()
262
+ for (const row of memory.store.commandCandidates(item.d.id, item.command, item.workdir, 'guard')) {
243
263
  if (!isKnowledge(row)) continue
244
264
  if (
245
265
  row.kind === 'runbook' &&
246
266
  row.knowledge?.steps?.verify === item.command &&
247
267
  row.knowledge.steps.workdir === item.workdir &&
248
- knowledgeValid(item.d, row).ok
268
+ knowledgeValid(item.d, row, anchors).ok
249
269
  ) {
250
270
  runbookMatches.push({ ref: { id: row.id, rev: row.rev }, basis: runbookBasis(row) })
251
271
  }
@@ -253,13 +273,20 @@ export function registerKnowledge(ctx: Host, memory: ProjectMemory, lookup?: Loo
253
273
  row.kind === 'episode' &&
254
274
  row.knowledge?.failure?.command === item.command &&
255
275
  row.knowledge.failure.workdir === item.workdir &&
256
- knowledgeValid(item.d, row).ok
276
+ knowledgeValid(item.d, row, anchors).ok
257
277
  )
258
278
  item.episodes.push({ id: row.id, rev: row.rev })
259
- if (!guardMatches(row, item)) continue
279
+ if (!guardMatches(row, item, anchors)) continue
260
280
  const record = { id: row.id, rev: row.rev, call: exec.callId }
261
- memory.store.audit(item.d.id, exec.agent.id, 'guard_block', record)
262
- return '用户确认的项目禁令 [' + row.id + '@' + row.rev + ']:' + row.action
281
+ const reason = prompts[memory.promptLanguage(exec.agent)].guard + ' [' + row.id + '@' + row.rev + '] ' + row.action
282
+ try {
283
+ memory.store.audit(item.d.id, exec.agent.id, 'guard_block', record)
284
+ receipts?.blocked(exec.agent, item.d, exec.callId, { id: row.id, rev: row.rev }, reason)
285
+ } catch (error) {
286
+ // Receipt persistence cannot turn a denial into permission to dispatch.
287
+ ctx.logger.warn('项目记忆无法记录本次守卫回执:' + String(error))
288
+ }
289
+ return reason
263
290
  }
264
291
  // A (verify, workdir) signature shared by more than one runbook cannot be
265
292
  // attributed to either from one real run, so this run credits neither.
@@ -296,13 +323,14 @@ export function registerKnowledge(ctx: Host, memory: ProjectMemory, lookup?: Loo
296
323
  item.rawExit = code
297
324
  if (code === undefined || code === 0) return decision
298
325
  try {
299
- const rows = memory.store.list(item.d.id).filter((row) => {
326
+ const anchors: AnchorCache = new Map()
327
+ const rows = memory.store.commandCandidates(item.d.id, item.command, item.workdir, 'failure').filter((row) => {
300
328
  if (!isKnowledge(row) || ['episode', 'guard'].includes(row.kind)) return false
301
329
  const trigger = row.knowledge?.trigger
302
330
  return (
303
331
  trigger?.command === item.command &&
304
332
  trigger.workdir === item.workdir &&
305
- knowledgeValid(item.d, row).ok
333
+ knowledgeValid(item.d, row, anchors).ok
306
334
  )
307
335
  })
308
336
  const message = issue(memory, exec.agent, item.d, 'post:' + exec.callId, rows)
@@ -324,6 +352,19 @@ export function registerKnowledge(ctx: Host, memory: ProjectMemory, lookup?: Loo
324
352
  attempts.get(exec.agent)?.delete(exec.callId)
325
353
  const code = item && exitStatus(result, item)
326
354
  if (!item || code === undefined || item.rawExit !== code) return
355
+ try {
356
+ receipts?.executed(exec, item.command, item.cwd, code)
357
+ } catch (error) {
358
+ ctx.logger.warn('项目记忆无法记录本次执行回执:' + String(error))
359
+ }
360
+ if (item.evidence) {
361
+ try {
362
+ const domain = memory.rootDomain(exec.agent, true)
363
+ memory.bashEvidence.observe(exec.agent, exec.callId, {
364
+ ...item.evidence, domain, generation: item.generation, command: item.command, cwd: item.cwd, workdir: item.workdir, exitCode: code,
365
+ })
366
+ } catch { /* A read-only session cannot offer a memory proposal. */ }
367
+ }
327
368
  if (code !== 0) {
328
369
  const delegated = exec.agent.session.header.origin === 'subagent'
329
370
  const root: Agent | undefined = delegated ? ctx.get('subagents')?.rootOf(exec.agent) : exec.agent
@@ -370,18 +411,19 @@ export function registerKnowledge(ctx: Host, memory: ProjectMemory, lookup?: Loo
370
411
  const decision = await next()
371
412
  if (decision.kind !== 'enter' || signal?.aborted || !agent) return decision
372
413
  if (memory.assistantGeneration() === undefined) return decision
373
- const direct = (decision.messages as Message[]).filter((m) => m.source?.kind === 'user')
414
+ const direct = (decision.messages as Message[]).filter(m => m.source?.kind === 'user').map(messageText)
374
415
  if (!direct.length) return decision
375
416
  const d = memory.domain(agent)
376
417
  if (!d || d.id === memory.personal.id) return decision
377
418
  try {
378
- const rows = memory.store.list(d.id).filter((row) => {
419
+ const anchors: AnchorCache = new Map()
420
+ const rows = memory.store.messageCandidates(d.id, direct).filter((row) => {
379
421
  if (!isKnowledge(row) || ['episode', 'guard'].includes(row.kind)) return false
380
422
  const trigger = row.knowledge?.trigger?.text
381
423
  return (
382
424
  !!trigger &&
383
- direct.some((message) => messageText(message).includes(trigger)) &&
384
- knowledgeValid(d, row).ok
425
+ direct.some(message => message.includes(trigger)) &&
426
+ knowledgeValid(d, row, anchors).ok
385
427
  )
386
428
  })
387
429
  const hint = issue(memory, agent, d, 'pre:' + turn + '/' + step, rows)
@@ -395,9 +437,9 @@ export function registerKnowledge(ctx: Host, memory: ProjectMemory, lookup?: Loo
395
437
  },
396
438
  { prepend: true },
397
439
  )
398
- ctx.tools.register({
440
+ registerConditionalTool(ctx, {
399
441
  name: 'project_memory_ticket',
400
- description: '按本步票据显式查阅仍然适用的项目知识。',
442
+ description: prompts[memory.promptLanguage()].ticket,
401
443
  parameters: {
402
444
  type: 'object',
403
445
  properties: { ticket: { type: 'string' } },
@@ -410,5 +452,5 @@ export function registerKnowledge(ctx: Host, memory: ProjectMemory, lookup?: Loo
410
452
  exec.agent ? readTicket(memory, exec.agent, args.ticket, exec.callId, lookup) : { items: [] },
411
453
  )
412
454
  },
413
- }, { when: () => memory.assistantGeneration() !== undefined })
455
+ }, () => memory.assistantGeneration() !== undefined)
414
456
  }
package/src/knowledge.ts CHANGED
@@ -1,8 +1,7 @@
1
1
  import { createHash } from 'node:crypto'
2
2
  import { closeSync, constants, fstatSync, openSync, readSync, statSync } from 'node:fs'
3
- import { relative } from 'node:path'
4
3
  import { bashScope, literalBashCommand } from './command-scope.ts'
5
- import { cleanRelative, projectPath, scopedPath, type AccessDomain } from './domain.ts'
4
+ import { cleanRelative, projectPath, scopedPath, projectRelative, type AccessDomain } from './domain.ts'
6
5
  import type { Agent } from './host.ts'
7
6
  import type { ProjectMemory } from './service.ts'
8
7
  import { StoreError, type DraftItem, type Ref, type Rule } from './store.ts'
@@ -141,7 +140,7 @@ function workdir(domain: AccessDomain, value: unknown, base: string): string {
141
140
  try {
142
141
  const path = scopedPath(domain, cleanRelative(field(value ?? '.', 768)), base)
143
142
  if (!statSync(path).isDirectory()) invalid('invalid_workdir')
144
- return relative(domain.root, path) || '.'
143
+ return projectRelative(domain.root, path) || '.'
145
144
  } catch {
146
145
  return invalid('invalid_workdir')
147
146
  }
@@ -7,6 +7,10 @@ import { episodeBodyDays } from './maintenance-episodes.ts'
7
7
  import { isMemorySlot } from './personal.ts'
8
8
  import { indexRevision, promptRole } from './search-index.ts'
9
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
+
10
14
  export const maintenanceSchema = `
11
15
  CREATE TABLE IF NOT EXISTS history_jobs (
12
16
  domain TEXT NOT NULL, stream TEXT NOT NULL, session TEXT NOT NULL, seq INTEGER NOT NULL, kind TEXT NOT NULL,
@@ -98,6 +102,8 @@ export class MaintenanceState {
98
102
  CREATE TABLE IF NOT EXISTS profile_clocks(domain TEXT NOT NULL,slot TEXT NOT NULL,stream TEXT NOT NULL,
99
103
  seq INTEGER NOT NULL,time INTEGER,PRIMARY KEY(domain,slot,stream));
100
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));
101
107
  CREATE TABLE IF NOT EXISTS suppression_keys(domain TEXT PRIMARY KEY,secret BLOB NOT NULL);
102
108
  CREATE TABLE IF NOT EXISTS purges(domain TEXT NOT NULL,id TEXT NOT NULL,mode TEXT NOT NULL,rev INTEGER NOT NULL,
103
109
  PRIMARY KEY(domain,id,mode));
@@ -282,6 +288,8 @@ export class MaintenanceState {
282
288
  .run(Date.now(), f.domain, f.id, head.rev)
283
289
  changed.add(String(f.domain))
284
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))
285
293
  for (const f of this.archive.prepare('SELECT * FROM purges').all()) {
286
294
  const args = [f.domain, f.id, f.rev] as const
287
295
  if (f.mode === 'signature') {
@@ -327,6 +335,31 @@ export class MaintenanceState {
327
335
  this.ops.bump(domain)
328
336
  }
329
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
+ }
330
363
  forgetSignature(domain: string, id: string, rev: number) {
331
364
  this.db.prepare('DELETE FROM episode_signatures WHERE domain=? AND id=?').run(domain, id)
332
365
  this.purgeThrough(domain, id, 'signature', rev)
@@ -459,10 +492,10 @@ export class MaintenanceState {
459
492
  })
460
493
  }
461
494
  hasRetainedQuote(domain: string, id: string): boolean {
462
- const quote = this.db.prepare("SELECT 1 FROM evidence WHERE domain=? AND id=? AND quote<>'' LIMIT 1")
495
+ const quote = this.db.prepare("SELECT 1 FROM evidence WHERE domain=? AND id=? AND (quote<>'' OR type='tool_result') LIMIT 1")
463
496
  if (quote.get(domain, id)) return true
464
497
  return !!this.archive
465
- .prepare("SELECT 1 FROM entries WHERE domain=? AND id=? AND json_extract(rule,'$.user_quote')<>'' LIMIT 1")
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")
466
499
  .get(domain, id)
467
500
  }
468
501
  suppressQuotes(domain: string, id: string) {
@@ -609,7 +642,7 @@ export class MaintenanceState {
609
642
  this.db
610
643
  .prepare(
611
644
  `INSERT INTO proposals(domain,id,session,turn,source,items,created,rev,epoch,digest,idem,state,receipt)
612
- VALUES(?,?,?,'restore',?,'[]',?,1,?,'',?,'confirmed',?)`,
645
+ VALUES(?,?,?,'restore',json_remove(?,${sourceDetailPaths}),'[]',?,1,?,'',?,'confirmed',?)`,
613
646
  )
614
647
  .run(
615
648
  domain,
@@ -641,7 +674,7 @@ export class MaintenanceState {
641
674
  this.ops.fingerprint(r),
642
675
  promptRole(r),
643
676
  )
644
- indexRevision(this.db, saved.lastInsertRowid, r)
677
+ indexRevision(this.db, domain, saved.lastInsertRowid, r)
645
678
  this.db
646
679
  .prepare('INSERT INTO evidence VALUES(?,?,?,?,?,?)')
647
680
  .run(domain, memory, rev, quoteType, user_quote, JSON.stringify(source))
@@ -9,7 +9,8 @@ import type { HistoryInput } from './maintenance-store.ts'
9
9
  import { prepareItems, type UserSource } from './policy.ts'
10
10
  import { type ProjectMemory, ruleFields } from './service.ts'
11
11
  import { loadedGuidance, sourceStore } from './sources.ts'
12
- import { verifiedQuestionAnswers } from './question-answers.ts'
12
+ import { isNativeProposalResult } from './proposal-receipts.ts'
13
+ import { verifiedQuestionForm } from './question-answers.ts'
13
14
  import { StoreError, type DraftItem, type Source } from './store.ts'
14
15
  import { notifyUI } from './ui.ts'
15
16
 
@@ -150,8 +151,11 @@ async function extract(memory: ProjectMemory, agent: Agent, d: AccessDomain, sou
150
151
  const turn = await historyTurn(h, source)
151
152
  if (!turn) return undefined
152
153
  const cut = Math.max(h.inheritedEventCount, turn[0]?.seq ?? 0)
153
- if (turn.some(entry => (userMessage(entry, entry.seq) && refusesAutomaticMemory(messageText(entry.data))) ||
154
- (entry.type === 'tool/result' && verifiedQuestionAnswers(turn, cut, entry).some(answer => refusesAutomaticMemory(answer.text))))) return []
154
+ if (turn.some(entry => {
155
+ if (userMessage(entry, entry.seq)) return refusesAutomaticMemory(messageText(entry.data))
156
+ const form = entry.type === 'tool/result' ? verifiedQuestionForm(turn, cut, entry) : undefined
157
+ return form?.refusedBy !== undefined || form?.custom.some(answer => refusesAutomaticMemory(answer.text))
158
+ })) return []
155
159
  const blocks: UserSource[] = []
156
160
  let offset = 0
157
161
  for (const [block, part] of (event.data.content ?? []).entries()) {
@@ -161,16 +165,32 @@ async function extract(memory: ProjectMemory, agent: Agent, d: AccessDomain, sou
161
165
  seq: source.seq, text, offset, block })
162
166
  offset += text.length + 1
163
167
  }
168
+ // A completed write already has an authoritative decision for every proposed
169
+ // item. Its draft labels and wording can differ from the normalized revision.
170
+ // Reconstruct only calls which never received a write decision.
171
+ const calls = new Map(turn.filter(e => e.type === 'tool/call' && e.data.name === 'project_memory_propose')
172
+ .map(e => [e.seq, e]))
173
+ const settled = new Set<string>()
174
+ for (const entry of turn) {
175
+ const message = entry.data.message
176
+ const call = calls.get(entry.sourceEventSeqs?.[0] ?? -1)
177
+ if (!call?.data.callId || !message?.toolCallId || message.isError || entry.data.error !== undefined ||
178
+ call.data.turn !== entry.data.turn || !isNativeProposalResult(entry, call.seq, call.data.callId, call.data.step)) continue
179
+ try {
180
+ const reply = JSON.parse(messageText(message))
181
+ if (['saved', 'partial', 'duplicate', 'skipped'].includes(reply?.status)) settled.add(message.toolCallId)
182
+ } catch { /* An interrupted or unrecognized result is not a completed write. */ }
183
+ }
164
184
  const result: DraftItem[] = []
165
185
  const guidance = loadedGuidance(agent.session, d, memory.ctx)
166
186
  for (const entry of turn) {
167
187
  if (entry.seq <= event.seq) continue
168
188
  if (entry.type === 'working-directory/change' || userMessage(entry, entry.seq)) break
169
- if (entry.type !== 'tool/call' || entry.data.name !== 'project_memory_propose' ||
189
+ if (entry.type !== 'tool/call' || entry.data.name !== 'project_memory_propose' || settled.has(entry.data.callId ?? '') ||
170
190
  String(entry.data.turn) !== source.turnId) continue
171
191
  try {
172
192
  for (const row of parseCandidates(JSON.parse(entry.data.arguments ?? ''))) {
173
- if (row.scope !== 'project' || row.replaces || row.correction || skipsCandidate(row)) continue
193
+ if (row.scope !== 'project' || row.replaces || skipsCandidate(row) || !row.user_quote.includes(row.action)) continue
174
194
  const [draft] = prepareItems(d, { items: [ruleFields(row)] }, blocks, guidance)
175
195
  result.push(semanticDraft(row, draft))
176
196
  if (result.length === 32) return result
package/src/personal.ts CHANGED
@@ -11,6 +11,42 @@ export function validLabel(label: unknown): label is string {
11
11
  return typeof label === 'string' && label.length <= 80 && !/[\p{Cc}\p{Cf}]/u.test(label) && !!normalizeLabel(label)
12
12
  }
13
13
 
14
+ export const subjectOwners = ['speaker', 'project', 'named', 'unspecified'] as const
15
+ export type SubjectOwner = typeof subjectOwners[number]
16
+ /** Canonical roles are selected by the model from the utterance. They survive a rename. */
17
+ export function subjectForOwner(owner: SubjectOwner, proposed?: string) {
18
+ if (owner === 'speaker') return 'self'
19
+ if (owner === 'project') return 'project'
20
+ return owner === 'named' ? proposed : undefined
21
+ }
22
+
23
+ export function reviewedSubject(owner: unknown, proposed?: string, target?: { subject?: string }, explicit = false,
24
+ named?: { subject: unknown; source: string[]; aliasQuote?: unknown }):
25
+ { subject: string | undefined } | { reason: 'invalid_model_result' | 'subject_mismatch' } {
26
+ const role = owner as SubjectOwner
27
+ if (!subjectOwners.includes(role)) return { reason: 'invalid_model_result' }
28
+ let subject = subjectForOwner(role, proposed)
29
+ if (role === 'named') {
30
+ if (!named || !validLabel(named.subject)) return { reason: 'invalid_model_result' }
31
+ subject = named.subject.trim()
32
+ const label = normalizeLabel(subject)
33
+ if (label === 'self' || label === 'project' || !named.source.some(text => normalizeLabel(text).includes(label)))
34
+ return { reason: 'subject_mismatch' }
35
+ if (target && proposed && normalizeLabel(proposed) !== label) {
36
+ // A candidate's name and the first model's label can differ. The user's own
37
+ // wording must support the alias and the reviewer must cite that wording.
38
+ const quote = named.aliasQuote
39
+ if (explicit || typeof quote !== 'string' || !quote.trim() || !named.source.some(text => text.includes(quote)) ||
40
+ ![label, normalizeLabel(proposed)].every(name => normalizeLabel(quote).includes(name)))
41
+ return { reason: 'subject_mismatch' }
42
+ }
43
+ }
44
+ if (!target) return { subject }
45
+ const retained = normalizeLabel(target.subject ?? '')
46
+ if (normalizeLabel(subject ?? '') === retained) return { subject: target.subject }
47
+ return { reason: 'subject_mismatch' }
48
+ }
49
+
14
50
  /** Subjects and topics are model-provided labels. Hash a tuple to avoid separator collisions. */
15
51
  export function semanticSlot(scope: 'global' | 'project', topic: string, subject?: string,
16
52
  context?: { when: string; paths: string[] }): MemorySlot | undefined {