dsh-cross-memory 0.0.0-stage → 0.2.1
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 +253 -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 +1660 -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 +4482 -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 +163 -0
- package/lib/query.js +93 -0
- package/lib/raw-recall.js +286 -0
- package/lib/reflection.js +291 -0
- package/lib/remote.js +490 -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 +341 -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 +142 -0
- package/lib/test/persona.test.js +86 -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 +238 -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 +76 -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 +246 -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
|
@@ -0,0 +1,1119 @@
|
|
|
1
|
+
import { BlockAssembler, createUserMessage } from '@deepseek-ai/dsh-llm';
|
|
2
|
+
import { mkdir, readFile, rm, writeFile } from 'node:fs/promises';
|
|
3
|
+
import { dirname, join } from 'node:path';
|
|
4
|
+
import { PERSONA_MAX_SOURCE_CHARS } from './persona.js';
|
|
5
|
+
import { carriesForward } from './storage.js';
|
|
6
|
+
import { toMemoryKind } from './types.js';
|
|
7
|
+
import { MEMORY_SOURCE_KIND } from './types.js';
|
|
8
|
+
/** System instruction for the consolidation sub-agent. */
|
|
9
|
+
export const CONSOLIDATE_SYSTEM = [
|
|
10
|
+
'You maintain the long-term memory of a coding assistant. You are given the CURRENT memories and must return a better set.',
|
|
11
|
+
'',
|
|
12
|
+
'You may:',
|
|
13
|
+
'- MERGE several memories that describe the same thing into one clear memory.',
|
|
14
|
+
'- REPLACE a memory that is now wrong or superseded, keeping its id.',
|
|
15
|
+
'- RETIRE a memory that is stale, trivial, duplicated, or no longer true.',
|
|
16
|
+
'- ADD a memory only when the input clearly states a durable fact that no current memory captures.',
|
|
17
|
+
'',
|
|
18
|
+
'Rules:',
|
|
19
|
+
'- Preserve every id you keep. A returned memory with an existing id REPLACES that memory; a new id ADDS one.',
|
|
20
|
+
'- Prefer fewer, sharper memories. Never invent facts that are not in the input.',
|
|
21
|
+
'- Keep scope honest: an EXISTING memory never changes scope — scope decides which sessions a memory is injected into, so the pass places new memories but leaves current ones where they are. Choose a scope for a NEW memory by breadth: "global" for anything true across the developer\'s machines and projects (preferences, tooling, machine and path facts, network and proxy setup, how to move work between machines); "project" only for a fact about one workspace that would be wrong or meaningless anywhere else. 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 stays global even when it mentions such a name.',
|
|
22
|
+
'- Keep the kind honest: "preference" for how the user wants work done, "failure" for something that went wrong, "procedure" for an ordered recipe, "knowledge" for a non-obvious technique, "fact" for background.',
|
|
23
|
+
'- When you MERGE memories into one, list every id you folded in under "derivedFrom" (the ids you are retiring because their content now lives in the merged memory). A plain rewrite of one memory, or a brand-new memory, gets an empty list. This is the only record of what a merge replaced: the sources are archived, and without the list a future reader cannot check the merged claim against what it replaced.',
|
|
24
|
+
'- Do not record secrets, credentials, transient task state, or restatements of code.',
|
|
25
|
+
'- Write every title, body and appliesTo in Simplified Chinese, keeping paths, commands, identifiers and product names exactly as they are. A memory the model wrote in Chinese must not come back in English.',
|
|
26
|
+
'- 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. This matters most when merging: the merged body must open with the one thing a future session needs.',
|
|
27
|
+
'- Always provide "appliesTo": a short phrase in the user\'s words saying when the memory matters ("准备推送代码之前"). When you rewrite a memory that already has one, carry it over unless the rewrite makes it wrong.',
|
|
28
|
+
'- 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>. When a number IS the point of the memory, set "durability":"snapshot" with "asOf" as the date it was measured, and carry both over when you rewrite such a memory.',
|
|
29
|
+
'- Never change a memory\'s "durability" or "asOf" by omission: a memory that already is a snapshot stays one unless the fact has become durable.',
|
|
30
|
+
'- A problem that is already fixed is recorded as fixed ("已修 in <commit>"); never leave it reading as an open problem.',
|
|
31
|
+
'- Write each body as 1-4 self-contained sentences. Titles are short and imperative.',
|
|
32
|
+
'',
|
|
33
|
+
'When two or more memories together describe a repeatable procedure that would be worth running again, also return it as a skill: a short kebab-case name, a one-line description, and the ordered steps. Skills are drafts a human promotes; return at most 2.',
|
|
34
|
+
'',
|
|
35
|
+
'When two memories contradict each other, do not quietly pick one: list the pair under "conflicts" with the id to keep, the id to drop, and one sentence saying what disagrees. A memory from the user ("voice: user") beats one the assistant concluded, and the newer statement beats the older — unless a rule is permanent, in which case name the pair and drop the OTHER one. "conflicts" is a report as much as an instruction: it is how the user finds out they changed their mind.',
|
|
36
|
+
'Also maintain "persona": a short profile of the USER, in markdown, built only from what they themselves said. The input marks those entries with "voice: user" and may include the current profile — refine it, do not rewrite it from nothing, and keep it under 40 lines. Contents: how they want work done, the corrections they have issued, how they write, what they care about, and what they never want. Write it in the third person ("他要求…"), never as instructions to yourself. If no entry carries voice: user, and no current profile exists, omit the field entirely.',
|
|
37
|
+
'',
|
|
38
|
+
'Reply with JSON only, no prose and no code fence:',
|
|
39
|
+
'{"memories":[{"id":string|null,"scope":"global"|"project","kind":string,"title":string,"body":string,"tags":string[],"keys":string[],"appliesTo":string,"derivedFrom":string[]}],"retire":[string],"skills":[{"name":string,"description":string,"steps":string[]}],"notes":string,"persona":string}',
|
|
40
|
+
'Use null for the id of a new memory. "retire" lists ids to delete. "notes" is one short sentence about what you changed.',
|
|
41
|
+
].join('\n');
|
|
42
|
+
/** JSON output contract for one consolidation call. */
|
|
43
|
+
export const CONSOLIDATE_JSON_SCHEMA = {
|
|
44
|
+
type: 'object',
|
|
45
|
+
additionalProperties: false,
|
|
46
|
+
required: ['memories'],
|
|
47
|
+
properties: {
|
|
48
|
+
memories: {
|
|
49
|
+
type: 'array',
|
|
50
|
+
items: {
|
|
51
|
+
type: 'object',
|
|
52
|
+
additionalProperties: false,
|
|
53
|
+
required: ['scope', 'title', 'body', 'appliesTo'],
|
|
54
|
+
properties: {
|
|
55
|
+
// A nullable field must be spelled with `oneOf`: the harness schema
|
|
56
|
+
// subset rejects `type: ["string", "null"]`, and a rejected schema
|
|
57
|
+
// fails the whole child run at start.
|
|
58
|
+
id: { oneOf: [{ type: 'string' }, { type: 'null' }] },
|
|
59
|
+
scope: { type: 'string', enum: ['global', 'project'] },
|
|
60
|
+
kind: { type: 'string', enum: ['fact', 'preference', 'knowledge', 'failure', 'procedure'] },
|
|
61
|
+
title: { type: 'string' },
|
|
62
|
+
body: { type: 'string' },
|
|
63
|
+
tags: { type: 'array', items: { type: 'string' } },
|
|
64
|
+
appliesTo: { type: 'string' },
|
|
65
|
+
durability: { type: 'string', enum: ['durable', 'snapshot'] },
|
|
66
|
+
asOf: { type: 'string' },
|
|
67
|
+
derivedFrom: { type: 'array', items: { type: 'string' } },
|
|
68
|
+
},
|
|
69
|
+
},
|
|
70
|
+
},
|
|
71
|
+
retire: { type: 'array', items: { type: 'string' } },
|
|
72
|
+
skills: {
|
|
73
|
+
type: 'array',
|
|
74
|
+
items: {
|
|
75
|
+
type: 'object',
|
|
76
|
+
additionalProperties: false,
|
|
77
|
+
required: ['name', 'description', 'steps'],
|
|
78
|
+
properties: {
|
|
79
|
+
name: { type: 'string' },
|
|
80
|
+
description: { type: 'string' },
|
|
81
|
+
steps: { type: 'array', items: { type: 'string' } },
|
|
82
|
+
},
|
|
83
|
+
},
|
|
84
|
+
},
|
|
85
|
+
notes: { type: 'string' },
|
|
86
|
+
persona: { type: 'string' },
|
|
87
|
+
conflicts: {
|
|
88
|
+
type: 'array',
|
|
89
|
+
items: {
|
|
90
|
+
type: 'object',
|
|
91
|
+
additionalProperties: false,
|
|
92
|
+
required: ['keep', 'drop', 'reason'],
|
|
93
|
+
properties: {
|
|
94
|
+
keep: { type: 'string' },
|
|
95
|
+
drop: { type: 'string' },
|
|
96
|
+
reason: { type: 'string' },
|
|
97
|
+
},
|
|
98
|
+
},
|
|
99
|
+
},
|
|
100
|
+
},
|
|
101
|
+
};
|
|
102
|
+
/** Render the input document handed to the consolidation agent. */
|
|
103
|
+
export function renderConsolidationInput(entries, projectLabel, currentPersona) {
|
|
104
|
+
const sections = new Map();
|
|
105
|
+
for (const entry of entries) {
|
|
106
|
+
const list = sections.get(entry.scope);
|
|
107
|
+
if (list === undefined)
|
|
108
|
+
sections.set(entry.scope, [entry]);
|
|
109
|
+
else
|
|
110
|
+
list.push(entry);
|
|
111
|
+
}
|
|
112
|
+
const blocks = [`Workspace scope label: ${projectLabel}`, `Current memories: ${entries.length}`, ''];
|
|
113
|
+
if (currentPersona !== undefined && currentPersona.trim().length > 0) {
|
|
114
|
+
blocks.push('## Current profile of the user (refine it; do not rewrite it from nothing)');
|
|
115
|
+
blocks.push(currentPersona.trim(), '');
|
|
116
|
+
}
|
|
117
|
+
for (const scope of ['global', 'project']) {
|
|
118
|
+
const list = sections.get(scope);
|
|
119
|
+
if (list === undefined || list.length === 0)
|
|
120
|
+
continue;
|
|
121
|
+
blocks.push(`## ${scope}`);
|
|
122
|
+
for (const entry of list) {
|
|
123
|
+
blocks.push(`- id: ${entry.id}`);
|
|
124
|
+
blocks.push(` title: ${entry.title}`);
|
|
125
|
+
blocks.push(` tags: ${entry.tags.join(', ') || '(none)'}`);
|
|
126
|
+
blocks.push(` keys: ${entry.keys.join(', ') || '(none)'}`);
|
|
127
|
+
blocks.push(` body: ${entry.body.replace(/\n+/gu, ' ')}`);
|
|
128
|
+
if (entry.voice === 'user')
|
|
129
|
+
blocks.push(' voice: user (the user\'s own words)');
|
|
130
|
+
}
|
|
131
|
+
blocks.push('');
|
|
132
|
+
}
|
|
133
|
+
return blocks.join('\n');
|
|
134
|
+
}
|
|
135
|
+
/** Parse and validate the agent's JSON reply into a plan. */
|
|
136
|
+
export function parsePlan(text, knownIds, maxUpserts) {
|
|
137
|
+
const trimmed = text.trim().replace(/^```(?:json)?\s*/iu, '').replace(/```$/u, '').trim();
|
|
138
|
+
const start = trimmed.indexOf('{');
|
|
139
|
+
const end = trimmed.lastIndexOf('}');
|
|
140
|
+
if (start < 0 || end <= start)
|
|
141
|
+
return undefined;
|
|
142
|
+
let parsed;
|
|
143
|
+
try {
|
|
144
|
+
parsed = JSON.parse(trimmed.slice(start, end + 1));
|
|
145
|
+
}
|
|
146
|
+
catch {
|
|
147
|
+
return undefined;
|
|
148
|
+
}
|
|
149
|
+
if (typeof parsed !== 'object' || parsed === null)
|
|
150
|
+
return undefined;
|
|
151
|
+
const record = parsed;
|
|
152
|
+
const rawMemories = Array.isArray(record['memories']) ? record['memories'] : [];
|
|
153
|
+
const upserts = [];
|
|
154
|
+
const seen = new Set();
|
|
155
|
+
for (const item of rawMemories) {
|
|
156
|
+
if (upserts.length >= maxUpserts)
|
|
157
|
+
break;
|
|
158
|
+
if (typeof item !== 'object' || item === null)
|
|
159
|
+
continue;
|
|
160
|
+
const entry = item;
|
|
161
|
+
const scope = entry['scope'];
|
|
162
|
+
const title = entry['title'];
|
|
163
|
+
const body = entry['body'];
|
|
164
|
+
if (scope !== 'global' && scope !== 'project')
|
|
165
|
+
continue;
|
|
166
|
+
if (typeof title !== 'string' || typeof body !== 'string')
|
|
167
|
+
continue;
|
|
168
|
+
const cleanTitle = title.replace(/\s+/gu, ' ').trim().slice(0, 120);
|
|
169
|
+
const cleanBody = body.trim().slice(0, 2000);
|
|
170
|
+
if (cleanTitle.length === 0 || cleanBody.length === 0)
|
|
171
|
+
continue;
|
|
172
|
+
// A "replace" id the store does not know is treated as a new memory: the
|
|
173
|
+
// agent inventing an id must not create a dangling reference.
|
|
174
|
+
const rawId = entry['id'];
|
|
175
|
+
const id = typeof rawId === 'string' && knownIds.has(rawId) ? rawId : null;
|
|
176
|
+
if (id !== null && seen.has(id))
|
|
177
|
+
continue;
|
|
178
|
+
if (id !== null)
|
|
179
|
+
seen.add(id);
|
|
180
|
+
const tags = Array.isArray(entry['tags']) ? entry['tags'].filter((tag) => typeof tag === 'string') : [];
|
|
181
|
+
const keys = Array.isArray(entry['keys']) ? entry['keys'].filter((key) => typeof key === 'string') : [];
|
|
182
|
+
const appliesTo = typeof entry['appliesTo'] === 'string' ? entry['appliesTo'].replace(/\s+/gu, ' ').trim().slice(0, 160) : '';
|
|
183
|
+
// A plan that omits durability must not silently turn a snapshot durable:
|
|
184
|
+
// the upsert preserves the stored value, so only an explicit field is passed.
|
|
185
|
+
const snapshot = entry['durability'] === 'snapshot';
|
|
186
|
+
const parsedAsOf = typeof entry['asOf'] === 'string' ? Date.parse(entry['asOf']) : Number.NaN;
|
|
187
|
+
// Only ids the store has, never the entry itself: a merge trail that points
|
|
188
|
+
// at a memory nobody can open is worse than no trail, because it reads as
|
|
189
|
+
// evidence. The same discipline the `id` field already follows.
|
|
190
|
+
const rawDerived = Array.isArray(entry['derivedFrom']) ? entry['derivedFrom'] : [];
|
|
191
|
+
const derivedFrom = [...new Set(rawDerived.filter((value) => typeof value === 'string' && knownIds.has(value) && value !== id))];
|
|
192
|
+
upserts.push({
|
|
193
|
+
id,
|
|
194
|
+
scope,
|
|
195
|
+
kind: toMemoryKind(entry['kind']),
|
|
196
|
+
title: cleanTitle,
|
|
197
|
+
body: cleanBody,
|
|
198
|
+
tags,
|
|
199
|
+
keys,
|
|
200
|
+
...appliesTo.length > 0 ? { appliesTo } : {},
|
|
201
|
+
...snapshot ? { durability: 'snapshot', ...Number.isFinite(parsedAsOf) ? { asOf: parsedAsOf } : {} } : {},
|
|
202
|
+
...derivedFrom.length > 0 ? { derivedFrom } : {},
|
|
203
|
+
});
|
|
204
|
+
}
|
|
205
|
+
const rawRetire = Array.isArray(record['retire']) ? record['retire'] : [];
|
|
206
|
+
const retired = new Set();
|
|
207
|
+
for (const value of rawRetire) {
|
|
208
|
+
if (typeof value !== 'string')
|
|
209
|
+
continue;
|
|
210
|
+
// Only ids the store actually has, and never one this plan rewrites.
|
|
211
|
+
if (!knownIds.has(value) || seen.has(value))
|
|
212
|
+
continue;
|
|
213
|
+
retired.add(value);
|
|
214
|
+
}
|
|
215
|
+
const skills = parseSkills(record['skills']);
|
|
216
|
+
const conflicts = parseConflicts(record['conflicts'], knownIds, retired);
|
|
217
|
+
const persona = typeof record['persona'] === 'string' ? record['persona'].trim().slice(0, PERSONA_MAX_SOURCE_CHARS) : '';
|
|
218
|
+
// A pass that only refines the profile is a real outcome: the profile changes
|
|
219
|
+
// without any memory moving, and dropping that reply would lose it.
|
|
220
|
+
if (upserts.length === 0 && retired.size === 0 && skills.length === 0 && persona.length === 0 && conflicts.length === 0)
|
|
221
|
+
return undefined;
|
|
222
|
+
return {
|
|
223
|
+
upserts,
|
|
224
|
+
retire: [...retired],
|
|
225
|
+
skills,
|
|
226
|
+
notes: typeof record['notes'] === 'string' ? record['notes'].slice(0, 300) : '',
|
|
227
|
+
...persona.length > 0 ? { persona } : {},
|
|
228
|
+
...conflicts.length > 0 ? { conflicts } : {},
|
|
229
|
+
};
|
|
230
|
+
}
|
|
231
|
+
/**
|
|
232
|
+
* Parse the contradiction report of one reply.
|
|
233
|
+
*
|
|
234
|
+
* Only ids the store actually has, never a pair that names the same memory
|
|
235
|
+
* twice, and never a "drop" the same plan is already retiring for another
|
|
236
|
+
* reason — that entry's question is already on its way to the reader.
|
|
237
|
+
*
|
|
238
|
+
* @param value - the raw `conflicts` field.
|
|
239
|
+
* @param knownIds - ids present in the reviewed page.
|
|
240
|
+
* @param retired - ids this plan already retires.
|
|
241
|
+
* @returns at most ten conflicts.
|
|
242
|
+
*/
|
|
243
|
+
function parseConflicts(value, knownIds, retired) {
|
|
244
|
+
if (!Array.isArray(value))
|
|
245
|
+
return [];
|
|
246
|
+
const conflicts = [];
|
|
247
|
+
const seen = new Set();
|
|
248
|
+
for (const item of value) {
|
|
249
|
+
if (conflicts.length >= 10)
|
|
250
|
+
break;
|
|
251
|
+
if (typeof item !== 'object' || item === null)
|
|
252
|
+
continue;
|
|
253
|
+
const record = item;
|
|
254
|
+
const keep = typeof record['keep'] === 'string' ? record['keep'] : '';
|
|
255
|
+
const drop = typeof record['drop'] === 'string' ? record['drop'] : '';
|
|
256
|
+
if (keep === drop || !knownIds.has(keep) || !knownIds.has(drop))
|
|
257
|
+
continue;
|
|
258
|
+
if (retired.has(drop) || seen.has(drop))
|
|
259
|
+
continue;
|
|
260
|
+
seen.add(drop);
|
|
261
|
+
conflicts.push({
|
|
262
|
+
keep,
|
|
263
|
+
drop,
|
|
264
|
+
reason: typeof record['reason'] === 'string' ? record['reason'].replace(/\s+/gu, ' ').trim().slice(0, 200) : '',
|
|
265
|
+
});
|
|
266
|
+
}
|
|
267
|
+
return conflicts;
|
|
268
|
+
}
|
|
269
|
+
/**
|
|
270
|
+
* Turn a contradiction report into questions for a person.
|
|
271
|
+
*
|
|
272
|
+
* A conflict is never auto-resolved, and never even adjudicated: whether a rule
|
|
273
|
+
* still holds is intent, and intent is the one thing only the user knows. The
|
|
274
|
+
* merge child's own opinion about the winner is recorded as the reason, not
|
|
275
|
+
* applied as a verdict. Every conflict therefore reaches a person, whatever
|
|
276
|
+
* `autoDecide` says.
|
|
277
|
+
*
|
|
278
|
+
* @param conflicts - the plan's report.
|
|
279
|
+
* @param entries - the reviewed page, for titles and protection flags.
|
|
280
|
+
* @returns one dispute per resolvable conflict.
|
|
281
|
+
*/
|
|
282
|
+
export function conflictDisputes(conflicts, entries) {
|
|
283
|
+
const byId = new Map(entries.map((entry) => [entry.id, entry]));
|
|
284
|
+
const disputes = [];
|
|
285
|
+
for (const conflict of conflicts) {
|
|
286
|
+
const loser = byId.get(conflict.drop);
|
|
287
|
+
if (loser === undefined)
|
|
288
|
+
continue;
|
|
289
|
+
disputes.push({
|
|
290
|
+
id: loser.id,
|
|
291
|
+
scope: loser.scope,
|
|
292
|
+
action: 'retire',
|
|
293
|
+
title: loser.title,
|
|
294
|
+
reason: `与 ${conflict.keep} 矛盾${conflict.reason.length > 0 ? ':' + conflict.reason : ''}`,
|
|
295
|
+
before: loser.body,
|
|
296
|
+
after: '',
|
|
297
|
+
hard: true,
|
|
298
|
+
});
|
|
299
|
+
}
|
|
300
|
+
return disputes;
|
|
301
|
+
}
|
|
302
|
+
/**
|
|
303
|
+
* Parse the skill drafts of one reply.
|
|
304
|
+
*
|
|
305
|
+
* A name is forced into the kebab-case grammar DSH's skill loader accepts, and
|
|
306
|
+
* a draft without a usable name, description, or any step is dropped: a skill
|
|
307
|
+
* that cannot be loaded is worse than no skill.
|
|
308
|
+
* @param value - the raw `skills` field.
|
|
309
|
+
* @returns the validated drafts, at most two.
|
|
310
|
+
*/
|
|
311
|
+
function parseSkills(value) {
|
|
312
|
+
if (!Array.isArray(value))
|
|
313
|
+
return [];
|
|
314
|
+
const drafts = [];
|
|
315
|
+
const seen = new Set();
|
|
316
|
+
for (const item of value) {
|
|
317
|
+
if (drafts.length >= MAX_SKILL_DRAFTS)
|
|
318
|
+
break;
|
|
319
|
+
if (typeof item !== 'object' || item === null)
|
|
320
|
+
continue;
|
|
321
|
+
const record = item;
|
|
322
|
+
const rawName = typeof record['name'] === 'string' ? record['name'] : '';
|
|
323
|
+
const name = rawName.toLowerCase().replace(/[^a-z0-9]+/gu, '-').replace(/^-+|-+$/gu, '').slice(0, 64);
|
|
324
|
+
const description = typeof record['description'] === 'string' ? record['description'].replace(/\s+/gu, ' ').trim().slice(0, 300) : '';
|
|
325
|
+
const steps = Array.isArray(record['steps'])
|
|
326
|
+
? record['steps'].filter((step) => typeof step === 'string').map((step) => step.trim()).filter((step) => step.length > 0).slice(0, 20)
|
|
327
|
+
: [];
|
|
328
|
+
if (name.length === 0 || description.length === 0 || steps.length === 0)
|
|
329
|
+
continue;
|
|
330
|
+
if (seen.has(name))
|
|
331
|
+
continue;
|
|
332
|
+
seen.add(name);
|
|
333
|
+
drafts.push({ name, description, steps });
|
|
334
|
+
}
|
|
335
|
+
return drafts;
|
|
336
|
+
}
|
|
337
|
+
/** Cap on skill drafts one pass may propose. */
|
|
338
|
+
const MAX_SKILL_DRAFTS = 2;
|
|
339
|
+
/**
|
|
340
|
+
* The Agent Preset the consolidation child runs under.
|
|
341
|
+
*
|
|
342
|
+
* Since 0.2.1-rc.2 the kernel takes a child's tool set from the preset it
|
|
343
|
+
* names: a request's own `toolFilter` and `persona` are gone, and a child that
|
|
344
|
+
* names no preset inherits the parent's composition — which would hand the
|
|
345
|
+
* consolidation pass the parent's tools, the one thing this pass must never
|
|
346
|
+
* have. This preset carries no tool rows at all, so the child can only answer.
|
|
347
|
+
*/
|
|
348
|
+
export const CONSOLIDATE_PRESET_ID = 'memories-consolidator';
|
|
349
|
+
/**
|
|
350
|
+
* Label every consolidation child runs under.
|
|
351
|
+
*
|
|
352
|
+
* A plain constant, never derived from anything that can be `undefined`: see
|
|
353
|
+
* {@link ActivationSpec.label} for what a missing label does to the child's
|
|
354
|
+
* descriptor.
|
|
355
|
+
*/
|
|
356
|
+
export const CONSOLIDATE_LABEL = '记忆合并';
|
|
357
|
+
/** Output token cap for the direct (no-subagent) consolidation path. */
|
|
358
|
+
export const DEFAULT_CONSOLIDATE_MAX_OUTPUT_TOKENS = 8192;
|
|
359
|
+
/**
|
|
360
|
+
* Tools the consolidation child must not have: it reads and proposes, nothing else.
|
|
361
|
+
*
|
|
362
|
+
* The list is deliberately cross-platform (it names both `bash` and `pwsh`,
|
|
363
|
+
* both `str_replace_editor` and `edit`), so any single deployment has only a
|
|
364
|
+
* subset. {@link denyToolsFor} narrows it before use.
|
|
365
|
+
*/
|
|
366
|
+
export const CONSOLIDATE_DENY_TOOLS = [
|
|
367
|
+
'write', 'edit', 'str_replace_editor', 'pwsh', 'bash', 'terminal',
|
|
368
|
+
'web_search', 'web_fetch', 'subagent', 'subagent_fork', 'workflow', 'ralph',
|
|
369
|
+
'job_kill', 'interrupt_agent', 'memory', 'todo_write', 'create_goal', 'update_goal',
|
|
370
|
+
];
|
|
371
|
+
/**
|
|
372
|
+
* Narrow the deny list to tools this deployment actually has.
|
|
373
|
+
*
|
|
374
|
+
* `tools.restrict()` fails loud on an unknown name — a feature, since a typo in
|
|
375
|
+
* a filter must not silently leave a capability enabled. But a cross-platform
|
|
376
|
+
* deny list names tools that do not exist here, and that loud failure would
|
|
377
|
+
* sink every consolidation pass. Pass the registry's own names and this returns
|
|
378
|
+
* the intersection.
|
|
379
|
+
* @param available - every tool name the registry knows.
|
|
380
|
+
* @returns the deny list, filtered to known names.
|
|
381
|
+
*/
|
|
382
|
+
export function denyToolsFor(available) {
|
|
383
|
+
return CONSOLIDATE_DENY_TOOLS.filter((tool) => available.has(tool));
|
|
384
|
+
}
|
|
385
|
+
/**
|
|
386
|
+
* Run one consolidation through a restricted sub-agent.
|
|
387
|
+
* @param seam - the `ctx.subagents` service.
|
|
388
|
+
* @param request - entries, route, caps, and cancellation.
|
|
389
|
+
* @returns the validated plan, or `undefined` when the child produced none.
|
|
390
|
+
*/
|
|
391
|
+
export async function runConsolidation(seam, request) {
|
|
392
|
+
if (request.entries.length === 0)
|
|
393
|
+
return undefined;
|
|
394
|
+
const known = new Set(request.entries.map((entry) => entry.id));
|
|
395
|
+
const input = renderConsolidationInput(request.entries, request.projectLabel, request.persona);
|
|
396
|
+
const timeout = AbortSignal.any([request.signal, AbortSignal.timeout(request.timeoutMs)]);
|
|
397
|
+
const prompt = [{ type: 'text', text: `${CONSOLIDATE_SYSTEM}\n\n---\n\n${input}` }];
|
|
398
|
+
const reply = await runChild(seam, prompt, request, timeout);
|
|
399
|
+
if (reply === undefined)
|
|
400
|
+
return undefined;
|
|
401
|
+
return parsePlan(reply, known, request.maxUpserts);
|
|
402
|
+
}
|
|
403
|
+
/**
|
|
404
|
+
* Build the spec the 0.2.1-rc.2 seam takes.
|
|
405
|
+
*
|
|
406
|
+
* Extracted so a test can inspect it without a kernel: the one bug this shape
|
|
407
|
+
* can carry — a missing `label` — is invisible from the seam's type unless the
|
|
408
|
+
* type declares the field, and the failure it causes happens inside the
|
|
409
|
+
* kernel's descriptor validator, three calls away from here. See
|
|
410
|
+
* {@link ActivationSpec.label}.
|
|
411
|
+
*
|
|
412
|
+
* @param request - route, preset and lineage parent.
|
|
413
|
+
* @param prompt - the child's single user message.
|
|
414
|
+
* @param timeout - the child's deadline.
|
|
415
|
+
* @returns the spec, with every optional field absent rather than `undefined`.
|
|
416
|
+
*/
|
|
417
|
+
export function buildActivationSpec(request, prompt, timeout, outputSchema = CONSOLIDATE_JSON_SCHEMA) {
|
|
418
|
+
const agentOptions = request.provider !== undefined && request.model !== undefined
|
|
419
|
+
? { provider: request.provider, model: request.model }
|
|
420
|
+
: undefined;
|
|
421
|
+
return {
|
|
422
|
+
provider: request.subagentProvider ?? 'spawn',
|
|
423
|
+
// Never optional, never derived: a missing label fails the kernel's
|
|
424
|
+
// descriptor validator BEFORE the child starts, and the symptom is a
|
|
425
|
+
// silently dead consolidation pass rather than a start error.
|
|
426
|
+
label: CONSOLIDATE_LABEL,
|
|
427
|
+
// Same class of mistake as the label, one field later: the kernel reads
|
|
428
|
+
// `spec.signal` and never `spec.request.signal`, so it has to be here too.
|
|
429
|
+
signal: timeout,
|
|
430
|
+
request: {
|
|
431
|
+
prompt,
|
|
432
|
+
parent: request.parent,
|
|
433
|
+
signal: timeout,
|
|
434
|
+
...agentOptions !== undefined ? { agentOptions } : {},
|
|
435
|
+
outputSchema,
|
|
436
|
+
// The child may not delegate further: it returns a plan, nothing else.
|
|
437
|
+
//
|
|
438
|
+
// `maxDepth` is the cap on the CHILD's depth, and DSH counts depth from
|
|
439
|
+
// 1 (a top-level agent is 0, its child is 1). So 1 admits this child and
|
|
440
|
+
// rejects any grandchild — 0 would reject the child itself, which is how
|
|
441
|
+
// this line was wrong the first time.
|
|
442
|
+
maxDepth: 1,
|
|
443
|
+
...request.agentPreset !== undefined ? { agentPreset: request.agentPreset } : {},
|
|
444
|
+
},
|
|
445
|
+
};
|
|
446
|
+
}
|
|
447
|
+
/**
|
|
448
|
+
* Ask the seam for one restricted child and return its answer as text.
|
|
449
|
+
*
|
|
450
|
+
* The 0.2.1-rc.2 seam is preferred, but only with a preset: a child that names
|
|
451
|
+
* no preset inherits the parent's composition, and the parent's tools are what
|
|
452
|
+
* this pass must withhold. The pre-0.2.1 seam is used when it is all there is.
|
|
453
|
+
*
|
|
454
|
+
* @param seam - the subagent service.
|
|
455
|
+
* @param prompt - the child's single user message.
|
|
456
|
+
* @param request - route, caps, and the preset name.
|
|
457
|
+
* @param timeout - the child's deadline.
|
|
458
|
+
* @returns the child's text, or `undefined` when the seam cannot run it.
|
|
459
|
+
*/
|
|
460
|
+
async function runChild(seam, prompt, request, timeout, outputSchema = CONSOLIDATE_JSON_SCHEMA) {
|
|
461
|
+
const agentOptions = request.provider !== undefined && request.model !== undefined
|
|
462
|
+
? { provider: request.provider, model: request.model }
|
|
463
|
+
: undefined;
|
|
464
|
+
if (typeof seam.startActivation === 'function' && request.agentPreset !== undefined) {
|
|
465
|
+
const run = await seam.startActivation(buildActivationSpec(request, prompt, timeout, outputSchema));
|
|
466
|
+
return textOf(await run.result);
|
|
467
|
+
}
|
|
468
|
+
if (typeof seam.start === 'function') {
|
|
469
|
+
const run = await seam.start('spawn', {
|
|
470
|
+
prompt,
|
|
471
|
+
parent: request.parent,
|
|
472
|
+
signal: timeout,
|
|
473
|
+
...agentOptions !== undefined ? { agentOptions } : {},
|
|
474
|
+
outputSchema,
|
|
475
|
+
maxDepth: 1,
|
|
476
|
+
// The child may not write anything and may not reach the network: its
|
|
477
|
+
// only output is the JSON plan it returns.
|
|
478
|
+
toolFilter: { deny: request.denyTools },
|
|
479
|
+
});
|
|
480
|
+
return textOf(await run.result);
|
|
481
|
+
}
|
|
482
|
+
return undefined;
|
|
483
|
+
}
|
|
484
|
+
/**
|
|
485
|
+
* Read one child's answer as text.
|
|
486
|
+
*
|
|
487
|
+
* A child that answered through the structured-output tool carries the plan in
|
|
488
|
+
* `structured`; a child that answered in prose carries it in the text blocks.
|
|
489
|
+
* @param result - the child's finished run.
|
|
490
|
+
* @returns the text the plan is parsed from.
|
|
491
|
+
*/
|
|
492
|
+
function textOf(result) {
|
|
493
|
+
if (typeof result.structured === 'object' && result.structured !== null)
|
|
494
|
+
return JSON.stringify(result.structured);
|
|
495
|
+
return result.output
|
|
496
|
+
.map((block) => (typeof block === 'object' && block !== null && 'text' in block && typeof block.text === 'string' ? block.text : ''))
|
|
497
|
+
.join('\n');
|
|
498
|
+
}
|
|
499
|
+
/**
|
|
500
|
+
* Run one consolidation without a subagent: a plain model call that owns no
|
|
501
|
+
* tools at all.
|
|
502
|
+
*
|
|
503
|
+
* This is the fallback for a deployment whose subagent seam cannot express a
|
|
504
|
+
* restricted child (no Agent Preset service, or a seam that predates the
|
|
505
|
+
* preset contract). It is not a weaker guarantee: the model is handed no tool
|
|
506
|
+
* list whatsoever, so it cannot write, shell out, or delegate — the same
|
|
507
|
+
* property the old deny list bought, reached by a different route.
|
|
508
|
+
*
|
|
509
|
+
* @param llm - the LLM runtime.
|
|
510
|
+
* @param request - entries, route, caps, and cancellation.
|
|
511
|
+
* @returns the validated plan, or `undefined` when the model produced none.
|
|
512
|
+
*/
|
|
513
|
+
export async function runConsolidationDirect(llm, request) {
|
|
514
|
+
if (request.entries.length === 0)
|
|
515
|
+
return undefined;
|
|
516
|
+
const route = request.route;
|
|
517
|
+
if (route === undefined)
|
|
518
|
+
return undefined;
|
|
519
|
+
const known = new Set(request.entries.map((entry) => entry.id));
|
|
520
|
+
const input = renderConsolidationInput(request.entries, request.projectLabel, request.persona);
|
|
521
|
+
const messages = [createUserMessage({
|
|
522
|
+
content: [{ type: 'text', text: input }],
|
|
523
|
+
source: { kind: MEMORY_SOURCE_KIND },
|
|
524
|
+
})];
|
|
525
|
+
const timeout = AbortSignal.any([request.signal, AbortSignal.timeout(request.timeoutMs)]);
|
|
526
|
+
const options = {
|
|
527
|
+
provider: route.provider,
|
|
528
|
+
model: route.model,
|
|
529
|
+
messages,
|
|
530
|
+
system: CONSOLIDATE_SYSTEM,
|
|
531
|
+
maxTokens: request.maxOutputTokens ?? DEFAULT_CONSOLIDATE_MAX_OUTPUT_TOKENS,
|
|
532
|
+
purpose: 'compaction',
|
|
533
|
+
sessionId: request.parent.session.id,
|
|
534
|
+
signal: timeout,
|
|
535
|
+
};
|
|
536
|
+
const assembler = new BlockAssembler();
|
|
537
|
+
for await (const chunk of llm.stream(options))
|
|
538
|
+
assembler.push(chunk);
|
|
539
|
+
const text = assembler.blocks()
|
|
540
|
+
.filter((block) => block.type === 'text')
|
|
541
|
+
.map((block) => block.text)
|
|
542
|
+
.join('\n');
|
|
543
|
+
if (text.trim().length === 0)
|
|
544
|
+
return undefined;
|
|
545
|
+
return parsePlan(text, known, request.maxUpserts);
|
|
546
|
+
}
|
|
547
|
+
/**
|
|
548
|
+
* Choose which memories one consolidation pass reviews.
|
|
549
|
+
*
|
|
550
|
+
* The pass used to receive the newest N entries, which meant an old memory was
|
|
551
|
+
* never looked at again: the first page never changed, so a stale fact deep in
|
|
552
|
+
* the store was unreachable by the only mechanism that could retire it.
|
|
553
|
+
* Selection prefers what was never reviewed, then what was reviewed longest
|
|
554
|
+
* ago, so every memory is eventually reached while new material — and material
|
|
555
|
+
* the model actually uses — still goes first.
|
|
556
|
+
*
|
|
557
|
+
* @param entries - every candidate entry.
|
|
558
|
+
* @param reviewedAt - `scope\u0000id` → last review time, or 0 when never.
|
|
559
|
+
* @param max - how many entries the pass may consider.
|
|
560
|
+
* @returns the selection to hand the sub-agent.
|
|
561
|
+
*/
|
|
562
|
+
export function selectForConsolidation(entries, reviewedAt, max) {
|
|
563
|
+
if (max <= 0)
|
|
564
|
+
return [];
|
|
565
|
+
const key = (entry) => `${entry.scope}\u0000${entry.id}`;
|
|
566
|
+
const selected = [];
|
|
567
|
+
const taken = new Set();
|
|
568
|
+
const fresh = entries.filter((entry) => (reviewedAt.get(key(entry)) ?? 0) === 0);
|
|
569
|
+
fresh.sort((left, right) => right.uses - left.uses || right.updatedAt - left.updatedAt || left.id.localeCompare(right.id));
|
|
570
|
+
for (const entry of fresh) {
|
|
571
|
+
if (selected.length >= max)
|
|
572
|
+
return selected;
|
|
573
|
+
selected.push(entry);
|
|
574
|
+
taken.add(key(entry));
|
|
575
|
+
}
|
|
576
|
+
const rest = entries.filter((entry) => !taken.has(key(entry)));
|
|
577
|
+
rest.sort((left, right) => (reviewedAt.get(key(left)) ?? 0) - (reviewedAt.get(key(right)) ?? 0)
|
|
578
|
+
|| right.updatedAt - left.updatedAt
|
|
579
|
+
|| left.id.localeCompare(right.id));
|
|
580
|
+
for (const entry of rest) {
|
|
581
|
+
if (selected.length >= max)
|
|
582
|
+
break;
|
|
583
|
+
selected.push(entry);
|
|
584
|
+
}
|
|
585
|
+
return selected;
|
|
586
|
+
}
|
|
587
|
+
/**
|
|
588
|
+
* Whether one dispute reason is a promise rather than a judgement.
|
|
589
|
+
*
|
|
590
|
+
* The reason strings are the plan's vocabulary, so this reads them the way the
|
|
591
|
+
* panel does. Kept next to {@link classifyPlan} so the two lists cannot drift.
|
|
592
|
+
*/
|
|
593
|
+
function isHardStopReason(reason) {
|
|
594
|
+
return reason.includes('人手写') || reason.includes('置顶') || reason.includes('永久保留');
|
|
595
|
+
}
|
|
596
|
+
/**
|
|
597
|
+
* Pin every existing memory to the scope it already lives in.
|
|
598
|
+
*
|
|
599
|
+
* A scope decides which sessions a memory is injected into, and a body that names
|
|
600
|
+
* a path, host or product says nothing about that: the developer's own machines,
|
|
601
|
+
* tools and cross-machine workflow are global even when they name a drive letter.
|
|
602
|
+
* Leaving the question to each pass produced two failure modes at once — a queue
|
|
603
|
+
* of "move this from global to project" decisions nobody wanted to answer, and a
|
|
604
|
+
* staged "move" whose acceptance wrote a second copy under the new scope (the
|
|
605
|
+
* original was never archived) and demoted its provenance to `auto`.
|
|
606
|
+
*
|
|
607
|
+
* So the rule is structural instead of conversational: the pass may place NEW
|
|
608
|
+
* memories anywhere, and every existing memory stays where it is. Callers that
|
|
609
|
+
* stage a disputed row must use the pinned plan too, or accepting that row would
|
|
610
|
+
* still write the proposed scope.
|
|
611
|
+
*
|
|
612
|
+
* @param plan - the plan the pass returned.
|
|
613
|
+
* @param entries - the entries as they were before the pass ran.
|
|
614
|
+
* @returns the plan with existing entries pinned, and each proposal that was overruled.
|
|
615
|
+
*/
|
|
616
|
+
export function pinExistingScopes(plan, entries) {
|
|
617
|
+
// Indexed by id to the list of copies: one id can exist in both scopes, and the
|
|
618
|
+
// copy the proposal names is the one to pin, exactly as `classifyPlan` reads it.
|
|
619
|
+
const byId = new Map();
|
|
620
|
+
for (const entry of entries) {
|
|
621
|
+
const list = byId.get(entry.id);
|
|
622
|
+
if (list === undefined)
|
|
623
|
+
byId.set(entry.id, [entry]);
|
|
624
|
+
else
|
|
625
|
+
list.push(entry);
|
|
626
|
+
}
|
|
627
|
+
const pinned = [];
|
|
628
|
+
const upserts = plan.upserts.map((item) => {
|
|
629
|
+
if (item.id === null)
|
|
630
|
+
return item;
|
|
631
|
+
const candidates = byId.get(item.id) ?? [];
|
|
632
|
+
const existing = candidates.find((entry) => entry.scope === item.scope) ?? candidates[0];
|
|
633
|
+
if (existing === undefined || existing.scope === item.scope)
|
|
634
|
+
return item;
|
|
635
|
+
pinned.push({ id: item.id, proposed: item.scope, kept: existing.scope });
|
|
636
|
+
return { ...item, scope: existing.scope };
|
|
637
|
+
});
|
|
638
|
+
return { plan: pinned.length === 0 ? plan : { ...plan, upserts }, pinned };
|
|
639
|
+
}
|
|
640
|
+
/** Paths a body cites, as anchors that must survive a rewrite. */
|
|
641
|
+
const CITATION = /\b[A-Za-z0-9_.-]+\/[A-Za-z0-9_./-]*\.[A-Za-z0-9]{1,6}\b/gu;
|
|
642
|
+
/** How many cited paths a body carries. */
|
|
643
|
+
function citationCount(body) {
|
|
644
|
+
return new Set([...body.matchAll(CITATION)].map((match) => match[0])).size;
|
|
645
|
+
}
|
|
646
|
+
/**
|
|
647
|
+
* Split a plan into what may be applied unattended and what should be asked about.
|
|
648
|
+
*
|
|
649
|
+
* The rules are deliberately about *loss*, not taste: the pass is allowed to
|
|
650
|
+
* sharpen wording, merge duplicates and retire memories nothing ever read. It is
|
|
651
|
+
* not allowed to quietly destroy a fact a session used, rewrite something a
|
|
652
|
+
* person wrote, or drop the concrete anchors (file paths) that made a body
|
|
653
|
+
* checkable. Scope is not a judgement at all: every existing entry is pinned to
|
|
654
|
+
* the scope it lives in (see {@link pinExistingScopes}), so a rewrite can never
|
|
655
|
+
* end up as a second copy in another scope.
|
|
656
|
+
*
|
|
657
|
+
* @param plan - the plan the pass returned.
|
|
658
|
+
* @param snapshot - the entries as they were before it ran.
|
|
659
|
+
* @returns the safe remainder and the decisions to ask about.
|
|
660
|
+
*/
|
|
661
|
+
export function classifyPlan(plan, snapshot) {
|
|
662
|
+
// Indexed by id alone: a pinned plan reuses the entry's own scope, but a caller
|
|
663
|
+
// that skipped the pin still names an existing id here, and an id-only lookup
|
|
664
|
+
// finds the entry it is describing instead of treating it as a new memory.
|
|
665
|
+
const byId = new Map();
|
|
666
|
+
for (const entry of snapshot.entries) {
|
|
667
|
+
const list = byId.get(entry.id);
|
|
668
|
+
if (list === undefined)
|
|
669
|
+
byId.set(entry.id, [entry]);
|
|
670
|
+
else
|
|
671
|
+
list.push(entry);
|
|
672
|
+
}
|
|
673
|
+
const previousOf = (id, scope) => {
|
|
674
|
+
const candidates = byId.get(id) ?? [];
|
|
675
|
+
return candidates.find((entry) => entry.scope === scope) ?? candidates[0];
|
|
676
|
+
};
|
|
677
|
+
const disputes = [];
|
|
678
|
+
const safeUpserts = [];
|
|
679
|
+
for (const raw of plan.upserts) {
|
|
680
|
+
const previous = raw.id === null ? undefined : previousOf(raw.id, raw.scope);
|
|
681
|
+
if (previous === undefined) {
|
|
682
|
+
// A brand-new memory destroys nothing: it can be un-written.
|
|
683
|
+
safeUpserts.push(raw);
|
|
684
|
+
continue;
|
|
685
|
+
}
|
|
686
|
+
// The structured form of the same rule: whatever the pass said about where an
|
|
687
|
+
// existing memory belongs, it stays where it lives.
|
|
688
|
+
const item = raw.scope === previous.scope ? raw : { ...raw, scope: previous.scope };
|
|
689
|
+
const reasons = [];
|
|
690
|
+
if (previous.source === 'user')
|
|
691
|
+
reasons.push('这条是人手写的');
|
|
692
|
+
if (previous.pinned === true)
|
|
693
|
+
reasons.push('这条是置顶的');
|
|
694
|
+
if (previous.permanent === true)
|
|
695
|
+
reasons.push('这条标记为永久保留');
|
|
696
|
+
const lostCitations = citationCount(previous.body) - citationCount(item.body);
|
|
697
|
+
if (lostCitations > 0)
|
|
698
|
+
reasons.push(`新版少了 ${lostCitations} 处文件路径引用`);
|
|
699
|
+
// A body that shrinks by half is not a rewrite, it is a summary — and what
|
|
700
|
+
// was dropped is exactly what the pass judged to be noise.
|
|
701
|
+
if (item.body.length * 2 < previous.body.length)
|
|
702
|
+
reasons.push('新版正文不到原来的一半');
|
|
703
|
+
if (reasons.length === 0) {
|
|
704
|
+
safeUpserts.push(item);
|
|
705
|
+
continue;
|
|
706
|
+
}
|
|
707
|
+
disputes.push({
|
|
708
|
+
id: previous.id,
|
|
709
|
+
scope: previous.scope,
|
|
710
|
+
action: 'rewrite',
|
|
711
|
+
title: previous.title,
|
|
712
|
+
reason: reasons.join(';'),
|
|
713
|
+
before: previous.body,
|
|
714
|
+
after: item.body,
|
|
715
|
+
// Reordering the promises: user/pinned/permanent are promises; a citation
|
|
716
|
+
// loss or a halved body is a judgement about information, which is exactly
|
|
717
|
+
// what an adjudicator can be trusted with.
|
|
718
|
+
...reasons.some(isHardStopReason) ? { hard: true } : {},
|
|
719
|
+
});
|
|
720
|
+
}
|
|
721
|
+
const safeRetire = [];
|
|
722
|
+
for (const id of plan.retire) {
|
|
723
|
+
const previous = snapshot.entries.find((entry) => entry.id === id);
|
|
724
|
+
if (previous === undefined)
|
|
725
|
+
continue;
|
|
726
|
+
const reasons = [];
|
|
727
|
+
if (previous.source === 'user')
|
|
728
|
+
reasons.push('这条是人手写的');
|
|
729
|
+
if (previous.pinned === true)
|
|
730
|
+
reasons.push('这条是置顶的');
|
|
731
|
+
if (previous.permanent === true)
|
|
732
|
+
reasons.push('这条标记为永久保留');
|
|
733
|
+
const hard = reasons.length > 0;
|
|
734
|
+
// Tier 1, deterministic and free: if the plan itself folds this entry into a
|
|
735
|
+
// successor that provably carries its material, the retirement destroys
|
|
736
|
+
// nothing and "it was read N times" stops being a reason to ask a person.
|
|
737
|
+
// Nobody loses the content, which was the only thing the question protected.
|
|
738
|
+
if (!hard) {
|
|
739
|
+
const heir = plan.upserts.find((item) => item.derivedFrom?.includes(id));
|
|
740
|
+
if (heir !== undefined && carriesForward(previous, heir)) {
|
|
741
|
+
safeRetire.push(id);
|
|
742
|
+
continue;
|
|
743
|
+
}
|
|
744
|
+
}
|
|
745
|
+
if (previous.uses > 0)
|
|
746
|
+
reasons.push(`它被读到过 ${previous.uses} 次`);
|
|
747
|
+
if (!hard && reasons.length === 0) {
|
|
748
|
+
safeRetire.push(id);
|
|
749
|
+
continue;
|
|
750
|
+
}
|
|
751
|
+
disputes.push({
|
|
752
|
+
id: previous.id,
|
|
753
|
+
scope: previous.scope,
|
|
754
|
+
action: 'retire',
|
|
755
|
+
title: previous.title,
|
|
756
|
+
reason: reasons.join(';'),
|
|
757
|
+
before: previous.body,
|
|
758
|
+
after: '',
|
|
759
|
+
...hard ? { hard: true } : {},
|
|
760
|
+
});
|
|
761
|
+
}
|
|
762
|
+
return {
|
|
763
|
+
safe: { upserts: safeUpserts, retire: safeRetire, skills: plan.skills, notes: plan.notes },
|
|
764
|
+
disputes,
|
|
765
|
+
};
|
|
766
|
+
}
|
|
767
|
+
/**
|
|
768
|
+
* Whether one waiting row still carries the plan fragment that applies it.
|
|
769
|
+
*
|
|
770
|
+
* The rows and the plan are stored side by side, so a row can outlive its
|
|
771
|
+
* fragment: a sync conflict used to stage `upserts: []` beside real questions,
|
|
772
|
+
* and applying that empty plan "succeeded" without writing anything, after
|
|
773
|
+
* which the row — the only visible trace — was dropped. A row that has no
|
|
774
|
+
* matching upsert (rewrite) or retire entry has nothing to apply, and saying so
|
|
775
|
+
* is the only honest answer.
|
|
776
|
+
*
|
|
777
|
+
* @param plan - the plan stored with the pending rows.
|
|
778
|
+
* @param row - the decision a person is answering.
|
|
779
|
+
* @returns true when applying this row is more than a no-op.
|
|
780
|
+
*/
|
|
781
|
+
export function hasApplicableFragment(plan, row) {
|
|
782
|
+
return row.action === 'retire'
|
|
783
|
+
? plan.retire.includes(row.id)
|
|
784
|
+
: plan.upserts.some((item) => item.id === row.id);
|
|
785
|
+
}
|
|
786
|
+
/** Where a pending proposal lives, one per store. */
|
|
787
|
+
export function pendingPlanPath(memoriesDir) {
|
|
788
|
+
return join(memoriesDir, 'pending', 'consolidation.json');
|
|
789
|
+
}
|
|
790
|
+
/**
|
|
791
|
+
* Stage a plan instead of applying it.
|
|
792
|
+
*
|
|
793
|
+
* A background pass rewrites memories with no model of what it is destroying: on
|
|
794
|
+
* a real store one such pass erased the trigger phrase from 32 memories, demoted
|
|
795
|
+
* 8 hand-written rules to "extracted guess", and turned Chinese titles back into
|
|
796
|
+
* English — all silently, and all found only in a later audit. A proposal has the
|
|
797
|
+
* same power and none of the risk: nothing changes until a person says so.
|
|
798
|
+
*
|
|
799
|
+
* @param memoriesDir - the store root.
|
|
800
|
+
* @param pending - the plan and where it came from.
|
|
801
|
+
*/
|
|
802
|
+
export async function writePendingPlan(memoriesDir, pending) {
|
|
803
|
+
const target = pendingPlanPath(memoriesDir);
|
|
804
|
+
await mkdir(dirname(target), { recursive: true });
|
|
805
|
+
await writeFile(target, `${JSON.stringify(pending, undefined, 2)}\n`, 'utf8');
|
|
806
|
+
}
|
|
807
|
+
/**
|
|
808
|
+
* Read the pending proposal, if any.
|
|
809
|
+
*
|
|
810
|
+
* @param memoriesDir - the store root.
|
|
811
|
+
* @returns the proposal, or `undefined` when there is none or it is unreadable.
|
|
812
|
+
*/
|
|
813
|
+
export async function readPendingPlan(memoriesDir) {
|
|
814
|
+
try {
|
|
815
|
+
const text = await readFile(pendingPlanPath(memoriesDir), 'utf8');
|
|
816
|
+
const parsed = JSON.parse(text);
|
|
817
|
+
if (typeof parsed !== 'object' || parsed === null || typeof parsed.plan !== 'object' || parsed.plan === null)
|
|
818
|
+
return undefined;
|
|
819
|
+
if (!Array.isArray(parsed.plan.upserts) || !Array.isArray(parsed.plan.retire))
|
|
820
|
+
return undefined;
|
|
821
|
+
// A file written before disputes existed carries no rows to show; it is
|
|
822
|
+
// treated as empty rather than as an unreadable file, so an upgrade cannot
|
|
823
|
+
// strand a question nobody can see.
|
|
824
|
+
return { ...parsed, disputes: Array.isArray(parsed.disputes) ? parsed.disputes : [] };
|
|
825
|
+
}
|
|
826
|
+
catch {
|
|
827
|
+
return undefined;
|
|
828
|
+
}
|
|
829
|
+
}
|
|
830
|
+
/**
|
|
831
|
+
* Merge newly disputed decisions into the ones already waiting.
|
|
832
|
+
*
|
|
833
|
+
* A later pass must not silently replace a question: the reader may be part-way
|
|
834
|
+
* through deciding, and the same id can legitimately be disputed twice (the pass
|
|
835
|
+
* proposes something else about it). Newest wins for an id, older rows stay.
|
|
836
|
+
*
|
|
837
|
+
* @param memoriesDir - the store root.
|
|
838
|
+
* @param pending - the rows and the plan fragment that would apply them.
|
|
839
|
+
* @returns how many rows are waiting after the merge.
|
|
840
|
+
*/
|
|
841
|
+
export async function mergePendingPlan(memoriesDir, pending) {
|
|
842
|
+
const existing = await readPendingPlan(memoriesDir);
|
|
843
|
+
if (existing === undefined) {
|
|
844
|
+
await writePendingPlan(memoriesDir, pending);
|
|
845
|
+
return pending.disputes.length;
|
|
846
|
+
}
|
|
847
|
+
const byId = new Map(existing.disputes.map((row) => [`${row.action}\u0000${row.id}`, row]));
|
|
848
|
+
for (const row of pending.disputes)
|
|
849
|
+
byId.set(`${row.action}\u0000${row.id}`, row);
|
|
850
|
+
const disputes = [...byId.values()];
|
|
851
|
+
// The plan fragment follows the rows: keep the upsert/retire for every id that
|
|
852
|
+
// is still waiting, so applying a row later needs no second model call.
|
|
853
|
+
const ids = new Set(disputes.map((row) => row.id));
|
|
854
|
+
const plan = {
|
|
855
|
+
upserts: [...existing.plan.upserts, ...pending.plan.upserts].filter((item) => item.id !== null && ids.has(item.id)),
|
|
856
|
+
retire: [...new Set([...existing.plan.retire, ...pending.plan.retire])].filter((id) => ids.has(id)),
|
|
857
|
+
skills: [],
|
|
858
|
+
notes: pending.plan.notes,
|
|
859
|
+
};
|
|
860
|
+
await writePendingPlan(memoriesDir, { plan, disputes, projectRoot: pending.projectRoot, at: pending.at, label: pending.label });
|
|
861
|
+
return disputes.length;
|
|
862
|
+
}
|
|
863
|
+
/**
|
|
864
|
+
* Whether a staged proposal is still worth leaving alone.
|
|
865
|
+
*
|
|
866
|
+
* A proposal is a question, and questions go stale: entries keep arriving while
|
|
867
|
+
* it waits, so an old proposal describes a store that no longer exists. Inside
|
|
868
|
+
* the window a background pass does not spend a model call to overwrite a
|
|
869
|
+
* question nobody has answered; past it, the fresh proposal wins.
|
|
870
|
+
*
|
|
871
|
+
* @param pending - the staged proposal.
|
|
872
|
+
* @param maxAgeHours - the window; `0` means "wait for an answer".
|
|
873
|
+
* @param now - clock.
|
|
874
|
+
* @returns true when a running pass should leave it in place.
|
|
875
|
+
*/
|
|
876
|
+
export function proposalIsFresh(pending, maxAgeHours, now) {
|
|
877
|
+
if (maxAgeHours <= 0)
|
|
878
|
+
return true;
|
|
879
|
+
return now - pending.at < maxAgeHours * 3_600_000;
|
|
880
|
+
}
|
|
881
|
+
/**
|
|
882
|
+
* Drop the pending proposal.
|
|
883
|
+
*
|
|
884
|
+
* @param memoriesDir - the store root.
|
|
885
|
+
* @returns whether one was there.
|
|
886
|
+
*/
|
|
887
|
+
export async function clearPendingPlan(memoriesDir) {
|
|
888
|
+
try {
|
|
889
|
+
await rm(pendingPlanPath(memoriesDir), { force: true });
|
|
890
|
+
return true;
|
|
891
|
+
}
|
|
892
|
+
catch {
|
|
893
|
+
return false;
|
|
894
|
+
}
|
|
895
|
+
}
|
|
896
|
+
/**
|
|
897
|
+
* Apply a plan, restoring the snapshot when a write fails.
|
|
898
|
+
*
|
|
899
|
+
* The child proposes; this function is the only writer. Applying is all-or-
|
|
900
|
+
* nothing: a failure mid-plan puts the entries it already touched back the way
|
|
901
|
+
* they were, so a half-consolidated store is never left behind.
|
|
902
|
+
*
|
|
903
|
+
* @param plan - the validated plan.
|
|
904
|
+
* @param target - the store to write to.
|
|
905
|
+
* @param projectRoot - workspace root for project entries.
|
|
906
|
+
* @param snapshot - entries as they were before the plan.
|
|
907
|
+
* @returns how many entries were written and retired.
|
|
908
|
+
*/
|
|
909
|
+
export async function applyPlan(plan, target, projectRoot, snapshot) {
|
|
910
|
+
const before = new Map(snapshot.entries.map((entry) => [`${entry.scope}\u0000${entry.id}`, entry]));
|
|
911
|
+
const touched = [];
|
|
912
|
+
/** Retirements already archived, so a failed plan can put them back. */
|
|
913
|
+
const archived = [];
|
|
914
|
+
try {
|
|
915
|
+
for (const item of plan.upserts) {
|
|
916
|
+
// A rewrite keeps the provenance of what it rewrites. Stamping every
|
|
917
|
+
// consolidation result `auto` demotes memories a person wrote: `auto` is
|
|
918
|
+
// the extractor's guess, `tool`/`user` is somebody's statement, and the
|
|
919
|
+
// distinction carries a ranking bonus and an exemption from retention.
|
|
920
|
+
// Measured on a real store, one consolidation run demoted the user's own
|
|
921
|
+
// "never break the prompt cache" rule to `auto`, which is what a guess is.
|
|
922
|
+
const previous = item.id === null ? undefined : before.get(`${item.scope}\u0000${item.id}`);
|
|
923
|
+
const draft = {
|
|
924
|
+
scope: item.scope,
|
|
925
|
+
title: item.title,
|
|
926
|
+
body: item.body,
|
|
927
|
+
tags: item.tags,
|
|
928
|
+
keys: item.keys ?? [],
|
|
929
|
+
...item.appliesTo === undefined ? {} : { appliesTo: item.appliesTo },
|
|
930
|
+
...item.derivedFrom === undefined ? {} : { derivedFrom: item.derivedFrom },
|
|
931
|
+
};
|
|
932
|
+
const result = await target.upsert(draft, item.scope === 'project' ? projectRoot : undefined, previous?.source ?? 'auto', item.id ?? undefined);
|
|
933
|
+
touched.push({ scope: result.entry.scope, id: result.entry.id });
|
|
934
|
+
}
|
|
935
|
+
for (const id of plan.retire) {
|
|
936
|
+
if (await target.archive('global', projectRoot, id))
|
|
937
|
+
archived.push({ scope: 'global', id });
|
|
938
|
+
if (await target.archive('project', projectRoot, id))
|
|
939
|
+
archived.push({ scope: 'project', id });
|
|
940
|
+
}
|
|
941
|
+
return { written: plan.upserts.length, retired: plan.retire.length, notes: plan.notes };
|
|
942
|
+
}
|
|
943
|
+
catch (error) {
|
|
944
|
+
// Restore every entry the plan may have changed, then rethrow so the caller
|
|
945
|
+
// can log it and retry with backoff.
|
|
946
|
+
for (const item of touched) {
|
|
947
|
+
const original = before.get(`${item.scope}\u0000${item.id}`);
|
|
948
|
+
if (original === undefined)
|
|
949
|
+
continue;
|
|
950
|
+
await target.upsert({ scope: original.scope, title: original.title, body: original.body, tags: original.tags, keys: [...original.keys] }, original.scope === 'project' ? projectRoot : undefined, original.source, original.id);
|
|
951
|
+
}
|
|
952
|
+
// A retirement is an archival, not a deletion, so it can be put back
|
|
953
|
+
// exactly; without this the store would lose entries to a plan that failed
|
|
954
|
+
// for an unrelated reason later in the same run.
|
|
955
|
+
for (const item of archived) {
|
|
956
|
+
await target.restore(item.scope, projectRoot, item.id).catch(() => undefined);
|
|
957
|
+
}
|
|
958
|
+
throw error;
|
|
959
|
+
}
|
|
960
|
+
}
|
|
961
|
+
// ── 裁决层(AI 只回答「这次变更有没有丢信息」)──────────────────────────────
|
|
962
|
+
/**
|
|
963
|
+
* The adjudicator's answer shape.
|
|
964
|
+
*
|
|
965
|
+
* One decision per dispute, keyed by id, plus a confidence the caller thresholds
|
|
966
|
+
* on. Deliberately no free-form field: an adjudicator that can explain itself in
|
|
967
|
+
* prose can also argue itself into a retire, and the only thing this layer is
|
|
968
|
+
* allowed to judge is whether information survives.
|
|
969
|
+
*/
|
|
970
|
+
export const ADJUDICATE_JSON_SCHEMA = {
|
|
971
|
+
type: 'object',
|
|
972
|
+
additionalProperties: false,
|
|
973
|
+
required: ['decisions'],
|
|
974
|
+
properties: {
|
|
975
|
+
decisions: {
|
|
976
|
+
type: 'array',
|
|
977
|
+
items: {
|
|
978
|
+
type: 'object',
|
|
979
|
+
additionalProperties: false,
|
|
980
|
+
required: ['id', 'accept', 'confidence', 'reason'],
|
|
981
|
+
properties: {
|
|
982
|
+
id: { type: 'string' },
|
|
983
|
+
accept: { type: 'boolean' },
|
|
984
|
+
confidence: { type: 'number' },
|
|
985
|
+
reason: { type: 'string' },
|
|
986
|
+
},
|
|
987
|
+
},
|
|
988
|
+
},
|
|
989
|
+
},
|
|
990
|
+
};
|
|
991
|
+
/** What the adjudicator is asked to judge. */
|
|
992
|
+
export const ADJUDICATE_SYSTEM = [
|
|
993
|
+
'You are the reviewer of a memory store. A merge pass proposed the changes below, and the plugin would not apply them without a second opinion.',
|
|
994
|
+
'Your only question for each item: does the proposed change keep everything a future reader needs? Facts, paths, numbers, commands, qualifiers, and the reason a rule exists must survive an ACCEPT. Anything dropped is gone — the old copy is archived, not read on demand.',
|
|
995
|
+
'',
|
|
996
|
+
'Rules:',
|
|
997
|
+
'- ACCEPT a rewrite only when the new body keeps every substantive fact of the old one, and the new body is not a vaguer restatement.',
|
|
998
|
+
'- ACCEPT a retirement only when the note says another memory now carries this content, and that is true of the text you were given.',
|
|
999
|
+
'- REJECT when you cannot see the replacement, or when the change narrows a rule (drops a condition, a scope, or a caveat).',
|
|
1000
|
+
'- When unsure, REJECT with a low confidence. Nothing is lost by keeping both copies.',
|
|
1001
|
+
'- Never accept a change because the entry was rarely read. Read counts are not evidence of value.',
|
|
1002
|
+
'',
|
|
1003
|
+
'Reply with JSON only: {"decisions":[{"id":string,"accept":boolean,"confidence":number,"reason":string}]}',
|
|
1004
|
+
'confidence is 0..1. reason is one short sentence.',
|
|
1005
|
+
].join('\n');
|
|
1006
|
+
/**
|
|
1007
|
+
* Render the disputes for the adjudicator.
|
|
1008
|
+
* @param disputes - items the classifier would not apply on its own.
|
|
1009
|
+
* @returns the document handed to the child.
|
|
1010
|
+
*/
|
|
1011
|
+
export function renderAdjudicationInput(disputes) {
|
|
1012
|
+
const blocks = disputes.map((dispute) => [
|
|
1013
|
+
`### ${dispute.id} (${dispute.action})`,
|
|
1014
|
+
`title: ${dispute.title}`,
|
|
1015
|
+
`flagged because: ${dispute.reason}`,
|
|
1016
|
+
'BEFORE:',
|
|
1017
|
+
dispute.before,
|
|
1018
|
+
dispute.action === 'rewrite' ? 'AFTER:' : 'AFTER: (retired; no replacement text given here)',
|
|
1019
|
+
dispute.action === 'rewrite' ? dispute.after : '',
|
|
1020
|
+
].join('\n'));
|
|
1021
|
+
return blocks.join('\n\n');
|
|
1022
|
+
}
|
|
1023
|
+
/**
|
|
1024
|
+
* Ask a restricted child to adjudicate the disputes a person used to answer.
|
|
1025
|
+
*
|
|
1026
|
+
* Same seam, same preset and same fence as the consolidation pass itself, so the
|
|
1027
|
+
* child still has no tools: it reads the two bodies and answers. Anything the
|
|
1028
|
+
* child does not return, returns twice, or returns unparseably is treated as
|
|
1029
|
+
* "no verdict" and stays with the human — this layer can only ever ADD an answer,
|
|
1030
|
+
* never suppress a question.
|
|
1031
|
+
*
|
|
1032
|
+
* @param seam - the `ctx.subagents` service.
|
|
1033
|
+
* @param request - route, preset, caps and the parent agent.
|
|
1034
|
+
* @param disputes - items to adjudicate; hard stops must already be filtered out.
|
|
1035
|
+
* @returns one verdict per answered id, possibly empty.
|
|
1036
|
+
*/
|
|
1037
|
+
export async function adjudicateDisputes(seam, request, disputes) {
|
|
1038
|
+
if (disputes.length === 0)
|
|
1039
|
+
return [];
|
|
1040
|
+
const timeout = AbortSignal.any([request.signal, AbortSignal.timeout(request.timeoutMs)]);
|
|
1041
|
+
const prompt = [{ type: 'text', text: `${ADJUDICATE_SYSTEM}\n\n---\n\n${renderAdjudicationInput(disputes)}` }];
|
|
1042
|
+
const reply = await runChild(seam, prompt, request, timeout, ADJUDICATE_JSON_SCHEMA);
|
|
1043
|
+
if (reply === undefined)
|
|
1044
|
+
return [];
|
|
1045
|
+
const trimmed = reply.trim().replace(/^```(?:json)?\s*/iu, '').replace(/```$/u, '').trim();
|
|
1046
|
+
const start = trimmed.indexOf('{');
|
|
1047
|
+
const end = trimmed.lastIndexOf('}');
|
|
1048
|
+
if (start < 0 || end <= start)
|
|
1049
|
+
return [];
|
|
1050
|
+
let parsed;
|
|
1051
|
+
try {
|
|
1052
|
+
parsed = JSON.parse(trimmed.slice(start, end + 1));
|
|
1053
|
+
}
|
|
1054
|
+
catch {
|
|
1055
|
+
return [];
|
|
1056
|
+
}
|
|
1057
|
+
if (typeof parsed !== 'object' || parsed === null)
|
|
1058
|
+
return [];
|
|
1059
|
+
const record0 = parsed;
|
|
1060
|
+
const rows = Array.isArray(record0['decisions']) ? record0['decisions'] : [];
|
|
1061
|
+
const known = new Set(disputes.map((dispute) => dispute.id));
|
|
1062
|
+
const verdicts = [];
|
|
1063
|
+
const seen = new Set();
|
|
1064
|
+
for (const row of rows) {
|
|
1065
|
+
if (typeof row !== 'object' || row === null)
|
|
1066
|
+
continue;
|
|
1067
|
+
const record = row;
|
|
1068
|
+
const id = typeof record['id'] === 'string' ? record['id'] : undefined;
|
|
1069
|
+
if (id === undefined || !known.has(id) || seen.has(id))
|
|
1070
|
+
continue;
|
|
1071
|
+
const accept = record['accept'] === true;
|
|
1072
|
+
const raw = typeof record['confidence'] === 'number' && Number.isFinite(record['confidence']) ? record['confidence'] : 0;
|
|
1073
|
+
seen.add(id);
|
|
1074
|
+
verdicts.push({
|
|
1075
|
+
id,
|
|
1076
|
+
accept,
|
|
1077
|
+
confidence: Math.max(0, Math.min(1, raw)),
|
|
1078
|
+
reason: typeof record['reason'] === 'string' ? record['reason'].slice(0, 200) : '',
|
|
1079
|
+
});
|
|
1080
|
+
}
|
|
1081
|
+
return verdicts;
|
|
1082
|
+
}
|
|
1083
|
+
/**
|
|
1084
|
+
* Fold adjudicator verdicts into the plan the caller is about to apply.
|
|
1085
|
+
*
|
|
1086
|
+
* Rejected items and items under the confidence floor are NOT left pending: a
|
|
1087
|
+
* rejection is an answer ("do nothing"), and re-asking it every six hours would
|
|
1088
|
+
* turn a decision into a queue. Only unanswered items stay with the human.
|
|
1089
|
+
*
|
|
1090
|
+
* @param safe - the plan the classifier already cleared; mutated in place.
|
|
1091
|
+
* @param plan - the pass's full plan, for the upsert bodies a rewrite needs.
|
|
1092
|
+
* @param disputes - items that were sent to the adjudicator.
|
|
1093
|
+
* @param verdicts - what came back.
|
|
1094
|
+
* @param minConfidence - floor below which a verdict is treated as no answer.
|
|
1095
|
+
* @returns the disputes that still need a person.
|
|
1096
|
+
*/
|
|
1097
|
+
export function applyVerdicts(safe, plan, disputes, verdicts, minConfidence) {
|
|
1098
|
+
const byId = new Map(verdicts.map((verdict) => [verdict.id, verdict]));
|
|
1099
|
+
const answered = new Set();
|
|
1100
|
+
for (const dispute of disputes) {
|
|
1101
|
+
const verdict = byId.get(dispute.id);
|
|
1102
|
+
if (verdict === undefined || verdict.confidence < minConfidence)
|
|
1103
|
+
continue;
|
|
1104
|
+
answered.add(dispute.id);
|
|
1105
|
+
if (!verdict.accept)
|
|
1106
|
+
continue;
|
|
1107
|
+
if (dispute.action === 'retire') {
|
|
1108
|
+
if (!safe.retire.includes(dispute.id))
|
|
1109
|
+
safe.retire.push(dispute.id);
|
|
1110
|
+
continue;
|
|
1111
|
+
}
|
|
1112
|
+
const item = plan.upserts.find((candidate) => candidate.id === dispute.id && candidate.scope === dispute.scope);
|
|
1113
|
+
if (item === undefined)
|
|
1114
|
+
continue;
|
|
1115
|
+
if (!safe.upserts.includes(item))
|
|
1116
|
+
safe.upserts.push(item);
|
|
1117
|
+
}
|
|
1118
|
+
return disputes.filter((dispute) => !answered.has(dispute.id));
|
|
1119
|
+
}
|