@oyasmi/pipiclaw 0.9.2 → 0.9.3-beta.2

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.
Files changed (178) hide show
  1. package/README.en.md +250 -0
  2. package/README.md +3 -1
  3. package/dist/agent/channel-runner.d.ts +59 -2
  4. package/dist/agent/channel-runner.js +177 -76
  5. package/dist/agent/job-manager.d.ts +76 -21
  6. package/dist/agent/job-manager.js +447 -63
  7. package/dist/agent/maintenance-context.js +4 -5
  8. package/dist/agent/prompt/manifest.d.ts +0 -2
  9. package/dist/agent/prompt/manifest.js +2 -3
  10. package/dist/agent/prompt/sections.js +3 -3
  11. package/dist/agent/session-events.js +4 -8
  12. package/dist/agent/turn-prompt.d.ts +7 -7
  13. package/dist/agent/turn-prompt.js +6 -9
  14. package/dist/agent/types.d.ts +12 -0
  15. package/dist/agent/types.js +1 -0
  16. package/dist/channel/channel-context.d.ts +13 -0
  17. package/dist/channel/channel-context.js +21 -1
  18. package/dist/commands/catalog.js +47 -20
  19. package/dist/memory/commands.d.ts +8 -0
  20. package/dist/memory/commands.js +113 -148
  21. package/dist/memory/index-budget.d.ts +27 -0
  22. package/dist/memory/index-budget.js +99 -0
  23. package/dist/memory/journal.d.ts +20 -0
  24. package/dist/memory/journal.js +78 -0
  25. package/dist/memory/lifecycle.d.ts +9 -15
  26. package/dist/memory/lifecycle.js +55 -145
  27. package/dist/memory/maintenance-gates.d.ts +13 -47
  28. package/dist/memory/maintenance-gates.js +13 -92
  29. package/dist/memory/maintenance-state.d.ts +10 -16
  30. package/dist/memory/maintenance-state.js +12 -59
  31. package/dist/memory/maintenance-tuning.d.ts +7 -27
  32. package/dist/memory/maintenance-tuning.js +11 -28
  33. package/dist/memory/migrate.d.ts +15 -0
  34. package/dist/memory/migrate.js +364 -0
  35. package/dist/memory/reflect-job.d.ts +43 -0
  36. package/dist/memory/reflect-job.js +117 -0
  37. package/dist/memory/reflect.d.ts +52 -0
  38. package/dist/memory/reflect.js +313 -0
  39. package/dist/memory/render.d.ts +19 -0
  40. package/dist/memory/render.js +35 -0
  41. package/dist/memory/review-log.d.ts +2 -1
  42. package/dist/memory/scheduler.d.ts +2 -3
  43. package/dist/memory/scheduler.js +14 -49
  44. package/dist/memory/search.d.ts +35 -0
  45. package/dist/memory/search.js +297 -0
  46. package/dist/memory/session-search.js +1 -1
  47. package/dist/memory/store.d.ts +108 -0
  48. package/dist/memory/store.js +418 -0
  49. package/dist/memory/task-digest.d.ts +2 -2
  50. package/dist/memory/task-digest.js +29 -36
  51. package/dist/memory/tombstones.d.ts +0 -11
  52. package/dist/memory/tombstones.js +6 -37
  53. package/dist/memory/transcript.js +12 -5
  54. package/dist/playbooks/agent-delegation.md +37 -9
  55. package/dist/playbooks/background-jobs.md +1 -1
  56. package/dist/playbooks/event-scheduling.md +6 -2
  57. package/dist/playbooks/memory-and-learning.md +36 -12
  58. package/dist/playbooks/outbound-media.md +1 -1
  59. package/dist/playbooks/runtime-orientation.md +9 -8
  60. package/dist/playbooks/task-loop.md +110 -0
  61. package/dist/runtime/bootstrap.d.ts +3 -3
  62. package/dist/runtime/bootstrap.js +66 -41
  63. package/dist/runtime/events.d.ts +9 -0
  64. package/dist/runtime/events.js +43 -4
  65. package/dist/runtime/task-commands.d.ts +14 -15
  66. package/dist/runtime/task-commands.js +249 -485
  67. package/dist/runtime/task-driver.d.ts +41 -29
  68. package/dist/runtime/task-driver.js +170 -317
  69. package/dist/runtime/task-migration.d.ts +34 -30
  70. package/dist/runtime/task-migration.js +229 -183
  71. package/dist/runtime/task-wake.d.ts +6 -3
  72. package/dist/runtime/task-wake.js +26 -19
  73. package/dist/settings.d.ts +0 -29
  74. package/dist/settings.js +12 -35
  75. package/dist/shared/markdown-sections.d.ts +0 -1
  76. package/dist/shared/markdown-sections.js +0 -3
  77. package/dist/subagents/discovery.d.ts +2 -2
  78. package/dist/subagents/discovery.js +21 -10
  79. package/dist/subagents/external/progress-tail.js +6 -1
  80. package/dist/subagents/external/run.js +1 -0
  81. package/dist/subagents/runs.d.ts +19 -2
  82. package/dist/subagents/runs.js +73 -4
  83. package/dist/subagents/tool.d.ts +10 -8
  84. package/dist/subagents/tool.js +55 -94
  85. package/dist/tasks/brief.d.ts +17 -0
  86. package/dist/tasks/brief.js +57 -0
  87. package/dist/tasks/budget.d.ts +26 -0
  88. package/dist/tasks/budget.js +59 -0
  89. package/dist/tasks/cycle.d.ts +48 -0
  90. package/dist/tasks/cycle.js +94 -0
  91. package/dist/tasks/frontmatter.d.ts +73 -0
  92. package/dist/tasks/frontmatter.js +175 -0
  93. package/dist/tasks/ledger.d.ts +66 -106
  94. package/dist/tasks/ledger.js +90 -546
  95. package/dist/tasks/log.d.ts +88 -0
  96. package/dist/tasks/log.js +97 -0
  97. package/dist/tasks/rounds.d.ts +41 -0
  98. package/dist/tasks/rounds.js +53 -0
  99. package/dist/tasks/session-path.d.ts +9 -0
  100. package/dist/tasks/session-path.js +16 -0
  101. package/dist/tasks/steer.d.ts +8 -0
  102. package/dist/tasks/steer.js +79 -0
  103. package/dist/tasks/store.d.ts +60 -35
  104. package/dist/tasks/store.js +166 -107
  105. package/dist/tasks/ticket.d.ts +102 -0
  106. package/dist/tasks/ticket.js +209 -0
  107. package/dist/tasks/verification.d.ts +47 -0
  108. package/dist/tasks/verification.js +60 -1
  109. package/dist/tools/index.d.ts +13 -4
  110. package/dist/tools/index.js +5 -10
  111. package/dist/tools/memory-manage.d.ts +6 -16
  112. package/dist/tools/memory-manage.js +108 -129
  113. package/dist/tools/presentation.js +2 -1
  114. package/dist/tools/registry.d.ts +11 -2
  115. package/dist/tools/registry.js +17 -6
  116. package/dist/tools/subagent-manage.d.ts +0 -9
  117. package/dist/tools/subagent-manage.js +8 -17
  118. package/dist/tools/task-manage/create.js +2 -2
  119. package/dist/tools/task-manage/lifecycle.d.ts +9 -4
  120. package/dist/tools/task-manage/lifecycle.js +136 -188
  121. package/dist/tools/task-manage/log-view.d.ts +8 -0
  122. package/dist/tools/task-manage/log-view.js +24 -0
  123. package/dist/tools/task-manage/schema.d.ts +38 -14
  124. package/dist/tools/task-manage/schema.js +46 -27
  125. package/dist/tools/task-manage/shared.d.ts +35 -31
  126. package/dist/tools/task-manage/shared.js +130 -141
  127. package/dist/tools/task-manage/step-end.d.ts +11 -0
  128. package/dist/tools/task-manage/step-end.js +134 -0
  129. package/dist/tools/task-manage/types.d.ts +23 -32
  130. package/dist/tools/task-manage.d.ts +4 -3
  131. package/dist/tools/task-manage.js +30 -15
  132. package/dist/tools/tool-details.d.ts +1 -1
  133. package/dist/tui/app.js +0 -2
  134. package/examples/sub-agents/README.md +54 -38
  135. package/examples/sub-agents/builder-hard.md +21 -12
  136. package/examples/sub-agents/builder.md +24 -16
  137. package/examples/sub-agents/explorer.md +17 -15
  138. package/examples/sub-agents/git-committer.md +8 -6
  139. package/examples/sub-agents/planner.md +17 -16
  140. package/examples/sub-agents/reviewer.md +11 -9
  141. package/examples/sub-agents/verifier.md +22 -16
  142. package/examples/sub-agents/worker.md +22 -6
  143. package/package.json +1 -1
  144. package/dist/agent/effect-ledger.d.ts +0 -32
  145. package/dist/agent/effect-ledger.js +0 -89
  146. package/dist/memory/bootstrap.d.ts +0 -17
  147. package/dist/memory/bootstrap.js +0 -120
  148. package/dist/memory/candidates.d.ts +0 -26
  149. package/dist/memory/candidates.js +0 -202
  150. package/dist/memory/consolidation.d.ts +0 -54
  151. package/dist/memory/consolidation.js +0 -292
  152. package/dist/memory/extraction.d.ts +0 -54
  153. package/dist/memory/extraction.js +0 -240
  154. package/dist/memory/files.d.ts +0 -71
  155. package/dist/memory/files.js +0 -419
  156. package/dist/memory/maintenance-jobs.d.ts +0 -41
  157. package/dist/memory/maintenance-jobs.js +0 -265
  158. package/dist/memory/metadata.d.ts +0 -57
  159. package/dist/memory/metadata.js +0 -142
  160. package/dist/memory/probation.d.ts +0 -17
  161. package/dist/memory/probation.js +0 -44
  162. package/dist/memory/promotion.d.ts +0 -38
  163. package/dist/memory/promotion.js +0 -36
  164. package/dist/memory/recall.d.ts +0 -59
  165. package/dist/memory/recall.js +0 -746
  166. package/dist/memory/session.d.ts +0 -24
  167. package/dist/memory/session.js +0 -273
  168. package/dist/playbooks/task-driving.md +0 -92
  169. package/dist/playbooks/task-planning.md +0 -58
  170. package/dist/tasks/control.d.ts +0 -56
  171. package/dist/tasks/control.js +0 -169
  172. package/dist/tasks/transitions.d.ts +0 -16
  173. package/dist/tasks/transitions.js +0 -48
  174. package/dist/tools/task-manage/verification.d.ts +0 -19
  175. package/dist/tools/task-manage/verification.js +0 -91
  176. package/examples/sub-agents/documenter.md +0 -50
  177. package/examples/sub-agents/log-sifter.md +0 -47
  178. package/examples/sub-agents/scout.md +0 -34
@@ -1,159 +1,124 @@
1
1
  import { renderSubcommandUsage } from "../commands/catalog.js";
2
2
  import { capReply } from "../commands/reply-limits.js";
3
- import { readOptionalTextFile } from "../shared/fs-utils.js";
4
- import { localDayKey, parseLocalTime } from "../shared/local-time.js";
5
- import { clipText } from "../shared/text-utils.js";
6
- import { getChannelMemoryPath, parseChannelMemoryEntries, readChannelMemory } from "./files.js";
7
- import { syncMemoryMetadata } from "./metadata.js";
8
- import { getMemoryReviewLogPath } from "./review-log.js";
9
- import { readMemoryTombstones } from "./tombstones.js";
10
- async function reconcile(options) {
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
- export async function handleMemoryCommand(options) {
47
- const [action = "status", argument] = options.args.trim().split(/\s+/, 2);
48
- const { entries, metadata } = await reconcile(options);
49
- if (action === "status") {
50
- const tombstones = await readMemoryTombstones(options.channelDir);
51
- const records = Object.values(metadata.entries);
52
- const active = records.filter((entry) => entry.status === "active");
53
- const probationary = active
54
- .filter((entry) => entry.probationUntil)
55
- .sort((a, b) => (a.probationUntil ?? "").localeCompare(b.probationUntil ?? ""));
56
- const since = new Date();
57
- since.setDate(since.getDate() - 29);
58
- const sinceDay = localDayKey(since);
59
- const recalls30d = active.reduce((sum, entry) => sum +
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);
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
- if (action === "list") {
102
- if (entries.length === 0)
103
- return "**记忆条目**\n\n暂无生效的频道记忆条目。";
104
- const visible = entries.slice(0, 50);
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
- if (action === "show") {
118
- if (!argument)
119
- return `缺少 entry id。${renderUsage()}`;
120
- const entry = entries.find((candidate) => candidate.id === argument);
121
- const record = metadata.entries[argument];
122
- if (!entry && !record)
123
- return `未找到记忆条目 \`${argument}\`。用 \`/memory list\` 查看 id。`;
124
- return [
125
- `**记忆 ${argument}**`,
126
- "",
127
- entry?.content ?? "(未在 MEMORY.md 中生效)",
128
- "",
129
- "```json",
130
- JSON.stringify(record ?? { id: argument, status: "unknown" }, null, 2),
131
- "```",
132
- ].join("\n");
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
- 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 天没有记忆活动。";
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
- export type ConsolidationReason = "compaction" | "new-session" | "idle" | "shutdown";
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 backgroundNewSessionConsolidation;
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 logConsolidationResult;
49
+ private logReflectResult;
55
50
  private appendReviewLog;
56
- private recordConsolidationReview;
57
- private runPreflightConsolidation;
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 consolidation (shutdown/tests). */
65
- whenNewSessionConsolidationSettled(): Promise<void>;
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
  }