dsh-memory-bond 0.3.0-beta.0 → 1.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (145) hide show
  1. package/CHANGELOG.md +6 -7
  2. package/README.md +125 -91
  3. package/README.zh-CN.md +122 -92
  4. package/SECURITY.md +29 -0
  5. package/dist/audit.js +155 -80
  6. package/dist/automatic.js +10 -2
  7. package/dist/client.js +2035 -0
  8. package/dist/command-scope.js +4 -4
  9. package/dist/commands.js +15 -9
  10. package/dist/consolidation-store.js +87 -20
  11. package/dist/consolidation.js +2 -6
  12. package/dist/domain.js +8 -4
  13. package/dist/encoder.js +46 -5
  14. package/dist/file-import-store.js +120 -0
  15. package/dist/file-import.js +265 -0
  16. package/dist/foreground-attempts.js +91 -0
  17. package/dist/guidance.js +133 -92
  18. package/dist/host.js +13 -0
  19. package/dist/index-policy.js +91 -48
  20. package/dist/index.js +102 -40
  21. package/dist/knowledge-hooks.js +70 -27
  22. package/dist/knowledge.js +2 -3
  23. package/dist/maintenance-store.js +38 -4
  24. package/dist/maintenance.js +29 -5
  25. package/dist/personal.js +37 -0
  26. package/dist/policy.js +45 -47
  27. package/dist/prompt-copy.js +93 -0
  28. package/dist/proposal-receipts.js +70 -0
  29. package/dist/proposal-review.js +656 -0
  30. package/dist/propose-contract.js +32 -36
  31. package/dist/question-answers.js +86 -29
  32. package/dist/retrieval.js +25 -8
  33. package/dist/scope-narrowing.js +49 -0
  34. package/dist/search-index.js +93 -13
  35. package/dist/semantic.js +69 -207
  36. package/dist/service.js +633 -204
  37. package/dist/sharing.js +7 -13
  38. package/dist/sources.js +28 -3
  39. package/dist/store.js +432 -96
  40. package/dist/tool-experience.js +87 -0
  41. package/dist/turn-review-store.js +83 -16
  42. package/dist/turn-review.js +155 -59
  43. package/dist/ui.js +128 -26
  44. package/dist/vector-index.js +69 -33
  45. package/docs/architecture.zh-CN.md +52 -0
  46. package/docs/benchmark.zh-CN.md +60 -0
  47. package/docs/benchmarks/repository-tasks.json +5355 -0
  48. package/docs/images/bond-memory-principle-en.svg +644 -0
  49. package/docs/images/bond-memory-principle-zh.svg +644 -0
  50. package/docs/images/bond-memory-principle.drawio +644 -0
  51. package/docs/images/memory-settings-en.png +0 -0
  52. package/docs/images/memory-settings-zh.png +0 -0
  53. package/docs/images/memory-turn-recalled-en.png +0 -0
  54. package/docs/images/memory-turn-recalled-zh.png +0 -0
  55. package/docs/images/memory-turn-saved-en.png +0 -0
  56. package/docs/images/memory-turn-saved-zh.png +0 -0
  57. package/docs/media/memory-bond-name-en.gif +0 -0
  58. package/docs/media/memory-bond-name-en.mp4 +0 -0
  59. package/docs/media/memory-bond-name-zh.gif +0 -0
  60. package/docs/media/memory-bond-name-zh.mp4 +0 -0
  61. package/locale/detail.en.md +5 -1
  62. package/locale/detail.zh.md +5 -1
  63. package/locale/en.json +338 -0
  64. package/locale/zh.json +338 -0
  65. package/native/embeddings/NOTICE.md +2 -2
  66. package/package.json +39 -19
  67. package/scripts/benchmark-bond.mjs +72 -0
  68. package/scripts/benchmark-conditions.mjs +144 -0
  69. package/scripts/benchmark-example.mjs +37 -0
  70. package/scripts/benchmark-scale.mjs +119 -0
  71. package/scripts/benchmark-scenarios.mjs +57 -0
  72. package/scripts/benchmark-tasks.mjs +244 -0
  73. package/src/audit.ts +144 -85
  74. package/src/automatic.ts +12 -2
  75. package/src/command-scope.ts +4 -4
  76. package/src/commands.ts +12 -8
  77. package/src/consolidation-store.ts +80 -18
  78. package/src/consolidation.ts +2 -6
  79. package/src/domain.ts +9 -4
  80. package/src/encoder.ts +46 -6
  81. package/src/file-import-store.ts +139 -0
  82. package/src/file-import.ts +256 -0
  83. package/src/foreground-attempts.ts +97 -0
  84. package/src/guidance.ts +138 -102
  85. package/src/host.ts +22 -2
  86. package/src/index-policy.ts +93 -46
  87. package/src/index.ts +87 -43
  88. package/src/knowledge-hooks.ts +71 -29
  89. package/src/knowledge.ts +2 -3
  90. package/src/maintenance-store.ts +37 -4
  91. package/src/maintenance.ts +25 -5
  92. package/src/personal.ts +36 -0
  93. package/src/policy.ts +55 -52
  94. package/src/prompt-copy.ts +99 -0
  95. package/src/proposal-receipts.ts +59 -0
  96. package/src/proposal-review.ts +614 -0
  97. package/src/propose-contract.ts +31 -35
  98. package/src/question-answers.ts +99 -29
  99. package/src/retrieval.ts +26 -9
  100. package/src/scope-narrowing.ts +58 -0
  101. package/src/search-index.ts +94 -14
  102. package/src/semantic.ts +67 -188
  103. package/src/service.ts +595 -210
  104. package/src/sharing.ts +7 -14
  105. package/src/sources.ts +26 -4
  106. package/src/store.ts +434 -97
  107. package/src/tool-experience.ts +93 -0
  108. package/src/turn-review-store.ts +86 -15
  109. package/src/turn-review.ts +142 -60
  110. package/src/ui.ts +122 -27
  111. package/src/vector-index.ts +57 -29
  112. package/client/index.js +0 -1186
  113. package/design/dsh-memory-plugin-design.md +0 -46
  114. package/design/dsh-memory-plugin-evaluation.md +0 -135
  115. package/design/evaluations/locomo-conv-26-2026-12-03.json +0 -252
  116. package/design/evaluations/locomo-conv-26-paired-2026-12-03.json +0 -549
  117. package/design/evaluations/locomo-conv-26-write-replay-2026-12-03.json +0 -289
  118. package/design/evaluations/project-memory-tasks-2026-12-03.json +0 -1059
  119. package/design/memory-lifecycle-consolidation.excalidraw +0 -1212
  120. package/design/memory-lifecycle-consolidation.mobile.excalidraw +0 -1083
  121. package/design/memory-lifecycle-consolidation.mobile.svg +0 -2
  122. package/design/memory-lifecycle-consolidation.mobile.zh-CN.excalidraw +0 -1083
  123. package/design/memory-lifecycle-consolidation.mobile.zh-CN.svg +0 -94
  124. package/design/memory-lifecycle-consolidation.svg +0 -2
  125. package/design/memory-lifecycle-consolidation.zh-CN.excalidraw +0 -1212
  126. package/design/memory-lifecycle-consolidation.zh-CN.svg +0 -94
  127. package/design/memory-lifecycle.excalidraw +0 -2105
  128. package/design/memory-lifecycle.mobile.excalidraw +0 -1896
  129. package/design/memory-lifecycle.mobile.svg +0 -95
  130. package/design/memory-lifecycle.mobile.zh-CN.excalidraw +0 -1896
  131. package/design/memory-lifecycle.mobile.zh-CN.svg +0 -97
  132. package/design/memory-lifecycle.svg +0 -95
  133. package/design/memory-lifecycle.zh-CN.excalidraw +0 -2105
  134. package/design/memory-lifecycle.zh-CN.svg +0 -97
  135. package/native/embeddings/LICENSE +0 -21
  136. package/native/embeddings/en/model.onnx +0 -4
  137. package/native/embeddings/en/vocab.txt +0 -30522
  138. package/native/embeddings/runtime/LICENSE +0 -21
  139. package/native/embeddings/runtime/ThirdPartyNotices.txt +0 -6156
  140. package/native/embeddings/runtime/ort-wasm-simd-threaded.mjs +0 -70
  141. package/native/embeddings/runtime/ort-wasm-simd-threaded.wasm +0 -0
  142. package/native/embeddings/runtime/ort.wasm.min.mjs +0 -7
  143. package/native/embeddings/worker.mjs +0 -97
  144. package/native/embeddings/zh/model.onnx +0 -0
  145. package/native/embeddings/zh/vocab.txt +0 -21128
package/src/service.ts CHANGED
@@ -1,14 +1,17 @@
1
- import { taskMatcher } from './index-policy.ts'
2
- import { Retrieval, matchingTopics, newSearchTrace, type SearchMode, type SearchOptions, type SearchTrace } from './retrieval.ts'
1
+ import { type PromptLanguage, prompts } from './prompt-copy.ts'
2
+ import { indexLimits, taskMatcher, taskTerms } from './index-policy.ts'
3
+ import { Retrieval, newSearchTrace, type SearchMode, type SearchOptions, type SearchTrace } from './retrieval.ts'
3
4
  import { isKnowledge, knowledgeValid, knowledgeDetails, reviseKnowledge, type AnchorCache } from './knowledge.ts'
4
5
  import { isPersonalSlot, isSemanticSlot, normalizeLabel, semanticSlot, validLabel, type MemorySlot } from './personal.ts'
5
- import { candidateRows, correctReviewSubject, parseCandidate, planSemantic, sameSemanticContent, separateContexts, skipsCandidate, type SemanticCandidate } from './semantic.ts'
6
+ import { candidateRows, parseCandidate, planSemantic, semanticDraft, targetMismatch, sameSemanticContent, separateContexts, skipsCandidate, type SemanticCandidate } from './semantic.ts'
6
7
  import { isDeepStrictEqual } from 'node:util'
7
8
  import { realpathSync } from 'node:fs'
9
+ import { createRequire } from 'node:module'
8
10
  import { refusesAutomaticMemory, skipsAutomaticMemory } from './automatic.ts'
9
11
  import { resolveDomainCached, type AccessDomain } from './domain.ts'
10
12
  import {
11
13
  MemoryStore,
14
+ inputClaimKey,
12
15
  revisionDraft,
13
16
  StoreError,
14
17
  type DraftItem,
@@ -19,6 +22,7 @@ import {
19
22
  } from './store.ts'
20
23
  import {
21
24
  type ProposalFields,
25
+ type UserSource,
22
26
  buildIndex,
23
27
  manualItem,
24
28
  needsHumanReview,
@@ -28,8 +32,10 @@ import {
28
32
  sameRule,
29
33
  validateRule,
30
34
  } from './policy.ts'
31
- import { bindSource, loadedGuidance, sources, sourceStore } from './sources.ts'
32
- import { questionAnswers } from './question-answers.ts'
35
+ import { bindSource, boundSourceDomain, loadedGuidance, sources, sourceStore } from './sources.ts'
36
+ import { questionForm, selectedAction, standingRequest, type SelectionEvidence } from './question-answers.ts'
37
+ import { proposalReceipts } from './proposal-receipts.ts'
38
+ import { ToolExperienceEvidence } from './tool-experience.ts'
33
39
  import {
34
40
  messageText,
35
41
  type Agent,
@@ -40,9 +46,19 @@ import {
40
46
  type Session,
41
47
  type RecordEvent,
42
48
  } from './host.ts'
49
+ import { currentImport, scanImport, type FileSelection } from './file-import.ts'
43
50
  import { notifyUI } from './ui.ts'
51
+ import { actionInDomain } from './command-scope.ts'
52
+ import { previousScopeAgreement } from './scope-narrowing.ts'
44
53
 
45
54
  export const indexName = 'project-memory:index'
55
+ // Set by a complete scoped projection only when its rows depend exclusively on SQLite and
56
+ // the re-authorized session directory. Ambiguous commands require live filesystem checks.
57
+ export interface ProjectionCheck { reusable: boolean }
58
+ function isDatabaseOnly(domain: AccessDomain, rule: Rule) {
59
+ return rule.usage === 'on_demand' && !isKnowledge(rule) && !rule.paths.length &&
60
+ !rule.hard && !rule.guidance && !rule.localException && actionInDomain(domain, rule.action, () => undefined)
61
+ }
46
62
  export const ruleFields = (r: ProposalFields) => ({
47
63
  action: r.action,
48
64
  when: r.when,
@@ -71,7 +87,8 @@ export const publicRule = (r: Rule) => ({
71
87
  localException: r.localException,
72
88
  })
73
89
  function managerRule(rule: Rule, indexed: boolean, delivered: boolean) {
74
- return { ...publicRule(rule), canChangeUsage: !isKnowledge(rule) && !rule.sensitive, indexed, delivered }
90
+ const canChangeUsage = !rule.sensitive && rule.kind !== 'fact' && !isKnowledge(rule)
91
+ return { ...publicRule(rule), canChangeUsage, indexed, delivered }
75
92
  }
76
93
  const exactMemoryId = /^(mem-[\da-f-]+)(?:@(\d+))?$/u
77
94
 
@@ -91,24 +108,11 @@ interface ReviewEntry extends Ref {
91
108
  action?: string
92
109
  previous?: string
93
110
  }
94
- const reviewReasonText: Record<string, string> = {
95
- outside_branch: '当前 Git 分支不适用',
96
- outside_path: '当前路径不适用',
97
- outside_command_scope: '命令超出项目范围',
98
- outside_environment: '当前机器或环境不适用',
99
- stale_guidance: '仓库指令已变更',
100
- needs_clarification: '需要澄清仓库指令',
101
- needs_review: '文件、构建目标或其他适用条件已变化',
102
- anchor_changed: '依据文件内容已变更',
103
- anchor_unavailable: '依据文件无法读取',
104
- invalid_anchor: '依据文件已失效',
105
- invalid_anchors: '文件依据不完整',
106
- symbol_missing: '依据中的符号已消失',
107
- invalid_reference: '参考来源已失效',
108
- invalid_workdir: '工作目录已失效',
109
- invalid_match: '适用命令已失效',
110
- unconfirmed_guard: '命令约束未确认',
111
- }
111
+ const requireUI = createRequire(import.meta.url)
112
+ const uiMessages = {
113
+ en: requireUI('../locale/en.json').ui,
114
+ zh: requireUI('../locale/zh.json').ui,
115
+ } as Record<'en' | 'zh', Record<string, string>>
112
116
  function containsWords(query: string, fields: (string | undefined)[]) {
113
117
  const text = fields.join(' ').normalize('NFKC').toLocaleLowerCase()
114
118
  const words = query.normalize('NFKC').trim().toLocaleLowerCase().split(/\s+/u)
@@ -140,9 +144,10 @@ export function matches(rule: Rule, query: string) {
140
144
  interface ReviewSelection {
141
145
  index: number
142
146
  changes?: Partial<ReturnType<typeof ruleFields>>
143
- exception?: { environment: string; scope: string }
147
+ exception?: { environment: string; scope: string; commands?: { present: string[]; absent: string[] } }
144
148
  replace?: Ref
145
149
  coexist?: boolean
150
+ guidanceReviewed?: boolean
146
151
  branch?: string | null
147
152
  }
148
153
  interface ReviewInput extends Pick<Proposal, 'id' | 'revision' | 'digest'> {
@@ -158,21 +163,62 @@ interface SourcedCandidate {
158
163
  row: SemanticCandidate
159
164
  prepared: DraftItem
160
165
  source: Source
161
- sourceText: string
162
166
  family: MemorySlot
167
+ inputSlot: MemorySlot
163
168
  observed?: Ref
164
169
  }
165
170
 
166
171
  export class ProjectMemory {
167
- // The first request is assembled before DSH appends the claimed user message.
168
- // Hold only this turn's bounded retrieval terms in memory, never in the index or audit log.
169
- private readonly claimedTasks = new WeakMap<Agent, { turn: number; matcher?: RegExp; domain: string; cwd: string; generation: number }>()
172
+ readonly bashEvidence = new ToolExperienceEvidence()
173
+
174
+ experienceSource(agent: Agent, generation: number, callId?: string) {
175
+ if (!this.bashEvidence.hasObservations(agent) || this.assistantGeneration() !== generation) return
176
+ const domain = this.rootDomain(agent, true)
177
+ if (domain.id === this.personal.id) return
178
+ const source = this.bashEvidence.source(agent, domain, generation, this.storeId(agent.session), callId)
179
+ if (!source) return
180
+ const blocks = sources(agent.session, domain, source.storeId, source.turnId)
181
+ if (!blocks.some(b => !b.question && b.memoryGeneration === generation) ||
182
+ blocks.some(b => b.refused || refusesAutomaticMemory(b.text))) return
183
+ return { domain, source }
184
+ }
185
+
186
+ proposeExperience(agent: Agent, args: Record<string, unknown>, generation: number) {
187
+ if (Object.keys(args).some(k => !['callId', 'topic', 'action'].includes(k)) ||
188
+ typeof args.callId !== 'string' || !args.callId || !validLabel(args.topic) ||
189
+ typeof args.action !== 'string' || !args.action.trim() || args.action.length > 512 || /[\p{Cc}\p{Cf}]/u.test(args.action) ||
190
+ skipsAutomaticMemory(args.topic + '\n' + args.action)) throw new StoreError('invalid_input')
191
+ const evidence = this.experienceSource(agent, generation, args.callId)
192
+ if (!evidence) throw new StoreError('invalid_source')
193
+ const { domain, source } = evidence
194
+ const topic = args.topic.trim()
195
+ const draft = manualItem(domain, { action: args.action, when: '', exceptions: '', paths: [], user_quote: '',
196
+ conflicts_with_repo_guidance: false }, loadedGuidance(agent.session, domain, this.ctx))
197
+ const item: DraftItem = { ...draft, kind: 'fact', usage: 'on_demand', slot: semanticSlot('project', topic), semanticTopic: topic }
198
+ const proposal = this.pending(agent, domain, source, [item])
199
+ return { status: proposal.state, proposalId: proposal.id }
200
+ }
201
+ private readonly sessionLanguages = new WeakMap<Session, PromptLanguage>()
202
+ private readonly defaultLanguage: PromptLanguage = Intl.DateTimeFormat().resolvedOptions().locale.startsWith('zh') ? 'zh' : 'en'
203
+ promptLanguage(agent?: Agent): PromptLanguage {
204
+ const configured = this.config.promptLanguage
205
+ if (configured === 'en' || configured === 'zh') return configured
206
+ return (agent && this.sessionLanguages.get(agent.session)) ?? this.defaultLanguage
207
+ }
208
+
209
+ // DSH assembles the first request before appending the user message. Cache only bounded terms.
210
+ private readonly claimedTasks = new WeakMap<Agent, { turn: number; terms: string[]; matcher?: RegExp; domain: string; cwd: string; generation: number }>()
170
211
  captureTask(agent: Agent, message: Message, turn: number) {
171
212
  if (message.source?.kind !== 'user') return
213
+ const text = messageText(message).slice(0, 2048)
214
+ if (/\p{Script=Han}/u.test(text)) this.sessionLanguages.set(agent.session, 'zh')
215
+ else if (/[a-z]{2}/iu.test(text)) this.sessionLanguages.set(agent.session, 'en')
172
216
  const generation = this.assistantGeneration()
173
217
  const domain = generation === undefined ? undefined : this.domain(agent)
174
- if (domain && generation !== undefined)
175
- this.claimedTasks.set(agent, { turn, matcher: taskMatcher(messageText(message)), domain: domain.id, cwd: domain.cwd, generation })
218
+ if (domain && generation !== undefined) {
219
+ const terms = taskTerms(text)
220
+ this.claimedTasks.set(agent, { turn, terms, matcher: taskMatcher(terms), domain: domain.id, cwd: domain.cwd, generation })
221
+ }
176
222
  }
177
223
 
178
224
  readonly personal: AccessDomain
@@ -242,7 +288,10 @@ export class ProjectMemory {
242
288
  capture(session: Session, event: HostEvent) {
243
289
  if (session.header.origin === 'subagent' || event.seq < session.inheritedEventCount) return
244
290
  const chat = event.type === 'user/message' && event.data.source?.kind === 'user'
245
- if (!chat && (event.type !== 'tool/result' || !questionAnswers(session, event).length)) return
291
+ if (!chat) {
292
+ const form = event.type === 'tool/result' && questionForm(session, event)
293
+ if (!form || (!form.custom.length && !form.selected.length && form.refusedBy === undefined)) return
294
+ }
246
295
  const owner = this.ctx.agents.get(session.id)
247
296
  if (owner?.session !== session || this.ctx.get('sandboxPolicy')?.resolve({ session }).mode === 'read-only') return
248
297
  let cwd: string | undefined = this.ctx.workingDirectory.get(session)
@@ -294,6 +343,40 @@ export class ProjectMemory {
294
343
  const row = this.store.read(d.id, id, rev)
295
344
  return row && this.validity(d, row).ok ? row : undefined
296
345
  }
346
+ turnReceipts(agent: Agent, answerSeq: number) {
347
+ const domain = this.rootDomain(agent)
348
+ const scopes = this.scopes(agent, domain)
349
+ const session = agent.session
350
+ const events = session.snapshotEvents()
351
+ const answer = events[answerSeq]
352
+ if (answerSeq < session.inheritedEventCount || answer?.seq !== answerSeq ||
353
+ answer.type !== 'assistant/message' || answer.data.message?.role !== 'assistant' ||
354
+ !messageText(answer.data.message).trim()) throw new StoreError('unavailable')
355
+ const { turn, step } = answer.data
356
+ if (typeof turn !== 'number' || !Number.isSafeInteger(turn) ||
357
+ typeof step !== 'number' || !Number.isSafeInteger(step)) throw new StoreError('unavailable')
358
+ // A fork can inherit part of a turn. Only expose requests from turns started in this session.
359
+ let start = answerSeq - 1
360
+ while (start >= session.inheritedEventCount && events[start].type !== 'turn/start' &&
361
+ events[start].type !== 'turn/end') start--
362
+ if (start < session.inheritedEventCount || events[start].type !== 'turn/start' ||
363
+ events[start].data.turn !== turn) throw new StoreError('unavailable')
364
+ const labels = new Map<string, string | undefined>()
365
+ const store = this.storeId(session)
366
+ const writes = proposalReceipts(events.slice(start + 1, answerSeq), turn, domain.id, store,
367
+ cwd => (resolveDomainCached(this.profile, cwd, this.config.nonGitRoots) ?? this.personal).id === domain.id,
368
+ code => Object.hasOwn(uiMessages.en, 'turnReceipts.reason.' + code))
369
+ return { ...(writes && { writes }), requests: this.store.turnReceipts(scopes.map(scope => scope.id), session.id,
370
+ store, String(turn), step, (domainId, ref) => {
371
+ const key = JSON.stringify([domainId, ref.id, ref.rev])
372
+ if (!labels.has(key)) {
373
+ const scope = scopes.find(scope => scope.id === domainId)
374
+ const rule = scope && this.current(scope, ref.id, ref.rev)
375
+ labels.set(key, rule && !rule.sensitive ? rule.semanticTopic : undefined)
376
+ }
377
+ return labels.get(key)
378
+ }) }
379
+ }
297
380
  listConsolidation(agent: Agent) {
298
381
  const project = this.rootDomain(agent)
299
382
  if (project.id === this.personal.id) return []
@@ -311,7 +394,8 @@ export class ProjectMemory {
311
394
  this.store.consolidation.decide(project.id, left, right, keep, agent.id)
312
395
  notifyUI(this.ctx, agent.id)
313
396
  }
314
- async search(agent: Agent, query: string, mode?: SearchMode, options: SearchOptions = {}, trace: SearchTrace = newSearchTrace()) {
397
+ async search(agent: Agent, query: string, mode?: SearchMode, options: SearchOptions = {}, trace: SearchTrace = newSearchTrace(),
398
+ review?: { accept(rule: Rule): boolean; limit: number }) {
315
399
  if (typeof query !== 'string' || query.length > 2048 ||
316
400
  (mode !== undefined && !['hybrid', 'keyword', 'semantic'].includes(mode)) ||
317
401
  (options.scope !== undefined && !['project', 'profile'].includes(options.scope)) ||
@@ -324,71 +408,108 @@ export class ProjectMemory {
324
408
  const scopes = this.scopes(agent, d).filter(s => !options.scope ||
325
409
  (s.id === this.personal.id ? 'profile' : 'project') === options.scope)
326
410
  type Candidate = { domain: string; id: string; rev?: number }
327
- const collect = (visibleScopes: AccessDomain[], candidates?: readonly Candidate[]) => {
411
+ const collect = (visibleScopes: AccessDomain[], candidates: readonly Candidate[] | undefined, projection: 'ranking' | 'review' | 'source' = 'ranking') => {
328
412
  const anchors: AnchorCache = new Map()
329
413
  return visibleScopes.flatMap(scope => {
330
414
  const refs = candidates?.filter(ref => ref.domain === scope.id)
331
415
  const start = performance.now()
332
- const rows = refs ? this.store.readMany(scope.id, refs) : this.store.list(scope.id)
416
+ const rows = projection === 'source' ? this.store.readMany(scope.id, refs!) :
417
+ this.store.searchHeads(scope.id, refs, projection === 'review')
333
418
  trace.sqliteMs += performance.now() - start
334
419
  return rows.filter(rule => this.validity(scope, rule, anchors).ok).map(rule => ({ rule, domain: scope.id }))
335
420
  })
336
421
  }
337
422
  const q = normalizeLabel(query)
338
423
  const exact = exactMemoryId.exec(q)
424
+ const domains = scopes.map(scope => scope.id)
425
+ const topicRefs = (visible: AccessDomain[]) =>
426
+ visible.flatMap(scope => this.store.topicRefs(scope.id, options.topic!, options.subject))
427
+ const identities = !exact && !mode && options.topic ? collect(scopes, topicRefs(scopes)) : []
428
+ const structured = identities.length > 1 || (identities.length === 1 && !!options.subject)
429
+ const lexicalOnly = mode !== 'semantic' && !this.retrieval.vectors.languages.length
339
430
  const keywordStart = performance.now()
340
- const keywordHits = !exact && mode === 'keyword' && (q || options.topic)
341
- ? this.retrieval.keywordHits(scopes.map(scope => scope.id), query, options)
431
+ const keywordHits = !exact && !structured && (mode === 'keyword' || lexicalOnly || review) && (q || options.topic)
432
+ ? this.retrieval.keywordHits(domains, query, options)
342
433
  : undefined
343
434
  if (keywordHits) trace.sqliteMs += performance.now() - keywordStart
344
435
  const candidates = exact
345
- ? scopes.map(scope => ({ domain: scope.id, id: exact[1], rev: exact[2] ? Number(exact[2]) : undefined }))
346
- : keywordHits
347
- const initial = collect(scopes, candidates)
348
- // A complete scan can distinguish an empty visible scope from a query with no matches.
349
- // An ID or FTS lookup inspects only its candidates and cannot make that claim.
350
- if (scopes.length && candidates === undefined && !initial.length) {
436
+ ? domains.map(domain => ({ domain, id: exact[1], rev: exact[2] ? Number(exact[2]) : undefined }))
437
+ : review && keywordHits ? this.retrieval.reviewRefs(domains, query, options, keywordHits) : keywordHits
438
+ let initial = structured ? identities : collect(scopes, candidates, review ? 'review' : 'ranking')
439
+ // With no embedding models, only FTS matches can score. A negative lookup must
440
+ // still distinguish an empty eligible scope from a scope with unrelated records.
441
+ const subject = normalizeLabel(options.subject ?? '')
442
+ const checkScope = !review && !exact && !structured && mode !== 'keyword' && lexicalOnly && keywordHits &&
443
+ !initial.some(({rule}) => !subject || !rule.subject || normalizeLabel(rule.subject) === subject)
444
+ if (checkScope) initial = collect(scopes, undefined)
445
+ if (scopes.length && (candidates === undefined || checkScope) && !initial.length) {
351
446
  trace.match = 'empty_scope'
352
447
  return []
353
448
  }
354
- const ranked = await this.retrieval.search(initial, query, mode, options, trace, keywordHits)
449
+ // Preserve the ambiguity decision across all identities before narrowing foreground
450
+ // review candidates. A keyword alias can belong to a different subject or protected fact.
451
+ const inputs = review && !structured ? initial.filter(({rule}) => review.accept(rule)) : initial
452
+ const ranked = await this.retrieval.search(inputs, query, mode, options, trace, keywordHits)
355
453
  const active = this.domain(agent)
356
454
  if (!active || this.ctx.agents.get(agent.id) !== agent || active.id !== d.id ||
357
455
  active.root !== d.root || active.cwd !== d.cwd) return []
358
456
  // Re-read returned revisions, permissions and their filesystem evidence after ranking.
359
457
  // A unique exact-topic hit also needs to notice a concurrent insertion.
360
458
  const visibleIds = new Set(this.scopes(agent, active).map(s => s.id))
361
- const hits = new Map(ranked.map(rule => [rule.id, rule.rev]))
362
- const refs = trace.match === 'exact_topic' ? undefined : initial.flatMap(({ domain, rule }) =>
363
- hits.get(rule.id) === rule.rev ? [{ domain, id: rule.id, rev: rule.rev }] : [])
364
- const rows = collect(scopes.filter(scope => visibleIds.has(scope.id)), refs)
459
+ const visible = scopes.filter(scope => visibleIds.has(scope.id))
365
460
  if (trace.match === 'exact_topic') {
366
- const exact = matchingTopics(rows, options)
461
+ const exact = collect(visible, topicRefs(visible), 'source').map(row => row.rule)
367
462
  if (exact.length > 1) {
368
463
  trace.match = 'ambiguous'
369
- return exact.map(r => r.rule)
464
+ return review ? exact.filter(review.accept).slice(0, review.limit) : exact
465
+ }
466
+ return exact.filter(row => row.id === ranked[0]?.id && row.rev === ranked[0]?.rev && (!review || review.accept(row)))
467
+ }
468
+ const result: Rule[] = []
469
+ const accepted = review ? ranked.filter(review.accept) : ranked
470
+ const batchSize = review ? review.limit : Math.max(1, accepted.length)
471
+ for (let i = 0; i < accepted.length; i += batchSize) {
472
+ const batch = accepted.slice(i, i + batchSize)
473
+ const refs = batch.map(rule => ({ domain: rule.domainId!, id: rule.id, rev: rule.rev }))
474
+ const current = new Map(collect(visible, refs, 'source').map(({rule}) => [rule.id, rule]))
475
+ for (const hit of batch) {
476
+ const row = current.get(hit.id)
477
+ if (row?.rev === hit.rev) result.push(row)
478
+ if (review && result.length === review.limit) return result
370
479
  }
371
480
  }
372
- const visible = new Map(rows.map(r => [r.rule.id, r.rule]))
373
- const result = ranked.flatMap(hit => {
374
- const current = visible.get(hit.id)
375
- return current?.rev === hit.rev ? [current] : []
376
- })
377
481
  return ranked.degraded ? Object.assign(result, { degraded: true }) : result
378
482
  }
379
483
  async manage(
380
484
  agent: Agent,
381
485
  op: string,
382
- args: { id?: unknown; rev?: unknown; query?: unknown; action?: unknown; mode?: unknown; usage?: unknown; scope?: 'project' | 'profile' },
486
+ args: { id?: unknown; rev?: unknown; sourceRev?: unknown; query?: unknown; action?: unknown; mode?: unknown; usage?: unknown; scope?: 'project' | 'profile'; locale?: 'en' | 'zh' },
487
+ check?: ProjectionCheck,
488
+ page?: {offset: number; limit: number},
383
489
  ) {
384
490
  const write = ['revise', 'usage', 'forget', 'undo', 'pin', 'unpin', 'clear-quote'].includes(op)
385
491
  const d = this.rootDomain(agent, write)
386
492
  if (op === 'list') {
387
- const view = this.view(agent)
388
- return { ...view, ...this.managerStatus(view.needs_review, '') }
493
+ const view = this.view(agent, args.scope, check)
494
+ const total = view.rules.length + view.needs_review.length
495
+ const rules = page ? view.rules.slice(page.offset, page.offset + page.limit) : view.rules
496
+ const invalid = page ? view.needs_review.slice(Math.max(0, page.offset - view.rules.length),
497
+ Math.max(0, page.offset + page.limit - view.rules.length)) : view.needs_review
498
+ const annotate = this.managerUsage(this.scopes(agent, d).filter(scope => !args.scope ||
499
+ (scope.id === this.personal.id ? 'profile' : 'project') === args.scope), page ? [...rules, ...invalid] : undefined)
500
+ return { ...view, rules: rules.map(annotate),
501
+ ...(page && { total, choices: view.proposals.some(card => card.state === 'pending' && !card.source.fileImport) ? view.rules : [] }),
502
+ needs_review: this.managerStatus(invalid, '', args.locale).needs_review.map(annotate) }
389
503
  }
390
- if (op === 'search') return this.searchManagedRules(agent, d, args.query as string, args.mode as SearchMode, args.scope)
504
+ if (op === 'search') return this.searchManagedRules(agent, d, args.query as string, args.mode as SearchMode, args.scope, args.locale)
391
505
  const { owner, ref } = this.resolveManagedRef(agent, d, args)
506
+ if (args.sourceRev !== undefined) {
507
+ if (op !== 'source' || !Number.isSafeInteger(args.sourceRev) || Number(args.sourceRev) < 1)
508
+ throw new StoreError('invalid_item')
509
+ if (owner.id !== this.personal.id || Number(args.sourceRev) >= ref.rev) return { status: 'not_found' }
510
+ }
511
+ if (op === 'source' && owner.id === this.personal.id)
512
+ return this.profileManagerSource(agent, ref, args.sourceRev as number | undefined)
392
513
  if (op === 'read' || op === 'source') return this.readManagedRule(agent, owner, ref, op === 'source')
393
514
  if (!write) throw new StoreError('invalid_command')
394
515
  const old = this.store.read(owner.id, ref.id, ref.rev)
@@ -423,16 +544,17 @@ export class ProjectMemory {
423
544
  notifyUI(this.ctx, agent.id)
424
545
  return { status: op === 'forget' ? 'revoked' : op, ...ref }
425
546
  }
426
- private resolveManagedRef(agent: Agent, domain: AccessDomain, args: { id?: unknown; rev?: unknown }) {
547
+ private resolveManagedRef(agent: Agent, domain: AccessDomain, args: { id?: unknown; rev?: unknown; scope?: 'profile' | 'project' }) {
427
548
  if (typeof args.id !== 'string' || !Number.isSafeInteger(args.rev) || Number(args.rev) < 1)
428
549
  throw new StoreError('expected_revision')
429
550
  const ref = { id: args.id, rev: Number(args.rev) }
430
551
  const owner = this.owner(agent, domain, ref.id)
431
- if (!owner) throw new StoreError('not_found')
552
+ if (!owner || (args.scope && args.scope !== (owner.id === this.personal.id ? 'profile' : 'project')))
553
+ throw new StoreError('not_found')
432
554
  return { owner, ref }
433
555
  }
434
556
  private async searchManagedRules(
435
- agent: Agent, d: AccessDomain, query: string, mode?: SearchMode, filter?: SearchOptions['scope'],
557
+ agent: Agent, d: AccessDomain, query: string, mode?: SearchMode, filter?: SearchOptions['scope'], locale?: 'en' | 'zh',
436
558
  ) {
437
559
  const rules = await this.search(agent, query, mode, { scope: filter })
438
560
  const live = this.rootDomain(agent)
@@ -458,11 +580,19 @@ export class ProjectMemory {
458
580
  const indexed = [...current.values()].some(row => row.usage === 'proactive' && !isKnowledge(row))
459
581
  ? this.index(agent, live, true).included : []
460
582
  const delivered = current.size ? scopes.flatMap(scope => this.store.delivered(scope.id, agent.id)) : []
583
+ const annotate = this.managerUsage(scopes)
461
584
  return { rules: rules.flatMap(hit => {
462
585
  const rule = current.get(hit.id)
463
586
  return rule ? [managerRule(rule, indexed.some(ref => ref.id === rule.id && ref.rev === rule.rev),
464
587
  delivered.some(ref => ref.id === rule.id && ref.rev === rule.rev))] : []
465
- }), ...this.managerStatus(withheld, query) }
588
+ }).map(annotate), needs_review: this.managerStatus(withheld, query, locale).needs_review.map(annotate) }
589
+ }
590
+ private managerUsage(scopes: AccessDomain[], page?: Ref[]) {
591
+ const refs = page?.map(({ id, rev }) => ({ id, rev }))
592
+ const usage = new Map(scopes.flatMap(scope => this.store.usageSignals(scope.id, refs).map(({ id, rev, ...counts }) =>
593
+ [(scope.id === this.personal.id ? 'profile/' : 'project/') + id + '@' + rev, counts] as const)))
594
+ return <T extends Ref & { scope: string }>(row: T) =>
595
+ ({ ...row, usageSignals: usage.get(`${row.scope}/${row.id}@${row.rev}`) })
466
596
  }
467
597
  private async readManagedRule(agent: Agent, owner: AccessDomain, { id, rev }: Ref, expand: boolean) {
468
598
  const result = await this.read(agent, id, rev, expand)
@@ -470,10 +600,41 @@ export class ProjectMemory {
470
600
  const live = this.rootDomain(agent)
471
601
  const scope = this.scopes(agent, live).find(s => s.id === owner.id)
472
602
  const head = scope && this.current(scope, id, rev)
473
- if (!head || ('quote' in result && head.user_quote !== result.quote)) return { status: 'not_found' }
603
+ if (!head || !this.canPublishEvidence(head, result)) return { status: 'not_found' }
474
604
  return 'quote' in result
475
605
  ? { ...result, hasRetainedQuote: this.store.maintenance.hasRetainedQuote(owner.id, id) } : result
476
606
  }
607
+ private *profileSourceHistory(head: Ref): IterableIterator<Rule> {
608
+ for (const version of this.store.previousVersions(this.personal.id, head.id, head.rev)) {
609
+ if (version.quoteType === 'user_quote' && version.user_quote && this.validity(this.personal, version).ok)
610
+ yield version
611
+ }
612
+ }
613
+ private async profileManagerSource(agent: Agent, head: Ref, sourceRev?: number) {
614
+ const select = () => {
615
+ const scope = this.rootDomain(agent)
616
+ if (!this.scopes(agent, scope).some(d => d.id === this.personal.id)) return
617
+ const current = this.current(this.personal, head.id, head.rev)
618
+ if (sourceRev === undefined || !current) return current
619
+ for (const version of this.profileSourceHistory(head)) {
620
+ if (version.rev === sourceRev) return version
621
+ if (version.rev < sourceRev) break
622
+ }
623
+ }
624
+ const record = select()
625
+ if (!record) return { status: 'not_found' }
626
+ const verified = await this.verifyQuote(this.personal, record)
627
+ // The chat read can outlive a clear-quote, a revision, access loss or history expiry.
628
+ const live = select()
629
+ if (!live) return { status: 'not_found' }
630
+ const result = this.sourceEvidence(this.personal, live, verified && this.sameQuoteSource(record, live))
631
+ if (sourceRev !== undefined) return result
632
+ return { ...result, hasRetainedQuote: this.store.maintenance.hasRetainedQuote(this.personal.id, head.id),
633
+ ...(live.rev > 1 && live.quoteType === 'receipt' && live.source.origin === 'manual' &&
634
+ (live.channel === 'owner_card' || live.channel === 'user_command') && { manualEdit: true }),
635
+ sourceRevisions: Array.from(this.profileSourceHistory(head), version => version.rev),
636
+ }
637
+ }
477
638
  private recordEdit(agent: Agent, { id, rev }: Ref): Source {
478
639
  const seq = this.append(agent.session, 'plugin:project-memory/edit', { id, rev })
479
640
  return {
@@ -505,7 +666,7 @@ export class ProjectMemory {
505
666
  const branch = (old.hard as { branch?: string } | undefined)?.branch
506
667
  if (branch) item.hard = { ...(item.hard as object), branch }
507
668
  if (!validateRule(owner, item).ok) {
508
- const p = this.pending(agent, owner, source, [item])
669
+ const p = this.pending(agent, owner, source, [item], 'settings')
509
670
  return { status: 'pending', proposal_id: p.id }
510
671
  }
511
672
  }
@@ -555,7 +716,7 @@ export class ProjectMemory {
555
716
  if (
556
717
  expanded ||
557
718
  sections.some(
558
- (section) => section.text.includes(id + '@') || section.text.includes('[' + id + '] 已撤回'),
719
+ (section) => section.text.includes(id + '@') || [prompts.en, prompts.zh].some(copy => section.text.includes('[' + id + '] ' + copy.withdrawn)),
559
720
  )
560
721
  )
561
722
  withdrawn.add(id)
@@ -564,28 +725,68 @@ export class ProjectMemory {
564
725
  }
565
726
  return [...withdrawn].sort()
566
727
  }
728
+ // A single recent plan bounds retention across projects. Only prompt callers
729
+ // can use it: callers requesting the entire overflow need every eligibility check.
730
+ private recentPrompt?: { key: string; recheck: Rule[]; result: { text: string; included: Rule[] } }
731
+ index(agent: Agent, d: AccessDomain, promptOnly: true): { text: string; included: Rule[] }
732
+ index(agent: Agent, d: AccessDomain, promptOnly?: false): ReturnType<typeof buildIndex<Rule>>
567
733
  index(agent: Agent, d: AccessDomain, promptOnly = false) {
568
734
  const generation = this.assistantGeneration()
569
- if (generation === undefined) return buildIndex<Rule>([], [])
735
+ if (generation === undefined) {
736
+ this.recentPrompt = undefined
737
+ return buildIndex<Rule>([], [])
738
+ }
570
739
  const scopes = this.scopes(agent, d)
571
- const rows = scopes.flatMap(scope =>
572
- this.store.indexHeads(scope.id).filter(rule => this.validity(scope, rule).ok))
573
- // A prompt only needs one eligible on-demand entry to reserve its search hint.
574
- // Confirmation receipts also use the full set to determine subsequent placement.
575
- onDemand: for (const scope of scopes) {
740
+ const claimed = this.claimedTasks.get(agent)
741
+ let task: typeof claimed
742
+ if (claimed && claimed.domain === d.id && claimed.cwd === d.cwd && claimed.generation === generation) {
743
+ const boundary = agent.session.snapshotEvents().findLast(event =>
744
+ event.type === 'turn/start' || event.type === 'turn/end' || event.type === 'working-directory/change')
745
+ if (boundary?.type === 'turn/start' && claimed.turn === boundary.data.turn) task = claimed
746
+ }
747
+ const onDemand: Rule[] = []
748
+ for (const scope of scopes) {
749
+ if (promptOnly && task?.terms.length && this.config.overflowHints !== false) {
750
+ // Check repository conditions on a bounded lexical shortlist before offering a pointer.
751
+ for (const row of this.store.onDemandCandidates(scope.id, task.terms)) {
752
+ if (this.validity(scope, row).ok) onDemand.push(row)
753
+ }
754
+ }
755
+ if (promptOnly && onDemand.length) continue
576
756
  for (const rule of this.store.onDemandHeads(scope.id)) {
577
757
  if (!this.validity(scope, rule).ok) continue
578
- rows.push(rule)
579
- if (promptOnly) break onDemand
758
+ onDemand.push(rule)
759
+ if (promptOnly) break
580
760
  }
581
761
  }
582
- return buildIndex(rows, scopes.flatMap(s => this.withdrawn(agent, s)), this.config, () => {
583
- const claimed = this.claimedTasks.get(agent)
584
- if (!claimed || claimed.domain !== d.id || claimed.cwd !== d.cwd || claimed.generation !== generation) return
585
- const boundary = agent.session.snapshotEvents().findLast(event =>
586
- event.type === 'turn/start' || event.type === 'turn/end' || event.type === 'working-directory/change')
587
- if (boundary?.type === 'turn/start' && claimed.turn === boundary.data.turn) return claimed.matcher
588
- })
762
+ const withdrawn = scopes.flatMap(scope => this.withdrawn(agent, scope))
763
+ const language = this.promptLanguage(agent)
764
+ const eligible = (rule: Rule) => this.validity(rule.domainId === this.personal.id ? this.personal : d, rule).ok
765
+ const build = (active: Rule[], recheck?: Set<Rule>) =>
766
+ buildIndex([...active, ...onDemand], withdrawn, this.config, () => task?.matcher, language, recheck)
767
+ const limits = indexLimits(this.config)
768
+ const key = promptOnly && JSON.stringify([generation, language, limits, task?.terms, withdrawn,
769
+ scopes.map(scope => [scope.id, scope.root, scope.cwd, scope.machine, this.store.epoch(scope.id)]),
770
+ onDemand.map(row => [row.id, row.rev])])
771
+ const cached = this.recentPrompt
772
+ if (cached && cached.key === key && cached.recheck.every(eligible)) return cached.result
773
+ if (promptOnly) this.recentPrompt = undefined
774
+ const active = scopes.flatMap(scope => this.store.indexHeads(scope.id))
775
+ if (key && active.length > limits.maxRows) {
776
+ const recheck = new Set<Rule>()
777
+ const { text, included } = build(active, recheck)
778
+ for (const row of included) recheck.add(row)
779
+ // Omitted singletons cannot displace a selected group. buildIndex also
780
+ // identifies variants, budget witnesses and hints that can affect ranking.
781
+ // Always check their *current* filesystem, branch and environment scope.
782
+ const required = [...recheck]
783
+ if (required.every(eligible)) {
784
+ const result = { text, included }
785
+ this.recentPrompt = { key, recheck: required, result }
786
+ return result
787
+ }
788
+ }
789
+ return build(active.filter(eligible))
589
790
  }
590
791
  /** The nearest earlier version of an automatic save that may be put back. */
591
792
  private restorable(d: AccessDomain, rule: Rule) {
@@ -606,8 +807,7 @@ export class ProjectMemory {
606
807
  }
607
808
  }
608
809
  private pending(root: Agent, d: AccessDomain, source: Source, items: DraftItem[], turnId?: string) {
609
- const current = this.store.list(d.id)
610
- const novel = items.filter((item) => !current.some((rule) => sameRule(item, rule)))
810
+ const novel = items.filter(item => !this.store.comparisonHeads(d.id, 'action', item.action).some(rule => sameRule(item, rule)))
611
811
  if (!novel.length) throw new StoreError('duplicate')
612
812
  const p = this.store.propose(d.id, root.id, source, novel, turnId)
613
813
  // A log-only identifier wakes headless observers. Body and approval digest stay in the store.
@@ -619,7 +819,11 @@ export class ProjectMemory {
619
819
  })
620
820
  return p
621
821
  }
622
- private projectConflict(item: DraftItem, current: Rule[]) {
822
+ private projectConflict(domain: string, item: DraftItem) {
823
+ // A conflict requires the same condition. For an empty condition it also requires the same slot.
824
+ const candidates = item.when ? this.store.comparisonHeads(domain, 'condition', item.when)
825
+ : item.slot ? this.store.comparisonHeads(domain, 'slot', item.slot) : []
826
+ const current = candidates.filter(rule => !isKnowledge(rule))
623
827
  return relatedRules(item, current).some(rule => !sameRule(item, rule) &&
624
828
  rule.when === item.when && JSON.stringify(rule.paths) === JSON.stringify(item.paths) &&
625
829
  ((rule.slot && rule.slot === item.slot) || Boolean(item.when)))
@@ -632,11 +836,10 @@ export class ProjectMemory {
632
836
  retry = true,
633
837
  ): { status: string; entries: Ref[]; proposal_id?: string } {
634
838
  const epoch = this.store.epoch(d.id)
635
- const current = this.store.list(d.id).filter((r) => !isKnowledge(r))
636
839
  const pending: DraftItem[] = [],
637
840
  ready: DraftItem[] = []
638
841
  for (const item of items) {
639
- const conflict = this.projectConflict(item, current)
842
+ const conflict = this.projectConflict(d.id, item)
640
843
  if (conflict || item.conflicts_with_repo_guidance || needsHumanReview(item) || !validateRule(d, item).ok)
641
844
  pending.push(item)
642
845
  else ready.push(item)
@@ -655,7 +858,7 @@ export class ProjectMemory {
655
858
  }
656
859
  return { status: saved?.state ?? 'skipped', entries: saved?.entries ?? [] }
657
860
  }
658
- propose(agent: Agent, input: unknown) {
861
+ proposalContext(agent: Agent) {
659
862
  const d = this.domain(agent)
660
863
  if (!d) throw new StoreError('unavailable')
661
864
  let root = agent
@@ -677,36 +880,91 @@ export class ProjectMemory {
677
880
  this.ctx.get('sandboxPolicy')?.resolve({ session: agent.session }).mode === 'read-only'
678
881
  )
679
882
  throw new StoreError('read_only')
680
- return this.applyProposals(root, agent, d, latestTurn(root.session), input)
883
+ return { root, domain: d, turnId: latestTurn(root.session) }
884
+ }
885
+ propose(agent: Agent, input: unknown, inputSlots?: readonly MemorySlot[], selections?: readonly (SelectionEvidence | undefined)[]) {
886
+ const { root, domain, turnId } = this.proposalContext(agent)
887
+ return this.applyProposals(root, agent, domain, turnId, input, { inputSlots, selections })
888
+ }
889
+ narrowToProject(agent: Agent, ref: Ref, clarification: string, generation: number,
890
+ epochs: ReadonlyMap<string, number>, candidate: SemanticCandidate) {
891
+ const project = this.rootDomain(agent, true)
892
+ if (project.id === this.personal.id || candidate.scope !== 'project') throw new StoreError('invalid_scope')
893
+ if (this.store.enabledGeneration() !== generation) throw new StoreError('memory_disabled')
894
+ const turnId = latestTurn(agent.session)
895
+ const current = this.proposalSources(agent, agent, project, turnId, generation)
896
+ if (current.reason) throw new StoreError(current.reason)
897
+ if (typeof clarification !== 'string' || !clarification.trim() || clarification.length > 480 ||
898
+ skipsAutomaticMemory(clarification)) throw new StoreError('invalid_source')
899
+ const excerpts = current.events.filter(block => !block.question && block.text.includes(clarification))
900
+ const block = excerpts[0]
901
+ if (excerpts.length !== 1 || block.text.indexOf(clarification) !== block.text.lastIndexOf(clarification))
902
+ throw new StoreError('invalid_source')
903
+ const start = (block.offset ?? 0) + block.text.indexOf(clarification)
904
+ const span = { seq: block.seq, start, end: start + clarification.length }
905
+ const source: Source = { storeId: block.storeId, sessionId: agent.id, turnId, seq: block.seq,
906
+ time: current.records.get(block.seq)?.time, origin: 'user' }
907
+ const result = this.store.narrowToProject(project.id, ref, source, clarification, span, generation, epochs, old => {
908
+ previousScopeAgreement(this, agent, project, ref, generation, turnId)
909
+ // A scope correction cannot edit the original claim or implicitly enable proactive delivery.
910
+ if (candidate.kind !== old.kind || candidate.subject !== old.subject || candidate.topic !== old.semanticTopic ||
911
+ candidate.usage !== old.usage || candidate.sensitive || candidate.replaces || skipsCandidate(candidate) ||
912
+ !isDeepStrictEqual(ruleFields(candidate), ruleFields(old))) throw new StoreError('target_mismatch')
913
+ const item = manualItem(project, ruleFields(old), loadedGuidance(agent.session, project, this.ctx))
914
+ const validity = validateRule(project, item)
915
+ if (!validity.ok || needsHumanReview(item)) throw new StoreError(validity.reason ?? 'needs_review')
916
+ const existing = this.store.comparisonHeads(project.id, 'action', item.action)
917
+ if (existing.some(rule => !isKnowledge(rule) && sameRule(item, rule)) || this.projectConflict(project.id, item)) throw new StoreError('conflict')
918
+ return { guidance: item.guidance, hard: item.hard }
919
+ })
920
+ if (result.status === 'duplicate' && !this.current(project, result.entries[0].id, result.entries[0].rev))
921
+ throw new StoreError('source_unavailable')
922
+ if (result.status === 'saved') notifyUI(this.ctx, agent.id)
923
+ return result
681
924
  }
682
925
  /** A background decision is bound to the original turn, even if a new one has started. */
683
- proposeFromTurn(root: Agent, turnId: string, input: unknown, reviewEpochs?: Map<string, number>) {
926
+ proposeFromTurn(root: Agent, turnId: string, input: unknown, reviewEpochs?: Map<string, number>,
927
+ selections?: readonly (SelectionEvidence | undefined)[]) {
684
928
  const domain = this.rootDomain(root, true)
685
- return this.applyProposals(root, root, domain, turnId, input, true, reviewEpochs)
929
+ return this.applyProposals(root, root, domain, turnId, input, { background: true, reviewEpochs, selections })
930
+ }
931
+ proposalSources(root: Agent, agent: Agent, domain: AccessDomain, turnId: string, generation: number | undefined):
932
+ { events: UserSource[]; records: Map<number, HostEvent>; reason?: string } {
933
+ const records = new Map(root.session.snapshotEvents().map(event => [event.seq, event]))
934
+ if (generation === undefined) return { events: [], records, reason: 'memory_disabled' }
935
+ const blocks = sources(root.session, domain, this.storeId(root.session), turnId)
936
+ if (blocks.some(block => block.refused || refusesAutomaticMemory(block.text) ||
937
+ refusesAutomaticMemory(messageText(records.get(block.seq)?.data)))) return { events: [], records, reason: 'opted_out' }
938
+ const authorized = blocks.filter(block => block.memoryGeneration === generation)
939
+ if (blocks.length && !authorized.length) return { events: [], records, reason: 'source_unavailable' }
940
+ const events = authorized.filter(block => (root === agent || !block.question) && !skipsAutomaticMemory(block.text) &&
941
+ !skipsAutomaticMemory(messageText(records.get(block.seq)?.data)))
942
+ return { events: agent === root ? events : events.map(({formSelections, ...block}) => block), records }
686
943
  }
687
944
  private applyProposals(root: Agent, agent: Agent, d: AccessDomain, turnId: string, input: unknown,
688
- background = false, reviewEpochs?: Map<string, number>) {
945
+ options: { background?: boolean; reviewEpochs?: Map<string, number>; inputSlots?: readonly MemorySlot[]; selections?: readonly (SelectionEvidence | undefined)[] }) {
946
+ const { background = false, reviewEpochs, inputSlots, selections } = options
689
947
  const rows = candidateRows(input)
948
+ if (inputSlots && (inputSlots.length !== rows.length || !inputSlots.every(isSemanticSlot))) throw new StoreError('invalid_input')
690
949
  const skipAll = (reason: string) => ({
691
- status: 'skipped', entries: [] as Ref[], results: rows.map((_, index) => ({ index, status: 'skipped', reason })),
950
+ status: 'skipped', entries: [] as Ref[], results: rows.map((_, index) => ({ index, status: 'skipped' as const, reason })),
692
951
  })
693
952
  const generation = this.store.enabledGeneration()
694
- if (generation === undefined) return skipAll('memory_disabled')
953
+ const { events, records, reason } = this.proposalSources(root, agent, d, turnId, generation)
954
+ if (reason || generation === undefined) return skipAll(reason ?? 'memory_disabled')
695
955
  const storeId = this.storeId(root.session)
696
- const blocks = sources(root.session, d, storeId, turnId)
697
- const records = new Map(root.session.snapshotEvents().map(event => [event.seq, event]))
698
- if (blocks.some(block => block.refused || refusesAutomaticMemory(block.text) ||
699
- refusesAutomaticMemory(messageText(records.get(block.seq)?.data)))) return skipAll('opted_out')
700
- const authorized = blocks.filter(block => block.memoryGeneration === generation)
701
- if (blocks.length && !authorized.length) return skipAll('source_unavailable')
702
- const events = authorized.filter(block => (root === agent || !block.question) && !skipsAutomaticMemory(block.text) &&
703
- !skipsAutomaticMemory(messageText(records.get(block.seq)?.data)))
704
956
  const groups = new Map<MemorySlot, SourcedCandidate[]>()
957
+ const claimSlots = new Map<string, MemorySlot>()
958
+ const ambiguousSlots = new Set<MemorySlot>()
705
959
  const outcomes: ProposalOutcome[] = []
706
960
  const guidance = loadedGuidance(root.session, d, this.ctx)
707
961
  for (const [index, raw] of rows.entries()) {
708
962
  try {
709
963
  const row = parseCandidate(raw)
964
+ // The reviewer can resolve a submitted label to a different canonical label.
965
+ // Bind the original claim as well, for source replay protection after withdrawal.
966
+ const inputSlot = inputSlots?.[index] ?? semanticSlot(row.scope, row.topic, row.subject)!
967
+ if ((row.scope === 'global') !== isPersonalSlot(inputSlot)) throw new StoreError('invalid_scope')
710
968
  if ((row.scope === 'project' && d.id === this.personal.id) ||
711
969
  (row.scope === 'global' && (root !== agent || row.paths.length))) {
712
970
  outcomes[index] = { status: 'skipped', reason: 'invalid_scope' }
@@ -718,20 +976,51 @@ export class ProjectMemory {
718
976
  }
719
977
  const [prepared] = prepareItems(d, { items: [ruleFields(row)] }, events, row.scope === 'project' ? guidance : [])
720
978
  const seq = prepared.evidence!.seq
979
+ const selection = selections?.[index]
980
+ if (selection) {
981
+ const eligible = root === agent && row.kind !== 'fact' &&
982
+ row.user_quote.includes(selection.directive) && standingRequest(selection.directive) &&
983
+ selectedAction(selection.directive, selection.option.label) === row.action &&
984
+ events.some(e => e.seq === seq && e.block === prepared.source?.block &&
985
+ e.formSelections?.some(option => isDeepStrictEqual(option, selection.option)))
986
+ if (!eligible) throw new StoreError('invalid_source')
987
+ prepared.source = { ...prepared.source!, formSelection: selection.option }
988
+ }
721
989
  const source: Source = { storeId, sessionId: root.id, turnId, seq, time: records.get(seq)?.time, origin: 'user' }
722
990
  const owner = row.scope === 'global' ? this.personal : d
723
- const matches = this.topicHeads(owner, row)
724
- const canonical = matches[0]?.semanticTopic ?? row.topic
991
+ const referenced = row.replaces ? this.store.read(owner.id, row.replaces.id) : undefined
992
+ if (row.replaces) {
993
+ if (!referenced) {
994
+ outcomes[index] = { status: 'skipped', reason: 'target_not_found' }
995
+ continue
996
+ }
997
+ const mismatch = targetMismatch(row, referenced)
998
+ if (mismatch) {
999
+ outcomes[index] = { status: 'skipped', reason: mismatch }
1000
+ continue
1001
+ }
1002
+ row.subject ??= referenced.subject
1003
+ if (referenced.rev !== row.replaces.rev) {
1004
+ const receipt = this.store.replayedReplacement(owner.id, row.replaces, source, semanticDraft(row, prepared, referenced))
1005
+ outcomes[index] = receipt ? { status: 'duplicate', ...receipt } : { status: 'skipped', reason: 'stale_revision' }
1006
+ continue
1007
+ }
1008
+ }
1009
+ const canonical = referenced?.semanticTopic ?? row.topic
1010
+ const matches = this.store.canonicalTopicHeads(owner.id, row.scope, canonical, row.subject)
725
1011
  const family = semanticSlot(row.scope, canonical, row.subject)!
726
- const referenced = row.replaces && matches.find(head => head.id === row.replaces!.id)
727
1012
  const context = matches.find(head => head.when === prepared.when && isDeepStrictEqual(head.paths, prepared.paths))
728
1013
  const observed = referenced || context
729
1014
  const slot = observed && isSemanticSlot(observed.slot) ? observed.slot : semanticSlot(row.scope, canonical, row.subject, prepared)!
1015
+ const claim = inputClaimKey(source, inputSlot, { ...prepared, kind: row.kind })!
1016
+ const assigned = claimSlots.get(claim)
1017
+ if (assigned && assigned !== slot) {
1018
+ ambiguousSlots.add(assigned)
1019
+ ambiguousSlots.add(slot)
1020
+ }
1021
+ claimSlots.set(claim, slot)
730
1022
  const group = groups.get(slot) ?? []
731
- const event = records.get(seq)
732
- const sourceText = event?.type === 'user/message' ? messageText(event.data) :
733
- events.find(block => block.seq === seq && block.text.includes(row.user_quote))!.text
734
- group.push({ index, row, prepared, source, sourceText, family, observed })
1023
+ group.push({ index, row, prepared, source, family, inputSlot, observed })
735
1024
  groups.set(slot, group)
736
1025
  } catch (error) {
737
1026
  // Preserve the established error response for a single invalid tool argument.
@@ -740,55 +1029,47 @@ export class ProjectMemory {
740
1029
  outcomes[index] = { status: 'skipped', reason: /^[a-z_]+$/.test(code) ? code : 'invalid_input' }
741
1030
  }
742
1031
  }
743
- const entries: Ref[] = []
744
1032
  for (const [slot, group] of groups) {
745
1033
  const owner = group[0].row.scope === 'global' ? this.personal : d
746
1034
  let result: ProposalOutcome
747
1035
  try {
748
1036
  const overlaps = [...groups].some(([otherSlot, others]) => otherSlot !== slot &&
749
1037
  others[0].family === group[0].family && !separateContexts(group[0].prepared, others[0].prepared))
750
- result = overlaps ? { status: 'skipped', reason: 'ambiguous_topic' } :
1038
+ result = overlaps || ambiguousSlots.has(slot) ? { status: 'skipped', reason: 'ambiguous_topic' } :
751
1039
  this.applySemantic(root, owner, slot, group, generation, background, reviewEpochs)
752
1040
  } catch (error) {
753
1041
  if (rows.length === 1) throw error
754
1042
  result = { status: 'skipped', reason: error instanceof StoreError ? error.code : 'write_failed' }
755
1043
  }
756
- if (result.status !== 'skipped') entries.push({ id: result.id, rev: result.rev })
757
1044
  for (const [position, candidate] of group.entries()) {
758
1045
  outcomes[candidate.index] = position > 0 && result.status === 'saved'
759
1046
  ? { ...result, status: 'duplicate' } : result
760
1047
  }
761
1048
  }
762
1049
  if (outcomes.some(item => item.status === 'saved')) notifyUI(this.ctx, root.id)
1050
+ const unique = new Map<string, Ref>()
1051
+ for (const result of outcomes) {
1052
+ if (result.status !== 'skipped') unique.set(result.id, { id: result.id, rev: result.rev })
1053
+ }
1054
+ const entries = [...unique.values()]
763
1055
  const status = !entries.length ? 'skipped' : outcomes.some(item => item.status === 'skipped') ? 'partial'
764
1056
  : outcomes.some(item => item.status === 'saved') ? 'saved' : 'duplicate'
765
1057
  return { status, entries, results: outcomes.map((result, index) => ({ index, ...result })) }
766
1058
  }
767
1059
 
768
- private topicHeads(owner: AccessDomain, row: SemanticCandidate) {
769
- const matches = this.store.semanticMatches(owner.id, row.scope, row.topic, row.subject)
770
- const canonical = matches[0]?.semanticTopic
771
- // A condition-specific head may carry an alias that its siblings don't. Compare all
772
- // contexts of the canonical topic before introducing another branch.
773
- if (canonical && normalizeLabel(canonical) !== normalizeLabel(row.topic) &&
774
- matches.every(head => normalizeLabel(head.semanticTopic!) === normalizeLabel(canonical)))
775
- return this.store.semanticMatches(owner.id, row.scope, canonical, row.subject)
776
- return matches
777
- }
778
-
779
1060
  private applySemantic(root: Agent, owner: AccessDomain, slot: MemorySlot, group: SourcedCandidate[],
780
1061
  generation: number, background: boolean, reviewEpochs?: Map<string, number>): ProposalOutcome {
781
1062
  const epoch = this.store.epoch(owner.id)
782
1063
  if (reviewEpochs && reviewEpochs.get(owner.id) !== epoch) return { status: 'skipped', reason: 'stale_revision' }
783
1064
  const items: DraftItem[] = []
784
1065
  const current = this.store.currentSlot(owner.id, slot)
785
- for (const { row, prepared, sourceText, source, observed } of group) {
786
- const plan = planSemantic(row, prepared, this.topicHeads(owner, row), sourceText, background,
787
- prefix => this.store.uniqueTopicPrefix(owner.id, row.scope, prefix, row.subject))
788
- if ('reason' in plan) return { status: 'skipped', reason: group.length > 1 ? 'ambiguous_topic' : plan.reason }
789
- if (background && row.replaces && plan.previous && !correctReviewSubject(row, sourceText,
790
- this.store.topicSubjects(owner.id, row.scope, plan.previous.semanticTopic!)))
791
- return { status: 'skipped', reason: 'ambiguous_topic' }
1066
+ for (const { row, prepared, source, observed } of group) {
1067
+ const target = row.replaces ? this.store.read(owner.id, row.replaces.id) : undefined
1068
+ if (row.replaces && (!target || target.rev !== row.replaces.rev))
1069
+ return { status: 'skipped', reason: 'stale_revision' }
1070
+ const matches = this.store.canonicalTopicHeads(owner.id, row.scope, target?.semanticTopic ?? row.topic, row.subject)
1071
+ const plan = planSemantic(row, prepared, matches, target, background, Boolean((prepared.source as Source | undefined)?.formSelection))
1072
+ if ('reason' in plan) return { status: 'skipped', reason: plan.reason }
792
1073
  if (observed?.id !== plan.previous?.id || observed?.rev !== plan.previous?.rev)
793
1074
  return { status: 'skipped', reason: 'stale_revision' }
794
1075
  // An explicit edit may have changed the conditions while retaining the original slot.
@@ -804,7 +1085,7 @@ export class ProjectMemory {
804
1085
  items.push({ ...item, source: { ...item.source as object, time: source.time } })
805
1086
  }
806
1087
  try {
807
- const inputSlots = group.map(({ row }) => semanticSlot(row.scope, row.topic, row.subject)!)
1088
+ const inputSlots = group.map(candidate => candidate.inputSlot)
808
1089
  const result = this.store.saveAutomatic(owner.id, root.id, group[0].source, items, epoch, generation, inputSlots)
809
1090
  if (result.state === 'stale') return { status: 'skipped', reason: 'stale_source' }
810
1091
  // Each successful automatic batch advances this domain exactly once. Keep the original
@@ -817,6 +1098,51 @@ export class ProjectMemory {
817
1098
  }
818
1099
  }
819
1100
 
1101
+ fileImport(agent: Agent, query: string, commandId: string) {
1102
+ const d = this.rootDomain(agent, query !== 'list')
1103
+ if (d.id === this.personal.id) throw new StoreError('project_required')
1104
+ if (query === 'list') return this.store.fileImports.list(d.id)
1105
+ const undo = /^undo (import-[a-f0-9-]+)$/u.exec(query)
1106
+ if (undo) {
1107
+ const result = this.store.fileImports.undo(d.id, agent.id, undo[1])
1108
+ notifyUI(this.ctx, agent.id)
1109
+ return result
1110
+ }
1111
+ const page = /^(all|agents|claude|claude-memory)(?: (\d{1,8}):([1-9]\d{0,7}))?$/u.exec(query || 'all')
1112
+ if (!page) throw new StoreError('invalid_command')
1113
+ const selection = page[1] as FileSelection
1114
+ if (!this.store.memoryEnabled()) throw new StoreError('memory_disabled')
1115
+ const event = agent.session.snapshotEvents().findLast(e => e.type === 'command/run' &&
1116
+ (e.data as { commandId?: string }).commandId === commandId)
1117
+ if (!event || !commandId) throw new StoreError('invalid_source')
1118
+ const source: Source = { storeId: this.storeId(agent.session), sessionId: agent.id,
1119
+ turnId: latestTurn(agent.session) || '0', seq: event.seq, origin: 'manual' }
1120
+ const scanned = scanImport(d.root, selection, Number(page[2] ?? 0), Number(page[3] ?? 1))
1121
+ const guidance = loadedGuidance(agent.session, d, this.ctx)
1122
+ const drafts = scanned.entries.flatMap(({ action, context, file }) => {
1123
+ try {
1124
+ const item = manualItem(d, { action, user_quote: action, when: context, exceptions: '', paths: [],
1125
+ conflicts_with_repo_guidance: false }, guidance, file)
1126
+ return [{ file, item: { ...item, usage: 'on_demand' as const } }]
1127
+ } catch {
1128
+ scanned.skipped++
1129
+ return []
1130
+ }
1131
+ })
1132
+ const next = scanned.next && '/project-memory import ' + selection + ' ' + scanned.next
1133
+ const staleImports = new Set(this.store.list(d.id)
1134
+ .filter(rule => rule.source.fileImport && this.validity(d, rule).reason === 'stale_guidance')
1135
+ .map(rule => rule.id + '@' + rule.rev))
1136
+ const result = this.store.fileImports.stage(d.id, source, page[0], scanned.files, scanned.skipped, drafts, next, staleImports)
1137
+ const announced = new Set(agent.session.snapshotEvents().filter(e => e.type === 'plugin:project-memory/proposal')
1138
+ .map(e => (e.data as { proposalId?: string }).proposalId))
1139
+ for (const id of result.proposals) {
1140
+ if (!announced.has(id) && this.store.proposal(d.id, agent.id, id)?.state === 'pending')
1141
+ this.announce(agent, 'proposal', { proposalId: id, state: 'pending', turnId: source.turnId })
1142
+ }
1143
+ return result
1144
+ }
1145
+
820
1146
  manual(
821
1147
  agent: Agent,
822
1148
  input: { turnId: number; items: DraftItem[]; userAuthored?: boolean },
@@ -871,26 +1197,34 @@ export class ProjectMemory {
871
1197
  }
872
1198
  // Only the human-facing manager searches these summaries. A project entry outside its
873
1199
  // valid scope contributes its public reason and id, never its body or retained wording.
874
- private managerStatus(withheld: ReviewEntry[], query: string) {
1200
+ private managerStatus(withheld: ReviewEntry[], query: string, locale?: 'en' | 'zh') {
1201
+ const labels = locale === 'en' ? uiMessages.en : uiMessages.zh
875
1202
  const needs_review = withheld.map((row) => {
876
- const reasonText = reviewReasonText[row.reason] ?? '当前项目无法核验此条记忆'
1203
+ const reasonText = labels['reason.' + row.reason] ?? labels['reason.unavailable']
877
1204
  const rule = row.scope === 'profile' ? this.store.read(this.personal.id, row.id, row.rev) : undefined
878
1205
  const quote = rule?.quoteType === 'user_quote' && rule.user_quote
879
- const statusLabel = ['outside_branch', 'outside_path', 'outside_environment'].includes(row.reason)
880
- ? '当前不适用' : '已停用'
881
- return { ...row, reasonText, statusLabel, ...(quote ? { quote } : {}) }
1206
+ const statusKey = ['outside_branch', 'outside_path', 'outside_environment'].includes(row.reason)
1207
+ ? 'section.inapplicable' : 'section.inactive'
1208
+ return { ...row, reasonText, statusKey, statusLabel: labels[statusKey], ...(quote ? { quote } : {}) }
882
1209
  }).filter((row) => containsWords(query, [
883
1210
  row.id + '@' + row.rev, row.action, row.previous, row.quote, row.reason, row.reasonText, row.kind,
884
- row.scope === 'profile' ? '全局' : '项目',
1211
+ labels[row.scope === 'profile' ? 'scope.global' : 'scope.project'],
885
1212
  row.statusLabel,
886
1213
  ]))
887
1214
  return { needs_review }
888
1215
  }
889
- view(agent: Agent) {
1216
+ view(agent: Agent, projection?: 'project' | 'profile' | 'chat', check?: ProjectionCheck) {
890
1217
  const d = this.rootDomain(agent)
891
- const delivered = this.scopes(agent, d).flatMap((s) => this.store.delivered(s.id, agent.id))
892
- const index = this.index(agent, d, true)
893
- const indexed = (r: Ref) => index.included.some((i) => i.id === r.id && i.rev === r.rev)
1218
+ const chat = projection === 'chat'
1219
+ const scopes = this.scopes(agent, d).filter(scope => !projection || chat ||
1220
+ (scope.id === this.personal.id ? 'profile' : 'project') === projection)
1221
+ const project = d.id !== this.personal.id
1222
+ const cards = project && !chat && projection !== 'profile' ? this.store.cards(d.id, agent.id) : []
1223
+ const conversationCards = project && chat ? this.store.conversationCards(d.id, agent.id) : []
1224
+ const pending = cards.some(card => card.state === 'pending')
1225
+ if (check) check.reusable = !pending && !conversationCards.some(card => card.state === 'pending')
1226
+ const receipts = conversationCards.flatMap(card => card.entries)
1227
+ const delivered = new Set<string>()
894
1228
  const eligible: Rule[] = []
895
1229
  const needs_review: ReviewEntry[] = []
896
1230
  // Saved in this session without a card. The turn that said it shows the line and its undo.
@@ -907,18 +1241,23 @@ export class ProjectMemory {
907
1241
  exceptions: string
908
1242
  previous?: string
909
1243
  }[] = []
910
- for (const scope of this.scopes(agent, d)) {
1244
+ for (const scope of scopes) {
911
1245
  const profile = scope.id === this.personal.id
912
- for (const rule of this.store.list(scope.id)) {
1246
+ for (const ref of this.store.delivered(scope.id, agent.id)) delivered.add(ref.id + '@' + ref.rev)
1247
+ const rows = chat ? this.store.chatHeads(scope.id, agent.id, profile ? [] : receipts) : this.store.list(scope.id)
1248
+ for (const rule of rows) {
1249
+ if (check?.reusable && !isDatabaseOnly(scope, rule)) check.reusable = false
913
1250
  const status = this.validity(scope, rule)
914
1251
  const automatic = rule.channel === 'automatic'
915
1252
  const mine = automatic && rule.source?.sessionId === agent.id
916
- if (mine && status.ok) {
1253
+ if (mine && status.ok && (chat || !projection)) {
1254
+ // A previous version can age out even when there has been no database write.
1255
+ if (check && rule.rev > 1) check.reusable = false
917
1256
  const before = !isKnowledge(rule) ? this.restorable(scope, rule)?.action : undefined
918
1257
  saved.push({
919
1258
  id: rule.id,
920
1259
  rev: rule.rev,
921
- turnId: rule.source.turnId,
1260
+ turnId: rule.source.scopeClarification?.turnId ?? rule.source.turnId,
922
1261
  usage: rule.usage ?? 'on_demand',
923
1262
  scope: profile ? 'profile' : 'project',
924
1263
  ...(rule.slot ? { slot: rule.slot } : {}),
@@ -930,17 +1269,29 @@ export class ProjectMemory {
930
1269
  })
931
1270
  }
932
1271
  if (status.ok) eligible.push(rule)
933
- else needs_review.push(this.reviewEntry(scope, rule, status.reason))
1272
+ else if (!chat) needs_review.push(this.reviewEntry(scope, rule, status.reason))
934
1273
  }
935
1274
  }
936
- const guidance = loadedGuidance(agent.session, d, this.ctx)
937
- const proposals = (d.id === this.personal.id ? [] : this.store.cards(d.id, agent.id)).map((card) => {
1275
+ const indexedHeads = new Set(eligible.some(row => row.usage === 'proactive')
1276
+ ? this.index(agent, d, true).included.map(row => row.id + '@' + row.rev) : [])
1277
+ const indexed = (r: Ref) => indexedHeads.has(r.id + '@' + r.rev)
1278
+ const available = new Set(eligible.map(row => row.id + '@' + row.rev))
1279
+ const guidance = pending ? loadedGuidance(agent.session, d, this.ctx) : []
1280
+ const related = pending ? eligible.filter(r => !isPersonalSlot(r.slot) && !isKnowledge(r)) : []
1281
+ const importValidity = new Map<string, boolean>()
1282
+ const proposals = cards.map((card) => {
938
1283
  let p = card
939
1284
  if (card.state === 'pending') {
940
1285
  const items = card.items.map((item) => {
941
1286
  let current
942
1287
  try {
943
- current = manualItem(d, ruleFields(item), guidance)
1288
+ const file = card.source.fileImport
1289
+ if (file) {
1290
+ const key = file.path + ':' + file.sha256
1291
+ if (!importValidity.has(key)) importValidity.set(key, currentImport(d.root, file))
1292
+ if (!importValidity.get(key)) throw new StoreError('stale_import')
1293
+ }
1294
+ current = manualItem(d, ruleFields(item), guidance, file, item.guidance as Parameters<typeof manualItem>[4])
944
1295
  } catch {
945
1296
  // A changed symlink or repo boundary can invalidate an old candidate.
946
1297
  // Keep the row rejectable and continue rendering the other cards.
@@ -960,10 +1311,7 @@ export class ProjectMemory {
960
1311
  ...p,
961
1312
  items: p.items.map((item) => ({
962
1313
  ...item,
963
- related: relatedRules(
964
- item,
965
- eligible.filter((r) => !isPersonalSlot(r.slot) && !isKnowledge(r)),
966
- ).map(publicRule),
1314
+ related: relatedRules(item, related).map(publicRule),
967
1315
  })),
968
1316
  receipt: p.receipt && {
969
1317
  ...p.receipt,
@@ -971,16 +1319,17 @@ export class ProjectMemory {
971
1319
  ...r,
972
1320
  indexed: r.indexed ?? indexed(r),
973
1321
  currentlyIndexed: indexed(r),
974
- available: eligible.some((current) => current.id === r.id && current.rev === r.rev),
1322
+ available: available.has(r.id + '@' + r.rev),
975
1323
  })),
976
1324
  },
977
1325
  }
978
1326
  })
979
1327
  return {
980
1328
  proposals,
1329
+ ...(chat && { conversationCards }),
981
1330
  needs_review,
982
1331
  saved: saved.sort((a, b) => Number(a.turnId) - Number(b.turnId)),
983
- rules: eligible.map(r => managerRule(r, indexed(r), delivered.some(ref => ref.id === r.id && ref.rev === r.rev))),
1332
+ rules: eligible.map(r => managerRule(r, indexed(r), delivered.has(r.id + '@' + r.rev))),
984
1333
  }
985
1334
  }
986
1335
  proposalOf(agent: Agent, id: string) {
@@ -1011,13 +1360,23 @@ export class ProjectMemory {
1011
1360
  const selections = input.selections.map((s) => {
1012
1361
  const original = p.items[s.index]
1013
1362
  if (!Number.isInteger(s.index) || !original) throw new StoreError('invalid_selection')
1014
- const validated = reviewItem(d, original, s.changes, s.exception, guidance, s.branch)
1015
- const item = { ...validated, ...semanticMetadata(original, validated.action) }
1363
+ const file = p.source.fileImport
1364
+ if (file && !currentImport(d.root, file)) throw new StoreError('stale_import')
1365
+ const validated = reviewItem(d, original, s.changes, s.exception, guidance, s.branch, file, s.guidanceReviewed)
1366
+ if (p.source.origin === 'tool' && (validated.user_quote || validated.action.length > 512 ||
1367
+ skipsAutomaticMemory([validated.action, validated.when, validated.exceptions, ...validated.paths].join('\n'))))
1368
+ throw new StoreError('invalid_input')
1369
+ if (file) {
1370
+ if (validated.action.length > 480 || skipsAutomaticMemory([validated.action, validated.when, validated.exceptions, ...validated.paths].join(' ')))
1371
+ throw new StoreError('invalid_item')
1372
+ validated.user_quote = validated.action
1373
+ }
1374
+ const item = { ...validated, ...semanticMetadata(original, validated.action), ...(file ? {kind:'rule' as const} : {}) }
1016
1375
  if (s.coexist && s.replace) throw new StoreError('invalid_selection')
1017
1376
  const replace = s.coexist ? undefined : (s.replace ?? (original.replace as Ref | undefined))
1018
1377
  if (replace && isKnowledge(this.store.read(d.id, replace.id, replace.rev) ?? original))
1019
1378
  throw new StoreError('invalid_selection')
1020
- if (!replace && !s.coexist && relatedRules(item, heads).length)
1379
+ if (!file && !replace && !s.coexist && relatedRules(item, heads).length)
1021
1380
  throw new StoreError('needs_resolution', '已有相关规则,请选择替代条目,或明确按不同条件并存。')
1022
1381
  return { index: s.index, item, replace }
1023
1382
  })
@@ -1031,7 +1390,7 @@ export class ProjectMemory {
1031
1390
  placement: (entries) => {
1032
1391
  for (const ref of entries) eligible.add(ref.id)
1033
1392
  const heads = scopes.flatMap((s) => this.store.list(s.id)).filter((r) => eligible.has(r.id))
1034
- const included = new Set(buildIndex(heads, withdrawn, this.config).included.map((r) => r.id))
1393
+ const included = new Set(buildIndex(heads, withdrawn, this.config, undefined, this.promptLanguage(agent)).included.map((r) => r.id))
1035
1394
  return {
1036
1395
  entries: entries.map((r) => ({ ...r, indexed: included.has(r.id) })),
1037
1396
  displaced: before.included.filter((r) => !included.has(r.id)).map((r) => r.id),
@@ -1041,63 +1400,89 @@ export class ProjectMemory {
1041
1400
  this.announce(agent, 'receipt', { proposalId: p.id, state: receipt.state, entries: receipt.entries })
1042
1401
  return receipt
1043
1402
  }
1403
+ private mayReadSourceSession(rule: Rule) {
1404
+ return !!rule.source.sessionId && this.ctx.get('remoteAccess')?.allows({ kind: 'session', id: rule.source.sessionId }) !== false
1405
+ }
1406
+ private readableToolSource(rule: Rule) {
1407
+ return rule.quoteType === 'tool_result' && rule.source.toolResult &&
1408
+ this.mayReadSourceSession(rule)
1409
+ }
1410
+ canPublishEvidence(rule: Rule, result: object) {
1411
+ if (!('quote' in result)) return true
1412
+ if (rule.user_quote !== result.quote || ('toolResult' in result && !this.readableToolSource(rule))) return false
1413
+ return !('source' in result || 'formSelection' in result || 'scopeClarification' in result) || this.mayReadSourceSession(rule)
1414
+ }
1415
+ private sameQuoteSource(a: Rule, b: Rule) {
1416
+ return a.quoteType === b.quoteType && a.user_quote === b.user_quote &&
1417
+ isDeepStrictEqual(a.evidence, b.evidence) && isDeepStrictEqual(a.source, b.source)
1418
+ }
1419
+ private sourceEvidence(d: AccessDomain, r: Rule, verified = false) {
1420
+ return {
1421
+ id: r.id, rev: r.rev, scope: d.id === this.personal.id ? 'profile' : 'project',
1422
+ evidence: r.quoteType === 'user_quote' ? 'retained_quote' : r.quoteType, quote: r.user_quote,
1423
+ ...(this.readableToolSource(r)
1424
+ ? { toolResult: r.source.toolResult, source: { session_id: r.source.sessionId, turn: r.source.turnId, seq: r.source.seq } } : {}),
1425
+ ...(r.source.fileImport ? { fileImport: r.source.fileImport } : {}),
1426
+ ...(r.source.scopeClarification && this.mayReadSourceSession(r) &&
1427
+ { scopeClarification: r.source.scopeClarification }),
1428
+ ...(r.source.formSelection && this.mayReadSourceSession(r) && { formSelection: r.source.formSelection }),
1429
+ ...(verified && r.evidence && this.mayReadSourceSession(r) && {
1430
+ evidence: 'verified_user_quote',
1431
+ source: { session_id: r.source.sessionId, turn: r.source.turnId, ...r.evidence },
1432
+ }),
1433
+ }
1434
+ }
1435
+ private async verifyQuote(d: AccessDomain, rule: Rule) {
1436
+ if (rule.quoteType !== 'user_quote' || !rule.user_quote || !rule.evidence || !this.mayReadSourceSession(rule)) return false
1437
+ const { seq, start, end } = rule.evidence
1438
+ if (!Number.isSafeInteger(seq) || seq < 0 || seq !== rule.source.seq ||
1439
+ !Number.isSafeInteger(start) || start < 0 || end !== start + rule.user_quote.length) return false
1440
+ try {
1441
+ const window = await this.ctx.get('sessionQuery')?.readEvent({ sessionId: rule.source.sessionId, seq, before: 0, after: 0 })
1442
+ if (!window || window.session.id !== rule.source.sessionId || window.target?.seq !== seq ||
1443
+ seq < window.inheritedEventCount || !this.mayReadSourceSession(rule) ||
1444
+ sourceStore(this.ctx, this.profile, window.session.createdAt) !== rule.source.storeId) return false
1445
+ const target = window.target as HostEvent
1446
+ if (target.data.turn !== undefined && String(target.data.turn) !== rule.source.turnId) return false
1447
+ if (target.type === 'user/message')
1448
+ return target.data.source?.kind === 'user' && messageText(target.data).slice(start, end) === rule.user_quote
1449
+ if (target.type !== 'tool/result') return false
1450
+ let origin = this.ctx.agents.get(rule.source.sessionId)?.session
1451
+ if (!origin && d.id === this.personal.id) {
1452
+ const loaded = await this.ctx.get('sessionController')?.resolveAgent(rule.source.sessionId)
1453
+ if (!loaded?.agent || loaded.agent !== this.ctx.agents.get(rule.source.sessionId)) return false
1454
+ origin = loaded.agent.session
1455
+ }
1456
+ if (!origin || origin.id !== rule.source.sessionId || origin.header.createdAt !== window.session.createdAt || !this.allows(origin))
1457
+ return false
1458
+ const live = origin.snapshotEvents()[seq]
1459
+ if (live?.type !== target.type || !isDeepStrictEqual(live.data, target.data)) return false
1460
+ // A global fact can come from a form submitted in a project; use that event's captured binding.
1461
+ const binding = d.id === this.personal.id ? boundSourceDomain(origin, rule.source.storeId, rule.source.turnId, seq) : d
1462
+ return !!binding && sources(origin, binding, rule.source.storeId, rule.source.turnId).some(block => {
1463
+ const offset = block.offset ?? 0
1464
+ return block.seq === seq && block.question && start >= offset && end <= offset + block.text.length &&
1465
+ block.text.slice(start - offset, end - offset) === rule.user_quote
1466
+ })
1467
+ } catch {
1468
+ return false
1469
+ }
1470
+ }
1044
1471
  async read(agent: Agent, id: string, rev?: number, expand = false) {
1045
1472
  const active = this.domain(agent)
1046
1473
  const d = active && this.owner(agent, active, id)
1047
1474
  const rule = d && this.current(d, id, rev)
1048
1475
  if (!d || !rule) return { status: 'not_found' }
1049
1476
  if (!expand) return publicRule(rule)
1050
- const evidenceOf = (r: Rule) => ({
1051
- id: r.id, rev: r.rev, scope: d.id === this.personal.id ? 'profile' : 'project',
1052
- evidence: r.quoteType === 'user_quote' ? 'retained_quote' : r.quoteType, quote: r.user_quote,
1053
- })
1054
- let verified = false
1055
- if (d.id !== this.personal.id && rule.evidence && rule.quoteType === 'user_quote') {
1056
- const query = this.ctx.get('sessionQuery')
1057
- const mayReadSource = () => this.ctx.get('remoteAccess')?.allows({ kind: 'session', id: rule.source.sessionId }) !== false
1058
- try {
1059
- const { seq, start, end } = rule.evidence
1060
- const window = mayReadSource() && await query?.readEvent({ sessionId: rule.source.sessionId, seq, before: 0, after: 0 })
1061
- if (
1062
- window && window.session.id === rule.source.sessionId && window.target?.seq === seq && mayReadSource() &&
1063
- sourceStore(this.ctx, this.profile, window.session.createdAt) === rule.source.storeId &&
1064
- seq >= window.inheritedEventCount
1065
- ) {
1066
- const target = window.target as HostEvent
1067
- if (target.type === 'user/message' && target.data.source?.kind === 'user' &&
1068
- messageText(target.data).slice(start, end) === rule.user_quote) verified = true
1069
- if (target.type === 'tool/result') {
1070
- const origin = this.ctx.agents.get(rule.source.sessionId)?.session
1071
- const live = origin?.snapshotEvents()[seq]
1072
- if (live?.type === target.type && isDeepStrictEqual(live.data, target.data) && origin && origin.header.createdAt === window.session.createdAt && this.allows(origin) &&
1073
- sources(origin, d, rule.source.storeId, rule.source.turnId).some(block => {
1074
- const offset = block.offset ?? 0
1075
- return block.seq === seq && block.question && start >= offset && end <= offset + block.text.length &&
1076
- block.text.slice(start - offset, end - offset) === rule.user_quote
1077
- })) verified = true
1078
- }
1079
- }
1080
- } catch {
1081
- /* A deleted source leaves only the approved short quote. */
1082
- }
1083
- const now = this.domain(agent)
1084
- const head = now?.id === d.id && this.current(now, id, rule.rev)
1085
- if (!head) return { status: 'not_found' }
1086
- if (head.user_quote !== rule.user_quote || head.quoteType !== rule.quoteType)
1087
- return evidenceOf(head)
1088
- }
1089
- return {
1090
- ...evidenceOf(rule),
1091
- ...(verified && rule.evidence
1092
- ? {
1093
- evidence: 'verified_user_quote',
1094
- source: {
1095
- session_id: rule.source.sessionId,
1096
- turn: rule.source.turnId,
1097
- ...rule.evidence,
1098
- },
1099
- }
1100
- : {}),
1101
- }
1477
+ const retained = this.sourceEvidence(d, rule)
1478
+ if (d.id === this.personal.id || !rule.evidence || rule.quoteType !== 'user_quote')
1479
+ return retained
1480
+ const verified = await this.verifyQuote(d, rule)
1481
+ const now = this.domain(agent)
1482
+ const head = now?.id === d.id && this.current(now, id, rule.rev)
1483
+ if (!head) return { status: 'not_found' }
1484
+ if (!this.sameQuoteSource(rule, head)) return this.sourceEvidence(d, head)
1485
+ if (!this.canPublishEvidence(head, retained)) return { status: 'not_found' }
1486
+ return verified ? this.sourceEvidence(d, head, true) : retained
1102
1487
  }
1103
1488
  }