@oyasmi/pipiclaw 0.8.5 → 0.8.7-beta.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/agent/channel-runner.d.ts +1 -0
- package/dist/agent/channel-runner.js +27 -10
- package/dist/agent/command-extension.d.ts +1 -0
- package/dist/agent/command-extension.js +6 -0
- package/dist/agent/commands.js +6 -0
- package/dist/agent/session-events.js +17 -5
- package/dist/agent/types.d.ts +1 -0
- package/dist/log.d.ts +12 -20
- package/dist/log.js +195 -198
- package/dist/memory/bootstrap.d.ts +5 -0
- package/dist/memory/bootstrap.js +14 -4
- package/dist/memory/candidates.d.ts +2 -0
- package/dist/memory/candidates.js +13 -3
- package/dist/memory/commands.d.ts +6 -0
- package/dist/memory/commands.js +112 -0
- package/dist/memory/consolidation.d.ts +3 -0
- package/dist/memory/consolidation.js +68 -26
- package/dist/memory/files.d.ts +13 -0
- package/dist/memory/files.js +65 -8
- package/dist/memory/lifecycle.d.ts +2 -1
- package/dist/memory/lifecycle.js +38 -7
- package/dist/memory/maintenance-jobs.js +48 -23
- package/dist/memory/metadata.d.ts +60 -0
- package/dist/memory/metadata.js +135 -0
- package/dist/memory/policy.d.ts +3 -0
- package/dist/memory/policy.js +19 -0
- package/dist/memory/post-turn-review.d.ts +11 -1
- package/dist/memory/post-turn-review.js +78 -19
- package/dist/memory/promotion.d.ts +5 -2
- package/dist/memory/promotion.js +3 -1
- package/dist/memory/recall.d.ts +3 -0
- package/dist/memory/recall.js +27 -5
- package/dist/memory/review-log.d.ts +2 -0
- package/dist/memory/review-log.js +15 -0
- package/dist/memory/session-corpus.js +11 -3
- package/dist/memory/session-search.js +8 -4
- package/dist/memory/session.d.ts +1 -0
- package/dist/memory/session.js +3 -1
- package/dist/memory/sidecar-worker.d.ts +1 -0
- package/dist/memory/sidecar-worker.js +1 -0
- package/dist/memory/source-window.d.ts +25 -0
- package/dist/memory/source-window.js +64 -0
- package/dist/memory/tombstones.d.ts +12 -0
- package/dist/memory/tombstones.js +44 -0
- package/dist/memory/transcript.js +26 -3
- package/dist/runtime/bootstrap.d.ts +1 -0
- package/dist/runtime/bootstrap.js +42 -11
- package/dist/runtime/dingtalk.js +19 -6
- package/dist/runtime/events.d.ts +2 -0
- package/dist/runtime/events.js +14 -7
- package/dist/runtime/store.d.ts +4 -6
- package/dist/runtime/store.js +44 -40
- package/dist/runtime/task-commands.js +1 -1
- package/dist/security/logger.d.ts +3 -1
- package/dist/security/logger.js +33 -10
- package/dist/settings.js +1 -1
- package/dist/shared/jsonl-appender.d.ts +27 -8
- package/dist/shared/jsonl-appender.js +128 -41
- package/dist/tasks/control.js +9 -3
- package/dist/tasks/store.d.ts +1 -0
- package/dist/tasks/store.js +11 -1
- package/dist/tools/bash.js +1 -1
- package/dist/tools/edit.js +1 -1
- package/dist/tools/grep.js +1 -1
- package/dist/tools/memory-manage.d.ts +1 -1
- package/dist/tools/memory-manage.js +27 -6
- package/dist/tools/read.js +1 -1
- package/dist/tools/task-manage.js +2 -2
- package/dist/tools/write-content.js +1 -1
- package/dist/tui/app.js +17 -0
- package/dist/usage/ledger.d.ts +4 -0
- package/dist/usage/ledger.js +3 -1
- package/dist/web/client.js +3 -3
- package/package.json +1 -1
|
@@ -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
|
|
247
|
-
|
|
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
|
|
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
|
-
|
|
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",
|
package/dist/memory/files.d.ts
CHANGED
|
@@ -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,
|
package/dist/memory/files.js
CHANGED
|
@@ -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
|
|
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
|
-
|
|
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
|
-
|
|
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
|
-
|
|
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
|
-
|
|
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,
|
|
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
|
-
|
|
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
|
|
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>;
|
package/dist/memory/lifecycle.js
CHANGED
|
@@ -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() {
|
|
@@ -129,7 +132,10 @@ export class MemoryLifecycle {
|
|
|
129
132
|
}
|
|
130
133
|
logConsolidationResult(reason, result) {
|
|
131
134
|
if (result.skipped) {
|
|
132
|
-
log.
|
|
135
|
+
log.logEvent("debug", "memory.consolidation.skipped", "No meaningful snapshot", {
|
|
136
|
+
ctx: { channelId: this.options.channelId },
|
|
137
|
+
fields: { reason },
|
|
138
|
+
});
|
|
133
139
|
return;
|
|
134
140
|
}
|
|
135
141
|
log.logInfo(`[${this.options.channelId}] Memory consolidation finished (${reason}): memory entries=${result.appendedMemoryEntries}, history=${result.appendedHistoryBlock ? "yes" : "no"}`);
|
|
@@ -168,16 +174,16 @@ export class MemoryLifecycle {
|
|
|
168
174
|
}
|
|
169
175
|
await this.appendReviewLog({ reason, actions, skipped });
|
|
170
176
|
}
|
|
171
|
-
async runPreflightConsolidation(reason, messages, sessionEntries) {
|
|
177
|
+
async runPreflightConsolidation(reason, messages, sessionEntries, firstKeptEntryId) {
|
|
172
178
|
const messageSnapshot = [...(messages ?? this.options.getMessages())];
|
|
173
179
|
const sessionEntrySnapshot = sessionEntries ? [...sessionEntries] : [...this.options.getSessionEntries()];
|
|
174
180
|
const revisionSnapshot = this.durableRevision;
|
|
175
181
|
const settings = this.options.getSessionMemorySettings();
|
|
176
182
|
await this.runDurableMemoryJobSerial(async () => {
|
|
177
|
-
await this.runPreflightConsolidationNow(reason, messageSnapshot, sessionEntrySnapshot, revisionSnapshot, settings);
|
|
183
|
+
await this.runPreflightConsolidationNow(reason, messageSnapshot, sessionEntrySnapshot, revisionSnapshot, settings, firstKeptEntryId);
|
|
178
184
|
});
|
|
179
185
|
}
|
|
180
|
-
async runPreflightConsolidationNow(reason, messageSnapshot, sessionEntrySnapshot, revisionSnapshot = this.durableRevision, settings = this.options.getSessionMemorySettings()) {
|
|
186
|
+
async runPreflightConsolidationNow(reason, messageSnapshot, sessionEntrySnapshot, revisionSnapshot = this.durableRevision, settings = this.options.getSessionMemorySettings(), firstKeptEntryId) {
|
|
181
187
|
if (this.shouldForceRefreshFor(reason, settings)) {
|
|
182
188
|
await this.runSessionRefreshSerial({
|
|
183
189
|
reason,
|
|
@@ -185,11 +191,36 @@ export class MemoryLifecycle {
|
|
|
185
191
|
});
|
|
186
192
|
}
|
|
187
193
|
try {
|
|
194
|
+
const maintenanceState = this.options.appHomeDir
|
|
195
|
+
? await readMemoryMaintenanceState(this.options.appHomeDir, this.options.channelId)
|
|
196
|
+
: undefined;
|
|
197
|
+
const lastEntryId = maintenanceState?.lastConsolidatedEntryId;
|
|
198
|
+
const sourceWindow = reason === "compaction"
|
|
199
|
+
? buildCompactionMemorySourceWindow({
|
|
200
|
+
entries: sessionEntrySnapshot ?? [],
|
|
201
|
+
messagesToSummarize: messageSnapshot,
|
|
202
|
+
firstKeptEntryId,
|
|
203
|
+
lastEntryId,
|
|
204
|
+
})
|
|
205
|
+
: buildIncrementalMemorySourceWindow({
|
|
206
|
+
entries: sessionEntrySnapshot ?? [],
|
|
207
|
+
lastEntryId,
|
|
208
|
+
sourceKind: reason,
|
|
209
|
+
fallbackMessages: messageSnapshot,
|
|
210
|
+
});
|
|
188
211
|
log.logInfo(`[${this.options.channelId}] Memory consolidation starting (${reason})`);
|
|
189
212
|
const result = await runInlineConsolidation({
|
|
190
|
-
...this.buildRunOptions(messageSnapshot, sessionEntrySnapshot),
|
|
213
|
+
...this.buildRunOptions(messageSnapshot, sessionEntrySnapshot, sourceWindow),
|
|
191
214
|
mode: "boundary",
|
|
192
215
|
});
|
|
216
|
+
if (this.options.appHomeDir && sourceWindow.throughEntryId) {
|
|
217
|
+
await updateMemoryMaintenanceState(this.options.appHomeDir, this.options.channelId, (current) => ({
|
|
218
|
+
...current,
|
|
219
|
+
lastConsolidatedEntryId: sourceWindow.throughEntryId,
|
|
220
|
+
lastDurableConsolidationAt: new Date().toISOString(),
|
|
221
|
+
failureBackoffUntil: null,
|
|
222
|
+
}));
|
|
223
|
+
}
|
|
193
224
|
this.markDurableConsolidationCheckpoint(revisionSnapshot);
|
|
194
225
|
this.logConsolidationResult(reason, result);
|
|
195
226
|
await this.recordConsolidationReview(reason, result);
|
|
@@ -205,7 +236,7 @@ export class MemoryLifecycle {
|
|
|
205
236
|
}
|
|
206
237
|
}
|
|
207
238
|
async handleSessionBeforeCompact(event) {
|
|
208
|
-
await this.runPreflightConsolidation("compaction", event.preparation.messagesToSummarize);
|
|
239
|
+
await this.runPreflightConsolidation("compaction", event.preparation.messagesToSummarize, this.options.getSessionEntries(), event.preparation.firstKeptEntryId);
|
|
209
240
|
}
|
|
210
241
|
handleSessionCompact(_event) {
|
|
211
242
|
this.recordActivity("boundary");
|