@oyasmi/pipiclaw 0.9.1-beta.2 → 0.9.2-beta.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/dist/agent/channel-runner.d.ts +9 -1
- package/dist/agent/channel-runner.js +51 -18
- package/dist/agent/command-extension.js +24 -27
- package/dist/agent/commands.d.ts +51 -7
- package/dist/agent/commands.js +199 -59
- package/dist/agent/effect-ledger.js +9 -2
- package/dist/agent/job-manager.d.ts +4 -0
- package/dist/agent/job-manager.js +17 -2
- package/dist/agent/prompt/manifest.d.ts +1 -1
- package/dist/agent/prompt/manifest.js +6 -7
- package/dist/agent/prompt/sections.js +9 -5
- package/dist/agent/reply-limits.d.ts +16 -0
- package/dist/agent/reply-limits.js +17 -0
- package/dist/agent/session-events.d.ts +2 -0
- package/dist/agent/session-events.js +29 -14
- package/dist/agent/status-render.js +12 -12
- package/dist/agent/turn-recovery.js +2 -2
- package/dist/agent/type-guards.js +5 -1
- package/dist/agent/workspace-resources.d.ts +2 -2
- package/dist/agent/workspace-resources.js +41 -3
- package/dist/executor.d.ts +28 -0
- package/dist/executor.js +120 -18
- package/dist/file-store.d.ts +96 -0
- package/dist/file-store.js +189 -0
- package/dist/main.js +3 -4
- package/dist/memory/commands.js +79 -38
- package/dist/memory/consolidation.d.ts +5 -1
- package/dist/memory/consolidation.js +35 -38
- package/dist/memory/extraction.d.ts +8 -1
- package/dist/memory/extraction.js +47 -4
- package/dist/memory/files.d.ts +0 -1
- package/dist/memory/files.js +31 -12
- package/dist/memory/lifecycle.js +9 -2
- package/dist/memory/maintenance-jobs.js +16 -38
- package/dist/memory/maintenance-state.js +2 -1
- package/dist/memory/metadata.d.ts +3 -0
- package/dist/memory/metadata.js +7 -0
- package/dist/memory/recall.d.ts +19 -0
- package/dist/memory/recall.js +116 -24
- package/dist/memory/review-log.d.ts +0 -2
- package/dist/memory/review-log.js +0 -0
- package/dist/memory/session-corpus.js +5 -0
- package/dist/memory/session-search.js +15 -22
- package/dist/memory/sidecar-worker.js +4 -0
- package/dist/memory/source-window.d.ts +0 -1
- package/dist/memory/source-window.js +0 -5
- package/dist/memory/transcript.d.ts +10 -0
- package/dist/memory/transcript.js +39 -0
- package/dist/playbooks/agent-delegation.md +34 -25
- package/dist/playbooks/background-jobs.md +8 -16
- package/dist/playbooks/catalog.d.ts +1 -1
- package/dist/playbooks/catalog.js +1 -1
- package/dist/playbooks/event-scheduling.md +15 -15
- package/dist/playbooks/memory-and-learning.md +30 -23
- package/dist/playbooks/outbound-media.md +15 -8
- package/dist/playbooks/runtime-orientation.md +40 -37
- package/dist/playbooks/task-driving.md +36 -38
- package/dist/playbooks/task-planning.md +21 -21
- package/dist/runtime/app-home.d.ts +6 -0
- package/dist/runtime/app-home.js +16 -7
- package/dist/runtime/bootstrap.js +54 -13
- package/dist/runtime/channel-context.d.ts +2 -1
- package/dist/runtime/delivery.js +3 -3
- package/dist/runtime/dingtalk.d.ts +9 -1
- package/dist/runtime/dingtalk.js +30 -15
- package/dist/runtime/durable-dispatch.d.ts +26 -1
- package/dist/runtime/durable-dispatch.js +51 -5
- package/dist/runtime/event-commands.d.ts +15 -0
- package/dist/runtime/event-commands.js +55 -56
- package/dist/runtime/events.d.ts +4 -2
- package/dist/runtime/events.js +15 -20
- package/dist/runtime/project-commands.d.ts +16 -0
- package/dist/runtime/project-commands.js +13 -17
- package/dist/runtime/subagent-commands.d.ts +20 -0
- package/dist/runtime/subagent-commands.js +61 -58
- package/dist/runtime/task-commands.d.ts +37 -0
- package/dist/runtime/task-commands.js +108 -66
- package/dist/runtime/task-driver.js +2 -2
- package/dist/security/block-message.d.ts +11 -0
- package/dist/security/block-message.js +12 -0
- package/dist/security/path-guard-check.d.ts +13 -0
- package/dist/security/path-guard-check.js +39 -0
- package/dist/security/path-guard.js +61 -12
- package/dist/security/types.d.ts +9 -0
- package/dist/settings.js +3 -2
- package/dist/shared/atomic-file.d.ts +17 -1
- package/dist/shared/atomic-file.js +50 -3
- package/dist/shared/duration.d.ts +2 -0
- package/dist/shared/duration.js +7 -0
- package/dist/shared/safe-id.d.ts +19 -0
- package/dist/shared/safe-id.js +24 -0
- package/dist/shared/text-utils.d.ts +1 -1
- package/dist/shared/text-utils.js +3 -8
- package/dist/shared/type-guards.d.ts +2 -0
- package/dist/shared/type-guards.js +4 -0
- package/dist/subagents/discovery.d.ts +51 -19
- package/dist/subagents/discovery.js +93 -98
- package/dist/subagents/external/claude-code.js +40 -2
- package/dist/subagents/external/harness.d.ts +1 -1
- package/dist/subagents/external/run.js +61 -8
- package/dist/subagents/format.d.ts +3 -2
- package/dist/subagents/format.js +3 -7
- package/dist/subagents/runs.d.ts +1 -1
- package/dist/subagents/runs.js +10 -9
- package/dist/subagents/tool.d.ts +31 -18
- package/dist/subagents/tool.js +592 -562
- package/dist/subagents/workspace-lease.js +1 -1
- package/dist/tasks/control.js +7 -9
- package/dist/tasks/ledger.d.ts +2 -2
- package/dist/tasks/ledger.js +3 -7
- package/dist/tasks/transitions.d.ts +5 -1
- package/dist/tasks/transitions.js +2 -2
- package/dist/tasks/verification.d.ts +7 -5
- package/dist/tools/bash.d.ts +1 -2
- package/dist/tools/bash.js +99 -76
- package/dist/tools/config.d.ts +6 -1
- package/dist/tools/config.js +9 -0
- package/dist/tools/edit.d.ts +2 -3
- package/dist/tools/edit.js +276 -75
- package/dist/tools/event-manage.d.ts +13 -7
- package/dist/tools/event-manage.js +52 -14
- package/dist/tools/glob-match.d.ts +11 -0
- package/dist/tools/glob-match.js +75 -0
- package/dist/tools/glob.d.ts +15 -0
- package/dist/tools/glob.js +113 -0
- package/dist/tools/grep.d.ts +0 -1
- package/dist/tools/grep.js +60 -44
- package/dist/tools/ignore-dirs.d.ts +6 -0
- package/dist/tools/ignore-dirs.js +15 -0
- package/dist/tools/index.d.ts +3 -0
- package/dist/tools/index.js +54 -40
- package/dist/tools/job.d.ts +0 -1
- package/dist/tools/job.js +3 -9
- package/dist/tools/line-index.d.ts +16 -0
- package/dist/tools/line-index.js +76 -0
- package/dist/tools/memory-manage.d.ts +21 -8
- package/dist/tools/memory-manage.js +114 -103
- package/dist/tools/presentation.d.ts +2 -0
- package/dist/tools/presentation.js +109 -0
- package/dist/tools/read.d.ts +2 -2
- package/dist/tools/read.js +100 -120
- package/dist/tools/registry.d.ts +4 -1
- package/dist/tools/registry.js +89 -22
- package/dist/tools/send-media.d.ts +6 -6
- package/dist/tools/send-media.js +21 -43
- package/dist/tools/session-search.d.ts +0 -1
- package/dist/tools/session-search.js +0 -1
- package/dist/tools/skill-security.d.ts +0 -2
- package/dist/tools/skill-security.js +1 -25
- package/dist/tools/skill.d.ts +31 -0
- package/dist/tools/skill.js +153 -0
- package/dist/tools/subagent-manage.d.ts +6 -5
- package/dist/tools/subagent-manage.js +47 -47
- package/dist/tools/task-manage/create.d.ts +2 -2
- package/dist/tools/task-manage/create.js +1 -3
- package/dist/tools/task-manage/lifecycle.d.ts +9 -6
- package/dist/tools/task-manage/lifecycle.js +49 -56
- package/dist/tools/task-manage/schema.d.ts +27 -15
- package/dist/tools/task-manage/schema.js +58 -74
- package/dist/tools/task-manage/shared.d.ts +11 -6
- package/dist/tools/task-manage/shared.js +30 -21
- package/dist/tools/task-manage/types.d.ts +14 -15
- package/dist/tools/task-manage/verification.d.ts +4 -4
- package/dist/tools/task-manage/verification.js +6 -8
- package/dist/tools/task-manage.d.ts +8 -11
- package/dist/tools/task-manage.js +63 -50
- package/dist/tools/tool-details.d.ts +17 -1
- package/dist/tools/tool-details.js +24 -0
- package/dist/tools/truncate.d.ts +8 -0
- package/dist/tools/truncate.js +8 -0
- package/dist/tools/web-fetch.d.ts +0 -1
- package/dist/tools/web-fetch.js +9 -2
- package/dist/tools/web-search.d.ts +0 -1
- package/dist/tools/web-search.js +0 -1
- package/dist/tools/write-content.d.ts +3 -3
- package/dist/tools/write-content.js +12 -41
- package/dist/tools/write.d.ts +2 -3
- package/dist/tools/write.js +3 -4
- package/dist/tui/app.js +1 -1
- package/dist/tui/commands.d.ts +1 -1
- package/dist/tui/commands.js +1 -1
- package/dist/tui/turn-controller.d.ts +1 -1
- package/dist/tui/turn-controller.js +14 -4
- package/dist/usage/ledger.js +7 -4
- package/dist/usage/render.js +10 -8
- package/examples/sub-agents/README.md +2 -0
- package/package.json +3 -2
- package/dist/tools/skill-manage.d.ts +0 -41
- package/dist/tools/skill-manage.js +0 -231
|
@@ -3,8 +3,10 @@ import { parseJsonObject } from "../shared/llm-json.js";
|
|
|
3
3
|
import { clipText } from "../shared/text-utils.js";
|
|
4
4
|
import { isRecord } from "../shared/type-guards.js";
|
|
5
5
|
import { parseChannelMemoryEntries, readChannelHistory, readChannelMemory, readChannelSession, } from "./files.js";
|
|
6
|
+
import { readMemoryMetadata } from "./metadata.js";
|
|
6
7
|
import { probationDeadline } from "./probation.js";
|
|
7
8
|
import { MEMORY_INPUT_SAFETY_RULES } from "./prompt-safety.js";
|
|
9
|
+
import { tokenizeRecallText } from "./recall.js";
|
|
8
10
|
import { runRetriedSidecarTask } from "./sidecar-worker.js";
|
|
9
11
|
import { sanitizeMessagesForMemory } from "./transcript.js";
|
|
10
12
|
/**
|
|
@@ -140,6 +142,7 @@ export function toMemoryOp(candidate, provenance, tier) {
|
|
|
140
142
|
const metadata = {
|
|
141
143
|
kind: candidate.kind,
|
|
142
144
|
sourceType: "agent",
|
|
145
|
+
necessity: candidate.necessity,
|
|
143
146
|
sourceCorrelationId: provenance.correlationId,
|
|
144
147
|
probationUntil: tier === "probationary" ? probationDeadline() : null,
|
|
145
148
|
};
|
|
@@ -159,14 +162,54 @@ export function toMemoryOp(candidate, provenance, tier) {
|
|
|
159
162
|
metadata,
|
|
160
163
|
};
|
|
161
164
|
}
|
|
162
|
-
/**
|
|
163
|
-
|
|
165
|
+
/**
|
|
166
|
+
* Above this many entries, a full-corpus render stops being useful: MEMORY_ENTRIES clips at 8000
|
|
167
|
+
* chars anyway, so the model never sees enough of the tail to consider superseding it. Past the
|
|
168
|
+
* threshold, render only the entries most lexically similar to this window's transcript, plus
|
|
169
|
+
* every user-saved entry regardless of similarity (a user's explicit fact must always be a
|
|
170
|
+
* candidate for supersede, never silently excluded by relevance ranking).
|
|
171
|
+
*/
|
|
172
|
+
const MEMORY_ENTRIES_SIMILARITY_THRESHOLD = 40;
|
|
173
|
+
const MEMORY_ENTRIES_SIMILARITY_TOP_N = 20;
|
|
174
|
+
/**
|
|
175
|
+
* Entries rendered as `id — content` so supersede/invalidate can reference real ids.
|
|
176
|
+
*
|
|
177
|
+
* A lightweight local token-overlap score, not the full recall pipeline — extraction only has a
|
|
178
|
+
* `channelDir`, and reusing `recallRelevantMemory` here would mean threading `workspaceDir`
|
|
179
|
+
* through every consolidation call site just to rank entries already loaded in memory.
|
|
180
|
+
*/
|
|
181
|
+
async function renderSimilarMemoryEntriesForPrompt(channelDir, rawMemory, transcript) {
|
|
164
182
|
const entries = parseChannelMemoryEntries(rawMemory);
|
|
165
183
|
if (entries.length === 0) {
|
|
166
184
|
return "";
|
|
167
185
|
}
|
|
168
|
-
|
|
186
|
+
if (entries.length <= MEMORY_ENTRIES_SIMILARITY_THRESHOLD) {
|
|
187
|
+
return entries.map((entry) => `${entry.id} — ${entry.content}`).join("\n");
|
|
188
|
+
}
|
|
189
|
+
const transcriptTokens = new Set(tokenizeRecallText(transcript));
|
|
190
|
+
const scored = entries
|
|
191
|
+
.map((entry) => {
|
|
192
|
+
const entryTokens = tokenizeRecallText(entry.content);
|
|
193
|
+
const overlap = entryTokens.filter((token) => transcriptTokens.has(token)).length;
|
|
194
|
+
return { entry, overlap };
|
|
195
|
+
})
|
|
196
|
+
.sort((a, b) => b.overlap - a.overlap);
|
|
197
|
+
const metadata = await readMemoryMetadata(channelDir);
|
|
198
|
+
const mustKeepIds = new Set(entries.filter((entry) => metadata.entries[entry.id]?.sourceType === "user").map((entry) => entry.id));
|
|
199
|
+
const selectedIds = new Set(scored.slice(0, MEMORY_ENTRIES_SIMILARITY_TOP_N).map(({ entry }) => entry.id));
|
|
200
|
+
for (const id of mustKeepIds)
|
|
201
|
+
selectedIds.add(id);
|
|
202
|
+
const selected = entries.filter((entry) => selectedIds.has(entry.id));
|
|
203
|
+
const note = `[showing ${selected.length} of ${entries.length} entries most relevant to this conversation — not the full file]`;
|
|
204
|
+
return `${note}\n${selected.map((entry) => `${entry.id} — ${entry.content}`).join("\n")}`;
|
|
169
205
|
}
|
|
206
|
+
/**
|
|
207
|
+
* Tool output never reaches this prompt: `sanitizeMessagesForMemory` drops every `toolResult`
|
|
208
|
+
* message before serialization (`transcript.ts`), an invariant pinned by
|
|
209
|
+
* `test/memory-transcript.test.ts` ("drops tool results ... before memory workers see them").
|
|
210
|
+
* That is why no additional untrusted-content filter is applied here — a window-level one used to
|
|
211
|
+
* exist and silently discarded every durable write from any tool-using conversation.
|
|
212
|
+
*/
|
|
170
213
|
export async function runMemoryExtraction(request) {
|
|
171
214
|
const [currentSession, rawMemory, currentHistory] = await Promise.all([
|
|
172
215
|
readChannelSession(request.channelDir),
|
|
@@ -174,7 +217,7 @@ export async function runMemoryExtraction(request) {
|
|
|
174
217
|
readChannelHistory(request.channelDir),
|
|
175
218
|
]);
|
|
176
219
|
const transcript = clipText(serializeConversation(sanitizeMessagesForMemory(request.messages)), request.transcriptMaxChars, { headRatio: 0.35 });
|
|
177
|
-
const currentMemory = clipText(
|
|
220
|
+
const currentMemory = clipText(await renderSimilarMemoryEntriesForPrompt(request.channelDir, rawMemory, transcript), 8_000, { headRatio: 0.35 });
|
|
178
221
|
const promptSections = [
|
|
179
222
|
`Current SESSION.md:\n${clipText(currentSession, 8_000, { headRatio: 0.35 }) || "(empty)"}`,
|
|
180
223
|
`Current MEMORY.md entries (id — content; reference ids in supersede/invalidate):\n${currentMemory || "(empty)"}`,
|
package/dist/memory/files.d.ts
CHANGED
|
@@ -68,6 +68,5 @@ export declare function rewriteChannelMemory(channelDir: string, content: string
|
|
|
68
68
|
export declare function rewriteChannelHistory(channelDir: string, content: string): Promise<void>;
|
|
69
69
|
export declare function rewriteChannelSession(channelDir: string, content: string): Promise<void>;
|
|
70
70
|
export declare function getChannelHistoryArchivePath(channelDir: string): string;
|
|
71
|
-
/** Append raw history blocks to a never-rewritten archive before lossy folding. */
|
|
72
71
|
export declare function appendChannelHistoryArchive(channelDir: string, block: HistoryBlock): Promise<void>;
|
|
73
72
|
export declare function appendChannelHistoryBlock(channelDir: string, block: HistoryBlock): Promise<void>;
|
package/dist/memory/files.js
CHANGED
|
@@ -1,10 +1,10 @@
|
|
|
1
1
|
import { createHash, randomBytes } from "crypto";
|
|
2
|
-
import { existsSync, mkdirSync
|
|
3
|
-
import { copyFile, readdir, rm } from "fs/promises";
|
|
2
|
+
import { existsSync, mkdirSync } from "fs";
|
|
3
|
+
import { appendFile, copyFile, readdir, rename, rm, stat } from "fs/promises";
|
|
4
4
|
import { basename, join } from "path";
|
|
5
|
-
import { writeFileAtomically } from "../shared/atomic-file.js";
|
|
5
|
+
import { writeFileAtomically, writeFileAtomicallySync } from "../shared/atomic-file.js";
|
|
6
6
|
import { readOptionalTextFile } from "../shared/fs-utils.js";
|
|
7
|
-
import { formatLocalTime, localStampForFilename } from "../shared/local-time.js";
|
|
7
|
+
import { formatLocalTime, localStampForFilename, parseLocalTime } from "../shared/local-time.js";
|
|
8
8
|
import { syncMemoryMetadata } from "./metadata.js";
|
|
9
9
|
import { containsSecret, REDACTED_SECRET } from "./secret-redaction.js";
|
|
10
10
|
import { appendMemoryTombstone, hashMemoryContent, readMemoryTombstones } from "./tombstones.js";
|
|
@@ -65,7 +65,10 @@ const DEFAULT_CHANNEL_SESSION = `# Session Title
|
|
|
65
65
|
<!-- Very terse notes about recent progress. -->
|
|
66
66
|
`;
|
|
67
67
|
const MEMORY_BACKUP_DIR = ".memory-backups";
|
|
68
|
-
|
|
68
|
+
// Backups are the last line of defense against a bad cleanup/rewrite (§1.3 tightened the guards
|
|
69
|
+
// in front of them, but the backups themselves are what a human falls back to). At the default
|
|
70
|
+
// 6-hour structural-maintenance cadence, 5 backups covered only ~30 hours of history.
|
|
71
|
+
const MEMORY_BACKUP_KEEP = 10;
|
|
69
72
|
const ENTRY_ID_COMMENT = /<!--\s*id:(m-[a-z0-9]+)\s*-->/i;
|
|
70
73
|
const ENTRY_ID_COMMENT_TRAILING = /\s*<!--\s*id:m-[a-z0-9]+\s*-->\s*$/i;
|
|
71
74
|
export function generateMemoryEntryId() {
|
|
@@ -89,7 +92,7 @@ export function parseUpdateHeadingTimestamp(heading) {
|
|
|
89
92
|
return undefined;
|
|
90
93
|
}
|
|
91
94
|
const timestamp = match[1].trim();
|
|
92
|
-
return
|
|
95
|
+
return parseLocalTime(timestamp) !== undefined ? timestamp : undefined;
|
|
93
96
|
}
|
|
94
97
|
/** Parse durable MEMORY.md bullet entries with stable ids for op-based edits. */
|
|
95
98
|
export function parseChannelMemoryEntries(content) {
|
|
@@ -336,13 +339,13 @@ export function ensureChannelMemoryFilesSync(channelDir) {
|
|
|
336
339
|
const sessionPath = getChannelSessionPath(channelDir);
|
|
337
340
|
mkdirSync(channelDir, { recursive: true });
|
|
338
341
|
if (!existsSync(memoryPath)) {
|
|
339
|
-
|
|
342
|
+
writeFileAtomicallySync(memoryPath, DEFAULT_CHANNEL_MEMORY);
|
|
340
343
|
}
|
|
341
344
|
if (!existsSync(historyPath)) {
|
|
342
|
-
|
|
345
|
+
writeFileAtomicallySync(historyPath, DEFAULT_CHANNEL_HISTORY);
|
|
343
346
|
}
|
|
344
347
|
if (!existsSync(sessionPath)) {
|
|
345
|
-
|
|
348
|
+
writeFileAtomicallySync(sessionPath, DEFAULT_CHANNEL_SESSION);
|
|
346
349
|
}
|
|
347
350
|
}
|
|
348
351
|
export async function readChannelMemory(channelDir) {
|
|
@@ -378,6 +381,10 @@ export function getChannelHistoryArchivePath(channelDir) {
|
|
|
378
381
|
return join(channelDir, "HISTORY.archive.md");
|
|
379
382
|
}
|
|
380
383
|
/** Append raw history blocks to a never-rewritten archive before lossy folding. */
|
|
384
|
+
// First-generation LLM summaries live only here (not in context.jsonl), so this file is never
|
|
385
|
+
// deleted, only rotated: at 4MB the whole file becomes `.1` (overwriting any older `.1`) and a
|
|
386
|
+
// fresh file starts, capping retention at two generations instead of growing unbounded.
|
|
387
|
+
const HISTORY_ARCHIVE_ROTATE_AT_BYTES = 4 * 1024 * 1024;
|
|
381
388
|
export async function appendChannelHistoryArchive(channelDir, block) {
|
|
382
389
|
const trimmedContent = block.content.trim();
|
|
383
390
|
if (!trimmedContent) {
|
|
@@ -385,10 +392,22 @@ export async function appendChannelHistoryArchive(channelDir, block) {
|
|
|
385
392
|
}
|
|
386
393
|
await ensureChannelMemoryFiles(channelDir);
|
|
387
394
|
const path = getChannelHistoryArchivePath(channelDir);
|
|
388
|
-
const existing = await readOptionalTextFile(path);
|
|
389
|
-
const header = existing.trim() ? existing : "# Channel History Archive\n";
|
|
390
395
|
const renderedBlock = [`## Archived ${block.timestamp}`, trimmedContent].join("\n\n");
|
|
391
|
-
await
|
|
396
|
+
const currentSize = await stat(path)
|
|
397
|
+
.then((info) => info.size)
|
|
398
|
+
.catch(() => 0);
|
|
399
|
+
if (currentSize === 0) {
|
|
400
|
+
await writeFileAtomically(path, `${ensureTrailingNewlines("# Channel History Archive\n")}${renderedBlock}\n`);
|
|
401
|
+
return;
|
|
402
|
+
}
|
|
403
|
+
if (currentSize >= HISTORY_ARCHIVE_ROTATE_AT_BYTES) {
|
|
404
|
+
await rename(path, `${path}.1`).catch(() => { });
|
|
405
|
+
await writeFileAtomically(path, `${ensureTrailingNewlines("# Channel History Archive\n")}${renderedBlock}\n`);
|
|
406
|
+
return;
|
|
407
|
+
}
|
|
408
|
+
// Append-only: this file only ever grows through this function, so a full read-modify-write
|
|
409
|
+
// on every fold (previously O(n) per call, O(n^2) over the file's lifetime) is unnecessary.
|
|
410
|
+
await appendFile(path, `\n${renderedBlock}\n`, "utf-8");
|
|
392
411
|
}
|
|
393
412
|
export async function appendChannelHistoryBlock(channelDir, block) {
|
|
394
413
|
const trimmedContent = block.content.trim();
|
package/dist/memory/lifecycle.js
CHANGED
|
@@ -211,8 +211,15 @@ export class MemoryLifecycle {
|
|
|
211
211
|
}
|
|
212
212
|
const actions = [];
|
|
213
213
|
const skipped = [];
|
|
214
|
-
|
|
215
|
-
|
|
214
|
+
const candidateCount = result.appendedDurableEntries + result.appendedProbationaryEntries;
|
|
215
|
+
if (candidateCount > 0 || result.appendedMemoryEntries > 0) {
|
|
216
|
+
actions.push({
|
|
217
|
+
target: "MEMORY.md",
|
|
218
|
+
action: "append",
|
|
219
|
+
entries: result.appendedMemoryEntries,
|
|
220
|
+
durableCandidates: result.appendedDurableEntries,
|
|
221
|
+
probationaryCandidates: result.appendedProbationaryEntries,
|
|
222
|
+
});
|
|
216
223
|
}
|
|
217
224
|
if (result.appendedHistoryBlock) {
|
|
218
225
|
actions.push({ target: "HISTORY.md", action: "append" });
|
|
@@ -10,7 +10,7 @@ import { collectExpiredEntryIds, expireMemoryEntries } from "./probation.js";
|
|
|
10
10
|
import { appendMemoryReviewLog } from "./review-log.js";
|
|
11
11
|
import { updateChannelSessionMemory } from "./session.js";
|
|
12
12
|
import { buildIncrementalMemorySourceWindow } from "./source-window.js";
|
|
13
|
-
import { sanitizeMessagesForMemory } from "./transcript.js";
|
|
13
|
+
import { hasMeaningfulExchange, sanitizeMessagesForMemory } from "./transcript.js";
|
|
14
14
|
/** Evaluate `load` at most once, so a gate and the job body can share one expensive read. */
|
|
15
15
|
function once(load) {
|
|
16
16
|
let cached;
|
|
@@ -22,40 +22,8 @@ function once(load) {
|
|
|
22
22
|
function latestEntryId(entries) {
|
|
23
23
|
return entries.at(-1)?.id;
|
|
24
24
|
}
|
|
25
|
-
function messageToText(message) {
|
|
26
|
-
if (message.role === "user") {
|
|
27
|
-
return typeof message.content === "string"
|
|
28
|
-
? message.content
|
|
29
|
-
: message.content.map((part) => (part.type === "text" ? part.text : "[image]")).join("\n");
|
|
30
|
-
}
|
|
31
|
-
if (message.role === "assistant") {
|
|
32
|
-
return message.content
|
|
33
|
-
.map((part) => (part.type === "text" ? part.text : ""))
|
|
34
|
-
.filter(Boolean)
|
|
35
|
-
.join("\n");
|
|
36
|
-
}
|
|
37
|
-
return "";
|
|
38
|
-
}
|
|
39
25
|
function hasMeaningfulMessages(messages) {
|
|
40
|
-
|
|
41
|
-
let userSeen = false;
|
|
42
|
-
let assistantSeen = false;
|
|
43
|
-
for (const message of standardMessages) {
|
|
44
|
-
const text = messageToText(message).trim();
|
|
45
|
-
if (!text) {
|
|
46
|
-
continue;
|
|
47
|
-
}
|
|
48
|
-
if (message.role === "user") {
|
|
49
|
-
userSeen = true;
|
|
50
|
-
}
|
|
51
|
-
if (message.role === "assistant") {
|
|
52
|
-
assistantSeen = true;
|
|
53
|
-
}
|
|
54
|
-
if (userSeen && assistantSeen) {
|
|
55
|
-
return true;
|
|
56
|
-
}
|
|
57
|
-
}
|
|
58
|
-
return false;
|
|
26
|
+
return hasMeaningfulExchange(sanitizeMessagesForMemory(messages));
|
|
59
27
|
}
|
|
60
28
|
function makeRunOptions(input, usageCorrelationId) {
|
|
61
29
|
return {
|
|
@@ -198,7 +166,15 @@ export async function runMemoryCheckpointJob(input) {
|
|
|
198
166
|
correlationId: sourceWindow.windowId,
|
|
199
167
|
}
|
|
200
168
|
: {
|
|
201
|
-
actions: [
|
|
169
|
+
actions: [
|
|
170
|
+
{
|
|
171
|
+
target: "MEMORY.md",
|
|
172
|
+
action: "append",
|
|
173
|
+
entries: result.appendedMemoryEntries,
|
|
174
|
+
durableCandidates: result.appendedDurableEntries,
|
|
175
|
+
probationaryCandidates: result.appendedProbationaryEntries,
|
|
176
|
+
},
|
|
177
|
+
],
|
|
202
178
|
skipped: (result.rejectedMemoryOps ?? []).map((candidate) => ({
|
|
203
179
|
target: "MEMORY.md",
|
|
204
180
|
candidate,
|
|
@@ -252,12 +228,12 @@ export async function runStructuralMaintenanceJob(input) {
|
|
|
252
228
|
// `loadFiles`'s cached read predates the expiry write above, so a fresh read is needed
|
|
253
229
|
// whenever expiry actually changed the file; otherwise the cache is still accurate.
|
|
254
230
|
const currentMemory = expiredCount > 0 ? await readChannelMemory(input.channelDir) : cachedMemory;
|
|
255
|
-
const
|
|
231
|
+
const cleanup = decision.runMemoryCleanup
|
|
256
232
|
? await cleanupChannelMemory(options, currentMemory, {
|
|
257
233
|
cleanupShrinkGuardMinRatio: input.settings.memoryMaintenance.cleanupShrinkGuardMinRatio,
|
|
258
234
|
cleanupShrinkGuardMinChars: input.settings.memoryMaintenance.cleanupShrinkGuardMinChars,
|
|
259
235
|
})
|
|
260
|
-
:
|
|
236
|
+
: null;
|
|
261
237
|
const foldedHistory = decision.runHistoryFolding ? await foldChannelHistory(options, currentHistory) : false;
|
|
262
238
|
await updateMemoryMaintenanceState(input.appHomeDir, input.channelId, (current) => ({
|
|
263
239
|
...current,
|
|
@@ -268,7 +244,9 @@ export async function runStructuralMaintenanceJob(input) {
|
|
|
268
244
|
correlationId,
|
|
269
245
|
actions: [
|
|
270
246
|
...(expiredCount > 0 ? [{ target: "MEMORY.md", action: "expire", entries: expiredCount }] : []),
|
|
271
|
-
...(
|
|
247
|
+
...(cleanup?.rewritten
|
|
248
|
+
? [{ target: "MEMORY.md", action: "rewrite", droppedEntryIds: cleanup.droppedEntryIds }]
|
|
249
|
+
: []),
|
|
272
250
|
...(foldedHistory ? [{ target: "HISTORY.md", action: "rewrite" }] : []),
|
|
273
251
|
],
|
|
274
252
|
}, now);
|
|
@@ -2,6 +2,7 @@ import { readFile } from "node:fs/promises";
|
|
|
2
2
|
import { join } from "node:path";
|
|
3
3
|
import * as log from "../log.js";
|
|
4
4
|
import { writeFileAtomically } from "../shared/atomic-file.js";
|
|
5
|
+
import { parseLocalTime } from "../shared/local-time.js";
|
|
5
6
|
import { createSerialQueue } from "../shared/serial-queue.js";
|
|
6
7
|
import { errorMessage } from "../shared/text-utils.js";
|
|
7
8
|
const stateUpdateQueue = createSerialQueue();
|
|
@@ -37,7 +38,7 @@ function laterTimestamp(a, b) {
|
|
|
37
38
|
return b;
|
|
38
39
|
if (!b)
|
|
39
40
|
return a;
|
|
40
|
-
return
|
|
41
|
+
return (parseLocalTime(a) ?? -Infinity) >= (parseLocalTime(b) ?? -Infinity) ? a : b;
|
|
41
42
|
}
|
|
42
43
|
function normalizeState(channelId, value) {
|
|
43
44
|
if (!value || typeof value !== "object" || Array.isArray(value)) {
|
|
@@ -1,10 +1,12 @@
|
|
|
1
1
|
export type MemoryEntryKind = "fact" | "preference" | "decision" | "constraint" | "open-loop" | "lesson";
|
|
2
2
|
export type MemorySourceType = "user" | "agent" | "repo" | "tool" | "web" | "legacy";
|
|
3
3
|
export type MemoryEntryStatus = "active" | "superseded" | "invalidated" | "forgotten";
|
|
4
|
+
export type MemoryEntryNecessity = "low" | "medium" | "high";
|
|
4
5
|
export interface MemoryWriteMetadataInput {
|
|
5
6
|
kind?: MemoryEntryKind;
|
|
6
7
|
sourceType?: MemorySourceType;
|
|
7
8
|
sourceCorrelationId?: string;
|
|
9
|
+
necessity?: MemoryEntryNecessity;
|
|
8
10
|
/**
|
|
9
11
|
* Probationary write deadline (spec 037, D6/D7): `undefined` leaves any existing value alone,
|
|
10
12
|
* a string sets/renews it, `null` explicitly clears it (promotion to durable). Distinct from
|
|
@@ -19,6 +21,7 @@ export interface MemoryEntryMetadata {
|
|
|
19
21
|
sourceEntryIds: string[];
|
|
20
22
|
sourceCorrelationIds: string[];
|
|
21
23
|
sourceType: MemorySourceType;
|
|
24
|
+
necessity?: MemoryEntryNecessity;
|
|
22
25
|
createdAt: string;
|
|
23
26
|
updatedAt: string;
|
|
24
27
|
status: MemoryEntryStatus;
|
package/dist/memory/metadata.js
CHANGED
|
@@ -63,6 +63,7 @@ export async function syncMemoryMetadata(channelDir, activeEntries, updates = []
|
|
|
63
63
|
...(hint?.sourceCorrelationId ? [hint.sourceCorrelationId] : []),
|
|
64
64
|
])),
|
|
65
65
|
sourceType: hint?.sourceType ?? previous?.sourceType ?? "legacy",
|
|
66
|
+
necessity: hint?.necessity ?? previous?.necessity,
|
|
66
67
|
createdAt: previous?.createdAt ?? entry.timestamp ?? timestamp,
|
|
67
68
|
updatedAt: update || previous?.contentHash !== contentHash(entry.content) ? timestamp : previous.updatedAt,
|
|
68
69
|
status: "active",
|
|
@@ -87,6 +88,12 @@ export async function syncMemoryMetadata(channelDir, activeEntries, updates = []
|
|
|
87
88
|
entries[id] = { ...entry, status: "invalidated", updatedAt: timestamp };
|
|
88
89
|
}
|
|
89
90
|
}
|
|
91
|
+
// `updatedAt` is per-entry and only advances when a field actually changes (see above), so
|
|
92
|
+
// a byte-identical `entries` map means this call had nothing new to record — a bare
|
|
93
|
+
// reconcile pass over an unchanged file should not cost an atomic write every turn.
|
|
94
|
+
if (JSON.stringify(entries) === JSON.stringify(current.entries)) {
|
|
95
|
+
return current;
|
|
96
|
+
}
|
|
90
97
|
const next = { schemaVersion: 1, updatedAt: timestamp, entries };
|
|
91
98
|
await writeFileAtomically(path, `${JSON.stringify(next, null, 2)}\n`);
|
|
92
99
|
return next;
|
package/dist/memory/recall.d.ts
CHANGED
|
@@ -1,3 +1,4 @@
|
|
|
1
|
+
import type { AgentMessage } from "@earendil-works/pi-agent-core";
|
|
1
2
|
import type { Api, Model } from "@earendil-works/pi-ai";
|
|
2
3
|
import { type MemoryCandidate, type MemoryCandidateStore } from "./candidates.js";
|
|
3
4
|
export interface RecallRequest {
|
|
@@ -20,6 +21,12 @@ export interface RecallRequest {
|
|
|
20
21
|
model: Model<Api>;
|
|
21
22
|
resolveApiKey: (model: Model<Api>) => Promise<string>;
|
|
22
23
|
candidateStore?: MemoryCandidateStore;
|
|
24
|
+
/**
|
|
25
|
+
* The previous user turn, offered as scoring-only fallback context for a deictic follow-up
|
|
26
|
+
* ("那个方案后来怎么定的?") whose own tokens cannot clear the evidence bar. Never enters the
|
|
27
|
+
* prompt or the recall query fingerprint — only `query` does.
|
|
28
|
+
*/
|
|
29
|
+
contextQuery?: string;
|
|
23
30
|
}
|
|
24
31
|
export interface RecalledMemory {
|
|
25
32
|
id: string;
|
|
@@ -36,5 +43,17 @@ export interface RecallResult {
|
|
|
36
43
|
}
|
|
37
44
|
/** Automatic-context share for relevant memory recall (spec 026 §5.3). */
|
|
38
45
|
export declare const MEMORY_RECALL_MAX_UNITS = 1800;
|
|
46
|
+
/** The most recent user turn, with injected memory/context wrappers stripped (see `transcript.ts`). */
|
|
47
|
+
export declare function findPreviousUserText(messages: AgentMessage[]): string | undefined;
|
|
39
48
|
export declare function tokenizeRecallText(text: string): string[];
|
|
49
|
+
/**
|
|
50
|
+
* Age-bucketed recency boost (≤1 day / ≤7 days / ≤30 days / older), scaled by `weights` — the
|
|
51
|
+
* bucket shape is shared with `session-search.ts`'s scoring, but the two scoring systems live on
|
|
52
|
+
* different magnitudes, so each caller supplies its own weights rather than sharing a fixed scale.
|
|
53
|
+
*/
|
|
54
|
+
export declare function recencyBoostByAge(timestamp: string | undefined, weights: {
|
|
55
|
+
day: number;
|
|
56
|
+
week: number;
|
|
57
|
+
month: number;
|
|
58
|
+
}): number;
|
|
40
59
|
export declare function recallRelevantMemory(request: RecallRequest): Promise<RecallResult>;
|
package/dist/memory/recall.js
CHANGED
|
@@ -1,11 +1,14 @@
|
|
|
1
1
|
import * as log from "../log.js";
|
|
2
2
|
import { parseJsonObject } from "../shared/llm-json.js";
|
|
3
|
+
import { parseLocalTime } from "../shared/local-time.js";
|
|
3
4
|
import { countPromptUnits } from "../shared/prompt-units.js";
|
|
4
5
|
import { errorMessage, HAN_REGEX } from "../shared/text-utils.js";
|
|
6
|
+
import { buildStandardMessages } from "../shared/type-guards.js";
|
|
5
7
|
import { buildMemoryCandidates, createMemoryCandidateStore, } from "./candidates.js";
|
|
6
8
|
import { COMMON_CHINESE_WORDS } from "./chinese-words.js";
|
|
7
|
-
import {
|
|
9
|
+
import { readMemoryMetadata, recordMemoryRecall } from "./metadata.js";
|
|
8
10
|
import { runSidecarTask } from "./sidecar-worker.js";
|
|
11
|
+
import { stripInjectedMemoryContext } from "./transcript.js";
|
|
9
12
|
const RERANK_SYSTEM_PROMPT = `You are selecting which memory snippets are most relevant to the current user turn.
|
|
10
13
|
|
|
11
14
|
Return strict JSON only:
|
|
@@ -37,6 +40,26 @@ const CLOSE_SCORE_DELTA = 3;
|
|
|
37
40
|
* absolute instead — one rare token match counts the same however long the message is.
|
|
38
41
|
*/
|
|
39
42
|
const MIN_MATCH_EVIDENCE = 2.5;
|
|
43
|
+
function extractUserMessageText(message) {
|
|
44
|
+
if (typeof message.content === "string")
|
|
45
|
+
return message.content;
|
|
46
|
+
return message.content
|
|
47
|
+
.filter((part) => part.type === "text")
|
|
48
|
+
.map((part) => part.text)
|
|
49
|
+
.join("\n");
|
|
50
|
+
}
|
|
51
|
+
/** The most recent user turn, with injected memory/context wrappers stripped (see `transcript.ts`). */
|
|
52
|
+
export function findPreviousUserText(messages) {
|
|
53
|
+
const standard = buildStandardMessages(messages);
|
|
54
|
+
for (let index = standard.length - 1; index >= 0; index--) {
|
|
55
|
+
const message = standard[index];
|
|
56
|
+
if (message?.role === "user") {
|
|
57
|
+
const text = stripInjectedMemoryContext(extractUserMessageText(message));
|
|
58
|
+
return text.length > 0 ? text : undefined;
|
|
59
|
+
}
|
|
60
|
+
}
|
|
61
|
+
return undefined;
|
|
62
|
+
}
|
|
40
63
|
/** Field the strongest match for a token was found in; a token scores once, at its best field. */
|
|
41
64
|
const FIELD_WEIGHTS = { title: 1.4, content: 1, path: 0.7 };
|
|
42
65
|
const MAX_HAN_WORD_LENGTH = Array.from(COMMON_CHINESE_WORDS).reduce((max, word) => Math.max(max, word.length), 2);
|
|
@@ -360,22 +383,30 @@ function normalizeExactMatchQuery(query) {
|
|
|
360
383
|
const minLength = containsHanText(normalizedQuery) ? 2 : 4;
|
|
361
384
|
return normalizedQuery.length >= minLength ? normalizedQuery : "";
|
|
362
385
|
}
|
|
363
|
-
|
|
386
|
+
/**
|
|
387
|
+
* Age-bucketed recency boost (≤1 day / ≤7 days / ≤30 days / older), scaled by `weights` — the
|
|
388
|
+
* bucket shape is shared with `session-search.ts`'s scoring, but the two scoring systems live on
|
|
389
|
+
* different magnitudes, so each caller supplies its own weights rather than sharing a fixed scale.
|
|
390
|
+
*/
|
|
391
|
+
export function recencyBoostByAge(timestamp, weights) {
|
|
364
392
|
if (!timestamp)
|
|
365
393
|
return 0;
|
|
366
|
-
const timestampMs =
|
|
367
|
-
if (
|
|
394
|
+
const timestampMs = parseLocalTime(timestamp);
|
|
395
|
+
if (timestampMs === undefined)
|
|
368
396
|
return 0;
|
|
369
397
|
const ageMs = Date.now() - timestampMs;
|
|
370
398
|
const dayMs = 24 * 60 * 60 * 1000;
|
|
371
399
|
if (ageMs <= dayMs)
|
|
372
|
-
return
|
|
400
|
+
return weights.day;
|
|
373
401
|
if (ageMs <= 7 * dayMs)
|
|
374
|
-
return
|
|
402
|
+
return weights.week;
|
|
375
403
|
if (ageMs <= 30 * dayMs)
|
|
376
|
-
return
|
|
404
|
+
return weights.month;
|
|
377
405
|
return 0;
|
|
378
406
|
}
|
|
407
|
+
function computeRecencyBoost(timestamp) {
|
|
408
|
+
return recencyBoostByAge(timestamp, { day: 6, week: 4, month: 2 });
|
|
409
|
+
}
|
|
379
410
|
function detectQueryIntents(query) {
|
|
380
411
|
const intents = new Set();
|
|
381
412
|
if (/\b(now|current|currently|status)\b/i.test(query) || /(现在|当前|目前|正在|状态)/u.test(query)) {
|
|
@@ -422,14 +453,49 @@ function compareScoredCandidates(a, b) {
|
|
|
422
453
|
b.candidate.priority - a.candidate.priority ||
|
|
423
454
|
a.candidate.title.localeCompare(b.candidate.title));
|
|
424
455
|
}
|
|
425
|
-
|
|
456
|
+
const USAGE_BOOST_MAX = 6;
|
|
457
|
+
const STALE_PENALTY = 2;
|
|
458
|
+
const STALE_AFTER_DAYS = 90;
|
|
459
|
+
const NECESSITY_BOOST = { high: 4, medium: 1, low: 0 };
|
|
460
|
+
function isOlderThanDays(timestamp, days, nowMs) {
|
|
461
|
+
if (!timestamp)
|
|
462
|
+
return false;
|
|
463
|
+
const ms = parseLocalTime(timestamp);
|
|
464
|
+
if (ms === undefined)
|
|
465
|
+
return false;
|
|
466
|
+
return nowMs - ms > days * 24 * 60 * 60 * 1000;
|
|
467
|
+
}
|
|
468
|
+
/**
|
|
469
|
+
* A small, capped tiebreaker on top of lexical evidence — never the reason a candidate enters
|
|
470
|
+
* the shortlist, only a nudge in how the shortlist is ordered (see `scoreCandidate`'s `1 +
|
|
471
|
+
* structuralScore / 100` multiplier, currently ~4-34 without this term; this adds at most +10%).
|
|
472
|
+
* Kept deliberately small: `recallCount` measures "was injected into a prompt", not "was actually
|
|
473
|
+
* used" — a strong signal would let a handful of noisy queries entrench one entry at the top of
|
|
474
|
+
* every future recall.
|
|
475
|
+
*/
|
|
476
|
+
function computeMemoryUsageBoost(record, nowMs) {
|
|
477
|
+
if (!record)
|
|
478
|
+
return 0;
|
|
479
|
+
// Distinct query fingerprints matter more than raw count: one person asking the same thing
|
|
480
|
+
// twenty times is one recurring need, twenty different phrasings is a fact the channel keeps
|
|
481
|
+
// bumping into from different directions.
|
|
482
|
+
const used = Math.min(USAGE_BOOST_MAX, 1.5 * Math.log2(1 + record.recallCount) + 1.5 * Math.log2(1 + record.queryFingerprints.length));
|
|
483
|
+
// A user-saved fact that nobody has asked about yet is not stale — it just hasn't come up.
|
|
484
|
+
const stale = record.sourceType === "agent" &&
|
|
485
|
+
isOlderThanDays(record.lastRecalledAt ?? record.createdAt, STALE_AFTER_DAYS, nowMs)
|
|
486
|
+
? STALE_PENALTY
|
|
487
|
+
: 0;
|
|
488
|
+
return used - stale + (NECESSITY_BOOST[record.necessity ?? "low"] ?? 0);
|
|
489
|
+
}
|
|
490
|
+
function scoreCandidate(exactMatchQuery, queryTokens, intents, candidate, documentFrequencies, totalCandidates, metadataFor, nowMs) {
|
|
426
491
|
const evidence = computeMatchEvidence(queryTokens, candidate, documentFrequencies, totalCandidates);
|
|
427
492
|
const totalEvidence = evidence.mass + computeExactMatchBoost(exactMatchQuery, candidate);
|
|
428
493
|
if (totalEvidence < MIN_MATCH_EVIDENCE) {
|
|
429
494
|
return null;
|
|
430
495
|
}
|
|
431
496
|
const intentBoost = computeSectionIntentBoost(intents, candidate);
|
|
432
|
-
const
|
|
497
|
+
const usageBoost = computeMemoryUsageBoost(metadataFor(candidate.entryId), nowMs);
|
|
498
|
+
const structuralScore = candidate.priority + intentBoost + usageBoost + computeRecencyBoost(candidate.timestamp);
|
|
433
499
|
return {
|
|
434
500
|
candidate,
|
|
435
501
|
score: totalEvidence * (1 + structuralScore / 100),
|
|
@@ -513,7 +579,15 @@ async function rerankCandidates(request, candidates) {
|
|
|
513
579
|
});
|
|
514
580
|
const selectedIds = new Set(result.output);
|
|
515
581
|
if (selectedIds.size === 0) {
|
|
516
|
-
|
|
582
|
+
// The reranker only ever runs on a shortlist that already cleared MIN_MATCH_EVIDENCE,
|
|
583
|
+
// so "nothing is relevant" is a judgement call over candidates with real lexical
|
|
584
|
+
// evidence behind them. Injecting one extra item costs a few hundred units; injecting
|
|
585
|
+
// nothing costs the turn its memory — and "it forgot what I told it" is this
|
|
586
|
+
// subsystem's most common complaint. Floor at the local top pick.
|
|
587
|
+
log.logEvent("debug", "memory.recall.rerank.empty", "Reranker selected nothing; keeping local top-1", {
|
|
588
|
+
fields: { shortlist: candidates.length },
|
|
589
|
+
});
|
|
590
|
+
return candidates.slice(0, 1);
|
|
517
591
|
}
|
|
518
592
|
const selected = candidates.filter(({ candidate }) => selectedIds.has(candidate.id));
|
|
519
593
|
return selected.length > 0 ? selected : candidates;
|
|
@@ -587,7 +661,7 @@ function renderRecallResult(items, maxChars, maxUnits) {
|
|
|
587
661
|
}
|
|
588
662
|
const omittedCount = items.length - includedCount;
|
|
589
663
|
if (omittedCount > 0) {
|
|
590
|
-
clippedLines.push("", `[- ${omittedCount} more item(s) omitted for length; use
|
|
664
|
+
clippedLines.push("", `[- ${omittedCount} more item(s) omitted for length; use memory_search or session_search to look them up.]`);
|
|
591
665
|
}
|
|
592
666
|
clippedLines.push(closing);
|
|
593
667
|
return clippedLines.join("\n");
|
|
@@ -609,15 +683,38 @@ export async function recallRelevantMemory(request) {
|
|
|
609
683
|
if (eligibleCandidates.length === 0) {
|
|
610
684
|
return { items: [], renderedText: "" };
|
|
611
685
|
}
|
|
612
|
-
const queryTokens = tokenize(query);
|
|
613
|
-
const queryIntents = detectQueryIntents(query);
|
|
614
686
|
const exactMatchQuery = normalizeExactMatchQuery(query);
|
|
615
687
|
const documentFrequencies = buildDocumentFrequency(eligibleCandidates);
|
|
616
688
|
const totalCandidates = eligibleCandidates.length;
|
|
617
|
-
const
|
|
618
|
-
|
|
689
|
+
const memoryMetadata = await readMemoryMetadata(request.channelDir);
|
|
690
|
+
const metadataFor = (entryId) => entryId ? memoryMetadata.entries[entryId] : undefined;
|
|
691
|
+
const nowMs = Date.now();
|
|
692
|
+
const scoreAll = (tokens, intents) => eligibleCandidates
|
|
693
|
+
.map((candidate) => scoreCandidate(exactMatchQuery, tokens, intents, candidate, documentFrequencies, totalCandidates, metadataFor, nowMs))
|
|
619
694
|
.filter((candidate) => candidate !== null)
|
|
620
695
|
.sort(compareScoredCandidates);
|
|
696
|
+
let queryTokens = tokenize(query);
|
|
697
|
+
let queryIntents = detectQueryIntents(query);
|
|
698
|
+
let scored = scoreAll(queryTokens, queryIntents);
|
|
699
|
+
// A deictic follow-up ("那个方案后来怎么定的") cannot clear MIN_MATCH_EVIDENCE against any
|
|
700
|
+
// candidate on its own — the query's own tokens produced an empty shortlist. Only then is it
|
|
701
|
+
// worth borrowing the previous user turn for scoring. When the current message *can* clear
|
|
702
|
+
// the bar by itself this branch never runs, so expansion is invisible except exactly where
|
|
703
|
+
// recall would otherwise return empty — scoring is absolute evidence mass, not
|
|
704
|
+
// query-length-normalized coverage, so appending tokens can only ever add candidates, never
|
|
705
|
+
// drop ones the own query already found.
|
|
706
|
+
const contextQuery = scored.length === 0 ? request.contextQuery?.trim() : undefined;
|
|
707
|
+
if (contextQuery) {
|
|
708
|
+
const scoringQuery = `${query} ${contextQuery}`;
|
|
709
|
+
const combinedTokens = tokenize(scoringQuery);
|
|
710
|
+
const combinedIntents = detectQueryIntents(scoringQuery);
|
|
711
|
+
const combinedScored = scoreAll(combinedTokens, combinedIntents);
|
|
712
|
+
if (combinedScored.length > 0) {
|
|
713
|
+
queryTokens = combinedTokens;
|
|
714
|
+
queryIntents = combinedIntents;
|
|
715
|
+
scored = combinedScored;
|
|
716
|
+
}
|
|
717
|
+
}
|
|
621
718
|
const shortlist = seedIntentCandidates(request, eligibleCandidates, scored, queryIntents, queryTokens, documentFrequencies, totalCandidates)
|
|
622
719
|
.sort(compareScoredCandidates)
|
|
623
720
|
.slice(0, Math.max(request.maxCandidates, request.maxInjected));
|
|
@@ -636,15 +733,10 @@ export async function recallRelevantMemory(request) {
|
|
|
636
733
|
}));
|
|
637
734
|
const recalledEntryIds = items.flatMap((item) => (item.entryId ? [item.entryId] : []));
|
|
638
735
|
if (recalledEntryIds.length > 0) {
|
|
639
|
-
|
|
640
|
-
|
|
641
|
-
|
|
642
|
-
|
|
643
|
-
content: candidate.content,
|
|
644
|
-
sectionHeading: candidate.title,
|
|
645
|
-
timestamp: candidate.timestamp,
|
|
646
|
-
}));
|
|
647
|
-
await syncMemoryMetadata(request.channelDir, metadataEntries);
|
|
736
|
+
// Recall is a read path: reconciling metadata against a possibly-stale
|
|
737
|
+
// `MemoryCandidateStore` snapshot here was the one source of the metadata/MEMORY.md drift
|
|
738
|
+
// race (every write path already reconciles: `applyChannelMemoryOps`, `rewriteChannelMemory`,
|
|
739
|
+
// and the `/memory` commands). `recordMemoryRecall` already no-ops on ids it doesn't know.
|
|
648
740
|
await recordMemoryRecall(request.channelDir, recalledEntryIds, query);
|
|
649
741
|
}
|
|
650
742
|
return {
|
|
@@ -5,9 +5,7 @@ export interface MemoryReviewLogEntry {
|
|
|
5
5
|
reason: MemoryReviewReason;
|
|
6
6
|
/** Joins this outcome to the corresponding sidecar usage-ledger entry. */
|
|
7
7
|
correlationId?: string;
|
|
8
|
-
candidates?: unknown[];
|
|
9
8
|
actions?: unknown[];
|
|
10
|
-
suggestions?: unknown[];
|
|
11
9
|
skipped?: unknown[];
|
|
12
10
|
error?: string;
|
|
13
11
|
}
|
|
Binary file
|
|
@@ -150,6 +150,11 @@ function parseLogEntry(value, path, lineNumber, maxChars) {
|
|
|
150
150
|
if (!isRecord(value)) {
|
|
151
151
|
return null;
|
|
152
152
|
}
|
|
153
|
+
// Command traffic (help/status/tasks/... echoes) is marked skipContextSync at write time
|
|
154
|
+
// (runtime/bootstrap.ts) so it never comes back as memory-extraction input.
|
|
155
|
+
if (value.skipContextSync === true) {
|
|
156
|
+
return null;
|
|
157
|
+
}
|
|
153
158
|
const isBot = value.isBot === true;
|
|
154
159
|
const text = getStringField(value, "text") ?? "";
|
|
155
160
|
const role = isBot ? "assistant" : "user";
|