@oyasmi/pipiclaw 0.9.2-beta.6 → 0.9.3-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/README.en.md +250 -0
- package/README.md +2 -0
- package/dist/agent/channel-runner.d.ts +43 -2
- package/dist/agent/channel-runner.js +135 -75
- package/dist/agent/job-manager.d.ts +76 -21
- package/dist/agent/job-manager.js +447 -63
- package/dist/agent/maintenance-context.js +4 -5
- package/dist/agent/prompt/manifest.d.ts +0 -2
- package/dist/agent/prompt/manifest.js +2 -3
- package/dist/agent/prompt/sections.js +3 -3
- package/dist/agent/session-events.js +4 -8
- package/dist/agent/turn-prompt.d.ts +7 -7
- package/dist/agent/turn-prompt.js +6 -9
- package/dist/agent/types.d.ts +12 -0
- package/dist/agent/types.js +1 -0
- package/dist/channel/channel-context.d.ts +13 -0
- package/dist/channel/channel-context.js +21 -1
- package/dist/commands/catalog.js +47 -20
- package/dist/memory/commands.d.ts +8 -0
- package/dist/memory/commands.js +113 -148
- package/dist/memory/index-budget.d.ts +27 -0
- package/dist/memory/index-budget.js +99 -0
- package/dist/memory/journal.d.ts +20 -0
- package/dist/memory/journal.js +78 -0
- package/dist/memory/lifecycle.d.ts +9 -15
- package/dist/memory/lifecycle.js +55 -145
- package/dist/memory/maintenance-gates.d.ts +13 -47
- package/dist/memory/maintenance-gates.js +13 -92
- package/dist/memory/maintenance-state.d.ts +10 -16
- package/dist/memory/maintenance-state.js +12 -59
- package/dist/memory/maintenance-tuning.d.ts +7 -27
- package/dist/memory/maintenance-tuning.js +11 -28
- package/dist/memory/migrate.d.ts +15 -0
- package/dist/memory/migrate.js +364 -0
- package/dist/memory/reflect-job.d.ts +43 -0
- package/dist/memory/reflect-job.js +117 -0
- package/dist/memory/reflect.d.ts +52 -0
- package/dist/memory/reflect.js +313 -0
- package/dist/memory/render.d.ts +14 -0
- package/dist/memory/render.js +28 -0
- package/dist/memory/review-log.d.ts +2 -1
- package/dist/memory/scheduler.d.ts +2 -3
- package/dist/memory/scheduler.js +14 -49
- package/dist/memory/search.d.ts +35 -0
- package/dist/memory/search.js +297 -0
- package/dist/memory/session-search.js +1 -1
- package/dist/memory/store.d.ts +108 -0
- package/dist/memory/store.js +418 -0
- package/dist/memory/task-digest.d.ts +2 -2
- package/dist/memory/task-digest.js +29 -36
- package/dist/memory/tombstones.d.ts +0 -11
- package/dist/memory/tombstones.js +6 -37
- package/dist/playbooks/agent-delegation.md +4 -2
- package/dist/playbooks/background-jobs.md +1 -1
- package/dist/playbooks/event-scheduling.md +6 -2
- package/dist/playbooks/memory-and-learning.md +18 -11
- package/dist/playbooks/outbound-media.md +1 -1
- package/dist/playbooks/runtime-orientation.md +9 -8
- package/dist/playbooks/task-loop.md +88 -0
- package/dist/runtime/bootstrap.d.ts +3 -3
- package/dist/runtime/bootstrap.js +66 -41
- package/dist/runtime/events.d.ts +9 -0
- package/dist/runtime/events.js +43 -4
- package/dist/runtime/task-commands.d.ts +14 -15
- package/dist/runtime/task-commands.js +249 -485
- package/dist/runtime/task-driver.d.ts +41 -29
- package/dist/runtime/task-driver.js +170 -317
- package/dist/runtime/task-migration.d.ts +34 -30
- package/dist/runtime/task-migration.js +229 -183
- package/dist/runtime/task-wake.d.ts +6 -3
- package/dist/runtime/task-wake.js +26 -19
- package/dist/settings.d.ts +0 -29
- package/dist/settings.js +12 -35
- package/dist/shared/markdown-sections.d.ts +0 -1
- package/dist/shared/markdown-sections.js +0 -3
- package/dist/subagents/discovery.d.ts +2 -2
- package/dist/subagents/discovery.js +21 -10
- package/dist/subagents/external/progress-tail.js +6 -1
- package/dist/subagents/external/run.js +1 -0
- package/dist/subagents/runs.d.ts +19 -2
- package/dist/subagents/runs.js +73 -4
- package/dist/subagents/tool.d.ts +10 -8
- package/dist/subagents/tool.js +55 -94
- package/dist/tasks/brief.d.ts +17 -0
- package/dist/tasks/brief.js +57 -0
- package/dist/tasks/budget.d.ts +26 -0
- package/dist/tasks/budget.js +59 -0
- package/dist/tasks/cycle.d.ts +48 -0
- package/dist/tasks/cycle.js +94 -0
- package/dist/tasks/frontmatter.d.ts +73 -0
- package/dist/tasks/frontmatter.js +175 -0
- package/dist/tasks/ledger.d.ts +66 -106
- package/dist/tasks/ledger.js +90 -546
- package/dist/tasks/log.d.ts +88 -0
- package/dist/tasks/log.js +97 -0
- package/dist/tasks/rounds.d.ts +43 -0
- package/dist/tasks/rounds.js +57 -0
- package/dist/tasks/session-path.d.ts +9 -0
- package/dist/tasks/session-path.js +16 -0
- package/dist/tasks/steer.d.ts +8 -0
- package/dist/tasks/steer.js +79 -0
- package/dist/tasks/store.d.ts +60 -35
- package/dist/tasks/store.js +166 -107
- package/dist/tasks/ticket.d.ts +102 -0
- package/dist/tasks/ticket.js +209 -0
- package/dist/tasks/verification.d.ts +16 -0
- package/dist/tasks/verification.js +40 -1
- package/dist/tools/index.d.ts +13 -4
- package/dist/tools/index.js +5 -10
- package/dist/tools/memory-manage.d.ts +6 -16
- package/dist/tools/memory-manage.js +108 -129
- package/dist/tools/presentation.js +2 -1
- package/dist/tools/registry.d.ts +11 -2
- package/dist/tools/registry.js +17 -6
- package/dist/tools/subagent-manage.d.ts +0 -9
- package/dist/tools/subagent-manage.js +8 -17
- package/dist/tools/task-manage/create.js +2 -2
- package/dist/tools/task-manage/lifecycle.d.ts +9 -4
- package/dist/tools/task-manage/lifecycle.js +139 -187
- package/dist/tools/task-manage/log-view.d.ts +8 -0
- package/dist/tools/task-manage/log-view.js +24 -0
- package/dist/tools/task-manage/schema.d.ts +38 -14
- package/dist/tools/task-manage/schema.js +46 -27
- package/dist/tools/task-manage/shared.d.ts +24 -31
- package/dist/tools/task-manage/shared.js +103 -141
- package/dist/tools/task-manage/step-end.d.ts +11 -0
- package/dist/tools/task-manage/step-end.js +136 -0
- package/dist/tools/task-manage/types.d.ts +23 -32
- package/dist/tools/task-manage.d.ts +4 -3
- package/dist/tools/task-manage.js +30 -15
- package/dist/tools/tool-details.d.ts +1 -1
- package/dist/tui/app.js +0 -2
- package/package.json +1 -1
- package/dist/agent/effect-ledger.d.ts +0 -32
- package/dist/agent/effect-ledger.js +0 -89
- package/dist/memory/bootstrap.d.ts +0 -17
- package/dist/memory/bootstrap.js +0 -120
- package/dist/memory/candidates.d.ts +0 -26
- package/dist/memory/candidates.js +0 -202
- package/dist/memory/consolidation.d.ts +0 -54
- package/dist/memory/consolidation.js +0 -292
- package/dist/memory/extraction.d.ts +0 -54
- package/dist/memory/extraction.js +0 -240
- package/dist/memory/files.d.ts +0 -71
- package/dist/memory/files.js +0 -419
- package/dist/memory/maintenance-jobs.d.ts +0 -41
- package/dist/memory/maintenance-jobs.js +0 -265
- package/dist/memory/metadata.d.ts +0 -57
- package/dist/memory/metadata.js +0 -142
- package/dist/memory/probation.d.ts +0 -17
- package/dist/memory/probation.js +0 -44
- package/dist/memory/promotion.d.ts +0 -38
- package/dist/memory/promotion.js +0 -36
- package/dist/memory/recall.d.ts +0 -59
- package/dist/memory/recall.js +0 -746
- package/dist/memory/session.d.ts +0 -24
- package/dist/memory/session.js +0 -273
- package/dist/playbooks/task-driving.md +0 -92
- package/dist/playbooks/task-planning.md +0 -58
- package/dist/tasks/control.d.ts +0 -56
- package/dist/tasks/control.js +0 -169
- package/dist/tasks/transitions.d.ts +0 -16
- package/dist/tasks/transitions.js +0 -48
- package/dist/tools/task-manage/verification.d.ts +0 -19
- package/dist/tools/task-manage/verification.js +0 -91
package/dist/memory/commands.js
CHANGED
|
@@ -1,159 +1,124 @@
|
|
|
1
1
|
import { renderSubcommandUsage } from "../commands/catalog.js";
|
|
2
2
|
import { capReply } from "../commands/reply-limits.js";
|
|
3
|
-
import {
|
|
4
|
-
import {
|
|
5
|
-
import {
|
|
6
|
-
import {
|
|
7
|
-
import {
|
|
8
|
-
import {
|
|
9
|
-
import {
|
|
10
|
-
|
|
11
|
-
const entries = parseChannelMemoryEntries(await readChannelMemory(options.channelDir));
|
|
12
|
-
const metadata = await syncMemoryMetadata(options.channelDir, entries);
|
|
13
|
-
return { entries, metadata };
|
|
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) {
|
|
21
|
-
const raw = await readOptionalTextFile(getMemoryReviewLogPath(channelDir));
|
|
22
|
-
const actions = [];
|
|
23
|
-
for (const line of raw.split("\n")) {
|
|
24
|
-
if (!line.trim())
|
|
25
|
-
continue;
|
|
26
|
-
try {
|
|
27
|
-
const entry = JSON.parse(line);
|
|
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
|
-
}
|
|
35
|
-
}
|
|
36
|
-
}
|
|
37
|
-
catch {
|
|
38
|
-
// A torn audit line should not break the management surface.
|
|
39
|
-
}
|
|
40
|
-
}
|
|
41
|
-
return actions;
|
|
42
|
-
}
|
|
3
|
+
import { localDayKey } from "../shared/local-time.js";
|
|
4
|
+
import { getDefaultChannelMemoryQueue } from "./channel-maintenance-queue.js";
|
|
5
|
+
import { buildChannelIndexForBootstrap, CHANNEL_INDEX_MAX_UNITS } from "./index-budget.js";
|
|
6
|
+
import { listJournalDates, readJournalDay } from "./journal.js";
|
|
7
|
+
import { readMemoryMaintenanceState } from "./maintenance-state.js";
|
|
8
|
+
import { appendMemoryReviewLog } from "./review-log.js";
|
|
9
|
+
import { applyMemoryOps, listMemoryEntries, MEMORY_TYPE_ORDER, readMemoryEntry, } from "./store.js";
|
|
10
|
+
import { hashMemoryContent } from "./tombstones.js";
|
|
43
11
|
function renderUsage() {
|
|
44
12
|
return renderSubcommandUsage("memory");
|
|
45
13
|
}
|
|
46
|
-
|
|
47
|
-
|
|
48
|
-
|
|
49
|
-
|
|
50
|
-
|
|
51
|
-
|
|
52
|
-
|
|
53
|
-
|
|
54
|
-
|
|
55
|
-
|
|
56
|
-
|
|
57
|
-
|
|
58
|
-
|
|
59
|
-
|
|
60
|
-
|
|
61
|
-
|
|
62
|
-
|
|
63
|
-
|
|
64
|
-
|
|
65
|
-
|
|
66
|
-
|
|
67
|
-
|
|
68
|
-
|
|
69
|
-
|
|
70
|
-
|
|
71
|
-
|
|
72
|
-
|
|
73
|
-
|
|
74
|
-
|
|
75
|
-
|
|
76
|
-
.reduce((sum, item) => sum + (item.entries ?? 0), 0);
|
|
77
|
-
const lastFailure = (await readOptionalTextFile(getMemoryReviewLogPath(options.channelDir)))
|
|
78
|
-
.split("\n")
|
|
79
|
-
.reverse()
|
|
80
|
-
.find((line) => line.includes('"error"'));
|
|
81
|
-
return [
|
|
82
|
-
"**记忆状态**",
|
|
83
|
-
"",
|
|
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
|
|
93
|
-
.map((entry) => entry.lastRecalledAt)
|
|
94
|
-
.filter(Boolean)
|
|
95
|
-
.sort()
|
|
96
|
-
.at(-1) ?? "从未"}\``,
|
|
97
|
-
`- 近期失败:${lastFailure ? "有,查看 memory-review.jsonl" : "无"}`,
|
|
98
|
-
`- 生效文件:\`${getChannelMemoryPath(options.channelDir)}\``,
|
|
99
|
-
].join("\n");
|
|
14
|
+
function isMemoryType(value) {
|
|
15
|
+
return value !== undefined && MEMORY_TYPE_ORDER.includes(value);
|
|
16
|
+
}
|
|
17
|
+
async function handleStatus(options) {
|
|
18
|
+
const entries = await listMemoryEntries(options.channelDir);
|
|
19
|
+
const byType = new Map(MEMORY_TYPE_ORDER.map((type) => [type, 0]));
|
|
20
|
+
for (const entry of entries) {
|
|
21
|
+
byType.set(entry.type, (byType.get(entry.type) ?? 0) + 1);
|
|
22
|
+
}
|
|
23
|
+
const probationary = entries
|
|
24
|
+
.filter((entry) => Boolean(entry.expires))
|
|
25
|
+
.sort((a, b) => a.expires.localeCompare(b.expires));
|
|
26
|
+
const malformed = entries.filter((entry) => entry.malformed);
|
|
27
|
+
const tiered = buildChannelIndexForBootstrap(entries, CHANNEL_INDEX_MAX_UNITS);
|
|
28
|
+
const state = options.appHomeDir
|
|
29
|
+
? await readMemoryMaintenanceState(options.appHomeDir, options.channelId)
|
|
30
|
+
: undefined;
|
|
31
|
+
return [
|
|
32
|
+
"**记忆状态**",
|
|
33
|
+
"",
|
|
34
|
+
`- 频道条目:\`${entries.length}\`(${MEMORY_TYPE_ORDER.map((type) => `${type} ${byType.get(type) ?? 0}`).join(" / ")})`,
|
|
35
|
+
`- 试用期条目:\`${probationary.length}\`${probationary.length > 0 ? `(最早到期 \`${probationary[0].expires}\`)` : ""}`,
|
|
36
|
+
`- frontmatter 解析异常的文件:\`${malformed.length}\`${malformed.length > 0 ? `(${malformed.map((e) => e.name).join(", ")})` : ""}`,
|
|
37
|
+
`- 上次反思:\`${state?.lastReflectAt ?? "从未"}\`${state?.lastReflectedEntryId ? `(游标 \`${state.lastReflectedEntryId}\`)` : ""}`,
|
|
38
|
+
`- 索引预算:${tiered.overBudget ? `超出,注入时按 updated 降序分层;下次反思会尝试合并` : "未超出,整份注入"}`,
|
|
39
|
+
].join("\n");
|
|
40
|
+
}
|
|
41
|
+
async function handleList(options, typeArg) {
|
|
42
|
+
if (typeArg && !isMemoryType(typeArg)) {
|
|
43
|
+
return `未知的记忆类型 \`${typeArg}\`。可用类型:${MEMORY_TYPE_ORDER.join(", ")}。`;
|
|
100
44
|
}
|
|
101
|
-
|
|
102
|
-
|
|
103
|
-
|
|
104
|
-
|
|
105
|
-
const lines = visible.map((entry) => {
|
|
106
|
-
const record = metadata.entries[entry.id];
|
|
107
|
-
const probation = record?.probationUntil ? `(观察期至 \`${record.probationUntil}\`)` : "";
|
|
108
|
-
return `- \`${entry.id}\` [${record?.kind ?? "fact"}]${probation} ${clipText(entry.content, 180, { headRatio: 1 })}`;
|
|
109
|
-
});
|
|
110
|
-
if (entries.length > visible.length) {
|
|
111
|
-
lines.push(`- 另有 ${entries.length - visible.length} 条已省略;缩小范围后用 \`/memory show <entry-id>\` 查看。`);
|
|
112
|
-
}
|
|
113
|
-
return capReply(`**记忆条目**\n\n${lines.join("\n")}`, {
|
|
114
|
-
nextStepHint: "用 `/memory show <entry-id>` 查看单条记忆",
|
|
115
|
-
}).text;
|
|
45
|
+
const entries = await listMemoryEntries(options.channelDir);
|
|
46
|
+
const filtered = typeArg ? entries.filter((entry) => entry.type === typeArg) : entries;
|
|
47
|
+
if (filtered.length === 0) {
|
|
48
|
+
return typeArg ? `**记忆条目(${typeArg})**\n\n暂无该类型的记忆。` : "**记忆条目**\n\n暂无生效的频道记忆。";
|
|
116
49
|
}
|
|
117
|
-
|
|
118
|
-
|
|
119
|
-
|
|
120
|
-
|
|
121
|
-
|
|
122
|
-
|
|
123
|
-
|
|
124
|
-
|
|
125
|
-
|
|
126
|
-
|
|
127
|
-
|
|
128
|
-
|
|
129
|
-
|
|
130
|
-
|
|
131
|
-
|
|
132
|
-
|
|
50
|
+
const lines = filtered.map((entry) => {
|
|
51
|
+
const marker = entry.body.trim() ? " (+)" : "";
|
|
52
|
+
const probation = entry.expires ? `(观察期至 \`${entry.expires}\`)` : "";
|
|
53
|
+
return `- \`${entry.name}\` [${entry.type}]${probation} ${entry.description}${marker}`;
|
|
54
|
+
});
|
|
55
|
+
return capReply(`**记忆条目${typeArg ? `(${typeArg})` : ""}**\n\n${lines.join("\n")}`, {
|
|
56
|
+
nextStepHint: "用 `/memory show <name>` 查看单条记忆全文",
|
|
57
|
+
}).text;
|
|
58
|
+
}
|
|
59
|
+
async function handleShow(options, name) {
|
|
60
|
+
if (!name)
|
|
61
|
+
return `缺少记忆名称。${renderUsage()}`;
|
|
62
|
+
const entry = await readMemoryEntry(options.channelDir, name);
|
|
63
|
+
if (!entry)
|
|
64
|
+
return `未找到记忆 \`${name}\`。用 \`/memory list\` 查看可用名称。`;
|
|
65
|
+
const lines = [
|
|
66
|
+
`**记忆 ${name}**`,
|
|
67
|
+
"",
|
|
68
|
+
`- type: \`${entry.type}\``,
|
|
69
|
+
`- source: \`${entry.source}\``,
|
|
70
|
+
`- created: \`${entry.created}\` / updated: \`${entry.updated}\``,
|
|
71
|
+
];
|
|
72
|
+
if (entry.expires)
|
|
73
|
+
lines.push(`- expires: \`${entry.expires}\``);
|
|
74
|
+
if (entry.malformed)
|
|
75
|
+
lines.push("- ⚠️ frontmatter 解析异常,以第一段作为 description");
|
|
76
|
+
lines.push("", entry.description);
|
|
77
|
+
if (entry.body.trim())
|
|
78
|
+
lines.push("", entry.body.trim());
|
|
79
|
+
return lines.join("\n");
|
|
80
|
+
}
|
|
81
|
+
async function handleForget(options, name) {
|
|
82
|
+
if (!name)
|
|
83
|
+
return `缺少记忆名称。${renderUsage()}`;
|
|
84
|
+
const entry = await readMemoryEntry(options.channelDir, name);
|
|
85
|
+
if (!entry)
|
|
86
|
+
return `未找到记忆 \`${name}\`;未做任何改动。`;
|
|
87
|
+
await getDefaultChannelMemoryQueue().run(options.channelId, () => applyMemoryOps(options.channelDir, [{ op: "delete", name, reason: "/memory forget" }]));
|
|
88
|
+
await appendMemoryReviewLog(options.channelDir, {
|
|
89
|
+
timestamp: new Date().toISOString(),
|
|
90
|
+
channelId: options.channelId,
|
|
91
|
+
reason: "memory-forget",
|
|
92
|
+
actions: [{ op: "forget", name, contentHash: hashMemoryContent(entry.description) }],
|
|
93
|
+
}).catch(() => { });
|
|
94
|
+
return `已删除 \`${name}\`。内容按哈希墓碑化,避免被反思重新写入;重新说出该事实仍可被学到。`;
|
|
95
|
+
}
|
|
96
|
+
async function handleJournal(options, dateArg) {
|
|
97
|
+
const date = dateArg ?? localDayKey();
|
|
98
|
+
if (!/^\d{4}-\d{2}-\d{2}$/.test(date)) {
|
|
99
|
+
return `日期格式应为 \`YYYY-MM-DD\`。${renderUsage()}`;
|
|
133
100
|
}
|
|
134
|
-
|
|
135
|
-
|
|
136
|
-
|
|
137
|
-
const
|
|
138
|
-
|
|
139
|
-
return "**近期记忆活动**\n\n最近 7 天没有记忆活动。";
|
|
140
|
-
return [
|
|
141
|
-
"**近期记忆活动**",
|
|
142
|
-
"",
|
|
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
|
-
}),
|
|
156
|
-
].join("\n");
|
|
101
|
+
const content = await readJournalDay(options.channelDir, date);
|
|
102
|
+
if (!content.trim()) {
|
|
103
|
+
const dates = await listJournalDates(options.channelDir);
|
|
104
|
+
const hint = dates.length > 0 ? `\n\n有记录的日期:${dates.slice(-10).join(", ")}` : "";
|
|
105
|
+
return `**日志 ${date}**\n\n当天没有记录。${hint}`;
|
|
157
106
|
}
|
|
107
|
+
return capReply(`**日志 ${date}**\n\n${content.trim()}`, {
|
|
108
|
+
nextStepHint: "用 `/memory journal <YYYY-MM-DD>` 查看其他日期",
|
|
109
|
+
}).text;
|
|
110
|
+
}
|
|
111
|
+
export async function handleMemoryCommand(options) {
|
|
112
|
+
const [action = "status", argument] = options.args.trim().split(/\s+/, 2);
|
|
113
|
+
if (action === "status")
|
|
114
|
+
return handleStatus(options);
|
|
115
|
+
if (action === "list")
|
|
116
|
+
return handleList(options, argument);
|
|
117
|
+
if (action === "show")
|
|
118
|
+
return handleShow(options, argument);
|
|
119
|
+
if (action === "forget")
|
|
120
|
+
return handleForget(options, argument);
|
|
121
|
+
if (action === "journal")
|
|
122
|
+
return handleJournal(options, argument);
|
|
158
123
|
return `未知的 memory 命令 \`${action}\`。${renderUsage()}`;
|
|
159
124
|
}
|
|
@@ -0,0 +1,27 @@
|
|
|
1
|
+
import { type MemoryEntry } from "./store.js";
|
|
2
|
+
/**
|
|
3
|
+
* Spec 050, D1/D4/D11: what actually goes into `<memory_bootstrap>` on the first turn, and the
|
|
4
|
+
* budget tiering when the channel index does not fit.
|
|
5
|
+
*
|
|
6
|
+
* Budgets are code constants, reallocated inside spec 026 §5.3's automatic-context share.
|
|
7
|
+
*/
|
|
8
|
+
export declare const WORKSPACE_MEMORY_MAX_UNITS = 500;
|
|
9
|
+
export declare const CHANNEL_INDEX_MAX_UNITS = 1400;
|
|
10
|
+
export declare const JOURNAL_TAIL_MAX_UNITS = 400;
|
|
11
|
+
export interface TieredIndexResult {
|
|
12
|
+
text: string;
|
|
13
|
+
includedNames: string[];
|
|
14
|
+
omittedCount: number;
|
|
15
|
+
/** The full index did not fit; the reflect pass should run in `condense` mode. */
|
|
16
|
+
overBudget: boolean;
|
|
17
|
+
}
|
|
18
|
+
/**
|
|
19
|
+
* D4: full index if it fits; otherwise `user` + `feedback` entries in full, then
|
|
20
|
+
* `project` / `reference` by `updated` descending until the budget is spent, with a
|
|
21
|
+
* trailing pointer to `memory_search`.
|
|
22
|
+
*/
|
|
23
|
+
export declare function buildChannelIndexForBootstrap(entries: MemoryEntry[], maxUnits?: number): TieredIndexResult;
|
|
24
|
+
/** D11: workspace MEMORY.md, whole H2 sections from the top until the budget is spent. */
|
|
25
|
+
export declare function clipWorkspaceMemoryForBootstrap(workspaceMemory: string, maxUnits?: number): string;
|
|
26
|
+
/** Tail of a journal day, clipped to the injection budget (head dropped, newest kept). */
|
|
27
|
+
export declare function clipJournalTailForBootstrap(journalText: string, maxUnits?: number): string;
|
|
@@ -0,0 +1,99 @@
|
|
|
1
|
+
import { splitH2Sections } from "../shared/markdown-sections.js";
|
|
2
|
+
import { clipTextByPromptUnits, countPromptUnits } from "../shared/prompt-units.js";
|
|
3
|
+
import { stripCrAndTrim } from "../shared/text-utils.js";
|
|
4
|
+
import { renderMemoryIndex } from "./store.js";
|
|
5
|
+
/**
|
|
6
|
+
* Spec 050, D1/D4/D11: what actually goes into `<memory_bootstrap>` on the first turn, and the
|
|
7
|
+
* budget tiering when the channel index does not fit.
|
|
8
|
+
*
|
|
9
|
+
* Budgets are code constants, reallocated inside spec 026 §5.3's automatic-context share.
|
|
10
|
+
*/
|
|
11
|
+
export const WORKSPACE_MEMORY_MAX_UNITS = 500;
|
|
12
|
+
export const CHANNEL_INDEX_MAX_UNITS = 1_400;
|
|
13
|
+
export const JOURNAL_TAIL_MAX_UNITS = 400;
|
|
14
|
+
const WORKSPACE_MEMORY_MAX_CHARS = 4_000;
|
|
15
|
+
const JOURNAL_TAIL_MAX_CHARS = 3_000;
|
|
16
|
+
const ALWAYS_INCLUDED = new Set(["user", "feedback"]);
|
|
17
|
+
/**
|
|
18
|
+
* D4: full index if it fits; otherwise `user` + `feedback` entries in full, then
|
|
19
|
+
* `project` / `reference` by `updated` descending until the budget is spent, with a
|
|
20
|
+
* trailing pointer to `memory_search`.
|
|
21
|
+
*/
|
|
22
|
+
export function buildChannelIndexForBootstrap(entries, maxUnits = CHANNEL_INDEX_MAX_UNITS) {
|
|
23
|
+
const full = renderMemoryIndex(entries);
|
|
24
|
+
if (entries.length === 0 || countPromptUnits(full) <= maxUnits) {
|
|
25
|
+
return { text: full, includedNames: entries.map((e) => e.name), omittedCount: 0, overBudget: false };
|
|
26
|
+
}
|
|
27
|
+
const pinned = entries.filter((e) => ALWAYS_INCLUDED.has(e.type));
|
|
28
|
+
const droppable = entries
|
|
29
|
+
.filter((e) => !ALWAYS_INCLUDED.has(e.type))
|
|
30
|
+
.sort((a, b) => b.updated.localeCompare(a.updated) || a.name.localeCompare(b.name));
|
|
31
|
+
let kept = droppable.length;
|
|
32
|
+
let rendered = "";
|
|
33
|
+
while (true) {
|
|
34
|
+
const included = [...pinned, ...droppable.slice(0, kept)];
|
|
35
|
+
const omitted = entries.length - included.length;
|
|
36
|
+
rendered = renderMemoryIndex(included) + (omitted > 0 ? omittedLine(omitted) : "");
|
|
37
|
+
if (kept === 0 || countPromptUnits(rendered) <= maxUnits) {
|
|
38
|
+
return {
|
|
39
|
+
text: rendered,
|
|
40
|
+
includedNames: included.map((e) => e.name),
|
|
41
|
+
omittedCount: omitted,
|
|
42
|
+
overBudget: true,
|
|
43
|
+
};
|
|
44
|
+
}
|
|
45
|
+
kept--;
|
|
46
|
+
}
|
|
47
|
+
}
|
|
48
|
+
function omittedLine(count) {
|
|
49
|
+
return `\n[- ${count} more ${count === 1 ? "entry" : "entries"} omitted; use memory_search]\n`;
|
|
50
|
+
}
|
|
51
|
+
/** D11: workspace MEMORY.md, whole H2 sections from the top until the budget is spent. */
|
|
52
|
+
export function clipWorkspaceMemoryForBootstrap(workspaceMemory, maxUnits = WORKSPACE_MEMORY_MAX_UNITS) {
|
|
53
|
+
const text = stripCrAndTrim(workspaceMemory);
|
|
54
|
+
if (!text) {
|
|
55
|
+
return "";
|
|
56
|
+
}
|
|
57
|
+
if (countPromptUnits(text) <= maxUnits && text.length <= WORKSPACE_MEMORY_MAX_CHARS) {
|
|
58
|
+
return text;
|
|
59
|
+
}
|
|
60
|
+
const sections = splitH2Sections(text);
|
|
61
|
+
if (sections.length === 0) {
|
|
62
|
+
return clipTextByPromptUnits(text, maxUnits, {
|
|
63
|
+
headRatio: 1,
|
|
64
|
+
maxChars: WORKSPACE_MEMORY_MAX_CHARS,
|
|
65
|
+
marker: "\n\n[... omitted for length ...]\n",
|
|
66
|
+
}).text;
|
|
67
|
+
}
|
|
68
|
+
const head = text.slice(0, text.indexOf("## ") === -1 ? 0 : text.indexOf("## ")).trim();
|
|
69
|
+
const kept = head ? [head] : [];
|
|
70
|
+
let used = countPromptUnits(kept.join("\n\n"));
|
|
71
|
+
let omitted = 0;
|
|
72
|
+
for (const section of sections) {
|
|
73
|
+
const block = `## ${section.heading}\n\n${section.content}`;
|
|
74
|
+
const cost = countPromptUnits(block);
|
|
75
|
+
if (used + cost <= maxUnits && kept.join("\n\n").length + block.length <= WORKSPACE_MEMORY_MAX_CHARS) {
|
|
76
|
+
kept.push(block);
|
|
77
|
+
used += cost;
|
|
78
|
+
}
|
|
79
|
+
else {
|
|
80
|
+
omitted++;
|
|
81
|
+
}
|
|
82
|
+
}
|
|
83
|
+
if (omitted > 0) {
|
|
84
|
+
kept.push(`[... ${omitted} more section(s) omitted; read workspace/MEMORY.md ...]`);
|
|
85
|
+
}
|
|
86
|
+
return kept.join("\n\n");
|
|
87
|
+
}
|
|
88
|
+
/** Tail of a journal day, clipped to the injection budget (head dropped, newest kept). */
|
|
89
|
+
export function clipJournalTailForBootstrap(journalText, maxUnits = JOURNAL_TAIL_MAX_UNITS) {
|
|
90
|
+
const text = stripCrAndTrim(journalText);
|
|
91
|
+
if (!text) {
|
|
92
|
+
return "";
|
|
93
|
+
}
|
|
94
|
+
return clipTextByPromptUnits(text, maxUnits, {
|
|
95
|
+
headRatio: 0,
|
|
96
|
+
maxChars: JOURNAL_TAIL_MAX_CHARS,
|
|
97
|
+
marker: "[... earlier entries omitted ...]\n",
|
|
98
|
+
}).text;
|
|
99
|
+
}
|
|
@@ -0,0 +1,20 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Spec 050, D5: `journal/YYYY-MM-DD.md`, append-only, one file per local day. Replaces
|
|
3
|
+
* `SESSION.md` (current state) and `HISTORY.md` (folded older history) — a day is never
|
|
4
|
+
* folded or rewritten, only appended to, so it stays a plain, growing record.
|
|
5
|
+
*/
|
|
6
|
+
export declare function getJournalDir(channelDir: string): string;
|
|
7
|
+
export declare function getJournalPath(channelDir: string, date: string): string;
|
|
8
|
+
export declare function readJournalDay(channelDir: string, date?: string): Promise<string>;
|
|
9
|
+
export declare function listJournalDates(channelDir: string): Promise<string[]>;
|
|
10
|
+
export interface JournalAppendResult {
|
|
11
|
+
appended: number;
|
|
12
|
+
skippedDuplicate: number;
|
|
13
|
+
}
|
|
14
|
+
/**
|
|
15
|
+
* Append `lines` (bare text, no `- ` prefix) to today's journal, skipping any line whose
|
|
16
|
+
* normalized text (time prefix stripped) already appears in the day — the reflect pass can see
|
|
17
|
+
* the day it is about to write to, but a deterministic backstop costs nothing and protects a
|
|
18
|
+
* hand-edited file too.
|
|
19
|
+
*/
|
|
20
|
+
export declare function appendJournalEntries(channelDir: string, date: string, lines: string[]): Promise<JournalAppendResult>;
|
|
@@ -0,0 +1,78 @@
|
|
|
1
|
+
import { mkdir, readdir } from "node:fs/promises";
|
|
2
|
+
import { join } from "node:path";
|
|
3
|
+
import { writeFileAtomically } from "../shared/atomic-file.js";
|
|
4
|
+
import { readOptionalTextFile } from "../shared/fs-utils.js";
|
|
5
|
+
import { localDayKey } from "../shared/local-time.js";
|
|
6
|
+
/**
|
|
7
|
+
* Spec 050, D5: `journal/YYYY-MM-DD.md`, append-only, one file per local day. Replaces
|
|
8
|
+
* `SESSION.md` (current state) and `HISTORY.md` (folded older history) — a day is never
|
|
9
|
+
* folded or rewritten, only appended to, so it stays a plain, growing record.
|
|
10
|
+
*/
|
|
11
|
+
export function getJournalDir(channelDir) {
|
|
12
|
+
return join(channelDir, "journal");
|
|
13
|
+
}
|
|
14
|
+
export function getJournalPath(channelDir, date) {
|
|
15
|
+
return join(getJournalDir(channelDir), `${date}.md`);
|
|
16
|
+
}
|
|
17
|
+
export async function readJournalDay(channelDir, date = localDayKey()) {
|
|
18
|
+
return readOptionalTextFile(getJournalPath(channelDir, date));
|
|
19
|
+
}
|
|
20
|
+
export async function listJournalDates(channelDir) {
|
|
21
|
+
try {
|
|
22
|
+
const files = await readdir(getJournalDir(channelDir));
|
|
23
|
+
return files
|
|
24
|
+
.filter((f) => /^\d{4}-\d{2}-\d{2}\.md$/.test(f))
|
|
25
|
+
.map((f) => f.slice(0, -3))
|
|
26
|
+
.sort();
|
|
27
|
+
}
|
|
28
|
+
catch {
|
|
29
|
+
return [];
|
|
30
|
+
}
|
|
31
|
+
}
|
|
32
|
+
function normalizeLine(line) {
|
|
33
|
+
return line
|
|
34
|
+
.replace(/^[-*]\s*/, "")
|
|
35
|
+
.replace(/^\d{2}:\d{2}\s+/, "")
|
|
36
|
+
.normalize("NFKC")
|
|
37
|
+
.replace(/\s+/g, " ")
|
|
38
|
+
.trim()
|
|
39
|
+
.toLowerCase();
|
|
40
|
+
}
|
|
41
|
+
/**
|
|
42
|
+
* Append `lines` (bare text, no `- ` prefix) to today's journal, skipping any line whose
|
|
43
|
+
* normalized text (time prefix stripped) already appears in the day — the reflect pass can see
|
|
44
|
+
* the day it is about to write to, but a deterministic backstop costs nothing and protects a
|
|
45
|
+
* hand-edited file too.
|
|
46
|
+
*/
|
|
47
|
+
export async function appendJournalEntries(channelDir, date, lines) {
|
|
48
|
+
const trimmedLines = lines.map((line) => line.trim()).filter(Boolean);
|
|
49
|
+
if (trimmedLines.length === 0) {
|
|
50
|
+
return { appended: 0, skippedDuplicate: 0 };
|
|
51
|
+
}
|
|
52
|
+
await mkdir(getJournalDir(channelDir), { recursive: true });
|
|
53
|
+
const path = getJournalPath(channelDir, date);
|
|
54
|
+
const existing = await readOptionalTextFile(path);
|
|
55
|
+
const existingNormalized = new Set(existing
|
|
56
|
+
.split("\n")
|
|
57
|
+
.filter((line) => line.trim().startsWith("-"))
|
|
58
|
+
.map(normalizeLine));
|
|
59
|
+
const toAppend = [];
|
|
60
|
+
let skippedDuplicate = 0;
|
|
61
|
+
for (const line of trimmedLines) {
|
|
62
|
+
const key = normalizeLine(line);
|
|
63
|
+
if (existingNormalized.has(key)) {
|
|
64
|
+
skippedDuplicate++;
|
|
65
|
+
continue;
|
|
66
|
+
}
|
|
67
|
+
existingNormalized.add(key);
|
|
68
|
+
toAppend.push(`- ${line}`);
|
|
69
|
+
}
|
|
70
|
+
if (toAppend.length === 0) {
|
|
71
|
+
return { appended: 0, skippedDuplicate };
|
|
72
|
+
}
|
|
73
|
+
const header = `# ${date}`;
|
|
74
|
+
const base = existing.trim() ? existing.trimEnd() : header;
|
|
75
|
+
const next = `${base}\n${toAppend.join("\n")}\n`;
|
|
76
|
+
await writeFileAtomically(path, next);
|
|
77
|
+
return { appended: toAppend.length, skippedDuplicate };
|
|
78
|
+
}
|
|
@@ -1,10 +1,10 @@
|
|
|
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 { ExtensionFactory, SessionEntry } from "@earendil-works/pi-coding-agent";
|
|
4
|
-
import type { PipiclawSessionMemorySettings } from "../settings.js";
|
|
5
4
|
import { type ChannelMemoryQueue } from "./channel-maintenance-queue.js";
|
|
6
5
|
import { type MemoryActivityEvent } from "./maintenance-state.js";
|
|
7
|
-
|
|
6
|
+
/** Boundaries `MemoryLifecycle` reflects on directly, outside the scheduled idle job (spec 050, D7). */
|
|
7
|
+
export type ConsolidationReason = "compaction" | "new-session" | "shutdown";
|
|
8
8
|
/**
|
|
9
9
|
* Bound one standalone summarization request. Provider limits can be lower than a model's
|
|
10
10
|
* advertised context window; sending the whole pre-compaction transcript is therefore not safe.
|
|
@@ -21,48 +21,42 @@ export declare function boundCompactionMessages(messages: AgentMessage[], contex
|
|
|
21
21
|
export interface MemoryLifecycleOptions {
|
|
22
22
|
channelId: string;
|
|
23
23
|
channelDir: string;
|
|
24
|
+
workspaceDir: string;
|
|
24
25
|
appHomeDir?: string;
|
|
25
26
|
getMessages: () => AgentMessage[];
|
|
26
27
|
getSessionEntries: () => SessionEntry[];
|
|
27
28
|
getModel: () => Model<Api>;
|
|
28
29
|
resolveApiKey: (model: Model<Api>) => Promise<string>;
|
|
29
|
-
getSessionMemorySettings: () => PipiclawSessionMemorySettings;
|
|
30
30
|
recordMemoryActivity?: (event: MemoryActivityEvent) => Promise<void> | void;
|
|
31
31
|
channelMemoryQueue?: ChannelMemoryQueue;
|
|
32
32
|
}
|
|
33
33
|
export declare class MemoryLifecycle {
|
|
34
34
|
private options;
|
|
35
|
-
private sessionRefreshQueue;
|
|
36
35
|
private durableDirty;
|
|
37
36
|
private durableRevision;
|
|
38
37
|
private lastDurableConsolidationRevision;
|
|
39
38
|
private readonly channelMemoryQueue;
|
|
40
|
-
private
|
|
39
|
+
private backgroundNewSessionReflect;
|
|
41
40
|
constructor(options: MemoryLifecycleOptions);
|
|
42
|
-
private buildRunOptions;
|
|
43
41
|
createExtensionFactory(): ExtensionFactory;
|
|
44
42
|
noteUserTurnStarted(): void;
|
|
45
43
|
noteToolCall(): void;
|
|
46
44
|
noteCompletedAssistantTurn(): void;
|
|
47
45
|
flushForShutdown(): Promise<void>;
|
|
48
|
-
private shouldForceRefreshFor;
|
|
49
|
-
private refreshSessionMemory;
|
|
50
|
-
private runSessionRefreshSerial;
|
|
51
46
|
private runDurableMemoryJobSerial;
|
|
52
47
|
private hasPendingDurableSnapshot;
|
|
53
48
|
private markDurableConsolidationCheckpoint;
|
|
54
|
-
private
|
|
49
|
+
private logReflectResult;
|
|
55
50
|
private appendReviewLog;
|
|
56
|
-
private
|
|
57
|
-
private
|
|
58
|
-
private runPreflightConsolidationNow;
|
|
51
|
+
private runBoundaryReflect;
|
|
52
|
+
private runBoundaryReflectNow;
|
|
59
53
|
private handleSessionBeforeCompact;
|
|
60
54
|
private handleSessionCompact;
|
|
61
55
|
private handleSessionBeforeSwitch;
|
|
62
56
|
/** Snapshot the outgoing state for an out-of-band `/new` before its runner is retired. */
|
|
63
57
|
noteNewSessionBoundary(): void;
|
|
64
|
-
/** Await any in-flight detached new-session
|
|
65
|
-
|
|
58
|
+
/** Await any in-flight detached new-session reflect run (shutdown/tests). */
|
|
59
|
+
whenNewSessionReflectSettled(): Promise<void>;
|
|
66
60
|
private handleSessionStart;
|
|
67
61
|
private recordActivity;
|
|
68
62
|
}
|