@oyasmi/pipiclaw 0.8.5 → 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 (53) hide show
  1. package/dist/agent/channel-runner.d.ts +1 -0
  2. package/dist/agent/channel-runner.js +19 -8
  3. package/dist/agent/command-extension.d.ts +1 -0
  4. package/dist/agent/command-extension.js +6 -0
  5. package/dist/agent/commands.js +6 -0
  6. package/dist/agent/types.d.ts +1 -0
  7. package/dist/memory/bootstrap.d.ts +5 -0
  8. package/dist/memory/bootstrap.js +14 -4
  9. package/dist/memory/candidates.d.ts +2 -0
  10. package/dist/memory/candidates.js +13 -3
  11. package/dist/memory/commands.d.ts +6 -0
  12. package/dist/memory/commands.js +112 -0
  13. package/dist/memory/consolidation.d.ts +3 -0
  14. package/dist/memory/consolidation.js +68 -26
  15. package/dist/memory/files.d.ts +13 -0
  16. package/dist/memory/files.js +65 -8
  17. package/dist/memory/lifecycle.d.ts +2 -1
  18. package/dist/memory/lifecycle.js +34 -6
  19. package/dist/memory/maintenance-jobs.js +48 -23
  20. package/dist/memory/metadata.d.ts +60 -0
  21. package/dist/memory/metadata.js +135 -0
  22. package/dist/memory/policy.d.ts +3 -0
  23. package/dist/memory/policy.js +19 -0
  24. package/dist/memory/post-turn-review.d.ts +11 -1
  25. package/dist/memory/post-turn-review.js +78 -19
  26. package/dist/memory/promotion.d.ts +5 -2
  27. package/dist/memory/promotion.js +3 -1
  28. package/dist/memory/recall.d.ts +3 -0
  29. package/dist/memory/recall.js +27 -5
  30. package/dist/memory/review-log.d.ts +2 -0
  31. package/dist/memory/review-log.js +15 -0
  32. package/dist/memory/session-corpus.js +11 -3
  33. package/dist/memory/session-search.js +8 -4
  34. package/dist/memory/session.d.ts +1 -0
  35. package/dist/memory/session.js +3 -1
  36. package/dist/memory/sidecar-worker.d.ts +1 -0
  37. package/dist/memory/sidecar-worker.js +1 -0
  38. package/dist/memory/source-window.d.ts +25 -0
  39. package/dist/memory/source-window.js +64 -0
  40. package/dist/memory/tombstones.d.ts +12 -0
  41. package/dist/memory/tombstones.js +44 -0
  42. package/dist/memory/transcript.js +26 -3
  43. package/dist/runtime/bootstrap.js +1 -0
  44. package/dist/runtime/task-commands.js +1 -1
  45. package/dist/settings.js +1 -1
  46. package/dist/tasks/control.js +9 -3
  47. package/dist/tasks/store.d.ts +1 -0
  48. package/dist/tasks/store.js +11 -1
  49. package/dist/tools/memory-manage.d.ts +1 -1
  50. package/dist/tools/memory-manage.js +27 -6
  51. package/dist/tools/task-manage.js +2 -2
  52. package/dist/usage/ledger.d.ts +2 -0
  53. package/package.json +1 -1
@@ -53,6 +53,7 @@ export declare class ChannelRunner implements AgentRunner {
53
53
  errorMessage?: string;
54
54
  usage: UsageTotals;
55
55
  durationMs: number;
56
+ silent: boolean;
56
57
  }>;
57
58
  handleBuiltinCommand(ctx: ChannelContext, command: RunnerBuiltInCommand): Promise<void>;
58
59
  /**
@@ -4,8 +4,9 @@ import { mkdir, readFile, writeFile } from "fs/promises";
4
4
  import { dirname, join, resolve } from "path";
5
5
  import { createExecutor } from "../executor.js";
6
6
  import * as log from "../log.js";
7
- import { buildFirstTurnMemoryBootstrap as renderFirstTurnMemoryBootstrap } from "../memory/bootstrap.js";
7
+ import { buildFirstTurnMemoryBootstrapResult } from "../memory/bootstrap.js";
8
8
  import { createMemoryCandidateStore } from "../memory/candidates.js";
9
+ import { handleMemoryCommand } from "../memory/commands.js";
9
10
  import { getChannelMemoryPath } from "../memory/files.js";
10
11
  import { MemoryLifecycle } from "../memory/lifecycle.js";
11
12
  import { applyMemoryActivityToState, updateMemoryMaintenanceState, } from "../memory/maintenance-state.js";
@@ -106,6 +107,7 @@ export class ChannelRunner {
106
107
  this.memoryLifecycle = new MemoryLifecycle({
107
108
  channelId: this.channelId,
108
109
  channelDir: this.channelDir,
110
+ appHomeDir: this.appHomeDir,
109
111
  getMessages: () => this.session.messages,
110
112
  getSessionEntries: () => this.sessionManager.getBranch(),
111
113
  getModel: () => this.session.model ?? this.activeModel,
@@ -190,6 +192,8 @@ export class ChannelRunner {
190
192
  let recalledContextText = "";
191
193
  let taskDigestText = "";
192
194
  let durableMemoryBootstrapText = "";
195
+ let bootstrapCandidateIds = [];
196
+ let bootstrapPrepared = false;
193
197
  try {
194
198
  await this.ensureSessionReady();
195
199
  await this.maybeRestorePrimaryModel();
@@ -208,6 +212,12 @@ export class ChannelRunner {
208
212
  // Channel facts are turn-dynamic by design (spec 025 §7.3): keeping them out of the
209
213
  // system prompt is what lets every channel in a workspace share one cached prefix.
210
214
  promptText = `${this.renderChannelTurnContext()}\n\n<user_message>\n${promptText}\n</user_message>`;
215
+ if (this.firstTurnMemoryBootstrapPending) {
216
+ const bootstrap = await this.buildFirstTurnMemoryBootstrap();
217
+ durableMemoryBootstrapText = bootstrap.renderedText;
218
+ bootstrapCandidateIds = bootstrap.includedCandidateIds;
219
+ bootstrapPrepared = true;
220
+ }
211
221
  const recallSettings = this.settingsManager.getMemoryRecallSettings();
212
222
  if (recallSettings.enabled) {
213
223
  const recall = await recallRelevantMemory({
@@ -219,6 +229,7 @@ export class ChannelRunner {
219
229
  maxInjected: recallSettings.maxInjected,
220
230
  maxChars: recallSettings.maxChars,
221
231
  rerankWithModel: recallSettings.rerankWithModel,
232
+ excludedCandidateIds: bootstrapCandidateIds,
222
233
  // Let shouldUseModelRerank's own memory-intent gate decide (it already handles
223
234
  // Chinese phrasing) — forcing autoRerank for every Han-script message triggered a
224
235
  // model rerank (up to 8s) on nearly every Chinese turn once memory filled up.
@@ -243,12 +254,8 @@ export class ChannelRunner {
243
254
  promptText = `${taskDigestText}\n\n${promptText}`;
244
255
  }
245
256
  }
246
- if (this.firstTurnMemoryBootstrapPending) {
247
- durableMemoryBootstrapText = await this.buildFirstTurnMemoryBootstrap();
248
- if (durableMemoryBootstrapText) {
249
- promptText = `${durableMemoryBootstrapText}\n\n${promptText}`;
250
- }
251
- this.firstTurnMemoryBootstrapPending = false;
257
+ if (durableMemoryBootstrapText) {
258
+ promptText = `${durableMemoryBootstrapText}\n\n${promptText}`;
252
259
  }
253
260
  }
254
261
  // Estimated against the fully assembled prompt (recall + task digest + bootstrap all
@@ -267,6 +274,8 @@ export class ChannelRunner {
267
274
  await this.sessionResourceGate.runPrompt(async () => {
268
275
  await this.session.prompt(text);
269
276
  promptSubmitted = true;
277
+ if (bootstrapPrepared)
278
+ this.firstTurnMemoryBootstrapPending = false;
270
279
  });
271
280
  }
272
281
  catch (err) {
@@ -457,6 +466,7 @@ export class ChannelRunner {
457
466
  errorMessage: this.runState.errorMessage,
458
467
  usage: { ...this.runState.totalUsage, cost: { ...this.runState.totalUsage.cost } },
459
468
  durationMs: Date.now() - startedAt,
469
+ silent: this.runState.finalOutcome.kind === "silent",
460
470
  };
461
471
  }
462
472
  async handleBuiltinCommand(ctx, command) {
@@ -882,6 +892,7 @@ export class ChannelRunner {
882
892
  refreshSessionResources: async () => {
883
893
  await this.refreshSessionResources();
884
894
  },
895
+ runMemoryCommand: async (args) => handleMemoryCommand({ channelDir: this.channelDir, args }),
885
896
  }),
886
897
  ],
887
898
  // Pipiclaw owns the base prompt: with a custom prompt present, pi emits no
@@ -1028,7 +1039,7 @@ export class ChannelRunner {
1028
1039
  readOptionalFile(getChannelMemoryPath(this.channelDir)),
1029
1040
  readOptionalFile(join(this.workspaceDir, "MEMORY.md")),
1030
1041
  ]);
1031
- return renderFirstTurnMemoryBootstrap({
1042
+ return buildFirstTurnMemoryBootstrapResult({
1032
1043
  channelMemory,
1033
1044
  workspaceMemory,
1034
1045
  });
@@ -10,5 +10,6 @@ export interface PipiclawCommandExtensionOptions {
10
10
  getLastResponseModel?: () => string | undefined;
11
11
  switchModel: (model: Model<Api>) => Promise<void>;
12
12
  refreshSessionResources: () => Promise<void>;
13
+ runMemoryCommand: (args: string) => Promise<string>;
13
14
  }
14
15
  export declare function createCommandExtension(options: PipiclawCommandExtensionOptions): ExtensionFactory;
@@ -41,6 +41,12 @@ function sendCommandResult(sender, text) {
41
41
  }
42
42
  export function createCommandExtension(options) {
43
43
  return (pi) => {
44
+ pi.registerCommand("memory", {
45
+ description: sessionCommandDescription("memory"),
46
+ handler: async (args) => {
47
+ sendCommandResult(pi, await options.runMemoryCommand(args));
48
+ },
49
+ });
44
50
  pi.registerCommand("session", {
45
51
  description: sessionCommandDescription("session"),
46
52
  handler: async () => {
@@ -87,6 +87,12 @@ export const BUILT_IN_COMMANDS = [
87
87
  * extension registration in `command-extension.ts`.
88
88
  */
89
89
  export const SESSION_COMMANDS = [
90
+ {
91
+ name: "memory",
92
+ argumentHint: "[status|list|show <id>|pending]",
93
+ description: "Inspect active memory, metadata, recall statistics, tombstones, and pending suggestions",
94
+ examples: ["/memory status", "/memory list", "/memory show m-1234abcd", "/memory pending"],
95
+ },
90
96
  {
91
97
  name: "session",
92
98
  description: "Show current session state, message stats, token usage, and model info",
@@ -38,6 +38,7 @@ export interface AgentRunner {
38
38
  errorMessage?: string;
39
39
  usage?: UsageTotals;
40
40
  durationMs?: number;
41
+ silent?: boolean;
41
42
  }>;
42
43
  handleBuiltinCommand(ctx: ChannelContext, command: RunnerBuiltInCommand): Promise<void>;
43
44
  /** True if `text` is a slash command the runtime or session layer can handle. */
@@ -3,4 +3,9 @@ export interface FirstTurnMemoryBootstrapOptions {
3
3
  workspaceMemory: string;
4
4
  maxChars?: number;
5
5
  }
6
+ export interface FirstTurnMemoryBootstrapResult {
7
+ renderedText: string;
8
+ includedCandidateIds: string[];
9
+ }
6
10
  export declare function buildFirstTurnMemoryBootstrap(options: FirstTurnMemoryBootstrapOptions): string;
11
+ export declare function buildFirstTurnMemoryBootstrapResult(options: FirstTurnMemoryBootstrapOptions): FirstTurnMemoryBootstrapResult;
@@ -1,5 +1,7 @@
1
1
  import { splitH2Sections } from "../shared/markdown-sections.js";
2
2
  import { clipText } from "../shared/text-utils.js";
3
+ import { buildMemoryCandidateId } from "./candidates.js";
4
+ import { parseChannelMemoryEntries } from "./files.js";
3
5
  const FIRST_TURN_MEMORY_SNAPSHOT_MAX_CHARS = 3_000;
4
6
  const MIN_SECTION_BUDGET = 600;
5
7
  const CHANNEL_MEMORY_WEIGHT = 0.6;
@@ -55,11 +57,14 @@ function allocateBudgets(channelMemory, workspaceMemory, maxChars) {
55
57
  return [channelBudget + Math.max(0, remainder), workspaceBudget];
56
58
  }
57
59
  export function buildFirstTurnMemoryBootstrap(options) {
60
+ return buildFirstTurnMemoryBootstrapResult(options).renderedText;
61
+ }
62
+ export function buildFirstTurnMemoryBootstrapResult(options) {
58
63
  const maxChars = options.maxChars ?? FIRST_TURN_MEMORY_SNAPSHOT_MAX_CHARS;
59
64
  const channelMemory = normalizeContent(options.channelMemory);
60
65
  const workspaceMemory = normalizeContent(options.workspaceMemory);
61
66
  if (!channelMemory && !workspaceMemory) {
62
- return "";
67
+ return { renderedText: "", includedCandidateIds: [] };
63
68
  }
64
69
  const [channelBudget, workspaceBudget] = allocateBudgets(channelMemory, workspaceMemory, maxChars);
65
70
  const sections = [
@@ -67,14 +72,19 @@ export function buildFirstTurnMemoryBootstrap(options) {
67
72
  "Durable memory bootstrap for the first user turn in this session.",
68
73
  "Use it as background context together with any turn-specific recalled snippets.",
69
74
  ];
75
+ const includedCandidateIds = [];
70
76
  if (channelMemory) {
77
+ const selectedChannelMemory = channelBudget > 0 ? selectChannelMemoryForBootstrap(channelMemory, channelBudget) : channelMemory;
71
78
  sections.push("", "[Channel MEMORY.md]");
72
- sections.push(channelBudget > 0 ? selectChannelMemoryForBootstrap(channelMemory, channelBudget) : channelMemory);
79
+ sections.push(selectedChannelMemory);
80
+ includedCandidateIds.push(...parseChannelMemoryEntries(selectedChannelMemory).map((entry) => entry.id));
73
81
  }
74
82
  if (workspaceMemory) {
83
+ const selectedWorkspaceMemory = workspaceBudget > 0 ? clipText(workspaceMemory, workspaceBudget, { headRatio: 1 }) : workspaceMemory;
75
84
  sections.push("", "[Workspace MEMORY.md]");
76
- sections.push(workspaceBudget > 0 ? clipText(workspaceMemory, workspaceBudget, { headRatio: 1 }) : workspaceMemory);
85
+ sections.push(selectedWorkspaceMemory);
86
+ includedCandidateIds.push(...splitH2Sections(selectedWorkspaceMemory).map((section) => buildMemoryCandidateId("workspace-memory", section.heading)));
77
87
  }
78
88
  sections.push("</durable_memory_snapshot>");
79
- return sections.join("\n");
89
+ return { renderedText: sections.join("\n"), includedCandidateIds };
80
90
  }
@@ -8,11 +8,13 @@ export interface MemoryCandidate {
8
8
  timestamp?: string;
9
9
  sectionKind?: string;
10
10
  priority: number;
11
+ entryId?: string;
11
12
  }
12
13
  export interface BuildMemoryCandidatesOptions {
13
14
  workspaceDir: string;
14
15
  channelDir: string;
15
16
  }
17
+ export declare function buildMemoryCandidateId(source: MemoryCandidate["source"], title: string, timestamp?: string): string;
16
18
  export declare class MemoryCandidateStore {
17
19
  private files;
18
20
  private inflight;
@@ -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,