@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.
- package/dist/agent/channel-runner.d.ts +1 -0
- package/dist/agent/channel-runner.js +19 -8
- 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/types.d.ts +1 -0
- 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 +34 -6
- 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.js +1 -0
- package/dist/runtime/task-commands.js +1 -1
- package/dist/settings.js +1 -1
- 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/memory-manage.d.ts +1 -1
- package/dist/tools/memory-manage.js +27 -6
- package/dist/tools/task-manage.js +2 -2
- package/dist/usage/ledger.d.ts +2 -0
- package/package.json +1 -1
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() {
|
|
@@ -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");
|
|
@@ -8,17 +8,11 @@ import { runPostTurnReview } from "./post-turn-review.js";
|
|
|
8
8
|
import { scanPromotionSignals } from "./promotion-signals.js";
|
|
9
9
|
import { appendMemoryReviewLog } from "./review-log.js";
|
|
10
10
|
import { updateChannelSessionMemory } from "./session.js";
|
|
11
|
+
import { buildIncrementalMemorySourceWindow } from "./source-window.js";
|
|
11
12
|
import { sanitizeMessagesForMemory } from "./transcript.js";
|
|
12
13
|
function latestEntryId(entries) {
|
|
13
14
|
return entries.at(-1)?.id;
|
|
14
15
|
}
|
|
15
|
-
function entriesSince(entries, lastEntryId) {
|
|
16
|
-
if (!lastEntryId) {
|
|
17
|
-
return entries;
|
|
18
|
-
}
|
|
19
|
-
const index = entries.findIndex((entry) => entry.id === lastEntryId);
|
|
20
|
-
return index >= 0 ? entries.slice(index + 1) : entries;
|
|
21
|
-
}
|
|
22
16
|
function messageToText(message) {
|
|
23
17
|
if (message.role === "user") {
|
|
24
18
|
return typeof message.content === "string"
|
|
@@ -57,7 +51,7 @@ function hasMeaningfulMessages(messages) {
|
|
|
57
51
|
function renderMessagesForSignalScan(messages) {
|
|
58
52
|
return sanitizeMessagesForMemory(messages).map(messageToText).join("\n");
|
|
59
53
|
}
|
|
60
|
-
function makeRunOptions(input) {
|
|
54
|
+
function makeRunOptions(input, usageCorrelationId) {
|
|
61
55
|
return {
|
|
62
56
|
channelId: input.channelId,
|
|
63
57
|
channelDir: input.channelDir,
|
|
@@ -65,6 +59,7 @@ function makeRunOptions(input) {
|
|
|
65
59
|
resolveApiKey: input.resolveApiKey,
|
|
66
60
|
messages: input.messages,
|
|
67
61
|
sessionEntries: input.sessionEntries,
|
|
62
|
+
usageCorrelationId,
|
|
68
63
|
};
|
|
69
64
|
}
|
|
70
65
|
function backoffUntil(now, settings) {
|
|
@@ -114,6 +109,7 @@ export async function runSessionRefreshJob(input) {
|
|
|
114
109
|
return skipped(decision.jobKind, decision.skipReason ?? "skipped");
|
|
115
110
|
}
|
|
116
111
|
try {
|
|
112
|
+
const correlationId = `session-refresh:${latestId ?? now.toISOString()}`;
|
|
117
113
|
await updateChannelSessionMemory({
|
|
118
114
|
channelId: input.channelId,
|
|
119
115
|
channelDir: input.channelDir,
|
|
@@ -121,6 +117,7 @@ export async function runSessionRefreshJob(input) {
|
|
|
121
117
|
model: input.model,
|
|
122
118
|
resolveApiKey: input.resolveApiKey,
|
|
123
119
|
timeoutMs: input.settings.sessionMemory.timeoutMs,
|
|
120
|
+
usageCorrelationId: correlationId,
|
|
124
121
|
});
|
|
125
122
|
await updateMemoryMaintenanceState(input.appHomeDir, input.channelId, (current) => ({
|
|
126
123
|
...current,
|
|
@@ -131,7 +128,7 @@ export async function runSessionRefreshJob(input) {
|
|
|
131
128
|
lastSessionEntryId: latestId ?? current.lastSessionEntryId,
|
|
132
129
|
failureBackoffUntil: null,
|
|
133
130
|
}));
|
|
134
|
-
await appendJobReviewLog(input.channelDir, input.channelId, "session-refresh-job", { actions: [{ target: "SESSION.md", action: "rewrite" }] }, now);
|
|
131
|
+
await appendJobReviewLog(input.channelDir, input.channelId, "session-refresh-job", { actions: [{ target: "SESSION.md", action: "rewrite" }], correlationId }, now);
|
|
135
132
|
return ran("session-refresh");
|
|
136
133
|
}
|
|
137
134
|
catch (error) {
|
|
@@ -149,7 +146,13 @@ export async function runDurableConsolidationJob(input) {
|
|
|
149
146
|
return runQueued(input, async () => {
|
|
150
147
|
const now = input.now ?? new Date();
|
|
151
148
|
const state = await readMemoryMaintenanceState(input.appHomeDir, input.channelId);
|
|
152
|
-
const
|
|
149
|
+
const sourceWindow = buildIncrementalMemorySourceWindow({
|
|
150
|
+
entries: input.sessionEntries,
|
|
151
|
+
lastEntryId: state.lastConsolidatedEntryId,
|
|
152
|
+
sourceKind: "idle",
|
|
153
|
+
fallbackMessages: input.messages,
|
|
154
|
+
});
|
|
155
|
+
const newEntries = sourceWindow.entries;
|
|
153
156
|
const latestId = latestEntryId(input.sessionEntries);
|
|
154
157
|
const decision = shouldRunDurableConsolidation({
|
|
155
158
|
now,
|
|
@@ -157,7 +160,7 @@ export async function runDurableConsolidationJob(input) {
|
|
|
157
160
|
maintenance: input.settings.memoryMaintenance,
|
|
158
161
|
channelActive: input.channelActive,
|
|
159
162
|
hasNewEntry: newEntries.length > 0,
|
|
160
|
-
hasMeaningfulExchange: hasMeaningfulMessages(
|
|
163
|
+
hasMeaningfulExchange: hasMeaningfulMessages(sourceWindow.messages),
|
|
161
164
|
batchSize: newEntries.length,
|
|
162
165
|
coveredByGrowthReview: Boolean(latestId && state.lastReviewedEntryId === latestId),
|
|
163
166
|
});
|
|
@@ -168,17 +171,24 @@ export async function runDurableConsolidationJob(input) {
|
|
|
168
171
|
try {
|
|
169
172
|
const result = await runInlineConsolidation({
|
|
170
173
|
...makeRunOptions(input),
|
|
174
|
+
sourceWindow,
|
|
171
175
|
mode: "idle",
|
|
172
176
|
});
|
|
173
177
|
await updateMemoryMaintenanceState(input.appHomeDir, input.channelId, (current) => ({
|
|
174
178
|
...current,
|
|
175
179
|
lastDurableConsolidationAt: now.toISOString(),
|
|
176
|
-
lastConsolidatedEntryId:
|
|
180
|
+
lastConsolidatedEntryId: sourceWindow.throughEntryId ?? current.lastConsolidatedEntryId,
|
|
177
181
|
failureBackoffUntil: null,
|
|
178
182
|
}));
|
|
179
183
|
await appendJobReviewLog(input.channelDir, input.channelId, "durable-consolidation-job", result.skipped
|
|
180
|
-
? {
|
|
181
|
-
|
|
184
|
+
? {
|
|
185
|
+
skipped: [{ target: "consolidation", reason: "no meaningful snapshot" }],
|
|
186
|
+
correlationId: sourceWindow.windowId,
|
|
187
|
+
}
|
|
188
|
+
: {
|
|
189
|
+
actions: [{ target: "MEMORY.md", action: "append", entries: result.appendedMemoryEntries }],
|
|
190
|
+
correlationId: sourceWindow.windowId,
|
|
191
|
+
}, now);
|
|
182
192
|
return ran("durable-consolidation");
|
|
183
193
|
}
|
|
184
194
|
catch (error) {
|
|
@@ -196,9 +206,14 @@ export async function runGrowthReviewJob(input) {
|
|
|
196
206
|
return runQueued(input, async () => {
|
|
197
207
|
const now = input.now ?? new Date();
|
|
198
208
|
const state = await readMemoryMaintenanceState(input.appHomeDir, input.channelId);
|
|
199
|
-
const
|
|
200
|
-
|
|
201
|
-
|
|
209
|
+
const sourceWindow = buildIncrementalMemorySourceWindow({
|
|
210
|
+
entries: input.sessionEntries,
|
|
211
|
+
lastEntryId: state.lastReviewedEntryId,
|
|
212
|
+
sourceKind: "growth-review",
|
|
213
|
+
fallbackMessages: input.messages,
|
|
214
|
+
});
|
|
215
|
+
const newEntries = sourceWindow.entries;
|
|
216
|
+
const signalScan = scanPromotionSignals(renderMessagesForSignalScan(sourceWindow.messages));
|
|
202
217
|
const decision = shouldRunGrowthReview({
|
|
203
218
|
now,
|
|
204
219
|
state,
|
|
@@ -206,7 +221,7 @@ export async function runGrowthReviewJob(input) {
|
|
|
206
221
|
maintenance: input.settings.memoryMaintenance,
|
|
207
222
|
channelActive: input.channelActive,
|
|
208
223
|
hasNewEntry: newEntries.length > 0,
|
|
209
|
-
hasMeaningfulMaterial: hasMeaningfulMessages(
|
|
224
|
+
hasMeaningfulMaterial: hasMeaningfulMessages(sourceWindow.messages),
|
|
210
225
|
hasPromotionSignal: signalScan.hasSignal,
|
|
211
226
|
});
|
|
212
227
|
if (!decision.allowed) {
|
|
@@ -219,7 +234,9 @@ export async function runGrowthReviewJob(input) {
|
|
|
219
234
|
channelId: input.channelId,
|
|
220
235
|
channelDir: input.channelDir,
|
|
221
236
|
workspaceDir: input.workspaceDir,
|
|
222
|
-
messages:
|
|
237
|
+
messages: sourceWindow.messages,
|
|
238
|
+
sourceEntryIds: sourceWindow.entries.map((entry) => entry.id),
|
|
239
|
+
suppressAutomaticWrites: sourceWindow.hasExternalToolContent,
|
|
223
240
|
model: input.model,
|
|
224
241
|
resolveApiKey: input.resolveApiKey,
|
|
225
242
|
timeoutMs: input.settings.sessionMemory.timeoutMs,
|
|
@@ -228,17 +245,22 @@ export async function runGrowthReviewJob(input) {
|
|
|
228
245
|
minMemoryAutoWriteConfidence: input.settings.memoryGrowth.minMemoryAutoWriteConfidence,
|
|
229
246
|
minSkillAutoWriteConfidence: input.settings.memoryGrowth.minSkillAutoWriteConfidence,
|
|
230
247
|
loadedSkills: input.loadedSkills,
|
|
248
|
+
correlationId: sourceWindow.windowId,
|
|
231
249
|
emitNotice: async (notice) => {
|
|
232
250
|
notices.push(notice);
|
|
233
251
|
},
|
|
234
252
|
refreshWorkspaceResources: input.refreshWorkspaceResources,
|
|
235
253
|
});
|
|
254
|
+
if (result.status === "failed") {
|
|
255
|
+
throw new Error(`Growth review failed: ${result.error}. Retry this memory window after backoff.`);
|
|
256
|
+
}
|
|
257
|
+
const appliedResult = result.result;
|
|
236
258
|
await updateMemoryMaintenanceState(input.appHomeDir, input.channelId, (current) => ({
|
|
237
259
|
...current,
|
|
238
260
|
lastGrowthReviewAt: now.toISOString(),
|
|
239
261
|
turnsSinceGrowthReview: 0,
|
|
240
262
|
toolCallsSinceGrowthReview: 0,
|
|
241
|
-
lastReviewedEntryId:
|
|
263
|
+
lastReviewedEntryId: sourceWindow.throughEntryId ?? current.lastReviewedEntryId,
|
|
242
264
|
failureBackoffUntil: null,
|
|
243
265
|
}));
|
|
244
266
|
if (notices.length > 0) {
|
|
@@ -246,8 +268,9 @@ export async function runGrowthReviewJob(input) {
|
|
|
246
268
|
await input.emitNotice?.(uniqueNotices.join("\n"));
|
|
247
269
|
}
|
|
248
270
|
await appendJobReviewLog(input.channelDir, input.channelId, "growth-review-job", {
|
|
249
|
-
actions:
|
|
250
|
-
skipped:
|
|
271
|
+
actions: appliedResult.actions,
|
|
272
|
+
skipped: appliedResult.skipped,
|
|
273
|
+
correlationId: sourceWindow.windowId,
|
|
251
274
|
}, now);
|
|
252
275
|
return ran("growth-review");
|
|
253
276
|
}
|
|
@@ -283,7 +306,8 @@ export async function runStructuralMaintenanceJob(input) {
|
|
|
283
306
|
return skipped(decision.jobKind, decision.skipReason ?? "skipped");
|
|
284
307
|
}
|
|
285
308
|
try {
|
|
286
|
-
const
|
|
309
|
+
const correlationId = `structural-maintenance:${now.toISOString()}`;
|
|
310
|
+
const options = makeRunOptions(input, correlationId);
|
|
287
311
|
const cleanedMemory = decision.runMemoryCleanup
|
|
288
312
|
? await cleanupChannelMemory(options, currentMemory, {
|
|
289
313
|
cleanupShrinkGuardMinRatio: input.settings.memoryMaintenance.cleanupShrinkGuardMinRatio,
|
|
@@ -297,6 +321,7 @@ export async function runStructuralMaintenanceJob(input) {
|
|
|
297
321
|
failureBackoffUntil: null,
|
|
298
322
|
}));
|
|
299
323
|
await appendJobReviewLog(input.channelDir, input.channelId, "structural-maintenance-job", {
|
|
324
|
+
correlationId,
|
|
300
325
|
actions: [
|
|
301
326
|
...(cleanedMemory ? [{ target: "MEMORY.md", action: "rewrite" }] : []),
|
|
302
327
|
...(foldedHistory ? [{ target: "HISTORY.md", action: "rewrite" }] : []),
|
|
@@ -0,0 +1,60 @@
|
|
|
1
|
+
export type MemoryEntryKind = "fact" | "preference" | "decision" | "constraint" | "open-loop" | "lesson";
|
|
2
|
+
export type MemorySourceType = "user" | "agent" | "repo" | "tool" | "web" | "legacy";
|
|
3
|
+
export type MemoryTrust = "explicit" | "verified" | "inferred" | "untrusted";
|
|
4
|
+
export type MemorySensitivity = "normal" | "personal" | "secret";
|
|
5
|
+
export type MemoryEntryStatus = "active" | "superseded" | "invalidated" | "forgotten";
|
|
6
|
+
export interface MemoryWriteMetadataInput {
|
|
7
|
+
kind?: MemoryEntryKind;
|
|
8
|
+
subjectId?: string;
|
|
9
|
+
ownerId?: string;
|
|
10
|
+
sourceType?: MemorySourceType;
|
|
11
|
+
trust?: MemoryTrust;
|
|
12
|
+
validFrom?: string;
|
|
13
|
+
expiresAt?: string;
|
|
14
|
+
sensitivity?: MemorySensitivity;
|
|
15
|
+
sourceCorrelationId?: string;
|
|
16
|
+
}
|
|
17
|
+
export interface MemoryEntryMetadata {
|
|
18
|
+
id: string;
|
|
19
|
+
kind: MemoryEntryKind;
|
|
20
|
+
scope: "channel";
|
|
21
|
+
subjectId?: string;
|
|
22
|
+
ownerId?: string;
|
|
23
|
+
sourceEntryIds: string[];
|
|
24
|
+
sourceCorrelationIds: string[];
|
|
25
|
+
sourceType: MemorySourceType;
|
|
26
|
+
trust: MemoryTrust;
|
|
27
|
+
createdAt: string;
|
|
28
|
+
updatedAt: string;
|
|
29
|
+
validFrom?: string;
|
|
30
|
+
expiresAt?: string;
|
|
31
|
+
status: MemoryEntryStatus;
|
|
32
|
+
sensitivity: MemorySensitivity;
|
|
33
|
+
sectionHeading: string;
|
|
34
|
+
contentHash: string;
|
|
35
|
+
recallCount: number;
|
|
36
|
+
lastRecalledAt?: string;
|
|
37
|
+
queryFingerprints: string[];
|
|
38
|
+
recallByDay: Record<string, number>;
|
|
39
|
+
}
|
|
40
|
+
export interface MemoryMetadataFile {
|
|
41
|
+
schemaVersion: 1;
|
|
42
|
+
updatedAt: string;
|
|
43
|
+
entries: Record<string, MemoryEntryMetadata>;
|
|
44
|
+
}
|
|
45
|
+
export interface MetadataEntryView {
|
|
46
|
+
id: string;
|
|
47
|
+
content: string;
|
|
48
|
+
sectionHeading: string;
|
|
49
|
+
timestamp?: string;
|
|
50
|
+
}
|
|
51
|
+
export interface MemoryMetadataUpdate {
|
|
52
|
+
id: string;
|
|
53
|
+
status?: MemoryEntryStatus;
|
|
54
|
+
metadata?: MemoryWriteMetadataInput;
|
|
55
|
+
sourceEntryIds?: string[];
|
|
56
|
+
}
|
|
57
|
+
export declare function getMemoryMetadataPath(channelDir: string): string;
|
|
58
|
+
export declare function readMemoryMetadata(channelDir: string): Promise<MemoryMetadataFile>;
|
|
59
|
+
export declare function syncMemoryMetadata(channelDir: string, activeEntries: MetadataEntryView[], updates?: MemoryMetadataUpdate[], timestamp?: string): Promise<MemoryMetadataFile>;
|
|
60
|
+
export declare function recordMemoryRecall(channelDir: string, entryIds: string[], query: string, timestamp?: string): Promise<void>;
|
|
@@ -0,0 +1,135 @@
|
|
|
1
|
+
import { createHash } from "node:crypto";
|
|
2
|
+
import { join } from "node:path";
|
|
3
|
+
import { writeFileAtomically } from "../shared/atomic-file.js";
|
|
4
|
+
import { readOptionalTextFile } from "../shared/fs-utils.js";
|
|
5
|
+
import { createSerialQueue } from "../shared/serial-queue.js";
|
|
6
|
+
const metadataQueue = createSerialQueue();
|
|
7
|
+
function contentHash(content) {
|
|
8
|
+
return createHash("sha256").update(content.normalize("NFKC").replace(/\s+/g, " ").trim()).digest("hex");
|
|
9
|
+
}
|
|
10
|
+
function inferKind(sectionHeading) {
|
|
11
|
+
const section = sectionHeading.toLowerCase();
|
|
12
|
+
if (section.includes("preference"))
|
|
13
|
+
return "preference";
|
|
14
|
+
if (section.includes("decision"))
|
|
15
|
+
return "decision";
|
|
16
|
+
if (section.includes("constraint"))
|
|
17
|
+
return "constraint";
|
|
18
|
+
if (section.includes("open loop") || section.includes("ongoing"))
|
|
19
|
+
return "open-loop";
|
|
20
|
+
if (section.includes("lesson") || section.includes("correction"))
|
|
21
|
+
return "lesson";
|
|
22
|
+
return "fact";
|
|
23
|
+
}
|
|
24
|
+
function emptyMetadataFile(timestamp) {
|
|
25
|
+
return { schemaVersion: 1, updatedAt: timestamp, entries: {} };
|
|
26
|
+
}
|
|
27
|
+
export function getMemoryMetadataPath(channelDir) {
|
|
28
|
+
return join(channelDir, ".memory", "entries.json");
|
|
29
|
+
}
|
|
30
|
+
export async function readMemoryMetadata(channelDir) {
|
|
31
|
+
const timestamp = new Date().toISOString();
|
|
32
|
+
const raw = await readOptionalTextFile(getMemoryMetadataPath(channelDir));
|
|
33
|
+
if (!raw.trim())
|
|
34
|
+
return emptyMetadataFile(timestamp);
|
|
35
|
+
try {
|
|
36
|
+
const parsed = JSON.parse(raw);
|
|
37
|
+
if (parsed.schemaVersion === 1 && parsed.entries && typeof parsed.entries === "object")
|
|
38
|
+
return parsed;
|
|
39
|
+
}
|
|
40
|
+
catch {
|
|
41
|
+
// Rebuildable from MEMORY.md on the next reconciliation.
|
|
42
|
+
}
|
|
43
|
+
return emptyMetadataFile(timestamp);
|
|
44
|
+
}
|
|
45
|
+
export async function syncMemoryMetadata(channelDir, activeEntries, updates = [], timestamp = new Date().toISOString()) {
|
|
46
|
+
const path = getMemoryMetadataPath(channelDir);
|
|
47
|
+
return metadataQueue.run(path, async () => {
|
|
48
|
+
const current = await readMemoryMetadata(channelDir);
|
|
49
|
+
const entries = { ...current.entries };
|
|
50
|
+
const updatesById = new Map(updates.map((update) => [update.id, update]));
|
|
51
|
+
const activeIds = new Set(activeEntries.map((entry) => entry.id));
|
|
52
|
+
for (const entry of activeEntries) {
|
|
53
|
+
const previous = entries[entry.id];
|
|
54
|
+
const update = updatesById.get(entry.id);
|
|
55
|
+
const hint = update?.metadata;
|
|
56
|
+
entries[entry.id] = {
|
|
57
|
+
id: entry.id,
|
|
58
|
+
kind: hint?.kind ?? previous?.kind ?? inferKind(entry.sectionHeading),
|
|
59
|
+
scope: "channel",
|
|
60
|
+
subjectId: hint?.subjectId ?? previous?.subjectId,
|
|
61
|
+
ownerId: hint?.ownerId ?? previous?.ownerId,
|
|
62
|
+
sourceEntryIds: Array.from(new Set([...(previous?.sourceEntryIds ?? []), ...(update?.sourceEntryIds ?? [])])),
|
|
63
|
+
sourceCorrelationIds: Array.from(new Set([
|
|
64
|
+
...(previous?.sourceCorrelationIds ?? []),
|
|
65
|
+
...(hint?.sourceCorrelationId ? [hint.sourceCorrelationId] : []),
|
|
66
|
+
])),
|
|
67
|
+
sourceType: hint?.sourceType ?? previous?.sourceType ?? "legacy",
|
|
68
|
+
trust: hint?.trust ?? previous?.trust ?? "inferred",
|
|
69
|
+
createdAt: previous?.createdAt ?? entry.timestamp ?? timestamp,
|
|
70
|
+
updatedAt: update || previous?.contentHash !== contentHash(entry.content) ? timestamp : previous.updatedAt,
|
|
71
|
+
validFrom: hint?.validFrom ?? previous?.validFrom,
|
|
72
|
+
expiresAt: hint?.expiresAt ?? previous?.expiresAt,
|
|
73
|
+
status: "active",
|
|
74
|
+
sensitivity: hint?.sensitivity ?? previous?.sensitivity ?? "normal",
|
|
75
|
+
sectionHeading: entry.sectionHeading,
|
|
76
|
+
contentHash: contentHash(entry.content),
|
|
77
|
+
recallCount: previous?.recallCount ?? 0,
|
|
78
|
+
lastRecalledAt: previous?.lastRecalledAt,
|
|
79
|
+
queryFingerprints: previous?.queryFingerprints ?? [],
|
|
80
|
+
recallByDay: previous?.recallByDay ?? {},
|
|
81
|
+
};
|
|
82
|
+
}
|
|
83
|
+
for (const update of updates) {
|
|
84
|
+
if (!update.status || update.status === "active" || activeIds.has(update.id))
|
|
85
|
+
continue;
|
|
86
|
+
const previous = entries[update.id];
|
|
87
|
+
if (previous)
|
|
88
|
+
entries[update.id] = { ...previous, status: update.status, updatedAt: timestamp };
|
|
89
|
+
}
|
|
90
|
+
for (const [id, entry] of Object.entries(entries)) {
|
|
91
|
+
if (entry.status === "active" && !activeIds.has(id) && !updatesById.has(id)) {
|
|
92
|
+
entries[id] = { ...entry, status: "invalidated", updatedAt: timestamp };
|
|
93
|
+
}
|
|
94
|
+
}
|
|
95
|
+
const next = { schemaVersion: 1, updatedAt: timestamp, entries };
|
|
96
|
+
await writeFileAtomically(path, `${JSON.stringify(next, null, 2)}\n`);
|
|
97
|
+
return next;
|
|
98
|
+
});
|
|
99
|
+
}
|
|
100
|
+
export async function recordMemoryRecall(channelDir, entryIds, query, timestamp = new Date().toISOString()) {
|
|
101
|
+
if (entryIds.length === 0)
|
|
102
|
+
return;
|
|
103
|
+
const path = getMemoryMetadataPath(channelDir);
|
|
104
|
+
await metadataQueue.run(path, async () => {
|
|
105
|
+
const current = await readMemoryMetadata(channelDir);
|
|
106
|
+
const fingerprint = createHash("sha256")
|
|
107
|
+
.update(query.normalize("NFKC").replace(/\s+/g, " ").trim().toLowerCase())
|
|
108
|
+
.digest("hex")
|
|
109
|
+
.slice(0, 16);
|
|
110
|
+
const day = timestamp.slice(0, 10);
|
|
111
|
+
const cutoff = new Date(timestamp);
|
|
112
|
+
cutoff.setUTCDate(cutoff.getUTCDate() - 89);
|
|
113
|
+
const cutoffDay = cutoff.toISOString().slice(0, 10);
|
|
114
|
+
let changed = false;
|
|
115
|
+
for (const id of new Set(entryIds)) {
|
|
116
|
+
const entry = current.entries[id];
|
|
117
|
+
if (!entry || entry.status !== "active")
|
|
118
|
+
continue;
|
|
119
|
+
const fingerprints = Array.from(new Set([...entry.queryFingerprints, fingerprint])).slice(-32);
|
|
120
|
+
const recallByDay = Object.fromEntries(Object.entries(entry.recallByDay ?? {}).filter(([recordedDay]) => recordedDay >= cutoffDay));
|
|
121
|
+
current.entries[id] = {
|
|
122
|
+
...entry,
|
|
123
|
+
recallCount: entry.recallCount + 1,
|
|
124
|
+
lastRecalledAt: timestamp,
|
|
125
|
+
queryFingerprints: fingerprints,
|
|
126
|
+
recallByDay: { ...recallByDay, [day]: (recallByDay[day] ?? 0) + 1 },
|
|
127
|
+
};
|
|
128
|
+
changed = true;
|
|
129
|
+
}
|
|
130
|
+
if (!changed)
|
|
131
|
+
return;
|
|
132
|
+
current.updatedAt = timestamp;
|
|
133
|
+
await writeFileAtomically(path, `${JSON.stringify(current, null, 2)}\n`);
|
|
134
|
+
});
|
|
135
|
+
}
|