@oyasmi/pipiclaw 0.9.1-beta.1 → 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.
Files changed (126) hide show
  1. package/dist/agent/channel-runner.d.ts +7 -1
  2. package/dist/agent/channel-runner.js +42 -15
  3. package/dist/agent/command-extension.js +24 -27
  4. package/dist/agent/commands.d.ts +51 -7
  5. package/dist/agent/commands.js +199 -59
  6. package/dist/agent/prompt/manifest.js +5 -6
  7. package/dist/agent/prompt/sections.js +1 -0
  8. package/dist/agent/reply-limits.d.ts +16 -0
  9. package/dist/agent/reply-limits.js +17 -0
  10. package/dist/agent/runner-factory.d.ts +0 -2
  11. package/dist/agent/session-events.js +2 -2
  12. package/dist/agent/status-render.js +12 -12
  13. package/dist/executor.d.ts +14 -0
  14. package/dist/executor.js +36 -6
  15. package/dist/main.js +3 -4
  16. package/dist/memory/commands.js +79 -38
  17. package/dist/memory/consolidation.d.ts +5 -1
  18. package/dist/memory/consolidation.js +33 -12
  19. package/dist/memory/extraction.d.ts +8 -1
  20. package/dist/memory/extraction.js +47 -4
  21. package/dist/memory/files.d.ts +0 -1
  22. package/dist/memory/files.js +24 -5
  23. package/dist/memory/lifecycle.js +9 -2
  24. package/dist/memory/maintenance-jobs.js +14 -4
  25. package/dist/memory/metadata.d.ts +3 -0
  26. package/dist/memory/metadata.js +7 -0
  27. package/dist/memory/recall.d.ts +9 -0
  28. package/dist/memory/recall.js +101 -17
  29. package/dist/memory/review-log.d.ts +0 -2
  30. package/dist/memory/review-log.js +0 -0
  31. package/dist/memory/session-corpus.js +5 -0
  32. package/dist/memory/session-search.js +9 -0
  33. package/dist/memory/sidecar-worker.js +4 -0
  34. package/dist/memory/source-window.d.ts +0 -1
  35. package/dist/memory/source-window.js +0 -5
  36. package/dist/memory/task-digest.js +0 -2
  37. package/dist/playbooks/agent-delegation.md +32 -24
  38. package/dist/playbooks/background-jobs.md +8 -16
  39. package/dist/playbooks/event-scheduling.md +13 -15
  40. package/dist/playbooks/memory-and-learning.md +29 -22
  41. package/dist/playbooks/outbound-media.md +15 -8
  42. package/dist/playbooks/runtime-orientation.md +40 -37
  43. package/dist/playbooks/task-driving.md +34 -38
  44. package/dist/playbooks/task-planning.md +18 -20
  45. package/dist/runtime/app-home.d.ts +6 -0
  46. package/dist/runtime/app-home.js +15 -6
  47. package/dist/runtime/bootstrap.d.ts +1 -1
  48. package/dist/runtime/bootstrap.js +57 -62
  49. package/dist/runtime/channel-context.d.ts +2 -1
  50. package/dist/runtime/channel-event.d.ts +0 -6
  51. package/dist/runtime/delivery.js +3 -3
  52. package/dist/runtime/dingtalk.d.ts +9 -1
  53. package/dist/runtime/dingtalk.js +27 -13
  54. package/dist/runtime/event-commands.d.ts +15 -0
  55. package/dist/runtime/event-commands.js +48 -40
  56. package/dist/runtime/project-commands.d.ts +16 -0
  57. package/dist/runtime/project-commands.js +13 -17
  58. package/dist/runtime/subagent-commands.d.ts +20 -0
  59. package/dist/runtime/subagent-commands.js +61 -58
  60. package/dist/runtime/task-commands.d.ts +38 -1
  61. package/dist/runtime/task-commands.js +135 -234
  62. package/dist/runtime/task-driver.d.ts +1 -3
  63. package/dist/runtime/task-driver.js +34 -40
  64. package/dist/runtime/task-migration.d.ts +7 -6
  65. package/dist/runtime/task-migration.js +85 -19
  66. package/dist/runtime/task-wake.d.ts +3 -5
  67. package/dist/runtime/task-wake.js +7 -15
  68. package/dist/security/path-guard.js +33 -2
  69. package/dist/security/types.d.ts +9 -0
  70. package/dist/subagents/discovery.d.ts +7 -2
  71. package/dist/subagents/discovery.js +31 -7
  72. package/dist/subagents/external/claude-code.js +42 -2
  73. package/dist/subagents/external/run.js +72 -2
  74. package/dist/subagents/runs.js +28 -3
  75. package/dist/subagents/tool.d.ts +11 -0
  76. package/dist/subagents/tool.js +89 -55
  77. package/dist/subagents/verification-outcome.js +17 -10
  78. package/dist/tasks/control.d.ts +18 -67
  79. package/dist/tasks/control.js +44 -176
  80. package/dist/tasks/ledger.d.ts +7 -13
  81. package/dist/tasks/ledger.js +13 -49
  82. package/dist/tasks/store.d.ts +15 -48
  83. package/dist/tasks/store.js +22 -154
  84. package/dist/tasks/transitions.d.ts +3 -4
  85. package/dist/tasks/transitions.js +8 -27
  86. package/dist/tasks/verification.d.ts +7 -5
  87. package/dist/tools/bash.d.ts +1 -1
  88. package/dist/tools/bash.js +77 -59
  89. package/dist/tools/edit.js +17 -4
  90. package/dist/tools/grep.js +3 -2
  91. package/dist/tools/index.d.ts +0 -2
  92. package/dist/tools/index.js +6 -1
  93. package/dist/tools/job.js +2 -1
  94. package/dist/tools/memory-manage.d.ts +1 -0
  95. package/dist/tools/memory-manage.js +54 -16
  96. package/dist/tools/read.js +21 -5
  97. package/dist/tools/registry.d.ts +0 -1
  98. package/dist/tools/registry.js +0 -1
  99. package/dist/tools/send-media.js +17 -6
  100. package/dist/tools/skill-manage.js +12 -11
  101. package/dist/tools/skill-security.js +1 -1
  102. package/dist/tools/subagent-manage.d.ts +8 -1
  103. package/dist/tools/subagent-manage.js +77 -7
  104. package/dist/tools/task-manage/lifecycle.js +19 -17
  105. package/dist/tools/task-manage/schema.d.ts +2 -6
  106. package/dist/tools/task-manage/schema.js +4 -17
  107. package/dist/tools/task-manage/shared.js +1 -6
  108. package/dist/tools/task-manage/types.d.ts +0 -3
  109. package/dist/tools/task-manage/verification.d.ts +9 -6
  110. package/dist/tools/task-manage/verification.js +19 -71
  111. package/dist/tools/task-manage.d.ts +1 -1
  112. package/dist/tools/task-manage.js +3 -5
  113. package/dist/tools/truncate.d.ts +8 -0
  114. package/dist/tools/truncate.js +8 -0
  115. package/dist/tools/web-fetch.js +9 -1
  116. package/dist/tools/write-content.js +11 -1
  117. package/dist/tui/app.js +1 -1
  118. package/dist/tui/commands.d.ts +1 -1
  119. package/dist/tui/commands.js +1 -1
  120. package/dist/tui/turn-controller.d.ts +1 -1
  121. package/dist/tui/turn-controller.js +14 -4
  122. package/dist/usage/ledger.d.ts +4 -0
  123. package/dist/usage/ledger.js +3 -0
  124. package/dist/usage/render.js +10 -8
  125. package/examples/sub-agents/README.md +2 -0
  126. package/package.json +3 -2
@@ -1,6 +1,7 @@
1
- import { createHash } from "node:crypto";
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
- async function readPendingSuggestions(channelDir) {
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 suggestions = [];
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
- for (const value of entry.suggestions ?? []) {
23
- const id = `p-${createHash("sha256").update(JSON.stringify(value)).digest("hex").slice(0, 8)}`;
24
- suggestions.push({ id, timestamp: entry.timestamp, value });
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 suggestions.slice(-50);
41
+ return actions;
32
42
  }
33
43
  function renderUsage() {
34
- return "Use `/memory status`, `/memory list`, `/memory show <entry-id>`, or `/memory pending`.";
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
- "# Memory Status",
82
+ "**记忆状态**",
58
83
  "",
59
- `- Active entries: \`${entries.length}\``,
60
- `- Metadata records: \`${records.length}\``,
61
- `- Probationary: \`${probationary.length}\`${probationary.length > 0 ? ` (earliest expiry \`${probationary[0].probationUntil}\`)` : ""}`,
62
- `- Pending suggestions: \`${pending.length}\``,
63
- `- Tombstones: \`${tombstones.length}\``,
64
- `- Total recalls: \`${active.reduce((sum, entry) => sum + entry.recallCount, 0)}\``,
65
- `- Recalls (30d): \`${recalls30d}\``,
66
- `- Query diversity: \`${new Set(active.flatMap((entry) => entry.queryFingerprints)).size}\``,
67
- `- Last recalled: \`${active
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) ?? "never"}\``,
72
- `- Recent failure: ${lastFailure ? "yes; inspect memory-review.jsonl" : "none"}`,
73
- `- Active file: \`${getChannelMemoryPath(options.channelDir)}\``,
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 "# Memory Entries\n\nNo active channel memory entries.";
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 ? ` (probation until \`${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} more omitted; use \`/memory show <entry-id>\` after narrowing the file.`);
111
+ lines.push(`- 另有 ${entries.length - visible.length} 条已省略;缩小范围后用 \`/memory show <entry-id>\` 查看。`);
87
112
  }
88
- return `# Memory Entries\n\n${lines.join("\n")}`;
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 `Missing entry id. ${renderUsage()}`;
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 `Memory entry \`${argument}\` was not found. Use \`/memory list\` to see ids.`;
123
+ return `未找到记忆条目 \`${argument}\`。用 \`/memory list\` 查看 id。`;
97
124
  return [
98
- `# Memory ${argument}`,
125
+ `**记忆 ${argument}**`,
99
126
  "",
100
- entry?.content ?? "(not active in MEMORY.md)",
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 === "pending") {
108
- const pending = await readPendingSuggestions(options.channelDir);
109
- if (pending.length === 0)
110
- return "# Pending Memory Suggestions\n\nNo pending suggestions.";
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
- "# Pending Memory Suggestions",
141
+ "**近期记忆活动**",
113
142
  "",
114
- ...pending.map((item) => `- \`${item.id}\`${item.timestamp ? ` (${item.timestamp})` : ""}: ${clipText(JSON.stringify(item.value), 300)}`),
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 `Unknown memory command \`${action}\`. ${renderUsage()}`;
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 declare function cleanupChannelMemory(options: ConsolidationRunOptions, currentMemory: string, guard?: MemoryCleanupShrinkGuard): Promise<boolean>;
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 ((durableCandidates.length > 0 || acceptedProbationary.length > 0) &&
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
- if (after.length < before.length * Math.max(0, Math.min(1, guard.cleanupShrinkGuardMinRatio))) {
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 prompt = `Current MEMORY.md:
254
- ${currentMemory}`;
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 { MemoryEntryKind } from "./metadata.js";
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
- /** Entries rendered as `id — content` so supersede/invalidate can reference real ids. */
163
- function renderMemoryEntriesForPrompt(rawMemory) {
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
- return entries.map((entry) => `${entry.id} — ${entry.content}`).join("\n");
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(renderMemoryEntriesForPrompt(rawMemory), 8_000, { headRatio: 0.35 });
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)"}`,
@@ -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>;
@@ -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
- const MEMORY_BACKUP_KEEP = 5;
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 writeFileAtomically(path, `${ensureTrailingNewlines(header)}${renderedBlock}\n`);
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();
@@ -211,8 +211,15 @@ export class MemoryLifecycle {
211
211
  }
212
212
  const actions = [];
213
213
  const skipped = [];
214
- if (result.appendedMemoryEntries > 0) {
215
- actions.push({ target: "MEMORY.md", action: "append", entries: result.appendedMemoryEntries });
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: [{ target: "MEMORY.md", action: "append", entries: result.appendedMemoryEntries }],
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 cleanedMemory = decision.runMemoryCleanup
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
- : false;
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
- ...(cleanedMemory ? [{ target: "MEMORY.md", action: "rewrite" }] : []),
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;
@@ -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;
@@ -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>;