@oyasmi/pipiclaw 0.9.1-beta.2 → 0.9.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 +7 -0
- package/dist/agent/channel-runner.js +42 -13
- 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/prompt/manifest.js +5 -6
- package/dist/agent/prompt/sections.js +1 -0
- package/dist/agent/reply-limits.d.ts +16 -0
- package/dist/agent/reply-limits.js +17 -0
- package/dist/agent/session-events.js +2 -2
- package/dist/agent/status-render.js +12 -12
- package/dist/executor.d.ts +14 -0
- package/dist/executor.js +36 -6
- 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 +33 -12
- 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 +24 -5
- package/dist/memory/lifecycle.js +9 -2
- package/dist/memory/maintenance-jobs.js +14 -4
- package/dist/memory/metadata.d.ts +3 -0
- package/dist/memory/metadata.js +7 -0
- package/dist/memory/recall.d.ts +9 -0
- package/dist/memory/recall.js +101 -17
- 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 +9 -0
- 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/playbooks/agent-delegation.md +32 -25
- package/dist/playbooks/background-jobs.md +8 -16
- package/dist/playbooks/event-scheduling.md +13 -15
- package/dist/playbooks/memory-and-learning.md +29 -22
- package/dist/playbooks/outbound-media.md +15 -8
- package/dist/playbooks/runtime-orientation.md +40 -37
- package/dist/playbooks/task-driving.md +34 -36
- package/dist/playbooks/task-planning.md +18 -18
- package/dist/runtime/app-home.d.ts +6 -0
- package/dist/runtime/app-home.js +15 -6
- package/dist/runtime/bootstrap.js +44 -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 +27 -13
- package/dist/runtime/event-commands.d.ts +15 -0
- package/dist/runtime/event-commands.js +48 -40
- 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 +106 -64
- package/dist/security/path-guard.js +33 -2
- package/dist/security/types.d.ts +9 -0
- package/dist/subagents/discovery.d.ts +7 -2
- package/dist/subagents/discovery.js +31 -7
- package/dist/subagents/external/claude-code.js +42 -2
- package/dist/subagents/external/run.js +61 -8
- package/dist/subagents/runs.js +6 -0
- package/dist/subagents/tool.d.ts +1 -0
- package/dist/subagents/tool.js +62 -53
- package/dist/tasks/verification.d.ts +7 -5
- package/dist/tools/bash.d.ts +1 -1
- package/dist/tools/bash.js +77 -59
- package/dist/tools/edit.js +17 -4
- package/dist/tools/grep.js +3 -2
- package/dist/tools/index.js +4 -0
- package/dist/tools/job.js +2 -1
- package/dist/tools/memory-manage.d.ts +1 -0
- package/dist/tools/memory-manage.js +54 -16
- package/dist/tools/read.js +21 -5
- package/dist/tools/send-media.js +17 -6
- package/dist/tools/skill-manage.js +12 -11
- package/dist/tools/skill-security.js +1 -1
- package/dist/tools/task-manage.js +1 -1
- package/dist/tools/truncate.d.ts +8 -0
- package/dist/tools/truncate.js +8 -0
- package/dist/tools/web-fetch.js +9 -1
- package/dist/tools/write-content.js +11 -1
- 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/render.js +10 -8
- package/examples/sub-agents/README.md +2 -0
- package/package.json +3 -2
package/dist/memory/commands.js
CHANGED
|
@@ -1,6 +1,7 @@
|
|
|
1
|
-
import {
|
|
1
|
+
import { renderSubcommandUsage } from "../agent/commands.js";
|
|
2
|
+
import { capReply } from "../agent/reply-limits.js";
|
|
2
3
|
import { readOptionalTextFile } from "../shared/fs-utils.js";
|
|
3
|
-
import { localDayKey } from "../shared/local-time.js";
|
|
4
|
+
import { localDayKey, parseLocalTime } from "../shared/local-time.js";
|
|
4
5
|
import { clipText } from "../shared/text-utils.js";
|
|
5
6
|
import { getChannelMemoryPath, parseChannelMemoryEntries, readChannelMemory } from "./files.js";
|
|
6
7
|
import { syncMemoryMetadata } from "./metadata.js";
|
|
@@ -11,33 +12,41 @@ async function reconcile(options) {
|
|
|
11
12
|
const metadata = await syncMemoryMetadata(options.channelDir, entries);
|
|
12
13
|
return { entries, metadata };
|
|
13
14
|
}
|
|
14
|
-
|
|
15
|
+
/**
|
|
16
|
+
* Flattens `memory-review.jsonl` action entries for `/memory recent` and the `status` summary —
|
|
17
|
+
* the only consumers of the review log's write history. `user-forget` actions carry `entryId`
|
|
18
|
+
* instead of `target`/`action`; both shapes are tolerated here.
|
|
19
|
+
*/
|
|
20
|
+
async function readRecentMemoryActions(channelDir, sinceMs) {
|
|
15
21
|
const raw = await readOptionalTextFile(getMemoryReviewLogPath(channelDir));
|
|
16
|
-
const
|
|
22
|
+
const actions = [];
|
|
17
23
|
for (const line of raw.split("\n")) {
|
|
18
24
|
if (!line.trim())
|
|
19
25
|
continue;
|
|
20
26
|
try {
|
|
21
27
|
const entry = JSON.parse(line);
|
|
22
|
-
|
|
23
|
-
|
|
24
|
-
|
|
28
|
+
const entryMs = entry.timestamp ? (parseLocalTime(entry.timestamp) ?? 0) : 0;
|
|
29
|
+
if (entryMs < sinceMs)
|
|
30
|
+
continue;
|
|
31
|
+
for (const value of entry.actions ?? []) {
|
|
32
|
+
if (value && typeof value === "object") {
|
|
33
|
+
actions.push({ timestamp: entry.timestamp, reason: entry.reason, ...value });
|
|
34
|
+
}
|
|
25
35
|
}
|
|
26
36
|
}
|
|
27
37
|
catch {
|
|
28
38
|
// A torn audit line should not break the management surface.
|
|
29
39
|
}
|
|
30
40
|
}
|
|
31
|
-
return
|
|
41
|
+
return actions;
|
|
32
42
|
}
|
|
33
43
|
function renderUsage() {
|
|
34
|
-
return "
|
|
44
|
+
return renderSubcommandUsage("memory");
|
|
35
45
|
}
|
|
36
46
|
export async function handleMemoryCommand(options) {
|
|
37
47
|
const [action = "status", argument] = options.args.trim().split(/\s+/, 2);
|
|
38
48
|
const { entries, metadata } = await reconcile(options);
|
|
39
49
|
if (action === "status") {
|
|
40
|
-
const pending = await readPendingSuggestions(options.channelDir);
|
|
41
50
|
const tombstones = await readMemoryTombstones(options.channelDir);
|
|
42
51
|
const records = Object.values(metadata.entries);
|
|
43
52
|
const active = records.filter((entry) => entry.status === "active");
|
|
@@ -49,70 +58,102 @@ export async function handleMemoryCommand(options) {
|
|
|
49
58
|
const sinceDay = localDayKey(since);
|
|
50
59
|
const recalls30d = active.reduce((sum, entry) => sum +
|
|
51
60
|
Object.entries(entry.recallByDay ?? {}).reduce((entrySum, [day, count]) => entrySum + (day >= sinceDay ? count : 0), 0), 0);
|
|
61
|
+
const last7d = new Date();
|
|
62
|
+
last7d.setDate(last7d.getDate() - 7);
|
|
63
|
+
const recent = await readRecentMemoryActions(options.channelDir, last7d.getTime());
|
|
64
|
+
const written = recent
|
|
65
|
+
.filter((item) => item.target === "MEMORY.md" && item.action === "append")
|
|
66
|
+
.reduce((sum, item) => sum + (item.entries ?? 0), 0);
|
|
67
|
+
const dropped = recent.reduce((sum, item) => {
|
|
68
|
+
if (item.entryId)
|
|
69
|
+
return sum + 1;
|
|
70
|
+
if (item.target === "MEMORY.md" && item.action === "rewrite")
|
|
71
|
+
return sum + (item.droppedEntryIds?.length ?? 0);
|
|
72
|
+
return sum;
|
|
73
|
+
}, 0);
|
|
74
|
+
const expired = recent
|
|
75
|
+
.filter((item) => item.target === "MEMORY.md" && item.action === "expire")
|
|
76
|
+
.reduce((sum, item) => sum + (item.entries ?? 0), 0);
|
|
52
77
|
const lastFailure = (await readOptionalTextFile(getMemoryReviewLogPath(options.channelDir)))
|
|
53
78
|
.split("\n")
|
|
54
79
|
.reverse()
|
|
55
80
|
.find((line) => line.includes('"error"'));
|
|
56
81
|
return [
|
|
57
|
-
"
|
|
82
|
+
"**记忆状态**",
|
|
58
83
|
"",
|
|
59
|
-
`-
|
|
60
|
-
`-
|
|
61
|
-
`-
|
|
62
|
-
`-
|
|
63
|
-
`-
|
|
64
|
-
`-
|
|
65
|
-
`-
|
|
66
|
-
`-
|
|
67
|
-
`-
|
|
84
|
+
`- 生效条目:\`${entries.length}\``,
|
|
85
|
+
`- 元数据记录:\`${records.length}\``,
|
|
86
|
+
`- 观察期:\`${probationary.length}\`${probationary.length > 0 ? `(最早到期 \`${probationary[0].probationUntil}\`)` : ""}`,
|
|
87
|
+
`- 最近 7 天:+${written} 写入 / -${dropped} 丢弃 / -${expired} 过期`,
|
|
88
|
+
`- 墓碑:\`${tombstones.length}\``,
|
|
89
|
+
`- 累计召回:\`${active.reduce((sum, entry) => sum + entry.recallCount, 0)}\``,
|
|
90
|
+
`- 召回(30 天):\`${recalls30d}\``,
|
|
91
|
+
`- 查询多样性:\`${new Set(active.flatMap((entry) => entry.queryFingerprints)).size}\``,
|
|
92
|
+
`- 最近一次召回:\`${active
|
|
68
93
|
.map((entry) => entry.lastRecalledAt)
|
|
69
94
|
.filter(Boolean)
|
|
70
95
|
.sort()
|
|
71
|
-
.at(-1) ?? "
|
|
72
|
-
`-
|
|
73
|
-
`-
|
|
96
|
+
.at(-1) ?? "从未"}\``,
|
|
97
|
+
`- 近期失败:${lastFailure ? "有,查看 memory-review.jsonl" : "无"}`,
|
|
98
|
+
`- 生效文件:\`${getChannelMemoryPath(options.channelDir)}\``,
|
|
74
99
|
].join("\n");
|
|
75
100
|
}
|
|
76
101
|
if (action === "list") {
|
|
77
102
|
if (entries.length === 0)
|
|
78
|
-
return "
|
|
103
|
+
return "**记忆条目**\n\n暂无生效的频道记忆条目。";
|
|
79
104
|
const visible = entries.slice(0, 50);
|
|
80
105
|
const lines = visible.map((entry) => {
|
|
81
106
|
const record = metadata.entries[entry.id];
|
|
82
|
-
const probation = record?.probationUntil ?
|
|
107
|
+
const probation = record?.probationUntil ? `(观察期至 \`${record.probationUntil}\`)` : "";
|
|
83
108
|
return `- \`${entry.id}\` [${record?.kind ?? "fact"}]${probation} ${clipText(entry.content, 180, { headRatio: 1 })}`;
|
|
84
109
|
});
|
|
85
110
|
if (entries.length > visible.length) {
|
|
86
|
-
lines.push(`- ${entries.length - visible.length}
|
|
111
|
+
lines.push(`- 另有 ${entries.length - visible.length} 条已省略;缩小范围后用 \`/memory show <entry-id>\` 查看。`);
|
|
87
112
|
}
|
|
88
|
-
return
|
|
113
|
+
return capReply(`**记忆条目**\n\n${lines.join("\n")}`, {
|
|
114
|
+
nextStepHint: "用 `/memory show <entry-id>` 查看单条记忆",
|
|
115
|
+
}).text;
|
|
89
116
|
}
|
|
90
117
|
if (action === "show") {
|
|
91
118
|
if (!argument)
|
|
92
|
-
return
|
|
119
|
+
return `缺少 entry id。${renderUsage()}`;
|
|
93
120
|
const entry = entries.find((candidate) => candidate.id === argument);
|
|
94
121
|
const record = metadata.entries[argument];
|
|
95
122
|
if (!entry && !record)
|
|
96
|
-
return
|
|
123
|
+
return `未找到记忆条目 \`${argument}\`。用 \`/memory list\` 查看 id。`;
|
|
97
124
|
return [
|
|
98
|
-
|
|
125
|
+
`**记忆 ${argument}**`,
|
|
99
126
|
"",
|
|
100
|
-
entry?.content ?? "
|
|
127
|
+
entry?.content ?? "(未在 MEMORY.md 中生效)",
|
|
101
128
|
"",
|
|
102
129
|
"```json",
|
|
103
130
|
JSON.stringify(record ?? { id: argument, status: "unknown" }, null, 2),
|
|
104
131
|
"```",
|
|
105
132
|
].join("\n");
|
|
106
133
|
}
|
|
107
|
-
if (action === "
|
|
108
|
-
const
|
|
109
|
-
|
|
110
|
-
|
|
134
|
+
if (action === "recent") {
|
|
135
|
+
const last7d = new Date();
|
|
136
|
+
last7d.setDate(last7d.getDate() - 7);
|
|
137
|
+
const recent = (await readRecentMemoryActions(options.channelDir, last7d.getTime())).slice(-30).reverse();
|
|
138
|
+
if (recent.length === 0)
|
|
139
|
+
return "**近期记忆活动**\n\n最近 7 天没有记忆活动。";
|
|
111
140
|
return [
|
|
112
|
-
"
|
|
141
|
+
"**近期记忆活动**",
|
|
113
142
|
"",
|
|
114
|
-
...
|
|
143
|
+
...recent.map((item) => {
|
|
144
|
+
const when = item.timestamp ? `(${item.timestamp})` : "";
|
|
145
|
+
if (item.entryId)
|
|
146
|
+
return `- ${when}遗忘 \`${item.entryId}\`(${item.reason})`;
|
|
147
|
+
const detail = item.action === "append"
|
|
148
|
+
? `新增 ${item.entries ?? 0} 条`
|
|
149
|
+
: item.action === "rewrite"
|
|
150
|
+
? `重写${item.droppedEntryIds?.length ? `(丢弃 ${item.droppedEntryIds.join(", ")})` : ""}`
|
|
151
|
+
: item.action === "expire"
|
|
152
|
+
? `过期 ${item.entries ?? 0} 条`
|
|
153
|
+
: (item.action ?? "unknown");
|
|
154
|
+
return `- ${when}${item.target ?? "?"}:${detail}(${item.reason})`;
|
|
155
|
+
}),
|
|
115
156
|
].join("\n");
|
|
116
157
|
}
|
|
117
|
-
return
|
|
158
|
+
return `未知的 memory 命令 \`${action}\`。${renderUsage()}`;
|
|
118
159
|
}
|
|
@@ -46,5 +46,9 @@ export type MemoryCleanupShrinkGuard = Pick<PipiclawMemoryMaintenanceSettings, "
|
|
|
46
46
|
export declare class MemoryCleanupRejectedError extends Error {
|
|
47
47
|
constructor(reason: string);
|
|
48
48
|
}
|
|
49
|
-
export
|
|
49
|
+
export interface MemoryCleanupResult {
|
|
50
|
+
rewritten: boolean;
|
|
51
|
+
droppedEntryIds: string[];
|
|
52
|
+
}
|
|
53
|
+
export declare function cleanupChannelMemory(options: ConsolidationRunOptions, currentMemory: string, guard?: MemoryCleanupShrinkGuard): Promise<MemoryCleanupResult>;
|
|
50
54
|
export declare function foldChannelHistory(options: ConsolidationRunOptions, currentHistory: string): Promise<boolean>;
|
|
@@ -1,8 +1,10 @@
|
|
|
1
1
|
import { getLatestCompactionEntry } from "@earendil-works/pi-coding-agent";
|
|
2
2
|
import { formatLocalTime } from "../shared/local-time.js";
|
|
3
3
|
import { splitH2Sections } from "../shared/markdown-sections.js";
|
|
4
|
+
import { clipText } from "../shared/text-utils.js";
|
|
4
5
|
import { runMemoryExtraction, toMemoryOp } from "./extraction.js";
|
|
5
6
|
import { appendChannelHistoryArchive, appendChannelHistoryBlock, applyChannelMemoryOps, parseChannelMemoryEntries, rewriteChannelHistory, rewriteChannelMemory, } from "./files.js";
|
|
7
|
+
import { readMemoryMetadata } from "./metadata.js";
|
|
6
8
|
import { classifyMemoryWrite, DEFAULT_MEMORY_AUTO_WRITE_CONFIDENCE, MAX_PROBATION_WRITES_PER_RUN, } from "./promotion.js";
|
|
7
9
|
import { MEMORY_INPUT_SAFETY_RULES } from "./prompt-safety.js";
|
|
8
10
|
import { runSidecarTask } from "./sidecar-worker.js";
|
|
@@ -15,6 +17,7 @@ const HISTORY_BLOCK_THRESHOLD = 5;
|
|
|
15
17
|
const HISTORY_RECENT_BLOCKS_TO_KEEP = 3;
|
|
16
18
|
const INLINE_CONSOLIDATION_TIMEOUT_MS = 20_000;
|
|
17
19
|
const MEMORY_CLEANUP_TIMEOUT_MS = 120_000;
|
|
20
|
+
const MEMORY_CLEANUP_INPUT_MAX_CHARS = 24_000;
|
|
18
21
|
const HISTORY_FOLDING_TIMEOUT_MS = 120_000;
|
|
19
22
|
const MEMORY_CLEANUP_SYSTEM_PROMPT = `You are rewriting a Pipiclaw channel MEMORY.md file.
|
|
20
23
|
|
|
@@ -182,8 +185,7 @@ export async function runInlineConsolidation(options) {
|
|
|
182
185
|
const acceptedProbationary = probationaryCandidates.slice(0, MAX_PROBATION_WRITES_PER_RUN);
|
|
183
186
|
rejectedMemoryOps.push(...probationaryCandidates.slice(MAX_PROBATION_WRITES_PER_RUN));
|
|
184
187
|
let appliedMemoryOps = 0;
|
|
185
|
-
if (
|
|
186
|
-
!options.sourceWindow?.hasExternalToolContent) {
|
|
188
|
+
if (durableCandidates.length > 0 || acceptedProbationary.length > 0) {
|
|
187
189
|
const sourceEntryIds = options.sourceWindow?.entries.map((entry) => entry.id) ?? [];
|
|
188
190
|
const ops = [
|
|
189
191
|
...durableCandidates.map((candidate) => toMemoryOp(candidate, { sourceEntryIds, correlationId }, "durable")),
|
|
@@ -223,14 +225,17 @@ function isCleanupResultTooSmall(currentMemory, nextMemory, guard) {
|
|
|
223
225
|
const afterEntries = parseChannelMemoryEntries(after).length;
|
|
224
226
|
if (beforeEntries > 0 && afterEntries === 0)
|
|
225
227
|
return true;
|
|
228
|
+
// Entry-count guard applies at every file size. The char threshold below exists so a tiny
|
|
229
|
+
// file is not judged on byte ratio, but "four short Update blocks" is exactly the shape
|
|
230
|
+
// cleanup fires on and it sits under that threshold — letting the char escape short-circuit
|
|
231
|
+
// the entry guard left the most common cleanup input completely unprotected.
|
|
232
|
+
if (beforeEntries >= 4 && afterEntries * 2 < beforeEntries)
|
|
233
|
+
return true;
|
|
226
234
|
if (before.length < Math.max(0, guard.cleanupShrinkGuardMinChars))
|
|
227
235
|
return false;
|
|
228
|
-
|
|
229
|
-
return true;
|
|
230
|
-
}
|
|
231
|
-
return beforeEntries > 0 && afterEntries * 2 < beforeEntries;
|
|
236
|
+
return after.length < before.length * Math.max(0, Math.min(1, guard.cleanupShrinkGuardMinRatio));
|
|
232
237
|
}
|
|
233
|
-
function validateCleanupSchema(currentMemory, nextMemory) {
|
|
238
|
+
function validateCleanupSchema(currentMemory, nextMemory, mustKeepIds) {
|
|
234
239
|
if (!/^# Channel Memory(?:\s|$)/.test(nextMemory.trimStart())) {
|
|
235
240
|
return 'cleanup output must start with "# Channel Memory"';
|
|
236
241
|
}
|
|
@@ -244,24 +249,40 @@ function validateCleanupSchema(currentMemory, nextMemory) {
|
|
|
244
249
|
return `cleanup output duplicated entry id ${entry.id}`;
|
|
245
250
|
ids.add(entry.id);
|
|
246
251
|
}
|
|
252
|
+
const missing = mustKeepIds.filter((id) => !ids.has(id));
|
|
253
|
+
if (missing.length > 0)
|
|
254
|
+
return `cleanup output dropped user-saved entries: ${missing.join(", ")}`;
|
|
247
255
|
return null;
|
|
248
256
|
}
|
|
249
257
|
export async function cleanupChannelMemory(options, currentMemory, guard) {
|
|
250
258
|
if (!shouldCleanupChannelMemory(currentMemory)) {
|
|
251
|
-
return false;
|
|
259
|
+
return { rewritten: false, droppedEntryIds: [] };
|
|
252
260
|
}
|
|
253
|
-
const
|
|
254
|
-
|
|
261
|
+
const metadata = await readMemoryMetadata(options.channelDir);
|
|
262
|
+
const beforeEntries = parseChannelMemoryEntries(currentMemory);
|
|
263
|
+
const mustKeepIds = beforeEntries
|
|
264
|
+
.map((entry) => entry.id)
|
|
265
|
+
.filter((id) => metadata.entries[id]?.sourceType === "user");
|
|
266
|
+
const prompt = [
|
|
267
|
+
mustKeepIds.length > 0
|
|
268
|
+
? `These entries were saved on the user's explicit instruction and MUST appear verbatim in the output: ${mustKeepIds.join(", ")}`
|
|
269
|
+
: "",
|
|
270
|
+
`Current MEMORY.md:\n${clipText(currentMemory, MEMORY_CLEANUP_INPUT_MAX_CHARS, { headRatio: 0.5 })}`,
|
|
271
|
+
]
|
|
272
|
+
.filter(Boolean)
|
|
273
|
+
.join("\n\n");
|
|
255
274
|
const nextMemory = await runWorkerPrompt("memory-cleanup", options.model, options.resolveApiKey, MEMORY_CLEANUP_SYSTEM_PROMPT, prompt, MEMORY_CLEANUP_TIMEOUT_MS, usageContextFor(options.channelId, options.usageCorrelationId));
|
|
256
|
-
const schemaError = validateCleanupSchema(currentMemory, nextMemory);
|
|
275
|
+
const schemaError = validateCleanupSchema(currentMemory, nextMemory, mustKeepIds);
|
|
257
276
|
if (schemaError) {
|
|
258
277
|
throw new MemoryCleanupRejectedError(`${schemaError}. Retry cleanup while preserving the MEMORY.md schema and ids.`);
|
|
259
278
|
}
|
|
260
279
|
if (guard && isCleanupResultTooSmall(currentMemory, nextMemory, guard)) {
|
|
261
280
|
throw new MemoryCleanupRejectedError("cleanup result shrank below the configured guard threshold");
|
|
262
281
|
}
|
|
282
|
+
const afterIds = new Set(parseChannelMemoryEntries(nextMemory).map((entry) => entry.id));
|
|
283
|
+
const droppedEntryIds = beforeEntries.map((entry) => entry.id).filter((id) => !afterIds.has(id));
|
|
263
284
|
await rewriteChannelMemory(options.channelDir, nextMemory);
|
|
264
|
-
return true;
|
|
285
|
+
return { rewritten: true, droppedEntryIds };
|
|
265
286
|
}
|
|
266
287
|
export async function foldChannelHistory(options, currentHistory) {
|
|
267
288
|
if (!shouldFoldChannelHistory(currentHistory)) {
|
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
import type { AgentMessage } from "@earendil-works/pi-agent-core";
|
|
2
2
|
import type { Api, Model } from "@earendil-works/pi-ai";
|
|
3
3
|
import { type MemoryOp } from "./files.js";
|
|
4
|
-
import type
|
|
4
|
+
import { type MemoryEntryKind } from "./metadata.js";
|
|
5
5
|
import type { MemoryPromotionCandidate, MemoryWriteTier } from "./promotion.js";
|
|
6
6
|
export interface MemoryExtractionPromptOptions {
|
|
7
7
|
includeHistoryBlock: boolean;
|
|
@@ -44,4 +44,11 @@ export interface MemoryExtractionRequest extends MemoryExtractionPromptOptions {
|
|
|
44
44
|
correlationId?: string;
|
|
45
45
|
};
|
|
46
46
|
}
|
|
47
|
+
/**
|
|
48
|
+
* Tool output never reaches this prompt: `sanitizeMessagesForMemory` drops every `toolResult`
|
|
49
|
+
* message before serialization (`transcript.ts`), an invariant pinned by
|
|
50
|
+
* `test/memory-transcript.test.ts` ("drops tool results ... before memory workers see them").
|
|
51
|
+
* That is why no additional untrusted-content filter is applied here — a window-level one used to
|
|
52
|
+
* exist and silently discarded every durable write from any tool-using conversation.
|
|
53
|
+
*/
|
|
47
54
|
export declare function runMemoryExtraction(request: MemoryExtractionRequest): Promise<MemoryExtractionResult>;
|
|
@@ -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,6 +1,6 @@
|
|
|
1
1
|
import { createHash, randomBytes } from "crypto";
|
|
2
2
|
import { existsSync, mkdirSync, writeFileSync } from "fs";
|
|
3
|
-
import { copyFile, readdir, rm } from "fs/promises";
|
|
3
|
+
import { appendFile, copyFile, readdir, rename, rm, stat } from "fs/promises";
|
|
4
4
|
import { basename, join } from "path";
|
|
5
5
|
import { writeFileAtomically } from "../shared/atomic-file.js";
|
|
6
6
|
import { readOptionalTextFile } from "../shared/fs-utils.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() {
|
|
@@ -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" });
|
|
@@ -198,7 +198,15 @@ export async function runMemoryCheckpointJob(input) {
|
|
|
198
198
|
correlationId: sourceWindow.windowId,
|
|
199
199
|
}
|
|
200
200
|
: {
|
|
201
|
-
actions: [
|
|
201
|
+
actions: [
|
|
202
|
+
{
|
|
203
|
+
target: "MEMORY.md",
|
|
204
|
+
action: "append",
|
|
205
|
+
entries: result.appendedMemoryEntries,
|
|
206
|
+
durableCandidates: result.appendedDurableEntries,
|
|
207
|
+
probationaryCandidates: result.appendedProbationaryEntries,
|
|
208
|
+
},
|
|
209
|
+
],
|
|
202
210
|
skipped: (result.rejectedMemoryOps ?? []).map((candidate) => ({
|
|
203
211
|
target: "MEMORY.md",
|
|
204
212
|
candidate,
|
|
@@ -252,12 +260,12 @@ export async function runStructuralMaintenanceJob(input) {
|
|
|
252
260
|
// `loadFiles`'s cached read predates the expiry write above, so a fresh read is needed
|
|
253
261
|
// whenever expiry actually changed the file; otherwise the cache is still accurate.
|
|
254
262
|
const currentMemory = expiredCount > 0 ? await readChannelMemory(input.channelDir) : cachedMemory;
|
|
255
|
-
const
|
|
263
|
+
const cleanup = decision.runMemoryCleanup
|
|
256
264
|
? await cleanupChannelMemory(options, currentMemory, {
|
|
257
265
|
cleanupShrinkGuardMinRatio: input.settings.memoryMaintenance.cleanupShrinkGuardMinRatio,
|
|
258
266
|
cleanupShrinkGuardMinChars: input.settings.memoryMaintenance.cleanupShrinkGuardMinChars,
|
|
259
267
|
})
|
|
260
|
-
:
|
|
268
|
+
: null;
|
|
261
269
|
const foldedHistory = decision.runHistoryFolding ? await foldChannelHistory(options, currentHistory) : false;
|
|
262
270
|
await updateMemoryMaintenanceState(input.appHomeDir, input.channelId, (current) => ({
|
|
263
271
|
...current,
|
|
@@ -268,7 +276,9 @@ export async function runStructuralMaintenanceJob(input) {
|
|
|
268
276
|
correlationId,
|
|
269
277
|
actions: [
|
|
270
278
|
...(expiredCount > 0 ? [{ target: "MEMORY.md", action: "expire", entries: expiredCount }] : []),
|
|
271
|
-
...(
|
|
279
|
+
...(cleanup?.rewritten
|
|
280
|
+
? [{ target: "MEMORY.md", action: "rewrite", droppedEntryIds: cleanup.droppedEntryIds }]
|
|
281
|
+
: []),
|
|
272
282
|
...(foldedHistory ? [{ target: "HISTORY.md", action: "rewrite" }] : []),
|
|
273
283
|
],
|
|
274
284
|
}, now);
|
|
@@ -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,7 @@ 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[];
|
|
40
49
|
export declare function recallRelevantMemory(request: RecallRequest): Promise<RecallResult>;
|