@oyasmi/pipiclaw 0.8.4 → 0.8.6

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 (92) hide show
  1. package/README.md +2 -1
  2. package/dist/agent/channel-runner.d.ts +29 -0
  3. package/dist/agent/channel-runner.js +156 -53
  4. package/dist/agent/command-extension.d.ts +1 -0
  5. package/dist/agent/command-extension.js +6 -0
  6. package/dist/agent/commands.d.ts +2 -2
  7. package/dist/agent/commands.js +16 -1
  8. package/dist/agent/maintenance-context.js +1 -1
  9. package/dist/agent/prompt/builder.d.ts +32 -0
  10. package/dist/agent/prompt/builder.js +252 -0
  11. package/dist/agent/prompt/extension.d.ts +22 -0
  12. package/dist/agent/prompt/extension.js +24 -0
  13. package/dist/agent/prompt/manifest.d.ts +51 -0
  14. package/dist/agent/prompt/manifest.js +84 -0
  15. package/dist/agent/prompt/resources.d.ts +18 -0
  16. package/dist/agent/prompt/resources.js +61 -0
  17. package/dist/agent/prompt/sections.d.ts +39 -0
  18. package/dist/agent/prompt/sections.js +267 -0
  19. package/dist/agent/prompt/types.d.ts +110 -0
  20. package/dist/agent/prompt/types.js +11 -0
  21. package/dist/agent/types.d.ts +3 -0
  22. package/dist/agent/workspace-resources.d.ts +25 -13
  23. package/dist/agent/workspace-resources.js +28 -41
  24. package/dist/index.d.ts +7 -2
  25. package/dist/index.js +6 -2
  26. package/dist/memory/bootstrap.d.ts +5 -0
  27. package/dist/memory/bootstrap.js +14 -4
  28. package/dist/memory/candidates.d.ts +2 -0
  29. package/dist/memory/candidates.js +13 -3
  30. package/dist/memory/commands.d.ts +6 -0
  31. package/dist/memory/commands.js +112 -0
  32. package/dist/memory/consolidation.d.ts +3 -0
  33. package/dist/memory/consolidation.js +68 -26
  34. package/dist/memory/files.d.ts +13 -0
  35. package/dist/memory/files.js +65 -8
  36. package/dist/memory/lifecycle.d.ts +2 -1
  37. package/dist/memory/lifecycle.js +34 -6
  38. package/dist/memory/maintenance-jobs.js +48 -23
  39. package/dist/memory/metadata.d.ts +60 -0
  40. package/dist/memory/metadata.js +135 -0
  41. package/dist/memory/policy.d.ts +3 -0
  42. package/dist/memory/policy.js +19 -0
  43. package/dist/memory/post-turn-review.d.ts +11 -1
  44. package/dist/memory/post-turn-review.js +78 -19
  45. package/dist/memory/promotion.d.ts +5 -2
  46. package/dist/memory/promotion.js +3 -1
  47. package/dist/memory/recall.d.ts +3 -0
  48. package/dist/memory/recall.js +27 -5
  49. package/dist/memory/review-log.d.ts +2 -0
  50. package/dist/memory/review-log.js +15 -0
  51. package/dist/memory/session-corpus.js +11 -3
  52. package/dist/memory/session-search.js +8 -4
  53. package/dist/memory/session.d.ts +1 -0
  54. package/dist/memory/session.js +3 -1
  55. package/dist/memory/sidecar-worker.d.ts +1 -0
  56. package/dist/memory/sidecar-worker.js +1 -0
  57. package/dist/memory/source-window.d.ts +25 -0
  58. package/dist/memory/source-window.js +64 -0
  59. package/dist/memory/tombstones.d.ts +12 -0
  60. package/dist/memory/tombstones.js +44 -0
  61. package/dist/memory/transcript.js +33 -9
  62. package/dist/playbooks/catalog.d.ts +22 -1
  63. package/dist/playbooks/catalog.js +57 -4
  64. package/dist/playbooks/event-scheduling.md +2 -0
  65. package/dist/playbooks/memory-and-learning.md +2 -0
  66. package/dist/playbooks/runtime-orientation.md +1 -0
  67. package/dist/playbooks/task-closeout.md +3 -1
  68. package/dist/playbooks/task-delegation.md +3 -1
  69. package/dist/playbooks/task-driving.md +2 -0
  70. package/dist/playbooks/task-planning.md +2 -0
  71. package/dist/playbooks/task-recurring.md +2 -0
  72. package/dist/playbooks/task-repair.md +3 -1
  73. package/dist/runtime/bootstrap.js +8 -38
  74. package/dist/runtime/dingtalk.d.ts +1 -0
  75. package/dist/runtime/dingtalk.js +3 -0
  76. package/dist/runtime/task-commands.js +1 -1
  77. package/dist/runtime/workspace-templates.d.ts +11 -0
  78. package/dist/runtime/workspace-templates.js +51 -0
  79. package/dist/settings.js +1 -1
  80. package/dist/tasks/control.js +9 -3
  81. package/dist/tasks/store.d.ts +1 -0
  82. package/dist/tasks/store.js +11 -1
  83. package/dist/tools/memory-manage.d.ts +1 -1
  84. package/dist/tools/memory-manage.js +27 -6
  85. package/dist/tools/task-manage.js +2 -2
  86. package/dist/tui/commands.d.ts +1 -0
  87. package/dist/tui/commands.js +2 -0
  88. package/dist/tui/turn-controller.js +1 -0
  89. package/dist/usage/ledger.d.ts +2 -0
  90. package/package.json +1 -1
  91. package/dist/agent/prompt-builder.d.ts +0 -12
  92. package/dist/agent/prompt-builder.js +0 -71
@@ -2,7 +2,7 @@ import { stat } from "fs/promises";
2
2
  import { join } from "path";
3
3
  import { readOptionalTextFile } from "../shared/fs-utils.js";
4
4
  import { splitH1Sections, splitH2Sections } from "../shared/markdown-sections.js";
5
- import { getChannelHistoryPath, getChannelMemoryPath, getChannelSessionPath, parseUpdateHeadingTimestamp, } from "./files.js";
5
+ import { getChannelHistoryPath, getChannelMemoryPath, getChannelSessionPath, parseChannelMemoryEntries, parseUpdateHeadingTimestamp, } from "./files.js";
6
6
  function normalizeContent(content) {
7
7
  return content.replace(/\r/g, "").trim();
8
8
  }
@@ -61,10 +61,13 @@ const ENTRY_ID_COMMENT_GLOBAL = /\s*<!--\s*id:m-[a-z0-9]+\s*-->/gi;
61
61
  function stripEntryIdComments(text) {
62
62
  return text.replace(ENTRY_ID_COMMENT_GLOBAL, "");
63
63
  }
64
- function buildCandidate(source, path, title, content, timestamp, searchText) {
64
+ export function buildMemoryCandidateId(source, title, timestamp) {
65
+ return `${source}:${slugify(title)}:${timestamp ?? ""}`;
66
+ }
67
+ function buildCandidate(source, path, title, content, timestamp, searchText, id, entryId) {
65
68
  const cleanContent = stripEntryIdComments(content);
66
69
  return {
67
- id: `${source}:${slugify(title)}:${timestamp ?? ""}`,
70
+ id: id ?? buildMemoryCandidateId(source, title, timestamp),
68
71
  source,
69
72
  path,
70
73
  title,
@@ -73,9 +76,16 @@ function buildCandidate(source, path, title, content, timestamp, searchText) {
73
76
  timestamp,
74
77
  sectionKind: title.trim().toLowerCase(),
75
78
  priority: inferPriority(source, title),
79
+ entryId,
76
80
  };
77
81
  }
78
82
  function buildWorkspaceOrChannelMemoryCandidates(source, path, content) {
83
+ if (source === "channel-memory") {
84
+ const entries = parseChannelMemoryEntries(content);
85
+ if (entries.length > 0) {
86
+ return entries.map((entry) => buildCandidate(source, path, entry.sectionHeading, entry.content, entry.timestamp, entry.content, entry.id, entry.id));
87
+ }
88
+ }
79
89
  const sections = splitH2Sections(content);
80
90
  if (sections.length === 0 && content) {
81
91
  return [
@@ -0,0 +1,6 @@
1
+ interface MemoryCommandOptions {
2
+ channelDir: string;
3
+ args: string;
4
+ }
5
+ export declare function handleMemoryCommand(options: MemoryCommandOptions): Promise<string>;
6
+ export {};
@@ -0,0 +1,112 @@
1
+ import { createHash } from "node:crypto";
2
+ import { readOptionalTextFile } from "../shared/fs-utils.js";
3
+ import { clipText } from "../shared/text-utils.js";
4
+ import { getChannelMemoryPath, parseChannelMemoryEntries, readChannelMemory } from "./files.js";
5
+ import { syncMemoryMetadata } from "./metadata.js";
6
+ import { getMemoryReviewLogPath } from "./review-log.js";
7
+ import { readMemoryTombstones } from "./tombstones.js";
8
+ async function reconcile(options) {
9
+ const entries = parseChannelMemoryEntries(await readChannelMemory(options.channelDir));
10
+ const metadata = await syncMemoryMetadata(options.channelDir, entries);
11
+ return { entries, metadata };
12
+ }
13
+ async function readPendingSuggestions(channelDir) {
14
+ const raw = await readOptionalTextFile(getMemoryReviewLogPath(channelDir));
15
+ const suggestions = [];
16
+ for (const line of raw.split("\n")) {
17
+ if (!line.trim())
18
+ continue;
19
+ try {
20
+ const entry = JSON.parse(line);
21
+ for (const value of entry.suggestions ?? []) {
22
+ const id = `p-${createHash("sha256").update(JSON.stringify(value)).digest("hex").slice(0, 8)}`;
23
+ suggestions.push({ id, timestamp: entry.timestamp, value });
24
+ }
25
+ }
26
+ catch {
27
+ // A torn audit line should not break the management surface.
28
+ }
29
+ }
30
+ return suggestions.slice(-50);
31
+ }
32
+ function renderUsage() {
33
+ return "Use `/memory status`, `/memory list`, `/memory show <entry-id>`, or `/memory pending`.";
34
+ }
35
+ export async function handleMemoryCommand(options) {
36
+ const [action = "status", argument] = options.args.trim().split(/\s+/, 2);
37
+ const { entries, metadata } = await reconcile(options);
38
+ if (action === "status") {
39
+ const pending = await readPendingSuggestions(options.channelDir);
40
+ const tombstones = await readMemoryTombstones(options.channelDir);
41
+ const records = Object.values(metadata.entries);
42
+ const active = records.filter((entry) => entry.status === "active");
43
+ const since = new Date();
44
+ since.setUTCDate(since.getUTCDate() - 29);
45
+ const sinceDay = since.toISOString().slice(0, 10);
46
+ const recalls30d = active.reduce((sum, entry) => sum +
47
+ Object.entries(entry.recallByDay ?? {}).reduce((entrySum, [day, count]) => entrySum + (day >= sinceDay ? count : 0), 0), 0);
48
+ const lastFailure = (await readOptionalTextFile(getMemoryReviewLogPath(options.channelDir)))
49
+ .split("\n")
50
+ .reverse()
51
+ .find((line) => line.includes('"error"'));
52
+ return [
53
+ "# Memory Status",
54
+ "",
55
+ `- Active entries: \`${entries.length}\``,
56
+ `- Metadata records: \`${records.length}\``,
57
+ `- Pending suggestions: \`${pending.length}\``,
58
+ `- Tombstones: \`${tombstones.length}\``,
59
+ `- Total recalls: \`${active.reduce((sum, entry) => sum + entry.recallCount, 0)}\``,
60
+ `- Recalls (30d): \`${recalls30d}\``,
61
+ `- Query diversity: \`${new Set(active.flatMap((entry) => entry.queryFingerprints)).size}\``,
62
+ `- Last recalled: \`${active
63
+ .map((entry) => entry.lastRecalledAt)
64
+ .filter(Boolean)
65
+ .sort()
66
+ .at(-1) ?? "never"}\``,
67
+ `- Recent failure: ${lastFailure ? "yes; inspect memory-review.jsonl" : "none"}`,
68
+ `- Active file: \`${getChannelMemoryPath(options.channelDir)}\``,
69
+ ].join("\n");
70
+ }
71
+ if (action === "list") {
72
+ if (entries.length === 0)
73
+ return "# Memory Entries\n\nNo active channel memory entries.";
74
+ const visible = entries.slice(0, 50);
75
+ const lines = visible.map((entry) => {
76
+ const record = metadata.entries[entry.id];
77
+ return `- \`${entry.id}\` [${record?.kind ?? "fact"}] ${clipText(entry.content, 180, { headRatio: 1 })}`;
78
+ });
79
+ if (entries.length > visible.length) {
80
+ lines.push(`- ${entries.length - visible.length} more omitted; use \`/memory show <entry-id>\` after narrowing the file.`);
81
+ }
82
+ return `# Memory Entries\n\n${lines.join("\n")}`;
83
+ }
84
+ if (action === "show") {
85
+ if (!argument)
86
+ return `Missing entry id. ${renderUsage()}`;
87
+ const entry = entries.find((candidate) => candidate.id === argument);
88
+ const record = metadata.entries[argument];
89
+ if (!entry && !record)
90
+ return `Memory entry \`${argument}\` was not found. Use \`/memory list\` to see ids.`;
91
+ return [
92
+ `# Memory ${argument}`,
93
+ "",
94
+ entry?.content ?? "(not active in MEMORY.md)",
95
+ "",
96
+ "```json",
97
+ JSON.stringify(record ?? { id: argument, status: "unknown" }, null, 2),
98
+ "```",
99
+ ].join("\n");
100
+ }
101
+ if (action === "pending") {
102
+ const pending = await readPendingSuggestions(options.channelDir);
103
+ if (pending.length === 0)
104
+ return "# Pending Memory Suggestions\n\nNo pending suggestions.";
105
+ return [
106
+ "# Pending Memory Suggestions",
107
+ "",
108
+ ...pending.map((item) => `- \`${item.id}\`${item.timestamp ? ` (${item.timestamp})` : ""}: ${clipText(JSON.stringify(item.value), 300)}`),
109
+ ].join("\n");
110
+ }
111
+ return `Unknown memory command \`${action}\`. ${renderUsage()}`;
112
+ }
@@ -2,6 +2,7 @@ import type { AgentMessage } from "@earendil-works/pi-agent-core";
2
2
  import type { Api, Model } from "@earendil-works/pi-ai";
3
3
  import { type SessionEntry } from "@earendil-works/pi-coding-agent";
4
4
  import type { PipiclawMemoryMaintenanceSettings } from "../settings.js";
5
+ import type { MemorySourceWindow } from "./source-window.js";
5
6
  export type ConsolidationMode = "idle" | "boundary";
6
7
  export interface ConsolidationRunOptions {
7
8
  channelId?: string;
@@ -10,7 +11,9 @@ export interface ConsolidationRunOptions {
10
11
  resolveApiKey: (model: Model<Api>) => Promise<string>;
11
12
  messages: AgentMessage[];
12
13
  sessionEntries?: SessionEntry[];
14
+ sourceWindow?: MemorySourceWindow;
13
15
  mode?: ConsolidationMode;
16
+ usageCorrelationId?: string;
14
17
  }
15
18
  export interface InlineConsolidationResult {
16
19
  skipped: boolean;
@@ -15,8 +15,8 @@ const INLINE_CONSOLIDATION_TIMEOUT_MS = 20_000;
15
15
  const MEMORY_CLEANUP_TIMEOUT_MS = 120_000;
16
16
  const HISTORY_FOLDING_TIMEOUT_MS = 120_000;
17
17
  const MEMORY_OPS_RULES = `- memoryOps entries operate on the durable channel MEMORY.md:
18
- - {"op":"add","content":"..."} for a genuinely new durable fact.
19
- - {"op":"supersede","targetId":"m-xxxx","content":"..."} when new information updates or contradicts an existing entry (use its id).
18
+ - {"op":"add","content":"...","kind":"fact|preference|decision|constraint|open-loop|lesson"} for a genuinely new durable fact.
19
+ - {"op":"supersede","targetId":"m-xxxx","content":"...","kind":"..."} when new information updates or contradicts an existing entry (use its id).
20
20
  - {"op":"invalidate","targetId":"m-xxxx","reason":"..."} when an existing entry is now obsolete or resolved.
21
21
  - Only reference targetId values that appear in the current MEMORY.md entries shown below.
22
22
  - Durable = stable facts, decisions, preferences, constraints, or medium-horizon open loops.
@@ -75,6 +75,9 @@ Goals:
75
75
  - Prefer concise bullets over prose.
76
76
  - Remove content that is clearly transient session-state and belongs in SESSION.md instead.
77
77
  - Do not preserve minute-level current task progress unless it is a durable decision, constraint, user preference, or medium-horizon open loop.
78
+ - Preserve the top-level "# Channel Memory" heading.
79
+ - Every retained bullet must preserve its original <!--id:m-*--> comment exactly.
80
+ - Do not invent ids, duplicate ids, prose instructions, or content outside H2 sections.
78
81
 
79
82
  Suggested sections:
80
83
  - ## Identity / Participants
@@ -94,8 +97,8 @@ Goals:
94
97
  - Keep important decisions, milestones, and unresolved outcomes.
95
98
  - Remove redundancy and transcript-like detail.
96
99
  - Preserve a chronological narrative at a high level.`;
97
- function usageContextFor(channelId) {
98
- return channelId ? { channelId } : undefined;
100
+ function usageContextFor(channelId, correlationId) {
101
+ return channelId ? { channelId, correlationId } : undefined;
99
102
  }
100
103
  function normalizeText(text) {
101
104
  return text.replace(/\r/g, "").trim();
@@ -107,8 +110,16 @@ function normalizeMemoryOp(value) {
107
110
  const record = value;
108
111
  const content = typeof record.content === "string" ? record.content.trim() : "";
109
112
  const targetId = typeof record.targetId === "string" ? record.targetId.trim() : "";
113
+ const kind = record.kind === "preference" ||
114
+ record.kind === "decision" ||
115
+ record.kind === "constraint" ||
116
+ record.kind === "open-loop" ||
117
+ record.kind === "lesson"
118
+ ? record.kind
119
+ : "fact";
120
+ const metadata = { kind, sourceType: "agent", trust: "inferred" };
110
121
  if (record.op === "supersede" && targetId && content) {
111
- return { op: "supersede", targetId, content };
122
+ return { op: "supersede", targetId, content, metadata };
112
123
  }
113
124
  if (record.op === "invalidate" && targetId) {
114
125
  return {
@@ -119,7 +130,7 @@ function normalizeMemoryOp(value) {
119
130
  }
120
131
  // Default to add for "add" or any unrecognized op that still carries content.
121
132
  if (content) {
122
- return { op: "add", content };
133
+ return { op: "add", content, metadata };
123
134
  }
124
135
  return null;
125
136
  }
@@ -131,17 +142,16 @@ function parseConsolidationResponse(text) {
131
142
  historyBlock: typeof parsed.historyBlock === "string" ? parsed.historyBlock.trim() : "",
132
143
  };
133
144
  }
134
- function getLatestCompactionBoundary(entries) {
135
- const latestCompaction = getLatestCompactionEntry(entries);
136
- if (!latestCompaction) {
137
- return 0;
138
- }
139
- const boundaryIndex = entries.findIndex((entry) => entry.id === latestCompaction.firstKeptEntryId);
140
- return boundaryIndex >= 0 ? boundaryIndex : 0;
141
- }
142
145
  function isMessage(entry) {
143
146
  return entry.type === "message";
144
147
  }
148
+ function entriesAfterLatestCompactionBoundary(entries) {
149
+ const latestCompaction = getLatestCompactionEntry(entries);
150
+ if (!latestCompaction)
151
+ return entries;
152
+ const boundaryIndex = entries.findIndex((entry) => entry.id === latestCompaction.firstKeptEntryId);
153
+ return boundaryIndex >= 0 ? entries.slice(boundaryIndex) : entries;
154
+ }
145
155
  function extractMessagesFromSessionEntries(entries) {
146
156
  return entries.filter(isMessage).map((entry) => entry.message);
147
157
  }
@@ -234,7 +244,7 @@ ${transcript || "(empty)"}`;
234
244
  systemPrompt: mode === "idle" ? IDLE_INLINE_CONSOLIDATION_SYSTEM_PROMPT : BOUNDARY_INLINE_CONSOLIDATION_SYSTEM_PROMPT,
235
245
  prompt,
236
246
  timeoutMs: INLINE_CONSOLIDATION_TIMEOUT_MS,
237
- usageContext: usageContextFor(options.channelId),
247
+ usageContext: usageContextFor(options.channelId, options.sourceWindow?.windowId ?? options.usageCorrelationId),
238
248
  parse: (text) => text.trim(),
239
249
  });
240
250
  const rawResponse = result.output;
@@ -242,17 +252,28 @@ ${transcript || "(empty)"}`;
242
252
  }
243
253
  export async function runInlineConsolidation(options) {
244
254
  const mode = options.mode ?? "boundary";
245
- const sourceEntries = options.sessionEntries ?? [];
246
- const relevantEntries = sourceEntries.length > 0 ? sourceEntries.slice(getLatestCompactionBoundary(sourceEntries)) : sourceEntries;
247
- const relevantMessages = sanitizeMessagesForMemory(relevantEntries.length > 0 ? extractMessagesFromSessionEntries(relevantEntries) : options.messages);
255
+ const sourceEntries = options.sourceWindow?.entries ?? entriesAfterLatestCompactionBoundary(options.sessionEntries ?? []);
256
+ const relevantMessages = sanitizeMessagesForMemory(options.sourceWindow?.messages ??
257
+ (sourceEntries.length > 0 ? extractMessagesFromSessionEntries(sourceEntries) : options.messages));
248
258
  if (!hasMeaningfulMessages(relevantMessages)) {
249
259
  return { skipped: true, appendedMemoryEntries: 0, appendedHistoryBlock: false };
250
260
  }
251
261
  const response = await buildInlineConsolidationResponse(options, relevantMessages);
252
262
  const timestamp = new Date().toISOString();
253
263
  let appliedMemoryOps = 0;
254
- if (response.memoryOps.length > 0) {
255
- const applied = await applyChannelMemoryOps(options.channelDir, response.memoryOps, timestamp);
264
+ if (response.memoryOps.length > 0 && !options.sourceWindow?.hasExternalToolContent) {
265
+ const sourceEntryIds = options.sourceWindow?.entries.map((entry) => entry.id) ?? [];
266
+ const ops = response.memoryOps.map((op) => op.op === "add" || op.op === "supersede"
267
+ ? {
268
+ ...op,
269
+ sourceEntryIds,
270
+ metadata: {
271
+ ...op.metadata,
272
+ sourceCorrelationId: options.sourceWindow?.windowId ?? options.usageCorrelationId,
273
+ },
274
+ }
275
+ : op);
276
+ const applied = await applyChannelMemoryOps(options.channelDir, ops, timestamp);
256
277
  appliedMemoryOps = applied.added + applied.superseded + applied.invalidated + applied.downgradedToAdd;
257
278
  }
258
279
  if (mode === "boundary" && response.historyBlock.trim()) {
@@ -279,23 +300,44 @@ export class MemoryCleanupRejectedError extends Error {
279
300
  function isCleanupResultTooSmall(currentMemory, nextMemory, guard) {
280
301
  const before = normalizeText(currentMemory);
281
302
  const after = normalizeText(nextMemory);
282
- if (before.length < Math.max(0, guard.cleanupShrinkGuardMinChars)) {
303
+ const beforeEntries = parseChannelMemoryEntries(before).length;
304
+ const afterEntries = parseChannelMemoryEntries(after).length;
305
+ if (beforeEntries > 0 && afterEntries === 0)
306
+ return true;
307
+ if (before.length < Math.max(0, guard.cleanupShrinkGuardMinChars))
283
308
  return false;
284
- }
285
309
  if (after.length < before.length * Math.max(0, Math.min(1, guard.cleanupShrinkGuardMinRatio))) {
286
310
  return true;
287
311
  }
288
- const beforeEntries = parseChannelMemoryEntries(before).length;
289
- const afterEntries = parseChannelMemoryEntries(after).length;
290
312
  return beforeEntries > 0 && afterEntries * 2 < beforeEntries;
291
313
  }
314
+ function validateCleanupSchema(currentMemory, nextMemory) {
315
+ if (!/^# Channel Memory(?:\s|$)/.test(nextMemory.trimStart())) {
316
+ return 'cleanup output must start with "# Channel Memory"';
317
+ }
318
+ const originalIds = new Set(parseChannelMemoryEntries(currentMemory).map((entry) => entry.id));
319
+ const entries = parseChannelMemoryEntries(nextMemory);
320
+ const ids = new Set();
321
+ for (const entry of entries) {
322
+ if (!originalIds.has(entry.id))
323
+ return `cleanup output invented unknown entry id ${entry.id}`;
324
+ if (ids.has(entry.id))
325
+ return `cleanup output duplicated entry id ${entry.id}`;
326
+ ids.add(entry.id);
327
+ }
328
+ return null;
329
+ }
292
330
  export async function cleanupChannelMemory(options, currentMemory, guard) {
293
331
  if (!shouldCleanupChannelMemory(currentMemory)) {
294
332
  return false;
295
333
  }
296
334
  const prompt = `Current MEMORY.md:
297
335
  ${currentMemory}`;
298
- const nextMemory = await runWorkerPrompt("memory-cleanup", options.model, options.resolveApiKey, MEMORY_CLEANUP_SYSTEM_PROMPT, prompt, MEMORY_CLEANUP_TIMEOUT_MS, usageContextFor(options.channelId));
336
+ const nextMemory = await runWorkerPrompt("memory-cleanup", options.model, options.resolveApiKey, MEMORY_CLEANUP_SYSTEM_PROMPT, prompt, MEMORY_CLEANUP_TIMEOUT_MS, usageContextFor(options.channelId, options.usageCorrelationId));
337
+ const schemaError = validateCleanupSchema(currentMemory, nextMemory);
338
+ if (schemaError) {
339
+ throw new MemoryCleanupRejectedError(`${schemaError}. Retry cleanup while preserving the MEMORY.md schema and ids.`);
340
+ }
299
341
  if (guard && isCleanupResultTooSmall(currentMemory, nextMemory, guard)) {
300
342
  throw new MemoryCleanupRejectedError("cleanup result shrank below the configured guard threshold");
301
343
  }
@@ -318,7 +360,7 @@ export async function foldChannelHistory(options, currentHistory) {
318
360
  });
319
361
  const prompt = `Older history blocks to fold:
320
362
  ${renderedOlder}`;
321
- const foldedSummary = await runWorkerPrompt("history-folding", options.model, options.resolveApiKey, HISTORY_FOLDING_SYSTEM_PROMPT, prompt, HISTORY_FOLDING_TIMEOUT_MS, usageContextFor(options.channelId));
363
+ const foldedSummary = await runWorkerPrompt("history-folding", options.model, options.resolveApiKey, HISTORY_FOLDING_SYSTEM_PROMPT, prompt, HISTORY_FOLDING_TIMEOUT_MS, usageContextFor(options.channelId, options.usageCorrelationId));
322
364
  const foldedHeading = `## Folded History Through ${olderSections[olderSections.length - 1]?.heading ?? new Date().toISOString()}`;
323
365
  const rebuiltHistory = [
324
366
  "# Channel History",
@@ -1,3 +1,4 @@
1
+ import { type MemoryWriteMetadataInput } from "./metadata.js";
1
2
  export declare function generateMemoryEntryId(): string;
2
3
  export declare function stripMemoryEntryIdComment(text: string): string;
3
4
  export declare function parseUpdateHeadingTimestamp(heading: string): string | undefined;
@@ -14,14 +15,23 @@ export declare function parseChannelMemoryEntries(content: string): ParsedMemory
14
15
  export type MemoryOp = {
15
16
  op: "add";
16
17
  content: string;
18
+ sourceEntryIds?: string[];
19
+ metadata?: MemoryWriteMetadataInput;
17
20
  } | {
18
21
  op: "supersede";
19
22
  targetId: string;
20
23
  content: string;
24
+ sourceEntryIds?: string[];
25
+ metadata?: MemoryWriteMetadataInput;
21
26
  } | {
22
27
  op: "invalidate";
23
28
  targetId: string;
24
29
  reason?: string;
30
+ } | {
31
+ op: "forget";
32
+ targetId: string;
33
+ reason?: string;
34
+ sourceEntryIds?: string[];
25
35
  };
26
36
  export interface ApplyMemoryOpsResult {
27
37
  added: number;
@@ -29,6 +39,9 @@ export interface ApplyMemoryOpsResult {
29
39
  invalidated: number;
30
40
  downgradedToAdd: number;
31
41
  missingTarget: number;
42
+ forgotten: number;
43
+ blockedByPolicy: number;
44
+ blockedByTombstone: number;
32
45
  }
33
46
  /**
34
47
  * Apply add/supersede/invalidate ops to a channel MEMORY.md with line-level edits,
@@ -4,6 +4,9 @@ import { copyFile, readdir, rm } 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";
7
+ import { syncMemoryMetadata } from "./metadata.js";
8
+ import { containsSecret, REDACTED_SECRET } from "./policy.js";
9
+ import { appendMemoryTombstone, hashMemoryContent, readMemoryTombstones } from "./tombstones.js";
7
10
  const DEFAULT_CHANNEL_MEMORY = `# Channel Memory
8
11
 
9
12
  This file stores durable channel-specific memory.
@@ -133,6 +136,9 @@ export async function applyChannelMemoryOps(channelDir, ops, timestamp = new Dat
133
136
  invalidated: 0,
134
137
  downgradedToAdd: 0,
135
138
  missingTarget: 0,
139
+ forgotten: 0,
140
+ blockedByPolicy: 0,
141
+ blockedByTombstone: 0,
136
142
  };
137
143
  if (ops.length === 0) {
138
144
  return result;
@@ -141,23 +147,59 @@ export async function applyChannelMemoryOps(channelDir, ops, timestamp = new Dat
141
147
  const path = getChannelMemoryPath(channelDir);
142
148
  const existing = await readOptionalTextFile(path);
143
149
  const lines = existing.replace(/\r/g, "").split("\n");
144
- const byId = new Map(parseChannelMemoryEntries(existing).map((entry) => [entry.id, entry]));
150
+ const existingEntries = parseChannelMemoryEntries(existing);
151
+ const byId = new Map(existingEntries.map((entry) => [entry.id, entry]));
152
+ // Reconcile legacy entries before applying removals so terminal status retains
153
+ // the entry's provenance even when no sidecar record existed yet.
154
+ await syncMemoryMetadata(channelDir, existingEntries, [], timestamp);
155
+ const tombstones = await readMemoryTombstones(channelDir);
156
+ const tombstoneHashes = new Set(tombstones.map((tombstone) => tombstone.contentHash));
157
+ const tombstoneSourceIds = new Set(tombstones.flatMap((tombstone) => tombstone.sourceEntryIds ?? []));
145
158
  const removals = new Set();
146
159
  const replacements = new Map();
147
160
  const additions = [];
161
+ const metadataUpdates = [];
148
162
  for (const op of ops) {
163
+ if (op.op === "add" || op.op === "supersede") {
164
+ if (containsSecret(op.content) || op.content.includes(REDACTED_SECRET)) {
165
+ result.blockedByPolicy++;
166
+ continue;
167
+ }
168
+ if (tombstoneHashes.has(hashMemoryContent(op.content)) ||
169
+ op.sourceEntryIds?.some((entryId) => tombstoneSourceIds.has(entryId))) {
170
+ result.blockedByTombstone++;
171
+ continue;
172
+ }
173
+ }
149
174
  if (op.op === "add") {
150
175
  if (op.content.trim()) {
151
- additions.push(op.content.trim());
176
+ const id = generateMemoryEntryId();
177
+ additions.push({ content: op.content.trim(), id });
178
+ metadataUpdates.push({ id, status: "active", metadata: op.metadata, sourceEntryIds: op.sourceEntryIds });
152
179
  result.added++;
153
180
  }
154
181
  continue;
155
182
  }
156
183
  const target = byId.get(op.targetId);
157
- if (op.op === "invalidate") {
184
+ if (op.op === "invalidate" || op.op === "forget") {
158
185
  if (target) {
159
186
  removals.add(target.lineIndex);
160
- result.invalidated++;
187
+ if (op.op === "forget") {
188
+ await appendMemoryTombstone(channelDir, {
189
+ entryId: target.id,
190
+ contentHash: hashMemoryContent(target.content),
191
+ deletedAt: timestamp,
192
+ scope: "channel",
193
+ reason: op.reason?.trim() || "user forget",
194
+ sourceEntryIds: op.sourceEntryIds,
195
+ });
196
+ result.forgotten++;
197
+ metadataUpdates.push({ id: target.id, status: "forgotten", sourceEntryIds: op.sourceEntryIds });
198
+ }
199
+ else {
200
+ result.invalidated++;
201
+ metadataUpdates.push({ id: target.id, status: "invalidated" });
202
+ }
161
203
  }
162
204
  else {
163
205
  result.missingTarget++;
@@ -169,11 +211,22 @@ export async function applyChannelMemoryOps(channelDir, ops, timestamp = new Dat
169
211
  continue;
170
212
  }
171
213
  if (target) {
172
- replacements.set(target.lineIndex, renderMemoryEntryLine(op.content, target.hasExplicitId ? target.id : generateMemoryEntryId()));
214
+ const replacementId = target.hasExplicitId ? target.id : generateMemoryEntryId();
215
+ replacements.set(target.lineIndex, renderMemoryEntryLine(op.content, replacementId));
216
+ if (replacementId !== target.id)
217
+ metadataUpdates.push({ id: target.id, status: "superseded" });
218
+ metadataUpdates.push({
219
+ id: replacementId,
220
+ status: "active",
221
+ metadata: op.metadata,
222
+ sourceEntryIds: op.sourceEntryIds,
223
+ });
173
224
  result.superseded++;
174
225
  }
175
226
  else {
176
- additions.push(op.content.trim());
227
+ const id = generateMemoryEntryId();
228
+ additions.push({ content: op.content.trim(), id });
229
+ metadataUpdates.push({ id, status: "active", metadata: op.metadata, sourceEntryIds: op.sourceEntryIds });
177
230
  result.downgradedToAdd++;
178
231
  result.missingTarget++;
179
232
  }
@@ -185,7 +238,7 @@ export async function applyChannelMemoryOps(channelDir, ops, timestamp = new Dat
185
238
  if (additions.length > 0) {
186
239
  const block = [
187
240
  `## Update ${timestamp}`,
188
- ...additions.map((content) => renderMemoryEntryLine(content, generateMemoryEntryId())),
241
+ ...additions.map(({ content, id }) => renderMemoryEntryLine(content, id)),
189
242
  ].join("\n");
190
243
  nextContent = `${ensureTrailingNewlines(nextContent)}${block}\n`;
191
244
  }
@@ -196,6 +249,7 @@ export async function applyChannelMemoryOps(channelDir, ops, timestamp = new Dat
196
249
  await backupBeforeRewrite(channelDir, path);
197
250
  }
198
251
  await writeFileAtomically(path, nextContent);
252
+ await syncMemoryMetadata(channelDir, parseChannelMemoryEntries(nextContent), metadataUpdates, timestamp);
199
253
  return result;
200
254
  }
201
255
  // Best-effort: a backup is a safety net, never a precondition for the write, so a
@@ -268,6 +322,7 @@ export async function rewriteChannelMemory(channelDir, content) {
268
322
  await backupBeforeRewrite(channelDir, path);
269
323
  const nextContent = normalizeContent(content) || DEFAULT_CHANNEL_MEMORY;
270
324
  await writeFileAtomically(path, nextContent);
325
+ await syncMemoryMetadata(channelDir, parseChannelMemoryEntries(nextContent));
271
326
  }
272
327
  export async function rewriteChannelHistory(channelDir, content) {
273
328
  await ensureChannelMemoryFiles(channelDir);
@@ -292,7 +347,9 @@ export async function appendChannelMemoryUpdate(channelDir, block) {
292
347
  `## Update ${block.timestamp}`,
293
348
  ...block.entries.map((entry) => renderMemoryEntryLine(entry, generateMemoryEntryId())),
294
349
  ].join("\n");
295
- await writeFileAtomically(path, `${ensureTrailingNewlines(existing)}${renderedBlock}\n`);
350
+ const nextContent = `${ensureTrailingNewlines(existing)}${renderedBlock}\n`;
351
+ await writeFileAtomically(path, nextContent);
352
+ await syncMemoryMetadata(channelDir, parseChannelMemoryEntries(nextContent), [], block.timestamp);
296
353
  }
297
354
  export function getChannelHistoryArchivePath(channelDir) {
298
355
  return join(channelDir, "HISTORY.archive.md");
@@ -3,11 +3,12 @@ import type { Api, Model } from "@earendil-works/pi-ai";
3
3
  import type { ExtensionFactory, SessionEntry } from "@earendil-works/pi-coding-agent";
4
4
  import type { PipiclawSessionMemorySettings } from "../settings.js";
5
5
  import { type ChannelMemoryQueue } from "./channel-maintenance-queue.js";
6
- import type { MemoryActivityEvent } from "./maintenance-state.js";
6
+ import { type MemoryActivityEvent } from "./maintenance-state.js";
7
7
  export type ConsolidationReason = "compaction" | "new-session" | "idle" | "shutdown";
8
8
  export interface MemoryLifecycleOptions {
9
9
  channelId: string;
10
10
  channelDir: string;
11
+ appHomeDir?: string;
11
12
  getMessages: () => AgentMessage[];
12
13
  getSessionEntries: () => SessionEntry[];
13
14
  getModel: () => Model<Api>;
@@ -2,8 +2,10 @@ import * as log from "../log.js";
2
2
  import { errorMessage } from "../shared/text-utils.js";
3
3
  import { getDefaultChannelMemoryQueue } from "./channel-maintenance-queue.js";
4
4
  import { runInlineConsolidation, } from "./consolidation.js";
5
+ import { readMemoryMaintenanceState, updateMemoryMaintenanceState, } from "./maintenance-state.js";
5
6
  import { appendMemoryReviewLog } from "./review-log.js";
6
7
  import { updateChannelSessionMemory } from "./session.js";
8
+ import { buildCompactionMemorySourceWindow, buildIncrementalMemorySourceWindow, } from "./source-window.js";
7
9
  export class MemoryLifecycle {
8
10
  constructor(options) {
9
11
  this.options = options;
@@ -15,7 +17,7 @@ export class MemoryLifecycle {
15
17
  this.backgroundNewSessionConsolidation = Promise.resolve();
16
18
  this.channelMemoryQueue = options.channelMemoryQueue ?? getDefaultChannelMemoryQueue();
17
19
  }
18
- buildRunOptions(messages, sessionEntries) {
20
+ buildRunOptions(messages, sessionEntries, sourceWindow) {
19
21
  return {
20
22
  channelId: this.options.channelId,
21
23
  channelDir: this.options.channelDir,
@@ -23,6 +25,7 @@ export class MemoryLifecycle {
23
25
  resolveApiKey: this.options.resolveApiKey,
24
26
  messages: messages ?? this.options.getMessages(),
25
27
  sessionEntries: sessionEntries ?? this.options.getSessionEntries(),
28
+ sourceWindow,
26
29
  };
27
30
  }
28
31
  createExtensionFactory() {
@@ -168,16 +171,16 @@ export class MemoryLifecycle {
168
171
  }
169
172
  await this.appendReviewLog({ reason, actions, skipped });
170
173
  }
171
- async runPreflightConsolidation(reason, messages, sessionEntries) {
174
+ async runPreflightConsolidation(reason, messages, sessionEntries, firstKeptEntryId) {
172
175
  const messageSnapshot = [...(messages ?? this.options.getMessages())];
173
176
  const sessionEntrySnapshot = sessionEntries ? [...sessionEntries] : [...this.options.getSessionEntries()];
174
177
  const revisionSnapshot = this.durableRevision;
175
178
  const settings = this.options.getSessionMemorySettings();
176
179
  await this.runDurableMemoryJobSerial(async () => {
177
- await this.runPreflightConsolidationNow(reason, messageSnapshot, sessionEntrySnapshot, revisionSnapshot, settings);
180
+ await this.runPreflightConsolidationNow(reason, messageSnapshot, sessionEntrySnapshot, revisionSnapshot, settings, firstKeptEntryId);
178
181
  });
179
182
  }
180
- async runPreflightConsolidationNow(reason, messageSnapshot, sessionEntrySnapshot, revisionSnapshot = this.durableRevision, settings = this.options.getSessionMemorySettings()) {
183
+ async runPreflightConsolidationNow(reason, messageSnapshot, sessionEntrySnapshot, revisionSnapshot = this.durableRevision, settings = this.options.getSessionMemorySettings(), firstKeptEntryId) {
181
184
  if (this.shouldForceRefreshFor(reason, settings)) {
182
185
  await this.runSessionRefreshSerial({
183
186
  reason,
@@ -185,11 +188,36 @@ export class MemoryLifecycle {
185
188
  });
186
189
  }
187
190
  try {
191
+ const maintenanceState = this.options.appHomeDir
192
+ ? await readMemoryMaintenanceState(this.options.appHomeDir, this.options.channelId)
193
+ : undefined;
194
+ const lastEntryId = maintenanceState?.lastConsolidatedEntryId;
195
+ const sourceWindow = reason === "compaction"
196
+ ? buildCompactionMemorySourceWindow({
197
+ entries: sessionEntrySnapshot ?? [],
198
+ messagesToSummarize: messageSnapshot,
199
+ firstKeptEntryId,
200
+ lastEntryId,
201
+ })
202
+ : buildIncrementalMemorySourceWindow({
203
+ entries: sessionEntrySnapshot ?? [],
204
+ lastEntryId,
205
+ sourceKind: reason,
206
+ fallbackMessages: messageSnapshot,
207
+ });
188
208
  log.logInfo(`[${this.options.channelId}] Memory consolidation starting (${reason})`);
189
209
  const result = await runInlineConsolidation({
190
- ...this.buildRunOptions(messageSnapshot, sessionEntrySnapshot),
210
+ ...this.buildRunOptions(messageSnapshot, sessionEntrySnapshot, sourceWindow),
191
211
  mode: "boundary",
192
212
  });
213
+ if (this.options.appHomeDir && sourceWindow.throughEntryId) {
214
+ await updateMemoryMaintenanceState(this.options.appHomeDir, this.options.channelId, (current) => ({
215
+ ...current,
216
+ lastConsolidatedEntryId: sourceWindow.throughEntryId,
217
+ lastDurableConsolidationAt: new Date().toISOString(),
218
+ failureBackoffUntil: null,
219
+ }));
220
+ }
193
221
  this.markDurableConsolidationCheckpoint(revisionSnapshot);
194
222
  this.logConsolidationResult(reason, result);
195
223
  await this.recordConsolidationReview(reason, result);
@@ -205,7 +233,7 @@ export class MemoryLifecycle {
205
233
  }
206
234
  }
207
235
  async handleSessionBeforeCompact(event) {
208
- await this.runPreflightConsolidation("compaction", event.preparation.messagesToSummarize);
236
+ await this.runPreflightConsolidation("compaction", event.preparation.messagesToSummarize, this.options.getSessionEntries(), event.preparation.firstKeptEntryId);
209
237
  }
210
238
  handleSessionCompact(_event) {
211
239
  this.recordActivity("boundary");