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/propose-contract.js
CHANGED
|
@@ -1,42 +1,38 @@
|
|
|
1
|
-
|
|
2
|
-
|
|
3
|
-
|
|
4
|
-
|
|
5
|
-
|
|
6
|
-
|
|
7
|
-
|
|
8
|
-
|
|
9
|
-
export const proposeTool = {
|
|
10
|
-
description: memoryInstructions + ' 遇到 unsupported_correction,可以从引文中逐字提取明确的新值重试一次。仍无法核对时保留原记录。保存状态由聊天回执展示。日常对话直接回应用户的话。用户询问记忆状态或明确要求保存时,按 results 的输入序号逐项回答,只有 saved 或 duplicate 表示该项已记住;partial 表示本批仅部分成功。',
|
|
11
|
-
parameters: {
|
|
12
|
-
type: 'object', additionalProperties: false, required: ['items'],
|
|
13
|
-
properties: {
|
|
14
|
-
items: {
|
|
15
|
-
type: 'array', minItems: 1, maxItems: 32,
|
|
1
|
+
import { prompts } from "./prompt-copy.js";
|
|
2
|
+
export function proposalContract(language) {
|
|
3
|
+
const copy = prompts[language];
|
|
4
|
+
return {
|
|
5
|
+
description: copy.write + ' ' + copy.propose,
|
|
6
|
+
parameters: {
|
|
7
|
+
type: 'object', additionalProperties: false, required: ['items'],
|
|
8
|
+
properties: {
|
|
16
9
|
items: {
|
|
17
|
-
type: '
|
|
18
|
-
|
|
19
|
-
|
|
20
|
-
|
|
21
|
-
|
|
22
|
-
|
|
23
|
-
|
|
24
|
-
|
|
25
|
-
|
|
26
|
-
|
|
27
|
-
|
|
28
|
-
|
|
29
|
-
|
|
30
|
-
type: '
|
|
31
|
-
|
|
10
|
+
type: 'array', minItems: 1, maxItems: 32,
|
|
11
|
+
items: {
|
|
12
|
+
type: 'object', additionalProperties: false, required: ['scope', 'action'],
|
|
13
|
+
anyOf: [{ required: ['replaces'] }, { required: ['kind', 'topic'] }],
|
|
14
|
+
properties: {
|
|
15
|
+
user_quote: { type: 'string', minLength: 1, maxLength: 480, description: copy.user_quote },
|
|
16
|
+
action: { type: 'string', minLength: 1, maxLength: 480, description: copy.action },
|
|
17
|
+
scope: { type: 'string', enum: ['global', 'project'], description: copy.scope },
|
|
18
|
+
kind: { type: 'string', enum: ['fact', 'preference', 'rule'] },
|
|
19
|
+
topic: { type: 'string', minLength: 1, maxLength: 80, description: copy.topic },
|
|
20
|
+
subject: { type: 'string', minLength: 1, maxLength: 80, description: copy.subject },
|
|
21
|
+
usage: { type: 'string', enum: ['proactive', 'on_demand'], description: copy.usage },
|
|
22
|
+
keywords: { type: 'array', maxItems: 8, items: { type: 'string', minLength: 1, maxLength: 40 }, description: copy.keywords },
|
|
23
|
+
sensitive: { type: 'boolean', description: copy.sensitive },
|
|
24
|
+
replaces: {
|
|
25
|
+
type: 'object', additionalProperties: false, required: ['id', 'rev'],
|
|
26
|
+
description: copy.replaces,
|
|
27
|
+
properties: { id: { type: 'string' }, rev: { type: 'integer', minimum: 1 } },
|
|
28
|
+
},
|
|
29
|
+
when: { type: 'string', maxLength: 480, description: copy.when },
|
|
30
|
+
exceptions: { type: 'string', maxLength: 480, description: copy.exceptions },
|
|
31
|
+
paths: { type: 'array', maxItems: 64, items: { type: 'string', maxLength: 1024 }, description: copy.paths },
|
|
32
32
|
},
|
|
33
|
-
when: { type: 'string', maxLength: 480, description: '原话中的适用条件。' },
|
|
34
|
-
exceptions: { type: 'string', maxLength: 480, description: '原话中的例外。' },
|
|
35
|
-
paths: { type: 'array', maxItems: 64, items: { type: 'string', maxLength: 1024 }, description: '原话中的项目相对路径。' },
|
|
36
|
-
conflicts_with_repo_guidance: { type: 'boolean' },
|
|
37
33
|
},
|
|
38
34
|
},
|
|
39
35
|
},
|
|
40
36
|
},
|
|
41
|
-
}
|
|
42
|
-
}
|
|
37
|
+
};
|
|
38
|
+
}
|
package/dist/question-answers.js
CHANGED
|
@@ -1,100 +1,157 @@
|
|
|
1
1
|
import { refusesAutomaticMemory, skipsAutomaticMemory } from "./automatic.js";
|
|
2
2
|
import { messageText } from "./host.js";
|
|
3
|
+
/** Keep the user's directive and the submitted format intact. Strip only the
|
|
4
|
+
* recommendation marker that DSH forms display as part of an option label. */
|
|
5
|
+
export function selectedAction(directive, label) {
|
|
6
|
+
return directive + '\n' + label.replace(/\s*(?:\((?:recommended|推荐)\)|((?:recommended|推荐)))\s*$/iu, '').trim();
|
|
7
|
+
}
|
|
8
|
+
// A submitted choice can supply the implementation of a standing request. The
|
|
9
|
+
// user must express its continuing applicability in their own cited words.
|
|
10
|
+
export function standingRequest(text) {
|
|
11
|
+
return /以后|今后|往后|后续|每次|每当|一律|始终|总是|长期|默认|记住|记下|之[后後]都|\b(?:always|each|every|whenever|henceforth|remember|by default|from now on|in future|in the future|going forward)\b/iu.test(text);
|
|
12
|
+
}
|
|
13
|
+
const sentences = new Intl.Segmenter(undefined, { granularity: 'sentence' });
|
|
14
|
+
/** Include submitted formats only for claims in a standing-request sentence.
|
|
15
|
+
* A cropped quote must not turn that same instruction back into a bare rule. */
|
|
16
|
+
export function choicesForQuote(text, quote, choices) {
|
|
17
|
+
if (!choices?.length)
|
|
18
|
+
return;
|
|
19
|
+
const start = text.indexOf(quote);
|
|
20
|
+
if (start < 0)
|
|
21
|
+
return;
|
|
22
|
+
const end = start + quote.length;
|
|
23
|
+
for (const sentence of sentences.segment(text)) {
|
|
24
|
+
if (sentence.index < end && sentence.index + sentence.segment.length > start && standingRequest(sentence.segment))
|
|
25
|
+
return choices;
|
|
26
|
+
}
|
|
27
|
+
}
|
|
28
|
+
/** Both reviewers use the same reference into the native form. Unrelated
|
|
29
|
+
* options require an explicit null decision before saving a standing rule. */
|
|
30
|
+
export function resolveSelectedDirective(action, index, choices, canSelect) {
|
|
31
|
+
if (index == null) {
|
|
32
|
+
if (choices?.length && canSelect && index !== null)
|
|
33
|
+
return;
|
|
34
|
+
return { action };
|
|
35
|
+
}
|
|
36
|
+
if (!canSelect || !Number.isSafeInteger(index) || !standingRequest(action))
|
|
37
|
+
return;
|
|
38
|
+
const option = choices?.[Number(index)];
|
|
39
|
+
if (!option)
|
|
40
|
+
return;
|
|
41
|
+
const combined = selectedAction(action, option.label);
|
|
42
|
+
if (combined.length > 480)
|
|
43
|
+
return;
|
|
44
|
+
return { action: combined, selection: { directive: action, option } };
|
|
45
|
+
}
|
|
3
46
|
const record = (value) => typeof value === 'object' && value !== null && !Array.isArray(value);
|
|
4
47
|
function eligiblePrompt(text) {
|
|
5
48
|
// Unlabelled answers like "123456" cannot identify an OTP by themselves.
|
|
6
|
-
return !skipsAutomaticMemory(text) && !/\b(?:otp|pin|one[- ]time (?:code|password)|token)\b
|
|
49
|
+
return !skipsAutomaticMemory(text) && !/\b(?:otp|pin|one[- ]time (?:code|password)|token)\b|令牌|密码/iu.test(text);
|
|
7
50
|
}
|
|
8
|
-
/**
|
|
9
|
-
function
|
|
51
|
+
/** Keep user-typed text and submitted option labels distinct. */
|
|
52
|
+
function submittedForm(args, result, userSeq, callSeq, resultSeq) {
|
|
10
53
|
if (!record(args) || !Array.isArray(args.questions) || !record(result) ||
|
|
11
54
|
Object.keys(result).some(key => key !== 'answers') || !Array.isArray(result.answers) ||
|
|
12
55
|
!args.questions.length || result.answers.length !== args.questions.length)
|
|
13
|
-
return
|
|
56
|
+
return undefined;
|
|
14
57
|
const questions = new Map();
|
|
15
58
|
for (const field of args.questions) {
|
|
16
59
|
if (!record(field) || typeof field.id !== 'string' || !field.id.trim() || questions.has(field.id) ||
|
|
17
60
|
typeof field.question !== 'string' || !field.question.trim() ||
|
|
18
61
|
(field.header !== undefined && typeof field.header !== 'string'))
|
|
19
|
-
return
|
|
62
|
+
return undefined;
|
|
20
63
|
const fieldName = field.id.replace(/([a-z])([A-Z])/gu, '$1 $2').replace(/[_-]/gu, ' ');
|
|
21
64
|
questions.set(field.id, {
|
|
22
|
-
text: field.question,
|
|
65
|
+
text: field.question, options: field.options,
|
|
23
66
|
eligible: field.question.length <= 1024 && eligiblePrompt([fieldName, field.header, field.question].join(' ')),
|
|
24
67
|
});
|
|
25
68
|
}
|
|
26
69
|
let offset = 0;
|
|
27
70
|
const answers = [];
|
|
71
|
+
const selected = [];
|
|
72
|
+
let refusedBy;
|
|
28
73
|
for (const [block, answer] of result.answers.entries()) {
|
|
29
74
|
if (!record(answer) || typeof answer.id !== 'string' || !Array.isArray(answer.selected) ||
|
|
30
75
|
!answer.selected.every(label => typeof label === 'string') ||
|
|
31
76
|
(answer.custom !== undefined && typeof answer.custom !== 'string') ||
|
|
32
77
|
Object.keys(answer).some(key => !['id', 'selected', 'custom'].includes(key)))
|
|
33
|
-
return
|
|
78
|
+
return undefined;
|
|
34
79
|
const question = questions.get(answer.id);
|
|
35
80
|
if (!question)
|
|
36
|
-
return
|
|
81
|
+
return undefined;
|
|
37
82
|
questions.delete(answer.id);
|
|
38
|
-
if (typeof answer.custom !== 'string' || !answer.custom.trim())
|
|
83
|
+
if (typeof answer.custom !== 'string' || !answer.custom.trim()) {
|
|
84
|
+
const label = answer.selected.length === 1 ? answer.selected[0] : undefined;
|
|
85
|
+
if (typeof label === 'string' && label.trim() && label.length <= 480 && Array.isArray(question.options) &&
|
|
86
|
+
question.options.filter(option => record(option) && option.label === label).length === 1) {
|
|
87
|
+
if (refusesAutomaticMemory(label))
|
|
88
|
+
refusedBy = userSeq;
|
|
89
|
+
else if (question.eligible && !skipsAutomaticMemory(label))
|
|
90
|
+
selected.push({ userSeq, callSeq, resultSeq, questionId: answer.id, question: question.text, label });
|
|
91
|
+
}
|
|
39
92
|
continue;
|
|
93
|
+
}
|
|
40
94
|
// Offsets refer to the decoded custom answers joined by newlines, so escaped
|
|
41
95
|
// characters and surrogate pairs have the same UTF-16 positions during rechecking.
|
|
42
96
|
if (question.eligible || refusesAutomaticMemory(answer.custom))
|
|
43
97
|
answers.push({ question: question.text, text: answer.custom, block, offset, userSeq });
|
|
44
98
|
offset += answer.custom.length + 1;
|
|
45
99
|
}
|
|
46
|
-
return answers;
|
|
100
|
+
return { custom: answers, selected, refusedBy };
|
|
47
101
|
}
|
|
48
|
-
/**
|
|
49
|
-
export function
|
|
102
|
+
/** Only a native submitted result can supply a custom answer or an option selection. */
|
|
103
|
+
export function questionForm(session, published) {
|
|
50
104
|
if (session.header.origin === 'subagent')
|
|
51
|
-
return
|
|
52
|
-
return
|
|
105
|
+
return;
|
|
106
|
+
return verifiedQuestionForm(session.snapshotEvents(), session.inheritedEventCount, published);
|
|
107
|
+
}
|
|
108
|
+
export function questionAnswers(session, published) {
|
|
109
|
+
return questionForm(session, published)?.custom ?? [];
|
|
53
110
|
}
|
|
54
|
-
/** Accepts
|
|
55
|
-
export function
|
|
111
|
+
/** Accepts a full session snapshot or a contiguous slice of its original event sequence. */
|
|
112
|
+
export function verifiedQuestionForm(events, cut, published) {
|
|
56
113
|
if (published.type !== 'tool/result')
|
|
57
|
-
return
|
|
114
|
+
return undefined;
|
|
58
115
|
const offset = events[0]?.seq ?? 0;
|
|
59
116
|
const at = (seq) => events[seq - offset];
|
|
60
117
|
const event = at(published.seq);
|
|
61
118
|
if (event?.type !== 'tool/result' || event.surfaceOp !== 'append' ||
|
|
62
119
|
event.sourceEventSeqs?.length !== 1 || event.data.error !== undefined)
|
|
63
|
-
return
|
|
120
|
+
return undefined;
|
|
64
121
|
const { message, step, turn } = event.data;
|
|
65
122
|
const callId = message?.toolCallId;
|
|
66
123
|
if (!callId || message.role !== 'tool' || message.isError || message.source?.kind !== 'tool' ||
|
|
67
124
|
message.source.callId !== callId || !Number.isSafeInteger(step) || !Number.isSafeInteger(turn))
|
|
68
|
-
return
|
|
125
|
+
return undefined;
|
|
69
126
|
const [callSeq] = event.sourceEventSeqs;
|
|
70
127
|
const call = at(callSeq);
|
|
71
128
|
if (callSeq < cut || callSeq >= event.seq || call?.seq !== callSeq ||
|
|
72
129
|
call.type !== 'tool/call' || call.data.name !== 'ask_user_question' || call.data.callId !== callId ||
|
|
73
130
|
call.data.turn !== turn || call.data.step !== step)
|
|
74
|
-
return
|
|
131
|
+
return undefined;
|
|
75
132
|
// Replay only the local turn. A call or an opening user prompt inherited at
|
|
76
133
|
// a fork, or a change of project between prompt, question and answer, breaks attribution.
|
|
77
134
|
let start = callSeq;
|
|
78
135
|
while (start >= cut && at(start).type !== 'turn/start')
|
|
79
136
|
start--;
|
|
80
137
|
if (start < cut || at(start).data.turn !== turn)
|
|
81
|
-
return
|
|
138
|
+
return undefined;
|
|
82
139
|
let userSeq;
|
|
83
140
|
let calls = 0, results = 0;
|
|
84
141
|
for (let index = start + 1; index < offset + events.length; index++) {
|
|
85
142
|
const e = at(index);
|
|
86
143
|
if (e.type === 'turn/start' || e.type === 'turn/end') {
|
|
87
144
|
if (e.seq < event.seq)
|
|
88
|
-
return
|
|
145
|
+
return undefined;
|
|
89
146
|
break;
|
|
90
147
|
}
|
|
91
148
|
if (e.seq <= event.seq && e.type === 'working-directory/change' && userSeq !== undefined)
|
|
92
|
-
return
|
|
149
|
+
return undefined;
|
|
93
150
|
if (e.seq > callSeq && e.seq < event.seq && (e.type === 'step/start' || e.type === 'step/end'))
|
|
94
|
-
return
|
|
151
|
+
return undefined;
|
|
95
152
|
if (e.seq < event.seq && e.type === 'user/message' && e.data.source?.kind === 'user') {
|
|
96
153
|
if ((e.surfaceOp && e.surfaceOp !== 'append') || !eligiblePrompt(messageText(e.data)))
|
|
97
|
-
return
|
|
154
|
+
return undefined;
|
|
98
155
|
if (e.seq < callSeq)
|
|
99
156
|
userSeq = e.seq;
|
|
100
157
|
}
|
|
@@ -106,14 +163,14 @@ export function verifiedQuestionAnswers(events, cut, published) {
|
|
|
106
163
|
results++;
|
|
107
164
|
}
|
|
108
165
|
if (userSeq === undefined || calls !== 1 || results !== 1 || message.content?.length !== 1)
|
|
109
|
-
return
|
|
166
|
+
return undefined;
|
|
110
167
|
const [part] = message.content;
|
|
111
168
|
if (part.type !== 'text' || typeof part.text !== 'string' || typeof call.data.arguments !== 'string')
|
|
112
|
-
return
|
|
169
|
+
return undefined;
|
|
113
170
|
try {
|
|
114
|
-
return
|
|
171
|
+
return submittedForm(JSON.parse(call.data.arguments), JSON.parse(part.text), userSeq, callSeq, event.seq);
|
|
115
172
|
}
|
|
116
173
|
catch {
|
|
117
|
-
return
|
|
174
|
+
return undefined;
|
|
118
175
|
}
|
|
119
176
|
}
|
package/dist/retrieval.js
CHANGED
|
@@ -1,13 +1,14 @@
|
|
|
1
1
|
// Rank only the heads that have already passed the caller's scope and validity checks.
|
|
2
2
|
import { normalizeLabel } from "./personal.js";
|
|
3
|
+
import { encoderId, queryLanguages } from "./encoder.js";
|
|
3
4
|
import { document, language, newSearchTrace, VectorIndex } from "./vector-index.js";
|
|
4
5
|
export { newSearchTrace } from "./vector-index.js";
|
|
5
|
-
//
|
|
6
|
-
//
|
|
6
|
+
// Rank each distinct wording in its own language and retain the strongest
|
|
7
|
+
// match per revision. This also admits paraphrases in a single language.
|
|
7
8
|
function queryVariants(query, options) {
|
|
8
9
|
const primary = normalizeLabel(query || options.topic || '');
|
|
9
10
|
const alternate = normalizeLabel(options.alternateQuery ?? '');
|
|
10
|
-
return primary && alternate &&
|
|
11
|
+
return primary && alternate && primary !== alternate ? [primary, alternate] : [primary];
|
|
11
12
|
}
|
|
12
13
|
export function matchingTopics(rows, options) {
|
|
13
14
|
const subject = normalizeLabel(options.subject ?? '');
|
|
@@ -40,6 +41,15 @@ export class Retrieval {
|
|
|
40
41
|
}
|
|
41
42
|
return [...hits.values()];
|
|
42
43
|
}
|
|
44
|
+
// A foreground save only consumes matched candidates, not corpus coverage statistics.
|
|
45
|
+
// A revision with neither a lexical hit nor any passage of a requested model cannot
|
|
46
|
+
// score. Include every indexed passage, even when it shares no words with the proposal.
|
|
47
|
+
reviewRefs(domains, query, options, lexical) {
|
|
48
|
+
const langs = new Set(queryVariants(query, options).flatMap(queryLanguages));
|
|
49
|
+
const models = this.vectors.languages.filter(lang => langs.has(lang)).flatMap(lang => Array.from({ length: 8 }, (_, i) => encoderId(lang) + '/passage-' + i));
|
|
50
|
+
const refs = domains.flatMap(domain => this.store.vectorRefs(domain, models));
|
|
51
|
+
return [...new Map([...refs, ...lexical].map(row => [JSON.stringify([row.domain, row.id, row.rev]), row])).values()];
|
|
52
|
+
}
|
|
43
53
|
async search(rows, query, mode, options = {}, trace = newSearchTrace(), keywordHits) {
|
|
44
54
|
const q = normalizeLabel(query);
|
|
45
55
|
const subject = normalizeLabel(options.subject ?? '');
|
|
@@ -70,16 +80,23 @@ export class Retrieval {
|
|
|
70
80
|
trace.sqliteMs += performance.now() - started;
|
|
71
81
|
const semantic = new Map();
|
|
72
82
|
if (mode !== 'keyword') {
|
|
73
|
-
const
|
|
83
|
+
const languages = this.vectors.languages;
|
|
84
|
+
const docs = languages.length ? rows.map(row => ({ ...row, text: document(row.rule) })) : [];
|
|
74
85
|
const coverage = new Set();
|
|
75
|
-
|
|
76
|
-
|
|
86
|
+
const queries = queryVariants(q, options).flatMap(wording => queryLanguages(wording).map(lang => ({ wording, lang })));
|
|
87
|
+
if (!queries.length)
|
|
88
|
+
coverage.add('unavailable');
|
|
89
|
+
for (const { wording, lang } of queries) {
|
|
90
|
+
if (!languages.includes(lang)) {
|
|
91
|
+
coverage.add('unavailable');
|
|
92
|
+
continue;
|
|
93
|
+
}
|
|
77
94
|
if (!docs.some(doc => language(doc.text) === lang))
|
|
78
95
|
continue;
|
|
79
96
|
try {
|
|
80
|
-
const scores = await this.vectors.scores(wording, docs, trace);
|
|
97
|
+
const scores = await this.vectors.scores(wording, docs, trace, lang);
|
|
81
98
|
for (const [id, score] of scores)
|
|
82
|
-
semantic.set(id, score);
|
|
99
|
+
semantic.set(id, Math.max(score, semantic.get(id) ?? -Infinity));
|
|
83
100
|
coverage.add(trace.coverage);
|
|
84
101
|
}
|
|
85
102
|
catch {
|
|
@@ -0,0 +1,49 @@
|
|
|
1
|
+
import { isDeepStrictEqual } from 'node:util';
|
|
2
|
+
import { skipsAutomaticMemory } from "./automatic.js";
|
|
3
|
+
import { isPersonalSlot } from "./personal.js";
|
|
4
|
+
import { StoreError } from "./store.js";
|
|
5
|
+
function isAgreement(rule) {
|
|
6
|
+
return Boolean(rule.semanticTopic) && (rule.kind === 'rule' || rule.kind === 'preference');
|
|
7
|
+
}
|
|
8
|
+
/** Bind a follow-up such as "I meant this project" to the actual agreement from
|
|
9
|
+
* the preceding turn. An assistant-supplied ID alone cannot authorize moving it. */
|
|
10
|
+
export function previousScopeAgreement(memory, agent, project, ref, generation, turn) {
|
|
11
|
+
const old = memory.current(memory.personal, ref.id);
|
|
12
|
+
if (!old || old.source.sessionId !== agent.id || old.source.storeId !== memory.storeId(agent.session))
|
|
13
|
+
throw new StoreError('target_not_found');
|
|
14
|
+
if (old.rev !== ref.rev)
|
|
15
|
+
throw new StoreError('stale_revision');
|
|
16
|
+
if (!isPersonalSlot(old.slot) || !isAgreement(old) ||
|
|
17
|
+
old.channel !== 'automatic' || old.pinned || old.usageOverride || old.sensitive || old.localException ||
|
|
18
|
+
old.quoteType !== 'user_quote' || !old.evidence ||
|
|
19
|
+
skipsAutomaticMemory([old.action, old.user_quote, old.when, old.exceptions, old.semanticTopic,
|
|
20
|
+
old.subject, ...(old.keywords ?? [])].join('\n')))
|
|
21
|
+
throw new StoreError('protected_revision');
|
|
22
|
+
const starts = agent.session.snapshotEvents().slice(agent.session.inheritedEventCount)
|
|
23
|
+
.filter(event => event.type === 'turn/start').slice(-2);
|
|
24
|
+
if (starts.length !== 2 || String(starts[1].data.turn) !== turn || String(starts[0].data.turn) !== old.source.turnId)
|
|
25
|
+
throw new StoreError('invalid_source');
|
|
26
|
+
const prior = memory.proposalSources(agent, agent, project, old.source.turnId, generation);
|
|
27
|
+
const span = old.evidence;
|
|
28
|
+
const block = prior.events.find(event => {
|
|
29
|
+
const start = span.start - (event.offset ?? 0);
|
|
30
|
+
return event.seq === old.source.seq && event.seq === span.seq && start >= 0 &&
|
|
31
|
+
event.text.slice(start, start + span.end - span.start) === old.user_quote &&
|
|
32
|
+
(!old.source.formSelection || event.formSelections?.some(option => isDeepStrictEqual(option, old.source.formSelection)));
|
|
33
|
+
});
|
|
34
|
+
if (prior.reason || !block)
|
|
35
|
+
throw new StoreError(prior.reason ?? 'invalid_source');
|
|
36
|
+
if (!memory.store.soleTurnAgreement([project.id, memory.personal.id], old.source, ref))
|
|
37
|
+
throw new StoreError('ambiguous_topic');
|
|
38
|
+
return old;
|
|
39
|
+
}
|
|
40
|
+
/** Project the saved agreement. The second proposal supplies only a clarification,
|
|
41
|
+
* never a new body, a new subject, or model-invented path restrictions. */
|
|
42
|
+
export function projectAgreement(old) {
|
|
43
|
+
return {
|
|
44
|
+
scope: 'project', kind: old.kind, topic: old.semanticTopic,
|
|
45
|
+
action: old.action, user_quote: old.user_quote, subject: old.subject, when: old.when,
|
|
46
|
+
exceptions: old.exceptions, paths: old.paths, keywords: old.keywords ?? [],
|
|
47
|
+
usage: old.usage ?? 'on_demand', sensitive: false, conflicts_with_repo_guidance: false,
|
|
48
|
+
};
|
|
49
|
+
}
|
package/dist/search-index.js
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { encoderId } from "./encoder.js";
|
|
1
|
+
import { encoderId, language } from "./encoder.js";
|
|
2
2
|
import { isKnowledge } from "./knowledge.js";
|
|
3
3
|
import { normalizeLabel } from "./personal.js";
|
|
4
4
|
import { searchWords } from "./search-words.js";
|
|
@@ -13,12 +13,27 @@ export function document(rule) {
|
|
|
13
13
|
// The second column indexes codepoint positions and supports literal substring phrases of any length.
|
|
14
14
|
export const indexWords = (text) => searchWords(text).map(word => Buffer.from(word).toString('hex'));
|
|
15
15
|
const characters = (text) => Array.from(text, char => char.codePointAt(0).toString(16)).join(' ');
|
|
16
|
-
|
|
17
|
-
|
|
18
|
-
const
|
|
19
|
-
|
|
20
|
-
|
|
21
|
-
|
|
16
|
+
function indexLabels(db, domain, rid, rule) {
|
|
17
|
+
const canonical = normalizeLabel(rule.semanticTopic ?? '');
|
|
18
|
+
const aliases = new Set([canonical, ...(rule.keywords ?? []).map(normalizeLabel)]);
|
|
19
|
+
aliases.delete('');
|
|
20
|
+
if (!aliases.size)
|
|
21
|
+
return;
|
|
22
|
+
const subject = normalizeLabel(rule.subject ?? '');
|
|
23
|
+
const insert = db.prepare('INSERT INTO memory_topic_labels(domain,label,subject,rid,canonical) VALUES(?,?,?,?,?)');
|
|
24
|
+
for (const label of aliases)
|
|
25
|
+
insert.run(domain, label, subject, rid, Number(label === canonical));
|
|
26
|
+
}
|
|
27
|
+
// Each derived row belongs to the stable primary key of its source revision.
|
|
28
|
+
export function indexRevision(db, domain, rid, rule) {
|
|
29
|
+
indexLabels(db, domain, rid, rule);
|
|
30
|
+
const content = document(rule);
|
|
31
|
+
const text = normalizeLabel(content);
|
|
32
|
+
const labels = rule.sensitive || rule.usage !== 'on_demand' ? '' :
|
|
33
|
+
normalizeLabel([rule.semanticTopic, ...(rule.keywords ?? [])].filter(Boolean).join(' '));
|
|
34
|
+
db.prepare('INSERT INTO memory_fts(rowid,words,chars,labels) VALUES(?,?,?,?)')
|
|
35
|
+
.run(rid, indexWords(text).join(' '), characters(text), indexWords(labels).join(' '));
|
|
36
|
+
db.prepare('INSERT INTO memory_vector_jobs(rid,language) VALUES(?,?)').run(rid, language(content));
|
|
22
37
|
}
|
|
23
38
|
export function promptRole(rule) {
|
|
24
39
|
return isKnowledge(rule) ? null : Number(rule.usage === 'proactive' && !rule.sensitive);
|
|
@@ -33,10 +48,11 @@ export class SearchIndex {
|
|
|
33
48
|
CREATE INDEX revision_current_slot ON revisions(domain,slot)
|
|
34
49
|
WHERE state='confirmed' AND slot IS NOT NULL;
|
|
35
50
|
CREATE INDEX revision_prompt_role ON revisions(domain,proactive) WHERE state='confirmed';
|
|
36
|
-
CREATE VIRTUAL TABLE memory_fts USING fts5(words,chars,content='',contentless_delete=1);
|
|
51
|
+
CREATE VIRTUAL TABLE memory_fts USING fts5(words,chars,labels,content='',contentless_delete=1);
|
|
37
52
|
INSERT INTO memory_fts(memory_fts,rank) VALUES('secure-delete',1);
|
|
38
|
-
CREATE TABLE memory_vector_jobs (rid INTEGER PRIMARY KEY, available INTEGER NOT NULL DEFAULT 0);
|
|
53
|
+
CREATE TABLE memory_vector_jobs (rid INTEGER PRIMARY KEY, available INTEGER NOT NULL DEFAULT 0, language TEXT NOT NULL);
|
|
39
54
|
CREATE INDEX memory_vector_ready ON memory_vector_jobs(available,rid);
|
|
55
|
+
CREATE INDEX memory_vector_language_ready ON memory_vector_jobs(language,available,rid);
|
|
40
56
|
CREATE TABLE memory_vector_format (version TEXT PRIMARY KEY);
|
|
41
57
|
CREATE TRIGGER remove_retired_search AFTER UPDATE OF state ON revisions WHEN OLD.state='confirmed' AND NEW.state<>'confirmed' BEGIN
|
|
42
58
|
DELETE FROM memory_fts WHERE rowid=NEW.rid;
|
|
@@ -44,13 +60,77 @@ export class SearchIndex {
|
|
|
44
60
|
END;
|
|
45
61
|
`);
|
|
46
62
|
}
|
|
63
|
+
ensureTopicLabels() {
|
|
64
|
+
if (this.db.prepare("SELECT 1 FROM sqlite_schema WHERE type='table' AND name='memory_topic_labels'").get()) {
|
|
65
|
+
const pending = this.db.prepare(`SELECT r.rid,r.domain,r.payload FROM memory_unindexed_topics u
|
|
66
|
+
CROSS JOIN revisions r ON u.rid=r.rid AND r.state='confirmed'`);
|
|
67
|
+
for (const row of pending.iterate())
|
|
68
|
+
indexLabels(this.db, String(row.domain), Number(row.rid), JSON.parse(String(row.payload)));
|
|
69
|
+
this.db.exec('DELETE FROM memory_unindexed_topics');
|
|
70
|
+
return;
|
|
71
|
+
}
|
|
72
|
+
// Backfill once, under the same write transaction as initialization. Retired revisions
|
|
73
|
+
// never contribute aliases and consent cleanup removes their derived labels atomically.
|
|
74
|
+
// An older CLI sharing the same database can write FTS without knowing this index.
|
|
75
|
+
// The heads trigger marks just those revisions. New writers have already indexed
|
|
76
|
+
// their labels before they publish a head. A reader includes pending rows immediately.
|
|
77
|
+
const queueUnindexed = `INSERT OR IGNORE INTO memory_unindexed_topics(domain,rid)
|
|
78
|
+
SELECT r.domain,r.rid FROM revisions r WHERE r.domain=NEW.domain AND r.id=NEW.id AND r.rev=NEW.rev AND r.state='confirmed'
|
|
79
|
+
AND (json_type(r.payload,'$.semanticTopic')='text' OR json_array_length(r.payload,'$.keywords')>0)
|
|
80
|
+
AND NOT EXISTS(SELECT 1 FROM memory_topic_labels l WHERE l.rid=r.rid);`;
|
|
81
|
+
this.db.exec(`CREATE TABLE memory_topic_labels (
|
|
82
|
+
domain TEXT NOT NULL, label TEXT NOT NULL, subject TEXT NOT NULL, rid INTEGER NOT NULL,
|
|
83
|
+
canonical INTEGER NOT NULL, PRIMARY KEY(domain,label,subject,rid)
|
|
84
|
+
) WITHOUT ROWID;
|
|
85
|
+
CREATE INDEX memory_topic_revision ON memory_topic_labels(rid);
|
|
86
|
+
CREATE TABLE memory_unindexed_topics(domain TEXT NOT NULL,rid INTEGER NOT NULL,PRIMARY KEY(domain,rid)) WITHOUT ROWID;
|
|
87
|
+
CREATE TRIGGER queue_legacy_topic_insert AFTER INSERT ON heads BEGIN ${queueUnindexed} END;
|
|
88
|
+
CREATE TRIGGER queue_legacy_topic_update AFTER UPDATE OF rev ON heads BEGIN ${queueUnindexed} END;
|
|
89
|
+
CREATE INDEX memory_scope_vector_models ON memory_vectors(domain,model,id,rev);
|
|
90
|
+
CREATE TRIGGER retire_topic_labels AFTER UPDATE OF state ON revisions
|
|
91
|
+
WHEN OLD.state='confirmed' AND NEW.state<>'confirmed'
|
|
92
|
+
BEGIN DELETE FROM memory_topic_labels WHERE rid=OLD.rid;
|
|
93
|
+
DELETE FROM memory_unindexed_topics WHERE domain=OLD.domain AND rid=OLD.rid; END;`);
|
|
94
|
+
const heads = this.db.prepare(`SELECT r.domain,r.rid,r.payload FROM heads h
|
|
95
|
+
CROSS JOIN revisions r USING(domain,id,rev) WHERE r.state='confirmed'`);
|
|
96
|
+
for (const row of heads.iterate())
|
|
97
|
+
indexLabels(this.db, String(row.domain), Number(row.rid), JSON.parse(String(row.payload)));
|
|
98
|
+
}
|
|
99
|
+
topicRefs(domain, topic, subject, canonicalScope) {
|
|
100
|
+
const hasSubject = canonicalScope !== undefined || subject !== undefined;
|
|
101
|
+
const slot = canonicalScope === 'global' ? " AND r.slot GLOB 'profile.topic.*'" :
|
|
102
|
+
canonicalScope === 'project' ? " AND r.slot GLOB 'project.topic.*'" : '';
|
|
103
|
+
const normalized = normalizeLabel(topic);
|
|
104
|
+
const owner = normalizeLabel(subject ?? '');
|
|
105
|
+
const rows = this.db.prepare(`SELECT r.id,r.rev,r.confirmed,NULL AS pending FROM memory_topic_labels l
|
|
106
|
+
CROSS JOIN revisions r ON r.rid=l.rid CROSS JOIN heads h ON h.domain=r.domain AND h.id=r.id AND h.rev=r.rev
|
|
107
|
+
WHERE l.domain=? AND l.label=? ${hasSubject ? 'AND l.subject=?' : ''}${canonicalScope ? ' AND l.canonical=1' : ''}${slot}
|
|
108
|
+
AND r.state='confirmed'
|
|
109
|
+
UNION ALL SELECT r.id,r.rev,r.confirmed,r.payload AS pending FROM memory_unindexed_topics u
|
|
110
|
+
CROSS JOIN revisions r ON r.rid=u.rid CROSS JOIN heads h ON h.domain=r.domain AND h.id=r.id AND h.rev=r.rev
|
|
111
|
+
WHERE u.domain=? AND r.state='confirmed'${slot} ORDER BY 3 DESC,1`)
|
|
112
|
+
.all(domain, normalized, ...(hasSubject ? [owner] : []), domain);
|
|
113
|
+
return rows.flatMap(row => {
|
|
114
|
+
if (row.pending) {
|
|
115
|
+
const rule = JSON.parse(String(row.pending));
|
|
116
|
+
if (hasSubject && normalizeLabel(rule.subject ?? '') !== owner)
|
|
117
|
+
return [];
|
|
118
|
+
const labels = canonicalScope ? [rule.semanticTopic] : [rule.semanticTopic, ...(rule.keywords ?? [])];
|
|
119
|
+
if (!labels.some(label => label && normalizeLabel(label) === normalized))
|
|
120
|
+
return [];
|
|
121
|
+
}
|
|
122
|
+
return [{ domain, id: String(row.id), rev: Number(row.rev) }];
|
|
123
|
+
});
|
|
124
|
+
}
|
|
47
125
|
syncVectorFormat() {
|
|
48
126
|
// Changing the encoder or passage layout requeues current revisions, including completed jobs.
|
|
49
127
|
const version = [encoderId('en'), encoderId('zh'), 'passages-v1'].join('|');
|
|
50
128
|
if (!this.db.prepare('SELECT 1 FROM memory_vector_format WHERE version=?').get(version)) {
|
|
51
|
-
this.db.exec(
|
|
52
|
-
|
|
53
|
-
|
|
129
|
+
this.db.exec('DELETE FROM memory_vector_format');
|
|
130
|
+
const heads = this.db.prepare("SELECT r.rid,r.payload FROM heads h JOIN revisions r USING(domain,id,rev) WHERE r.state='confirmed'");
|
|
131
|
+
const enqueue = this.db.prepare('INSERT OR IGNORE INTO memory_vector_jobs(rid,language) VALUES(?,?)');
|
|
132
|
+
for (const row of heads.iterate())
|
|
133
|
+
enqueue.run(row.rid, language(document(JSON.parse(String(row.payload)))));
|
|
54
134
|
this.db.prepare('INSERT INTO memory_vector_format VALUES(?)').run(version);
|
|
55
135
|
}
|
|
56
136
|
}
|
|
@@ -76,7 +156,7 @@ export class SearchIndex {
|
|
|
76
156
|
}
|
|
77
157
|
};
|
|
78
158
|
if (terms.length)
|
|
79
|
-
collect('words:(' + terms.join(' OR ') + ')', '-bm25(memory_fts,1,0)');
|
|
159
|
+
collect('words:(' + terms.join(' OR ') + ')', '-bm25(memory_fts,1,0,0)');
|
|
80
160
|
if (q)
|
|
81
161
|
collect('chars:"' + characters(q) + '"', '3');
|
|
82
162
|
return [...hits.values()];
|