@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
|
@@ -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";
|
package/dist/memory/recall.d.ts
CHANGED
|
@@ -6,6 +6,7 @@ export interface RecallRequest {
|
|
|
6
6
|
workspaceDir: string;
|
|
7
7
|
channelDir: string;
|
|
8
8
|
allowedSources?: MemoryCandidate["source"][];
|
|
9
|
+
excludedCandidateIds?: string[];
|
|
9
10
|
maxCandidates: number;
|
|
10
11
|
maxInjected: number;
|
|
11
12
|
maxChars: number;
|
|
@@ -16,6 +17,8 @@ export interface RecallRequest {
|
|
|
16
17
|
candidateStore?: MemoryCandidateStore;
|
|
17
18
|
}
|
|
18
19
|
export interface RecalledMemory {
|
|
20
|
+
id: string;
|
|
21
|
+
entryId?: string;
|
|
19
22
|
source: MemoryCandidate["source"];
|
|
20
23
|
path: string;
|
|
21
24
|
title: string;
|
package/dist/memory/recall.js
CHANGED
|
@@ -2,6 +2,7 @@ import { parseJsonObject } from "../shared/llm-json.js";
|
|
|
2
2
|
import { HAN_REGEX } from "../shared/text-utils.js";
|
|
3
3
|
import { buildMemoryCandidates, createMemoryCandidateStore, } from "./candidates.js";
|
|
4
4
|
import { COMMON_CHINESE_WORDS } from "./chinese-words.js";
|
|
5
|
+
import { recordMemoryRecall, syncMemoryMetadata } from "./metadata.js";
|
|
5
6
|
import { runSidecarTask } from "./sidecar-worker.js";
|
|
6
7
|
const RERANK_SYSTEM_PROMPT = `You are selecting which memory snippets are most relevant to the current user turn.
|
|
7
8
|
|
|
@@ -21,6 +22,8 @@ const MEMORY_RECALL_RERANK_TIMEOUT_MS = 8_000;
|
|
|
21
22
|
const RERANK_CONTENT_CLIP = 800;
|
|
22
23
|
const HIGH_CONFIDENCE_SCORE = 36;
|
|
23
24
|
const CLOSE_SCORE_DELTA = 8;
|
|
25
|
+
const MIN_LOCAL_SCORE = 12;
|
|
26
|
+
const MIN_QUERY_COVERAGE = 0.25;
|
|
24
27
|
const MAX_HAN_WORD_LENGTH = Array.from(COMMON_CHINESE_WORDS).reduce((max, word) => Math.max(max, word.length), 2);
|
|
25
28
|
const LATIN_STOP_WORDS = new Set([
|
|
26
29
|
"a",
|
|
@@ -327,6 +330,7 @@ function scoreCandidate(query, queryTokens, intents, candidate) {
|
|
|
327
330
|
const contentStats = computeTokenMatchStats(queryTokens, searchText);
|
|
328
331
|
const pathStats = computeTokenMatchStats(queryTokens, candidate.path);
|
|
329
332
|
const matchedTokens = collectMatchingQueryTokens(queryTokens, [candidate.title, searchText, candidate.path]);
|
|
333
|
+
const semanticFieldMatches = collectMatchingQueryTokens(queryTokens, [candidate.title, searchText]);
|
|
330
334
|
const exactBoost = computeExactMatchBoost(query, candidate);
|
|
331
335
|
const intentBoost = computeSectionIntentBoost(intents, candidate);
|
|
332
336
|
const overallCoverage = queryTokens.length > 0 ? matchedTokens.size / queryTokens.length : 0;
|
|
@@ -336,7 +340,7 @@ function scoreCandidate(query, queryTokens, intents, candidate) {
|
|
|
336
340
|
pathStats.coverage * 8 +
|
|
337
341
|
exactBoost;
|
|
338
342
|
const structuralScore = candidate.priority + intentBoost + computeRecencyBoost(candidate.timestamp);
|
|
339
|
-
if (
|
|
343
|
+
if (semanticFieldMatches.size === 0 || (overallCoverage < MIN_QUERY_COVERAGE && exactBoost === 0)) {
|
|
340
344
|
return null;
|
|
341
345
|
}
|
|
342
346
|
return {
|
|
@@ -423,7 +427,7 @@ async function rerankCandidates(request, candidates) {
|
|
|
423
427
|
});
|
|
424
428
|
const selectedIds = new Set(result.output);
|
|
425
429
|
if (selectedIds.size === 0) {
|
|
426
|
-
return
|
|
430
|
+
return [];
|
|
427
431
|
}
|
|
428
432
|
const selected = candidates.filter(({ candidate }) => selectedIds.has(candidate.id));
|
|
429
433
|
return selected.length > 0 ? selected : candidates;
|
|
@@ -517,16 +521,19 @@ export async function recallRelevantMemory(request) {
|
|
|
517
521
|
const filteredCandidates = request.allowedSources?.length
|
|
518
522
|
? candidates.filter((candidate) => request.allowedSources?.includes(candidate.source))
|
|
519
523
|
: candidates;
|
|
520
|
-
|
|
524
|
+
const excludedIds = new Set(request.excludedCandidateIds ?? []);
|
|
525
|
+
const eligibleCandidates = filteredCandidates.filter((candidate) => !excludedIds.has(candidate.id));
|
|
526
|
+
if (eligibleCandidates.length === 0) {
|
|
521
527
|
return { items: [], renderedText: "" };
|
|
522
528
|
}
|
|
523
529
|
const queryTokens = tokenize(query);
|
|
524
530
|
const queryIntents = detectQueryIntents(query);
|
|
525
|
-
const scored =
|
|
531
|
+
const scored = eligibleCandidates
|
|
526
532
|
.map((candidate) => scoreCandidate(query, queryTokens, queryIntents, candidate))
|
|
527
533
|
.filter((candidate) => candidate !== null)
|
|
534
|
+
.filter((candidate) => candidate.score >= MIN_LOCAL_SCORE)
|
|
528
535
|
.sort(compareScoredCandidates);
|
|
529
|
-
const shortlist = seedIntentCandidates(request,
|
|
536
|
+
const shortlist = seedIntentCandidates(request, eligibleCandidates, scored, queryIntents, queryTokens)
|
|
530
537
|
.sort(compareScoredCandidates)
|
|
531
538
|
.slice(0, Math.max(request.maxCandidates, request.maxInjected));
|
|
532
539
|
if (shortlist.length === 0) {
|
|
@@ -534,12 +541,27 @@ export async function recallRelevantMemory(request) {
|
|
|
534
541
|
}
|
|
535
542
|
const reranked = await rerankCandidates(request, shortlist);
|
|
536
543
|
const items = reranked.slice(0, request.maxInjected).map(({ candidate, score }) => ({
|
|
544
|
+
id: candidate.id,
|
|
545
|
+
entryId: candidate.entryId,
|
|
537
546
|
source: candidate.source,
|
|
538
547
|
path: candidate.path,
|
|
539
548
|
title: candidate.title,
|
|
540
549
|
content: candidate.content,
|
|
541
550
|
score,
|
|
542
551
|
}));
|
|
552
|
+
const recalledEntryIds = items.flatMap((item) => (item.entryId ? [item.entryId] : []));
|
|
553
|
+
if (recalledEntryIds.length > 0) {
|
|
554
|
+
const metadataEntries = candidates
|
|
555
|
+
.filter((candidate) => candidate.source === "channel-memory" && candidate.entryId)
|
|
556
|
+
.map((candidate) => ({
|
|
557
|
+
id: candidate.entryId,
|
|
558
|
+
content: candidate.content,
|
|
559
|
+
sectionHeading: candidate.title,
|
|
560
|
+
timestamp: candidate.timestamp,
|
|
561
|
+
}));
|
|
562
|
+
await syncMemoryMetadata(request.channelDir, metadataEntries);
|
|
563
|
+
await recordMemoryRecall(request.channelDir, recalledEntryIds, query);
|
|
564
|
+
}
|
|
543
565
|
return {
|
|
544
566
|
items,
|
|
545
567
|
renderedText: renderRecallResult(items, request.maxChars),
|
|
@@ -3,6 +3,8 @@ export interface MemoryReviewLogEntry {
|
|
|
3
3
|
timestamp: string;
|
|
4
4
|
channelId: string;
|
|
5
5
|
reason: MemoryReviewReason;
|
|
6
|
+
/** Joins this outcome to the corresponding sidecar usage-ledger entry. */
|
|
7
|
+
correlationId?: string;
|
|
6
8
|
candidates?: unknown[];
|
|
7
9
|
actions?: unknown[];
|
|
8
10
|
suggestions?: unknown[];
|
|
@@ -4,6 +4,7 @@ import { writeFileAtomically } from "../shared/atomic-file.js";
|
|
|
4
4
|
import { createSerialQueue } from "../shared/serial-queue.js";
|
|
5
5
|
const REVIEW_LOG_MAX_BYTES = 1_024 * 1_024; // 1 MB
|
|
6
6
|
const writeQueue = createSerialQueue();
|
|
7
|
+
const lastGateSkipByPath = new Map();
|
|
7
8
|
export function getMemoryReviewLogPath(channelDir) {
|
|
8
9
|
return join(channelDir, "memory-review.jsonl");
|
|
9
10
|
}
|
|
@@ -29,6 +30,20 @@ async function rotateIfNeeded(path, incomingBytes) {
|
|
|
29
30
|
}
|
|
30
31
|
export async function appendMemoryReviewLog(channelDir, entry) {
|
|
31
32
|
const path = getMemoryReviewLogPath(channelDir);
|
|
33
|
+
const gateSkipOnly = (entry.skipped?.length ?? 0) > 0 &&
|
|
34
|
+
(entry.actions?.length ?? 0) === 0 &&
|
|
35
|
+
(entry.candidates?.length ?? 0) === 0 &&
|
|
36
|
+
(entry.suggestions?.length ?? 0) === 0 &&
|
|
37
|
+
!entry.error;
|
|
38
|
+
if (gateSkipOnly) {
|
|
39
|
+
const fingerprint = JSON.stringify({ reason: entry.reason, skipped: entry.skipped });
|
|
40
|
+
if (lastGateSkipByPath.get(path) === fingerprint)
|
|
41
|
+
return;
|
|
42
|
+
lastGateSkipByPath.set(path, fingerprint);
|
|
43
|
+
}
|
|
44
|
+
else {
|
|
45
|
+
lastGateSkipByPath.delete(path);
|
|
46
|
+
}
|
|
32
47
|
const line = `${JSON.stringify(entry)}\n`;
|
|
33
48
|
await writeQueue.run(path, async () => {
|
|
34
49
|
await mkdir(dirname(path), { recursive: true });
|
|
@@ -237,8 +237,16 @@ export async function buildSessionCorpus(options) {
|
|
|
237
237
|
break;
|
|
238
238
|
}
|
|
239
239
|
}
|
|
240
|
-
|
|
241
|
-
|
|
240
|
+
const deduplicated = [];
|
|
241
|
+
const seen = new Set();
|
|
242
|
+
for (const document of docs) {
|
|
243
|
+
const identity = document.timestamp
|
|
244
|
+
? `${document.timestamp}\0${document.role}\0${document.text}`
|
|
245
|
+
: `${document.source}\0${document.id}`;
|
|
246
|
+
if (seen.has(identity))
|
|
247
|
+
continue;
|
|
248
|
+
seen.add(identity);
|
|
249
|
+
deduplicated.push(document);
|
|
242
250
|
}
|
|
243
|
-
return
|
|
251
|
+
return deduplicated.length > maxDocuments ? deduplicated.slice(-maxDocuments) : deduplicated;
|
|
244
252
|
}
|
|
@@ -112,6 +112,7 @@ async function getCachedCorpus(channelDir, maxFiles, maxCharsPerChunk) {
|
|
|
112
112
|
if (corpusCache &&
|
|
113
113
|
corpusCache.channelDir === channelDir &&
|
|
114
114
|
corpusCache.maxFiles === maxFiles &&
|
|
115
|
+
corpusCache.maxCharsPerChunk === maxCharsPerChunk &&
|
|
115
116
|
Date.now() - corpusCache.timestamp < CORPUS_CACHE_TTL_MS) {
|
|
116
117
|
return corpusCache.documents;
|
|
117
118
|
}
|
|
@@ -120,7 +121,7 @@ async function getCachedCorpus(channelDir, maxFiles, maxCharsPerChunk) {
|
|
|
120
121
|
maxFiles,
|
|
121
122
|
maxCharsPerDocument: maxCharsPerChunk,
|
|
122
123
|
});
|
|
123
|
-
corpusCache = { channelDir, maxFiles, documents, timestamp: Date.now() };
|
|
124
|
+
corpusCache = { channelDir, maxFiles, maxCharsPerChunk, documents, timestamp: Date.now() };
|
|
124
125
|
return documents;
|
|
125
126
|
}
|
|
126
127
|
export async function searchChannelSessions(request) {
|
|
@@ -128,16 +129,19 @@ export async function searchChannelSessions(request) {
|
|
|
128
129
|
const maxChunks = clampInteger(request.maxChunks, 1, 500);
|
|
129
130
|
const query = request.query.trim();
|
|
130
131
|
const roleFilter = normalizeRoleFilter(request.roleFilter);
|
|
131
|
-
const documents = (await getCachedCorpus(request.channelDir, request.maxFiles, request.maxCharsPerChunk))
|
|
132
|
+
const documents = (await getCachedCorpus(request.channelDir, request.maxFiles, request.maxCharsPerChunk))
|
|
133
|
+
.filter((document) => roleFilter.size === 0 || roleFilter.has(document.role))
|
|
134
|
+
.sort(sortRecentDocuments)
|
|
135
|
+
.slice(0, maxChunks);
|
|
132
136
|
const selected = query
|
|
133
137
|
? documents
|
|
134
138
|
.map((document) => scoreDocument(document, query, tokenizeRecallText(query)))
|
|
135
139
|
.filter((entry) => entry.score > 0)
|
|
136
140
|
.sort((a, b) => b.score - a.score)
|
|
137
|
-
.slice(0,
|
|
141
|
+
.slice(0, limit)
|
|
138
142
|
: documents
|
|
139
143
|
.sort(sortRecentDocuments)
|
|
140
|
-
.slice(0,
|
|
144
|
+
.slice(0, limit)
|
|
141
145
|
.map((document) => ({ document, score: computeRecencyBoost(document.timestamp), matches: [] }));
|
|
142
146
|
const results = [];
|
|
143
147
|
for (const hit of selected) {
|
package/dist/memory/session.d.ts
CHANGED
|
@@ -18,6 +18,7 @@ export interface SessionMemoryUpdateOptions {
|
|
|
18
18
|
model: Model<Api>;
|
|
19
19
|
resolveApiKey: (model: Model<Api>) => Promise<string>;
|
|
20
20
|
timeoutMs?: number;
|
|
21
|
+
usageCorrelationId?: string;
|
|
21
22
|
}
|
|
22
23
|
export declare function renderSessionMemory(state: SessionMemoryState): string;
|
|
23
24
|
export declare function updateChannelSessionMemory(options: SessionMemoryUpdateOptions): Promise<SessionMemoryState>;
|
package/dist/memory/session.js
CHANGED
|
@@ -258,7 +258,9 @@ export async function updateChannelSessionMemory(options) {
|
|
|
258
258
|
prompt: buildSessionPrompt(currentSession, currentMemory, messages),
|
|
259
259
|
parse: parseStateUpdate,
|
|
260
260
|
timeoutMs: options.timeoutMs ?? DEFAULT_SESSION_MEMORY_TIMEOUT_MS,
|
|
261
|
-
usageContext: options.channelId
|
|
261
|
+
usageContext: options.channelId
|
|
262
|
+
? { channelId: options.channelId, correlationId: options.usageCorrelationId }
|
|
263
|
+
: undefined,
|
|
262
264
|
});
|
|
263
265
|
update = result.output;
|
|
264
266
|
}
|
|
@@ -0,0 +1,25 @@
|
|
|
1
|
+
import type { AgentMessage } from "@earendil-works/pi-agent-core";
|
|
2
|
+
import type { SessionEntry } from "@earendil-works/pi-coding-agent";
|
|
3
|
+
export type MemorySourceKind = "idle" | "compaction" | "new-session" | "shutdown" | "growth-review";
|
|
4
|
+
export interface MemorySourceWindow {
|
|
5
|
+
sourceKind: MemorySourceKind;
|
|
6
|
+
fromEntryId?: string;
|
|
7
|
+
throughEntryId?: string;
|
|
8
|
+
entries: SessionEntry[];
|
|
9
|
+
messages: AgentMessage[];
|
|
10
|
+
windowId: string;
|
|
11
|
+
hasExternalToolContent: boolean;
|
|
12
|
+
}
|
|
13
|
+
export declare function entriesSince(entries: SessionEntry[], lastEntryId: string | undefined): SessionEntry[];
|
|
14
|
+
export declare function buildIncrementalMemorySourceWindow(options: {
|
|
15
|
+
entries: SessionEntry[];
|
|
16
|
+
lastEntryId?: string;
|
|
17
|
+
sourceKind: Extract<MemorySourceKind, "idle" | "new-session" | "shutdown" | "growth-review">;
|
|
18
|
+
fallbackMessages?: AgentMessage[];
|
|
19
|
+
}): MemorySourceWindow;
|
|
20
|
+
export declare function buildCompactionMemorySourceWindow(options: {
|
|
21
|
+
entries: SessionEntry[];
|
|
22
|
+
messagesToSummarize: AgentMessage[];
|
|
23
|
+
firstKeptEntryId?: string;
|
|
24
|
+
lastEntryId?: string;
|
|
25
|
+
}): MemorySourceWindow;
|
|
@@ -0,0 +1,64 @@
|
|
|
1
|
+
import { createHash } from "node:crypto";
|
|
2
|
+
function isMessageEntry(entry) {
|
|
3
|
+
return entry.type === "message";
|
|
4
|
+
}
|
|
5
|
+
function messagesFromEntries(entries) {
|
|
6
|
+
return entries.filter(isMessageEntry).map((entry) => entry.message);
|
|
7
|
+
}
|
|
8
|
+
function hasToolResult(messages) {
|
|
9
|
+
return messages.some((message) => typeof message === "object" && message !== null && "role" in message && message.role === "toolResult");
|
|
10
|
+
}
|
|
11
|
+
function createWindowId(sourceKind, fromEntryId, throughEntryId, messages) {
|
|
12
|
+
const fallbackFingerprint = throughEntryId === undefined
|
|
13
|
+
? createHash("sha256").update(JSON.stringify(messages)).digest("hex").slice(0, 16)
|
|
14
|
+
: "";
|
|
15
|
+
return createHash("sha256")
|
|
16
|
+
.update([sourceKind, fromEntryId ?? "start", throughEntryId ?? fallbackFingerprint].join("\0"))
|
|
17
|
+
.digest("hex")
|
|
18
|
+
.slice(0, 20);
|
|
19
|
+
}
|
|
20
|
+
export function entriesSince(entries, lastEntryId) {
|
|
21
|
+
if (!lastEntryId) {
|
|
22
|
+
return [...entries];
|
|
23
|
+
}
|
|
24
|
+
const index = entries.findIndex((entry) => entry.id === lastEntryId);
|
|
25
|
+
return index >= 0 ? entries.slice(index + 1) : [...entries];
|
|
26
|
+
}
|
|
27
|
+
export function buildIncrementalMemorySourceWindow(options) {
|
|
28
|
+
const entries = entriesSince(options.entries, options.lastEntryId);
|
|
29
|
+
const entryMessages = messagesFromEntries(entries);
|
|
30
|
+
const messages = entryMessages.length > 0 || entries.length > 0 || options.lastEntryId !== undefined
|
|
31
|
+
? entryMessages
|
|
32
|
+
: [...(options.fallbackMessages ?? [])];
|
|
33
|
+
const throughEntryId = entries.at(-1)?.id;
|
|
34
|
+
return {
|
|
35
|
+
sourceKind: options.sourceKind,
|
|
36
|
+
fromEntryId: options.lastEntryId,
|
|
37
|
+
throughEntryId,
|
|
38
|
+
entries,
|
|
39
|
+
messages,
|
|
40
|
+
windowId: createWindowId(options.sourceKind, options.lastEntryId, throughEntryId, messages),
|
|
41
|
+
hasExternalToolContent: hasToolResult(messages),
|
|
42
|
+
};
|
|
43
|
+
}
|
|
44
|
+
export function buildCompactionMemorySourceWindow(options) {
|
|
45
|
+
const boundaryIndex = options.firstKeptEntryId
|
|
46
|
+
? options.entries.findIndex((entry) => entry.id === options.firstKeptEntryId)
|
|
47
|
+
: -1;
|
|
48
|
+
const coveredEntries = boundaryIndex >= 0 ? options.entries.slice(0, boundaryIndex) : [];
|
|
49
|
+
const incrementalEntries = entriesSince(coveredEntries, options.lastEntryId);
|
|
50
|
+
const throughEntryId = incrementalEntries.at(-1)?.id ?? coveredEntries.at(-1)?.id;
|
|
51
|
+
const incrementalMessages = messagesFromEntries(incrementalEntries);
|
|
52
|
+
const messages = incrementalMessages.length > 0 || options.lastEntryId !== undefined
|
|
53
|
+
? incrementalMessages
|
|
54
|
+
: [...options.messagesToSummarize];
|
|
55
|
+
return {
|
|
56
|
+
sourceKind: "compaction",
|
|
57
|
+
fromEntryId: options.lastEntryId,
|
|
58
|
+
throughEntryId,
|
|
59
|
+
entries: incrementalEntries,
|
|
60
|
+
messages,
|
|
61
|
+
windowId: createWindowId("compaction", options.lastEntryId, throughEntryId, messages),
|
|
62
|
+
hasExternalToolContent: hasToolResult(messages),
|
|
63
|
+
};
|
|
64
|
+
}
|
|
@@ -0,0 +1,12 @@
|
|
|
1
|
+
export interface MemoryTombstone {
|
|
2
|
+
entryId: string;
|
|
3
|
+
contentHash: string;
|
|
4
|
+
deletedAt: string;
|
|
5
|
+
scope: "channel";
|
|
6
|
+
reason: string;
|
|
7
|
+
sourceEntryIds?: string[];
|
|
8
|
+
}
|
|
9
|
+
export declare function hashMemoryContent(content: string): string;
|
|
10
|
+
export declare function getMemoryTombstonesPath(channelDir: string): string;
|
|
11
|
+
export declare function appendMemoryTombstone(channelDir: string, tombstone: MemoryTombstone): Promise<void>;
|
|
12
|
+
export declare function readMemoryTombstones(channelDir: string): Promise<MemoryTombstone[]>;
|