@oyasmi/pipiclaw 0.8.4 → 0.8.6
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +2 -1
- package/dist/agent/channel-runner.d.ts +29 -0
- package/dist/agent/channel-runner.js +156 -53
- package/dist/agent/command-extension.d.ts +1 -0
- package/dist/agent/command-extension.js +6 -0
- package/dist/agent/commands.d.ts +2 -2
- package/dist/agent/commands.js +16 -1
- package/dist/agent/maintenance-context.js +1 -1
- package/dist/agent/prompt/builder.d.ts +32 -0
- package/dist/agent/prompt/builder.js +252 -0
- package/dist/agent/prompt/extension.d.ts +22 -0
- package/dist/agent/prompt/extension.js +24 -0
- package/dist/agent/prompt/manifest.d.ts +51 -0
- package/dist/agent/prompt/manifest.js +84 -0
- package/dist/agent/prompt/resources.d.ts +18 -0
- package/dist/agent/prompt/resources.js +61 -0
- package/dist/agent/prompt/sections.d.ts +39 -0
- package/dist/agent/prompt/sections.js +267 -0
- package/dist/agent/prompt/types.d.ts +110 -0
- package/dist/agent/prompt/types.js +11 -0
- package/dist/agent/types.d.ts +3 -0
- package/dist/agent/workspace-resources.d.ts +25 -13
- package/dist/agent/workspace-resources.js +28 -41
- package/dist/index.d.ts +7 -2
- package/dist/index.js +6 -2
- 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 +33 -9
- package/dist/playbooks/catalog.d.ts +22 -1
- package/dist/playbooks/catalog.js +57 -4
- package/dist/playbooks/event-scheduling.md +2 -0
- package/dist/playbooks/memory-and-learning.md +2 -0
- package/dist/playbooks/runtime-orientation.md +1 -0
- package/dist/playbooks/task-closeout.md +3 -1
- package/dist/playbooks/task-delegation.md +3 -1
- package/dist/playbooks/task-driving.md +2 -0
- package/dist/playbooks/task-planning.md +2 -0
- package/dist/playbooks/task-recurring.md +2 -0
- package/dist/playbooks/task-repair.md +3 -1
- package/dist/runtime/bootstrap.js +8 -38
- package/dist/runtime/dingtalk.d.ts +1 -0
- package/dist/runtime/dingtalk.js +3 -0
- package/dist/runtime/task-commands.js +1 -1
- package/dist/runtime/workspace-templates.d.ts +11 -0
- package/dist/runtime/workspace-templates.js +51 -0
- 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/tui/commands.d.ts +1 -0
- package/dist/tui/commands.js +2 -0
- package/dist/tui/turn-controller.js +1 -0
- package/dist/usage/ledger.d.ts +2 -0
- package/package.json +1 -1
- package/dist/agent/prompt-builder.d.ts +0 -12
- package/dist/agent/prompt-builder.js +0 -71
|
@@ -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
|
+
}
|
|
@@ -0,0 +1,19 @@
|
|
|
1
|
+
const SECRET_PATTERNS = [
|
|
2
|
+
/-----BEGIN (?:RSA |EC |OPENSSH )?PRIVATE KEY-----[\s\S]*?-----END (?:RSA |EC |OPENSSH )?PRIVATE KEY-----/gi,
|
|
3
|
+
/\b(?:sk|rk|pk)-(?:live|test|proj)?-?[A-Za-z0-9_-]{16,}\b/g,
|
|
4
|
+
/\b(?:ghp|github_pat|glpat)_[A-Za-z0-9_-]{16,}\b/g,
|
|
5
|
+
/\bAKIA[A-Z0-9]{16}\b/g,
|
|
6
|
+
/\bBearer\s+[A-Za-z0-9._~+/-]{16,}=*/gi,
|
|
7
|
+
/\b(?:api[_-]?key|access[_-]?token|refresh[_-]?token|password|passwd|secret)\s*[:=]\s*["']?[^\s"']{8,}/gi,
|
|
8
|
+
];
|
|
9
|
+
export const REDACTED_SECRET = "[REDACTED_SECRET]";
|
|
10
|
+
export function redactSecrets(text) {
|
|
11
|
+
let redacted = text;
|
|
12
|
+
for (const pattern of SECRET_PATTERNS) {
|
|
13
|
+
redacted = redacted.replace(pattern, REDACTED_SECRET);
|
|
14
|
+
}
|
|
15
|
+
return redacted;
|
|
16
|
+
}
|
|
17
|
+
export function containsSecret(text) {
|
|
18
|
+
return redactSecrets(text) !== text;
|
|
19
|
+
}
|
|
@@ -19,6 +19,9 @@ export interface PostTurnReviewOptions {
|
|
|
19
19
|
}>;
|
|
20
20
|
emitNotice?: (notice: string) => Promise<void>;
|
|
21
21
|
refreshWorkspaceResources?: () => Promise<void>;
|
|
22
|
+
sourceEntryIds?: string[];
|
|
23
|
+
suppressAutomaticWrites?: boolean;
|
|
24
|
+
correlationId?: string;
|
|
22
25
|
}
|
|
23
26
|
export interface PostTurnReviewApplyResult {
|
|
24
27
|
actions: unknown[];
|
|
@@ -26,6 +29,13 @@ export interface PostTurnReviewApplyResult {
|
|
|
26
29
|
skipped: unknown[];
|
|
27
30
|
notices: string[];
|
|
28
31
|
}
|
|
32
|
+
export type PostTurnReviewRunResult = {
|
|
33
|
+
status: "applied" | "empty";
|
|
34
|
+
result: PostTurnReviewApplyResult;
|
|
35
|
+
} | {
|
|
36
|
+
status: "failed";
|
|
37
|
+
error: string;
|
|
38
|
+
};
|
|
29
39
|
export declare function parsePostTurnReviewResult(value: unknown): PostTurnReviewResult;
|
|
30
40
|
export declare function applyPostTurnReviewResult(options: PostTurnReviewOptions, review: PostTurnReviewResult): Promise<PostTurnReviewApplyResult>;
|
|
31
|
-
export declare function runPostTurnReview(options: PostTurnReviewOptions): Promise<
|
|
41
|
+
export declare function runPostTurnReview(options: PostTurnReviewOptions): Promise<PostTurnReviewRunResult>;
|
|
@@ -3,7 +3,8 @@ import { parseJsonObject } from "../shared/llm-json.js";
|
|
|
3
3
|
import { clipText, errorMessage } from "../shared/text-utils.js";
|
|
4
4
|
import { isRecord } from "../shared/type-guards.js";
|
|
5
5
|
import { manageWorkspaceSkill } from "../tools/skill-manage.js";
|
|
6
|
-
import {
|
|
6
|
+
import { applyChannelMemoryOps, readChannelHistory, readChannelMemory, readChannelSession, } from "./files.js";
|
|
7
|
+
import { containsSecret } from "./policy.js";
|
|
7
8
|
import { shouldAutoWriteMemory, shouldAutoWriteSkill, } from "./promotion.js";
|
|
8
9
|
import { appendMemoryReviewLog } from "./review-log.js";
|
|
9
10
|
import { runRetriedSidecarTask } from "./sidecar-worker.js";
|
|
@@ -12,10 +13,13 @@ const POST_TURN_REVIEW_SYSTEM_PROMPT = `You are Pipiclaw's post-turn memory revi
|
|
|
12
13
|
|
|
13
14
|
Return strict JSON only:
|
|
14
15
|
{
|
|
15
|
-
"
|
|
16
|
+
"memoryOps": [
|
|
16
17
|
{
|
|
17
18
|
"target": "channel-memory",
|
|
19
|
+
"op": "add|supersede|invalidate",
|
|
20
|
+
"targetId": "required for supersede/invalidate",
|
|
18
21
|
"content": "standalone durable memory bullet without '-'",
|
|
22
|
+
"kind": "fact|preference|decision|constraint|open-loop|lesson",
|
|
19
23
|
"confidence": 0.0,
|
|
20
24
|
"necessity": "low|medium|high",
|
|
21
25
|
"reason": "why it should or should not be stored"
|
|
@@ -59,13 +63,25 @@ function normalizeMemoryCandidate(value) {
|
|
|
59
63
|
return null;
|
|
60
64
|
}
|
|
61
65
|
const target = "channel-memory";
|
|
62
|
-
const
|
|
63
|
-
|
|
66
|
+
const op = value.op === "supersede" || value.op === "invalidate" ? value.op : "add";
|
|
67
|
+
const targetId = typeof value.targetId === "string" ? value.targetId.trim() : undefined;
|
|
68
|
+
const content = typeof value.content === "string" ? value.content.trim() : undefined;
|
|
69
|
+
const kind = value.kind === "preference" ||
|
|
70
|
+
value.kind === "decision" ||
|
|
71
|
+
value.kind === "constraint" ||
|
|
72
|
+
value.kind === "open-loop" ||
|
|
73
|
+
value.kind === "lesson"
|
|
74
|
+
? value.kind
|
|
75
|
+
: "fact";
|
|
76
|
+
if ((op === "invalidate" && !targetId) || (op !== "invalidate" && !content)) {
|
|
64
77
|
return null;
|
|
65
78
|
}
|
|
66
79
|
return {
|
|
67
80
|
target,
|
|
81
|
+
op,
|
|
82
|
+
targetId,
|
|
68
83
|
content,
|
|
84
|
+
kind,
|
|
69
85
|
confidence: normalizeConfidence(value.confidence),
|
|
70
86
|
necessity: normalizeNecessity(value.necessity),
|
|
71
87
|
reason: typeof value.reason === "string" ? value.reason.trim() : "",
|
|
@@ -97,8 +113,13 @@ function normalizeSkillCandidate(value) {
|
|
|
97
113
|
}
|
|
98
114
|
export function parsePostTurnReviewResult(value) {
|
|
99
115
|
const record = isRecord(value) ? value : {};
|
|
100
|
-
const
|
|
101
|
-
? record.
|
|
116
|
+
const rawMemoryOps = Array.isArray(record.memoryOps)
|
|
117
|
+
? record.memoryOps
|
|
118
|
+
: Array.isArray(record.memoryCandidates)
|
|
119
|
+
? record.memoryCandidates
|
|
120
|
+
: [];
|
|
121
|
+
const memoryOps = rawMemoryOps.length > 0
|
|
122
|
+
? rawMemoryOps.map(normalizeMemoryCandidate).filter((item) => !!item)
|
|
102
123
|
: [];
|
|
103
124
|
const skillCandidates = Array.isArray(record.skillCandidates)
|
|
104
125
|
? record.skillCandidates.map(normalizeSkillCandidate).filter((item) => !!item)
|
|
@@ -112,7 +133,7 @@ export function parsePostTurnReviewResult(value) {
|
|
|
112
133
|
}))
|
|
113
134
|
.filter((item) => item.content.trim() || item.reason.trim())
|
|
114
135
|
: [];
|
|
115
|
-
return {
|
|
136
|
+
return { memoryOps, skillCandidates, discarded };
|
|
116
137
|
}
|
|
117
138
|
async function runPostTurnReviewWorker(options) {
|
|
118
139
|
const [currentSession, currentMemory, currentHistory] = await Promise.all([
|
|
@@ -147,26 +168,61 @@ ${transcript || "(empty)"}`;
|
|
|
147
168
|
systemPrompt: POST_TURN_REVIEW_SYSTEM_PROMPT,
|
|
148
169
|
prompt,
|
|
149
170
|
timeoutMs: options.timeoutMs,
|
|
150
|
-
usageContext: { channelId: options.channelId },
|
|
171
|
+
usageContext: { channelId: options.channelId, correlationId: options.correlationId },
|
|
151
172
|
parse: (text) => parsePostTurnReviewResult(parseJsonObject(text)),
|
|
152
173
|
});
|
|
153
174
|
return result.output;
|
|
154
175
|
}
|
|
155
176
|
async function applyMemoryCandidate(options, candidate, result, timestamp) {
|
|
156
|
-
if (
|
|
177
|
+
if (options.suppressAutomaticWrites ||
|
|
178
|
+
!options.autoWriteChannelMemory ||
|
|
179
|
+
!shouldAutoWriteMemory(candidate, options.minMemoryAutoWriteConfidence)) {
|
|
157
180
|
result.suggestions.push({ type: "memory", candidate });
|
|
158
181
|
return;
|
|
159
182
|
}
|
|
160
|
-
|
|
161
|
-
|
|
162
|
-
|
|
163
|
-
}
|
|
164
|
-
const
|
|
183
|
+
if (candidate.content && containsSecret(candidate.content)) {
|
|
184
|
+
result.skipped.push({ type: "memory", candidate: { ...candidate, content: "[REDACTED]" }, reason: "secret" });
|
|
185
|
+
return;
|
|
186
|
+
}
|
|
187
|
+
const op = candidate.op === "invalidate"
|
|
188
|
+
? { op: "invalidate", targetId: candidate.targetId ?? "", reason: candidate.reason }
|
|
189
|
+
: candidate.op === "supersede"
|
|
190
|
+
? {
|
|
191
|
+
op: "supersede",
|
|
192
|
+
targetId: candidate.targetId ?? "",
|
|
193
|
+
content: candidate.content ?? "",
|
|
194
|
+
sourceEntryIds: options.sourceEntryIds,
|
|
195
|
+
metadata: {
|
|
196
|
+
kind: candidate.kind,
|
|
197
|
+
sourceType: "agent",
|
|
198
|
+
trust: "inferred",
|
|
199
|
+
sourceCorrelationId: options.correlationId,
|
|
200
|
+
},
|
|
201
|
+
}
|
|
202
|
+
: {
|
|
203
|
+
op: "add",
|
|
204
|
+
content: candidate.content ?? "",
|
|
205
|
+
sourceEntryIds: options.sourceEntryIds,
|
|
206
|
+
metadata: {
|
|
207
|
+
kind: candidate.kind,
|
|
208
|
+
sourceType: "agent",
|
|
209
|
+
trust: "inferred",
|
|
210
|
+
sourceCorrelationId: options.correlationId,
|
|
211
|
+
},
|
|
212
|
+
};
|
|
213
|
+
const applied = await applyChannelMemoryOps(options.channelDir, [op], timestamp);
|
|
214
|
+
if (applied.blockedByPolicy > 0 || applied.blockedByTombstone > 0) {
|
|
215
|
+
result.skipped.push({ type: "memory", entry: candidate.targetId, reason: "blocked by memory policy" });
|
|
216
|
+
return;
|
|
217
|
+
}
|
|
218
|
+
const action = { target: "MEMORY.md", action: candidate.op, entry: candidate.targetId, reason: candidate.reason };
|
|
165
219
|
result.actions.push(action);
|
|
166
220
|
result.notices.push("已沉淀:更新 channel memory。");
|
|
167
221
|
}
|
|
168
222
|
async function applySkillCandidate(options, candidate, result) {
|
|
169
|
-
if (
|
|
223
|
+
if (options.suppressAutomaticWrites ||
|
|
224
|
+
!options.autoWriteWorkspaceSkills ||
|
|
225
|
+
!shouldAutoWriteSkill(candidate, options.minSkillAutoWriteConfidence)) {
|
|
170
226
|
result.suggestions.push({ type: "skill", candidate });
|
|
171
227
|
return;
|
|
172
228
|
}
|
|
@@ -199,7 +255,7 @@ export async function applyPostTurnReviewResult(options, review) {
|
|
|
199
255
|
skipped: [],
|
|
200
256
|
notices: [],
|
|
201
257
|
};
|
|
202
|
-
for (const candidate of review.
|
|
258
|
+
for (const candidate of review.memoryOps) {
|
|
203
259
|
await applyMemoryCandidate(options, candidate, result, timestamp);
|
|
204
260
|
}
|
|
205
261
|
for (const candidate of review.skillCandidates) {
|
|
@@ -212,7 +268,8 @@ export async function applyPostTurnReviewResult(options, review) {
|
|
|
212
268
|
timestamp,
|
|
213
269
|
channelId: options.channelId,
|
|
214
270
|
reason: "post-turn",
|
|
215
|
-
|
|
271
|
+
correlationId: options.correlationId,
|
|
272
|
+
candidates: [...review.memoryOps, ...review.skillCandidates],
|
|
216
273
|
actions: result.actions,
|
|
217
274
|
suggestions: result.suggestions,
|
|
218
275
|
skipped: result.skipped,
|
|
@@ -230,7 +287,8 @@ export async function applyPostTurnReviewResult(options, review) {
|
|
|
230
287
|
export async function runPostTurnReview(options) {
|
|
231
288
|
try {
|
|
232
289
|
const review = await runPostTurnReviewWorker(options);
|
|
233
|
-
|
|
290
|
+
const result = await applyPostTurnReviewResult(options, review);
|
|
291
|
+
return { status: result.actions.length > 0 ? "applied" : "empty", result };
|
|
234
292
|
}
|
|
235
293
|
catch (error) {
|
|
236
294
|
const message = errorMessage(error);
|
|
@@ -238,9 +296,10 @@ export async function runPostTurnReview(options) {
|
|
|
238
296
|
timestamp: new Date().toISOString(),
|
|
239
297
|
channelId: options.channelId,
|
|
240
298
|
reason: "post-turn",
|
|
299
|
+
correlationId: options.correlationId,
|
|
241
300
|
error: message,
|
|
242
301
|
skipped: [{ target: "post-turn-review", reason: "failed" }],
|
|
243
302
|
});
|
|
244
|
-
return {
|
|
303
|
+
return { status: "failed", error: message };
|
|
245
304
|
}
|
|
246
305
|
}
|
|
@@ -2,7 +2,10 @@ export type MemoryPromotionTarget = "channel-memory";
|
|
|
2
2
|
export type SkillPromotionAction = "create" | "patch" | "write_file";
|
|
3
3
|
export interface MemoryPromotionCandidate {
|
|
4
4
|
target: MemoryPromotionTarget;
|
|
5
|
-
|
|
5
|
+
op: "add" | "supersede" | "invalidate";
|
|
6
|
+
targetId?: string;
|
|
7
|
+
content?: string;
|
|
8
|
+
kind: "fact" | "preference" | "decision" | "constraint" | "open-loop" | "lesson";
|
|
6
9
|
confidence: number;
|
|
7
10
|
reason: string;
|
|
8
11
|
necessity: "low" | "medium" | "high";
|
|
@@ -19,7 +22,7 @@ export interface SkillPromotionCandidate {
|
|
|
19
22
|
reason: string;
|
|
20
23
|
}
|
|
21
24
|
export interface PostTurnReviewResult {
|
|
22
|
-
|
|
25
|
+
memoryOps: MemoryPromotionCandidate[];
|
|
23
26
|
skillCandidates: SkillPromotionCandidate[];
|
|
24
27
|
discarded: Array<{
|
|
25
28
|
content: string;
|
package/dist/memory/promotion.js
CHANGED
|
@@ -4,7 +4,9 @@ function isHighNecessity(value) {
|
|
|
4
4
|
return value === "high";
|
|
5
5
|
}
|
|
6
6
|
export function shouldAutoWriteMemory(candidate, threshold = DEFAULT_MEMORY_AUTO_WRITE_CONFIDENCE) {
|
|
7
|
-
return (candidate.confidence >= threshold &&
|
|
7
|
+
return (candidate.confidence >= threshold &&
|
|
8
|
+
isHighNecessity(candidate.necessity) &&
|
|
9
|
+
(candidate.op === "invalidate" ? Boolean(candidate.targetId) : Boolean(candidate.content?.trim())));
|
|
8
10
|
}
|
|
9
11
|
export function shouldAutoWriteSkill(candidate, threshold = DEFAULT_SKILL_AUTO_WRITE_CONFIDENCE) {
|
|
10
12
|
return candidate.confidence >= threshold && candidate.necessity === "high";
|