dsh-memory-bond 0.3.0-beta.0 → 1.0.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +6 -7
- package/README.md +125 -91
- package/README.zh-CN.md +122 -92
- package/SECURITY.md +29 -0
- package/dist/audit.js +155 -80
- package/dist/automatic.js +10 -2
- package/dist/client.js +2035 -0
- package/dist/command-scope.js +4 -4
- package/dist/commands.js +15 -9
- package/dist/consolidation-store.js +87 -20
- package/dist/consolidation.js +2 -6
- package/dist/domain.js +8 -4
- package/dist/encoder.js +46 -5
- package/dist/file-import-store.js +120 -0
- package/dist/file-import.js +265 -0
- package/dist/foreground-attempts.js +91 -0
- package/dist/guidance.js +133 -92
- package/dist/host.js +13 -0
- package/dist/index-policy.js +91 -48
- package/dist/index.js +102 -40
- package/dist/knowledge-hooks.js +70 -27
- package/dist/knowledge.js +2 -3
- package/dist/maintenance-store.js +38 -4
- package/dist/maintenance.js +29 -5
- package/dist/personal.js +37 -0
- package/dist/policy.js +45 -47
- package/dist/prompt-copy.js +93 -0
- package/dist/proposal-receipts.js +70 -0
- package/dist/proposal-review.js +656 -0
- package/dist/propose-contract.js +32 -36
- package/dist/question-answers.js +86 -29
- package/dist/retrieval.js +25 -8
- package/dist/scope-narrowing.js +49 -0
- package/dist/search-index.js +93 -13
- package/dist/semantic.js +69 -207
- package/dist/service.js +633 -204
- package/dist/sharing.js +7 -13
- package/dist/sources.js +28 -3
- package/dist/store.js +432 -96
- package/dist/tool-experience.js +87 -0
- package/dist/turn-review-store.js +83 -16
- package/dist/turn-review.js +155 -59
- package/dist/ui.js +128 -26
- package/dist/vector-index.js +69 -33
- package/docs/architecture.zh-CN.md +52 -0
- package/docs/benchmark.zh-CN.md +60 -0
- package/docs/benchmarks/repository-tasks.json +5355 -0
- package/docs/images/bond-memory-principle-en.svg +644 -0
- package/docs/images/bond-memory-principle-zh.svg +644 -0
- package/docs/images/bond-memory-principle.drawio +644 -0
- package/docs/images/memory-settings-en.png +0 -0
- package/docs/images/memory-settings-zh.png +0 -0
- package/docs/images/memory-turn-recalled-en.png +0 -0
- package/docs/images/memory-turn-recalled-zh.png +0 -0
- package/docs/images/memory-turn-saved-en.png +0 -0
- package/docs/images/memory-turn-saved-zh.png +0 -0
- package/docs/media/memory-bond-name-en.gif +0 -0
- package/docs/media/memory-bond-name-en.mp4 +0 -0
- package/docs/media/memory-bond-name-zh.gif +0 -0
- package/docs/media/memory-bond-name-zh.mp4 +0 -0
- package/locale/detail.en.md +5 -1
- package/locale/detail.zh.md +5 -1
- package/locale/en.json +338 -0
- package/locale/zh.json +338 -0
- package/native/embeddings/NOTICE.md +2 -2
- package/package.json +39 -19
- package/scripts/benchmark-bond.mjs +72 -0
- package/scripts/benchmark-conditions.mjs +144 -0
- package/scripts/benchmark-example.mjs +37 -0
- package/scripts/benchmark-scale.mjs +119 -0
- package/scripts/benchmark-scenarios.mjs +57 -0
- package/scripts/benchmark-tasks.mjs +244 -0
- package/src/audit.ts +144 -85
- package/src/automatic.ts +12 -2
- package/src/command-scope.ts +4 -4
- package/src/commands.ts +12 -8
- package/src/consolidation-store.ts +80 -18
- package/src/consolidation.ts +2 -6
- package/src/domain.ts +9 -4
- package/src/encoder.ts +46 -6
- package/src/file-import-store.ts +139 -0
- package/src/file-import.ts +256 -0
- package/src/foreground-attempts.ts +97 -0
- package/src/guidance.ts +138 -102
- package/src/host.ts +22 -2
- package/src/index-policy.ts +93 -46
- package/src/index.ts +87 -43
- package/src/knowledge-hooks.ts +71 -29
- package/src/knowledge.ts +2 -3
- package/src/maintenance-store.ts +37 -4
- package/src/maintenance.ts +25 -5
- package/src/personal.ts +36 -0
- package/src/policy.ts +55 -52
- package/src/prompt-copy.ts +99 -0
- package/src/proposal-receipts.ts +59 -0
- package/src/proposal-review.ts +614 -0
- package/src/propose-contract.ts +31 -35
- package/src/question-answers.ts +99 -29
- package/src/retrieval.ts +26 -9
- package/src/scope-narrowing.ts +58 -0
- package/src/search-index.ts +94 -14
- package/src/semantic.ts +67 -188
- package/src/service.ts +595 -210
- package/src/sharing.ts +7 -14
- package/src/sources.ts +26 -4
- package/src/store.ts +434 -97
- package/src/tool-experience.ts +93 -0
- package/src/turn-review-store.ts +86 -15
- package/src/turn-review.ts +142 -60
- package/src/ui.ts +122 -27
- package/src/vector-index.ts +57 -29
- package/client/index.js +0 -1186
- package/design/dsh-memory-plugin-design.md +0 -46
- package/design/dsh-memory-plugin-evaluation.md +0 -135
- package/design/evaluations/locomo-conv-26-2026-12-03.json +0 -252
- package/design/evaluations/locomo-conv-26-paired-2026-12-03.json +0 -549
- package/design/evaluations/locomo-conv-26-write-replay-2026-12-03.json +0 -289
- package/design/evaluations/project-memory-tasks-2026-12-03.json +0 -1059
- package/design/memory-lifecycle-consolidation.excalidraw +0 -1212
- package/design/memory-lifecycle-consolidation.mobile.excalidraw +0 -1083
- package/design/memory-lifecycle-consolidation.mobile.svg +0 -2
- package/design/memory-lifecycle-consolidation.mobile.zh-CN.excalidraw +0 -1083
- package/design/memory-lifecycle-consolidation.mobile.zh-CN.svg +0 -94
- package/design/memory-lifecycle-consolidation.svg +0 -2
- package/design/memory-lifecycle-consolidation.zh-CN.excalidraw +0 -1212
- package/design/memory-lifecycle-consolidation.zh-CN.svg +0 -94
- package/design/memory-lifecycle.excalidraw +0 -2105
- package/design/memory-lifecycle.mobile.excalidraw +0 -1896
- package/design/memory-lifecycle.mobile.svg +0 -95
- package/design/memory-lifecycle.mobile.zh-CN.excalidraw +0 -1896
- package/design/memory-lifecycle.mobile.zh-CN.svg +0 -97
- package/design/memory-lifecycle.svg +0 -95
- package/design/memory-lifecycle.zh-CN.excalidraw +0 -2105
- package/design/memory-lifecycle.zh-CN.svg +0 -97
- package/native/embeddings/LICENSE +0 -21
- package/native/embeddings/en/model.onnx +0 -4
- package/native/embeddings/en/vocab.txt +0 -30522
- package/native/embeddings/runtime/LICENSE +0 -21
- package/native/embeddings/runtime/ThirdPartyNotices.txt +0 -6156
- package/native/embeddings/runtime/ort-wasm-simd-threaded.mjs +0 -70
- package/native/embeddings/runtime/ort-wasm-simd-threaded.wasm +0 -0
- package/native/embeddings/runtime/ort.wasm.min.mjs +0 -7
- package/native/embeddings/worker.mjs +0 -97
- package/native/embeddings/zh/model.onnx +0 -0
- package/native/embeddings/zh/vocab.txt +0 -21128
|
@@ -0,0 +1,87 @@
|
|
|
1
|
+
import { skipsAutomaticMemory } from "./automatic.js";
|
|
2
|
+
import { bashScope } from "./command-scope.js";
|
|
3
|
+
function currentTurn(agent) {
|
|
4
|
+
const events = agent.session.snapshotEvents();
|
|
5
|
+
const start = events.findLast(e => e.type === 'turn/start' || e.type === 'turn/end');
|
|
6
|
+
if (start?.type !== 'turn/start' || start.seq < agent.session.inheritedEventCount ||
|
|
7
|
+
!Number.isSafeInteger(start.data.turn))
|
|
8
|
+
return;
|
|
9
|
+
return { start, events: events.slice(start.seq + 1) };
|
|
10
|
+
}
|
|
11
|
+
export function originalBashCall(agent, callId) {
|
|
12
|
+
const turn = currentTurn(agent);
|
|
13
|
+
if (!turn)
|
|
14
|
+
return;
|
|
15
|
+
const calls = turn.events.filter(e => e.type === 'tool/call' && e.data.callId === callId);
|
|
16
|
+
const call = calls[0];
|
|
17
|
+
if (calls.length === 1 && call.data.name === 'bash' && call.data.turn === turn.start.data.turn &&
|
|
18
|
+
Number.isSafeInteger(call.data.step))
|
|
19
|
+
return { callSeq: call.seq, turnStart: turn.start.seq };
|
|
20
|
+
}
|
|
21
|
+
// The session log can locate a call, but only the native execution hooks can attest its exit status.
|
|
22
|
+
export class ToolExperienceEvidence {
|
|
23
|
+
byAgent = new WeakMap();
|
|
24
|
+
hasObservations(agent) { return !!this.byAgent.get(agent)?.size; }
|
|
25
|
+
endTurn(agent) { this.byAgent.delete(agent); }
|
|
26
|
+
observe(agent, callId, item) {
|
|
27
|
+
if (agent.session.header.origin === 'subagent' || !callId || callId.length > 128 || item.workdir.length > 512 ||
|
|
28
|
+
item.command.length > 512 || skipsAutomaticMemory([callId, item.command, item.workdir].join('\n')))
|
|
29
|
+
return;
|
|
30
|
+
const turn = currentTurn(agent);
|
|
31
|
+
const call = turn?.events.find(e => e.seq === item.callSeq);
|
|
32
|
+
if (!call || turn?.start.seq !== item.turnStart)
|
|
33
|
+
return;
|
|
34
|
+
try {
|
|
35
|
+
const args = JSON.parse(call.data.arguments ?? '');
|
|
36
|
+
const scope = bashScope(item.domain, args.command, args.workdir);
|
|
37
|
+
if (scope?.command !== item.command || scope.cwd !== item.cwd)
|
|
38
|
+
return;
|
|
39
|
+
}
|
|
40
|
+
catch {
|
|
41
|
+
return;
|
|
42
|
+
}
|
|
43
|
+
let table = this.byAgent.get(agent);
|
|
44
|
+
if (!table)
|
|
45
|
+
this.byAgent.set(agent, table = new Map());
|
|
46
|
+
table.set(callId, item);
|
|
47
|
+
if (table.size > 64)
|
|
48
|
+
table.delete(table.keys().next().value);
|
|
49
|
+
}
|
|
50
|
+
source(agent, domain, generation, storeId, callId) {
|
|
51
|
+
const table = this.byAgent.get(agent);
|
|
52
|
+
if (!table?.size)
|
|
53
|
+
return;
|
|
54
|
+
const turn = currentTurn(agent);
|
|
55
|
+
if (!turn)
|
|
56
|
+
return;
|
|
57
|
+
for (const [id, item] of table) {
|
|
58
|
+
if (item.turnStart !== turn.start.seq || item.generation !== generation || storeId !== item.storeId || domain.id !== item.domain.id ||
|
|
59
|
+
domain.root !== item.domain.root || domain.cwd !== item.domain.cwd) {
|
|
60
|
+
table.delete(id);
|
|
61
|
+
continue;
|
|
62
|
+
}
|
|
63
|
+
if (callId !== undefined && id !== callId)
|
|
64
|
+
continue;
|
|
65
|
+
const call = turn.events.find(e => e.seq === item.callSeq);
|
|
66
|
+
if (!call || turn.events.some(e => e.seq > call.seq &&
|
|
67
|
+
(e.type === 'working-directory/change' || (e.type === 'tool/call' && e.data.callId === id))))
|
|
68
|
+
continue;
|
|
69
|
+
const results = turn.events.filter(e => e.type === 'tool/result' && e.data.message?.toolCallId === id);
|
|
70
|
+
if (results.length !== 1 || !originalResult(results[0], call, id))
|
|
71
|
+
continue;
|
|
72
|
+
const result = results[0];
|
|
73
|
+
return {
|
|
74
|
+
origin: 'tool', storeId, sessionId: agent.session.id, turnId: String(turn.start.data.turn), seq: result.seq,
|
|
75
|
+
toolResult: { callId: id, callSeq: call.seq, resultSeq: result.seq, command: item.command,
|
|
76
|
+
workdir: item.workdir, exitCode: item.exitCode },
|
|
77
|
+
};
|
|
78
|
+
}
|
|
79
|
+
}
|
|
80
|
+
}
|
|
81
|
+
function originalResult(result, call, callId) {
|
|
82
|
+
const message = result.data.message;
|
|
83
|
+
return result.seq > call.seq && result.surfaceOp === 'append' && result.sourceEventSeqs?.length === 1 &&
|
|
84
|
+
result.sourceEventSeqs[0] === call.seq && result.data.turn === call.data.turn && result.data.step === call.data.step &&
|
|
85
|
+
result.data.error === undefined && message?.role === 'tool' && !message.isError &&
|
|
86
|
+
message.source?.kind === 'tool' && message.source.callId === callId;
|
|
87
|
+
}
|
|
@@ -1,4 +1,6 @@
|
|
|
1
1
|
import { createHash, randomUUID } from 'node:crypto';
|
|
2
|
+
export const foregroundAttemptLimit = 3;
|
|
3
|
+
const foregroundRetentionDays = 30;
|
|
2
4
|
function turnKey(domain, session, turn, store) {
|
|
3
5
|
return createHash('sha256').update(JSON.stringify([domain, session, turn, store])).digest('hex');
|
|
4
6
|
}
|
|
@@ -10,27 +12,97 @@ export class ReviewLedger {
|
|
|
10
12
|
db.exec(`CREATE TABLE IF NOT EXISTS turn_review_usage (
|
|
11
13
|
turn_key TEXT PRIMARY KEY, day INTEGER NOT NULL, batch TEXT NOT NULL
|
|
12
14
|
); CREATE INDEX IF NOT EXISTS turn_review_day ON turn_review_usage(day,batch);
|
|
13
|
-
CREATE TABLE IF NOT EXISTS
|
|
15
|
+
CREATE TABLE IF NOT EXISTS turn_review_spans (
|
|
14
16
|
turn_key TEXT NOT NULL, seq INTEGER NOT NULL, start INTEGER NOT NULL, end INTEGER NOT NULL,
|
|
15
17
|
day INTEGER NOT NULL, PRIMARY KEY(turn_key,seq,start,end)
|
|
16
|
-
); CREATE INDEX IF NOT EXISTS
|
|
18
|
+
); CREATE INDEX IF NOT EXISTS turn_review_span_day ON turn_review_spans(day);
|
|
19
|
+
CREATE TABLE IF NOT EXISTS foreground_review_usage (
|
|
20
|
+
evidence_key TEXT PRIMARY KEY CHECK(length(evidence_key)=64 AND evidence_key NOT GLOB '*[^0-9a-f]*'),
|
|
21
|
+
day INTEGER NOT NULL,
|
|
22
|
+
attempts INTEGER NOT NULL CHECK(attempts BETWEEN 1 AND ${foregroundAttemptLimit})
|
|
23
|
+
) WITHOUT ROWID;
|
|
24
|
+
CREATE INDEX IF NOT EXISTS foreground_review_day ON foreground_review_usage(day);
|
|
25
|
+
CREATE INDEX IF NOT EXISTS foreground_review_stopped ON foreground_review_usage(day)
|
|
26
|
+
WHERE attempts=${foregroundAttemptLimit}`);
|
|
17
27
|
}
|
|
18
|
-
|
|
19
|
-
|
|
20
|
-
|
|
28
|
+
immediate(run) {
|
|
29
|
+
this.db.exec('BEGIN IMMEDIATE');
|
|
30
|
+
try {
|
|
31
|
+
const result = run();
|
|
32
|
+
this.db.exec('COMMIT');
|
|
33
|
+
return result;
|
|
34
|
+
}
|
|
35
|
+
catch (error) {
|
|
36
|
+
this.db.exec('ROLLBACK');
|
|
37
|
+
throw error;
|
|
38
|
+
}
|
|
39
|
+
}
|
|
40
|
+
foregroundUsage(evidence, day) {
|
|
41
|
+
const row = this.db.prepare(`SELECT MAX(attempts) AS used FROM foreground_review_usage
|
|
42
|
+
WHERE evidence_key IN (SELECT value FROM json_each(?)) AND day>=?`).get(evidence, day - foregroundRetentionDays);
|
|
43
|
+
return Number(row.used ?? 0);
|
|
44
|
+
}
|
|
45
|
+
/** Cheap early check before candidate retrieval. The reservation remains authoritative under concurrent writes. */
|
|
46
|
+
foregroundExhausted(keys) {
|
|
47
|
+
return keys.length > 0 && this.foregroundUsage(JSON.stringify(keys), Math.floor(Date.now() / 86_400_000)) >= foregroundAttemptLimit;
|
|
48
|
+
}
|
|
49
|
+
hasExhaustedForeground() {
|
|
50
|
+
return !!this.db.prepare(`SELECT 1 FROM foreground_review_usage
|
|
51
|
+
WHERE attempts=${foregroundAttemptLimit} AND day>=? LIMIT 1`).get(Math.floor(Date.now() / 86_400_000) - foregroundRetentionDays);
|
|
52
|
+
}
|
|
53
|
+
exhaustedForegroundKeys(keys) {
|
|
54
|
+
if (!keys.length)
|
|
55
|
+
return new Set();
|
|
56
|
+
const cutoff = Math.floor(Date.now() / 86_400_000) - foregroundRetentionDays;
|
|
57
|
+
const rows = this.db.prepare(`SELECT f.evidence_key FROM json_each(?) k CROSS JOIN foreground_review_usage f
|
|
58
|
+
ON f.evidence_key=k.value WHERE f.attempts=${foregroundAttemptLimit} AND f.day>=?`).all(JSON.stringify(keys), cutoff);
|
|
59
|
+
return new Set(rows.map(row => String(row.evidence_key)));
|
|
60
|
+
}
|
|
61
|
+
/** Reserve each distinct evidence digest once, or none if any is exhausted. */
|
|
62
|
+
reserveForeground(keys) {
|
|
63
|
+
if (!keys.length)
|
|
64
|
+
return 0;
|
|
65
|
+
const evidence = JSON.stringify([...new Set(keys)]);
|
|
66
|
+
const day = Math.floor(Date.now() / 86_400_000);
|
|
67
|
+
return this.immediate(() => {
|
|
68
|
+
// As with turn-review claims, keep recent failures across restarts and prune old accounting.
|
|
69
|
+
this.db.prepare('DELETE FROM foreground_review_usage WHERE day < ?').run(day - foregroundRetentionDays);
|
|
70
|
+
const used = this.foregroundUsage(evidence, day);
|
|
71
|
+
if (used >= foregroundAttemptLimit)
|
|
72
|
+
return 0;
|
|
73
|
+
this.db.prepare(`INSERT INTO foreground_review_usage(evidence_key,day,attempts)
|
|
74
|
+
SELECT value,?,1 FROM json_each(?) WHERE true
|
|
75
|
+
ON CONFLICT(evidence_key) DO UPDATE SET attempts=attempts+1,day=excluded.day`).run(day, evidence);
|
|
76
|
+
return used + 1;
|
|
77
|
+
});
|
|
78
|
+
}
|
|
79
|
+
/** A completed save refunds only its own claim, preserving overlapping failed or in-flight attempts. */
|
|
80
|
+
releaseForeground(keys) {
|
|
81
|
+
if (!keys.length)
|
|
82
|
+
return;
|
|
83
|
+
const evidence = JSON.stringify(keys);
|
|
84
|
+
this.immediate(() => {
|
|
85
|
+
this.db.prepare(`DELETE FROM foreground_review_usage WHERE attempts=1
|
|
86
|
+
AND evidence_key IN (SELECT value FROM json_each(?))`).run(evidence);
|
|
87
|
+
this.db.prepare(`UPDATE foreground_review_usage SET attempts=attempts-1
|
|
88
|
+
WHERE evidence_key IN (SELECT value FROM json_each(?))`).run(evidence);
|
|
89
|
+
});
|
|
90
|
+
}
|
|
91
|
+
// Restatements and explicit semantic exclusions have no new revision from which
|
|
92
|
+
// to recover their offsets. Keep only these ranges for subsequent turn review.
|
|
93
|
+
noteHandled(domain, source, spans) {
|
|
21
94
|
if (!spans.length)
|
|
22
95
|
return;
|
|
23
96
|
const key = turnKey(domain, source.sessionId, source.turnId, source.storeId);
|
|
24
97
|
const day = Math.floor(Date.now() / 86_400_000);
|
|
25
|
-
this.db.prepare('DELETE FROM
|
|
26
|
-
const insert = this.db.prepare('INSERT OR IGNORE INTO
|
|
98
|
+
this.db.prepare('DELETE FROM turn_review_spans WHERE day < ?').run(day - 1);
|
|
99
|
+
const insert = this.db.prepare('INSERT OR IGNORE INTO turn_review_spans VALUES(?,?,?,?,?)');
|
|
27
100
|
for (const span of spans)
|
|
28
101
|
insert.run(key, span.seq, span.start, span.end, day);
|
|
29
102
|
}
|
|
30
103
|
/** Claim before dispatch so multiple processes, replays and provider failures cannot spend twice. */
|
|
31
104
|
reserve(keys, budget, day = Math.floor(Date.now() / 86_400_000)) {
|
|
32
|
-
this.
|
|
33
|
-
try {
|
|
105
|
+
return this.immediate(() => {
|
|
34
106
|
this.db.prepare('DELETE FROM turn_review_usage WHERE day < ?').run(day - 30);
|
|
35
107
|
const spent = this.db.prepare('SELECT COUNT(DISTINCT batch) AS n FROM turn_review_usage WHERE day=?').get(day);
|
|
36
108
|
const claimed = new Set();
|
|
@@ -41,13 +113,8 @@ export class ReviewLedger {
|
|
|
41
113
|
if (insert.run(key, day, batch).changes)
|
|
42
114
|
claimed.add(key);
|
|
43
115
|
}
|
|
44
|
-
this.db.exec('COMMIT');
|
|
45
116
|
return claimed;
|
|
46
|
-
}
|
|
47
|
-
catch (error) {
|
|
48
|
-
this.db.exec('ROLLBACK');
|
|
49
|
-
throw error;
|
|
50
|
-
}
|
|
117
|
+
});
|
|
51
118
|
}
|
|
52
119
|
/** Scope the evidence lookup to this session and turn; exclude pending, decided, or erased sources. */
|
|
53
120
|
handledRanges(domains, session, turn, store) {
|
|
@@ -61,7 +128,7 @@ export class ReviewLedger {
|
|
|
61
128
|
const revisions = this.db.prepare(`SELECT json_extract(e.source,'$.seq') AS seq,
|
|
62
129
|
json_extract(r.payload,'$.evidence.start') AS start, json_extract(r.payload,'$.evidence.end') AS end
|
|
63
130
|
FROM revisions r JOIN evidence e USING(domain,id,rev) WHERE r.domain=? AND r.batch=?`);
|
|
64
|
-
const duplicates = this.db.prepare('SELECT seq,start,end FROM
|
|
131
|
+
const duplicates = this.db.prepare('SELECT seq,start,end FROM turn_review_spans WHERE turn_key=?');
|
|
65
132
|
for (const domain of domains) {
|
|
66
133
|
for (const span of duplicates.all(turnKey(domain, session, turn, store)))
|
|
67
134
|
add(Number(span.seq), Number(span.start), Number(span.end));
|
package/dist/turn-review.js
CHANGED
|
@@ -1,32 +1,39 @@
|
|
|
1
|
+
import { isDeepStrictEqual } from 'node:util';
|
|
2
|
+
import { prompts } from "./prompt-copy.js";
|
|
1
3
|
import { refusesAutomaticMemory, skipsAutomaticMemory } from "./automatic.js";
|
|
2
4
|
import { digest } from "./domain.js";
|
|
5
|
+
import { foregroundEvidence, foregroundTurnKey } from "./foreground-attempts.js";
|
|
3
6
|
import { messageText } from "./host.js";
|
|
4
7
|
import { reviewText } from "./model-review.js";
|
|
5
|
-
import {
|
|
6
|
-
import {
|
|
7
|
-
import {
|
|
8
|
-
import {
|
|
8
|
+
import { prepareProjectGuidance } from "./proposal-review.js";
|
|
9
|
+
import { isSemanticSlot, normalizeLabel, reviewedSubject } from "./personal.js";
|
|
10
|
+
import { choicesForQuote, questionForm, resolveSelectedDirective, standingRequest } from "./question-answers.js";
|
|
11
|
+
import { reviewedQualifiers, parseCandidates as validateCandidates } from "./semantic.js";
|
|
9
12
|
import { sources } from "./sources.js";
|
|
10
|
-
const
|
|
11
|
-
|
|
12
|
-
|
|
13
|
-
|
|
14
|
-
'existingTopics 是当前可见记忆的主题索引。重复陈述沿用已有的 scope、subject 和 topic。只有原话明确更正且唯一对应某项时,才标 correction:true 并将该项的 id 和 rev 填入 replaces。仅有词义相似、主体或适用条件不清时,不能据此合并或覆盖。',
|
|
15
|
-
].join('\n');
|
|
13
|
+
const sentences = new Intl.Segmenter(undefined, { granularity: 'sentence' });
|
|
14
|
+
const maxExcerpts = 24, maxInputChars = 12000;
|
|
15
|
+
const questionChars = (entry) => (entry.question?.length ?? 0) +
|
|
16
|
+
(entry.submittedOptions ?? []).reduce((sum, choice) => sum + choice.question.length + choice.label.length, 0);
|
|
16
17
|
function availableText(block, handled) {
|
|
17
|
-
|
|
18
|
-
|
|
19
|
-
|
|
18
|
+
if (!handled.length)
|
|
19
|
+
return /[\p{L}\p{N}]/u.test(block.text) ? [block.text] : [];
|
|
20
|
+
const offset = block.offset ?? 0;
|
|
21
|
+
// Removing a handled clause can turn a qualified statement into an apparently
|
|
22
|
+
// unconditional one. Offer only complete, contiguous, previously unhandled sentences.
|
|
20
23
|
const segments = [];
|
|
21
|
-
|
|
22
|
-
|
|
23
|
-
|
|
24
|
-
if (left >
|
|
25
|
-
|
|
26
|
-
|
|
24
|
+
let part = '';
|
|
25
|
+
for (const { index, segment } of sentences.segment(block.text)) {
|
|
26
|
+
const start = index + offset;
|
|
27
|
+
if (handled.some(([left, right]) => left < start + segment.length && right > start)) {
|
|
28
|
+
if (part)
|
|
29
|
+
segments.push(part);
|
|
30
|
+
part = '';
|
|
31
|
+
}
|
|
32
|
+
else
|
|
33
|
+
part += segment;
|
|
27
34
|
}
|
|
28
|
-
if (
|
|
29
|
-
segments.push(
|
|
35
|
+
if (part)
|
|
36
|
+
segments.push(part);
|
|
30
37
|
return segments.filter((text) => /[\p{L}\p{N}]/u.test(text));
|
|
31
38
|
}
|
|
32
39
|
function eligible(memory, root, domain, turn, allowed, generation) {
|
|
@@ -41,14 +48,28 @@ function eligible(memory, root, domain, turn, allowed, generation) {
|
|
|
41
48
|
if (records.some((event) => refusesAutomaticMemory(messageText(event.data))))
|
|
42
49
|
return [];
|
|
43
50
|
const excluded = new Set(records.filter((event) => skipsAutomaticMemory(messageText(event.data))).map((event) => event.seq));
|
|
44
|
-
const
|
|
45
|
-
|
|
51
|
+
const ledger = memory.store.turnReviews;
|
|
52
|
+
const handled = ledger.handledRanges(memory.scopes(root, domain).map((d) => d.id), root.id, turn, store);
|
|
53
|
+
const turnKey = accepted.length && ledger.hasExhaustedForeground() ? foregroundTurnKey(store, root.id, turn, domain.id, generation) : undefined;
|
|
54
|
+
return accepted.flatMap(block => {
|
|
46
55
|
if (excluded.has(block.seq) || skipsAutomaticMemory(block.text))
|
|
47
56
|
return [];
|
|
48
|
-
|
|
57
|
+
const ranges = [...(handled.get(block.seq) ?? [])];
|
|
58
|
+
if (turnKey) {
|
|
59
|
+
const clauses = foregroundEvidence(block, turnKey);
|
|
60
|
+
const stopped = ledger.exhaustedForegroundKeys(clauses.map(clause => clause.key));
|
|
61
|
+
const offset = block.offset ?? 0;
|
|
62
|
+
for (const clause of clauses)
|
|
63
|
+
if (stopped.has(clause.key))
|
|
64
|
+
ranges.push([offset + clause.start, offset + clause.end]);
|
|
65
|
+
}
|
|
66
|
+
return availableText(block, ranges).map((text) => ({
|
|
67
|
+
turn, text, ...(block.question && { question: block.question }),
|
|
68
|
+
...(block.formSelections?.length && standingRequest(text) && { submittedOptions: block.formSelections }),
|
|
69
|
+
}));
|
|
49
70
|
});
|
|
50
71
|
}
|
|
51
|
-
function parseCandidates(text) {
|
|
72
|
+
function parseCandidates(text, topics, excerpts) {
|
|
52
73
|
// Some providers wrap valid JSON in a Markdown fence. No recovery of partially streamed output.
|
|
53
74
|
const response = JSON.parse(text.trim().replace(/^\x60\x60\x60(?:json)?\s*\n([\s\S]*)\n\x60\x60\x60$/iu, '$1'));
|
|
54
75
|
if (!Array.isArray(response?.items) || response.items.length > 12)
|
|
@@ -56,11 +77,28 @@ function parseCandidates(text) {
|
|
|
56
77
|
return response.items.flatMap((row) => {
|
|
57
78
|
if (!row || typeof row !== 'object')
|
|
58
79
|
return [];
|
|
59
|
-
const { turn, ...fields } = row;
|
|
80
|
+
const { turn, owner, equivalentQualifiers, selectedOption, ...fields } = row;
|
|
60
81
|
if (typeof turn !== 'string')
|
|
61
82
|
return [];
|
|
62
83
|
try {
|
|
63
|
-
|
|
84
|
+
const [item] = validateCandidates({ items: [fields] });
|
|
85
|
+
const target = topics.find(topic => topic.id === item.replaces?.id && topic.rev === item.replaces.rev && topic.scope === item.scope);
|
|
86
|
+
if (item.replaces && (!target || target.kind !== item.kind || normalizeLabel(target.topic) !== normalizeLabel(item.topic)))
|
|
87
|
+
return [];
|
|
88
|
+
const evidence = excerpts.filter(e => e.turn === turn && e.text.includes(item.user_quote));
|
|
89
|
+
if (evidence.length !== 1)
|
|
90
|
+
return [];
|
|
91
|
+
const excerpt = evidence[0];
|
|
92
|
+
const choices = choicesForQuote(excerpt.text, item.user_quote, excerpt.submittedOptions);
|
|
93
|
+
const selected = resolveSelectedDirective(item.action, selectedOption, choices, item.kind !== 'fact');
|
|
94
|
+
if (!selected || (selected.selection && !item.user_quote.includes(selected.selection.directive)))
|
|
95
|
+
return [];
|
|
96
|
+
const source = [excerpt.text, excerpt.question ?? ''];
|
|
97
|
+
const identity = reviewedSubject(owner, item.subject, target, Boolean(item.replaces), { subject: item.subject, source });
|
|
98
|
+
if ('reason' in identity)
|
|
99
|
+
return [];
|
|
100
|
+
return [{ turn, selection: selected.selection, item: { ...item, action: selected.action,
|
|
101
|
+
subject: identity.subject, ...reviewedQualifiers(item, target, equivalentQualifiers) } }];
|
|
64
102
|
}
|
|
65
103
|
catch {
|
|
66
104
|
return [];
|
|
@@ -80,10 +118,9 @@ async function relevantTopics(memory, owners, excerpts, signal) {
|
|
|
80
118
|
continue;
|
|
81
119
|
const keywords = memory.store.keywordMatches(domains, query, '', 'review_topics')
|
|
82
120
|
.sort((a, b) => b.score - a.score || a.id.localeCompare(b.id));
|
|
83
|
-
//
|
|
84
|
-
//
|
|
85
|
-
const semantic =
|
|
86
|
-
? await memory.retrieval.vectors.reviewTopics(domains, query).catch(() => []) : [];
|
|
121
|
+
// Retrieve evidence before the reviewer interprets whether the user is restating,
|
|
122
|
+
// replacing or creating a fact. A paraphrase may share no words with the old entry.
|
|
123
|
+
const semantic = await memory.retrieval.vectors.reviewTopics(domains, query).catch(() => []);
|
|
87
124
|
signal.throwIfAborted();
|
|
88
125
|
const shortlist = [];
|
|
89
126
|
const seen = new Set();
|
|
@@ -96,11 +133,14 @@ async function relevantTopics(memory, owners, excerpts, signal) {
|
|
|
96
133
|
const rule = memory.current(owner, hit.id, hit.rev);
|
|
97
134
|
if (!rule || rule.sensitive || !isSemanticSlot(rule.slot) || !rule.semanticTopic)
|
|
98
135
|
continue;
|
|
99
|
-
|
|
100
|
-
|
|
136
|
+
// Show the complete current claim and its qualifiers, never the old source
|
|
137
|
+
// quote. Omit oversized candidates instead of dropping a limiting condition.
|
|
138
|
+
if (rule.paths.join(' ').length > 1024 || skipsAutomaticMemory([rule.subject, rule.semanticTopic, rule.action, rule.when, rule.exceptions, ...rule.paths].join(' ')))
|
|
139
|
+
continue;
|
|
101
140
|
shortlist.push({ scope: owner.id === memory.personal.id ? 'global' : 'project', subject: rule.subject,
|
|
102
|
-
topic: rule.semanticTopic, kind: rule.kind, id: rule.id, rev: rule.rev,
|
|
103
|
-
...(
|
|
141
|
+
topic: rule.semanticTopic, kind: rule.kind, id: rule.id, rev: rule.rev, action: rule.action,
|
|
142
|
+
usage: rule.usage ?? 'on_demand', ...(rule.when && { when: rule.when }),
|
|
143
|
+
...(rule.exceptions && { exceptions: rule.exceptions }), ...(rule.paths.length && { paths: rule.paths }) });
|
|
104
144
|
}
|
|
105
145
|
}
|
|
106
146
|
byQuery.set(query, shortlist);
|
|
@@ -155,10 +195,11 @@ export function registerTurnReview(memory, sdk, delayMs = 1200) {
|
|
|
155
195
|
for (const entry of blocks) {
|
|
156
196
|
// Keep whole lines or sentences in their original order. Leave an
|
|
157
197
|
// unbroken over-limit sentence out; cuts could detach its qualifiers.
|
|
158
|
-
const
|
|
198
|
+
const overhead = questionChars(entry);
|
|
199
|
+
const limit = 6000 - overhead;
|
|
159
200
|
const fragments = [];
|
|
160
201
|
let part = '';
|
|
161
|
-
for (const line of entry.text
|
|
202
|
+
for (const { segment: line } of sentences.segment(entry.text)) {
|
|
162
203
|
if (part.length + line.length > limit) {
|
|
163
204
|
if (part)
|
|
164
205
|
fragments.push(part);
|
|
@@ -170,8 +211,8 @@ export function registerTurnReview(memory, sdk, delayMs = 1200) {
|
|
|
170
211
|
if (part)
|
|
171
212
|
fragments.push(part);
|
|
172
213
|
for (const text of fragments) {
|
|
173
|
-
const length = text.length +
|
|
174
|
-
if (size + length >
|
|
214
|
+
const length = text.length + overhead;
|
|
215
|
+
if (size + length > maxInputChars || excerpts.length >= maxExcerpts)
|
|
175
216
|
continue;
|
|
176
217
|
excerpts.push({ ...entry, text });
|
|
177
218
|
size += length;
|
|
@@ -182,7 +223,7 @@ export function registerTurnReview(memory, sdk, delayMs = 1200) {
|
|
|
182
223
|
if (!excerpts.length)
|
|
183
224
|
return;
|
|
184
225
|
const claimed = memory.store.turnReviews.reserve([...turns.values()], budget);
|
|
185
|
-
|
|
226
|
+
let input = excerpts.filter((e) => claimed.has(turns.get(e.turn)));
|
|
186
227
|
if (!input.length)
|
|
187
228
|
return;
|
|
188
229
|
const owners = memory.scopes(root, domain);
|
|
@@ -199,44 +240,98 @@ export function registerTurnReview(memory, sdk, delayMs = 1200) {
|
|
|
199
240
|
currentRoute?.provider !== job.route.provider || currentRoute.model !== job.route.model ||
|
|
200
241
|
memory.store.enabledGeneration() !== job.generation || owners.some(owner => memory.store.epoch(owner.id) !== epochs.get(owner.id)))
|
|
201
242
|
return;
|
|
243
|
+
if (topics.some(topic => !memory.current(topic.scope === 'global' ? memory.personal : currentDomain, topic.id, topic.rev)))
|
|
244
|
+
return;
|
|
245
|
+
// Preparation and retrieval can suspend while another foreground attempt exhausts a
|
|
246
|
+
// clause or the native form changes. Only send text and options that remain eligible.
|
|
247
|
+
if (input.some(e => e.submittedOptions) || memory.store.turnReviews.hasExhaustedForeground()) {
|
|
248
|
+
const current = new Map();
|
|
249
|
+
let chars = 0, count = 0;
|
|
250
|
+
input = input.flatMap(entry => {
|
|
251
|
+
let remaining = current.get(entry.turn);
|
|
252
|
+
if (!remaining) {
|
|
253
|
+
remaining = eligible(memory, root, domain, entry.turn, job.turns.get(entry.turn), job.generation);
|
|
254
|
+
current.set(entry.turn, remaining);
|
|
255
|
+
}
|
|
256
|
+
const matching = remaining.filter(e => e.question === entry.question);
|
|
257
|
+
if (matching.some(e => e.text.includes(entry.text) && isDeepStrictEqual(e.submittedOptions, entry.submittedOptions)))
|
|
258
|
+
return [entry];
|
|
259
|
+
// A newly stopped sentence can divide a previously selected passage. Other complete
|
|
260
|
+
// sentences still qualify, but the old passage's ranking cannot authorize replacing a target.
|
|
261
|
+
return matching.filter(e => entry.text.includes(e.text) && (isDeepStrictEqual(e.submittedOptions, entry.submittedOptions) ||
|
|
262
|
+
(!e.submittedOptions && !standingRequest(e.text))));
|
|
263
|
+
}).filter(entry => {
|
|
264
|
+
const length = questionChars(entry) + entry.text.length;
|
|
265
|
+
if (chars + length > maxInputChars || count >= maxExcerpts)
|
|
266
|
+
return false;
|
|
267
|
+
chars += length;
|
|
268
|
+
count++;
|
|
269
|
+
return true;
|
|
270
|
+
});
|
|
271
|
+
if (!input.length)
|
|
272
|
+
return;
|
|
273
|
+
}
|
|
274
|
+
// The reviewer selects by array index. Native event coordinates stay local.
|
|
275
|
+
const projected = input.map(({ submittedOptions, ...entry }) => ({
|
|
276
|
+
...entry, ...(submittedOptions && { submittedOptions: submittedOptions.map(({ question, label }) => ({ question, label })) }),
|
|
277
|
+
}));
|
|
278
|
+
const copy = prompts[memory.promptLanguage(root)];
|
|
202
279
|
const rows = parseCandidates(await reviewText(prepared ?? llm, sdk, {
|
|
203
|
-
...job.route, maxTokens: 1200, ...prepared?.config, system:
|
|
204
|
-
messages: [sdk.createUserMessage({ content: [{ type: 'text', text: JSON.stringify({ existingTopics: topics, excerpts:
|
|
280
|
+
...job.route, maxTokens: 1200, ...prepared?.config, system: copy.review + '\n' + copy.write, signal,
|
|
281
|
+
messages: [sdk.createUserMessage({ content: [{ type: 'text', text: JSON.stringify({ existingTopics: topics, excerpts: projected }) }],
|
|
205
282
|
source: { kind: 'project-memory-review' } })],
|
|
206
|
-
}));
|
|
283
|
+
}), topics, input);
|
|
207
284
|
let saved = 0, duplicates = 0;
|
|
208
|
-
|
|
209
|
-
signal.throwIfAborted();
|
|
285
|
+
const stillCurrent = () => {
|
|
210
286
|
if (memory.store.enabledGeneration() !== job.generation)
|
|
211
|
-
return;
|
|
287
|
+
return false;
|
|
212
288
|
const activeDomain = memory.rootDomain(root, true);
|
|
213
|
-
if (activeDomain.id !== job.domain || activeDomain.cwd !== domain.cwd || memory.storeId(job.session) !== job.store)
|
|
214
|
-
return;
|
|
215
289
|
const activeRoute = root.model?.current();
|
|
216
|
-
|
|
290
|
+
return activeDomain.id === job.domain && activeDomain.cwd === domain.cwd && memory.storeId(job.session) === job.store &&
|
|
291
|
+
activeRoute?.provider === job.route.provider && activeRoute.model === job.route.model;
|
|
292
|
+
};
|
|
293
|
+
for (const [turn, seqs] of job.turns) {
|
|
294
|
+
signal.throwIfAborted();
|
|
295
|
+
if (!stillCurrent())
|
|
217
296
|
return;
|
|
218
297
|
const sent = input.filter(excerpt => excerpt.turn === turn);
|
|
219
298
|
if (!sent.length)
|
|
220
299
|
continue;
|
|
221
300
|
// A foreground write may have handled an excerpt while the model was running.
|
|
222
|
-
const
|
|
223
|
-
const items = rows.filter(row => row.turn === turn).map(row => row.item).filter(item => {
|
|
301
|
+
const allowed = ({ item, selection }, remaining) => {
|
|
224
302
|
const evidence = sent.filter(e => e.text.includes(item.user_quote));
|
|
225
|
-
if (!evidence.length || !remaining.some(e => e.text.includes(item.user_quote)
|
|
303
|
+
if (!evidence.length || !remaining.some(e => e.text.includes(item.user_quote) && (!selection ||
|
|
304
|
+
e.submittedOptions?.some(option => isDeepStrictEqual(option, selection.option)))))
|
|
226
305
|
return false;
|
|
227
|
-
const owner = item.scope === 'global' ? memory.personal :
|
|
306
|
+
const owner = item.scope === 'global' ? memory.personal : domain;
|
|
228
307
|
if (memory.store.epoch(owner.id) !== epochs.get(owner.id))
|
|
229
308
|
return false;
|
|
230
309
|
const ref = item.replaces;
|
|
231
310
|
if (!ref)
|
|
232
|
-
return
|
|
311
|
+
return true;
|
|
233
312
|
const matches = (t) => t.scope === item.scope && t.id === ref.id && t.rev === ref.rev;
|
|
234
313
|
return topics.some(matches) && evidence.some(e => byQuery.get(excerptQuery(e))?.some(matches)) &&
|
|
235
314
|
!!memory.current(owner, ref.id, ref.rev);
|
|
236
|
-
}
|
|
315
|
+
};
|
|
316
|
+
let remaining = eligible(memory, root, domain, turn, seqs, job.generation);
|
|
317
|
+
const items = rows.filter(row => row.turn === turn && allowed(row, remaining));
|
|
237
318
|
// Evaluate competing statements about the same topic together, in their original turn.
|
|
238
319
|
if (items.length) {
|
|
239
|
-
|
|
320
|
+
await prepareProjectGuidance(memory, root, items.map(row => row.item), sdk, turn, signal, job.generation, () => {
|
|
321
|
+
if (!memory.store.turnReviews.hasExhaustedForeground())
|
|
322
|
+
return;
|
|
323
|
+
const valid = eligible(memory, root, domain, turn, seqs, job.generation);
|
|
324
|
+
if (items.some(item => !allowed(item, valid)))
|
|
325
|
+
throw Error('source_unavailable');
|
|
326
|
+
});
|
|
327
|
+
signal.throwIfAborted();
|
|
328
|
+
if (!stillCurrent())
|
|
329
|
+
return;
|
|
330
|
+
remaining = eligible(memory, root, domain, turn, seqs, job.generation);
|
|
331
|
+
const authorized = items.filter(item => allowed(item, remaining));
|
|
332
|
+
if (!authorized.length)
|
|
333
|
+
continue;
|
|
334
|
+
const { results } = memory.proposeFromTurn(root, turn, { items: authorized.map(row => row.item) }, epochs, authorized.map(row => row.selection));
|
|
240
335
|
saved += results.filter(row => row.status === 'saved').length;
|
|
241
336
|
duplicates += results.filter(row => row.status === 'duplicate').length;
|
|
242
337
|
}
|
|
@@ -284,11 +379,12 @@ export function registerTurnReview(memory, sdk, delayMs = 1200) {
|
|
|
284
379
|
return;
|
|
285
380
|
}
|
|
286
381
|
const capture = captured.get(session);
|
|
382
|
+
const form = event.type === 'tool/result' ? questionForm(session, event) : undefined;
|
|
287
383
|
const inputs = event.type === 'user/message' && event.data.source?.kind === 'user'
|
|
288
384
|
? [{ text: messageText(event.data) }]
|
|
289
|
-
:
|
|
290
|
-
if (inputs.length) {
|
|
291
|
-
if (inputs.some(({ text }) => refusesAutomaticMemory(text))) {
|
|
385
|
+
: form?.custom ?? [];
|
|
386
|
+
if (inputs.length || form?.refusedBy !== undefined) {
|
|
387
|
+
if (form?.refusedBy !== undefined || inputs.some(({ text }) => refusesAutomaticMemory(text))) {
|
|
292
388
|
if (capture)
|
|
293
389
|
capture.refused = true;
|
|
294
390
|
clearTimeout(pending.get(session)?.timer);
|