dsh-cross-memory 0.0.0-stage → 0.2.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/LICENSE +21 -0
- package/README.md +247 -2
- package/cordis.patch.yml +27 -0
- package/docs/DETAIL.md +13 -0
- package/docs/DETAIL.zh.md +17 -0
- package/icon.svg +1 -0
- package/lib/backfill.js +273 -0
- package/lib/citations.js +305 -0
- package/lib/client.js +1550 -0
- package/lib/config.js +736 -0
- package/lib/consolidate.js +1119 -0
- package/lib/extract.js +570 -0
- package/lib/gate.js +137 -0
- package/lib/git-origin.js +224 -0
- package/lib/index.js +4475 -0
- package/lib/log.js +260 -0
- package/lib/loops.js +186 -0
- package/lib/notices.js +195 -0
- package/lib/notify.js +33 -0
- package/lib/persona.js +112 -0
- package/lib/query.js +93 -0
- package/lib/raw-recall.js +286 -0
- package/lib/reflection.js +291 -0
- package/lib/remote.js +455 -0
- package/lib/render.js +678 -0
- package/lib/retention.js +64 -0
- package/lib/schedule.js +245 -0
- package/lib/search.js +1068 -0
- package/lib/skills.js +220 -0
- package/lib/state.js +701 -0
- package/lib/storage.js +1424 -0
- package/lib/sync-runtime.js +268 -0
- package/lib/sync.js +620 -0
- package/lib/test/activity.test.js +74 -0
- package/lib/test/archive.test.js +182 -0
- package/lib/test/backfill.test.js +144 -0
- package/lib/test/citations.test.js +91 -0
- package/lib/test/client-wiring.test.js +134 -0
- package/lib/test/consolidate-job.test.js +95 -0
- package/lib/test/consolidate.test.js +430 -0
- package/lib/test/consolidation-selection.test.js +152 -0
- package/lib/test/dedupe-keys.test.js +230 -0
- package/lib/test/delta.test.js +93 -0
- package/lib/test/derived.test.js +110 -0
- package/lib/test/disputes-panel.test.js +314 -0
- package/lib/test/eval.test.js +171 -0
- package/lib/test/expand.test.js +164 -0
- package/lib/test/extract.test.js +1020 -0
- package/lib/test/git-origin.test.js +189 -0
- package/lib/test/injection.test.js +440 -0
- package/lib/test/kind-filter.test.js +49 -0
- package/lib/test/legacy-state.test.js +69 -0
- package/lib/test/log.test.js +156 -0
- package/lib/test/loops.test.js +86 -0
- package/lib/test/memory.test.js +855 -0
- package/lib/test/notices.test.js +140 -0
- package/lib/test/persona.test.js +73 -0
- package/lib/test/prefilter.test.js +73 -0
- package/lib/test/preset.test.js +77 -0
- package/lib/test/raw-recall.test.js +186 -0
- package/lib/test/recall.test.js +433 -0
- package/lib/test/reflection.test.js +64 -0
- package/lib/test/remote.test.js +227 -0
- package/lib/test/retention.test.js +117 -0
- package/lib/test/retrieval.test.js +142 -0
- package/lib/test/rotation.test.js +228 -0
- package/lib/test/schedule.test.js +112 -0
- package/lib/test/settings-card.test.js +58 -0
- package/lib/test/skills.test.js +129 -0
- package/lib/test/state.test.js +212 -0
- package/lib/test/subagent-contract.test.js +139 -0
- package/lib/test/sweep.test.js +159 -0
- package/lib/test/sync.test.js +314 -0
- package/lib/test/time.test.js +171 -0
- package/lib/time.js +303 -0
- package/lib/tool.js +330 -0
- package/lib/types/backfill.d.ts +96 -0
- package/lib/types/citations.d.ts +105 -0
- package/lib/types/config.d.ts +811 -0
- package/lib/types/consolidate.d.ts +742 -0
- package/lib/types/extract.d.ts +352 -0
- package/lib/types/gate.d.ts +83 -0
- package/lib/types/git-origin.d.ts +23 -0
- package/lib/types/index.d.ts +1316 -0
- package/lib/types/log.d.ts +144 -0
- package/lib/types/loops.d.ts +82 -0
- package/lib/types/notices.d.ts +117 -0
- package/lib/types/notify.d.ts +12 -0
- package/lib/types/persona.d.ts +43 -0
- package/lib/types/query.d.ts +45 -0
- package/lib/types/raw-recall.d.ts +84 -0
- package/lib/types/reflection.d.ts +122 -0
- package/lib/types/remote.d.ts +233 -0
- package/lib/types/render.d.ts +286 -0
- package/lib/types/retention.d.ts +66 -0
- package/lib/types/schedule.d.ts +116 -0
- package/lib/types/search.d.ts +583 -0
- package/lib/types/skills.d.ts +71 -0
- package/lib/types/state.d.ts +294 -0
- package/lib/types/storage.d.ts +458 -0
- package/lib/types/sync-runtime.d.ts +103 -0
- package/lib/types/sync.d.ts +222 -0
- package/lib/types/test/activity.test.d.ts +1 -0
- package/lib/types/test/archive.test.d.ts +1 -0
- package/lib/types/test/backfill.test.d.ts +1 -0
- package/lib/types/test/citations.test.d.ts +1 -0
- package/lib/types/test/client-wiring.test.d.ts +1 -0
- package/lib/types/test/consolidate-job.test.d.ts +1 -0
- package/lib/types/test/consolidate.test.d.ts +1 -0
- package/lib/types/test/consolidation-selection.test.d.ts +1 -0
- package/lib/types/test/dedupe-keys.test.d.ts +1 -0
- package/lib/types/test/delta.test.d.ts +1 -0
- package/lib/types/test/derived.test.d.ts +1 -0
- package/lib/types/test/disputes-panel.test.d.ts +1 -0
- package/lib/types/test/eval.test.d.ts +1 -0
- package/lib/types/test/expand.test.d.ts +1 -0
- package/lib/types/test/extract.test.d.ts +1 -0
- package/lib/types/test/git-origin.test.d.ts +1 -0
- package/lib/types/test/injection.test.d.ts +1 -0
- package/lib/types/test/kind-filter.test.d.ts +1 -0
- package/lib/types/test/legacy-state.test.d.ts +1 -0
- package/lib/types/test/log.test.d.ts +1 -0
- package/lib/types/test/loops.test.d.ts +1 -0
- package/lib/types/test/memory.test.d.ts +1 -0
- package/lib/types/test/notices.test.d.ts +1 -0
- package/lib/types/test/persona.test.d.ts +1 -0
- package/lib/types/test/prefilter.test.d.ts +1 -0
- package/lib/types/test/preset.test.d.ts +1 -0
- package/lib/types/test/raw-recall.test.d.ts +1 -0
- package/lib/types/test/recall.test.d.ts +1 -0
- package/lib/types/test/reflection.test.d.ts +1 -0
- package/lib/types/test/remote.test.d.ts +1 -0
- package/lib/types/test/retention.test.d.ts +1 -0
- package/lib/types/test/retrieval.test.d.ts +1 -0
- package/lib/types/test/rotation.test.d.ts +1 -0
- package/lib/types/test/schedule.test.d.ts +1 -0
- package/lib/types/test/settings-card.test.d.ts +1 -0
- package/lib/types/test/skills.test.d.ts +1 -0
- package/lib/types/test/state.test.d.ts +1 -0
- package/lib/types/test/subagent-contract.test.d.ts +1 -0
- package/lib/types/test/sweep.test.d.ts +1 -0
- package/lib/types/test/sync.test.d.ts +1 -0
- package/lib/types/test/time.test.d.ts +1 -0
- package/lib/types/time.d.ts +67 -0
- package/lib/types/tool.d.ts +9 -0
- package/lib/types/types.d.ts +374 -0
- package/lib/types/workspace.d.ts +20 -0
- package/lib/types.js +47 -0
- package/lib/workspace.js +65 -0
- package/locale/en.json +7 -0
- package/locale/zh.json +7 -0
- package/package.json +126 -4
package/lib/extract.js
ADDED
|
@@ -0,0 +1,570 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Idle-time memory extraction.
|
|
3
|
+
*
|
|
4
|
+
* After a session has been quiet for a while, the extractor replays a bounded
|
|
5
|
+
* tail of its transcript through one auxiliary model call and turns the result
|
|
6
|
+
* into memory drafts. It never touches the conversation: extraction runs on the
|
|
7
|
+
* maintenance path, writes only to the memory store, and is fully optional
|
|
8
|
+
* (`autoExtract: false` disables it).
|
|
9
|
+
*
|
|
10
|
+
* @module dsh-cross-memory/extract
|
|
11
|
+
*/
|
|
12
|
+
import { BlockAssembler, createUserMessage } from '@deepseek-ai/dsh-llm';
|
|
13
|
+
import { deriveEventMessage } from '@deepseek-ai/dsh-session/surface';
|
|
14
|
+
import { SessionSeq } from '@deepseek-ai/dsh-session';
|
|
15
|
+
import { MEMORY_SOURCE_KIND, toMemoryKind } from './types.js';
|
|
16
|
+
/**
|
|
17
|
+
* The system instruction for the extraction call.
|
|
18
|
+
*
|
|
19
|
+
* The reply's key order is load-bearing, not cosmetic. `maxOutputTokens` is a
|
|
20
|
+
* ceiling on the *whole* completion, reasoning included, and the reply's only
|
|
21
|
+
* recoverable part is the sequence of COMPLETE memory objects: when the ceiling
|
|
22
|
+
* bites mid-reply, `repairTruncatedJson` can close the array after the last
|
|
23
|
+
* finished object, but it can never resurrect one that was not written yet.
|
|
24
|
+
* With `summary` first, a model that spends the budget on the summary paragraph
|
|
25
|
+
* loses every memory at once — measured on this store, 2026-09-23/24, five
|
|
26
|
+
* extraction calls came back capped with nothing usable (`[5766 in / 4096 out]`
|
|
27
|
+
* … `[24490 in / 4096 out]`, `raise extractMaxOutputTokens`), four of them on
|
|
28
|
+
* `deepseek-flash` at `reasoningEffort: high` and one on `gpt-6-astra`, where
|
|
29
|
+
* the thinking tokens alone can consume the cap. Memories first makes the same
|
|
30
|
+
* truncation keep everything that finished.
|
|
31
|
+
*/
|
|
32
|
+
export const EXTRACT_SYSTEM = [
|
|
33
|
+
'You maintain long-term memory for a coding assistant.',
|
|
34
|
+
'Read the supplied conversation transcript and extract only durable, reusable facts that would help in a FUTURE session.',
|
|
35
|
+
'',
|
|
36
|
+
'Record: stable user preferences and working style; project architecture and conventions; build/test/deploy commands; environment and tooling facts; non-obvious gotchas; decisions and their reasons.',
|
|
37
|
+
'Do NOT record: transient task state, one-off debugging output, secrets, API keys, tokens, credentials, personal data, restatements of the code the assistant just wrote, or anything already stated in the transcript as a question rather than a fact.',
|
|
38
|
+
'',
|
|
39
|
+
'Write every title and body in Simplified Chinese. Keep paths, commands, identifiers, product names and error strings exactly as they are.',
|
|
40
|
+
'The injected summary shows only the title and roughly the first 100 characters of the body (the budget forces short previews), so lead with the trigger and the decision; put the detail after.',
|
|
41
|
+
'Never record a number that moves on its own (test counts, file or row counts, "ahead by N commits", a version that will be bumped). Record the command that produces the number instead, or mark the value 截至 <date>.',
|
|
42
|
+
'When a number IS the point of the memory (a measured pass rate, a corpus size, the current state of a system), set "durability":"snapshot" and give "asOf" as the date it was measured; it is then shown with that date and retired once it is old. Everything else is "durable" and needs neither field.',
|
|
43
|
+
'A problem that is already fixed is recorded as fixed ("已修 in <commit>"); never leave it reading as an open problem.',
|
|
44
|
+
'',
|
|
45
|
+
'Choose the scope of each memory:',
|
|
46
|
+
'- "global": true across the developer\'s machines and projects — how they like to work, general preferences, tooling, machine and path facts, network and proxy setup, how to move work between machines.',
|
|
47
|
+
'- "project": true only for this workspace (its architecture, commands, conventions, gotchas).',
|
|
48
|
+
'Choose by breadth, not by wording: naming a machine, drive letter, repository path, host, employer or customer is NOT by itself evidence of project scope. A durable fact about the developer\'s own environment is global even when it names such a thing, because global memories are what every unrelated project reads. A fact becomes "project" only when it would be wrong or meaningless outside this one workspace.',
|
|
49
|
+
'',
|
|
50
|
+
'Each memory has a short imperative title (max 80 characters), a 1-3 sentence body, up to 5 lowercase keyword tags, and 1-5 search keys: the aliases and keyphrases a future session would actually type (for example "monorepo" for a pnpm-workspace fact).',
|
|
51
|
+
'Search keys are how a memory is found at all, so spend them on the words a person would use who has NOT read the memory: the other name for the same thing, the command, the file, the error text, the product\'s own term. Include the English technical term when the memory is written in Chinese and vice versa — a turn that mixes them ("这个排序改动会不会动到 system prompt") shares no characters with "前缀缓存", and the keys are the only place that gap can be closed. Retrieval is lexical: it matches characters, not meaning.',
|
|
52
|
+
'Give each memory a kind, because the kinds are recalled differently:',
|
|
53
|
+
'- "preference": how the user wants work done, or a correction they issued.',
|
|
54
|
+
'- "failure": something that went wrong and how to avoid repeating it.',
|
|
55
|
+
'- "procedure": an ordered recipe for a recurring task.',
|
|
56
|
+
'- "knowledge": a non-obvious technique worth reusing.',
|
|
57
|
+
'- "fact": durable background that is none of the above.',
|
|
58
|
+
'Always provide "appliesTo": a short phrase in the user\'s words saying when this memory matters ("准备推送代码之前"). It is the field that lets a paraphrased turn find the memory, and it is required.',
|
|
59
|
+
'Every memory must also carry "quote": one continuous passage copied VERBATIM from a single message in the transcript above (8-200 characters), keeping its punctuation and wording exactly, and without the "USER:"/"ASSISTANT:" line prefix. Choose the sentence that carries the claim — the user stating it, or the assistant\'s conclusion you are recording — not a greeting, a question or your own summary. Never paraphrase the quote, combine two messages, or invent one. The quote is checked as an exact substring of the transcript before the memory is written, and a memory whose quote does not appear there is discarded, so a paraphrased quote loses the memory.',
|
|
60
|
+
'',
|
|
61
|
+
'Mark whose words a memory preserves with "voice":',
|
|
62
|
+
'- "user" when the user themselves stated it: how they want work done, a correction they issued, a habit, an opinion, a rule they set ("以后都…", "不要…", "我喜欢…").',
|
|
63
|
+
'- Record the SUBSTANCE faithfully but in the form that will be found and understood later: rewrite for clarity when their sentence was context-bound, and keep their exact phrasing only where the wording itself carries the rule (a threshold, a condition, a turn of phrase they will repeat). The voice field records whose claim it is, not a transcript.',
|
|
64
|
+
'- omit the field (the default) when the memory is your own conclusion, an observation about the code, or a fact you looked up.',
|
|
65
|
+
'Never attribute your own conclusion to the user. A profile of this person is rebuilt from the "user" entries, so a misattributed guess becomes a false belief about them.',
|
|
66
|
+
'',
|
|
67
|
+
'Also return "loops": things the USER said they would do or asked to be reminded of, and that are still not done ("我明天发出去", "下周再看", "周五前给你"). These are not memories — they are obligations with a deadline and a lifecycle, and the only thing that can justify speaking up without being asked.',
|
|
68
|
+
'- One short sentence each, in the user\'s framing, naming the object ("把报价单发出去", not "邮件相关").',
|
|
69
|
+
'- NEVER drop the time word: if the user said 明天/周五/下周三, the loop text must start with it ("明天把登录页的截图补齐"), because a later question may be exactly "我明天要做什么"; resolve "dueAt" to the absolute ISO date computed from today\'s date given above, and omit it when no deadline was said.',
|
|
70
|
+
'- "dueAt" only when a deadline was actually said, as ISO date or date-time. Never invent one: a loop without a deadline is a note, and nagging somebody about a note turns help into supervision.',
|
|
71
|
+
'- Skip what the session shows as already done, and skip the assistant\'s own to-dos. An empty array is the normal result.',
|
|
72
|
+
'Prefer few high-value memories over many trivial ones. Return at most the requested number.',
|
|
73
|
+
'Reply with JSON only, no prose and no code fence: {"memories":[{"scope":"global"|"project","kind":string,"title":string,"body":string,"tags":string[],"appliesTo":string,"quote":string}],"loops":[{"text":string,"dueAt":string?}],"summary":string}',
|
|
74
|
+
'Write the "memories" array first and the "summary" paragraph last: the reply is capped, and a summary written first can spend the whole budget before the first memory is complete.',
|
|
75
|
+
'Write "summary" as one paragraph (2-4 sentences) saying what this session was about — the task, the decisions, and anything that would help someone judge the memories above later. It is stored as the evidence behind them.',
|
|
76
|
+
'When nothing is worth remembering, reply exactly {"memories":[],"summary":""}.'
|
|
77
|
+
].join('\n');
|
|
78
|
+
/**
|
|
79
|
+
* JSON output contract for one extraction call.
|
|
80
|
+
*
|
|
81
|
+
* `memories` is declared (and required) before `summary` on purpose: property
|
|
82
|
+
* declaration order guides generation, and the array is the part a truncated
|
|
83
|
+
* reply can still salvage. See {@link EXTRACT_SYSTEM}.
|
|
84
|
+
*/
|
|
85
|
+
export const EXTRACT_JSON_SCHEMA = {
|
|
86
|
+
type: 'object',
|
|
87
|
+
additionalProperties: false,
|
|
88
|
+
required: ['memories', 'summary'],
|
|
89
|
+
properties: {
|
|
90
|
+
memories: {
|
|
91
|
+
type: 'array',
|
|
92
|
+
items: {
|
|
93
|
+
type: 'object',
|
|
94
|
+
additionalProperties: false,
|
|
95
|
+
required: ['scope', 'title', 'body', 'appliesTo', 'quote'],
|
|
96
|
+
properties: {
|
|
97
|
+
scope: { type: 'string', enum: ['global', 'project'] },
|
|
98
|
+
kind: { type: 'string', enum: ['fact', 'preference', 'knowledge', 'failure', 'procedure'] },
|
|
99
|
+
title: { type: 'string' },
|
|
100
|
+
body: { type: 'string' },
|
|
101
|
+
tags: { type: 'array', items: { type: 'string' } },
|
|
102
|
+
keys: { type: 'array', items: { type: 'string' } },
|
|
103
|
+
appliesTo: { type: 'string' },
|
|
104
|
+
quote: { type: 'string' },
|
|
105
|
+
voice: { type: 'string', enum: ['user', 'assistant'] },
|
|
106
|
+
durability: { type: 'string', enum: ['durable', 'snapshot'] },
|
|
107
|
+
asOf: { type: 'string' },
|
|
108
|
+
},
|
|
109
|
+
},
|
|
110
|
+
},
|
|
111
|
+
loops: {
|
|
112
|
+
type: 'array',
|
|
113
|
+
items: {
|
|
114
|
+
type: 'object',
|
|
115
|
+
additionalProperties: false,
|
|
116
|
+
required: ['text'],
|
|
117
|
+
properties: {
|
|
118
|
+
text: { type: 'string' },
|
|
119
|
+
dueAt: { type: 'string' },
|
|
120
|
+
},
|
|
121
|
+
},
|
|
122
|
+
},
|
|
123
|
+
summary: { type: 'string' },
|
|
124
|
+
},
|
|
125
|
+
};
|
|
126
|
+
/**
|
|
127
|
+
* Parse the open-loop list of one reply.
|
|
128
|
+
*
|
|
129
|
+
* Deliberately strict about deadlines: an unparseable `dueAt` is dropped rather
|
|
130
|
+
* than defaulted to "now", because a fake deadline is a reminder the user never
|
|
131
|
+
* asked for. The text is the only required field.
|
|
132
|
+
*
|
|
133
|
+
* @param value - the raw `loops` field.
|
|
134
|
+
* @returns at most ten loops, duplicates removed.
|
|
135
|
+
*/
|
|
136
|
+
function parseLoops(value) {
|
|
137
|
+
if (!Array.isArray(value))
|
|
138
|
+
return [];
|
|
139
|
+
const loops = [];
|
|
140
|
+
const seen = new Set();
|
|
141
|
+
for (const item of value) {
|
|
142
|
+
if (loops.length >= 10)
|
|
143
|
+
break;
|
|
144
|
+
// A bare string is accepted as the text: observed in the end-to-end run,
|
|
145
|
+
// DeepSeek read the prompt's "things the user would do" and returned
|
|
146
|
+
// ["把登录页的截图补齐", ...]. The shape is lossless to normalize (there is
|
|
147
|
+
// no deadline to lose), and dropping the whole list silently lost an open
|
|
148
|
+
// promise the ledger exists to keep.
|
|
149
|
+
const record = typeof item === 'string'
|
|
150
|
+
? { text: item }
|
|
151
|
+
: typeof item === 'object' && item !== null ? item : undefined;
|
|
152
|
+
if (record === undefined)
|
|
153
|
+
continue;
|
|
154
|
+
const text = typeof record['text'] === 'string' ? record['text'].replace(/\s+/gu, ' ').trim().slice(0, 200) : '';
|
|
155
|
+
if (text.length < 4 || seen.has(text))
|
|
156
|
+
continue;
|
|
157
|
+
seen.add(text);
|
|
158
|
+
const parsed = typeof record['dueAt'] === 'string' ? Date.parse(record['dueAt']) : Number.NaN;
|
|
159
|
+
// A resolved deadline must be plausible against the extraction's own clock.
|
|
160
|
+
// Observed in the e2e run: the model read "明天" and answered a date four
|
|
161
|
+
// months in the past, which then rendered as an overdue loop and made the
|
|
162
|
+
// promise unreadable. A date that far outside the window is a guess, and a
|
|
163
|
+
// guessed deadline is worse than none, so the text is kept without it.
|
|
164
|
+
const plausible = Number.isFinite(parsed)
|
|
165
|
+
&& parsed >= Date.now() - 30 * 86_400_000
|
|
166
|
+
&& parsed <= Date.now() + 366 * 86_400_000;
|
|
167
|
+
loops.push(plausible ? { text, dueAt: parsed } : { text });
|
|
168
|
+
}
|
|
169
|
+
return loops;
|
|
170
|
+
}
|
|
171
|
+
/** Patterns that look like credentials and must never enter the memory store. */
|
|
172
|
+
const SECRET_PATTERNS = [
|
|
173
|
+
/\bgh[pousr]_[A-Za-z0-9]{16,}/gu,
|
|
174
|
+
/\bglpat-[A-Za-z0-9_-]{16,}/gu,
|
|
175
|
+
/\b(?:sk|pk|xox[baprs])-[A-Za-z0-9_-]{16,}/gu,
|
|
176
|
+
/\bAKIA[0-9A-Z]{16}\b/gu,
|
|
177
|
+
/\beyJ[\w-]{10,}\.[\w-]{10,}\.[\w-]{10,}\b/gu,
|
|
178
|
+
/-----BEGIN [A-Z ]*PRIVATE KEY-----[\s\S]*?-----END [A-Z ]*PRIVATE KEY-----/gu,
|
|
179
|
+
/\b(?:api[_-]?key|apikey|access[_-]?token|auth[_-]?token|client[_-]?secret|password|passwd|secret|token)\b\s*[:=]\s*["']?[^\s"',;]{8,}["']?/giu,
|
|
180
|
+
/\bBearer\s+[\w.-]{20,}/gu,
|
|
181
|
+
];
|
|
182
|
+
/**
|
|
183
|
+
* Redact credential-shaped text. Deliberately conservative and applied before
|
|
184
|
+
* anything is written, because a memory store outlives the session it came from.
|
|
185
|
+
* @param text - candidate memory text.
|
|
186
|
+
* @returns the text with credential-shaped spans replaced.
|
|
187
|
+
*/
|
|
188
|
+
export function redactSecrets(text) {
|
|
189
|
+
let redacted = text;
|
|
190
|
+
for (const pattern of SECRET_PATTERNS)
|
|
191
|
+
redacted = redacted.replace(pattern, '[redacted]');
|
|
192
|
+
return redacted;
|
|
193
|
+
}
|
|
194
|
+
/** Extract the text of one content block list. */
|
|
195
|
+
function blockText(content) {
|
|
196
|
+
const parts = [];
|
|
197
|
+
for (const block of content) {
|
|
198
|
+
if (block.type === 'text')
|
|
199
|
+
parts.push(block.text);
|
|
200
|
+
}
|
|
201
|
+
return parts.join('\n').trim();
|
|
202
|
+
}
|
|
203
|
+
/**
|
|
204
|
+
* Collect the conversation tail a session has produced since `afterSeq`.
|
|
205
|
+
*
|
|
206
|
+
* Only user and assistant prose is taken: tool results are dropped because
|
|
207
|
+
* they are bulky and rarely the durable lesson, and plugin-injected context is
|
|
208
|
+
* dropped so memory never feeds on its own summaries.
|
|
209
|
+
*
|
|
210
|
+
* @param session - session to read.
|
|
211
|
+
* @param afterSeq - last surface seq already mined (exclusive).
|
|
212
|
+
* @param maxMessages - message cap.
|
|
213
|
+
* @param maxChars - transcript character cap; the newest messages win.
|
|
214
|
+
* @returns the rendered window and the highest included seq.
|
|
215
|
+
*/
|
|
216
|
+
export function collectWindow(session, afterSeq, maxMessages, maxChars) {
|
|
217
|
+
const floor = SessionSeq(Math.max(0, Math.trunc(afterSeq)));
|
|
218
|
+
const lines = [];
|
|
219
|
+
for (const seq of session.surface.nodes) {
|
|
220
|
+
if (seq <= floor)
|
|
221
|
+
continue;
|
|
222
|
+
const event = session.eventAt(seq);
|
|
223
|
+
if (event === undefined)
|
|
224
|
+
continue;
|
|
225
|
+
if (event.type !== 'user/message' && event.type !== 'assistant/message')
|
|
226
|
+
continue;
|
|
227
|
+
if (event.type === 'user/message' && event.data.source.kind !== 'user')
|
|
228
|
+
continue;
|
|
229
|
+
const message = deriveEventMessage(event);
|
|
230
|
+
if (message === null)
|
|
231
|
+
continue;
|
|
232
|
+
const text = blockText(message.content);
|
|
233
|
+
if (text.length === 0)
|
|
234
|
+
continue;
|
|
235
|
+
lines.push({ seq, role: message.role === 'user' ? 'user' : 'assistant', text });
|
|
236
|
+
}
|
|
237
|
+
const selected = lines.slice(-maxMessages);
|
|
238
|
+
const kept = [];
|
|
239
|
+
let used = 0;
|
|
240
|
+
for (let index = selected.length - 1; index >= 0; index -= 1) {
|
|
241
|
+
const line = selected[index];
|
|
242
|
+
if (line === undefined)
|
|
243
|
+
continue;
|
|
244
|
+
const cost = `${line.role === 'user' ? 'USER' : 'ASSISTANT'}: ${line.text}`.length + 1;
|
|
245
|
+
if (used + cost > maxChars && kept.length > 0)
|
|
246
|
+
break;
|
|
247
|
+
used += cost;
|
|
248
|
+
kept.unshift(line);
|
|
249
|
+
}
|
|
250
|
+
const lastSeq = selected.at(-1)?.seq;
|
|
251
|
+
return {
|
|
252
|
+
text: kept.map((line) => `${line.role === 'user' ? 'USER' : 'ASSISTANT'}: ${line.text}`).join('\n\n'),
|
|
253
|
+
lastSeq,
|
|
254
|
+
messages: kept.length,
|
|
255
|
+
sources: kept.map((line) => ({ seq: line.seq, text: line.text })),
|
|
256
|
+
};
|
|
257
|
+
}
|
|
258
|
+
/**
|
|
259
|
+
* Resolve the provider/model route for a model call.
|
|
260
|
+
*
|
|
261
|
+
* The session's own route is inherited deliberately — a background call should
|
|
262
|
+
* not silently run on a model nobody chose — but the reasoning level comes with
|
|
263
|
+
* it, and that level is what the output cap has to pay for: a thinking model
|
|
264
|
+
* bills its reasoning against `maxOutputTokens` before the first visible token.
|
|
265
|
+
* Carrying the level out with the route is what lets the caller's log line name
|
|
266
|
+
* the reason a capped call produced nothing, instead of only naming the knob.
|
|
267
|
+
*
|
|
268
|
+
* @param session - the session whose logged route is the fallback.
|
|
269
|
+
* @param provider - an explicit provider, if the caller names one.
|
|
270
|
+
* @param model - an explicit model, if the caller names one.
|
|
271
|
+
* @param fallback - the route to use when the session has none.
|
|
272
|
+
* @returns the route, or `undefined` when no route can be resolved.
|
|
273
|
+
*/
|
|
274
|
+
export function resolveLlmRoute(session, provider, model, fallback) {
|
|
275
|
+
if (provider !== undefined && model !== undefined)
|
|
276
|
+
return { provider, model };
|
|
277
|
+
const header = session.requestHeader();
|
|
278
|
+
if (header !== undefined) {
|
|
279
|
+
const config = header.config;
|
|
280
|
+
return config.reasoningEffort === undefined
|
|
281
|
+
? { provider: config.provider, model: config.model }
|
|
282
|
+
: { provider: config.provider, model: config.model, reasoningEffort: config.reasoningEffort };
|
|
283
|
+
}
|
|
284
|
+
if (fallback.provider !== undefined && fallback.model !== undefined) {
|
|
285
|
+
return { provider: fallback.provider, model: fallback.model };
|
|
286
|
+
}
|
|
287
|
+
return undefined;
|
|
288
|
+
}
|
|
289
|
+
/**
|
|
290
|
+
* Parse the model's JSON reply into the session summary and its drafts,
|
|
291
|
+
* tolerating a code fence.
|
|
292
|
+
*
|
|
293
|
+
* Every usable draft in the reply is validated even once the cap is reached, so
|
|
294
|
+
* the caller can report how many were dropped. A pass that always lands exactly
|
|
295
|
+
* on the cap looks identical to a pass that found exactly that many facts, and
|
|
296
|
+
* the difference is the only signal that `extractMaxMemories` is the knob
|
|
297
|
+
* limiting what the plugin remembers.
|
|
298
|
+
*
|
|
299
|
+
* @param text - the model's reply.
|
|
300
|
+
* @param maxMemories - how many drafts to keep.
|
|
301
|
+
* @param sessionId - session the drafts came from, recorded as provenance.
|
|
302
|
+
* @returns the drafts, the evidence summary, and how many were over the cap.
|
|
303
|
+
*/
|
|
304
|
+
export function parseExtraction(text, maxMemories, sessionId) {
|
|
305
|
+
const result = { drafts: [], loops: [], summary: '', dropped: 0 };
|
|
306
|
+
const trimmed = text.trim().replace(/^```(?:json)?\s*/iu, '').replace(/```$/u, '').trim();
|
|
307
|
+
const start = trimmed.indexOf('{');
|
|
308
|
+
const end = trimmed.lastIndexOf('}');
|
|
309
|
+
if (start < 0 || end <= start)
|
|
310
|
+
return result;
|
|
311
|
+
let parsed;
|
|
312
|
+
try {
|
|
313
|
+
parsed = JSON.parse(trimmed.slice(start, end + 1));
|
|
314
|
+
}
|
|
315
|
+
catch {
|
|
316
|
+
return result;
|
|
317
|
+
}
|
|
318
|
+
if (typeof parsed !== 'object' || parsed === null || !('memories' in parsed))
|
|
319
|
+
return result;
|
|
320
|
+
const envelope = parsed;
|
|
321
|
+
if (typeof envelope.summary === 'string') {
|
|
322
|
+
result.summary = redactSecrets(envelope.summary.replace(/\s+/gu, ' ').trim()).slice(0, 1_200);
|
|
323
|
+
}
|
|
324
|
+
const raw = envelope.memories;
|
|
325
|
+
if (!Array.isArray(raw))
|
|
326
|
+
return result;
|
|
327
|
+
const usable = [];
|
|
328
|
+
for (const item of raw) {
|
|
329
|
+
if (typeof item !== 'object' || item === null)
|
|
330
|
+
continue;
|
|
331
|
+
const record = item;
|
|
332
|
+
const scope = record['scope'];
|
|
333
|
+
const title = record['title'];
|
|
334
|
+
const body = record['body'];
|
|
335
|
+
if (scope !== 'global' && scope !== 'project')
|
|
336
|
+
continue;
|
|
337
|
+
if (typeof title !== 'string' || typeof body !== 'string')
|
|
338
|
+
continue;
|
|
339
|
+
const cleanTitle = redactSecrets(title.replace(/\s+/gu, ' ').trim()).slice(0, 120);
|
|
340
|
+
const cleanBody = redactSecrets(body.trim()).slice(0, 2000);
|
|
341
|
+
if (cleanTitle.length === 0 || cleanBody.length === 0)
|
|
342
|
+
continue;
|
|
343
|
+
if (cleanTitle === '[redacted]' || cleanBody === '[redacted]')
|
|
344
|
+
continue;
|
|
345
|
+
const tags = Array.isArray(record['tags'])
|
|
346
|
+
? record['tags'].filter((tag) => typeof tag === 'string')
|
|
347
|
+
: [];
|
|
348
|
+
const keys = Array.isArray(record['keys']) ? record['keys'].filter((key) => typeof key === 'string') : [];
|
|
349
|
+
const appliesTo = typeof record['appliesTo'] === 'string'
|
|
350
|
+
? redactSecrets(record['appliesTo'].replace(/\s+/gu, ' ').trim()).slice(0, 160)
|
|
351
|
+
: '';
|
|
352
|
+
// A snapshot without a date cannot be judged later, so it gets one: the
|
|
353
|
+
// extractor's own claim if it parsed, otherwise the moment of extraction.
|
|
354
|
+
const snapshot = record['durability'] === 'snapshot';
|
|
355
|
+
const parsedAsOf = typeof record['asOf'] === 'string' ? Date.parse(record['asOf']) : Number.NaN;
|
|
356
|
+
// The evidence excerpt. Kept as close to the reply as verification allows:
|
|
357
|
+
// only whitespace is normalized (a long transcript line may be re-wrapped),
|
|
358
|
+
// never punctuation or wording — those are what the substring check proves.
|
|
359
|
+
const quote = typeof record['quote'] === 'string'
|
|
360
|
+
? redactSecrets(record['quote'].replace(/\s+/gu, ' ').trim()).slice(0, 300)
|
|
361
|
+
: '';
|
|
362
|
+
// "assistant" is the default and is stored as absent, so every entry written
|
|
363
|
+
// before this field existed keeps its meaning.
|
|
364
|
+
const voice = record['voice'] === 'user' ? 'user' : undefined;
|
|
365
|
+
usable.push({
|
|
366
|
+
scope: scope,
|
|
367
|
+
kind: toMemoryKind(record['kind']),
|
|
368
|
+
title: cleanTitle,
|
|
369
|
+
body: cleanBody,
|
|
370
|
+
tags,
|
|
371
|
+
keys,
|
|
372
|
+
...voice === undefined ? {} : { voice },
|
|
373
|
+
...appliesTo.length > 0 ? { appliesTo } : {},
|
|
374
|
+
...quote.length > 0 && quote !== '[redacted]' ? { quote } : {},
|
|
375
|
+
...snapshot ? { durability: 'snapshot', asOf: Number.isFinite(parsedAsOf) ? parsedAsOf : Date.now() } : {},
|
|
376
|
+
sourceSession: sessionId,
|
|
377
|
+
});
|
|
378
|
+
}
|
|
379
|
+
result.drafts = usable.slice(0, Math.max(0, maxMemories));
|
|
380
|
+
result.dropped = usable.length - result.drafts.length;
|
|
381
|
+
result.loops = parseLoops(envelope.loops);
|
|
382
|
+
return result;
|
|
383
|
+
}
|
|
384
|
+
/**
|
|
385
|
+
* Shortest quote that can count as evidence.
|
|
386
|
+
*
|
|
387
|
+
* Four characters was too few in practice: a phrase like "这个" or "pnpm" occurs
|
|
388
|
+
* in most messages, so it would "verify" a claim it does not support. Eight
|
|
389
|
+
* characters is about the shortest span that can carry a claim in Chinese and
|
|
390
|
+
* still be unique enough to be worth checking.
|
|
391
|
+
*/
|
|
392
|
+
const MIN_QUOTE_CHARS = 8;
|
|
393
|
+
/** Collapse whitespace so a re-wrapped quote still matches its source line. */
|
|
394
|
+
function squash(value) {
|
|
395
|
+
return value.replace(/\s+/gu, ' ').trim();
|
|
396
|
+
}
|
|
397
|
+
/**
|
|
398
|
+
* Check every draft's quote against the transcript it claims to come from.
|
|
399
|
+
*
|
|
400
|
+
* This is the mechanical half of the evidence contract: the extractor is asked
|
|
401
|
+
* to copy a verbatim passage, and nothing else in the pipeline can tell a copied
|
|
402
|
+
* passage from a plausible one. A draft without a usable quote is dropped rather
|
|
403
|
+
* than stored unverified — the whole point of the field is that a memory the
|
|
404
|
+
* transcript does not support must not enter the store silently. The message the
|
|
405
|
+
* quote matched supplies an `evidenceSeq`, so `memory action=evidence` can point
|
|
406
|
+
* at the exact turn.
|
|
407
|
+
*
|
|
408
|
+
* @param drafts - drafts parsed from the reply.
|
|
409
|
+
* @param sources - messages in the window the reply was shown.
|
|
410
|
+
* @returns the verified drafts and how many were rejected.
|
|
411
|
+
*/
|
|
412
|
+
export function bindEvidence(drafts, sources) {
|
|
413
|
+
const verified = [];
|
|
414
|
+
let unsupported = 0;
|
|
415
|
+
for (const draft of drafts) {
|
|
416
|
+
const quote = draft.quote === undefined ? '' : squash(draft.quote);
|
|
417
|
+
if (quote.length < MIN_QUOTE_CHARS) {
|
|
418
|
+
unsupported += 1;
|
|
419
|
+
continue;
|
|
420
|
+
}
|
|
421
|
+
const source = sources.find((candidate) => squash(candidate.text).includes(quote));
|
|
422
|
+
if (source === undefined) {
|
|
423
|
+
unsupported += 1;
|
|
424
|
+
continue;
|
|
425
|
+
}
|
|
426
|
+
verified.push({ ...draft, evidenceSeq: source.seq });
|
|
427
|
+
}
|
|
428
|
+
return { drafts: verified, unsupported };
|
|
429
|
+
}
|
|
430
|
+
/** The user's local calendar date, as `YYYY-MM-DD`, for resolving relative times. */
|
|
431
|
+
function localDate(now = new Date()) {
|
|
432
|
+
// `sv-SE` short date is ISO-like and uses the runtime's local time zone; UTC
|
|
433
|
+
// would name the wrong day for a user east or west of it (at 01:30 in Shanghai,
|
|
434
|
+
// the UTC date is still yesterday).
|
|
435
|
+
return new Intl.DateTimeFormat('sv-SE', { dateStyle: 'short' }).format(now);
|
|
436
|
+
}
|
|
437
|
+
/**
|
|
438
|
+
* Run one extraction call and return the drafts it produced.
|
|
439
|
+
*
|
|
440
|
+
* Failures are the caller's to contain: this function throws only on transport
|
|
441
|
+
* or protocol errors, and never mutates the session.
|
|
442
|
+
*
|
|
443
|
+
* @param llm - the LLM runtime.
|
|
444
|
+
* @param request - session, window, route, and budget.
|
|
445
|
+
* @returns the parsed drafts, or a reason there are none.
|
|
446
|
+
*/
|
|
447
|
+
export async function runExtraction(llm, request) {
|
|
448
|
+
if (request.window.text.trim().length === 0)
|
|
449
|
+
return { kind: 'none', reason: 'empty-window' };
|
|
450
|
+
const route = resolveLlmRoute(request.session, request.provider, request.model, request.fallbackRoute ?? {});
|
|
451
|
+
if (route === undefined)
|
|
452
|
+
return { kind: 'none', reason: 'no-route' };
|
|
453
|
+
const known = request.knownTitles ?? [];
|
|
454
|
+
const framed = [
|
|
455
|
+
`Workspace scope label: ${request.projectLabel}`,
|
|
456
|
+
`Today's date is ${localDate()} (the user's local date). Resolve every relative time in the transcript against it.`,
|
|
457
|
+
`Extract at most ${request.maxMemories} memories from this transcript.`,
|
|
458
|
+
...known.length === 0 ? [] : [
|
|
459
|
+
'',
|
|
460
|
+
'Memories already stored in the scopes this pass writes to:',
|
|
461
|
+
...known.map((title) => `- ${title}`),
|
|
462
|
+
'If the transcript adds to (or corrects) one of those, reuse its EXACT title so that entry is updated instead of duplicated. Only invent a new title for a genuinely new fact.',
|
|
463
|
+
],
|
|
464
|
+
'',
|
|
465
|
+
request.window.text,
|
|
466
|
+
].join('\n');
|
|
467
|
+
const messages = [createUserMessage({
|
|
468
|
+
content: [{ type: 'text', text: framed }],
|
|
469
|
+
source: { kind: MEMORY_SOURCE_KIND },
|
|
470
|
+
})];
|
|
471
|
+
const timeout = AbortSignal.any([request.signal, AbortSignal.timeout(request.timeoutMs)]);
|
|
472
|
+
const options = {
|
|
473
|
+
provider: route.provider,
|
|
474
|
+
model: route.model,
|
|
475
|
+
messages,
|
|
476
|
+
system: EXTRACT_SYSTEM,
|
|
477
|
+
maxTokens: request.maxOutputTokens,
|
|
478
|
+
purpose: 'compaction',
|
|
479
|
+
sessionId: request.session.id,
|
|
480
|
+
signal: timeout,
|
|
481
|
+
};
|
|
482
|
+
const assembler = new BlockAssembler();
|
|
483
|
+
for await (const chunk of llm.stream(options))
|
|
484
|
+
assembler.push(chunk);
|
|
485
|
+
const finish = assembler.finish.kind;
|
|
486
|
+
const text = assembler.blocks()
|
|
487
|
+
.filter((block) => block.type === 'text')
|
|
488
|
+
.map((block) => block.text)
|
|
489
|
+
.join('\n');
|
|
490
|
+
// The adapter emits usage before the terminal finish chunk; when a provider
|
|
491
|
+
// reports none, the call still happened and simply cannot be priced here.
|
|
492
|
+
const reported = assembler.usage;
|
|
493
|
+
const usage = reported === undefined
|
|
494
|
+
? undefined
|
|
495
|
+
: { inputTokens: reported.inputTokens, outputTokens: reported.outputTokens };
|
|
496
|
+
if (finish !== 'stop') {
|
|
497
|
+
// A reply the output cap cut short is not a failure of the pass. Throwing
|
|
498
|
+
// here turned an ordinary "raise `extractMaxOutputTokens`" into an exception
|
|
499
|
+
// that reached the user's own command line (`/memories mine` reports the
|
|
500
|
+
// handler error verbatim) and made a background pass look broken — measured
|
|
501
|
+
// 2026-09-23, the first `/memories mine` in the field died this way.
|
|
502
|
+
//
|
|
503
|
+
// The extractor is asked for one object whose `memories` array comes first,
|
|
504
|
+
// so a truncated reply is normally an unterminated array of COMPLETE
|
|
505
|
+
// objects: keep what parsed, and only when nothing did does the caller hear
|
|
506
|
+
// about the cap.
|
|
507
|
+
const complete = parseExtraction(text, request.maxMemories, request.session.id);
|
|
508
|
+
const salvaged = complete.drafts.length > 0
|
|
509
|
+
? complete
|
|
510
|
+
: parseExtraction(repairTruncatedJson(text), request.maxMemories, request.session.id);
|
|
511
|
+
// Evidence is checked before "was anything kept": a salvaged object whose
|
|
512
|
+
// quote is not in the transcript is exactly the case the check exists for.
|
|
513
|
+
const bound = bindEvidence(salvaged.drafts, request.window.sources);
|
|
514
|
+
if (bound.drafts.length > 0) {
|
|
515
|
+
return {
|
|
516
|
+
kind: 'memories',
|
|
517
|
+
drafts: bound.drafts,
|
|
518
|
+
loops: salvaged.loops,
|
|
519
|
+
summary: salvaged.summary,
|
|
520
|
+
dropped: salvaged.dropped,
|
|
521
|
+
unsupported: bound.unsupported,
|
|
522
|
+
route,
|
|
523
|
+
truncated: true,
|
|
524
|
+
...usage === undefined ? {} : { usage },
|
|
525
|
+
};
|
|
526
|
+
}
|
|
527
|
+
if (bound.unsupported > 0) {
|
|
528
|
+
return { kind: 'none', reason: 'unsupported-evidence', route, ...usage === undefined ? {} : { usage } };
|
|
529
|
+
}
|
|
530
|
+
return { kind: 'none', reason: finish === 'max-tokens' ? 'max-tokens' : 'incomplete', route, ...usage === undefined ? {} : { usage } };
|
|
531
|
+
}
|
|
532
|
+
const parsed = parseExtraction(text, request.maxMemories, request.session.id);
|
|
533
|
+
if (parsed.drafts.length === 0)
|
|
534
|
+
return { kind: 'none', reason: 'empty-reply', route, ...usage === undefined ? {} : { usage } };
|
|
535
|
+
const bound = bindEvidence(parsed.drafts, request.window.sources);
|
|
536
|
+
if (bound.drafts.length === 0) {
|
|
537
|
+
return { kind: 'none', reason: 'unsupported-evidence', route, ...usage === undefined ? {} : { usage } };
|
|
538
|
+
}
|
|
539
|
+
return { kind: 'memories', drafts: bound.drafts, loops: parsed.loops, summary: parsed.summary, dropped: parsed.dropped, unsupported: bound.unsupported, route, ...usage === undefined ? {} : { usage } };
|
|
540
|
+
}
|
|
541
|
+
/**
|
|
542
|
+
* Close a JSON reply the output cap cut in half.
|
|
543
|
+
*
|
|
544
|
+
* The reply is one object whose `memories` array is written first, so a
|
|
545
|
+
* truncated reply is an unterminated array whose earlier elements are complete.
|
|
546
|
+
* Candidate cut points are tried from the end backwards — the first one that
|
|
547
|
+
* parses wins — which keeps every memory that was fully written. A reply cut
|
|
548
|
+
* inside a string, or before the first object, yields `''` so the caller can
|
|
549
|
+
* report the cap instead of pretending it salvaged something.
|
|
550
|
+
*
|
|
551
|
+
* @param text - the truncated reply.
|
|
552
|
+
* @returns parseable JSON, or an empty string when no cut point parses.
|
|
553
|
+
*/
|
|
554
|
+
export function repairTruncatedJson(text) {
|
|
555
|
+
const trimmed = text.trim().replace(/^```(?:json)?\s*/iu, '');
|
|
556
|
+
let cursor = trimmed.lastIndexOf('}');
|
|
557
|
+
let attempts = 0;
|
|
558
|
+
while (cursor > 0 && attempts < 64) {
|
|
559
|
+
const candidate = `${trimmed.slice(0, cursor + 1)}]}`;
|
|
560
|
+
try {
|
|
561
|
+
JSON.parse(candidate);
|
|
562
|
+
return candidate;
|
|
563
|
+
}
|
|
564
|
+
catch {
|
|
565
|
+
cursor = trimmed.lastIndexOf('}', cursor - 1);
|
|
566
|
+
attempts += 1;
|
|
567
|
+
}
|
|
568
|
+
}
|
|
569
|
+
return '';
|
|
570
|
+
}
|