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/audit.ts CHANGED
@@ -2,6 +2,7 @@ import { createHash } from 'node:crypto'
2
2
  import { resolve, sep } from 'node:path'
3
3
  import { bashScope, literalActionCommand } from './command-scope.ts'
4
4
  import type { AccessDomain } from './domain.ts'
5
+ import { indexHintRefs } from './index-policy.ts'
5
6
  import { indexName, latestTurn, ProjectMemory } from './service.ts'
6
7
  import {
7
8
  messageText,
@@ -13,16 +14,18 @@ import {
13
14
  } from './host.ts'
14
15
  import type { AuditMeta, Ref } from './store.ts'
15
16
 
17
+ type RequestRef = Ref & { hintOnly?: boolean; viaLookup?: boolean; actionable?: boolean }
18
+ type Exposure = RequestRef & { domain: string }
16
19
  interface Step {
17
20
  turn: string
18
21
  step: number
19
22
  attempts: number
20
- exposed: Ref[]
23
+ exposed: Exposure[]
21
24
  generation?: number
22
25
  }
23
26
  interface ReadResult {
24
27
  domain: string
25
- refs: Ref[]
28
+ refs: (Ref & { bodyDigest: string; denial?: true })[]
26
29
  searchContext?: string
27
30
  }
28
31
  export function searchContext(agent: Agent, domain: AccessDomain, generation: number) {
@@ -30,7 +33,15 @@ export function searchContext(agent: Agent, domain: AccessDomain, generation: nu
30
33
  return turn && JSON.stringify([turn, domain.id, domain.cwd, generation])
31
34
  }
32
35
  // Pinning can change the public result without creating a new revision.
33
- export const searchRowDigest = (row: object) => createHash('sha256').update(JSON.stringify(row)).digest('hex')
36
+ export const searchRowDigest = (row: object | string) => createHash('sha256').update(JSON.stringify(row)).digest('hex')
37
+ const bodyDigest = (row: Ref & { action: string }) => searchRowDigest([row.id, row.rev, row.action])
38
+ function writeReceiptBodies(results: unknown): (Ref & { bodyDigest: string })[] {
39
+ if (!Array.isArray(results)) return []
40
+ return results.flatMap(row =>
41
+ (row?.status === 'saved' || row?.status === 'duplicate') && typeof row.id === 'string' &&
42
+ Number.isSafeInteger(row.rev) && typeof row.stored?.action === 'string' && row.stored.action
43
+ ? [{ id: row.id, rev: row.rev, bodyDigest: searchRowDigest([row.id, row.rev, row.stored]) }] : [])
44
+ }
34
45
  const refsIn = (text: string): Ref[] =>
35
46
  Array.from(text.matchAll(/\b(mem-[\da-f-]+)@(\d+)\b/gi), (m) => ({ id: m[1], rev: Number(m[2]) }))
36
47
 
@@ -39,13 +50,15 @@ export function registerAudit(memory: ProjectMemory, isAgentLoopRequest: (req: u
39
50
  const steps = new WeakMap<Session, Step>()
40
51
  const lookups = new WeakMap<Session, Map<string, ReadResult>>()
41
52
  const visibleSearches = new WeakMap<Agent, { context: string; rows: Map<string, string> }>()
42
- const commands = new WeakMap<Session, Map<string, { generation: number; domain: string; refs: Ref[]; cwd: string }>>()
43
- const meta = (agent: Agent, extra: AuditMeta = {}) => ({
53
+ const commands = new WeakMap<Session, Map<string, {
54
+ generation: number; domain: string; refs: Exposure[]; command: string; cwd: string; request: AuditMeta
55
+ }>>()
56
+ const requestMeta = (agent: Agent, step?: Step): AuditMeta => ({
44
57
  agent: agent.id,
45
58
  store: memory.storeId(agent.session),
46
- turn: steps.get(agent.session)?.turn,
47
- step: steps.get(agent.session)?.step,
48
- ...extra,
59
+ turn: step?.turn,
60
+ step: step?.step,
61
+ retry: step && step.attempts - 1,
49
62
  })
50
63
  function lookupTable(session: Session) {
51
64
  let table = lookups.get(session)
@@ -60,80 +73,118 @@ export function registerAudit(memory: ProjectMemory, isAgentLoopRequest: (req: u
60
73
  }
61
74
  return table
62
75
  }
63
- const lookUp = (agent: Agent, d: AccessDomain, call: string, refs: Ref[], searchContext?: string) => {
64
- const table = lookupTable(agent.session)
65
- table.set(call, { domain: d.id, refs, searchContext })
66
- if (refs.length)
67
- memory.append(agent.session, 'plugin:project-memory/lookup', { callId: call, domainId: d.id, refs })
76
+ const rememberLookup = (agent: Agent, call: string, read: ReadResult) => {
77
+ lookupTable(agent.session).set(call, read)
78
+ if (read.refs.length)
79
+ memory.append(agent.session, 'plugin:project-memory/lookup', { callId: call, domainId: read.domain, refs: read.refs })
68
80
  }
69
- ctx.on('llm/stream', (req, next) => {
70
- if (!isAgentLoopRequest(req)) return next()
71
- const generation = memory.assistantGeneration()
72
- if (generation === undefined) return next()
73
- // Unlike 'session/event'/'tools/result', a listener error here is NOT contained by the host
74
- // and would abort the whole model stream - a store failure must degrade, not propagate.
81
+ const lookUp = (agent: Agent, d: AccessDomain, call: string, rows: (Ref & { action: string })[], searchContext?: string) => {
82
+ const refs = rows.map(row => ({ id: row.id, rev: row.rev, bodyDigest: bodyDigest(row) }))
83
+ rememberLookup(agent, call, { domain: d.id, refs, searchContext })
84
+ }
85
+ function auditRequest(req: { sessionId?: string; messages: (Message & { toolCallId?: string; isError?: boolean })[] }) {
86
+ // A failure in the host classifier or memory store must not interrupt the model stream.
75
87
  try {
76
- const agent: Agent | undefined = req.sessionId && ctx.agents.get(req.sessionId)
88
+ if (!isAgentLoopRequest(req)) return
89
+ const generation = memory.assistantGeneration()
90
+ if (generation === undefined) return
91
+ const agent = req.sessionId ? ctx.agents.get(req.sessionId) : undefined
77
92
  if (agent) visibleSearches.delete(agent)
78
93
  const d = memory.domain(agent)
79
- if (!agent || !d) return next()
80
- const messages: (Message & { toolCallId?: string })[] = req.messages
81
- const snapshot = messages.findLast((m) => m.source?.kind === 'runtime-context')
82
- const value = snapshot?.source?.sections?.find((s) => s.name === indexName)?.text
83
- // A model can quote a fabricated ID elsewhere. Only accept complete lines in the named host contribution.
84
- const refs =
85
- value && messageText(snapshot).includes(value)
86
- ? value.split('\n').flatMap((line) => {
87
- const trailing = line.match(/\[(mem-[\da-f-]+)@(\d+)\]$/i)
88
- return trailing ? [{ id: trailing[1], rev: Number(trailing[2]) }] : []
89
- })
90
- : []
94
+ if (!agent || !d) return
95
+ const step = steps.get(agent.session)
96
+ if (step) {
97
+ step.exposed = []
98
+ step.generation = generation
99
+ step.attempts++
100
+ }
101
+ const messages = req.messages
102
+ const snapshots = messages.filter(m => m.source?.kind === 'runtime-context')
103
+ const latest = snapshots.at(-1)
104
+ const refs: RequestRef[] = []
105
+ for (const snapshot of snapshots) {
106
+ const value = snapshot.source?.sections?.find(s => s.name === indexName)?.text
107
+ // DSH can retain earlier reminders in the physical request. A superseded body
108
+ // counts as visible, while only a current body can credit a later command.
109
+ if (!value || !messageText(snapshot).includes(value)) continue
110
+ for (const line of value.split('\n')) {
111
+ const trailing = line.match(/\[(mem-[\da-f-]+)@(\d+)\]$/i)
112
+ if (trailing) refs.push({ id: trailing[1], rev: Number(trailing[2]), actionable: snapshot === latest })
113
+ else for (const ref of indexHintRefs(line)) refs.push({ ...ref, hintOnly: true })
114
+ }
115
+ }
91
116
  let context: string | undefined
92
117
  let shown: Map<string, string> | undefined
93
118
  for (const message of messages) {
94
119
  if (message.role !== 'tool' || !message.toolCallId) continue
95
120
  const read = lookupTable(agent.session).get(message.toolCallId)
96
121
  if (read?.domain !== d.id) continue
97
- const text = messageText(message)
98
- for (const ref of read.refs) {
99
- // Explicit read/search returns a stringified JSON projection.
100
- if (text.includes(ref.id)) refs.push(ref)
122
+ if (message.isError) {
123
+ const denial = read.refs.find(ref => ref.denial)
124
+ if (denial && denial.bodyDigest === searchRowDigest(messageText(message)))
125
+ refs.push({ id: denial.id, rev: denial.rev })
126
+ continue
101
127
  }
102
- if (read.searchContext && read.searchContext === (context ??= searchContext(agent, d, generation))) {
103
- // A prior call may have failed delivery or been removed/truncated by compaction.
104
- // Suppress only full search rows still present in this model request.
105
- let value
106
- try { value = JSON.parse(text) } catch { continue }
107
- if (!Array.isArray(value?.rules)) continue
108
- shown ??= new Map()
109
- for (const row of value.rules)
110
- if (typeof row?.action === 'string') shown.set(row.id, searchRowDigest(row))
128
+ let result
129
+ try { result = JSON.parse(messageText(message)) } catch { continue }
130
+ const trusted = new Map(read.refs.map(ref => [ref.id, ref.bodyDigest]))
131
+ if (Array.isArray(result?.results)) {
132
+ for (const row of writeReceiptBodies(result.results))
133
+ if (trusted.get(row.id) === row.bodyDigest) refs.push({ id: row.id, rev: row.rev, actionable: true })
134
+ continue
135
+ }
136
+ const rows = Array.isArray(result?.rules) ? result.rules : Array.isArray(result?.items) ? result.items : [result]
137
+ const currentSearch = read.searchContext && Array.isArray(result?.rules) &&
138
+ read.searchContext === (context ??= searchContext(agent, d, generation))
139
+ if (currentSearch) shown ??= new Map()
140
+ for (const row of rows) {
141
+ // Compaction, a bare pointer and an alreadyShown row can all retain an ID without the body.
142
+ if (typeof row?.action !== 'string' || !row.action || trusted.get(row.id) !== bodyDigest(row)) continue
143
+ refs.push({ id: row.id, rev: row.rev, viaLookup: true, actionable: true })
144
+ if (currentSearch) shown!.set(row.id, searchRowDigest(row))
111
145
  }
112
146
  }
113
147
  if (context && shown) visibleSearches.set(agent, { context, rows: shown })
114
- const unique = [...new Map(refs.map((r) => [r.id + '@' + r.rev, r])).values()]
115
- const step = steps.get(agent.session)
116
- if (step) {
117
- step.exposed = unique
118
- step.generation = generation
148
+ // A lookup body takes precedence over a pointer or proactive copy of the same revision.
149
+ const exposures = new Map<string, typeof refs[number]>()
150
+ for (const ref of refs) {
151
+ const key = ref.id + '@' + ref.rev
152
+ const previous = exposures.get(key)
153
+ if (!previous) exposures.set(key, ref)
154
+ else {
155
+ previous.hintOnly = previous.hintOnly && ref.hintOnly
156
+ previous.actionable ||= ref.actionable
157
+ previous.viaLookup ||= ref.viaLookup
158
+ }
119
159
  }
120
- const retry = step ? step.attempts++ : 0
121
160
  // The request can already contain a revision another session has just withdrawn.
122
161
  // recordDelivery checks historical membership inside its transaction.
123
- if (unique.length) {
124
- for (const scope of memory.scopes(agent, d))
125
- memory.store.recordDelivery(scope.id, agent.id, unique, meta(agent, { retry }))
162
+ if (exposures.size) {
163
+ const unique = [...exposures.values()]
164
+ const meta = requestMeta(agent, step)
165
+ for (const scope of memory.scopes(agent, d)) {
166
+ const recorded = memory.store.recordDelivery(scope.id, agent.id, unique, meta)
167
+ if (step) step.exposed.push(...recorded.map(ref => ({ ...ref, domain: scope.id })))
168
+ }
126
169
  }
127
170
  } catch (error) {
128
171
  ctx.logger.warn('项目记忆无法记录本步引用:' + (error instanceof Error ? error.message : String(error)))
129
172
  }
173
+ }
174
+ ctx.on('llm/stream', (req, next) => {
175
+ auditRequest(req)
130
176
  return next()
131
177
  })
132
- ctx.on('session/event', (session: Session, event: HostEvent) => {
178
+ function auditEvent(session: Session, event: HostEvent) {
179
+ if (event.seq < session.inheritedEventCount) return
133
180
  if (event.type === 'step/start') {
134
181
  steps.set(session, { turn: String(event.data.turn), step: event.data.step!, attempts: 0, exposed: [] })
135
182
  return
136
183
  }
184
+ if (event.type === 'turn/start' || event.type === 'turn/end' || event.type === 'step/end') {
185
+ steps.delete(session)
186
+ return
187
+ }
137
188
  if (!['tool/call', 'tool/result', 'assistant/message'].includes(event.type)) return
138
189
  const completed = event.type === 'tool/result' ? event.data.message?.toolCallId : undefined
139
190
  const record = completed ? commands.get(session)?.get(completed) : undefined
@@ -142,18 +193,15 @@ export function registerAudit(memory: ProjectMemory, isAgentLoopRequest: (req: u
142
193
  if (generation === undefined) return
143
194
  const agent = ctx.agents.get(session.id)
144
195
  const d = memory.domain(agent)
145
- if (!agent || !d) return
196
+ if (!agent || agent.session !== session || !d) return
146
197
  const step = steps.get(session)
147
198
  const refs = step?.generation === generation ? step.exposed : []
148
199
  if (event.type === 'assistant/message') {
200
+ if (!step || event.data.turn !== Number(step.turn) || event.data.step !== step.step) return
149
201
  for (const ref of refsIn(messageText(event.data.message))) {
150
- const owner = memory.owner(agent, d, ref.id)
151
- if (
152
- owner &&
153
- refs.some((r) => r.id === ref.id && r.rev === ref.rev) &&
154
- memory.current(owner, ref.id, ref.rev)
155
- )
156
- memory.store.audit(owner.id, agent.id, 'cite', meta(agent, { ...ref, seq: event.seq }))
202
+ const observed = refs.find(r => r.id === ref.id && r.rev === ref.rev)
203
+ if (observed && memory.scopes(agent, d).some(scope => scope.id === observed.domain))
204
+ memory.store.audit(observed.domain, agent.id, 'cite', { ...requestMeta(agent, step), ...ref, seq: event.seq })
157
205
  }
158
206
  } else if (event.type === 'tool/call' && event.data.name === 'bash') {
159
207
  let args: { command?: string; workdir?: string }
@@ -165,8 +213,10 @@ export function registerAudit(memory: ProjectMemory, isAgentLoopRequest: (req: u
165
213
  const scope = args.command && bashScope(d, args.command, args.workdir)
166
214
  if (!scope) return
167
215
  const { command, cwd, directory } = scope
216
+ const scopes = memory.scopes(agent, { ...d, cwd })
168
217
  const matching = refs.filter((r) => {
169
- const row = memory.current({ ...d, cwd }, r.id, r.rev)
218
+ const owner = r.actionable && scopes.find(scope => scope.id === r.domain)
219
+ const row = owner && memory.current(owner, r.id, r.rev)
170
220
  return (
171
221
  row &&
172
222
  literalActionCommand(row.action) === command &&
@@ -180,45 +230,54 @@ export function registerAudit(memory: ProjectMemory, isAgentLoopRequest: (req: u
180
230
  if (!matching.length) return
181
231
  let byCall = commands.get(session)
182
232
  if (!byCall) commands.set(session, (byCall = new Map()))
183
- byCall.set(event.data.callId!, { generation, domain: d.id, refs: matching, cwd })
233
+ const request = requestMeta(agent, step)
234
+ byCall.set(event.data.callId!, { generation, domain: d.id, refs: matching, cwd, command, request })
184
235
  for (const ref of matching)
185
236
  memory.store.audit(
186
- d.id,
237
+ ref.domain,
187
238
  agent.id,
188
239
  'attempt',
189
- meta(agent, { ...ref, call: event.data.callId, seq: event.seq }),
240
+ { ...request, ...ref, call: event.data.callId, seq: event.seq },
190
241
  )
191
242
  } else if (record?.generation === generation && record.domain === d.id) {
192
243
  for (const ref of record.refs)
193
244
  memory.store.audit(
194
- d.id,
245
+ ref.domain,
195
246
  agent.id,
196
247
  'tool_result',
197
- meta(agent, {
198
- ...ref,
248
+ {
249
+ ...record.request, ...ref,
199
250
  call: completed,
200
251
  seq: event.seq,
201
252
  outcome: event.data.message?.isError ? 'error' : 'recorded',
202
- }),
253
+ },
203
254
  )
204
255
  }
205
- })
206
- ctx.on('tools/result', (exec: Execution, result) => {
207
- if (!exec.agent || exec.name !== 'bash') return
208
- const record = commands.get(exec.agent.session)?.get(exec.callId)
209
- if (!record || record.generation !== memory.assistantGeneration() ||
210
- record.domain !== memory.domain(exec.agent)?.id || result.value?.cwd !== record.cwd) return
211
- const outcome = Number.isSafeInteger(result.value.exitCode) ? result.value.exitCode : 'unknown'
212
- for (const ref of record.refs)
213
- memory.store.audit(
214
- record.domain,
215
- exec.agent.id,
216
- 'bash_result',
217
- meta(exec.agent, { ...ref, call: exec.callId, outcome }),
218
- )
256
+ }
257
+ ctx.on('session/event', (session: Session, event: HostEvent) => {
258
+ try { auditEvent(session, event) } catch (error) {
259
+ ctx.logger.warn('项目记忆无法记录本次会话回执:' + String(error))
260
+ }
219
261
  })
220
262
  return {
221
263
  expanded: lookUp,
264
+ wrote(agent: Agent, domain: AccessDomain, call: string, results: unknown) {
265
+ const refs = writeReceiptBodies(results)
266
+ if (refs.length) rememberLookup(agent, call, { domain: domain.id, refs })
267
+ },
268
+ blocked(agent: Agent, domain: AccessDomain, call: string, ref: Ref, reason: string) {
269
+ const digest = searchRowDigest('Error: ' + reason)
270
+ rememberLookup(agent, call, { domain: domain.id, refs: [{ ...ref, bodyDigest: digest, denial: true }] })
271
+ },
272
+ executed(exec: Execution, command: string, cwd: string, exitCode: number) {
273
+ if (!exec.agent) return
274
+ const record = commands.get(exec.agent.session)?.get(exec.callId)
275
+ if (!record || record.generation !== memory.assistantGeneration() || record.domain !== memory.domain(exec.agent)?.id ||
276
+ record.command !== command || record.cwd !== cwd) return
277
+ for (const ref of record.refs)
278
+ memory.store.audit(ref.domain, exec.agent.id, 'bash_result',
279
+ { ...record.request, ...ref, call: exec.callId, outcome: exitCode })
280
+ },
222
281
  shownSearchRows(agent: Agent, context: string) {
223
282
  const seen = visibleSearches.get(agent)
224
283
  return seen?.context === context ? seen.rows : undefined
package/src/automatic.ts CHANGED
@@ -1,9 +1,19 @@
1
1
  const noStore =
2
2
  /(?:不要|别|不用|不需要|不许|禁止|请勿|无需)(?:再|把.{0,24})?(?:记住|记下|记录|记忆|保存|存储|存下|记到|加入记忆|记入)|别记|不要记|(?:不用|不必|无需)记|请忘(?:掉|记)|不留(?:记录|记忆)|忘(?:记|掉)我的|(?:清除|删除|移除).{0,12}(?:记忆|记录|名字|姓名|偏好)|\b(?:do not|don['’]t|never)\s+(?:ever\s+)?(?:remember|memorize|save|store|retain|record|keep)|\b(?:forget|erase|delete|remove)\s+(?:this|that|my|the (?:memory|name|preference))|\b(?:not for (?:memory|storage)|off the record|private browsing)\b|\b(?:do not|don['’]t) want.{0,25}(?:saved|stored|remembered|retained)/iu
3
3
  const secret =
4
- /(?:令牌|(?:api\s*)?token|one[- ]time code|otp|pin)\s*(?:[是为:=]|is\b)\s*\S|(?:密码|口令|密钥|私钥|助记词|验证码|访问令牌|安全码)|\b(?:password|passwd|passphrase|secret|private key|api[-_ ]?key|access[-_ ]?token|refresh[-_ ]?token|seed phrase|verification code|recovery code)\b|\bauthorization\s*:[ \t]*\S|-----BEGIN\s+[^\n]*KEY-----|\b(?:sk-[a-z0-9_-]{12,}|gh[pousr]_[a-z0-9_]{12,}|AKIA[A-Z0-9]{16}|eyJ[A-Za-z0-9_-]+\.eyJ[A-Za-z0-9_-]+\.)/iu
4
+ /(?:令牌|(?:api\s*)?token|one[- ]time code|otp|pin)\s*(?:[是为:=]|is\b)\s*\S|\b(?:password|passwd|passphrase|secret|private key|api[-_ ]?key|access[-_ ]?token|refresh[-_ ]?token|seed phrase|verification code|recovery code)\b|\bauthorization\s*:[ \t]*\S|-----BEGIN\s+[^\n]*KEY-----|\b(?:sk-[a-z0-9_-]{12,}|gh[pousr]_[a-z0-9_]{12,}|AKIA[A-Z0-9]{16}|eyJ[A-Za-z0-9_-]+\.eyJ[A-Za-z0-9_-]+\.)/iu
5
+ // Recognized provider credentials and credential-bearing URIs are excluded from retention and team exports.
6
+ const credentialValue =
7
+ /-----BEGIN [^\n]*PRIVATE KEY-----|\b(?:sk-[a-zA-Z0-9_-]{12,}|AIza[A-Za-z0-9_-]{20,}|gh[pousr]_[A-Za-z0-9_]{16,}|github_pat_[A-Za-z0-9_]{20,}|glpat-[A-Za-z0-9_-]{16,}|npm_[A-Za-z0-9]{20,}|hf_[A-Za-z0-9]{20,}|xoxb-[A-Za-z0-9-]{10,}|sk_live_[A-Za-z0-9]{10,}|rk_test_[A-Za-z0-9]{10,}|whsec_[A-Za-z0-9]{10,}|(?:AKIA|ASIA)[A-Z0-9]{16}|(?:LTAI|AKID)[A-Za-z0-9]{12,}|eyJ[A-Za-z0-9_-]+\.eyJ[A-Za-z0-9_-]+\.)\b|[a-z][a-z0-9+.-]*:\/\/[^\s/:@]+:[^\s/@]+@|\b(?:password|passwd|passphrase|secret|private[ _-]?key|api[ _-]?key|access[ _-]?token|refresh[ _-]?token|token|authorization)\b\s*(?:[::=]|is\b)\s*\S+/iu
8
+ // The complete academic noun 密码学 ends at a word delimiter. Keep the conservative
9
+ // credential interpretation for a possessive label, an assignment, or an unseparated value.
10
+ const credentialLabel = /的密码|密码(?!学(?=$|[\s。!?,、;()「」“”.!?,;()]))|口令|密钥|私钥|助记词|验证码|访问令牌|安全码/u
11
+
12
+ export function containsCredential(text: string): boolean {
13
+ return credentialValue.test(text) || credentialLabel.test(text)
14
+ }
5
15
  export function skipsAutomaticMemory(text: string): boolean {
6
- return text.length > 32000 || noStore.test(text) || secret.test(text)
16
+ return text.length > 32000 || noStore.test(text) || secret.test(text) || containsCredential(text) || /(?:^|\s)--(?:token|authorization|auth|credential)\s+\S/iu.test(text)
7
17
  }
8
18
 
9
19
  export function refusesAutomaticMemory(text: string): boolean {
@@ -94,7 +94,7 @@ export function bashScope(domain: AccessDomain, input: string, workdir = domain.
94
94
  }
95
95
 
96
96
  /** Prose and negative preferences have no implicit operation. Ambiguous shell syntax gets no active rule. */
97
- export function actionInDomain(domain: AccessDomain, action: string): boolean {
97
+ export function actionInDomain(domain: AccessDomain, action: string, check = bashScope): boolean {
98
98
  const command = literalActionCommand(action)
99
99
  const raw = action.trim()
100
100
  const invocation =
@@ -106,9 +106,9 @@ export function actionInDomain(domain: AccessDomain, action: string): boolean {
106
106
  !command &&
107
107
  /\p{Script=Han}/u.test(raw) &&
108
108
  !/(?:^|\s)(?:-+[A-Za-z]|[./~])|[;&|$<>]|^(?:cd|pushd|popd)\s/u.test(raw)
109
- return prose || !!bashScope(domain, command ?? raw)
109
+ return prose || !!check(domain, command ?? raw)
110
110
  }
111
- if (command && command !== raw) return !!bashScope(domain, command)
111
+ if (command && command !== raw) return !!check(domain, command)
112
112
  // Preserve natural-language exceptions and negations even if they cite shell commands.
113
113
  if (/(?:不|别|勿|禁止|避免|停用|\b(?:not|never|avoid|without|unless|except|don't)\b)/iu.test(action))
114
114
  return true
@@ -117,7 +117,7 @@ export function actionInDomain(domain: AccessDomain, action: string): boolean {
117
117
  // sitting behind it, so a trailing run that is itself a clean command still gets
118
118
  // the real scope check instead of being waved through on name recognition alone.
119
119
  const tail = literalTail.exec(raw)?.[0]
120
- if (tail) return !!bashScope(domain, tail)
120
+ if (tail) return !!check(domain, tail)
121
121
  const affirmative =
122
122
  /(?:运行|执行|采用|改用|使用|\b(?:run|execute|invoke))\s*[::]?\s*`?\s*([^\s`]+)(?:\s|$)/iu
123
123
  const embedded = affirmative.exec(action)?.[1]
package/src/commands.ts CHANGED
@@ -6,7 +6,7 @@ import { exportCommand } from './sharing.ts'
6
6
  import type { Agent, Host } from './host.ts'
7
7
 
8
8
  const usage =
9
- 'inbox · remember <动作或 JSON> · revise <ID@版本> <新动作或 JSON> · confirm <提案ID> <卡片版本> <摘要> all|选择数组 · reject <提案ID> <卡片版本> <摘要> · search [--hybrid|--semantic|--keyword] <查询> · read|source|why|forget|undo|clear-quote|pin|unpin <ID@版本> · usage <ID@版本> proactive|on_demand · status · fact|episode|reference|runbook|guard <JSON> · episode-stats <经历ID> · history [会话ID] · history import <旧会话ID> · backup [personal] · restore [personal] <备份ID> · clear <ID@版本> · export agents|skill <ID@版本> [名称] · export apply <预览凭据>'
9
+ 'inbox · remember <动作或 JSON> · revise <ID@版本> <新动作或 JSON> · confirm <提案ID> <卡片版本> <摘要> all|选择数组 · reject <提案ID> <卡片版本> <摘要> · search [--hybrid|--semantic|--keyword] <查询> · read|source|why|forget|undo|clear-quote|pin|unpin <ID@版本> · usage <ID@版本> proactive|on_demand · status · fact|episode|reference|runbook|guard <JSON> · episode-stats <经历ID> · import [all|agents|claude|claude-memory] · import list · import undo <批次ID> · history [会话ID] · history import <旧会话ID> · backup [personal] · restore [personal] <备份ID> · clear <ID@版本> · export agents|skill <ID@版本> [名称] · export apply <预览凭据>'
10
10
  export function parseRef(text: string) {
11
11
  const match = /^(mem-[a-z0-9-]+)(?:@([1-9]\d*))?$/i.exec(text)
12
12
  return match ? { id: match[1], rev: match[2] ? Number(match[2]) : undefined } : undefined
@@ -19,7 +19,7 @@ function manualFields(value: string, base?: DraftItem) {
19
19
  : { user_quote: '', when: '', action: '', paths: [], exceptions: '', conflicts_with_repo_guidance: false }
20
20
  return { ...fields, ...updates }
21
21
  }
22
- export function registerCommands(ctx: Host, memory: ProjectMemory) {
22
+ export function registerCommands(ctx: Host, memory: ProjectMemory, hostIssues: string[] = []) {
23
23
  ctx.commands!.register({
24
24
  name: 'project-memory',
25
25
  description: '查询和管理全局偏好、项目规则与知识',
@@ -27,7 +27,7 @@ export function registerCommands(ctx: Host, memory: ProjectMemory) {
27
27
  input: { hint: usage },
28
28
  async handler({ agent, rawInput, commandId }) {
29
29
  try {
30
- const value = await run(memory, agent, rawInput.trim(), commandId)
30
+ const value = await run(memory, agent, rawInput.trim(), commandId, hostIssues)
31
31
  return { kind: 'success', text: typeof value === 'string' ? value : JSON.stringify(value, null, 2) }
32
32
  } catch (error) {
33
33
  return { kind: 'error', text: error instanceof Error ? error.message : 'operation_failed' }
@@ -35,7 +35,7 @@ export function registerCommands(ctx: Host, memory: ProjectMemory) {
35
35
  },
36
36
  })
37
37
  }
38
- async function run(memory: ProjectMemory, agent: Agent, input: string, commandId: string) {
38
+ async function run(memory: ProjectMemory, agent: Agent, input: string, commandId: string, hostIssues: string[]) {
39
39
  const [verb = '', ...rest] = input.split(/\s+/)
40
40
  const query = input.slice(verb.length).trim()
41
41
  const [identifier, revision, digest] = rest
@@ -57,6 +57,7 @@ async function run(memory: ProjectMemory, agent: Agent, input: string, commandId
57
57
  return maintenanceCommand(memory, agent, verb, query)
58
58
  if (['fact', 'episode', 'episode-stats', 'reference', 'runbook', 'guard'].includes(verb))
59
59
  return knowledgeCommand(memory, agent, verb, query, commandId)
60
+ if (verb === 'import') return memory.fileImport(agent, query, commandId)
60
61
  if (verb === 'export') return exportCommand(memory, agent, query)
61
62
  if (verb === 'inbox') return memory.view(agent).proposals.filter((p) => p.state === 'pending')
62
63
  if (verb === 'confirm' || verb === 'reject') {
@@ -91,6 +92,8 @@ async function run(memory: ProjectMemory, agent: Agent, input: string, commandId
91
92
  const { rules: status, proposals, needs_review } = memory.view(agent)
92
93
  return {
93
94
  memoryEnabled: memory.store.memoryEnabled(),
95
+ hostIssues,
96
+ embeddingLanguages: memory.retrieval.vectors.languages,
94
97
  rules: status,
95
98
  pending: proposals.filter((p) => p.state === 'pending').length,
96
99
  needs_review,
@@ -110,20 +113,21 @@ async function run(memory: ProjectMemory, agent: Agent, input: string, commandId
110
113
  hint: usage,
111
114
  }
112
115
  d = memory.owner(agent, d, ref.id) ?? d
113
- if (verb === 'why') {
116
+ if (verb === 'why' || verb === 'source') {
114
117
  const evidence = await memory.read(agent, ref.id, ref.rev, true)
115
118
  if (!memory.scopes(agent, memory.rootDomain(agent)).some(scope => scope.id === d.id))
116
119
  throw new StoreError('not_found')
117
120
  const rule = memory.current(d, ref.id, ref.rev)
121
+ const visible = rule && 'quote' in evidence && evidence.rev === rule.rev && memory.canPublishEvidence(rule, evidence)
122
+ if (verb === 'source') return visible ? evidence : { status: 'not_found' }
118
123
  const history = memory.store.history(d.id, ref.id)
119
124
  if (!history.length && !rule) throw new StoreError('not_found')
120
125
  return {
121
- rule: rule && 'quote' in evidence && evidence.rev === rule.rev && evidence.quote === rule.user_quote
122
- ? { ...publicRule(rule), ...evidence } : undefined,
126
+ rule: visible ? { ...publicRule(rule), ...evidence } : undefined,
123
127
  history,
124
128
  }
125
129
  }
126
- if (verb === 'read' || verb === 'source') return memory.read(agent, ref.id, ref.rev, verb === 'source')
130
+ if (verb === 'read') return memory.read(agent, ref.id, ref.rev)
127
131
  if (ref.rev === undefined) throw new StoreError('expected_revision', '请使用卡片上显示的 ID@版本')
128
132
  if (verb === 'revise') {
129
133
  if (d.id === memory.personal.id)