dsh-memory-bond 0.0.0-stage → 1.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (126) hide show
  1. package/CHANGELOG.md +10 -0
  2. package/LICENSE +21 -0
  3. package/README.md +181 -2
  4. package/README.zh-CN.md +180 -0
  5. package/SECURITY.md +29 -0
  6. package/client/memory-icon.svg +21 -0
  7. package/cordis.patch.yml +3 -0
  8. package/dist/audit.js +286 -0
  9. package/dist/automatic.js +16 -0
  10. package/dist/cache.js +40 -0
  11. package/dist/client.js +2035 -0
  12. package/dist/command-scope.js +123 -0
  13. package/dist/commands.js +156 -0
  14. package/dist/consolidation-store.js +357 -0
  15. package/dist/consolidation.js +182 -0
  16. package/dist/domain.js +245 -0
  17. package/dist/encoder.js +138 -0
  18. package/dist/export-files.js +161 -0
  19. package/dist/file-import-store.js +120 -0
  20. package/dist/file-import.js +265 -0
  21. package/dist/foreground-attempts.js +91 -0
  22. package/dist/guidance.js +242 -0
  23. package/dist/host.js +19 -0
  24. package/dist/index-policy.js +191 -0
  25. package/dist/index.js +349 -0
  26. package/dist/knowledge-hooks.js +398 -0
  27. package/dist/knowledge.js +359 -0
  28. package/dist/maintenance-episodes.js +73 -0
  29. package/dist/maintenance-import.js +92 -0
  30. package/dist/maintenance-store.js +738 -0
  31. package/dist/maintenance.js +376 -0
  32. package/dist/model-review.js +16 -0
  33. package/dist/personal.js +60 -0
  34. package/dist/policy.js +382 -0
  35. package/dist/prompt-copy.js +93 -0
  36. package/dist/proposal-receipts.js +70 -0
  37. package/dist/proposal-review.js +656 -0
  38. package/dist/propose-contract.js +38 -0
  39. package/dist/question-answers.js +176 -0
  40. package/dist/retrieval.js +126 -0
  41. package/dist/scope-narrowing.js +49 -0
  42. package/dist/search-index.js +164 -0
  43. package/dist/search-words.js +5 -0
  44. package/dist/semantic.js +157 -0
  45. package/dist/service.js +1473 -0
  46. package/dist/sharing.js +289 -0
  47. package/dist/sources.js +149 -0
  48. package/dist/store.js +1578 -0
  49. package/dist/tool-experience.js +87 -0
  50. package/dist/turn-review-store.js +159 -0
  51. package/dist/turn-review.js +459 -0
  52. package/dist/ui.js +346 -0
  53. package/dist/vector-index.js +232 -0
  54. package/docs/architecture.zh-CN.md +52 -0
  55. package/docs/benchmark.zh-CN.md +60 -0
  56. package/docs/benchmarks/repository-tasks.json +5355 -0
  57. package/docs/images/bond-memory-principle-en.svg +644 -0
  58. package/docs/images/bond-memory-principle-zh.svg +644 -0
  59. package/docs/images/bond-memory-principle.drawio +644 -0
  60. package/docs/images/memory-settings-en.png +0 -0
  61. package/docs/images/memory-settings-zh.png +0 -0
  62. package/docs/images/memory-turn-recalled-en.png +0 -0
  63. package/docs/images/memory-turn-recalled-zh.png +0 -0
  64. package/docs/images/memory-turn-saved-en.png +0 -0
  65. package/docs/images/memory-turn-saved-zh.png +0 -0
  66. package/docs/media/memory-bond-name-en.gif +0 -0
  67. package/docs/media/memory-bond-name-en.mp4 +0 -0
  68. package/docs/media/memory-bond-name-zh.gif +0 -0
  69. package/docs/media/memory-bond-name-zh.mp4 +0 -0
  70. package/locale/detail.en.md +13 -0
  71. package/locale/detail.zh.md +13 -0
  72. package/locale/en.json +345 -0
  73. package/locale/zh.json +345 -0
  74. package/native/embeddings/NOTICE.md +12 -0
  75. package/package.json +117 -4
  76. package/scripts/benchmark-bond.mjs +72 -0
  77. package/scripts/benchmark-conditions.mjs +144 -0
  78. package/scripts/benchmark-example.mjs +37 -0
  79. package/scripts/benchmark-scale.mjs +119 -0
  80. package/scripts/benchmark-scenarios.mjs +57 -0
  81. package/scripts/benchmark-tasks.mjs +244 -0
  82. package/src/audit.ts +286 -0
  83. package/src/automatic.ts +21 -0
  84. package/src/cache.ts +38 -0
  85. package/src/command-scope.ts +125 -0
  86. package/src/commands.ts +159 -0
  87. package/src/consolidation-store.ts +350 -0
  88. package/src/consolidation.ts +176 -0
  89. package/src/domain.ts +254 -0
  90. package/src/encoder.ts +142 -0
  91. package/src/export-files.ts +178 -0
  92. package/src/file-import-store.ts +139 -0
  93. package/src/file-import.ts +256 -0
  94. package/src/foreground-attempts.ts +97 -0
  95. package/src/guidance.ts +265 -0
  96. package/src/host.ts +119 -0
  97. package/src/index-policy.ts +231 -0
  98. package/src/index.ts +333 -0
  99. package/src/knowledge-hooks.ts +456 -0
  100. package/src/knowledge.ts +432 -0
  101. package/src/maintenance-episodes.ts +76 -0
  102. package/src/maintenance-import.ts +107 -0
  103. package/src/maintenance-store.ts +868 -0
  104. package/src/maintenance.ts +380 -0
  105. package/src/model-review.ts +27 -0
  106. package/src/personal.ts +68 -0
  107. package/src/policy.ts +508 -0
  108. package/src/prompt-copy.ts +99 -0
  109. package/src/proposal-receipts.ts +59 -0
  110. package/src/proposal-review.ts +614 -0
  111. package/src/propose-contract.ts +39 -0
  112. package/src/question-answers.ts +181 -0
  113. package/src/retrieval.ts +133 -0
  114. package/src/scope-narrowing.ts +58 -0
  115. package/src/search-index.ts +177 -0
  116. package/src/search-words.ts +6 -0
  117. package/src/semantic.ts +178 -0
  118. package/src/service.ts +1488 -0
  119. package/src/sharing.ts +349 -0
  120. package/src/sources.ts +150 -0
  121. package/src/store.ts +1829 -0
  122. package/src/tool-experience.ts +93 -0
  123. package/src/turn-review-store.ts +158 -0
  124. package/src/turn-review.ts +418 -0
  125. package/src/ui.ts +385 -0
  126. package/src/vector-index.ts +228 -0
package/src/service.ts ADDED
@@ -0,0 +1,1488 @@
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'
4
+ import { isKnowledge, knowledgeValid, knowledgeDetails, reviseKnowledge, type AnchorCache } from './knowledge.ts'
5
+ import { isPersonalSlot, isSemanticSlot, normalizeLabel, semanticSlot, validLabel, type MemorySlot } from './personal.ts'
6
+ import { candidateRows, parseCandidate, planSemantic, semanticDraft, targetMismatch, sameSemanticContent, separateContexts, skipsCandidate, type SemanticCandidate } from './semantic.ts'
7
+ import { isDeepStrictEqual } from 'node:util'
8
+ import { realpathSync } from 'node:fs'
9
+ import { createRequire } from 'node:module'
10
+ import { refusesAutomaticMemory, skipsAutomaticMemory } from './automatic.ts'
11
+ import { resolveDomainCached, type AccessDomain } from './domain.ts'
12
+ import {
13
+ MemoryStore,
14
+ inputClaimKey,
15
+ revisionDraft,
16
+ StoreError,
17
+ type DraftItem,
18
+ type Proposal,
19
+ type Ref,
20
+ type Rule,
21
+ type Source,
22
+ } from './store.ts'
23
+ import {
24
+ type ProposalFields,
25
+ type UserSource,
26
+ buildIndex,
27
+ manualItem,
28
+ needsHumanReview,
29
+ prepareItems,
30
+ relatedRules,
31
+ reviewItem,
32
+ sameRule,
33
+ validateRule,
34
+ } from './policy.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'
39
+ import {
40
+ messageText,
41
+ type Agent,
42
+ type Host,
43
+ type HostEvent,
44
+ type Message,
45
+ type PluginConfig,
46
+ type Session,
47
+ type RecordEvent,
48
+ } from './host.ts'
49
+ import { currentImport, scanImport, type FileSelection } from './file-import.ts'
50
+ import { notifyUI } from './ui.ts'
51
+ import { actionInDomain } from './command-scope.ts'
52
+ import { previousScopeAgreement } from './scope-narrowing.ts'
53
+
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
+ }
62
+ export const ruleFields = (r: ProposalFields) => ({
63
+ action: r.action,
64
+ when: r.when,
65
+ exceptions: r.exceptions,
66
+ paths: r.paths,
67
+ user_quote: r.user_quote,
68
+ conflicts_with_repo_guidance: r.conflicts_with_repo_guidance,
69
+ })
70
+ export const publicRule = (r: Rule) => ({
71
+ id: r.id,
72
+ rev: r.rev,
73
+ action: r.action,
74
+ when: r.when,
75
+ exceptions: r.exceptions,
76
+ paths: r.paths,
77
+ kind: r.kind ?? 'preference',
78
+ pinned: r.pinned,
79
+ usage: r.usage ?? 'on_demand',
80
+ usageOverride: r.usageOverride === true,
81
+ sensitive: r.sensitive === true,
82
+ subject: r.subject,
83
+ channel: r.channel,
84
+ ...knowledgeDetails(r),
85
+ ...(isSemanticSlot(r.slot) ? { topic: r.semanticTopic, keywords: r.keywords } : {}),
86
+ scope: r.domainId === 'profile:personal' ? 'profile' : 'project',
87
+ localException: r.localException,
88
+ })
89
+ function managerRule(rule: Rule, indexed: boolean, delivered: boolean) {
90
+ const canChangeUsage = !rule.sensitive && rule.kind !== 'fact' && !isKnowledge(rule)
91
+ return { ...publicRule(rule), canChangeUsage, indexed, delivered }
92
+ }
93
+ const exactMemoryId = /^(mem-[\da-f-]+)(?:@(\d+))?$/u
94
+
95
+ function semanticMetadata(row: DraftItem, action = row.action) {
96
+ if (!isSemanticSlot(row.slot)) return { usage: row.usage ?? 'on_demand', usageOverride: row.usageOverride }
97
+ return {
98
+ subject: row.subject, usage: row.usage, usageOverride: row.usageOverride,
99
+ slot: row.slot, kind: row.kind, semanticTopic: row.semanticTopic, sensitive: row.sensitive,
100
+ keywords: row.keywords?.filter(word => !row.action.includes(word) || action.includes(word)),
101
+ }
102
+ }
103
+
104
+ interface ReviewEntry extends Ref {
105
+ kind: string
106
+ reason: string
107
+ scope: 'profile' | 'project'
108
+ action?: string
109
+ previous?: string
110
+ }
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>>
116
+ function containsWords(query: string, fields: (string | undefined)[]) {
117
+ const text = fields.join(' ').normalize('NFKC').toLocaleLowerCase()
118
+ const words = query.normalize('NFKC').trim().toLocaleLowerCase().split(/\s+/u)
119
+ return words.every((word) => text.includes(word))
120
+ }
121
+ export function latestTurn(session: Session): string {
122
+ const turn = session.snapshotEvents().findLast((e) => e.type === 'turn/start')?.data.turn
123
+ return turn === undefined ? '' : String(turn)
124
+ }
125
+ export function matches(rule: Rule, query: string) {
126
+ const haystack = [
127
+ rule.id,
128
+ rule.action,
129
+ rule.when,
130
+ rule.exceptions,
131
+ rule.slot,
132
+ ...(Array.isArray(rule.keywords) ? rule.keywords : []),
133
+ rule.semanticTopic, rule.subject,
134
+ ...rule.paths,
135
+ ]
136
+ .join(' ')
137
+ .toLocaleLowerCase()
138
+ return query
139
+ .trim()
140
+ .toLocaleLowerCase()
141
+ .split(/\s+/)
142
+ .every((word) => haystack.includes(word))
143
+ }
144
+ interface ReviewSelection {
145
+ index: number
146
+ changes?: Partial<ReturnType<typeof ruleFields>>
147
+ exception?: { environment: string; scope: string; commands?: { present: string[]; absent: string[] } }
148
+ replace?: Ref
149
+ coexist?: boolean
150
+ guidanceReviewed?: boolean
151
+ branch?: string | null
152
+ }
153
+ interface ReviewInput extends Pick<Proposal, 'id' | 'revision' | 'digest'> {
154
+ selections: ReviewSelection[]
155
+ }
156
+
157
+ type ProposalOutcome =
158
+ | { status: 'saved' | 'duplicate'; id: string; rev: number }
159
+ | { status: 'skipped'; reason: string }
160
+
161
+ interface SourcedCandidate {
162
+ index: number
163
+ row: SemanticCandidate
164
+ prepared: DraftItem
165
+ source: Source
166
+ family: MemorySlot
167
+ inputSlot: MemorySlot
168
+ observed?: Ref
169
+ }
170
+
171
+ export class ProjectMemory {
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 }>()
211
+ captureTask(agent: Agent, message: Message, turn: number) {
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')
216
+ const generation = this.assistantGeneration()
217
+ const domain = generation === undefined ? undefined : this.domain(agent)
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
+ }
222
+ }
223
+
224
+ readonly personal: AccessDomain
225
+ readonly store: MemoryStore
226
+ readonly retrieval: Retrieval
227
+ readonly ctx: Host
228
+ readonly profile: string
229
+ readonly config: PluginConfig
230
+ readonly append: RecordEvent
231
+ constructor(ctx: Host, profile: string, config: PluginConfig, append: RecordEvent) {
232
+ this.append = append
233
+ this.store = new MemoryStore(profile, config.historyDays)
234
+ this.retrieval = new Retrieval(this.store)
235
+ const dir = realpathSync(profile)
236
+ this.personal = { id: 'profile:personal', root: dir, cwd: dir, profileDir: dir, git: false, machine: '' }
237
+ this.ctx = ctx
238
+ this.profile = profile
239
+ this.config = config
240
+ }
241
+ private allows(session: Session) {
242
+ const access = this.ctx.get('remoteAccess')
243
+ return (
244
+ access?.allows({ kind: 'global' }) !== false &&
245
+ access?.allows({ kind: 'session', id: session.id }) !== false
246
+ )
247
+ }
248
+ // A settings read failure must not abort a host step or expose stored memory.
249
+ assistantGeneration() {
250
+ try {
251
+ return this.store.enabledGeneration()
252
+ } catch (error) {
253
+ this.ctx.logger.warn('无法读取记忆开关,本步暂停使用记忆:' + String(error))
254
+ return undefined
255
+ }
256
+ }
257
+ domain(agent?: Agent) {
258
+ if (!agent || !this.allows(agent.session)) return
259
+ return this.domainOf(agent.session) ?? (this.isOwner(agent) ? this.personal : undefined)
260
+ }
261
+ private isOwner(agent: Agent) {
262
+ return agent.session.header.origin !== 'subagent' && this.ctx.agents.get(agent.id) === agent
263
+ }
264
+ scopes(agent: Agent, d: AccessDomain) {
265
+ return d.id !== this.personal.id && this.isOwner(agent) ? [d, this.personal] : [d]
266
+ }
267
+ owner(agent: Agent, d: AccessDomain, id: string) {
268
+ return this.scopes(agent, d).find((s) => this.store.read(s.id, id) || this.store.history(s.id, id).length)
269
+ }
270
+ visible(agent: Agent, d: AccessDomain) {
271
+ return this.scopes(agent, d).flatMap((s) => this.eligible(s))
272
+ }
273
+ domainOf(session: Session) {
274
+ return resolveDomainCached(this.profile, this.ctx.workingDirectory.get(session), this.config.nonGitRoots)
275
+ }
276
+ rootDomain(agent: Agent, write = false) {
277
+ if (!agent || this.ctx.agents.get(agent.id) !== agent || agent.session.header.origin === 'subagent')
278
+ throw new StoreError('unavailable')
279
+ if (write && this.ctx.get('sandboxPolicy')?.resolve({ session: agent.session }).mode === 'read-only')
280
+ throw new StoreError('read_only')
281
+ const domain = this.domain(agent)
282
+ if (!domain) throw new StoreError('unavailable')
283
+ return domain
284
+ }
285
+ storeId(session: Session) {
286
+ return sourceStore(this.ctx, this.profile, session.header.createdAt)
287
+ }
288
+ capture(session: Session, event: HostEvent) {
289
+ if (session.header.origin === 'subagent' || event.seq < session.inheritedEventCount) return
290
+ const chat = event.type === 'user/message' && event.data.source?.kind === 'user'
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
+ }
295
+ const owner = this.ctx.agents.get(session.id)
296
+ if (owner?.session !== session || this.ctx.get('sandboxPolicy')?.resolve({ session }).mode === 'read-only') return
297
+ let cwd: string | undefined = this.ctx.workingDirectory.get(session)
298
+ if (session.currentBatchPublication) {
299
+ // During batch publication the host projection already reflects the last
300
+ // member. A later cwd change must never authorize an earlier message.
301
+ const all = session.snapshotEvents()
302
+ const changes = all.slice(session.inheritedEventCount)
303
+ if (changes.some((e) => e.seq > event.seq && e.type === 'working-directory/change'))
304
+ cwd =
305
+ changes.findLast((e) => e.seq <= event.seq && e.type === 'working-directory/change')?.data.cwd ??
306
+ // An ordinary fork's header.cwd is the ancestor's ORIGINAL directory, which can be
307
+ // stale by a change the ancestor made before the fork boundary. Replay the inherited
308
+ // prefix for the directory actually in effect there before falling back further.
309
+ all.slice(0, session.inheritedEventCount).findLast((e) => e.type === 'working-directory/change')?.data
310
+ .cwd ??
311
+ session.header.cwd ??
312
+ this.ctx.workingDirectory.defaultDirectory
313
+ }
314
+ if (!this.allows(session)) return
315
+ const d = (cwd && resolveDomainCached(this.profile, cwd, this.config.nonGitRoots)) || this.personal
316
+ const storeId = this.storeId(session)
317
+ bindSource(
318
+ session,
319
+ event.seq,
320
+ d,
321
+ storeId,
322
+ this.store.enabledGeneration(),
323
+ this.append,
324
+ () => this.ctx.logger.warn('项目记忆无法保存当前消息的来源或记忆。'),
325
+ )
326
+ }
327
+ sources(agent: Agent, turnId: number) {
328
+ const d = this.rootDomain(agent)
329
+ const generation = this.store.enabledGeneration()
330
+ if (generation === undefined) return []
331
+ return sources(agent.session, d, this.storeId(agent.session), String(turnId)).filter(block => block.memoryGeneration === generation).map(({ text }) => ({
332
+ text,
333
+ }))
334
+ }
335
+ validity(d: AccessDomain, rule: Rule, anchors?: AnchorCache): { ok: boolean; reason?: string } {
336
+ if (isKnowledge(rule)) return knowledgeValid(d, rule, anchors)
337
+ return validateRule(d, rule)
338
+ }
339
+ eligible(d: AccessDomain) {
340
+ return this.store.list(d.id).filter((rule) => this.validity(d, rule).ok)
341
+ }
342
+ current(d: AccessDomain, id: string, rev?: number) {
343
+ const row = this.store.read(d.id, id, rev)
344
+ return row && this.validity(d, row).ok ? row : undefined
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
+ }
380
+ listConsolidation(agent: Agent) {
381
+ const project = this.rootDomain(agent)
382
+ if (project.id === this.personal.id) return []
383
+ return this.store.consolidation.suggestions(project.id).flatMap(pair => {
384
+ const left = this.current(project, pair.left.id, pair.left.rev)
385
+ const right = this.current(project, pair.right.id, pair.right.rev)
386
+ return left && right ? [{ left: publicRule(left), right: publicRule(right) }] : []
387
+ })
388
+ }
389
+ decideConsolidation(agent: Agent, left: Ref, right: Ref, keep: Ref | null) {
390
+ const project = this.rootDomain(agent, true)
391
+ if (project.id === this.personal.id ||
392
+ !this.current(project, left.id, left.rev) || !this.current(project, right.id, right.rev))
393
+ throw new StoreError('conflict')
394
+ this.store.consolidation.decide(project.id, left, right, keep, agent.id)
395
+ notifyUI(this.ctx, agent.id)
396
+ }
397
+ async search(agent: Agent, query: string, mode?: SearchMode, options: SearchOptions = {}, trace: SearchTrace = newSearchTrace(),
398
+ review?: { accept(rule: Rule): boolean; limit: number }) {
399
+ if (typeof query !== 'string' || query.length > 2048 ||
400
+ (mode !== undefined && !['hybrid', 'keyword', 'semantic'].includes(mode)) ||
401
+ (options.scope !== undefined && !['project', 'profile'].includes(options.scope)) ||
402
+ (options.subject !== undefined && !validLabel(options.subject)) ||
403
+ (options.topic !== undefined && !validLabel(options.topic)) ||
404
+ (options.alternateQuery !== undefined && (typeof options.alternateQuery !== 'string' || options.alternateQuery.length > 2048)))
405
+ throw new StoreError('invalid_input')
406
+ const d = this.domain(agent)
407
+ if (!d) return []
408
+ const scopes = this.scopes(agent, d).filter(s => !options.scope ||
409
+ (s.id === this.personal.id ? 'profile' : 'project') === options.scope)
410
+ type Candidate = { domain: string; id: string; rev?: number }
411
+ const collect = (visibleScopes: AccessDomain[], candidates: readonly Candidate[] | undefined, projection: 'ranking' | 'review' | 'source' = 'ranking') => {
412
+ const anchors: AnchorCache = new Map()
413
+ return visibleScopes.flatMap(scope => {
414
+ const refs = candidates?.filter(ref => ref.domain === scope.id)
415
+ const start = performance.now()
416
+ const rows = projection === 'source' ? this.store.readMany(scope.id, refs!) :
417
+ this.store.searchHeads(scope.id, refs, projection === 'review')
418
+ trace.sqliteMs += performance.now() - start
419
+ return rows.filter(rule => this.validity(scope, rule, anchors).ok).map(rule => ({ rule, domain: scope.id }))
420
+ })
421
+ }
422
+ const q = normalizeLabel(query)
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
430
+ const keywordStart = performance.now()
431
+ const keywordHits = !exact && !structured && (mode === 'keyword' || lexicalOnly || review) && (q || options.topic)
432
+ ? this.retrieval.keywordHits(domains, query, options)
433
+ : undefined
434
+ if (keywordHits) trace.sqliteMs += performance.now() - keywordStart
435
+ const candidates = exact
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) {
446
+ trace.match = 'empty_scope'
447
+ return []
448
+ }
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)
453
+ const active = this.domain(agent)
454
+ if (!active || this.ctx.agents.get(agent.id) !== agent || active.id !== d.id ||
455
+ active.root !== d.root || active.cwd !== d.cwd) return []
456
+ // Re-read returned revisions, permissions and their filesystem evidence after ranking.
457
+ // A unique exact-topic hit also needs to notice a concurrent insertion.
458
+ const visibleIds = new Set(this.scopes(agent, active).map(s => s.id))
459
+ const visible = scopes.filter(scope => visibleIds.has(scope.id))
460
+ if (trace.match === 'exact_topic') {
461
+ const exact = collect(visible, topicRefs(visible), 'source').map(row => row.rule)
462
+ if (exact.length > 1) {
463
+ trace.match = 'ambiguous'
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
479
+ }
480
+ }
481
+ return ranked.degraded ? Object.assign(result, { degraded: true }) : result
482
+ }
483
+ async manage(
484
+ agent: Agent,
485
+ op: string,
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},
489
+ ) {
490
+ const write = ['revise', 'usage', 'forget', 'undo', 'pin', 'unpin', 'clear-quote'].includes(op)
491
+ const d = this.rootDomain(agent, write)
492
+ if (op === 'list') {
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) }
503
+ }
504
+ if (op === 'search') return this.searchManagedRules(agent, d, args.query as string, args.mode as SearchMode, args.scope, args.locale)
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)
513
+ if (op === 'read' || op === 'source') return this.readManagedRule(agent, owner, ref, op === 'source')
514
+ if (!write) throw new StoreError('invalid_command')
515
+ const old = this.store.read(owner.id, ref.id, ref.rev)
516
+ if (!old) throw new StoreError('conflict')
517
+ switch (op) {
518
+ case 'revise':
519
+ return this.reviseManagedRule(agent, owner, old, args.action)
520
+ case 'undo': {
521
+ const result = this.undoAutomaticSave(agent, owner, old)
522
+ notifyUI(this.ctx, agent.id)
523
+ return result
524
+ }
525
+ case 'usage': {
526
+ if (args.usage !== 'proactive' && args.usage !== 'on_demand') throw new StoreError('invalid_item')
527
+ if (isKnowledge(old)) throw new StoreError('invalid_command')
528
+ const updated = this.store.setUsage(owner.id, agent.id, ref, args.usage)
529
+ notifyUI(this.ctx, agent.id)
530
+ return { status: 'saved', entries: [updated] }
531
+ }
532
+ case 'forget':
533
+ this.store.revoke(owner.id, ref.id, ref.rev, agent.id)
534
+ break
535
+ case 'clear-quote':
536
+ this.store.clearQuote(owner.id, ref.id, ref.rev, agent.id)
537
+ break
538
+ case 'pin':
539
+ case 'unpin':
540
+ if (op === 'pin' && old.usage !== 'proactive') throw new StoreError('on_demand')
541
+ this.store.pin(owner.id, ref.id, ref.rev, op === 'pin', agent.id)
542
+ break
543
+ }
544
+ notifyUI(this.ctx, agent.id)
545
+ return { status: op === 'forget' ? 'revoked' : op, ...ref }
546
+ }
547
+ private resolveManagedRef(agent: Agent, domain: AccessDomain, args: { id?: unknown; rev?: unknown; scope?: 'profile' | 'project' }) {
548
+ if (typeof args.id !== 'string' || !Number.isSafeInteger(args.rev) || Number(args.rev) < 1)
549
+ throw new StoreError('expected_revision')
550
+ const ref = { id: args.id, rev: Number(args.rev) }
551
+ const owner = this.owner(agent, domain, ref.id)
552
+ if (!owner || (args.scope && args.scope !== (owner.id === this.personal.id ? 'profile' : 'project')))
553
+ throw new StoreError('not_found')
554
+ return { owner, ref }
555
+ }
556
+ private async searchManagedRules(
557
+ agent: Agent, d: AccessDomain, query: string, mode?: SearchMode, filter?: SearchOptions['scope'], locale?: 'en' | 'zh',
558
+ ) {
559
+ const rules = await this.search(agent, query, mode, { scope: filter })
560
+ const live = this.rootDomain(agent)
561
+ if (d.id !== live.id || d.root !== live.root || d.cwd !== live.cwd) throw new StoreError('unavailable')
562
+ const scopes = this.scopes(agent, live).filter(scope => !filter ||
563
+ (scope.id === this.personal.id ? 'profile' : 'project') === filter)
564
+ const exact = exactMemoryId.exec(normalizeLabel(query))
565
+ const matches = new Map(rules.map(row => [row.id, row.rev]))
566
+ const current = new Map<string, Rule>()
567
+ const withheld: ReviewEntry[] = []
568
+ const anchors: AnchorCache = new Map()
569
+ for (const scope of scopes) {
570
+ // The manager can also find an invalid head by its public ID or reason.
571
+ const records = exact ? this.store.readMany(scope.id, [{
572
+ id: exact[1], rev: exact[2] ? Number(exact[2]) : undefined,
573
+ }]) : this.store.list(scope.id)
574
+ for (const rule of records) {
575
+ const status = this.validity(scope, rule, anchors)
576
+ if (!status.ok) withheld.push(this.reviewEntry(scope, rule, status.reason))
577
+ else if (matches.get(rule.id) === rule.rev) current.set(rule.id, rule)
578
+ }
579
+ }
580
+ const indexed = [...current.values()].some(row => row.usage === 'proactive' && !isKnowledge(row))
581
+ ? this.index(agent, live, true).included : []
582
+ const delivered = current.size ? scopes.flatMap(scope => this.store.delivered(scope.id, agent.id)) : []
583
+ const annotate = this.managerUsage(scopes)
584
+ return { rules: rules.flatMap(hit => {
585
+ const rule = current.get(hit.id)
586
+ return rule ? [managerRule(rule, indexed.some(ref => ref.id === rule.id && ref.rev === rule.rev),
587
+ delivered.some(ref => ref.id === rule.id && ref.rev === rule.rev))] : []
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}`) })
596
+ }
597
+ private async readManagedRule(agent: Agent, owner: AccessDomain, { id, rev }: Ref, expand: boolean) {
598
+ const result = await this.read(agent, id, rev, expand)
599
+ if (!('id' in result)) return result
600
+ const live = this.rootDomain(agent)
601
+ const scope = this.scopes(agent, live).find(s => s.id === owner.id)
602
+ const head = scope && this.current(scope, id, rev)
603
+ if (!head || !this.canPublishEvidence(head, result)) return { status: 'not_found' }
604
+ return 'quote' in result
605
+ ? { ...result, hasRetainedQuote: this.store.maintenance.hasRetainedQuote(owner.id, id) } : result
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
+ }
638
+ private recordEdit(agent: Agent, { id, rev }: Ref): Source {
639
+ const seq = this.append(agent.session, 'plugin:project-memory/edit', { id, rev })
640
+ return {
641
+ storeId: this.storeId(agent.session),
642
+ sessionId: agent.id,
643
+ turnId: latestTurn(agent.session) || '0',
644
+ seq,
645
+ origin: 'manual',
646
+ }
647
+ }
648
+ private reviseManagedRule(agent: Agent, owner: AccessDomain, old: Rule, input: unknown) {
649
+ if (typeof input !== 'string' || !input.trim() || input.length > 4096)
650
+ throw new StoreError('invalid_item')
651
+ const action = input.trim()
652
+ const ref = { id: old.id, rev: old.rev }
653
+ if (action === old.action) return { status: 'duplicate', entries: [ref] }
654
+ const source = this.recordEdit(agent, ref)
655
+ let item: DraftItem
656
+ if (isKnowledge(old)) item = reviseKnowledge(owner, old, action)
657
+ else if (owner.id === this.personal.id)
658
+ item = { ...ruleFields(old), slot: old.slot, kind: 'preference', ...semanticMetadata(old, action), action, user_quote: '' }
659
+ else {
660
+ item = manualItem(
661
+ owner,
662
+ { ...ruleFields(old), action, user_quote: '' },
663
+ loadedGuidance(agent.session, owner, this.ctx),
664
+ )
665
+ item = { ...item, ...semanticMetadata(old, action), replace: ref }
666
+ const branch = (old.hard as { branch?: string } | undefined)?.branch
667
+ if (branch) item.hard = { ...(item.hard as object), branch }
668
+ if (!validateRule(owner, item).ok) {
669
+ const p = this.pending(agent, owner, source, [item], 'settings')
670
+ return { status: 'pending', proposal_id: p.id }
671
+ }
672
+ }
673
+ const receipt = this.store.commitManual(owner.id, agent.id, source, item, ref, 'owner_card')
674
+ notifyUI(this.ctx, agent.id)
675
+ return { status: 'saved', entries: receipt.entries }
676
+ }
677
+ private undoAutomaticSave(agent: Agent, owner: AccessDomain, rule: Rule) {
678
+ if (rule.channel !== 'automatic') throw new StoreError('invalid_command')
679
+ const ref = { id: rule.id, rev: rule.rev }
680
+ const before = isKnowledge(rule) ? undefined : this.restorable(owner, rule)
681
+ if (!before) {
682
+ this.store.revoke(owner.id, ref.id, ref.rev, agent.id)
683
+ return { status: 'revoked', ...ref }
684
+ }
685
+ // The restored revision keeps its applicability and receives a new manual edit receipt.
686
+ const source = this.recordEdit(agent, ref)
687
+ const item = { ...revisionDraft(before), replace: ref, provenance: 'manual', actionInferred: true }
688
+ const receipt = this.store.commitManual(owner.id, agent.id, source, item, ref, 'owner_card')
689
+ return { status: 'restored', entries: receipt.entries }
690
+ }
691
+ private withdrawn(agent: Agent, d: AccessDomain) {
692
+ const withdrawn = new Set(this.store.withdrawn(d.id, agent.id))
693
+ const parent = agent.session.header.parentSession
694
+ if (parent && agent.session.inheritedEventCount) {
695
+ // Only notify a fork about parent exposures present in its inherited prefix.
696
+ const old = this.store.withdrawn(d.id, parent)
697
+ if (old.length) {
698
+ const inherited = agent.session.snapshotEvents().slice(0, agent.session.inheritedEventCount)
699
+ const sections = inherited
700
+ .filter((e) => e.type === 'user/message' && e.data.source?.kind === 'runtime-context')
701
+ .flatMap((e) => e.data.source?.sections ?? [])
702
+ .filter((section) => section.name === indexName)
703
+ // A lookup records the request domain. Profile entries can be read from any
704
+ // project, and the parent's delivery record already establishes their owner.
705
+ const lookups = inherited.filter(e => e.type === 'plugin:project-memory/lookup' &&
706
+ e.data.domainId && (d.id === this.personal.id || e.data.domainId === d.id))
707
+ const results = new Map(
708
+ inherited
709
+ .filter((e) => e.type === 'tool/result' && !e.data.message?.isError)
710
+ .map((e) => [e.data.message?.toolCallId, messageText(e.data.message)]),
711
+ )
712
+ for (const id of old) {
713
+ const expanded = lookups.some(
714
+ (e) => e.data.refs?.some((r) => r.id === id) && results.get(e.data.callId)?.includes(id),
715
+ )
716
+ if (
717
+ expanded ||
718
+ sections.some(
719
+ (section) => section.text.includes(id + '@') || [prompts.en, prompts.zh].some(copy => section.text.includes('[' + id + '] ' + copy.withdrawn)),
720
+ )
721
+ )
722
+ withdrawn.add(id)
723
+ }
724
+ }
725
+ }
726
+ return [...withdrawn].sort()
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>>
733
+ index(agent: Agent, d: AccessDomain, promptOnly = false) {
734
+ const generation = this.assistantGeneration()
735
+ if (generation === undefined) {
736
+ this.recentPrompt = undefined
737
+ return buildIndex<Rule>([], [])
738
+ }
739
+ const scopes = this.scopes(agent, d)
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
756
+ for (const rule of this.store.onDemandHeads(scope.id)) {
757
+ if (!this.validity(scope, rule).ok) continue
758
+ onDemand.push(rule)
759
+ if (promptOnly) break
760
+ }
761
+ }
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))
790
+ }
791
+ /** The nearest earlier version of an automatic save that may be put back. */
792
+ private restorable(d: AccessDomain, rule: Rule) {
793
+ return this.store.previous(d.id, rule.id, rule.rev)
794
+ }
795
+ private announce(agent: Agent, event: 'proposal' | 'receipt', fields: object) {
796
+ // SQLite is the authority. A disconnected renderer or a just-closed session
797
+ // must not turn a durable commit into an apparent failed write.
798
+ try {
799
+ this.append(agent.session, 'plugin:project-memory/' + event, fields)
800
+ } catch {
801
+ this.ctx.logger.warn('项目记忆回执已保存在收件箱,会话日志未能追加通知。')
802
+ }
803
+ try {
804
+ notifyUI(this.ctx, agent.id)
805
+ } catch {
806
+ this.ctx.logger.warn('项目记忆界面需要重新读取收件箱。')
807
+ }
808
+ }
809
+ private pending(root: Agent, d: AccessDomain, source: Source, items: DraftItem[], turnId?: string) {
810
+ const novel = items.filter(item => !this.store.comparisonHeads(d.id, 'action', item.action).some(rule => sameRule(item, rule)))
811
+ if (!novel.length) throw new StoreError('duplicate')
812
+ const p = this.store.propose(d.id, root.id, source, novel, turnId)
813
+ // A log-only identifier wakes headless observers. Body and approval digest stay in the store.
814
+ this.announce(root, 'proposal', {
815
+ proposalId: p.id,
816
+ revision: p.revision,
817
+ state: p.state,
818
+ turnId: turnId ?? p.turnId,
819
+ })
820
+ return p
821
+ }
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))
827
+ return relatedRules(item, current).some(rule => !sameRule(item, rule) &&
828
+ rule.when === item.when && JSON.stringify(rule.paths) === JSON.stringify(item.paths) &&
829
+ ((rule.slot && rule.slot === item.slot) || Boolean(item.when)))
830
+ }
831
+ private saveOrReview(
832
+ root: Agent,
833
+ d: AccessDomain,
834
+ source: Source,
835
+ items: DraftItem[],
836
+ retry = true,
837
+ ): { status: string; entries: Ref[]; proposal_id?: string } {
838
+ const epoch = this.store.epoch(d.id)
839
+ const pending: DraftItem[] = [],
840
+ ready: DraftItem[] = []
841
+ for (const item of items) {
842
+ const conflict = this.projectConflict(d.id, item)
843
+ if (conflict || item.conflicts_with_repo_guidance || needsHumanReview(item) || !validateRule(d, item).ok)
844
+ pending.push(item)
845
+ else ready.push(item)
846
+ }
847
+ let saved
848
+ try {
849
+ saved = ready.length ? this.store.saveAutomatic(d.id, root.id, source, ready, epoch) : undefined
850
+ } catch (e) {
851
+ if (retry && e instanceof StoreError && e.code === 'conflict')
852
+ return this.saveOrReview(root, d, source, items, false)
853
+ throw e
854
+ }
855
+ if (pending.length && source.origin === 'manual') {
856
+ const p = this.pending(root, d, source, pending, source.turnId)
857
+ return { status: p.state, proposal_id: p.id, entries: saved?.entries ?? [] }
858
+ }
859
+ return { status: saved?.state ?? 'skipped', entries: saved?.entries ?? [] }
860
+ }
861
+ proposalContext(agent: Agent) {
862
+ const d = this.domain(agent)
863
+ if (!d) throw new StoreError('unavailable')
864
+ let root = agent
865
+ if (agent.session.header.origin === 'subagent') {
866
+ root = this.ctx.get('subagents')?.rootOf(agent)
867
+ if (!root || this.rootDomain(root).id !== d.id) throw new StoreError('unavailable')
868
+ const last = root.session
869
+ .snapshotEvents()
870
+ .findLast((e) => e.type === 'turn/start' || e.type === 'turn/end')
871
+ if (last?.type !== 'turn/start') throw new StoreError('invalid_source')
872
+ }
873
+ this.rootDomain(root, true)
874
+ // A subagent's own sandbox mode is fixed at delegation and never widens from
875
+ // inside its session, even after the root is later elevated. rootDomain(root)
876
+ // above only reads the root's current mode, so the caller's own (possibly
877
+ // still read-only) mode needs its own check.
878
+ if (
879
+ agent !== root &&
880
+ this.ctx.get('sandboxPolicy')?.resolve({ session: agent.session }).mode === 'read-only'
881
+ )
882
+ throw new StoreError('read_only')
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
924
+ }
925
+ /** A background decision is bound to the original turn, even if a new one has started. */
926
+ proposeFromTurn(root: Agent, turnId: string, input: unknown, reviewEpochs?: Map<string, number>,
927
+ selections?: readonly (SelectionEvidence | undefined)[]) {
928
+ const domain = this.rootDomain(root, true)
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 }
943
+ }
944
+ private applyProposals(root: Agent, agent: Agent, d: AccessDomain, turnId: string, input: unknown,
945
+ options: { background?: boolean; reviewEpochs?: Map<string, number>; inputSlots?: readonly MemorySlot[]; selections?: readonly (SelectionEvidence | undefined)[] }) {
946
+ const { background = false, reviewEpochs, inputSlots, selections } = options
947
+ const rows = candidateRows(input)
948
+ if (inputSlots && (inputSlots.length !== rows.length || !inputSlots.every(isSemanticSlot))) throw new StoreError('invalid_input')
949
+ const skipAll = (reason: string) => ({
950
+ status: 'skipped', entries: [] as Ref[], results: rows.map((_, index) => ({ index, status: 'skipped' as const, reason })),
951
+ })
952
+ const generation = this.store.enabledGeneration()
953
+ const { events, records, reason } = this.proposalSources(root, agent, d, turnId, generation)
954
+ if (reason || generation === undefined) return skipAll(reason ?? 'memory_disabled')
955
+ const storeId = this.storeId(root.session)
956
+ const groups = new Map<MemorySlot, SourcedCandidate[]>()
957
+ const claimSlots = new Map<string, MemorySlot>()
958
+ const ambiguousSlots = new Set<MemorySlot>()
959
+ const outcomes: ProposalOutcome[] = []
960
+ const guidance = loadedGuidance(root.session, d, this.ctx)
961
+ for (const [index, raw] of rows.entries()) {
962
+ try {
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')
968
+ if ((row.scope === 'project' && d.id === this.personal.id) ||
969
+ (row.scope === 'global' && (root !== agent || row.paths.length))) {
970
+ outcomes[index] = { status: 'skipped', reason: 'invalid_scope' }
971
+ continue
972
+ }
973
+ if (skipsCandidate(row)) {
974
+ outcomes[index] = { status: 'skipped', reason: 'ineligible' }
975
+ continue
976
+ }
977
+ const [prepared] = prepareItems(d, { items: [ruleFields(row)] }, events, row.scope === 'project' ? guidance : [])
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
+ }
989
+ const source: Source = { storeId, sessionId: root.id, turnId, seq, time: records.get(seq)?.time, origin: 'user' }
990
+ const owner = row.scope === 'global' ? this.personal : d
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)
1011
+ const family = semanticSlot(row.scope, canonical, row.subject)!
1012
+ const context = matches.find(head => head.when === prepared.when && isDeepStrictEqual(head.paths, prepared.paths))
1013
+ const observed = referenced || context
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)
1022
+ const group = groups.get(slot) ?? []
1023
+ group.push({ index, row, prepared, source, family, inputSlot, observed })
1024
+ groups.set(slot, group)
1025
+ } catch (error) {
1026
+ // Preserve the established error response for a single invalid tool argument.
1027
+ if (!background && rows.length === 1) throw error
1028
+ const code = error instanceof Error ? error.message : ''
1029
+ outcomes[index] = { status: 'skipped', reason: /^[a-z_]+$/.test(code) ? code : 'invalid_input' }
1030
+ }
1031
+ }
1032
+ for (const [slot, group] of groups) {
1033
+ const owner = group[0].row.scope === 'global' ? this.personal : d
1034
+ let result: ProposalOutcome
1035
+ try {
1036
+ const overlaps = [...groups].some(([otherSlot, others]) => otherSlot !== slot &&
1037
+ others[0].family === group[0].family && !separateContexts(group[0].prepared, others[0].prepared))
1038
+ result = overlaps || ambiguousSlots.has(slot) ? { status: 'skipped', reason: 'ambiguous_topic' } :
1039
+ this.applySemantic(root, owner, slot, group, generation, background, reviewEpochs)
1040
+ } catch (error) {
1041
+ if (rows.length === 1) throw error
1042
+ result = { status: 'skipped', reason: error instanceof StoreError ? error.code : 'write_failed' }
1043
+ }
1044
+ for (const [position, candidate] of group.entries()) {
1045
+ outcomes[candidate.index] = position > 0 && result.status === 'saved'
1046
+ ? { ...result, status: 'duplicate' } : result
1047
+ }
1048
+ }
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()]
1055
+ const status = !entries.length ? 'skipped' : outcomes.some(item => item.status === 'skipped') ? 'partial'
1056
+ : outcomes.some(item => item.status === 'saved') ? 'saved' : 'duplicate'
1057
+ return { status, entries, results: outcomes.map((result, index) => ({ index, ...result })) }
1058
+ }
1059
+
1060
+ private applySemantic(root: Agent, owner: AccessDomain, slot: MemorySlot, group: SourcedCandidate[],
1061
+ generation: number, background: boolean, reviewEpochs?: Map<string, number>): ProposalOutcome {
1062
+ const epoch = this.store.epoch(owner.id)
1063
+ if (reviewEpochs && reviewEpochs.get(owner.id) !== epoch) return { status: 'skipped', reason: 'stale_revision' }
1064
+ const items: DraftItem[] = []
1065
+ const current = this.store.currentSlot(owner.id, slot)
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 }
1073
+ if (observed?.id !== plan.previous?.id || observed?.rev !== plan.previous?.rev)
1074
+ return { status: 'skipped', reason: 'stale_revision' }
1075
+ // An explicit edit may have changed the conditions while retaining the original slot.
1076
+ // Never let the store's slot replacement turn a planned insert into a revision.
1077
+ if (current?.id !== plan.previous?.id || current?.rev !== plan.previous?.rev)
1078
+ return { status: 'skipped', reason: 'conflict' }
1079
+ const item = plan.item
1080
+ if (item.slot !== slot || (items.length && !sameSemanticContent(items[0], item)))
1081
+ return { status: 'skipped', reason: 'ambiguous_topic' }
1082
+ if (item.conflicts_with_repo_guidance || needsHumanReview(item)) return { status: 'skipped', reason: 'needs_review' }
1083
+ const validity = validateRule(owner, item)
1084
+ if (!validity.ok) return { status: 'skipped', reason: validity.reason ?? 'ineligible' }
1085
+ items.push({ ...item, source: { ...item.source as object, time: source.time } })
1086
+ }
1087
+ try {
1088
+ const inputSlots = group.map(candidate => candidate.inputSlot)
1089
+ const result = this.store.saveAutomatic(owner.id, root.id, group[0].source, items, epoch, generation, inputSlots)
1090
+ if (result.state === 'stale') return { status: 'skipped', reason: 'stale_source' }
1091
+ // Each successful automatic batch advances this domain exactly once. Keep the original
1092
+ // snapshot for other domains and never absorb a concurrent writer's epoch.
1093
+ if (result.state === 'saved') reviewEpochs?.set(owner.id, epoch + 1)
1094
+ return { status: result.state, ...result.entries[0] }
1095
+ } catch (error) {
1096
+ if (error instanceof StoreError && error.code === 'conflict') return { status: 'skipped', reason: 'conflict' }
1097
+ throw error
1098
+ }
1099
+ }
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
+
1146
+ manual(
1147
+ agent: Agent,
1148
+ input: { turnId: number; items: DraftItem[]; userAuthored?: boolean },
1149
+ commandId?: string,
1150
+ replace?: Ref,
1151
+ ) {
1152
+ const d = this.rootDomain(agent, true)
1153
+ if (d.id === this.personal.id) throw new StoreError('project_required')
1154
+ if (!replace && !this.store.memoryEnabled()) throw new StoreError('memory_disabled')
1155
+ const turnId = String(input.turnId),
1156
+ storeId = this.storeId(agent.session)
1157
+ const generation = this.store.enabledGeneration()
1158
+ const events = sources(agent.session, d, storeId, turnId).filter(block =>
1159
+ generation !== undefined && block.memoryGeneration === generation && !block.question && !block.refused)
1160
+ if (!commandId && !events.length) throw new StoreError('invalid_source')
1161
+ const guidance = loadedGuidance(agent.session, d, this.ctx)
1162
+ if (!Array.isArray(input.items) || !input.items.length || input.items.length > 32)
1163
+ throw new StoreError('invalid_item')
1164
+ const items: DraftItem[] = input.userAuthored
1165
+ ? input.items.map((row) => manualItem(d, row, guidance))
1166
+ : prepareItems(d, { items: input.items }, events, guidance)
1167
+ const seq = input.userAuthored
1168
+ ? agent.session
1169
+ .snapshotEvents()
1170
+ .findLast((e) =>
1171
+ commandId
1172
+ ? e.type === 'command/run' && (e.data as { commandId?: string }).commandId === commandId
1173
+ : e.seq === events[0]?.seq,
1174
+ )?.seq
1175
+ : items[0]?.evidence?.seq
1176
+ if (seq === undefined) throw new StoreError('invalid_source')
1177
+ if (replace) {
1178
+ const old = this.store.read(d.id, replace.id, replace.rev)
1179
+ if (!old) throw new StoreError('conflict')
1180
+ items[0] = { ...items[0], ...semanticMetadata(old, items[0].action), replace }
1181
+ const branch = (old.hard as { branch?: string } | undefined)?.branch
1182
+ if (branch) items[0].hard = { ...(items[0].hard as object), branch }
1183
+ }
1184
+ const source: Source = {
1185
+ storeId,
1186
+ sessionId: agent.id,
1187
+ turnId,
1188
+ seq,
1189
+ origin: input.userAuthored ? 'manual' : 'user',
1190
+ }
1191
+ if (replace || !commandId) return this.pending(agent, d, source, items)
1192
+ return this.saveOrReview(agent, d, source, items)
1193
+ }
1194
+ private reviewEntry(scope: AccessDomain, rule: Rule, reason?: string): ReviewEntry {
1195
+ return { id: rule.id, rev: rule.rev, kind: rule.kind ?? 'preference', reason: reason ?? 'unavailable',
1196
+ scope: scope.id === this.personal.id ? 'profile' : 'project' }
1197
+ }
1198
+ // Only the human-facing manager searches these summaries. A project entry outside its
1199
+ // valid scope contributes its public reason and id, never its body or retained wording.
1200
+ private managerStatus(withheld: ReviewEntry[], query: string, locale?: 'en' | 'zh') {
1201
+ const labels = locale === 'en' ? uiMessages.en : uiMessages.zh
1202
+ const needs_review = withheld.map((row) => {
1203
+ const reasonText = labels['reason.' + row.reason] ?? labels['reason.unavailable']
1204
+ const rule = row.scope === 'profile' ? this.store.read(this.personal.id, row.id, row.rev) : undefined
1205
+ const quote = rule?.quoteType === 'user_quote' && rule.user_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 } : {}) }
1209
+ }).filter((row) => containsWords(query, [
1210
+ row.id + '@' + row.rev, row.action, row.previous, row.quote, row.reason, row.reasonText, row.kind,
1211
+ labels[row.scope === 'profile' ? 'scope.global' : 'scope.project'],
1212
+ row.statusLabel,
1213
+ ]))
1214
+ return { needs_review }
1215
+ }
1216
+ view(agent: Agent, projection?: 'project' | 'profile' | 'chat', check?: ProjectionCheck) {
1217
+ const d = this.rootDomain(agent)
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>()
1228
+ const eligible: Rule[] = []
1229
+ const needs_review: ReviewEntry[] = []
1230
+ // Saved in this session without a card. The turn that said it shows the line and its undo.
1231
+ const saved: {
1232
+ id: string
1233
+ rev: number
1234
+ turnId: string
1235
+ scope: 'profile' | 'project'
1236
+ slot?: string
1237
+ topic?: string
1238
+ usage: 'proactive' | 'on_demand'
1239
+ when: string
1240
+ action: string
1241
+ exceptions: string
1242
+ previous?: string
1243
+ }[] = []
1244
+ for (const scope of scopes) {
1245
+ const profile = scope.id === this.personal.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
1250
+ const status = this.validity(scope, rule)
1251
+ const automatic = rule.channel === 'automatic'
1252
+ const mine = automatic && rule.source?.sessionId === agent.id
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
1256
+ const before = !isKnowledge(rule) ? this.restorable(scope, rule)?.action : undefined
1257
+ saved.push({
1258
+ id: rule.id,
1259
+ rev: rule.rev,
1260
+ turnId: rule.source.scopeClarification?.turnId ?? rule.source.turnId,
1261
+ usage: rule.usage ?? 'on_demand',
1262
+ scope: profile ? 'profile' : 'project',
1263
+ ...(rule.slot ? { slot: rule.slot } : {}),
1264
+ ...(isSemanticSlot(rule.slot) ? { topic: rule.semanticTopic } : {}),
1265
+ when: rule.when,
1266
+ action: rule.action,
1267
+ exceptions: rule.exceptions,
1268
+ ...(before ? { previous: before } : {}),
1269
+ })
1270
+ }
1271
+ if (status.ok) eligible.push(rule)
1272
+ else if (!chat) needs_review.push(this.reviewEntry(scope, rule, status.reason))
1273
+ }
1274
+ }
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) => {
1283
+ let p = card
1284
+ if (card.state === 'pending') {
1285
+ const items = card.items.map((item) => {
1286
+ let current
1287
+ try {
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])
1295
+ } catch {
1296
+ // A changed symlink or repo boundary can invalidate an old candidate.
1297
+ // Keep the row rejectable and continue rendering the other cards.
1298
+ return { ...item, guidance: { files: [], origin: '.', status: 'unavailable' } }
1299
+ }
1300
+ const old = item.hard as { branch?: string } | undefined
1301
+ return {
1302
+ ...item,
1303
+ guidance: current.guidance,
1304
+ hard: { ...current.hard, ...(old?.branch ? { branch: old.branch } : {}) },
1305
+ }
1306
+ })
1307
+ if (card.epoch !== this.store.epoch(d.id) || JSON.stringify(items) !== JSON.stringify(card.items))
1308
+ p = this.store.refresh(d.id, agent.id, card.id, { items, digest: card.digest })!
1309
+ }
1310
+ return {
1311
+ ...p,
1312
+ items: p.items.map((item) => ({
1313
+ ...item,
1314
+ related: relatedRules(item, related).map(publicRule),
1315
+ })),
1316
+ receipt: p.receipt && {
1317
+ ...p.receipt,
1318
+ entries: p.receipt.entries.map((r) => ({
1319
+ ...r,
1320
+ indexed: r.indexed ?? indexed(r),
1321
+ currentlyIndexed: indexed(r),
1322
+ available: available.has(r.id + '@' + r.rev),
1323
+ })),
1324
+ },
1325
+ }
1326
+ })
1327
+ return {
1328
+ proposals,
1329
+ ...(chat && { conversationCards }),
1330
+ needs_review,
1331
+ saved: saved.sort((a, b) => Number(a.turnId) - Number(b.turnId)),
1332
+ rules: eligible.map(r => managerRule(r, indexed(r), delivered.has(r.id + '@' + r.rev))),
1333
+ }
1334
+ }
1335
+ proposalOf(agent: Agent, id: string) {
1336
+ const owner = this.rootDomain(agent)
1337
+ if (owner.id === this.personal.id) return
1338
+ const p = this.store.proposal(owner.id, agent.id, id)
1339
+ if (p) return { p, owner }
1340
+ }
1341
+ review(
1342
+ agent: Agent,
1343
+ input: ReviewInput,
1344
+ commandChoice?: 'all' | 'reject',
1345
+ channel: 'owner_card' | 'user_command' | 'in_process' = 'in_process',
1346
+ ) {
1347
+ const d = this.rootDomain(agent, true)
1348
+ const found = this.proposalOf(agent, input.id)
1349
+ if (!found) throw new StoreError('not_found')
1350
+ const { p, owner } = found
1351
+ if (p.revision !== input.revision || p.digest !== input.digest) throw new StoreError('conflict')
1352
+ const decision = commandChoice ?? input.selections
1353
+ if (p.receipt)
1354
+ return this.store.review(owner.id, agent.id, p.id, input.revision, input.digest, [], { decision })
1355
+ if (p.state !== 'pending') throw new StoreError('conflict')
1356
+ if (!Array.isArray(input.selections) || input.selections.length > p.items.length)
1357
+ throw new StoreError('invalid_selection')
1358
+ const guidance = loadedGuidance(agent.session, d, this.ctx)
1359
+ const heads = this.eligible(d).filter((r) => !isKnowledge(r))
1360
+ const selections = input.selections.map((s) => {
1361
+ const original = p.items[s.index]
1362
+ if (!Number.isInteger(s.index) || !original) throw new StoreError('invalid_selection')
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} : {}) }
1375
+ if (s.coexist && s.replace) throw new StoreError('invalid_selection')
1376
+ const replace = s.coexist ? undefined : (s.replace ?? (original.replace as Ref | undefined))
1377
+ if (replace && isKnowledge(this.store.read(d.id, replace.id, replace.rev) ?? original))
1378
+ throw new StoreError('invalid_selection')
1379
+ if (!file && !replace && !s.coexist && relatedRules(item, heads).length)
1380
+ throw new StoreError('needs_resolution', '已有相关规则,请选择替代条目,或明确按不同条件并存。')
1381
+ return { index: s.index, item, replace }
1382
+ })
1383
+ const before = this.index(agent, d)
1384
+ const eligible = new Set([...before.included, ...before.overflow].map((r) => r.id))
1385
+ const scopes = this.scopes(agent, d)
1386
+ const withdrawn = scopes.flatMap((s) => this.withdrawn(agent, s))
1387
+ const receipt = this.store.review(d.id, agent.id, p.id, input.revision, input.digest, selections, {
1388
+ decision,
1389
+ channel,
1390
+ placement: (entries) => {
1391
+ for (const ref of entries) eligible.add(ref.id)
1392
+ const heads = scopes.flatMap((s) => this.store.list(s.id)).filter((r) => eligible.has(r.id))
1393
+ const included = new Set(buildIndex(heads, withdrawn, this.config, undefined, this.promptLanguage(agent)).included.map((r) => r.id))
1394
+ return {
1395
+ entries: entries.map((r) => ({ ...r, indexed: included.has(r.id) })),
1396
+ displaced: before.included.filter((r) => !included.has(r.id)).map((r) => r.id),
1397
+ }
1398
+ },
1399
+ })
1400
+ this.announce(agent, 'receipt', { proposalId: p.id, state: receipt.state, entries: receipt.entries })
1401
+ return receipt
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
+ }
1471
+ async read(agent: Agent, id: string, rev?: number, expand = false) {
1472
+ const active = this.domain(agent)
1473
+ const d = active && this.owner(agent, active, id)
1474
+ const rule = d && this.current(d, id, rev)
1475
+ if (!d || !rule) return { status: 'not_found' }
1476
+ if (!expand) return publicRule(rule)
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
1487
+ }
1488
+ }