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
package/dist/service.js
CHANGED
|
@@ -1,19 +1,30 @@
|
|
|
1
|
-
import {
|
|
2
|
-
import {
|
|
1
|
+
import { prompts } from "./prompt-copy.js";
|
|
2
|
+
import { indexLimits, taskMatcher, taskTerms } from "./index-policy.js";
|
|
3
|
+
import { Retrieval, newSearchTrace } from "./retrieval.js";
|
|
3
4
|
import { isKnowledge, knowledgeValid, knowledgeDetails, reviseKnowledge } from "./knowledge.js";
|
|
4
5
|
import { isPersonalSlot, isSemanticSlot, normalizeLabel, semanticSlot, validLabel } from "./personal.js";
|
|
5
|
-
import { candidateRows,
|
|
6
|
+
import { candidateRows, parseCandidate, planSemantic, semanticDraft, targetMismatch, sameSemanticContent, separateContexts, skipsCandidate } from "./semantic.js";
|
|
6
7
|
import { isDeepStrictEqual } from 'node:util';
|
|
7
8
|
import { realpathSync } from 'node:fs';
|
|
9
|
+
import { createRequire } from 'node:module';
|
|
8
10
|
import { refusesAutomaticMemory, skipsAutomaticMemory } from "./automatic.js";
|
|
9
11
|
import { resolveDomainCached } from "./domain.js";
|
|
10
|
-
import { MemoryStore, revisionDraft, StoreError, } from "./store.js";
|
|
12
|
+
import { MemoryStore, inputClaimKey, revisionDraft, StoreError, } from "./store.js";
|
|
11
13
|
import { buildIndex, manualItem, needsHumanReview, prepareItems, relatedRules, reviewItem, sameRule, validateRule, } from "./policy.js";
|
|
12
|
-
import { bindSource, loadedGuidance, sources, sourceStore } from "./sources.js";
|
|
13
|
-
import {
|
|
14
|
+
import { bindSource, boundSourceDomain, loadedGuidance, sources, sourceStore } from "./sources.js";
|
|
15
|
+
import { questionForm, selectedAction, standingRequest } from "./question-answers.js";
|
|
16
|
+
import { proposalReceipts } from "./proposal-receipts.js";
|
|
17
|
+
import { ToolExperienceEvidence } from "./tool-experience.js";
|
|
14
18
|
import { messageText, } from "./host.js";
|
|
19
|
+
import { currentImport, scanImport } from "./file-import.js";
|
|
15
20
|
import { notifyUI } from "./ui.js";
|
|
21
|
+
import { actionInDomain } from "./command-scope.js";
|
|
22
|
+
import { previousScopeAgreement } from "./scope-narrowing.js";
|
|
16
23
|
export const indexName = 'project-memory:index';
|
|
24
|
+
function isDatabaseOnly(domain, rule) {
|
|
25
|
+
return rule.usage === 'on_demand' && !isKnowledge(rule) && !rule.paths.length &&
|
|
26
|
+
!rule.hard && !rule.guidance && !rule.localException && actionInDomain(domain, rule.action, () => undefined);
|
|
27
|
+
}
|
|
17
28
|
export const ruleFields = (r) => ({
|
|
18
29
|
action: r.action,
|
|
19
30
|
when: r.when,
|
|
@@ -42,7 +53,8 @@ export const publicRule = (r) => ({
|
|
|
42
53
|
localException: r.localException,
|
|
43
54
|
});
|
|
44
55
|
function managerRule(rule, indexed, delivered) {
|
|
45
|
-
|
|
56
|
+
const canChangeUsage = !rule.sensitive && rule.kind !== 'fact' && !isKnowledge(rule);
|
|
57
|
+
return { ...publicRule(rule), canChangeUsage, indexed, delivered };
|
|
46
58
|
}
|
|
47
59
|
const exactMemoryId = /^(mem-[\da-f-]+)(?:@(\d+))?$/u;
|
|
48
60
|
function semanticMetadata(row, action = row.action) {
|
|
@@ -54,23 +66,10 @@ function semanticMetadata(row, action = row.action) {
|
|
|
54
66
|
keywords: row.keywords?.filter(word => !row.action.includes(word) || action.includes(word)),
|
|
55
67
|
};
|
|
56
68
|
}
|
|
57
|
-
const
|
|
58
|
-
|
|
59
|
-
|
|
60
|
-
|
|
61
|
-
outside_environment: '当前机器或环境不适用',
|
|
62
|
-
stale_guidance: '仓库指令已变更',
|
|
63
|
-
needs_clarification: '需要澄清仓库指令',
|
|
64
|
-
needs_review: '文件、构建目标或其他适用条件已变化',
|
|
65
|
-
anchor_changed: '依据文件内容已变更',
|
|
66
|
-
anchor_unavailable: '依据文件无法读取',
|
|
67
|
-
invalid_anchor: '依据文件已失效',
|
|
68
|
-
invalid_anchors: '文件依据不完整',
|
|
69
|
-
symbol_missing: '依据中的符号已消失',
|
|
70
|
-
invalid_reference: '参考来源已失效',
|
|
71
|
-
invalid_workdir: '工作目录已失效',
|
|
72
|
-
invalid_match: '适用命令已失效',
|
|
73
|
-
unconfirmed_guard: '命令约束未确认',
|
|
69
|
+
const requireUI = createRequire(import.meta.url);
|
|
70
|
+
const uiMessages = {
|
|
71
|
+
en: requireUI('../locale/en.json').ui,
|
|
72
|
+
zh: requireUI('../locale/zh.json').ui,
|
|
74
73
|
};
|
|
75
74
|
function containsWords(query, fields) {
|
|
76
75
|
const text = fields.join(' ').normalize('NFKC').toLocaleLowerCase();
|
|
@@ -101,16 +100,63 @@ export function matches(rule, query) {
|
|
|
101
100
|
.every((word) => haystack.includes(word));
|
|
102
101
|
}
|
|
103
102
|
export class ProjectMemory {
|
|
104
|
-
|
|
105
|
-
|
|
103
|
+
bashEvidence = new ToolExperienceEvidence();
|
|
104
|
+
experienceSource(agent, generation, callId) {
|
|
105
|
+
if (!this.bashEvidence.hasObservations(agent) || this.assistantGeneration() !== generation)
|
|
106
|
+
return;
|
|
107
|
+
const domain = this.rootDomain(agent, true);
|
|
108
|
+
if (domain.id === this.personal.id)
|
|
109
|
+
return;
|
|
110
|
+
const source = this.bashEvidence.source(agent, domain, generation, this.storeId(agent.session), callId);
|
|
111
|
+
if (!source)
|
|
112
|
+
return;
|
|
113
|
+
const blocks = sources(agent.session, domain, source.storeId, source.turnId);
|
|
114
|
+
if (!blocks.some(b => !b.question && b.memoryGeneration === generation) ||
|
|
115
|
+
blocks.some(b => b.refused || refusesAutomaticMemory(b.text)))
|
|
116
|
+
return;
|
|
117
|
+
return { domain, source };
|
|
118
|
+
}
|
|
119
|
+
proposeExperience(agent, args, generation) {
|
|
120
|
+
if (Object.keys(args).some(k => !['callId', 'topic', 'action'].includes(k)) ||
|
|
121
|
+
typeof args.callId !== 'string' || !args.callId || !validLabel(args.topic) ||
|
|
122
|
+
typeof args.action !== 'string' || !args.action.trim() || args.action.length > 512 || /[\p{Cc}\p{Cf}]/u.test(args.action) ||
|
|
123
|
+
skipsAutomaticMemory(args.topic + '\n' + args.action))
|
|
124
|
+
throw new StoreError('invalid_input');
|
|
125
|
+
const evidence = this.experienceSource(agent, generation, args.callId);
|
|
126
|
+
if (!evidence)
|
|
127
|
+
throw new StoreError('invalid_source');
|
|
128
|
+
const { domain, source } = evidence;
|
|
129
|
+
const topic = args.topic.trim();
|
|
130
|
+
const draft = manualItem(domain, { action: args.action, when: '', exceptions: '', paths: [], user_quote: '',
|
|
131
|
+
conflicts_with_repo_guidance: false }, loadedGuidance(agent.session, domain, this.ctx));
|
|
132
|
+
const item = { ...draft, kind: 'fact', usage: 'on_demand', slot: semanticSlot('project', topic), semanticTopic: topic };
|
|
133
|
+
const proposal = this.pending(agent, domain, source, [item]);
|
|
134
|
+
return { status: proposal.state, proposalId: proposal.id };
|
|
135
|
+
}
|
|
136
|
+
sessionLanguages = new WeakMap();
|
|
137
|
+
defaultLanguage = Intl.DateTimeFormat().resolvedOptions().locale.startsWith('zh') ? 'zh' : 'en';
|
|
138
|
+
promptLanguage(agent) {
|
|
139
|
+
const configured = this.config.promptLanguage;
|
|
140
|
+
if (configured === 'en' || configured === 'zh')
|
|
141
|
+
return configured;
|
|
142
|
+
return (agent && this.sessionLanguages.get(agent.session)) ?? this.defaultLanguage;
|
|
143
|
+
}
|
|
144
|
+
// DSH assembles the first request before appending the user message. Cache only bounded terms.
|
|
106
145
|
claimedTasks = new WeakMap();
|
|
107
146
|
captureTask(agent, message, turn) {
|
|
108
147
|
if (message.source?.kind !== 'user')
|
|
109
148
|
return;
|
|
149
|
+
const text = messageText(message).slice(0, 2048);
|
|
150
|
+
if (/\p{Script=Han}/u.test(text))
|
|
151
|
+
this.sessionLanguages.set(agent.session, 'zh');
|
|
152
|
+
else if (/[a-z]{2}/iu.test(text))
|
|
153
|
+
this.sessionLanguages.set(agent.session, 'en');
|
|
110
154
|
const generation = this.assistantGeneration();
|
|
111
155
|
const domain = generation === undefined ? undefined : this.domain(agent);
|
|
112
|
-
if (domain && generation !== undefined)
|
|
113
|
-
|
|
156
|
+
if (domain && generation !== undefined) {
|
|
157
|
+
const terms = taskTerms(text);
|
|
158
|
+
this.claimedTasks.set(agent, { turn, terms, matcher: taskMatcher(terms), domain: domain.id, cwd: domain.cwd, generation });
|
|
159
|
+
}
|
|
114
160
|
}
|
|
115
161
|
personal;
|
|
116
162
|
store;
|
|
@@ -181,8 +227,11 @@ export class ProjectMemory {
|
|
|
181
227
|
if (session.header.origin === 'subagent' || event.seq < session.inheritedEventCount)
|
|
182
228
|
return;
|
|
183
229
|
const chat = event.type === 'user/message' && event.data.source?.kind === 'user';
|
|
184
|
-
if (!chat
|
|
185
|
-
|
|
230
|
+
if (!chat) {
|
|
231
|
+
const form = event.type === 'tool/result' && questionForm(session, event);
|
|
232
|
+
if (!form || (!form.custom.length && !form.selected.length && form.refusedBy === undefined))
|
|
233
|
+
return;
|
|
234
|
+
}
|
|
186
235
|
const owner = this.ctx.agents.get(session.id);
|
|
187
236
|
if (owner?.session !== session || this.ctx.get('sandboxPolicy')?.resolve({ session }).mode === 'read-only')
|
|
188
237
|
return;
|
|
@@ -230,6 +279,41 @@ export class ProjectMemory {
|
|
|
230
279
|
const row = this.store.read(d.id, id, rev);
|
|
231
280
|
return row && this.validity(d, row).ok ? row : undefined;
|
|
232
281
|
}
|
|
282
|
+
turnReceipts(agent, answerSeq) {
|
|
283
|
+
const domain = this.rootDomain(agent);
|
|
284
|
+
const scopes = this.scopes(agent, domain);
|
|
285
|
+
const session = agent.session;
|
|
286
|
+
const events = session.snapshotEvents();
|
|
287
|
+
const answer = events[answerSeq];
|
|
288
|
+
if (answerSeq < session.inheritedEventCount || answer?.seq !== answerSeq ||
|
|
289
|
+
answer.type !== 'assistant/message' || answer.data.message?.role !== 'assistant' ||
|
|
290
|
+
!messageText(answer.data.message).trim())
|
|
291
|
+
throw new StoreError('unavailable');
|
|
292
|
+
const { turn, step } = answer.data;
|
|
293
|
+
if (typeof turn !== 'number' || !Number.isSafeInteger(turn) ||
|
|
294
|
+
typeof step !== 'number' || !Number.isSafeInteger(step))
|
|
295
|
+
throw new StoreError('unavailable');
|
|
296
|
+
// A fork can inherit part of a turn. Only expose requests from turns started in this session.
|
|
297
|
+
let start = answerSeq - 1;
|
|
298
|
+
while (start >= session.inheritedEventCount && events[start].type !== 'turn/start' &&
|
|
299
|
+
events[start].type !== 'turn/end')
|
|
300
|
+
start--;
|
|
301
|
+
if (start < session.inheritedEventCount || events[start].type !== 'turn/start' ||
|
|
302
|
+
events[start].data.turn !== turn)
|
|
303
|
+
throw new StoreError('unavailable');
|
|
304
|
+
const labels = new Map();
|
|
305
|
+
const store = this.storeId(session);
|
|
306
|
+
const writes = proposalReceipts(events.slice(start + 1, answerSeq), turn, domain.id, store, cwd => (resolveDomainCached(this.profile, cwd, this.config.nonGitRoots) ?? this.personal).id === domain.id, code => Object.hasOwn(uiMessages.en, 'turnReceipts.reason.' + code));
|
|
307
|
+
return { ...(writes && { writes }), requests: this.store.turnReceipts(scopes.map(scope => scope.id), session.id, store, String(turn), step, (domainId, ref) => {
|
|
308
|
+
const key = JSON.stringify([domainId, ref.id, ref.rev]);
|
|
309
|
+
if (!labels.has(key)) {
|
|
310
|
+
const scope = scopes.find(scope => scope.id === domainId);
|
|
311
|
+
const rule = scope && this.current(scope, ref.id, ref.rev);
|
|
312
|
+
labels.set(key, rule && !rule.sensitive ? rule.semanticTopic : undefined);
|
|
313
|
+
}
|
|
314
|
+
return labels.get(key);
|
|
315
|
+
}) };
|
|
316
|
+
}
|
|
233
317
|
listConsolidation(agent) {
|
|
234
318
|
const project = this.rootDomain(agent);
|
|
235
319
|
if (project.id === this.personal.id)
|
|
@@ -248,7 +332,7 @@ export class ProjectMemory {
|
|
|
248
332
|
this.store.consolidation.decide(project.id, left, right, keep, agent.id);
|
|
249
333
|
notifyUI(this.ctx, agent.id);
|
|
250
334
|
}
|
|
251
|
-
async search(agent, query, mode, options = {}, trace = newSearchTrace()) {
|
|
335
|
+
async search(agent, query, mode, options = {}, trace = newSearchTrace(), review) {
|
|
252
336
|
if (typeof query !== 'string' || query.length > 2048 ||
|
|
253
337
|
(mode !== undefined && !['hybrid', 'keyword', 'semantic'].includes(mode)) ||
|
|
254
338
|
(options.scope !== undefined && !['project', 'profile'].includes(options.scope)) ||
|
|
@@ -261,35 +345,49 @@ export class ProjectMemory {
|
|
|
261
345
|
return [];
|
|
262
346
|
const scopes = this.scopes(agent, d).filter(s => !options.scope ||
|
|
263
347
|
(s.id === this.personal.id ? 'profile' : 'project') === options.scope);
|
|
264
|
-
const collect = (visibleScopes, candidates) => {
|
|
348
|
+
const collect = (visibleScopes, candidates, projection = 'ranking') => {
|
|
265
349
|
const anchors = new Map();
|
|
266
350
|
return visibleScopes.flatMap(scope => {
|
|
267
351
|
const refs = candidates?.filter(ref => ref.domain === scope.id);
|
|
268
352
|
const start = performance.now();
|
|
269
|
-
const rows =
|
|
353
|
+
const rows = projection === 'source' ? this.store.readMany(scope.id, refs) :
|
|
354
|
+
this.store.searchHeads(scope.id, refs, projection === 'review');
|
|
270
355
|
trace.sqliteMs += performance.now() - start;
|
|
271
356
|
return rows.filter(rule => this.validity(scope, rule, anchors).ok).map(rule => ({ rule, domain: scope.id }));
|
|
272
357
|
});
|
|
273
358
|
};
|
|
274
359
|
const q = normalizeLabel(query);
|
|
275
360
|
const exact = exactMemoryId.exec(q);
|
|
361
|
+
const domains = scopes.map(scope => scope.id);
|
|
362
|
+
const topicRefs = (visible) => visible.flatMap(scope => this.store.topicRefs(scope.id, options.topic, options.subject));
|
|
363
|
+
const identities = !exact && !mode && options.topic ? collect(scopes, topicRefs(scopes)) : [];
|
|
364
|
+
const structured = identities.length > 1 || (identities.length === 1 && !!options.subject);
|
|
365
|
+
const lexicalOnly = mode !== 'semantic' && !this.retrieval.vectors.languages.length;
|
|
276
366
|
const keywordStart = performance.now();
|
|
277
|
-
const keywordHits = !exact && mode === 'keyword' && (q || options.topic)
|
|
278
|
-
? this.retrieval.keywordHits(
|
|
367
|
+
const keywordHits = !exact && !structured && (mode === 'keyword' || lexicalOnly || review) && (q || options.topic)
|
|
368
|
+
? this.retrieval.keywordHits(domains, query, options)
|
|
279
369
|
: undefined;
|
|
280
370
|
if (keywordHits)
|
|
281
371
|
trace.sqliteMs += performance.now() - keywordStart;
|
|
282
372
|
const candidates = exact
|
|
283
|
-
?
|
|
284
|
-
: keywordHits;
|
|
285
|
-
|
|
286
|
-
//
|
|
287
|
-
//
|
|
288
|
-
|
|
373
|
+
? domains.map(domain => ({ domain, id: exact[1], rev: exact[2] ? Number(exact[2]) : undefined }))
|
|
374
|
+
: review && keywordHits ? this.retrieval.reviewRefs(domains, query, options, keywordHits) : keywordHits;
|
|
375
|
+
let initial = structured ? identities : collect(scopes, candidates, review ? 'review' : 'ranking');
|
|
376
|
+
// With no embedding models, only FTS matches can score. A negative lookup must
|
|
377
|
+
// still distinguish an empty eligible scope from a scope with unrelated records.
|
|
378
|
+
const subject = normalizeLabel(options.subject ?? '');
|
|
379
|
+
const checkScope = !review && !exact && !structured && mode !== 'keyword' && lexicalOnly && keywordHits &&
|
|
380
|
+
!initial.some(({ rule }) => !subject || !rule.subject || normalizeLabel(rule.subject) === subject);
|
|
381
|
+
if (checkScope)
|
|
382
|
+
initial = collect(scopes, undefined);
|
|
383
|
+
if (scopes.length && (candidates === undefined || checkScope) && !initial.length) {
|
|
289
384
|
trace.match = 'empty_scope';
|
|
290
385
|
return [];
|
|
291
386
|
}
|
|
292
|
-
|
|
387
|
+
// Preserve the ambiguity decision across all identities before narrowing foreground
|
|
388
|
+
// review candidates. A keyword alias can belong to a different subject or protected fact.
|
|
389
|
+
const inputs = review && !structured ? initial.filter(({ rule }) => review.accept(rule)) : initial;
|
|
390
|
+
const ranked = await this.retrieval.search(inputs, query, mode, options, trace, keywordHits);
|
|
293
391
|
const active = this.domain(agent);
|
|
294
392
|
if (!active || this.ctx.agents.get(agent.id) !== agent || active.id !== d.id ||
|
|
295
393
|
active.root !== d.root || active.cwd !== d.cwd)
|
|
@@ -297,33 +395,57 @@ export class ProjectMemory {
|
|
|
297
395
|
// Re-read returned revisions, permissions and their filesystem evidence after ranking.
|
|
298
396
|
// A unique exact-topic hit also needs to notice a concurrent insertion.
|
|
299
397
|
const visibleIds = new Set(this.scopes(agent, active).map(s => s.id));
|
|
300
|
-
const
|
|
301
|
-
const refs = trace.match === 'exact_topic' ? undefined : initial.flatMap(({ domain, rule }) => hits.get(rule.id) === rule.rev ? [{ domain, id: rule.id, rev: rule.rev }] : []);
|
|
302
|
-
const rows = collect(scopes.filter(scope => visibleIds.has(scope.id)), refs);
|
|
398
|
+
const visible = scopes.filter(scope => visibleIds.has(scope.id));
|
|
303
399
|
if (trace.match === 'exact_topic') {
|
|
304
|
-
const exact =
|
|
400
|
+
const exact = collect(visible, topicRefs(visible), 'source').map(row => row.rule);
|
|
305
401
|
if (exact.length > 1) {
|
|
306
402
|
trace.match = 'ambiguous';
|
|
307
|
-
return exact.
|
|
403
|
+
return review ? exact.filter(review.accept).slice(0, review.limit) : exact;
|
|
404
|
+
}
|
|
405
|
+
return exact.filter(row => row.id === ranked[0]?.id && row.rev === ranked[0]?.rev && (!review || review.accept(row)));
|
|
406
|
+
}
|
|
407
|
+
const result = [];
|
|
408
|
+
const accepted = review ? ranked.filter(review.accept) : ranked;
|
|
409
|
+
const batchSize = review ? review.limit : Math.max(1, accepted.length);
|
|
410
|
+
for (let i = 0; i < accepted.length; i += batchSize) {
|
|
411
|
+
const batch = accepted.slice(i, i + batchSize);
|
|
412
|
+
const refs = batch.map(rule => ({ domain: rule.domainId, id: rule.id, rev: rule.rev }));
|
|
413
|
+
const current = new Map(collect(visible, refs, 'source').map(({ rule }) => [rule.id, rule]));
|
|
414
|
+
for (const hit of batch) {
|
|
415
|
+
const row = current.get(hit.id);
|
|
416
|
+
if (row?.rev === hit.rev)
|
|
417
|
+
result.push(row);
|
|
418
|
+
if (review && result.length === review.limit)
|
|
419
|
+
return result;
|
|
308
420
|
}
|
|
309
421
|
}
|
|
310
|
-
const visible = new Map(rows.map(r => [r.rule.id, r.rule]));
|
|
311
|
-
const result = ranked.flatMap(hit => {
|
|
312
|
-
const current = visible.get(hit.id);
|
|
313
|
-
return current?.rev === hit.rev ? [current] : [];
|
|
314
|
-
});
|
|
315
422
|
return ranked.degraded ? Object.assign(result, { degraded: true }) : result;
|
|
316
423
|
}
|
|
317
|
-
async manage(agent, op, args) {
|
|
424
|
+
async manage(agent, op, args, check, page) {
|
|
318
425
|
const write = ['revise', 'usage', 'forget', 'undo', 'pin', 'unpin', 'clear-quote'].includes(op);
|
|
319
426
|
const d = this.rootDomain(agent, write);
|
|
320
427
|
if (op === 'list') {
|
|
321
|
-
const view = this.view(agent);
|
|
322
|
-
|
|
428
|
+
const view = this.view(agent, args.scope, check);
|
|
429
|
+
const total = view.rules.length + view.needs_review.length;
|
|
430
|
+
const rules = page ? view.rules.slice(page.offset, page.offset + page.limit) : view.rules;
|
|
431
|
+
const invalid = page ? view.needs_review.slice(Math.max(0, page.offset - view.rules.length), Math.max(0, page.offset + page.limit - view.rules.length)) : view.needs_review;
|
|
432
|
+
const annotate = this.managerUsage(this.scopes(agent, d).filter(scope => !args.scope ||
|
|
433
|
+
(scope.id === this.personal.id ? 'profile' : 'project') === args.scope), page ? [...rules, ...invalid] : undefined);
|
|
434
|
+
return { ...view, rules: rules.map(annotate),
|
|
435
|
+
...(page && { total, choices: view.proposals.some(card => card.state === 'pending' && !card.source.fileImport) ? view.rules : [] }),
|
|
436
|
+
needs_review: this.managerStatus(invalid, '', args.locale).needs_review.map(annotate) };
|
|
323
437
|
}
|
|
324
438
|
if (op === 'search')
|
|
325
|
-
return this.searchManagedRules(agent, d, args.query, args.mode, args.scope);
|
|
439
|
+
return this.searchManagedRules(agent, d, args.query, args.mode, args.scope, args.locale);
|
|
326
440
|
const { owner, ref } = this.resolveManagedRef(agent, d, args);
|
|
441
|
+
if (args.sourceRev !== undefined) {
|
|
442
|
+
if (op !== 'source' || !Number.isSafeInteger(args.sourceRev) || Number(args.sourceRev) < 1)
|
|
443
|
+
throw new StoreError('invalid_item');
|
|
444
|
+
if (owner.id !== this.personal.id || Number(args.sourceRev) >= ref.rev)
|
|
445
|
+
return { status: 'not_found' };
|
|
446
|
+
}
|
|
447
|
+
if (op === 'source' && owner.id === this.personal.id)
|
|
448
|
+
return this.profileManagerSource(agent, ref, args.sourceRev);
|
|
327
449
|
if (op === 'read' || op === 'source')
|
|
328
450
|
return this.readManagedRule(agent, owner, ref, op === 'source');
|
|
329
451
|
if (!write)
|
|
@@ -369,11 +491,11 @@ export class ProjectMemory {
|
|
|
369
491
|
throw new StoreError('expected_revision');
|
|
370
492
|
const ref = { id: args.id, rev: Number(args.rev) };
|
|
371
493
|
const owner = this.owner(agent, domain, ref.id);
|
|
372
|
-
if (!owner)
|
|
494
|
+
if (!owner || (args.scope && args.scope !== (owner.id === this.personal.id ? 'profile' : 'project')))
|
|
373
495
|
throw new StoreError('not_found');
|
|
374
496
|
return { owner, ref };
|
|
375
497
|
}
|
|
376
|
-
async searchManagedRules(agent, d, query, mode, filter) {
|
|
498
|
+
async searchManagedRules(agent, d, query, mode, filter, locale) {
|
|
377
499
|
const rules = await this.search(agent, query, mode, { scope: filter });
|
|
378
500
|
const live = this.rootDomain(agent);
|
|
379
501
|
if (d.id !== live.id || d.root !== live.root || d.cwd !== live.cwd)
|
|
@@ -401,10 +523,16 @@ export class ProjectMemory {
|
|
|
401
523
|
const indexed = [...current.values()].some(row => row.usage === 'proactive' && !isKnowledge(row))
|
|
402
524
|
? this.index(agent, live, true).included : [];
|
|
403
525
|
const delivered = current.size ? scopes.flatMap(scope => this.store.delivered(scope.id, agent.id)) : [];
|
|
526
|
+
const annotate = this.managerUsage(scopes);
|
|
404
527
|
return { rules: rules.flatMap(hit => {
|
|
405
528
|
const rule = current.get(hit.id);
|
|
406
529
|
return rule ? [managerRule(rule, indexed.some(ref => ref.id === rule.id && ref.rev === rule.rev), delivered.some(ref => ref.id === rule.id && ref.rev === rule.rev))] : [];
|
|
407
|
-
}),
|
|
530
|
+
}).map(annotate), needs_review: this.managerStatus(withheld, query, locale).needs_review.map(annotate) };
|
|
531
|
+
}
|
|
532
|
+
managerUsage(scopes, page) {
|
|
533
|
+
const refs = page?.map(({ id, rev }) => ({ id, rev }));
|
|
534
|
+
const usage = new Map(scopes.flatMap(scope => this.store.usageSignals(scope.id, refs).map(({ id, rev, ...counts }) => [(scope.id === this.personal.id ? 'profile/' : 'project/') + id + '@' + rev, counts])));
|
|
535
|
+
return (row) => ({ ...row, usageSignals: usage.get(`${row.scope}/${row.id}@${row.rev}`) });
|
|
408
536
|
}
|
|
409
537
|
async readManagedRule(agent, owner, { id, rev }, expand) {
|
|
410
538
|
const result = await this.read(agent, id, rev, expand);
|
|
@@ -413,11 +541,49 @@ export class ProjectMemory {
|
|
|
413
541
|
const live = this.rootDomain(agent);
|
|
414
542
|
const scope = this.scopes(agent, live).find(s => s.id === owner.id);
|
|
415
543
|
const head = scope && this.current(scope, id, rev);
|
|
416
|
-
if (!head || (
|
|
544
|
+
if (!head || !this.canPublishEvidence(head, result))
|
|
417
545
|
return { status: 'not_found' };
|
|
418
546
|
return 'quote' in result
|
|
419
547
|
? { ...result, hasRetainedQuote: this.store.maintenance.hasRetainedQuote(owner.id, id) } : result;
|
|
420
548
|
}
|
|
549
|
+
*profileSourceHistory(head) {
|
|
550
|
+
for (const version of this.store.previousVersions(this.personal.id, head.id, head.rev)) {
|
|
551
|
+
if (version.quoteType === 'user_quote' && version.user_quote && this.validity(this.personal, version).ok)
|
|
552
|
+
yield version;
|
|
553
|
+
}
|
|
554
|
+
}
|
|
555
|
+
async profileManagerSource(agent, head, sourceRev) {
|
|
556
|
+
const select = () => {
|
|
557
|
+
const scope = this.rootDomain(agent);
|
|
558
|
+
if (!this.scopes(agent, scope).some(d => d.id === this.personal.id))
|
|
559
|
+
return;
|
|
560
|
+
const current = this.current(this.personal, head.id, head.rev);
|
|
561
|
+
if (sourceRev === undefined || !current)
|
|
562
|
+
return current;
|
|
563
|
+
for (const version of this.profileSourceHistory(head)) {
|
|
564
|
+
if (version.rev === sourceRev)
|
|
565
|
+
return version;
|
|
566
|
+
if (version.rev < sourceRev)
|
|
567
|
+
break;
|
|
568
|
+
}
|
|
569
|
+
};
|
|
570
|
+
const record = select();
|
|
571
|
+
if (!record)
|
|
572
|
+
return { status: 'not_found' };
|
|
573
|
+
const verified = await this.verifyQuote(this.personal, record);
|
|
574
|
+
// The chat read can outlive a clear-quote, a revision, access loss or history expiry.
|
|
575
|
+
const live = select();
|
|
576
|
+
if (!live)
|
|
577
|
+
return { status: 'not_found' };
|
|
578
|
+
const result = this.sourceEvidence(this.personal, live, verified && this.sameQuoteSource(record, live));
|
|
579
|
+
if (sourceRev !== undefined)
|
|
580
|
+
return result;
|
|
581
|
+
return { ...result, hasRetainedQuote: this.store.maintenance.hasRetainedQuote(this.personal.id, head.id),
|
|
582
|
+
...(live.rev > 1 && live.quoteType === 'receipt' && live.source.origin === 'manual' &&
|
|
583
|
+
(live.channel === 'owner_card' || live.channel === 'user_command') && { manualEdit: true }),
|
|
584
|
+
sourceRevisions: Array.from(this.profileSourceHistory(head), version => version.rev),
|
|
585
|
+
};
|
|
586
|
+
}
|
|
421
587
|
recordEdit(agent, { id, rev }) {
|
|
422
588
|
const seq = this.append(agent.session, 'plugin:project-memory/edit', { id, rev });
|
|
423
589
|
return {
|
|
@@ -448,7 +614,7 @@ export class ProjectMemory {
|
|
|
448
614
|
if (branch)
|
|
449
615
|
item.hard = { ...item.hard, branch };
|
|
450
616
|
if (!validateRule(owner, item).ok) {
|
|
451
|
-
const p = this.pending(agent, owner, source, [item]);
|
|
617
|
+
const p = this.pending(agent, owner, source, [item], 'settings');
|
|
452
618
|
return { status: 'pending', proposal_id: p.id };
|
|
453
619
|
}
|
|
454
620
|
}
|
|
@@ -493,38 +659,79 @@ export class ProjectMemory {
|
|
|
493
659
|
for (const id of old) {
|
|
494
660
|
const expanded = lookups.some((e) => e.data.refs?.some((r) => r.id === id) && results.get(e.data.callId)?.includes(id));
|
|
495
661
|
if (expanded ||
|
|
496
|
-
sections.some((section) => section.text.includes(id + '@') || section.text.includes('[' + id + ']
|
|
662
|
+
sections.some((section) => section.text.includes(id + '@') || [prompts.en, prompts.zh].some(copy => section.text.includes('[' + id + '] ' + copy.withdrawn))))
|
|
497
663
|
withdrawn.add(id);
|
|
498
664
|
}
|
|
499
665
|
}
|
|
500
666
|
}
|
|
501
667
|
return [...withdrawn].sort();
|
|
502
668
|
}
|
|
669
|
+
// A single recent plan bounds retention across projects. Only prompt callers
|
|
670
|
+
// can use it: callers requesting the entire overflow need every eligibility check.
|
|
671
|
+
recentPrompt;
|
|
503
672
|
index(agent, d, promptOnly = false) {
|
|
504
673
|
const generation = this.assistantGeneration();
|
|
505
|
-
if (generation === undefined)
|
|
674
|
+
if (generation === undefined) {
|
|
675
|
+
this.recentPrompt = undefined;
|
|
506
676
|
return buildIndex([], []);
|
|
677
|
+
}
|
|
507
678
|
const scopes = this.scopes(agent, d);
|
|
508
|
-
const
|
|
509
|
-
|
|
510
|
-
|
|
511
|
-
|
|
679
|
+
const claimed = this.claimedTasks.get(agent);
|
|
680
|
+
let task;
|
|
681
|
+
if (claimed && claimed.domain === d.id && claimed.cwd === d.cwd && claimed.generation === generation) {
|
|
682
|
+
const boundary = agent.session.snapshotEvents().findLast(event => event.type === 'turn/start' || event.type === 'turn/end' || event.type === 'working-directory/change');
|
|
683
|
+
if (boundary?.type === 'turn/start' && claimed.turn === boundary.data.turn)
|
|
684
|
+
task = claimed;
|
|
685
|
+
}
|
|
686
|
+
const onDemand = [];
|
|
687
|
+
for (const scope of scopes) {
|
|
688
|
+
if (promptOnly && task?.terms.length && this.config.overflowHints !== false) {
|
|
689
|
+
// Check repository conditions on a bounded lexical shortlist before offering a pointer.
|
|
690
|
+
for (const row of this.store.onDemandCandidates(scope.id, task.terms)) {
|
|
691
|
+
if (this.validity(scope, row).ok)
|
|
692
|
+
onDemand.push(row);
|
|
693
|
+
}
|
|
694
|
+
}
|
|
695
|
+
if (promptOnly && onDemand.length)
|
|
696
|
+
continue;
|
|
512
697
|
for (const rule of this.store.onDemandHeads(scope.id)) {
|
|
513
698
|
if (!this.validity(scope, rule).ok)
|
|
514
699
|
continue;
|
|
515
|
-
|
|
700
|
+
onDemand.push(rule);
|
|
516
701
|
if (promptOnly)
|
|
517
|
-
break
|
|
702
|
+
break;
|
|
518
703
|
}
|
|
519
704
|
}
|
|
520
|
-
|
|
521
|
-
|
|
522
|
-
|
|
523
|
-
|
|
524
|
-
|
|
525
|
-
|
|
526
|
-
|
|
527
|
-
|
|
705
|
+
const withdrawn = scopes.flatMap(scope => this.withdrawn(agent, scope));
|
|
706
|
+
const language = this.promptLanguage(agent);
|
|
707
|
+
const eligible = (rule) => this.validity(rule.domainId === this.personal.id ? this.personal : d, rule).ok;
|
|
708
|
+
const build = (active, recheck) => buildIndex([...active, ...onDemand], withdrawn, this.config, () => task?.matcher, language, recheck);
|
|
709
|
+
const limits = indexLimits(this.config);
|
|
710
|
+
const key = promptOnly && JSON.stringify([generation, language, limits, task?.terms, withdrawn,
|
|
711
|
+
scopes.map(scope => [scope.id, scope.root, scope.cwd, scope.machine, this.store.epoch(scope.id)]),
|
|
712
|
+
onDemand.map(row => [row.id, row.rev])]);
|
|
713
|
+
const cached = this.recentPrompt;
|
|
714
|
+
if (cached && cached.key === key && cached.recheck.every(eligible))
|
|
715
|
+
return cached.result;
|
|
716
|
+
if (promptOnly)
|
|
717
|
+
this.recentPrompt = undefined;
|
|
718
|
+
const active = scopes.flatMap(scope => this.store.indexHeads(scope.id));
|
|
719
|
+
if (key && active.length > limits.maxRows) {
|
|
720
|
+
const recheck = new Set();
|
|
721
|
+
const { text, included } = build(active, recheck);
|
|
722
|
+
for (const row of included)
|
|
723
|
+
recheck.add(row);
|
|
724
|
+
// Omitted singletons cannot displace a selected group. buildIndex also
|
|
725
|
+
// identifies variants, budget witnesses and hints that can affect ranking.
|
|
726
|
+
// Always check their *current* filesystem, branch and environment scope.
|
|
727
|
+
const required = [...recheck];
|
|
728
|
+
if (required.every(eligible)) {
|
|
729
|
+
const result = { text, included };
|
|
730
|
+
this.recentPrompt = { key, recheck: required, result };
|
|
731
|
+
return result;
|
|
732
|
+
}
|
|
733
|
+
}
|
|
734
|
+
return build(active.filter(eligible));
|
|
528
735
|
}
|
|
529
736
|
/** The nearest earlier version of an automatic save that may be put back. */
|
|
530
737
|
restorable(d, rule) {
|
|
@@ -547,8 +754,7 @@ export class ProjectMemory {
|
|
|
547
754
|
}
|
|
548
755
|
}
|
|
549
756
|
pending(root, d, source, items, turnId) {
|
|
550
|
-
const
|
|
551
|
-
const novel = items.filter((item) => !current.some((rule) => sameRule(item, rule)));
|
|
757
|
+
const novel = items.filter(item => !this.store.comparisonHeads(d.id, 'action', item.action).some(rule => sameRule(item, rule)));
|
|
552
758
|
if (!novel.length)
|
|
553
759
|
throw new StoreError('duplicate');
|
|
554
760
|
const p = this.store.propose(d.id, root.id, source, novel, turnId);
|
|
@@ -561,17 +767,20 @@ export class ProjectMemory {
|
|
|
561
767
|
});
|
|
562
768
|
return p;
|
|
563
769
|
}
|
|
564
|
-
projectConflict(
|
|
770
|
+
projectConflict(domain, item) {
|
|
771
|
+
// A conflict requires the same condition. For an empty condition it also requires the same slot.
|
|
772
|
+
const candidates = item.when ? this.store.comparisonHeads(domain, 'condition', item.when)
|
|
773
|
+
: item.slot ? this.store.comparisonHeads(domain, 'slot', item.slot) : [];
|
|
774
|
+
const current = candidates.filter(rule => !isKnowledge(rule));
|
|
565
775
|
return relatedRules(item, current).some(rule => !sameRule(item, rule) &&
|
|
566
776
|
rule.when === item.when && JSON.stringify(rule.paths) === JSON.stringify(item.paths) &&
|
|
567
777
|
((rule.slot && rule.slot === item.slot) || Boolean(item.when)));
|
|
568
778
|
}
|
|
569
779
|
saveOrReview(root, d, source, items, retry = true) {
|
|
570
780
|
const epoch = this.store.epoch(d.id);
|
|
571
|
-
const current = this.store.list(d.id).filter((r) => !isKnowledge(r));
|
|
572
781
|
const pending = [], ready = [];
|
|
573
782
|
for (const item of items) {
|
|
574
|
-
const conflict = this.projectConflict(
|
|
783
|
+
const conflict = this.projectConflict(d.id, item);
|
|
575
784
|
if (conflict || item.conflicts_with_repo_guidance || needsHumanReview(item) || !validateRule(d, item).ok)
|
|
576
785
|
pending.push(item);
|
|
577
786
|
else
|
|
@@ -592,7 +801,7 @@ export class ProjectMemory {
|
|
|
592
801
|
}
|
|
593
802
|
return { status: saved?.state ?? 'skipped', entries: saved?.entries ?? [] };
|
|
594
803
|
}
|
|
595
|
-
|
|
804
|
+
proposalContext(agent) {
|
|
596
805
|
const d = this.domain(agent);
|
|
597
806
|
if (!d)
|
|
598
807
|
throw new StoreError('unavailable');
|
|
@@ -615,38 +824,101 @@ export class ProjectMemory {
|
|
|
615
824
|
if (agent !== root &&
|
|
616
825
|
this.ctx.get('sandboxPolicy')?.resolve({ session: agent.session }).mode === 'read-only')
|
|
617
826
|
throw new StoreError('read_only');
|
|
618
|
-
return
|
|
827
|
+
return { root, domain: d, turnId: latestTurn(root.session) };
|
|
828
|
+
}
|
|
829
|
+
propose(agent, input, inputSlots, selections) {
|
|
830
|
+
const { root, domain, turnId } = this.proposalContext(agent);
|
|
831
|
+
return this.applyProposals(root, agent, domain, turnId, input, { inputSlots, selections });
|
|
832
|
+
}
|
|
833
|
+
narrowToProject(agent, ref, clarification, generation, epochs, candidate) {
|
|
834
|
+
const project = this.rootDomain(agent, true);
|
|
835
|
+
if (project.id === this.personal.id || candidate.scope !== 'project')
|
|
836
|
+
throw new StoreError('invalid_scope');
|
|
837
|
+
if (this.store.enabledGeneration() !== generation)
|
|
838
|
+
throw new StoreError('memory_disabled');
|
|
839
|
+
const turnId = latestTurn(agent.session);
|
|
840
|
+
const current = this.proposalSources(agent, agent, project, turnId, generation);
|
|
841
|
+
if (current.reason)
|
|
842
|
+
throw new StoreError(current.reason);
|
|
843
|
+
if (typeof clarification !== 'string' || !clarification.trim() || clarification.length > 480 ||
|
|
844
|
+
skipsAutomaticMemory(clarification))
|
|
845
|
+
throw new StoreError('invalid_source');
|
|
846
|
+
const excerpts = current.events.filter(block => !block.question && block.text.includes(clarification));
|
|
847
|
+
const block = excerpts[0];
|
|
848
|
+
if (excerpts.length !== 1 || block.text.indexOf(clarification) !== block.text.lastIndexOf(clarification))
|
|
849
|
+
throw new StoreError('invalid_source');
|
|
850
|
+
const start = (block.offset ?? 0) + block.text.indexOf(clarification);
|
|
851
|
+
const span = { seq: block.seq, start, end: start + clarification.length };
|
|
852
|
+
const source = { storeId: block.storeId, sessionId: agent.id, turnId, seq: block.seq,
|
|
853
|
+
time: current.records.get(block.seq)?.time, origin: 'user' };
|
|
854
|
+
const result = this.store.narrowToProject(project.id, ref, source, clarification, span, generation, epochs, old => {
|
|
855
|
+
previousScopeAgreement(this, agent, project, ref, generation, turnId);
|
|
856
|
+
// A scope correction cannot edit the original claim or implicitly enable proactive delivery.
|
|
857
|
+
if (candidate.kind !== old.kind || candidate.subject !== old.subject || candidate.topic !== old.semanticTopic ||
|
|
858
|
+
candidate.usage !== old.usage || candidate.sensitive || candidate.replaces || skipsCandidate(candidate) ||
|
|
859
|
+
!isDeepStrictEqual(ruleFields(candidate), ruleFields(old)))
|
|
860
|
+
throw new StoreError('target_mismatch');
|
|
861
|
+
const item = manualItem(project, ruleFields(old), loadedGuidance(agent.session, project, this.ctx));
|
|
862
|
+
const validity = validateRule(project, item);
|
|
863
|
+
if (!validity.ok || needsHumanReview(item))
|
|
864
|
+
throw new StoreError(validity.reason ?? 'needs_review');
|
|
865
|
+
const existing = this.store.comparisonHeads(project.id, 'action', item.action);
|
|
866
|
+
if (existing.some(rule => !isKnowledge(rule) && sameRule(item, rule)) || this.projectConflict(project.id, item))
|
|
867
|
+
throw new StoreError('conflict');
|
|
868
|
+
return { guidance: item.guidance, hard: item.hard };
|
|
869
|
+
});
|
|
870
|
+
if (result.status === 'duplicate' && !this.current(project, result.entries[0].id, result.entries[0].rev))
|
|
871
|
+
throw new StoreError('source_unavailable');
|
|
872
|
+
if (result.status === 'saved')
|
|
873
|
+
notifyUI(this.ctx, agent.id);
|
|
874
|
+
return result;
|
|
619
875
|
}
|
|
620
876
|
/** A background decision is bound to the original turn, even if a new one has started. */
|
|
621
|
-
proposeFromTurn(root, turnId, input, reviewEpochs) {
|
|
877
|
+
proposeFromTurn(root, turnId, input, reviewEpochs, selections) {
|
|
622
878
|
const domain = this.rootDomain(root, true);
|
|
623
|
-
return this.applyProposals(root, root, domain, turnId, input, true, reviewEpochs);
|
|
879
|
+
return this.applyProposals(root, root, domain, turnId, input, { background: true, reviewEpochs, selections });
|
|
624
880
|
}
|
|
625
|
-
|
|
626
|
-
const rows = candidateRows(input);
|
|
627
|
-
const skipAll = (reason) => ({
|
|
628
|
-
status: 'skipped', entries: [], results: rows.map((_, index) => ({ index, status: 'skipped', reason })),
|
|
629
|
-
});
|
|
630
|
-
const generation = this.store.enabledGeneration();
|
|
631
|
-
if (generation === undefined)
|
|
632
|
-
return skipAll('memory_disabled');
|
|
633
|
-
const storeId = this.storeId(root.session);
|
|
634
|
-
const blocks = sources(root.session, d, storeId, turnId);
|
|
881
|
+
proposalSources(root, agent, domain, turnId, generation) {
|
|
635
882
|
const records = new Map(root.session.snapshotEvents().map(event => [event.seq, event]));
|
|
883
|
+
if (generation === undefined)
|
|
884
|
+
return { events: [], records, reason: 'memory_disabled' };
|
|
885
|
+
const blocks = sources(root.session, domain, this.storeId(root.session), turnId);
|
|
636
886
|
if (blocks.some(block => block.refused || refusesAutomaticMemory(block.text) ||
|
|
637
887
|
refusesAutomaticMemory(messageText(records.get(block.seq)?.data))))
|
|
638
|
-
return
|
|
888
|
+
return { events: [], records, reason: 'opted_out' };
|
|
639
889
|
const authorized = blocks.filter(block => block.memoryGeneration === generation);
|
|
640
890
|
if (blocks.length && !authorized.length)
|
|
641
|
-
return
|
|
891
|
+
return { events: [], records, reason: 'source_unavailable' };
|
|
642
892
|
const events = authorized.filter(block => (root === agent || !block.question) && !skipsAutomaticMemory(block.text) &&
|
|
643
893
|
!skipsAutomaticMemory(messageText(records.get(block.seq)?.data)));
|
|
894
|
+
return { events: agent === root ? events : events.map(({ formSelections, ...block }) => block), records };
|
|
895
|
+
}
|
|
896
|
+
applyProposals(root, agent, d, turnId, input, options) {
|
|
897
|
+
const { background = false, reviewEpochs, inputSlots, selections } = options;
|
|
898
|
+
const rows = candidateRows(input);
|
|
899
|
+
if (inputSlots && (inputSlots.length !== rows.length || !inputSlots.every(isSemanticSlot)))
|
|
900
|
+
throw new StoreError('invalid_input');
|
|
901
|
+
const skipAll = (reason) => ({
|
|
902
|
+
status: 'skipped', entries: [], results: rows.map((_, index) => ({ index, status: 'skipped', reason })),
|
|
903
|
+
});
|
|
904
|
+
const generation = this.store.enabledGeneration();
|
|
905
|
+
const { events, records, reason } = this.proposalSources(root, agent, d, turnId, generation);
|
|
906
|
+
if (reason || generation === undefined)
|
|
907
|
+
return skipAll(reason ?? 'memory_disabled');
|
|
908
|
+
const storeId = this.storeId(root.session);
|
|
644
909
|
const groups = new Map();
|
|
910
|
+
const claimSlots = new Map();
|
|
911
|
+
const ambiguousSlots = new Set();
|
|
645
912
|
const outcomes = [];
|
|
646
913
|
const guidance = loadedGuidance(root.session, d, this.ctx);
|
|
647
914
|
for (const [index, raw] of rows.entries()) {
|
|
648
915
|
try {
|
|
649
916
|
const row = parseCandidate(raw);
|
|
917
|
+
// The reviewer can resolve a submitted label to a different canonical label.
|
|
918
|
+
// Bind the original claim as well, for source replay protection after withdrawal.
|
|
919
|
+
const inputSlot = inputSlots?.[index] ?? semanticSlot(row.scope, row.topic, row.subject);
|
|
920
|
+
if ((row.scope === 'global') !== isPersonalSlot(inputSlot))
|
|
921
|
+
throw new StoreError('invalid_scope');
|
|
650
922
|
if ((row.scope === 'project' && d.id === this.personal.id) ||
|
|
651
923
|
(row.scope === 'global' && (root !== agent || row.paths.length))) {
|
|
652
924
|
outcomes[index] = { status: 'skipped', reason: 'invalid_scope' };
|
|
@@ -658,20 +930,52 @@ export class ProjectMemory {
|
|
|
658
930
|
}
|
|
659
931
|
const [prepared] = prepareItems(d, { items: [ruleFields(row)] }, events, row.scope === 'project' ? guidance : []);
|
|
660
932
|
const seq = prepared.evidence.seq;
|
|
933
|
+
const selection = selections?.[index];
|
|
934
|
+
if (selection) {
|
|
935
|
+
const eligible = root === agent && row.kind !== 'fact' &&
|
|
936
|
+
row.user_quote.includes(selection.directive) && standingRequest(selection.directive) &&
|
|
937
|
+
selectedAction(selection.directive, selection.option.label) === row.action &&
|
|
938
|
+
events.some(e => e.seq === seq && e.block === prepared.source?.block &&
|
|
939
|
+
e.formSelections?.some(option => isDeepStrictEqual(option, selection.option)));
|
|
940
|
+
if (!eligible)
|
|
941
|
+
throw new StoreError('invalid_source');
|
|
942
|
+
prepared.source = { ...prepared.source, formSelection: selection.option };
|
|
943
|
+
}
|
|
661
944
|
const source = { storeId, sessionId: root.id, turnId, seq, time: records.get(seq)?.time, origin: 'user' };
|
|
662
945
|
const owner = row.scope === 'global' ? this.personal : d;
|
|
663
|
-
const
|
|
664
|
-
|
|
946
|
+
const referenced = row.replaces ? this.store.read(owner.id, row.replaces.id) : undefined;
|
|
947
|
+
if (row.replaces) {
|
|
948
|
+
if (!referenced) {
|
|
949
|
+
outcomes[index] = { status: 'skipped', reason: 'target_not_found' };
|
|
950
|
+
continue;
|
|
951
|
+
}
|
|
952
|
+
const mismatch = targetMismatch(row, referenced);
|
|
953
|
+
if (mismatch) {
|
|
954
|
+
outcomes[index] = { status: 'skipped', reason: mismatch };
|
|
955
|
+
continue;
|
|
956
|
+
}
|
|
957
|
+
row.subject ??= referenced.subject;
|
|
958
|
+
if (referenced.rev !== row.replaces.rev) {
|
|
959
|
+
const receipt = this.store.replayedReplacement(owner.id, row.replaces, source, semanticDraft(row, prepared, referenced));
|
|
960
|
+
outcomes[index] = receipt ? { status: 'duplicate', ...receipt } : { status: 'skipped', reason: 'stale_revision' };
|
|
961
|
+
continue;
|
|
962
|
+
}
|
|
963
|
+
}
|
|
964
|
+
const canonical = referenced?.semanticTopic ?? row.topic;
|
|
965
|
+
const matches = this.store.canonicalTopicHeads(owner.id, row.scope, canonical, row.subject);
|
|
665
966
|
const family = semanticSlot(row.scope, canonical, row.subject);
|
|
666
|
-
const referenced = row.replaces && matches.find(head => head.id === row.replaces.id);
|
|
667
967
|
const context = matches.find(head => head.when === prepared.when && isDeepStrictEqual(head.paths, prepared.paths));
|
|
668
968
|
const observed = referenced || context;
|
|
669
969
|
const slot = observed && isSemanticSlot(observed.slot) ? observed.slot : semanticSlot(row.scope, canonical, row.subject, prepared);
|
|
970
|
+
const claim = inputClaimKey(source, inputSlot, { ...prepared, kind: row.kind });
|
|
971
|
+
const assigned = claimSlots.get(claim);
|
|
972
|
+
if (assigned && assigned !== slot) {
|
|
973
|
+
ambiguousSlots.add(assigned);
|
|
974
|
+
ambiguousSlots.add(slot);
|
|
975
|
+
}
|
|
976
|
+
claimSlots.set(claim, slot);
|
|
670
977
|
const group = groups.get(slot) ?? [];
|
|
671
|
-
|
|
672
|
-
const sourceText = event?.type === 'user/message' ? messageText(event.data) :
|
|
673
|
-
events.find(block => block.seq === seq && block.text.includes(row.user_quote)).text;
|
|
674
|
-
group.push({ index, row, prepared, source, sourceText, family, observed });
|
|
978
|
+
group.push({ index, row, prepared, source, family, inputSlot, observed });
|
|
675
979
|
groups.set(slot, group);
|
|
676
980
|
}
|
|
677
981
|
catch (error) {
|
|
@@ -682,14 +986,13 @@ export class ProjectMemory {
|
|
|
682
986
|
outcomes[index] = { status: 'skipped', reason: /^[a-z_]+$/.test(code) ? code : 'invalid_input' };
|
|
683
987
|
}
|
|
684
988
|
}
|
|
685
|
-
const entries = [];
|
|
686
989
|
for (const [slot, group] of groups) {
|
|
687
990
|
const owner = group[0].row.scope === 'global' ? this.personal : d;
|
|
688
991
|
let result;
|
|
689
992
|
try {
|
|
690
993
|
const overlaps = [...groups].some(([otherSlot, others]) => otherSlot !== slot &&
|
|
691
994
|
others[0].family === group[0].family && !separateContexts(group[0].prepared, others[0].prepared));
|
|
692
|
-
result = overlaps ? { status: 'skipped', reason: 'ambiguous_topic' } :
|
|
995
|
+
result = overlaps || ambiguousSlots.has(slot) ? { status: 'skipped', reason: 'ambiguous_topic' } :
|
|
693
996
|
this.applySemantic(root, owner, slot, group, generation, background, reviewEpochs);
|
|
694
997
|
}
|
|
695
998
|
catch (error) {
|
|
@@ -697,8 +1000,6 @@ export class ProjectMemory {
|
|
|
697
1000
|
throw error;
|
|
698
1001
|
result = { status: 'skipped', reason: error instanceof StoreError ? error.code : 'write_failed' };
|
|
699
1002
|
}
|
|
700
|
-
if (result.status !== 'skipped')
|
|
701
|
-
entries.push({ id: result.id, rev: result.rev });
|
|
702
1003
|
for (const [position, candidate] of group.entries()) {
|
|
703
1004
|
outcomes[candidate.index] = position > 0 && result.status === 'saved'
|
|
704
1005
|
? { ...result, status: 'duplicate' } : result;
|
|
@@ -706,32 +1007,30 @@ export class ProjectMemory {
|
|
|
706
1007
|
}
|
|
707
1008
|
if (outcomes.some(item => item.status === 'saved'))
|
|
708
1009
|
notifyUI(this.ctx, root.id);
|
|
1010
|
+
const unique = new Map();
|
|
1011
|
+
for (const result of outcomes) {
|
|
1012
|
+
if (result.status !== 'skipped')
|
|
1013
|
+
unique.set(result.id, { id: result.id, rev: result.rev });
|
|
1014
|
+
}
|
|
1015
|
+
const entries = [...unique.values()];
|
|
709
1016
|
const status = !entries.length ? 'skipped' : outcomes.some(item => item.status === 'skipped') ? 'partial'
|
|
710
1017
|
: outcomes.some(item => item.status === 'saved') ? 'saved' : 'duplicate';
|
|
711
1018
|
return { status, entries, results: outcomes.map((result, index) => ({ index, ...result })) };
|
|
712
1019
|
}
|
|
713
|
-
topicHeads(owner, row) {
|
|
714
|
-
const matches = this.store.semanticMatches(owner.id, row.scope, row.topic, row.subject);
|
|
715
|
-
const canonical = matches[0]?.semanticTopic;
|
|
716
|
-
// A condition-specific head may carry an alias that its siblings don't. Compare all
|
|
717
|
-
// contexts of the canonical topic before introducing another branch.
|
|
718
|
-
if (canonical && normalizeLabel(canonical) !== normalizeLabel(row.topic) &&
|
|
719
|
-
matches.every(head => normalizeLabel(head.semanticTopic) === normalizeLabel(canonical)))
|
|
720
|
-
return this.store.semanticMatches(owner.id, row.scope, canonical, row.subject);
|
|
721
|
-
return matches;
|
|
722
|
-
}
|
|
723
1020
|
applySemantic(root, owner, slot, group, generation, background, reviewEpochs) {
|
|
724
1021
|
const epoch = this.store.epoch(owner.id);
|
|
725
1022
|
if (reviewEpochs && reviewEpochs.get(owner.id) !== epoch)
|
|
726
1023
|
return { status: 'skipped', reason: 'stale_revision' };
|
|
727
1024
|
const items = [];
|
|
728
1025
|
const current = this.store.currentSlot(owner.id, slot);
|
|
729
|
-
for (const { row, prepared,
|
|
730
|
-
const
|
|
1026
|
+
for (const { row, prepared, source, observed } of group) {
|
|
1027
|
+
const target = row.replaces ? this.store.read(owner.id, row.replaces.id) : undefined;
|
|
1028
|
+
if (row.replaces && (!target || target.rev !== row.replaces.rev))
|
|
1029
|
+
return { status: 'skipped', reason: 'stale_revision' };
|
|
1030
|
+
const matches = this.store.canonicalTopicHeads(owner.id, row.scope, target?.semanticTopic ?? row.topic, row.subject);
|
|
1031
|
+
const plan = planSemantic(row, prepared, matches, target, background, Boolean(prepared.source?.formSelection));
|
|
731
1032
|
if ('reason' in plan)
|
|
732
|
-
return { status: 'skipped', reason:
|
|
733
|
-
if (background && row.replaces && plan.previous && !correctReviewSubject(row, sourceText, this.store.topicSubjects(owner.id, row.scope, plan.previous.semanticTopic)))
|
|
734
|
-
return { status: 'skipped', reason: 'ambiguous_topic' };
|
|
1033
|
+
return { status: 'skipped', reason: plan.reason };
|
|
735
1034
|
if (observed?.id !== plan.previous?.id || observed?.rev !== plan.previous?.rev)
|
|
736
1035
|
return { status: 'skipped', reason: 'stale_revision' };
|
|
737
1036
|
// An explicit edit may have changed the conditions while retaining the original slot.
|
|
@@ -749,7 +1048,7 @@ export class ProjectMemory {
|
|
|
749
1048
|
items.push({ ...item, source: { ...item.source, time: source.time } });
|
|
750
1049
|
}
|
|
751
1050
|
try {
|
|
752
|
-
const inputSlots = group.map(
|
|
1051
|
+
const inputSlots = group.map(candidate => candidate.inputSlot);
|
|
753
1052
|
const result = this.store.saveAutomatic(owner.id, root.id, group[0].source, items, epoch, generation, inputSlots);
|
|
754
1053
|
if (result.state === 'stale')
|
|
755
1054
|
return { status: 'skipped', reason: 'stale_source' };
|
|
@@ -765,6 +1064,56 @@ export class ProjectMemory {
|
|
|
765
1064
|
throw error;
|
|
766
1065
|
}
|
|
767
1066
|
}
|
|
1067
|
+
fileImport(agent, query, commandId) {
|
|
1068
|
+
const d = this.rootDomain(agent, query !== 'list');
|
|
1069
|
+
if (d.id === this.personal.id)
|
|
1070
|
+
throw new StoreError('project_required');
|
|
1071
|
+
if (query === 'list')
|
|
1072
|
+
return this.store.fileImports.list(d.id);
|
|
1073
|
+
const undo = /^undo (import-[a-f0-9-]+)$/u.exec(query);
|
|
1074
|
+
if (undo) {
|
|
1075
|
+
const result = this.store.fileImports.undo(d.id, agent.id, undo[1]);
|
|
1076
|
+
notifyUI(this.ctx, agent.id);
|
|
1077
|
+
return result;
|
|
1078
|
+
}
|
|
1079
|
+
const page = /^(all|agents|claude|claude-memory)(?: (\d{1,8}):([1-9]\d{0,7}))?$/u.exec(query || 'all');
|
|
1080
|
+
if (!page)
|
|
1081
|
+
throw new StoreError('invalid_command');
|
|
1082
|
+
const selection = page[1];
|
|
1083
|
+
if (!this.store.memoryEnabled())
|
|
1084
|
+
throw new StoreError('memory_disabled');
|
|
1085
|
+
const event = agent.session.snapshotEvents().findLast(e => e.type === 'command/run' &&
|
|
1086
|
+
e.data.commandId === commandId);
|
|
1087
|
+
if (!event || !commandId)
|
|
1088
|
+
throw new StoreError('invalid_source');
|
|
1089
|
+
const source = { storeId: this.storeId(agent.session), sessionId: agent.id,
|
|
1090
|
+
turnId: latestTurn(agent.session) || '0', seq: event.seq, origin: 'manual' };
|
|
1091
|
+
const scanned = scanImport(d.root, selection, Number(page[2] ?? 0), Number(page[3] ?? 1));
|
|
1092
|
+
const guidance = loadedGuidance(agent.session, d, this.ctx);
|
|
1093
|
+
const drafts = scanned.entries.flatMap(({ action, context, file }) => {
|
|
1094
|
+
try {
|
|
1095
|
+
const item = manualItem(d, { action, user_quote: action, when: context, exceptions: '', paths: [],
|
|
1096
|
+
conflicts_with_repo_guidance: false }, guidance, file);
|
|
1097
|
+
return [{ file, item: { ...item, usage: 'on_demand' } }];
|
|
1098
|
+
}
|
|
1099
|
+
catch {
|
|
1100
|
+
scanned.skipped++;
|
|
1101
|
+
return [];
|
|
1102
|
+
}
|
|
1103
|
+
});
|
|
1104
|
+
const next = scanned.next && '/project-memory import ' + selection + ' ' + scanned.next;
|
|
1105
|
+
const staleImports = new Set(this.store.list(d.id)
|
|
1106
|
+
.filter(rule => rule.source.fileImport && this.validity(d, rule).reason === 'stale_guidance')
|
|
1107
|
+
.map(rule => rule.id + '@' + rule.rev));
|
|
1108
|
+
const result = this.store.fileImports.stage(d.id, source, page[0], scanned.files, scanned.skipped, drafts, next, staleImports);
|
|
1109
|
+
const announced = new Set(agent.session.snapshotEvents().filter(e => e.type === 'plugin:project-memory/proposal')
|
|
1110
|
+
.map(e => e.data.proposalId));
|
|
1111
|
+
for (const id of result.proposals) {
|
|
1112
|
+
if (!announced.has(id) && this.store.proposal(d.id, agent.id, id)?.state === 'pending')
|
|
1113
|
+
this.announce(agent, 'proposal', { proposalId: id, state: 'pending', turnId: source.turnId });
|
|
1114
|
+
}
|
|
1115
|
+
return result;
|
|
1116
|
+
}
|
|
768
1117
|
manual(agent, input, commandId, replace) {
|
|
769
1118
|
const d = this.rootDomain(agent, true);
|
|
770
1119
|
if (d.id === this.personal.id)
|
|
@@ -817,42 +1166,59 @@ export class ProjectMemory {
|
|
|
817
1166
|
}
|
|
818
1167
|
// Only the human-facing manager searches these summaries. A project entry outside its
|
|
819
1168
|
// valid scope contributes its public reason and id, never its body or retained wording.
|
|
820
|
-
managerStatus(withheld, query) {
|
|
1169
|
+
managerStatus(withheld, query, locale) {
|
|
1170
|
+
const labels = locale === 'en' ? uiMessages.en : uiMessages.zh;
|
|
821
1171
|
const needs_review = withheld.map((row) => {
|
|
822
|
-
const reasonText =
|
|
1172
|
+
const reasonText = labels['reason.' + row.reason] ?? labels['reason.unavailable'];
|
|
823
1173
|
const rule = row.scope === 'profile' ? this.store.read(this.personal.id, row.id, row.rev) : undefined;
|
|
824
1174
|
const quote = rule?.quoteType === 'user_quote' && rule.user_quote;
|
|
825
|
-
const
|
|
826
|
-
? '
|
|
827
|
-
return { ...row, reasonText, statusLabel, ...(quote ? { quote } : {}) };
|
|
1175
|
+
const statusKey = ['outside_branch', 'outside_path', 'outside_environment'].includes(row.reason)
|
|
1176
|
+
? 'section.inapplicable' : 'section.inactive';
|
|
1177
|
+
return { ...row, reasonText, statusKey, statusLabel: labels[statusKey], ...(quote ? { quote } : {}) };
|
|
828
1178
|
}).filter((row) => containsWords(query, [
|
|
829
1179
|
row.id + '@' + row.rev, row.action, row.previous, row.quote, row.reason, row.reasonText, row.kind,
|
|
830
|
-
row.scope === 'profile' ? '
|
|
1180
|
+
labels[row.scope === 'profile' ? 'scope.global' : 'scope.project'],
|
|
831
1181
|
row.statusLabel,
|
|
832
1182
|
]));
|
|
833
1183
|
return { needs_review };
|
|
834
1184
|
}
|
|
835
|
-
view(agent) {
|
|
1185
|
+
view(agent, projection, check) {
|
|
836
1186
|
const d = this.rootDomain(agent);
|
|
837
|
-
const
|
|
838
|
-
const
|
|
839
|
-
|
|
1187
|
+
const chat = projection === 'chat';
|
|
1188
|
+
const scopes = this.scopes(agent, d).filter(scope => !projection || chat ||
|
|
1189
|
+
(scope.id === this.personal.id ? 'profile' : 'project') === projection);
|
|
1190
|
+
const project = d.id !== this.personal.id;
|
|
1191
|
+
const cards = project && !chat && projection !== 'profile' ? this.store.cards(d.id, agent.id) : [];
|
|
1192
|
+
const conversationCards = project && chat ? this.store.conversationCards(d.id, agent.id) : [];
|
|
1193
|
+
const pending = cards.some(card => card.state === 'pending');
|
|
1194
|
+
if (check)
|
|
1195
|
+
check.reusable = !pending && !conversationCards.some(card => card.state === 'pending');
|
|
1196
|
+
const receipts = conversationCards.flatMap(card => card.entries);
|
|
1197
|
+
const delivered = new Set();
|
|
840
1198
|
const eligible = [];
|
|
841
1199
|
const needs_review = [];
|
|
842
1200
|
// Saved in this session without a card. The turn that said it shows the line and its undo.
|
|
843
1201
|
const saved = [];
|
|
844
|
-
for (const scope of
|
|
1202
|
+
for (const scope of scopes) {
|
|
845
1203
|
const profile = scope.id === this.personal.id;
|
|
846
|
-
for (const
|
|
1204
|
+
for (const ref of this.store.delivered(scope.id, agent.id))
|
|
1205
|
+
delivered.add(ref.id + '@' + ref.rev);
|
|
1206
|
+
const rows = chat ? this.store.chatHeads(scope.id, agent.id, profile ? [] : receipts) : this.store.list(scope.id);
|
|
1207
|
+
for (const rule of rows) {
|
|
1208
|
+
if (check?.reusable && !isDatabaseOnly(scope, rule))
|
|
1209
|
+
check.reusable = false;
|
|
847
1210
|
const status = this.validity(scope, rule);
|
|
848
1211
|
const automatic = rule.channel === 'automatic';
|
|
849
1212
|
const mine = automatic && rule.source?.sessionId === agent.id;
|
|
850
|
-
if (mine && status.ok) {
|
|
1213
|
+
if (mine && status.ok && (chat || !projection)) {
|
|
1214
|
+
// A previous version can age out even when there has been no database write.
|
|
1215
|
+
if (check && rule.rev > 1)
|
|
1216
|
+
check.reusable = false;
|
|
851
1217
|
const before = !isKnowledge(rule) ? this.restorable(scope, rule)?.action : undefined;
|
|
852
1218
|
saved.push({
|
|
853
1219
|
id: rule.id,
|
|
854
1220
|
rev: rule.rev,
|
|
855
|
-
turnId: rule.source.turnId,
|
|
1221
|
+
turnId: rule.source.scopeClarification?.turnId ?? rule.source.turnId,
|
|
856
1222
|
usage: rule.usage ?? 'on_demand',
|
|
857
1223
|
scope: profile ? 'profile' : 'project',
|
|
858
1224
|
...(rule.slot ? { slot: rule.slot } : {}),
|
|
@@ -865,18 +1231,32 @@ export class ProjectMemory {
|
|
|
865
1231
|
}
|
|
866
1232
|
if (status.ok)
|
|
867
1233
|
eligible.push(rule);
|
|
868
|
-
else
|
|
1234
|
+
else if (!chat)
|
|
869
1235
|
needs_review.push(this.reviewEntry(scope, rule, status.reason));
|
|
870
1236
|
}
|
|
871
1237
|
}
|
|
872
|
-
const
|
|
873
|
-
|
|
1238
|
+
const indexedHeads = new Set(eligible.some(row => row.usage === 'proactive')
|
|
1239
|
+
? this.index(agent, d, true).included.map(row => row.id + '@' + row.rev) : []);
|
|
1240
|
+
const indexed = (r) => indexedHeads.has(r.id + '@' + r.rev);
|
|
1241
|
+
const available = new Set(eligible.map(row => row.id + '@' + row.rev));
|
|
1242
|
+
const guidance = pending ? loadedGuidance(agent.session, d, this.ctx) : [];
|
|
1243
|
+
const related = pending ? eligible.filter(r => !isPersonalSlot(r.slot) && !isKnowledge(r)) : [];
|
|
1244
|
+
const importValidity = new Map();
|
|
1245
|
+
const proposals = cards.map((card) => {
|
|
874
1246
|
let p = card;
|
|
875
1247
|
if (card.state === 'pending') {
|
|
876
1248
|
const items = card.items.map((item) => {
|
|
877
1249
|
let current;
|
|
878
1250
|
try {
|
|
879
|
-
|
|
1251
|
+
const file = card.source.fileImport;
|
|
1252
|
+
if (file) {
|
|
1253
|
+
const key = file.path + ':' + file.sha256;
|
|
1254
|
+
if (!importValidity.has(key))
|
|
1255
|
+
importValidity.set(key, currentImport(d.root, file));
|
|
1256
|
+
if (!importValidity.get(key))
|
|
1257
|
+
throw new StoreError('stale_import');
|
|
1258
|
+
}
|
|
1259
|
+
current = manualItem(d, ruleFields(item), guidance, file, item.guidance);
|
|
880
1260
|
}
|
|
881
1261
|
catch {
|
|
882
1262
|
// A changed symlink or repo boundary can invalidate an old candidate.
|
|
@@ -897,7 +1277,7 @@ export class ProjectMemory {
|
|
|
897
1277
|
...p,
|
|
898
1278
|
items: p.items.map((item) => ({
|
|
899
1279
|
...item,
|
|
900
|
-
related: relatedRules(item,
|
|
1280
|
+
related: relatedRules(item, related).map(publicRule),
|
|
901
1281
|
})),
|
|
902
1282
|
receipt: p.receipt && {
|
|
903
1283
|
...p.receipt,
|
|
@@ -905,16 +1285,17 @@ export class ProjectMemory {
|
|
|
905
1285
|
...r,
|
|
906
1286
|
indexed: r.indexed ?? indexed(r),
|
|
907
1287
|
currentlyIndexed: indexed(r),
|
|
908
|
-
available:
|
|
1288
|
+
available: available.has(r.id + '@' + r.rev),
|
|
909
1289
|
})),
|
|
910
1290
|
},
|
|
911
1291
|
};
|
|
912
1292
|
});
|
|
913
1293
|
return {
|
|
914
1294
|
proposals,
|
|
1295
|
+
...(chat && { conversationCards }),
|
|
915
1296
|
needs_review,
|
|
916
1297
|
saved: saved.sort((a, b) => Number(a.turnId) - Number(b.turnId)),
|
|
917
|
-
rules: eligible.map(r => managerRule(r, indexed(r), delivered.
|
|
1298
|
+
rules: eligible.map(r => managerRule(r, indexed(r), delivered.has(r.id + '@' + r.rev))),
|
|
918
1299
|
};
|
|
919
1300
|
}
|
|
920
1301
|
proposalOf(agent, id) {
|
|
@@ -946,14 +1327,25 @@ export class ProjectMemory {
|
|
|
946
1327
|
const original = p.items[s.index];
|
|
947
1328
|
if (!Number.isInteger(s.index) || !original)
|
|
948
1329
|
throw new StoreError('invalid_selection');
|
|
949
|
-
const
|
|
950
|
-
|
|
1330
|
+
const file = p.source.fileImport;
|
|
1331
|
+
if (file && !currentImport(d.root, file))
|
|
1332
|
+
throw new StoreError('stale_import');
|
|
1333
|
+
const validated = reviewItem(d, original, s.changes, s.exception, guidance, s.branch, file, s.guidanceReviewed);
|
|
1334
|
+
if (p.source.origin === 'tool' && (validated.user_quote || validated.action.length > 512 ||
|
|
1335
|
+
skipsAutomaticMemory([validated.action, validated.when, validated.exceptions, ...validated.paths].join('\n'))))
|
|
1336
|
+
throw new StoreError('invalid_input');
|
|
1337
|
+
if (file) {
|
|
1338
|
+
if (validated.action.length > 480 || skipsAutomaticMemory([validated.action, validated.when, validated.exceptions, ...validated.paths].join(' ')))
|
|
1339
|
+
throw new StoreError('invalid_item');
|
|
1340
|
+
validated.user_quote = validated.action;
|
|
1341
|
+
}
|
|
1342
|
+
const item = { ...validated, ...semanticMetadata(original, validated.action), ...(file ? { kind: 'rule' } : {}) };
|
|
951
1343
|
if (s.coexist && s.replace)
|
|
952
1344
|
throw new StoreError('invalid_selection');
|
|
953
1345
|
const replace = s.coexist ? undefined : (s.replace ?? original.replace);
|
|
954
1346
|
if (replace && isKnowledge(this.store.read(d.id, replace.id, replace.rev) ?? original))
|
|
955
1347
|
throw new StoreError('invalid_selection');
|
|
956
|
-
if (!replace && !s.coexist && relatedRules(item, heads).length)
|
|
1348
|
+
if (!file && !replace && !s.coexist && relatedRules(item, heads).length)
|
|
957
1349
|
throw new StoreError('needs_resolution', '已有相关规则,请选择替代条目,或明确按不同条件并存。');
|
|
958
1350
|
return { index: s.index, item, replace };
|
|
959
1351
|
});
|
|
@@ -968,7 +1360,7 @@ export class ProjectMemory {
|
|
|
968
1360
|
for (const ref of entries)
|
|
969
1361
|
eligible.add(ref.id);
|
|
970
1362
|
const heads = scopes.flatMap((s) => this.store.list(s.id)).filter((r) => eligible.has(r.id));
|
|
971
|
-
const included = new Set(buildIndex(heads, withdrawn, this.config).included.map((r) => r.id));
|
|
1363
|
+
const included = new Set(buildIndex(heads, withdrawn, this.config, undefined, this.promptLanguage(agent)).included.map((r) => r.id));
|
|
972
1364
|
return {
|
|
973
1365
|
entries: entries.map((r) => ({ ...r, indexed: included.has(r.id) })),
|
|
974
1366
|
displaced: before.included.filter((r) => !included.has(r.id)).map((r) => r.id),
|
|
@@ -978,6 +1370,84 @@ export class ProjectMemory {
|
|
|
978
1370
|
this.announce(agent, 'receipt', { proposalId: p.id, state: receipt.state, entries: receipt.entries });
|
|
979
1371
|
return receipt;
|
|
980
1372
|
}
|
|
1373
|
+
mayReadSourceSession(rule) {
|
|
1374
|
+
return !!rule.source.sessionId && this.ctx.get('remoteAccess')?.allows({ kind: 'session', id: rule.source.sessionId }) !== false;
|
|
1375
|
+
}
|
|
1376
|
+
readableToolSource(rule) {
|
|
1377
|
+
return rule.quoteType === 'tool_result' && rule.source.toolResult &&
|
|
1378
|
+
this.mayReadSourceSession(rule);
|
|
1379
|
+
}
|
|
1380
|
+
canPublishEvidence(rule, result) {
|
|
1381
|
+
if (!('quote' in result))
|
|
1382
|
+
return true;
|
|
1383
|
+
if (rule.user_quote !== result.quote || ('toolResult' in result && !this.readableToolSource(rule)))
|
|
1384
|
+
return false;
|
|
1385
|
+
return !('source' in result || 'formSelection' in result || 'scopeClarification' in result) || this.mayReadSourceSession(rule);
|
|
1386
|
+
}
|
|
1387
|
+
sameQuoteSource(a, b) {
|
|
1388
|
+
return a.quoteType === b.quoteType && a.user_quote === b.user_quote &&
|
|
1389
|
+
isDeepStrictEqual(a.evidence, b.evidence) && isDeepStrictEqual(a.source, b.source);
|
|
1390
|
+
}
|
|
1391
|
+
sourceEvidence(d, r, verified = false) {
|
|
1392
|
+
return {
|
|
1393
|
+
id: r.id, rev: r.rev, scope: d.id === this.personal.id ? 'profile' : 'project',
|
|
1394
|
+
evidence: r.quoteType === 'user_quote' ? 'retained_quote' : r.quoteType, quote: r.user_quote,
|
|
1395
|
+
...(this.readableToolSource(r)
|
|
1396
|
+
? { toolResult: r.source.toolResult, source: { session_id: r.source.sessionId, turn: r.source.turnId, seq: r.source.seq } } : {}),
|
|
1397
|
+
...(r.source.fileImport ? { fileImport: r.source.fileImport } : {}),
|
|
1398
|
+
...(r.source.scopeClarification && this.mayReadSourceSession(r) &&
|
|
1399
|
+
{ scopeClarification: r.source.scopeClarification }),
|
|
1400
|
+
...(r.source.formSelection && this.mayReadSourceSession(r) && { formSelection: r.source.formSelection }),
|
|
1401
|
+
...(verified && r.evidence && this.mayReadSourceSession(r) && {
|
|
1402
|
+
evidence: 'verified_user_quote',
|
|
1403
|
+
source: { session_id: r.source.sessionId, turn: r.source.turnId, ...r.evidence },
|
|
1404
|
+
}),
|
|
1405
|
+
};
|
|
1406
|
+
}
|
|
1407
|
+
async verifyQuote(d, rule) {
|
|
1408
|
+
if (rule.quoteType !== 'user_quote' || !rule.user_quote || !rule.evidence || !this.mayReadSourceSession(rule))
|
|
1409
|
+
return false;
|
|
1410
|
+
const { seq, start, end } = rule.evidence;
|
|
1411
|
+
if (!Number.isSafeInteger(seq) || seq < 0 || seq !== rule.source.seq ||
|
|
1412
|
+
!Number.isSafeInteger(start) || start < 0 || end !== start + rule.user_quote.length)
|
|
1413
|
+
return false;
|
|
1414
|
+
try {
|
|
1415
|
+
const window = await this.ctx.get('sessionQuery')?.readEvent({ sessionId: rule.source.sessionId, seq, before: 0, after: 0 });
|
|
1416
|
+
if (!window || window.session.id !== rule.source.sessionId || window.target?.seq !== seq ||
|
|
1417
|
+
seq < window.inheritedEventCount || !this.mayReadSourceSession(rule) ||
|
|
1418
|
+
sourceStore(this.ctx, this.profile, window.session.createdAt) !== rule.source.storeId)
|
|
1419
|
+
return false;
|
|
1420
|
+
const target = window.target;
|
|
1421
|
+
if (target.data.turn !== undefined && String(target.data.turn) !== rule.source.turnId)
|
|
1422
|
+
return false;
|
|
1423
|
+
if (target.type === 'user/message')
|
|
1424
|
+
return target.data.source?.kind === 'user' && messageText(target.data).slice(start, end) === rule.user_quote;
|
|
1425
|
+
if (target.type !== 'tool/result')
|
|
1426
|
+
return false;
|
|
1427
|
+
let origin = this.ctx.agents.get(rule.source.sessionId)?.session;
|
|
1428
|
+
if (!origin && d.id === this.personal.id) {
|
|
1429
|
+
const loaded = await this.ctx.get('sessionController')?.resolveAgent(rule.source.sessionId);
|
|
1430
|
+
if (!loaded?.agent || loaded.agent !== this.ctx.agents.get(rule.source.sessionId))
|
|
1431
|
+
return false;
|
|
1432
|
+
origin = loaded.agent.session;
|
|
1433
|
+
}
|
|
1434
|
+
if (!origin || origin.id !== rule.source.sessionId || origin.header.createdAt !== window.session.createdAt || !this.allows(origin))
|
|
1435
|
+
return false;
|
|
1436
|
+
const live = origin.snapshotEvents()[seq];
|
|
1437
|
+
if (live?.type !== target.type || !isDeepStrictEqual(live.data, target.data))
|
|
1438
|
+
return false;
|
|
1439
|
+
// A global fact can come from a form submitted in a project; use that event's captured binding.
|
|
1440
|
+
const binding = d.id === this.personal.id ? boundSourceDomain(origin, rule.source.storeId, rule.source.turnId, seq) : d;
|
|
1441
|
+
return !!binding && sources(origin, binding, rule.source.storeId, rule.source.turnId).some(block => {
|
|
1442
|
+
const offset = block.offset ?? 0;
|
|
1443
|
+
return block.seq === seq && block.question && start >= offset && end <= offset + block.text.length &&
|
|
1444
|
+
block.text.slice(start - offset, end - offset) === rule.user_quote;
|
|
1445
|
+
});
|
|
1446
|
+
}
|
|
1447
|
+
catch {
|
|
1448
|
+
return false;
|
|
1449
|
+
}
|
|
1450
|
+
}
|
|
981
1451
|
async read(agent, id, rev, expand = false) {
|
|
982
1452
|
const active = this.domain(agent);
|
|
983
1453
|
const d = active && this.owner(agent, active, id);
|
|
@@ -986,59 +1456,18 @@ export class ProjectMemory {
|
|
|
986
1456
|
return { status: 'not_found' };
|
|
987
1457
|
if (!expand)
|
|
988
1458
|
return publicRule(rule);
|
|
989
|
-
const
|
|
990
|
-
|
|
991
|
-
|
|
992
|
-
|
|
993
|
-
|
|
994
|
-
|
|
995
|
-
|
|
996
|
-
|
|
997
|
-
|
|
998
|
-
|
|
999
|
-
|
|
1000
|
-
|
|
1001
|
-
|
|
1002
|
-
seq >= window.inheritedEventCount) {
|
|
1003
|
-
const target = window.target;
|
|
1004
|
-
if (target.type === 'user/message' && target.data.source?.kind === 'user' &&
|
|
1005
|
-
messageText(target.data).slice(start, end) === rule.user_quote)
|
|
1006
|
-
verified = true;
|
|
1007
|
-
if (target.type === 'tool/result') {
|
|
1008
|
-
const origin = this.ctx.agents.get(rule.source.sessionId)?.session;
|
|
1009
|
-
const live = origin?.snapshotEvents()[seq];
|
|
1010
|
-
if (live?.type === target.type && isDeepStrictEqual(live.data, target.data) && origin && origin.header.createdAt === window.session.createdAt && this.allows(origin) &&
|
|
1011
|
-
sources(origin, d, rule.source.storeId, rule.source.turnId).some(block => {
|
|
1012
|
-
const offset = block.offset ?? 0;
|
|
1013
|
-
return block.seq === seq && block.question && start >= offset && end <= offset + block.text.length &&
|
|
1014
|
-
block.text.slice(start - offset, end - offset) === rule.user_quote;
|
|
1015
|
-
}))
|
|
1016
|
-
verified = true;
|
|
1017
|
-
}
|
|
1018
|
-
}
|
|
1019
|
-
}
|
|
1020
|
-
catch {
|
|
1021
|
-
/* A deleted source leaves only the approved short quote. */
|
|
1022
|
-
}
|
|
1023
|
-
const now = this.domain(agent);
|
|
1024
|
-
const head = now?.id === d.id && this.current(now, id, rule.rev);
|
|
1025
|
-
if (!head)
|
|
1026
|
-
return { status: 'not_found' };
|
|
1027
|
-
if (head.user_quote !== rule.user_quote || head.quoteType !== rule.quoteType)
|
|
1028
|
-
return evidenceOf(head);
|
|
1029
|
-
}
|
|
1030
|
-
return {
|
|
1031
|
-
...evidenceOf(rule),
|
|
1032
|
-
...(verified && rule.evidence
|
|
1033
|
-
? {
|
|
1034
|
-
evidence: 'verified_user_quote',
|
|
1035
|
-
source: {
|
|
1036
|
-
session_id: rule.source.sessionId,
|
|
1037
|
-
turn: rule.source.turnId,
|
|
1038
|
-
...rule.evidence,
|
|
1039
|
-
},
|
|
1040
|
-
}
|
|
1041
|
-
: {}),
|
|
1042
|
-
};
|
|
1459
|
+
const retained = this.sourceEvidence(d, rule);
|
|
1460
|
+
if (d.id === this.personal.id || !rule.evidence || rule.quoteType !== 'user_quote')
|
|
1461
|
+
return retained;
|
|
1462
|
+
const verified = await this.verifyQuote(d, rule);
|
|
1463
|
+
const now = this.domain(agent);
|
|
1464
|
+
const head = now?.id === d.id && this.current(now, id, rule.rev);
|
|
1465
|
+
if (!head)
|
|
1466
|
+
return { status: 'not_found' };
|
|
1467
|
+
if (!this.sameQuoteSource(rule, head))
|
|
1468
|
+
return this.sourceEvidence(d, head);
|
|
1469
|
+
if (!this.canPublishEvidence(head, retained))
|
|
1470
|
+
return { status: 'not_found' };
|
|
1471
|
+
return verified ? this.sourceEvidence(d, head, true) : retained;
|
|
1043
1472
|
}
|
|
1044
1473
|
}
|