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.
- package/CHANGELOG.md +6 -7
- package/README.md +125 -91
- package/README.zh-CN.md +122 -92
- package/SECURITY.md +29 -0
- package/dist/audit.js +155 -80
- package/dist/automatic.js +10 -2
- package/dist/client.js +2035 -0
- package/dist/command-scope.js +4 -4
- package/dist/commands.js +15 -9
- package/dist/consolidation-store.js +87 -20
- package/dist/consolidation.js +2 -6
- package/dist/domain.js +8 -4
- package/dist/encoder.js +46 -5
- package/dist/file-import-store.js +120 -0
- package/dist/file-import.js +265 -0
- package/dist/foreground-attempts.js +91 -0
- package/dist/guidance.js +133 -92
- package/dist/host.js +13 -0
- package/dist/index-policy.js +91 -48
- package/dist/index.js +102 -40
- package/dist/knowledge-hooks.js +70 -27
- package/dist/knowledge.js +2 -3
- package/dist/maintenance-store.js +38 -4
- package/dist/maintenance.js +29 -5
- package/dist/personal.js +37 -0
- package/dist/policy.js +45 -47
- package/dist/prompt-copy.js +93 -0
- package/dist/proposal-receipts.js +70 -0
- package/dist/proposal-review.js +656 -0
- package/dist/propose-contract.js +32 -36
- package/dist/question-answers.js +86 -29
- package/dist/retrieval.js +25 -8
- package/dist/scope-narrowing.js +49 -0
- package/dist/search-index.js +93 -13
- package/dist/semantic.js +69 -207
- package/dist/service.js +633 -204
- package/dist/sharing.js +7 -13
- package/dist/sources.js +28 -3
- package/dist/store.js +432 -96
- package/dist/tool-experience.js +87 -0
- package/dist/turn-review-store.js +83 -16
- package/dist/turn-review.js +155 -59
- package/dist/ui.js +128 -26
- package/dist/vector-index.js +69 -33
- package/docs/architecture.zh-CN.md +52 -0
- package/docs/benchmark.zh-CN.md +60 -0
- package/docs/benchmarks/repository-tasks.json +5355 -0
- package/docs/images/bond-memory-principle-en.svg +644 -0
- package/docs/images/bond-memory-principle-zh.svg +644 -0
- package/docs/images/bond-memory-principle.drawio +644 -0
- package/docs/images/memory-settings-en.png +0 -0
- package/docs/images/memory-settings-zh.png +0 -0
- package/docs/images/memory-turn-recalled-en.png +0 -0
- package/docs/images/memory-turn-recalled-zh.png +0 -0
- package/docs/images/memory-turn-saved-en.png +0 -0
- package/docs/images/memory-turn-saved-zh.png +0 -0
- package/docs/media/memory-bond-name-en.gif +0 -0
- package/docs/media/memory-bond-name-en.mp4 +0 -0
- package/docs/media/memory-bond-name-zh.gif +0 -0
- package/docs/media/memory-bond-name-zh.mp4 +0 -0
- package/locale/detail.en.md +5 -1
- package/locale/detail.zh.md +5 -1
- package/locale/en.json +338 -0
- package/locale/zh.json +338 -0
- package/native/embeddings/NOTICE.md +2 -2
- package/package.json +39 -19
- package/scripts/benchmark-bond.mjs +72 -0
- package/scripts/benchmark-conditions.mjs +144 -0
- package/scripts/benchmark-example.mjs +37 -0
- package/scripts/benchmark-scale.mjs +119 -0
- package/scripts/benchmark-scenarios.mjs +57 -0
- package/scripts/benchmark-tasks.mjs +244 -0
- package/src/audit.ts +144 -85
- package/src/automatic.ts +12 -2
- package/src/command-scope.ts +4 -4
- package/src/commands.ts +12 -8
- package/src/consolidation-store.ts +80 -18
- package/src/consolidation.ts +2 -6
- package/src/domain.ts +9 -4
- package/src/encoder.ts +46 -6
- package/src/file-import-store.ts +139 -0
- package/src/file-import.ts +256 -0
- package/src/foreground-attempts.ts +97 -0
- package/src/guidance.ts +138 -102
- package/src/host.ts +22 -2
- package/src/index-policy.ts +93 -46
- package/src/index.ts +87 -43
- package/src/knowledge-hooks.ts +71 -29
- package/src/knowledge.ts +2 -3
- package/src/maintenance-store.ts +37 -4
- package/src/maintenance.ts +25 -5
- package/src/personal.ts +36 -0
- package/src/policy.ts +55 -52
- package/src/prompt-copy.ts +99 -0
- package/src/proposal-receipts.ts +59 -0
- package/src/proposal-review.ts +614 -0
- package/src/propose-contract.ts +31 -35
- package/src/question-answers.ts +99 -29
- package/src/retrieval.ts +26 -9
- package/src/scope-narrowing.ts +58 -0
- package/src/search-index.ts +94 -14
- package/src/semantic.ts +67 -188
- package/src/service.ts +595 -210
- package/src/sharing.ts +7 -14
- package/src/sources.ts +26 -4
- package/src/store.ts +434 -97
- package/src/tool-experience.ts +93 -0
- package/src/turn-review-store.ts +86 -15
- package/src/turn-review.ts +142 -60
- package/src/ui.ts +122 -27
- package/src/vector-index.ts +57 -29
- package/client/index.js +0 -1186
- package/design/dsh-memory-plugin-design.md +0 -46
- package/design/dsh-memory-plugin-evaluation.md +0 -135
- package/design/evaluations/locomo-conv-26-2026-12-03.json +0 -252
- package/design/evaluations/locomo-conv-26-paired-2026-12-03.json +0 -549
- package/design/evaluations/locomo-conv-26-write-replay-2026-12-03.json +0 -289
- package/design/evaluations/project-memory-tasks-2026-12-03.json +0 -1059
- package/design/memory-lifecycle-consolidation.excalidraw +0 -1212
- package/design/memory-lifecycle-consolidation.mobile.excalidraw +0 -1083
- package/design/memory-lifecycle-consolidation.mobile.svg +0 -2
- package/design/memory-lifecycle-consolidation.mobile.zh-CN.excalidraw +0 -1083
- package/design/memory-lifecycle-consolidation.mobile.zh-CN.svg +0 -94
- package/design/memory-lifecycle-consolidation.svg +0 -2
- package/design/memory-lifecycle-consolidation.zh-CN.excalidraw +0 -1212
- package/design/memory-lifecycle-consolidation.zh-CN.svg +0 -94
- package/design/memory-lifecycle.excalidraw +0 -2105
- package/design/memory-lifecycle.mobile.excalidraw +0 -1896
- package/design/memory-lifecycle.mobile.svg +0 -95
- package/design/memory-lifecycle.mobile.zh-CN.excalidraw +0 -1896
- package/design/memory-lifecycle.mobile.zh-CN.svg +0 -97
- package/design/memory-lifecycle.svg +0 -95
- package/design/memory-lifecycle.zh-CN.excalidraw +0 -2105
- package/design/memory-lifecycle.zh-CN.svg +0 -97
- package/native/embeddings/LICENSE +0 -21
- package/native/embeddings/en/model.onnx +0 -4
- package/native/embeddings/en/vocab.txt +0 -30522
- package/native/embeddings/runtime/LICENSE +0 -21
- package/native/embeddings/runtime/ThirdPartyNotices.txt +0 -6156
- package/native/embeddings/runtime/ort-wasm-simd-threaded.mjs +0 -70
- package/native/embeddings/runtime/ort-wasm-simd-threaded.wasm +0 -0
- package/native/embeddings/runtime/ort.wasm.min.mjs +0 -7
- package/native/embeddings/worker.mjs +0 -97
- package/native/embeddings/zh/model.onnx +0 -0
- package/native/embeddings/zh/vocab.txt +0 -21128
|
@@ -0,0 +1,614 @@
|
|
|
1
|
+
import { skipsAutomaticMemory } from './automatic.ts'
|
|
2
|
+
import { digest, type AccessDomain } from './domain.ts'
|
|
3
|
+
import { ForegroundAttempts, foregroundTurnKey } from './foreground-attempts.ts'
|
|
4
|
+
import { guidanceComparisonPrompt, reviewRepositoryGuidance } from './guidance.ts'
|
|
5
|
+
import { messageText, type Agent } from './host.ts'
|
|
6
|
+
import { normalizeLabel, reviewedSubject, semanticSlot, validLabel, type MemorySlot } from './personal.ts'
|
|
7
|
+
import { reviewText, type ReviewSdk } from './model-review.ts'
|
|
8
|
+
import { choicesForQuote, resolveSelectedDirective, type SelectionEvidence } from './question-answers.ts'
|
|
9
|
+
import { prompts } from './prompt-copy.ts'
|
|
10
|
+
import { candidateRows, parseCandidate, reviewedQualifiers, semanticDraft, skipsCandidate, targetMismatch, type SemanticCandidate } from './semantic.ts'
|
|
11
|
+
import { prepareItems } from './policy.ts'
|
|
12
|
+
import { latestTurn, ruleFields, type ProjectMemory } from './service.ts'
|
|
13
|
+
import { previousScopeAgreement, projectAgreement } from './scope-narrowing.ts'
|
|
14
|
+
import { loadedGuidance } from './sources.ts'
|
|
15
|
+
import { StoreError, type Ref, type Rule } from './store.ts'
|
|
16
|
+
|
|
17
|
+
type Committed = { status: 'saved' | 'duplicate' } & Ref
|
|
18
|
+
type Outcome = { status: 'skipped'; reason: string; retryScope?: SemanticCandidate['scope'] } |
|
|
19
|
+
(Committed & { stored: ReturnType<typeof storedFields> | null })
|
|
20
|
+
type Route = { provider: string; model: string }
|
|
21
|
+
const skipped = (reason: string): Outcome => ({ status: 'skipped', reason })
|
|
22
|
+
const failures = new Set(['insufficient_evidence', 'one_time_request', 'ambiguous_topic', 'subject_mismatch',
|
|
23
|
+
'topic_mismatch', 'kind_mismatch', 'context_mismatch', 'invalid_scope', 'opted_out'])
|
|
24
|
+
function projection(rule: Rule) {
|
|
25
|
+
const { id, rev, subject, semanticTopic: topic, kind, when, exceptions, paths, usage } = rule
|
|
26
|
+
const protectedBody = rule.sensitive === true || skipsAutomaticMemory([rule.action, when, exceptions, ...paths].join(' '))
|
|
27
|
+
return { id, rev, subject, topic, kind, usage, sensitive: protectedBody,
|
|
28
|
+
...(protectedBody ? {} : {action: rule.action, when, exceptions, paths}) }
|
|
29
|
+
}
|
|
30
|
+
const words = new Intl.Segmenter(undefined, { granularity: 'word' })
|
|
31
|
+
function evidenceTokens(quote: string): [number, string][] {
|
|
32
|
+
return Array.from(words.segment(quote), ({ segment }, index) => [index, segment])
|
|
33
|
+
}
|
|
34
|
+
const maxCandidates = 5
|
|
35
|
+
const maxBatchItems = 6
|
|
36
|
+
const maxBatchBytes = 96_000
|
|
37
|
+
type ProposalSources = ReturnType<ProjectMemory['proposalSources']>
|
|
38
|
+
type UserBlock = ProposalSources['events'][number]
|
|
39
|
+
|
|
40
|
+
function utterance(block: UserBlock, state: ProposalSources) {
|
|
41
|
+
const record = state.records.get(block.seq)
|
|
42
|
+
return record?.type === 'user/message' ? messageText(record.data) : block.text
|
|
43
|
+
}
|
|
44
|
+
|
|
45
|
+
function groundedProposal(value: unknown, state: ProposalSources, bind: (event: UserBlock, quote: string) => void,
|
|
46
|
+
resolveLabels?: (value: unknown) => unknown) {
|
|
47
|
+
// A single short user block has an unambiguous host citation. Other inputs require an excerpt.
|
|
48
|
+
const needsQuote = value && typeof value === 'object' && !Array.isArray(value) && !('user_quote' in value)
|
|
49
|
+
if (needsQuote && (state.events.length !== 1 || !state.events[0].text.trim() || state.events[0].text.length > 480))
|
|
50
|
+
throw new StoreError('source_quote_required')
|
|
51
|
+
const fields = needsQuote ? { ...value as object, user_quote: state.events[0].text } : value
|
|
52
|
+
const quote = (fields as { user_quote?: unknown } | null)?.user_quote
|
|
53
|
+
if (typeof quote !== 'string' || !quote.trim() || quote.length > 480) throw new StoreError('invalid_input')
|
|
54
|
+
const matches = state.events.filter(event => event.text.includes(quote))
|
|
55
|
+
const event = matches[0]
|
|
56
|
+
const unique = matches.length === 1 && event.text.indexOf(quote) === event.text.lastIndexOf(quote)
|
|
57
|
+
if (unique) bind(event, quote)
|
|
58
|
+
const row = parseCandidate(resolveLabels ? resolveLabels(fields) : fields)
|
|
59
|
+
if (skipsCandidate(row)) throw new StoreError('ineligible')
|
|
60
|
+
if (!unique) throw new StoreError('invalid_source')
|
|
61
|
+
return { row, event, source: utterance(event, state) }
|
|
62
|
+
}
|
|
63
|
+
|
|
64
|
+
function withTargetLabels(value: unknown, memory: ProjectMemory, domain: AccessDomain, canReadProfile: boolean) {
|
|
65
|
+
if (!value || typeof value !== 'object' || Array.isArray(value)) return value
|
|
66
|
+
const row = value as Record<string, unknown>
|
|
67
|
+
if ((row.kind !== undefined && row.topic !== undefined) || !row.replaces || typeof row.replaces !== 'object') return row
|
|
68
|
+
const ref = row.replaces as Record<string, unknown>
|
|
69
|
+
if (typeof ref.id !== 'string' || !Number.isSafeInteger(ref.rev) || Number(ref.rev) < 1) throw new StoreError('invalid_input')
|
|
70
|
+
if (row.scope !== 'project' && row.scope !== 'global') throw new StoreError('invalid_scope')
|
|
71
|
+
if ((row.scope === 'global' && !canReadProfile) || (row.scope === 'project' && domain.id === memory.personal.id))
|
|
72
|
+
throw new StoreError('invalid_scope')
|
|
73
|
+
const current = memory.current(row.scope === 'global' ? memory.personal : domain, ref.id)
|
|
74
|
+
if (!current) throw new StoreError('target_not_found')
|
|
75
|
+
return { ...row, kind: row.kind ?? current.kind, topic: row.topic ?? current.semanticTopic }
|
|
76
|
+
}
|
|
77
|
+
|
|
78
|
+
type BoundSource = Pick<UserBlock, 'seq' | 'block' | 'text' | 'question' | 'formSelections'> & { source: string }
|
|
79
|
+
function sourceIsCurrent(original: BoundSource | undefined, state: ProposalSources) {
|
|
80
|
+
return !!original && !state.reason && state.events.some(event => event.seq === original.seq &&
|
|
81
|
+
event.block === original.block && event.text === original.text && event.question === original.question &&
|
|
82
|
+
JSON.stringify(event.formSelections) === JSON.stringify(original.formSelections) && utterance(event, state) === original.source)
|
|
83
|
+
}
|
|
84
|
+
|
|
85
|
+
interface Comparison {
|
|
86
|
+
index: number
|
|
87
|
+
source: string
|
|
88
|
+
question?: string
|
|
89
|
+
proposal: SemanticCandidate
|
|
90
|
+
evidenceTokens: [number, string][]
|
|
91
|
+
submittedOptions?: NonNullable<UserBlock['formSelections']>
|
|
92
|
+
candidates: ReturnType<typeof projection>[]
|
|
93
|
+
}
|
|
94
|
+
type Approved = { row: SemanticCandidate; selection?: SelectionEvidence }
|
|
95
|
+
type Decision = Approved | { reason: string; retryScope?: SemanticCandidate['scope'] }
|
|
96
|
+
interface ReviewedTurn {
|
|
97
|
+
turn: string
|
|
98
|
+
rows: Map<string, Decision>
|
|
99
|
+
committed: Map<string, Approved>
|
|
100
|
+
scopeRetries: Map<string, SemanticCandidate['scope']>
|
|
101
|
+
scopeChanges: Map<string, boolean>
|
|
102
|
+
}
|
|
103
|
+
const remembered = new WeakMap<Agent, ReviewedTurn>()
|
|
104
|
+
function remember<T>(entries: Map<string, T>, key: string, value: T) {
|
|
105
|
+
if (entries.size >= 64) entries.delete(entries.keys().next().value!)
|
|
106
|
+
entries.set(key, value)
|
|
107
|
+
}
|
|
108
|
+
|
|
109
|
+
// Keep an adapter that ignores abort from holding a foreground tool or committing a late reply.
|
|
110
|
+
async function compare(memory: ProjectMemory, sdk: ReviewSdk | undefined, route: Route | undefined,
|
|
111
|
+
kind: string, system: string, input: unknown, caller: AbortSignal, maxTokens: number, authorized: () => void,
|
|
112
|
+
onRequest?: () => void) {
|
|
113
|
+
const signal = AbortSignal.any([caller, AbortSignal.timeout(30_000)])
|
|
114
|
+
const llm = memory.ctx.get('llm')
|
|
115
|
+
if (!sdk || !route || !llm?.stream) throw new StoreError('model_review_unavailable')
|
|
116
|
+
signal.throwIfAborted()
|
|
117
|
+
let stop!: () => void
|
|
118
|
+
const cancelled = new Promise<never>((_, reject) => {
|
|
119
|
+
stop = () => reject(new StoreError('model_review_unavailable'))
|
|
120
|
+
signal.addEventListener('abort', stop, { once: true })
|
|
121
|
+
})
|
|
122
|
+
const run = async () => {
|
|
123
|
+
const prepared = await llm.prepareCall?.({ ...route, maxTokens }, signal,
|
|
124
|
+
(controls: object, info: { reasoning?: { efforts: { id: string }[] } }) =>
|
|
125
|
+
info.reasoning?.efforts.some(e => e.id === 'off') ? { ...controls, reasoningEffort: 'off' } : controls)
|
|
126
|
+
signal.throwIfAborted()
|
|
127
|
+
authorized()
|
|
128
|
+
onRequest?.()
|
|
129
|
+
return reviewText(prepared ?? llm, sdk, { ...route, maxTokens, ...prepared?.config, system, signal,
|
|
130
|
+
messages: [sdk.createUserMessage({ source: { kind }, content: [{ type: 'text', text: JSON.stringify(input) }] })] })
|
|
131
|
+
}
|
|
132
|
+
try { return await Promise.race([run(), cancelled]) }
|
|
133
|
+
finally { signal.removeEventListener('abort', stop) }
|
|
134
|
+
}
|
|
135
|
+
|
|
136
|
+
export async function prepareProjectGuidance(memory: ProjectMemory, root: Agent, items: SemanticCandidate[],
|
|
137
|
+
sdk: ReviewSdk | undefined, sourceTurn: string, signal: AbortSignal, generation: number, authorize?: () => void, onRequest?: () => void) {
|
|
138
|
+
const scope = memory.rootDomain(root, true)
|
|
139
|
+
const eligible = (item: SemanticCandidate) => {
|
|
140
|
+
if (item.scope !== 'project' || item.sensitive || skipsCandidate(item)) return false
|
|
141
|
+
const target = item.replaces && memory.current(scope, item.replaces.id, item.replaces.rev)
|
|
142
|
+
return !item.replaces || (!!target && !projection(target).sensitive)
|
|
143
|
+
}
|
|
144
|
+
const projectItems = items.filter(eligible)
|
|
145
|
+
if (scope.id === memory.personal.id || !projectItems.length) return
|
|
146
|
+
const route = root.model?.current()
|
|
147
|
+
const hostTurn = latestTurn(root.session)
|
|
148
|
+
const original = memory.proposalSources(root, root, scope, sourceTurn, generation)
|
|
149
|
+
function sourceSnapshot(state: typeof original) {
|
|
150
|
+
return projectItems.map(item => state.events.filter(e => e.text.includes(item.user_quote)).map(e =>
|
|
151
|
+
[e.seq, e.block, e.question, e.text, e.formSelections, messageText(state.records.get(e.seq)?.data)]))
|
|
152
|
+
}
|
|
153
|
+
const initial = sourceSnapshot(original)
|
|
154
|
+
if (original.reason || initial.some(e => e.length !== 1)) return
|
|
155
|
+
const live = () => {
|
|
156
|
+
authorize?.()
|
|
157
|
+
signal.throwIfAborted()
|
|
158
|
+
const current = memory.rootDomain(root, true)
|
|
159
|
+
const currentRoute = root.model?.current()
|
|
160
|
+
const currentSources = memory.proposalSources(root, root, current, sourceTurn, generation)
|
|
161
|
+
if (!projectItems.every(eligible) || memory.assistantGeneration() !== generation || latestTurn(root.session) !== hostTurn ||
|
|
162
|
+
currentSources.reason || JSON.stringify(initial) !== JSON.stringify(sourceSnapshot(currentSources)) ||
|
|
163
|
+
currentRoute?.provider !== route?.provider || currentRoute?.model !== route?.model ||
|
|
164
|
+
current.id !== scope.id || current.cwd !== scope.cwd) throw new StoreError('source_unavailable')
|
|
165
|
+
}
|
|
166
|
+
await reviewRepositoryGuidance(scope, projectItems, loadedGuidance(root.session, scope, memory.ctx), async (payload, filesCurrent) => {
|
|
167
|
+
const authorized = () => {
|
|
168
|
+
live()
|
|
169
|
+
if (!filesCurrent()) throw new StoreError('stale_guidance')
|
|
170
|
+
}
|
|
171
|
+
const answer = await compare(memory, sdk, route, 'project-memory-guidance', guidanceComparisonPrompt, payload, signal, 4096, authorized, onRequest)
|
|
172
|
+
live()
|
|
173
|
+
return answer
|
|
174
|
+
})
|
|
175
|
+
}
|
|
176
|
+
|
|
177
|
+
function interpret(proposal: Comparison, response: Record<string, unknown>): Decision {
|
|
178
|
+
if (response.decision === 'skip')
|
|
179
|
+
return { reason: failures.has(String(response.reason)) ? String(response.reason) : 'insufficient_evidence' }
|
|
180
|
+
const row = proposal.proposal
|
|
181
|
+
const kind = response.kind
|
|
182
|
+
if ((kind !== 'fact' && kind !== 'preference' && kind !== 'rule') || !validLabel(response.topic))
|
|
183
|
+
return { reason: 'invalid_model_result' }
|
|
184
|
+
const { scope, usage } = response
|
|
185
|
+
if ((scope !== 'global' && scope !== 'project') || (usage !== 'proactive' && usage !== 'on_demand'))
|
|
186
|
+
return { reason: 'invalid_model_result' }
|
|
187
|
+
// The candidates and their revisions belong to the scope already authorized and
|
|
188
|
+
// searched. A different scope requires a fresh proposal and its own candidate pool.
|
|
189
|
+
if (scope !== row.scope)
|
|
190
|
+
return { reason: 'invalid_scope', ...(!row.replaces && !row.paths.length && {retryScope: scope}) }
|
|
191
|
+
const topic = response.topic.trim()
|
|
192
|
+
let target = proposal.candidates.find(ref => ref.id === response.target)
|
|
193
|
+
const same = response.decision === 'restate'
|
|
194
|
+
if (same || response.decision === 'replace') {
|
|
195
|
+
if (!target?.topic || (row.replaces && row.replaces.id !== target.id))
|
|
196
|
+
return { reason: 'ambiguous_topic' }
|
|
197
|
+
const distinctTopic = normalizeLabel(topic) !== normalizeLabel(target.topic)
|
|
198
|
+
if (distinctTopic || kind !== target.kind) {
|
|
199
|
+
// Search can offer related facts and preferences. An independently identified
|
|
200
|
+
// attribute with a grounded current value can stand on its own. An explicitly
|
|
201
|
+
// addressed write must report the conflict to its caller.
|
|
202
|
+
if (row.replaces || same || !distinctTopic)
|
|
203
|
+
return { reason: kind !== target.kind ? 'kind_mismatch' : 'topic_mismatch' }
|
|
204
|
+
target = undefined
|
|
205
|
+
}
|
|
206
|
+
} else {
|
|
207
|
+
if (response.decision !== 'create' || response.target != null) return { reason: 'ambiguous_topic' }
|
|
208
|
+
if (row.replaces) {
|
|
209
|
+
const requested = proposal.candidates.find(ref => ref.id === row.replaces!.id)
|
|
210
|
+
return { reason: requested && requested.kind !== kind ? 'kind_mismatch' : 'topic_mismatch' }
|
|
211
|
+
}
|
|
212
|
+
}
|
|
213
|
+
const identity = reviewedSubject(response.owner, row.subject, target, Boolean(row.replaces), {
|
|
214
|
+
subject: response.subject, source: [proposal.source, proposal.question ?? ''], aliasQuote: response.aliasQuote,
|
|
215
|
+
})
|
|
216
|
+
if ('reason' in identity) return identity
|
|
217
|
+
const span = response.span
|
|
218
|
+
const restatesOption = same && kind !== 'fact' && response.selectedOption != null
|
|
219
|
+
let action: unknown = same ? target!.action : response.action
|
|
220
|
+
if ((!same || restatesOption) && kind !== 'fact') {
|
|
221
|
+
// The model chooses the whole quote only after confirming it expresses one
|
|
222
|
+
// durable instruction. For a mixed utterance it must isolate the operative clause.
|
|
223
|
+
action = response.directive === true || (restatesOption && response.directive === undefined) ? row.user_quote : response.directive
|
|
224
|
+
} else if (!same && span !== undefined) {
|
|
225
|
+
if (!Array.isArray(span) || span.length !== 2 || !span.every(Number.isInteger) || span[0] < 0 ||
|
|
226
|
+
span[1] < span[0] || span[1] >= proposal.evidenceTokens.length) return { reason: 'insufficient_evidence' }
|
|
227
|
+
action = proposal.evidenceTokens.slice(span[0], span[1] + 1).map(([, token]) => token).join('').trim()
|
|
228
|
+
}
|
|
229
|
+
if (typeof action !== 'string' || !action.trim() || action.length > 480 || ((!same || restatesOption) && !row.user_quote.includes(action)))
|
|
230
|
+
return { reason: 'insufficient_evidence' }
|
|
231
|
+
const selected = resolveSelectedDirective(action, response.selectedOption, proposal.submittedOptions, kind !== 'fact')
|
|
232
|
+
if (!selected || (same && selected.action !== target!.action)) return { reason: 'insufficient_evidence' }
|
|
233
|
+
const { action: selectedDirective, selection } = selected
|
|
234
|
+
if (!target) return { selection, row: { ...row, kind, topic, action: selectedDirective, subject: identity.subject,
|
|
235
|
+
usage: row.sensitive ? 'on_demand' : usage } }
|
|
236
|
+
return { selection, row: { ...row, kind, action: selectedDirective, topic: target.topic!, subject: target.subject, usage: target.usage ?? row.usage,
|
|
237
|
+
sensitive: row.sensitive || target.sensitive,
|
|
238
|
+
...reviewedQualifiers(row, target, response.equivalentQualifiers),
|
|
239
|
+
replaces: { id: target.id, rev: target.rev } } }
|
|
240
|
+
}
|
|
241
|
+
|
|
242
|
+
interface ReviewCounts { interpretation: number; repositoryGuidance: number }
|
|
243
|
+
function storedFields(rule: Rule, scope: SemanticCandidate['scope']) {
|
|
244
|
+
const { subject, semanticTopic: topic, kind, usage, action, when, exceptions, paths } = rule
|
|
245
|
+
if (rule.sensitive || skipsAutomaticMemory([subject, topic, action, when, exceptions, ...paths].join(' ')))
|
|
246
|
+
return { scope, protected: true as const }
|
|
247
|
+
return { scope, kind, subject, topic, usage, action, when, exceptions, paths }
|
|
248
|
+
}
|
|
249
|
+
|
|
250
|
+
// Read the exact committed head. A concurrent replacement or withdrawal can leave a
|
|
251
|
+
// genuine write receipt whose contents are no longer current.
|
|
252
|
+
function storedOutcome(memory: ProjectMemory, owner: AccessDomain, outcome: Committed): Outcome {
|
|
253
|
+
try {
|
|
254
|
+
const rule = memory.current(owner, outcome.id, outcome.rev)
|
|
255
|
+
if (rule) return { ...outcome, stored: storedFields(rule, owner.id === memory.personal.id ? 'global' : 'project') }
|
|
256
|
+
} catch (error) {
|
|
257
|
+
memory.ctx.logger.warn('记忆已提交,暂时无法核对该版本的回执正文:' + String(error))
|
|
258
|
+
}
|
|
259
|
+
return { ...outcome, stored: null }
|
|
260
|
+
}
|
|
261
|
+
|
|
262
|
+
function result(outcomes: Outcome[], reviewRequests: ReviewCounts) {
|
|
263
|
+
const entries = new Map<string, Ref>()
|
|
264
|
+
for (const item of outcomes) if (item.status !== 'skipped') entries.set(item.id, { id: item.id, rev: item.rev })
|
|
265
|
+
const status = !entries.size ? 'skipped' : outcomes.some(r => r.status === 'skipped') ? 'partial'
|
|
266
|
+
: outcomes.some(r => r.status === 'saved') ? 'saved' : 'duplicate'
|
|
267
|
+
return { status, reviewRequests, entries: [...entries.values()], results: outcomes.map((r, index) => ({ index, ...r })) }
|
|
268
|
+
}
|
|
269
|
+
|
|
270
|
+
/** Normal foreground write entry. The chat proposes claims; one tool-free comparison binds each
|
|
271
|
+
* claim to its actual utterance and offered revisions. Only the synchronous store path commits. */
|
|
272
|
+
export async function reviewProposals(memory: ProjectMemory, agent: Agent, input: unknown, sdk?: ReviewSdk, callerSignal?: AbortSignal) {
|
|
273
|
+
const raw = candidateRows(input)
|
|
274
|
+
const { root, domain, turnId } = memory.proposalContext(agent)
|
|
275
|
+
const generation = memory.assistantGeneration()
|
|
276
|
+
const sources = memory.proposalSources(root, agent, domain, turnId, generation)
|
|
277
|
+
const reviewRequests = { interpretation: 0, repositoryGuidance: 0 }
|
|
278
|
+
const allSkipped = (why: string) => result(raw.map(() => skipped(why)), reviewRequests)
|
|
279
|
+
const unavailable = () => ({ ...result([], reviewRequests), status: 'unavailable' })
|
|
280
|
+
if (sources.reason || generation === undefined) return allSkipped(sources.reason ?? 'memory_disabled')
|
|
281
|
+
const route = root.model?.current()
|
|
282
|
+
const signal = callerSignal ?? new AbortController().signal
|
|
283
|
+
const store = memory.storeId(root.session)
|
|
284
|
+
const scopes = memory.scopes(agent, domain)
|
|
285
|
+
const epochs = new Map(scopes.map(scope => [scope.id, memory.store.epoch(scope.id)]))
|
|
286
|
+
const live = () => {
|
|
287
|
+
signal.throwIfAborted()
|
|
288
|
+
const now = memory.proposalContext(agent)
|
|
289
|
+
const currentRoute = root.model?.current()
|
|
290
|
+
if (now.root !== root || now.domain.id !== domain.id || now.domain.root !== domain.root || now.domain.cwd !== domain.cwd ||
|
|
291
|
+
now.turnId !== turnId || memory.storeId(root.session) !== store || memory.assistantGeneration() !== generation ||
|
|
292
|
+
route?.provider !== currentRoute?.provider || route?.model !== currentRoute?.model)
|
|
293
|
+
throw new StoreError('source_unavailable')
|
|
294
|
+
}
|
|
295
|
+
let cache = remembered.get(agent)
|
|
296
|
+
if (cache?.turn !== turnId) {
|
|
297
|
+
cache = { turn: turnId, rows: new Map(), committed: new Map(), scopeRetries: new Map(), scopeChanges: new Map() }
|
|
298
|
+
remembered.set(agent, cache)
|
|
299
|
+
}
|
|
300
|
+
const originals = new Map<number, BoundSource>()
|
|
301
|
+
const exclusions = new Map<number, { domain: string; seq: number; start: number; end: number }>()
|
|
302
|
+
const operations = new Map<number, string>()
|
|
303
|
+
const retryKeys = new Map<number, string>()
|
|
304
|
+
const inputSlots = new Map<number, MemorySlot>()
|
|
305
|
+
const prepared = new Map<number, SemanticCandidate>()
|
|
306
|
+
const selectionEvidence = new Map<number, SelectionEvidence>()
|
|
307
|
+
const outcomes: Outcome[] = new Array(raw.length)
|
|
308
|
+
const receipts = new Map<number, { owner: AccessDomain; receipt: Committed }>()
|
|
309
|
+
const successful = new Set<number>()
|
|
310
|
+
const attempts = new ForegroundAttempts(memory.store.turnReviews, foregroundTurnKey(store, root.id, turnId, domain.id, generation))
|
|
311
|
+
const localChecks = attempts.batch()
|
|
312
|
+
const charged = new Set<number>()
|
|
313
|
+
function reserve(index: number, batch = localChecks) {
|
|
314
|
+
if (!attempts.admit(index, batch)) throw new StoreError('retry_limit_reached')
|
|
315
|
+
charged.add(index)
|
|
316
|
+
}
|
|
317
|
+
function failItem(index: number, error: unknown, fallback: string) {
|
|
318
|
+
let reason = error instanceof StoreError ? error.code : fallback
|
|
319
|
+
if (!charged.has(index) && reason !== 'retry_limit_reached' && !attempts.admit(index, localChecks))
|
|
320
|
+
reason = 'retry_limit_reached'
|
|
321
|
+
outcomes[index] = skipped(reason)
|
|
322
|
+
}
|
|
323
|
+
function finish(disclose = true) {
|
|
324
|
+
try {
|
|
325
|
+
const exhausted = attempts.finish(index => successful.has(index) || receipts.has(index))
|
|
326
|
+
for (const index of exhausted) {
|
|
327
|
+
const outcome = outcomes[index]
|
|
328
|
+
// Explicit non-retention decisions keep their meaning for both the receipt and turn review.
|
|
329
|
+
if (outcome?.status === 'skipped' && outcome.reason !== 'opted_out' && outcome.reason !== 'one_time_request')
|
|
330
|
+
outcomes[index] = skipped('retry_limit_reached')
|
|
331
|
+
}
|
|
332
|
+
} catch {
|
|
333
|
+
// A failed refund conservatively leaves the reservation in place. It cannot undo a durable write.
|
|
334
|
+
memory.ctx.logger.warn('未能更新本轮记忆保存的重试次数。')
|
|
335
|
+
}
|
|
336
|
+
if (!disclose) return unavailable()
|
|
337
|
+
if (receipts.size) {
|
|
338
|
+
try { live() } catch { return unavailable() }
|
|
339
|
+
const visible = memory.scopes(agent, domain)
|
|
340
|
+
for (const [index, {owner, receipt}] of receipts) {
|
|
341
|
+
if (!visible.some(scope => scope.id === owner.id)) return unavailable()
|
|
342
|
+
outcomes[index] = storedOutcome(memory, owner, receipt)
|
|
343
|
+
}
|
|
344
|
+
}
|
|
345
|
+
return result(outcomes, reviewRequests)
|
|
346
|
+
}
|
|
347
|
+
const narrow = async (index: number, ref: Ref, row: SemanticCandidate, event: UserBlock, source: string): Promise<Committed> => {
|
|
348
|
+
live()
|
|
349
|
+
if (event.question || sources.records.get(event.seq)?.type !== 'user/message')
|
|
350
|
+
throw new StoreError('invalid_source')
|
|
351
|
+
const occurrence = { storeId: store, sessionId: root.id, turnId, seq: event.seq }
|
|
352
|
+
const replay = memory.store.narrowedProjectRef(domain.id, ref, occurrence, row.user_quote)
|
|
353
|
+
if (replay && memory.current(domain, replay.id, replay.rev)) return { status: 'duplicate', ...replay }
|
|
354
|
+
reserve(index, attempts.batch())
|
|
355
|
+
const old = previousScopeAgreement(memory, root, domain, ref, generation, turnId)
|
|
356
|
+
const candidate = projectAgreement(old)
|
|
357
|
+
const authorize = () => {
|
|
358
|
+
live()
|
|
359
|
+
const current = memory.proposalSources(root, agent, domain, turnId, generation)
|
|
360
|
+
if (!sourceIsCurrent({ ...event, source }, current)) throw new StoreError('source_unavailable')
|
|
361
|
+
if (scopes.some(scope => memory.store.epoch(scope.id) !== epochs.get(scope.id)))
|
|
362
|
+
throw new StoreError('candidate_set_changed')
|
|
363
|
+
previousScopeAgreement(memory, root, domain, ref, generation, turnId)
|
|
364
|
+
}
|
|
365
|
+
const key = digest(JSON.stringify([generation, route, domain.id, domain.cwd, store, ref, event.seq, source, row.user_quote]))
|
|
366
|
+
let accepted = cache.scopeChanges.get(key)
|
|
367
|
+
if (accepted === undefined) {
|
|
368
|
+
const input = { previous: { id: old.id, topic: candidate.topic, action: old.action, when: old.when, exceptions: old.exceptions },
|
|
369
|
+
source, excerpt: row.user_quote }
|
|
370
|
+
const text = await compare(memory, sdk, route, 'project-memory-scope', prompts[memory.promptLanguage(root)].narrow, input, signal, 512,
|
|
371
|
+
authorize, () => reviewRequests.interpretation++)
|
|
372
|
+
authorize()
|
|
373
|
+
let decision
|
|
374
|
+
try { decision = JSON.parse(text.trim().replace(/^```(?:json)?\s*\n([\s\S]*)\n```$/iu, '$1')) }
|
|
375
|
+
catch { throw new StoreError('invalid_model_result') }
|
|
376
|
+
accepted = decision?.decision === 'narrow' && decision.target === ref.id && typeof decision.quote === 'string' &&
|
|
377
|
+
Boolean(decision.quote.trim()) && row.user_quote.includes(decision.quote)
|
|
378
|
+
remember(cache.scopeChanges, key, accepted)
|
|
379
|
+
}
|
|
380
|
+
if (!accepted) throw new StoreError('insufficient_evidence')
|
|
381
|
+
await prepareProjectGuidance(memory, root, [candidate], sdk, old.source.turnId, signal, generation, authorize,
|
|
382
|
+
() => reviewRequests.repositoryGuidance++)
|
|
383
|
+
authorize()
|
|
384
|
+
const moved = memory.narrowToProject(root, ref, row.user_quote, generation, epochs, candidate)
|
|
385
|
+
return { status: moved.status, ...moved.entries[0] }
|
|
386
|
+
}
|
|
387
|
+
const pending: { comparison: Comparison; key: string; size: number }[] = []
|
|
388
|
+
const accept = (index: number, decision: Decision) => {
|
|
389
|
+
if ('row' in decision) {
|
|
390
|
+
prepared.set(index, decision.row)
|
|
391
|
+
if (decision.selection) selectionEvidence.set(index, decision.selection)
|
|
392
|
+
}
|
|
393
|
+
else {
|
|
394
|
+
const retry = decision.retryScope
|
|
395
|
+
const available = retry === 'global' ? agent === root && epochs.has(memory.personal.id) :
|
|
396
|
+
retry === 'project' && domain.id !== memory.personal.id && epochs.has(domain.id)
|
|
397
|
+
const key = retryKeys.get(index)
|
|
398
|
+
const mayRetry = retry && available && key && !cache.scopeRetries.has(key)
|
|
399
|
+
if (mayRetry) remember(cache.scopeRetries, key, retry)
|
|
400
|
+
outcomes[index] = { status:'skipped', reason:decision.reason, ...(mayRetry && {retryScope:retry}) }
|
|
401
|
+
}
|
|
402
|
+
}
|
|
403
|
+
// Complete scope corrections before searching for the other items. A move changes
|
|
404
|
+
// the visible candidates in both scopes, including for earlier items in this batch.
|
|
405
|
+
for (const [index, value] of raw.entries()) {
|
|
406
|
+
const item = value as Partial<SemanticCandidate> | null
|
|
407
|
+
if (root !== agent || domain.id === memory.personal.id || item?.scope !== 'project' ||
|
|
408
|
+
typeof item.replaces?.id !== 'string' || memory.store.read(domain.id, item.replaces.id)) continue
|
|
409
|
+
try {
|
|
410
|
+
const { row, event, source } = groundedProposal({ ...item, kind: item.kind ?? 'rule', topic: item.topic ?? 'scope' }, sources,
|
|
411
|
+
(event, quote) => attempts.bind(index, event, quote))
|
|
412
|
+
receipts.set(index, {owner: domain, receipt: await narrow(index, row.replaces!, row, event, source)})
|
|
413
|
+
} catch (error) {
|
|
414
|
+
failItem(index, error, 'model_review_unavailable')
|
|
415
|
+
}
|
|
416
|
+
}
|
|
417
|
+
if (receipts.size) for (const scope of scopes) epochs.set(scope.id, memory.store.epoch(scope.id))
|
|
418
|
+
for (const [index, value] of raw.entries()) {
|
|
419
|
+
if (receipts.has(index) || outcomes[index]) continue
|
|
420
|
+
try {
|
|
421
|
+
const { row, event, source } = groundedProposal(value, sources, (event, quote) => attempts.bind(index, event, quote),
|
|
422
|
+
fields => withTargetLabels(fields, memory, domain, root === agent && epochs.has(memory.personal.id)))
|
|
423
|
+
retryKeys.set(index, digest(JSON.stringify([generation, store, route, event.seq, event.block, row.user_quote, row.topic])))
|
|
424
|
+
inputSlots.set(index, semanticSlot(row.scope, row.topic, row.subject)!)
|
|
425
|
+
const owner = row.scope === 'global' ? memory.personal : domain
|
|
426
|
+
if (!epochs.has(owner.id) || (row.scope === 'global' && (agent !== root || row.paths.length)) ||
|
|
427
|
+
(row.scope === 'project' && owner.id === memory.personal.id)) throw new StoreError('invalid_scope')
|
|
428
|
+
const start = (event.offset ?? 0) + event.text.indexOf(row.user_quote)
|
|
429
|
+
exclusions.set(index, {domain:owner.id, seq:event.seq, start, end:start + row.user_quote.length})
|
|
430
|
+
originals.set(index, { ...event, source })
|
|
431
|
+
const operation = digest(JSON.stringify([store, generation, owner.id, route, event.seq, event.block, event.question, event.formSelections, source, row]))
|
|
432
|
+
operations.set(index, operation)
|
|
433
|
+
const replay = cache.committed.get(operation)
|
|
434
|
+
if (replay) {
|
|
435
|
+
accept(index, replay)
|
|
436
|
+
continue
|
|
437
|
+
}
|
|
438
|
+
let heads: Rule[]
|
|
439
|
+
if (row.replaces) {
|
|
440
|
+
const target = memory.current(owner, row.replaces.id)
|
|
441
|
+
if (!target) throw new StoreError('target_not_found')
|
|
442
|
+
// The metadata proposed by the chat model can use the old name for the
|
|
443
|
+
// speaker. Resolve who is speaking from the utterance before comparing roles.
|
|
444
|
+
const mismatch = targetMismatch({ ...row, subject: target.subject }, target)
|
|
445
|
+
if (mismatch) throw new StoreError(mismatch)
|
|
446
|
+
if (target.rev !== row.replaces.rev) {
|
|
447
|
+
// A restart can lose the in-memory decision. Only exact SQLite evidence may
|
|
448
|
+
// replay an already committed replacement, even when later retries exhausted the budget.
|
|
449
|
+
live()
|
|
450
|
+
const current = memory.proposalSources(root, agent, domain, turnId, generation)
|
|
451
|
+
if (!sourceIsCurrent({ ...event, source }, current)) throw new StoreError('source_unavailable')
|
|
452
|
+
const [draft] = prepareItems(domain, { items: [ruleFields(row)] }, current.events,
|
|
453
|
+
row.scope === 'project' ? loadedGuidance(root.session, domain, memory.ctx) : [])
|
|
454
|
+
const ref = memory.store.replayedReplacement(owner.id, row.replaces,
|
|
455
|
+
{storeId: store, sessionId: root.id, turnId, origin: 'user', seq: event.seq},
|
|
456
|
+
semanticDraft({...row, subject: target.subject}, draft, target))
|
|
457
|
+
if (!ref) throw new StoreError('stale_revision')
|
|
458
|
+
receipts.set(index, {owner, receipt: {status: 'duplicate', ...ref}})
|
|
459
|
+
continue
|
|
460
|
+
}
|
|
461
|
+
heads = [target]
|
|
462
|
+
} else {
|
|
463
|
+
if (attempts.exhausted(index)) throw new StoreError('retry_limit_reached')
|
|
464
|
+
// Subject labels are proposed in open vocabulary. Use them as search text;
|
|
465
|
+
// filtering by a generated spelling here can hide the correct incident target.
|
|
466
|
+
heads = await memory.search(agent, [row.subject, row.topic, row.user_quote].filter(Boolean).join(' '), undefined, {
|
|
467
|
+
scope: row.scope === 'global' ? 'profile' : 'project', topic: row.topic,
|
|
468
|
+
}, undefined, {
|
|
469
|
+
limit: maxCandidates,
|
|
470
|
+
// Only an exact submitted subject and topic may identify a protected fact.
|
|
471
|
+
accept: head => !!head.semanticTopic && (!head.sensitive || (!!row.subject &&
|
|
472
|
+
normalizeLabel(row.subject) === normalizeLabel(head.subject ?? '') &&
|
|
473
|
+
normalizeLabel(row.topic) === normalizeLabel(head.semanticTopic))),
|
|
474
|
+
})
|
|
475
|
+
}
|
|
476
|
+
const submittedOptions = choicesForQuote(event.text, row.user_quote, event.formSelections)
|
|
477
|
+
const comparison = { index, source, question: event.question, proposal: row, evidenceTokens: evidenceTokens(row.user_quote),
|
|
478
|
+
...(submittedOptions && { submittedOptions }),
|
|
479
|
+
candidates: heads.filter(r => !skipsAutomaticMemory([r.subject, r.semanticTopic].join(' '))).map(projection) }
|
|
480
|
+
const key = digest(JSON.stringify([operation, comparison.candidates]))
|
|
481
|
+
const previous = cache.rows.get(key)
|
|
482
|
+
if (previous) {
|
|
483
|
+
reserve(index)
|
|
484
|
+
accept(index, previous)
|
|
485
|
+
}
|
|
486
|
+
else {
|
|
487
|
+
const size = Buffer.byteLength(JSON.stringify(comparison))
|
|
488
|
+
if (size + 12 > maxBatchBytes) throw new StoreError('review_input_too_large')
|
|
489
|
+
else pending.push({ comparison, key, size })
|
|
490
|
+
}
|
|
491
|
+
} catch (error) {
|
|
492
|
+
failItem(index, error, 'source_unavailable')
|
|
493
|
+
}
|
|
494
|
+
}
|
|
495
|
+
// Bound both the number of proposed changes and their prompts. Never truncate the evidence
|
|
496
|
+
// or drop a trailing qualifier to fit an individual decision into the request.
|
|
497
|
+
while (pending.length) {
|
|
498
|
+
const batch = [pending.shift()!]
|
|
499
|
+
let bytes = 12 + batch[0].size
|
|
500
|
+
while (pending.length && batch.length < maxBatchItems && bytes + pending[0].size + 1 <= maxBatchBytes) {
|
|
501
|
+
bytes += pending[0].size + 1
|
|
502
|
+
batch.push(pending.shift()!)
|
|
503
|
+
}
|
|
504
|
+
try {
|
|
505
|
+
const allowance = attempts.batch()
|
|
506
|
+
const admitted = batch.filter(({comparison: {index}}) => {
|
|
507
|
+
try { reserve(index, allowance); return true }
|
|
508
|
+
catch (error) { failItem(index, error, 'source_unavailable'); return false }
|
|
509
|
+
})
|
|
510
|
+
if (!admitted.length) continue
|
|
511
|
+
const items = admitted.map(entry => entry.comparison)
|
|
512
|
+
const changed = ({ index, proposal, candidates }: Comparison, sources: ProposalSources) => {
|
|
513
|
+
if (!sourceIsCurrent(originals.get(index), sources)) return sources.reason ?? 'source_unavailable'
|
|
514
|
+
const owner = proposal.scope === 'global' ? memory.personal : domain
|
|
515
|
+
for (const candidate of candidates) {
|
|
516
|
+
if (memory.current(owner, candidate.id, candidate.rev)) continue
|
|
517
|
+
if (proposal.replaces?.id === candidate.id)
|
|
518
|
+
return memory.current(owner, candidate.id) ? 'stale_revision' : 'target_not_found'
|
|
519
|
+
return 'candidate_set_changed'
|
|
520
|
+
}
|
|
521
|
+
}
|
|
522
|
+
const authorized = () => {
|
|
523
|
+
live()
|
|
524
|
+
const sources = memory.proposalSources(root, agent, domain, turnId, generation)
|
|
525
|
+
for (const item of items) {
|
|
526
|
+
const reason = changed(item, sources)
|
|
527
|
+
if (reason) throw new StoreError(reason)
|
|
528
|
+
}
|
|
529
|
+
}
|
|
530
|
+
const claims = items.map(({proposal, submittedOptions, ...item}) => {
|
|
531
|
+
const { action, keywords, ...fields } = proposal
|
|
532
|
+
// Only offer a suggested value when the source actually contains it. A paraphrase
|
|
533
|
+
// or composite from the first model can otherwise anchor the second model's answer.
|
|
534
|
+
return { ...item, ...(submittedOptions && {submittedOptions: submittedOptions.map(({question, label}) => ({question, label}))}),
|
|
535
|
+
proposal: { ...fields, ...(proposal.user_quote.includes(action) && { action }) } }
|
|
536
|
+
})
|
|
537
|
+
const text = await compare(memory, sdk, route, 'project-memory-interpret', prompts[memory.promptLanguage(root)].interpret,
|
|
538
|
+
{ items: claims }, signal, 2048, authorized, () => reviewRequests.interpretation++)
|
|
539
|
+
live()
|
|
540
|
+
const current = memory.proposalSources(root, agent, domain, turnId, generation)
|
|
541
|
+
const response = JSON.parse(text.trim().replace(/^```(?:json)?\s*\n([\s\S]*)\n```$/iu, '$1'))
|
|
542
|
+
if (!Array.isArray(response?.items)) throw new StoreError('invalid_model_result')
|
|
543
|
+
for (const { comparison, key } of admitted) {
|
|
544
|
+
const why = changed(comparison, current)
|
|
545
|
+
if (why) { outcomes[comparison.index] = skipped(why); continue }
|
|
546
|
+
const rows = response.items.filter((r: Record<string, unknown> | null) => r?.index === comparison.index)
|
|
547
|
+
if (rows.length !== 1) { outcomes[comparison.index] = skipped('invalid_model_result'); continue }
|
|
548
|
+
const decision = interpret(comparison, rows[0])
|
|
549
|
+
remember(cache.rows, key, decision)
|
|
550
|
+
accept(comparison.index, decision)
|
|
551
|
+
}
|
|
552
|
+
} catch (error) {
|
|
553
|
+
const code = error instanceof StoreError ? error.code : error instanceof SyntaxError ? 'invalid_model_result' : 'model_review_unavailable'
|
|
554
|
+
for (const item of batch) outcomes[item.comparison.index] ??= skipped(code)
|
|
555
|
+
}
|
|
556
|
+
}
|
|
557
|
+
// A later end-of-turn pass must respect a verdict that the user declined
|
|
558
|
+
// retention or gave a one-off instruction. Store offsets only, never the quote.
|
|
559
|
+
const excluded = [...exclusions].filter(([index]) => {
|
|
560
|
+
const outcome = outcomes[index]
|
|
561
|
+
return outcome?.status === 'skipped' && (outcome.reason === 'opted_out' || outcome.reason === 'one_time_request')
|
|
562
|
+
})
|
|
563
|
+
if (excluded.length && memory.assistantGeneration() === generation && !signal.aborted) {
|
|
564
|
+
const current = memory.proposalSources(root, agent, domain, turnId, generation)
|
|
565
|
+
for (const [index, {domain: owner, ...span}] of excluded) if (sourceIsCurrent(originals.get(index), current)) {
|
|
566
|
+
memory.store.turnReviews.noteHandled(owner, { storeId:store, sessionId:root.id, turnId, seq:span.seq }, [span])
|
|
567
|
+
}
|
|
568
|
+
}
|
|
569
|
+
if (!prepared.size) return finish()
|
|
570
|
+
const ordered = [...prepared].sort(([a], [b]) => a - b)
|
|
571
|
+
try {
|
|
572
|
+
live()
|
|
573
|
+
// Committed replays still revalidate against the current store. They never need another model request.
|
|
574
|
+
await prepareProjectGuidance(memory, root, ordered.filter(([index]) => charged.has(index)).map(([, row]) => row), sdk, turnId, signal, generation, live,
|
|
575
|
+
() => reviewRequests.repositoryGuidance++)
|
|
576
|
+
live()
|
|
577
|
+
} catch (error) {
|
|
578
|
+
for (const [index] of ordered) outcomes[index] = skipped(error instanceof StoreError ? error.code : 'source_unavailable')
|
|
579
|
+
return finish()
|
|
580
|
+
}
|
|
581
|
+
const currentSources = memory.proposalSources(root, agent, domain, turnId, generation)
|
|
582
|
+
const stable = ordered.filter(([index, row]) => {
|
|
583
|
+
if (!sourceIsCurrent(originals.get(index), currentSources)) {
|
|
584
|
+
outcomes[index] = skipped(currentSources.reason ?? 'source_unavailable')
|
|
585
|
+
return false
|
|
586
|
+
}
|
|
587
|
+
const owner: AccessDomain = row.scope === 'global' ? memory.personal : domain
|
|
588
|
+
if (epochs.get(owner.id) === memory.store.epoch(owner.id)) return true
|
|
589
|
+
// Let the commit path report a genuinely changed target (or the receipt for this very
|
|
590
|
+
// operation). New records must be reconsidered if the candidate pool changed.
|
|
591
|
+
if (row.replaces && memory.store.read(owner.id, row.replaces.id)?.rev !== row.replaces.rev) return true
|
|
592
|
+
outcomes[index] = skipped('candidate_set_changed')
|
|
593
|
+
return false
|
|
594
|
+
})
|
|
595
|
+
if (stable.length) {
|
|
596
|
+
const committed = memory.propose(agent, { items: stable.map(([, row]) => row) }, stable.map(([index]) => inputSlots.get(index)!),
|
|
597
|
+
stable.map(([index]) => selectionEvidence.get(index)))
|
|
598
|
+
for (const outcome of committed.results) if (outcome.status !== 'skipped') successful.add(stable[outcome.index][0])
|
|
599
|
+
try { live() } catch { return finish(false) }
|
|
600
|
+
const visible = new Set(memory.scopes(agent, domain).map(scope => scope.id))
|
|
601
|
+
for (const { index, ...outcome } of committed.results) {
|
|
602
|
+
const [original, row] = stable[index]
|
|
603
|
+
if (outcome.status === 'skipped') {
|
|
604
|
+
outcomes[original] = outcome
|
|
605
|
+
continue
|
|
606
|
+
}
|
|
607
|
+
const owner = row.scope === 'global' ? memory.personal : domain
|
|
608
|
+
if (!visible.has(owner.id)) return finish(false)
|
|
609
|
+
outcomes[original] = storedOutcome(memory, owner, outcome)
|
|
610
|
+
remember(cache.committed, operations.get(original)!, {row, selection: selectionEvidence.get(original)})
|
|
611
|
+
}
|
|
612
|
+
}
|
|
613
|
+
return finish()
|
|
614
|
+
}
|