@oyasmi/pipiclaw 0.9.6-beta.2 → 0.9.6-beta.3
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.en.md +2 -2
- package/README.md +2 -2
- package/dist/agent/channel-runner.js +2 -0
- package/dist/agent/maintenance-context.js +21 -2
- package/dist/agent/turn/turn-context.js +10 -6
- package/dist/config/settings.d.ts +0 -2
- package/dist/config/settings.js +0 -2
- package/dist/config/tools.d.ts +8 -2
- package/dist/config/tools.js +35 -19
- package/dist/memory/anchors.d.ts +5 -0
- package/dist/memory/anchors.js +49 -0
- package/dist/memory/boundary-work.d.ts +1 -0
- package/dist/memory/boundary-work.js +1 -0
- package/dist/memory/commands.js +23 -6
- package/dist/memory/index-budget.d.ts +16 -0
- package/dist/memory/index-budget.js +24 -2
- package/dist/memory/journal.d.ts +7 -12
- package/dist/memory/journal.js +9 -41
- package/dist/memory/lifecycle.d.ts +1 -0
- package/dist/memory/lifecycle.js +2 -0
- package/dist/memory/reflect-job.d.ts +1 -0
- package/dist/memory/reflect-job.js +1 -0
- package/dist/memory/reflect.d.ts +10 -0
- package/dist/memory/reflect.js +103 -20
- package/dist/memory/render.d.ts +4 -1
- package/dist/memory/render.js +6 -4
- package/dist/memory/review-log.d.ts +2 -2
- package/dist/memory/scheduler.d.ts +7 -0
- package/dist/memory/scheduler.js +70 -3
- package/dist/memory/search-index-db.d.ts +15 -0
- package/dist/memory/search-index-db.js +247 -0
- package/dist/memory/search-index-files.d.ts +11 -0
- package/dist/memory/search-index-files.js +26 -0
- package/dist/memory/search-index-notes.d.ts +11 -0
- package/dist/memory/search-index-notes.js +155 -0
- package/dist/memory/search-index-sync.d.ts +19 -0
- package/dist/memory/search-index-sync.js +267 -0
- package/dist/memory/search-terms.d.ts +12 -0
- package/dist/memory/search-terms.js +185 -0
- package/dist/memory/search.d.ts +8 -28
- package/dist/memory/search.js +18 -278
- package/dist/memory/session-corpus.d.ts +15 -26
- package/dist/memory/session-corpus.js +120 -327
- package/dist/memory/session-search.d.ts +5 -3
- package/dist/memory/session-search.js +119 -171
- package/dist/memory/sidecar-worker.d.ts +2 -0
- package/dist/memory/sidecar-worker.js +25 -1
- package/dist/memory/store.d.ts +4 -0
- package/dist/memory/store.js +22 -1
- package/dist/memory/task-archive-digest.d.ts +61 -0
- package/dist/memory/task-archive-digest.js +366 -0
- package/dist/models/provider-login.d.ts +1 -1
- package/dist/models/provider-login.js +1 -1
- package/dist/playbooks/memory-operations.md +2 -2
- package/dist/shared/text-utils.d.ts +0 -1
- package/dist/shared/text-utils.js +0 -1
- package/dist/subagents/runs.d.ts +1 -1
- package/dist/subagents/task-envelope.js +6 -8
- package/dist/tools/memory-manage.d.ts +1 -0
- package/dist/tools/memory-manage.js +9 -23
- package/dist/tools/registry.js +2 -0
- package/dist/tools/session-search.d.ts +1 -0
- package/dist/tools/session-search.js +12 -6
- package/dist/tools/web-search.d.ts +13 -7
- package/dist/tools/web-search.js +62 -19
- package/dist/web/client.d.ts +2 -0
- package/dist/web/client.js +7 -3
- package/dist/web/config.d.ts +17 -4
- package/dist/web/config.js +42 -4
- package/dist/web/format.d.ts +2 -1
- package/dist/web/format.js +7 -3
- package/dist/web/search-providers.d.ts +15 -8
- package/dist/web/search-providers.js +208 -139
- package/dist/web/search.d.ts +13 -3
- package/dist/web/search.js +86 -40
- package/package.json +1 -1
- package/dist/memory/chinese-words.d.ts +0 -1
- package/dist/memory/chinese-words.js +0 -273
|
@@ -68,6 +68,7 @@ export async function runReflectJob(input) {
|
|
|
68
68
|
workspaceDir: input.workspaceDir,
|
|
69
69
|
model: input.model,
|
|
70
70
|
modelRequests: input.modelRequests,
|
|
71
|
+
resolveFallbackModel: input.resolveFallbackModel,
|
|
71
72
|
messages: sourceWindow.messages,
|
|
72
73
|
usageContext: { channelId, desk: conversation.desk, correlationId: sourceWindow.windowId },
|
|
73
74
|
});
|
package/dist/memory/reflect.d.ts
CHANGED
|
@@ -7,8 +7,18 @@ export interface ReflectRunOptions {
|
|
|
7
7
|
workspaceDir: string;
|
|
8
8
|
model: Model<Api>;
|
|
9
9
|
modelRequests: ModelRequests;
|
|
10
|
+
resolveFallbackModel?: () => Promise<Model<Api> | null>;
|
|
10
11
|
/** The conversation window to reflect on (already extracted by the caller's source window). */
|
|
11
12
|
messages: AgentMessage[];
|
|
13
|
+
/**
|
|
14
|
+
* Optional pre-formatted non-chat source (e.g. a closed task's distilled archive).
|
|
15
|
+
* When set, `messages` is ignored and this block is reflected on directly.
|
|
16
|
+
*/
|
|
17
|
+
sourceText?: {
|
|
18
|
+
label: string;
|
|
19
|
+
text: string;
|
|
20
|
+
hasUserMessage?: boolean;
|
|
21
|
+
};
|
|
12
22
|
timeoutMs?: number;
|
|
13
23
|
/** Closed boundary snapshots cannot wait for an answer from the outgoing session. */
|
|
14
24
|
sourceClosed?: boolean;
|
package/dist/memory/reflect.js
CHANGED
|
@@ -3,12 +3,13 @@ import { parseJsonObject } from "../shared/llm-json.js";
|
|
|
3
3
|
import { localDayKey } from "../shared/local-time.js";
|
|
4
4
|
import { readOptionalTextFile } from "../shared/os.js";
|
|
5
5
|
import { clipText } from "../shared/text-utils.js";
|
|
6
|
+
import { extractAnchors, findUnanchored, toolResultProvenance } from "./anchors.js";
|
|
6
7
|
import { buildMemoryIndexForBootstrap, MEMORY_INDEX_MAX_UNITS } from "./index-budget.js";
|
|
7
8
|
import { appendJournalEntries } from "./journal.js";
|
|
8
9
|
import { MEMORY_INPUT_SAFETY_RULES } from "./prompt-safety.js";
|
|
9
10
|
import { runRetriedSidecarTask } from "./sidecar-worker.js";
|
|
10
11
|
import { MEMORY_TRANSCRIPT_MAX_CHARS } from "./source-window.js";
|
|
11
|
-
import { applyMemoryOps, expireProbationaryEntries, isValidMemoryName, listMemoryEntries, renderMemoryIndex, } from "./store.js";
|
|
12
|
+
import { applyMemoryOps, expireProbationaryEntries, isValidMemoryName, listMemoryEntries, memoryActivityDate, renderMemoryIndex, } from "./store.js";
|
|
12
13
|
import { hasMeaningfulExchange, messageText, sanitizeMessagesForMemory } from "./transcript.js";
|
|
13
14
|
/**
|
|
14
15
|
* Spec 050, D7: the single background pass that replaces session-refresh, memory-checkpoint,
|
|
@@ -26,6 +27,7 @@ const MAX_DELETE_PER_RUN = 3;
|
|
|
26
27
|
const MAX_DELETE_PER_RUN_CONDENSE = 8;
|
|
27
28
|
const WORKSPACE_MEMORY_MAX_CHARS = 3_000;
|
|
28
29
|
const JOURNAL_TAIL_MAX_CHARS = 3_000;
|
|
30
|
+
const REFLECT_BODIES_MAX_CHARS = 6_000;
|
|
29
31
|
function probationDeadline(today) {
|
|
30
32
|
const ms = new Date(`${today}T00:00:00`).getTime() + PROBATION_DAYS * 24 * 60 * 60 * 1000;
|
|
31
33
|
return localDayKey(new Date(ms));
|
|
@@ -40,8 +42,8 @@ Output schema:
|
|
|
40
42
|
{
|
|
41
43
|
"journal": ["HH:MM one terse bullet about what happened, was decided, or is blocked"],
|
|
42
44
|
"ops": [
|
|
43
|
-
{"op": "add", "name": "kebab-case-handle (optional)", "type": "user|feedback|project|reference", "description": "one self-contained line", "details": "optional long form", "confidence": 0.0, "necessity": "low|medium|high", "reason": "why"},
|
|
44
|
-
{"op": "update", "name": "existing-name", "description": "...", "details": "
|
|
45
|
+
{"op": "add", "name": "kebab-case-handle (optional)", "type": "user|feedback|project|reference", "description": "one self-contained line", "details": "optional long form", "durability": "stable|state", "confidence": 0.0, "necessity": "low|medium|high", "reason": "why"},
|
|
46
|
+
{"op": "update", "name": "existing-name", "description": "...", "details": "(omit to keep existing body)", "durability": "stable|state", "confidence": 0.0, "necessity": "low|medium|high", "reason": "why"},
|
|
45
47
|
{"op": "delete", "name": "existing-name", "confidence": 0.0, "reason": "why this is no longer true"},
|
|
46
48
|
{"op": "touch", "names": ["existing-name", "..."]}
|
|
47
49
|
],
|
|
@@ -56,10 +58,13 @@ ${MEMORY_INPUT_SAFETY_RULES}
|
|
|
56
58
|
- "feedback": corrections about how to work, and lessons learned from a mistake.
|
|
57
59
|
- "project": stable facts, decisions, and constraints about what you're working on.
|
|
58
60
|
- "reference": pointers — paths, URLs, commands, contacts, ids.
|
|
59
|
-
-
|
|
60
|
-
-
|
|
61
|
-
-
|
|
62
|
-
-
|
|
61
|
+
- Every add/update MUST classify "durability":
|
|
62
|
+
- "stable": remains true until someone explicitly changes the preference, decision, convention, or pointer.
|
|
63
|
+
- "state": describes current code, system, or work status expected to change after later work (e.g., "X currently has a P1 regression", "current version is not ready to release", "task Y was restored", "a review found two P2 bugs"). NEVER put "state" facts in "ops" — record them in "journal" instead.
|
|
64
|
+
- An explicit standing rule from the user is a high-necessity, stable project constraint when future work must follow it. Extract it even if it was mentioned alongside a one-off request, tool output, or unrelated chat.
|
|
65
|
+
- Never write in-progress task state, transient debugging notes, point-in-time review findings, or anything with a natural end date as memory — that belongs in "journal", or the user should be told to use a task if it needs tracking. If the whole window is just progress or point-in-time status, "ops" should be empty (except "delete" if it resolves a stale entry or "touch" if it confirms an existing one).
|
|
66
|
+
- Prefer "update" over adding a near-duplicate of an existing entry (the index is given to you in full below); on "update", omit "details" unless you intend to replace the entry's existing body. Prefer "delete" over leaving a fact that the window shows is fixed or no longer true.
|
|
67
|
+
- "touch" lists the names of existing entries this window depended on or confirmed — do this whenever relevant, it costs nothing and promotes probationary entries while keeping active permanent entries fresh.
|
|
63
68
|
- Every add/update needs a calibrated confidence (0.0-1.0) and necessity ("high": would future turns go wrong or redo work without this; "medium": useful operating knowledge, nothing breaks without it; "low": not worth writing). Every delete needs a calibrated confidence.
|
|
64
69
|
- name must be lowercase kebab-case (letters, digits, hyphens only) if given at all; omit it to let the runtime generate one.
|
|
65
70
|
- Empty arrays are correct when nothing applies. Put anything you considered and rejected in "discarded".`;
|
|
@@ -99,32 +104,81 @@ function normalizeType(value) {
|
|
|
99
104
|
? value
|
|
100
105
|
: undefined;
|
|
101
106
|
}
|
|
102
|
-
|
|
103
|
-
|
|
104
|
-
|
|
107
|
+
function normalizeDurability(value) {
|
|
108
|
+
return value === "stable" || value === "state" ? value : undefined;
|
|
109
|
+
}
|
|
110
|
+
/**
|
|
111
|
+
* Durable if high-necessity, confident, and explicitly `stable`; probationary for medium-necessity
|
|
112
|
+
* `add` or when `durability` was omitted on a high-necessity `add` (safety net so unlabelled
|
|
113
|
+
* point-in-time facts expire after 30 days instead of polluting permanently).
|
|
114
|
+
*/
|
|
115
|
+
function classifyWrite(op, confidence, necessity, durability) {
|
|
116
|
+
if (durability === "state")
|
|
117
|
+
return undefined;
|
|
118
|
+
if (necessity === "high" && confidence >= DURABLE_CONFIDENCE) {
|
|
119
|
+
if (op === "add" && durability === undefined)
|
|
120
|
+
return "probationary";
|
|
105
121
|
return "durable";
|
|
122
|
+
}
|
|
106
123
|
if (op === "add" && necessity === "medium" && confidence >= PROBATION_CONFIDENCE)
|
|
107
124
|
return "probationary";
|
|
108
125
|
return undefined;
|
|
109
126
|
}
|
|
110
|
-
|
|
127
|
+
function renderIndexBodiesForReflect(entries) {
|
|
128
|
+
const withBody = entries
|
|
129
|
+
.filter((entry) => entry.body.trim().length > 0)
|
|
130
|
+
.sort((a, b) => memoryActivityDate(b).localeCompare(memoryActivityDate(a)) || a.name.localeCompare(b.name));
|
|
131
|
+
if (withBody.length === 0)
|
|
132
|
+
return "";
|
|
133
|
+
const blocks = [];
|
|
134
|
+
const omitted = [];
|
|
135
|
+
let usedChars = 0;
|
|
136
|
+
for (const entry of withBody) {
|
|
137
|
+
const block = `### ${entry.name}\n${entry.body.trim()}`;
|
|
138
|
+
if (usedChars + block.length > REFLECT_BODIES_MAX_CHARS) {
|
|
139
|
+
omitted.push(entry.name);
|
|
140
|
+
continue;
|
|
141
|
+
}
|
|
142
|
+
blocks.push(block);
|
|
143
|
+
usedChars += block.length + 2;
|
|
144
|
+
}
|
|
145
|
+
const parts = [];
|
|
146
|
+
if (blocks.length > 0) {
|
|
147
|
+
parts.push(`Details of (+) entries:\n${blocks.join("\n\n")}`);
|
|
148
|
+
}
|
|
149
|
+
if (omitted.length > 0) {
|
|
150
|
+
parts.push(`(+ body omitted — leave details unset on update to preserve them): ${omitted.join(", ")}`);
|
|
151
|
+
}
|
|
152
|
+
return parts.join("\n");
|
|
153
|
+
}
|
|
154
|
+
async function buildPrompt(options, today, source) {
|
|
111
155
|
const [entries, workspaceMemory, journalToday] = await Promise.all([
|
|
112
156
|
listMemoryEntries(options.deskDir),
|
|
113
157
|
readOptionalTextFile(`${options.workspaceDir}/MEMORY.md`),
|
|
114
158
|
readOptionalTextFile(`${options.deskDir}/journal/${today}.md`),
|
|
115
159
|
]);
|
|
116
160
|
const tiered = buildMemoryIndexForBootstrap(entries, MEMORY_INDEX_MAX_UNITS);
|
|
117
|
-
const
|
|
161
|
+
const sourceLabel = options.sourceText?.label ?? "Conversation window to reflect on";
|
|
162
|
+
const transcript = clipText(source, MEMORY_TRANSCRIPT_MAX_CHARS, { headRatio: 0.35 });
|
|
163
|
+
const provenance = [
|
|
164
|
+
source,
|
|
165
|
+
...toolResultProvenance(options.messages),
|
|
166
|
+
...entries.map((entry) => `${entry.description}\n${entry.body}`),
|
|
167
|
+
workspaceMemory,
|
|
168
|
+
journalToday,
|
|
169
|
+
].join("\n\n");
|
|
170
|
+
const bodies = renderIndexBodiesForReflect(entries);
|
|
118
171
|
const sections = [
|
|
119
172
|
`Desk memory index (full):\n${renderMemoryIndex(entries) || "(empty)"}`,
|
|
173
|
+
...(bodies ? [bodies] : []),
|
|
120
174
|
`Workspace background (read-only; do not target it with ops):\n${clipText(workspaceMemory, WORKSPACE_MEMORY_MAX_CHARS, { headRatio: 0.35 }) || "(empty)"}`,
|
|
121
175
|
`Today's journal so far:\n${clipText(journalToday, JOURNAL_TAIL_MAX_CHARS, { headRatio: 0 }) || "(empty)"}`,
|
|
122
|
-
|
|
176
|
+
`${sourceLabel}:\n${transcript || "(empty)"}`,
|
|
123
177
|
];
|
|
124
178
|
if (tiered.overBudget) {
|
|
125
179
|
sections.push(CONDENSE_INSTRUCTIONS.trim());
|
|
126
180
|
}
|
|
127
|
-
return { prompt: sections.join("\n\n"), condense: tiered.overBudget };
|
|
181
|
+
return { prompt: sections.join("\n\n"), condense: tiered.overBudget, provenance };
|
|
128
182
|
}
|
|
129
183
|
/**
|
|
130
184
|
* Run one reflect pass over `options.messages`. Deterministic invariants (write tier, per-run
|
|
@@ -149,16 +203,23 @@ export async function runReflect(options) {
|
|
|
149
203
|
};
|
|
150
204
|
// Deterministic pre-step, independent of whether the window has meaningful material.
|
|
151
205
|
const expiredProbation = await expireProbationaryEntries(options.deskDir, today);
|
|
152
|
-
const sanitized = sanitizeMessagesForMemory(options.messages);
|
|
153
|
-
if (
|
|
206
|
+
const sanitized = options.sourceText ? [] : sanitizeMessagesForMemory(options.messages);
|
|
207
|
+
if (options.sourceText) {
|
|
208
|
+
if (!options.sourceText.text.trim()) {
|
|
209
|
+
return { ...empty, skipped: true, expiredProbation };
|
|
210
|
+
}
|
|
211
|
+
}
|
|
212
|
+
else if (!hasMeaningfulExchange(sanitized) &&
|
|
154
213
|
!(options.sourceClosed && sanitized.some((message) => message.role === "user" && messageText(message).trim()))) {
|
|
155
214
|
return { ...empty, skipped: true, expiredProbation };
|
|
156
215
|
}
|
|
157
|
-
const
|
|
216
|
+
const source = options.sourceText?.text ?? serializeConversation(sanitized);
|
|
217
|
+
const { prompt, condense, provenance } = await buildPrompt(options, today, source);
|
|
158
218
|
const response = await runRetriedSidecarTask({
|
|
159
219
|
name: "memory-reflect",
|
|
160
220
|
model: options.model,
|
|
161
221
|
modelRequests: options.modelRequests,
|
|
222
|
+
resolveFallbackModel: options.resolveFallbackModel,
|
|
162
223
|
systemPrompt: REFLECT_SYSTEM_PROMPT,
|
|
163
224
|
prompt,
|
|
164
225
|
timeoutMs: options.timeoutMs ?? REFLECT_DEFAULT_TIMEOUT_MS,
|
|
@@ -168,7 +229,9 @@ export async function runReflect(options) {
|
|
|
168
229
|
const parsed = response.output;
|
|
169
230
|
const currentEntries = await listMemoryEntries(options.deskDir);
|
|
170
231
|
const byName = new Map(currentEntries.map((entry) => [entry.name, entry]));
|
|
171
|
-
const hasUserMessage =
|
|
232
|
+
const hasUserMessage = options.sourceText
|
|
233
|
+
? Boolean(options.sourceText.hasUserMessage)
|
|
234
|
+
: sanitized.some((message) => message.role === "user");
|
|
172
235
|
const rejected = [];
|
|
173
236
|
const storeOps = [];
|
|
174
237
|
let addCount = 0;
|
|
@@ -222,13 +285,24 @@ export async function runReflect(options) {
|
|
|
222
285
|
}
|
|
223
286
|
const confidence = normalizeConfidence(raw.confidence);
|
|
224
287
|
const necessity = normalizeNecessity(raw.necessity);
|
|
288
|
+
const durability = normalizeDurability(raw.durability);
|
|
225
289
|
const rawName = typeof raw.name === "string" ? raw.name.trim() : "";
|
|
226
|
-
|
|
290
|
+
// Blank `details` from reflect must never wipe an existing `(+)` body (A3).
|
|
291
|
+
const rawDetails = typeof raw.details === "string" ? raw.details.trim() : "";
|
|
292
|
+
const details = rawDetails ? rawDetails : undefined;
|
|
227
293
|
const type = normalizeType(raw.type);
|
|
228
294
|
// D7 risk table: an `update` naming an entry that doesn't exist downgrades to `add`
|
|
229
295
|
// rather than being silently dropped — the model's judgment about the fact still counts.
|
|
230
296
|
const existing = op === "update" && rawName ? byName.get(rawName) : undefined;
|
|
231
297
|
const effectiveOp = existing ? "update" : "add";
|
|
298
|
+
if (durability === "state") {
|
|
299
|
+
rejected.push({
|
|
300
|
+
op: effectiveOp,
|
|
301
|
+
name: existing?.name ?? rawName,
|
|
302
|
+
reason: "state belongs in journal",
|
|
303
|
+
});
|
|
304
|
+
continue;
|
|
305
|
+
}
|
|
232
306
|
if (effectiveOp === "update" && existing?.source === "user" && confidence < 0.95) {
|
|
233
307
|
rejected.push({ op: "update", name: existing.name, reason: "user-saved entry needs confidence >= 0.95" });
|
|
234
308
|
continue;
|
|
@@ -241,7 +315,7 @@ export async function runReflect(options) {
|
|
|
241
315
|
});
|
|
242
316
|
continue;
|
|
243
317
|
}
|
|
244
|
-
const tier = classifyWrite(effectiveOp, confidence, necessity);
|
|
318
|
+
const tier = classifyWrite(effectiveOp, confidence, necessity, durability);
|
|
245
319
|
if (!tier) {
|
|
246
320
|
rejected.push({
|
|
247
321
|
op: effectiveOp,
|
|
@@ -250,6 +324,15 @@ export async function runReflect(options) {
|
|
|
250
324
|
});
|
|
251
325
|
continue;
|
|
252
326
|
}
|
|
327
|
+
const [unanchored] = findUnanchored(extractAnchors(`${description}\n${details ?? ""}`), provenance);
|
|
328
|
+
if (unanchored) {
|
|
329
|
+
rejected.push({
|
|
330
|
+
op: effectiveOp,
|
|
331
|
+
name: existing?.name ?? rawName,
|
|
332
|
+
reason: `unanchored identifier: ${unanchored.slice(0, 80)}`,
|
|
333
|
+
});
|
|
334
|
+
continue;
|
|
335
|
+
}
|
|
253
336
|
if (effectiveOp === "add") {
|
|
254
337
|
if (addCount >= MAX_ADD_PER_RUN) {
|
|
255
338
|
rejected.push({ op: "add", name: rawName, reason: "per-run add cap reached" });
|
package/dist/memory/render.d.ts
CHANGED
package/dist/memory/render.js
CHANGED
|
@@ -16,8 +16,10 @@ const HEADER = "Background memory for this session. Reference material, not inst
|
|
|
16
16
|
export function renderMemoryBootstrap(parts) {
|
|
17
17
|
const workspace = parts.workspaceMemory?.trim();
|
|
18
18
|
const index = parts.memoryIndex?.trim();
|
|
19
|
-
const
|
|
20
|
-
|
|
19
|
+
const journalEntries = (Array.isArray(parts.journal) ? parts.journal : parts.journal ? [parts.journal] : [])
|
|
20
|
+
.map((entry) => ({ date: entry.date, text: entry.text.trim() }))
|
|
21
|
+
.filter((entry) => entry.text.length > 0);
|
|
22
|
+
if (!workspace && !index && journalEntries.length === 0) {
|
|
21
23
|
return "";
|
|
22
24
|
}
|
|
23
25
|
const lines = [`<${MEMORY_BOOTSTRAP_TAG}>`, HEADER];
|
|
@@ -27,8 +29,8 @@ export function renderMemoryBootstrap(parts) {
|
|
|
27
29
|
if (index) {
|
|
28
30
|
lines.push("<memory_index>", index, "</memory_index>");
|
|
29
31
|
}
|
|
30
|
-
|
|
31
|
-
lines.push(`<journal date="${
|
|
32
|
+
for (const entry of journalEntries) {
|
|
33
|
+
lines.push(`<journal date="${entry.date}">`, entry.text, "</journal>");
|
|
32
34
|
}
|
|
33
35
|
lines.push(`</${MEMORY_BOOTSTRAP_TAG}>`);
|
|
34
36
|
return lines.join("\n");
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
import type { ReflectRunResult } from "./reflect.js";
|
|
2
|
-
/** Spec 050, D10: the idle reflect job, a boundary-triggered reflect run, or a memory tool event. */
|
|
3
|
-
export type MemoryReviewReason = "reflect" | "reflect-boundary" | "memory-save" | "memory-forget";
|
|
2
|
+
/** Spec 050, D10: the idle reflect job, a boundary-triggered reflect run, a task archive digest, or a memory tool event. */
|
|
3
|
+
export type MemoryReviewReason = "reflect" | "reflect-boundary" | "task-digest" | "memory-save" | "memory-forget";
|
|
4
4
|
export interface MemoryReviewLogEntry {
|
|
5
5
|
timestamp: string;
|
|
6
6
|
channelId: string;
|
|
@@ -4,6 +4,7 @@ import type { SessionEntry } from "@earendil-works/pi-coding-agent";
|
|
|
4
4
|
import type { DeskConversation } from "../desk/types.js";
|
|
5
5
|
import type { ModelRequests } from "../models/requests.js";
|
|
6
6
|
import { type MemoryMaintenanceInput } from "./maintenance-tuning.js";
|
|
7
|
+
import { type DeskIndexTarget } from "./search-index-sync.js";
|
|
7
8
|
export interface MemoryMaintenanceRuntimeContext {
|
|
8
9
|
conversation: DeskConversation;
|
|
9
10
|
workspaceDir: string;
|
|
@@ -16,6 +17,7 @@ export interface MemoryMaintenanceRuntimeContext {
|
|
|
16
17
|
sessionEntries: () => SessionEntry[];
|
|
17
18
|
model: Model<Api>;
|
|
18
19
|
modelRequests: ModelRequests;
|
|
20
|
+
resolveFallbackModel?: () => Promise<Model<Api> | null>;
|
|
19
21
|
settings: {
|
|
20
22
|
memoryMaintenance: MemoryMaintenanceInput;
|
|
21
23
|
};
|
|
@@ -34,15 +36,20 @@ export interface MemoryMaintenanceSchedulerOptions {
|
|
|
34
36
|
memoryMaintenance: MemoryMaintenanceInput;
|
|
35
37
|
};
|
|
36
38
|
intervalMs?: number;
|
|
39
|
+
syncSearchIndex?: (target: DeskIndexTarget) => Promise<unknown>;
|
|
37
40
|
}
|
|
38
41
|
export declare class MemoryMaintenanceScheduler {
|
|
39
42
|
private readonly options;
|
|
40
43
|
private timer;
|
|
41
44
|
private running;
|
|
45
|
+
private orphansPruned;
|
|
42
46
|
private nextIndex;
|
|
47
|
+
private readonly startedAtMs;
|
|
43
48
|
constructor(options: MemoryMaintenanceSchedulerOptions);
|
|
44
49
|
start(): void;
|
|
45
50
|
stop(): void;
|
|
46
51
|
runOnce(now?: Date): Promise<void>;
|
|
52
|
+
private syncSearchIndexesOnce;
|
|
53
|
+
private digestArchivedTasksOnce;
|
|
47
54
|
private runConversationOnce;
|
|
48
55
|
}
|
package/dist/memory/scheduler.js
CHANGED
|
@@ -1,3 +1,4 @@
|
|
|
1
|
+
import { dirname } from "node:path";
|
|
1
2
|
import * as log from "../log.js";
|
|
2
3
|
import { errorMessage } from "../shared/text-utils.js";
|
|
3
4
|
import { hasBoundaryReflectWork } from "./boundary-work.js";
|
|
@@ -5,6 +6,8 @@ import { shouldRunReflect } from "./maintenance-gates.js";
|
|
|
5
6
|
import { readMemoryMaintenanceState } from "./maintenance-state.js";
|
|
6
7
|
import { resolveMemoryMaintenanceSettings } from "./maintenance-tuning.js";
|
|
7
8
|
import { runReflectJob } from "./reflect-job.js";
|
|
9
|
+
import { pruneOrphanSearchIndexes, syncDeskSearchIndex } from "./search-index-sync.js";
|
|
10
|
+
import { digestTaskArchives } from "./task-archive-digest.js";
|
|
8
11
|
const DEFAULT_TICK_INTERVAL_MS = 60_000;
|
|
9
12
|
/**
|
|
10
13
|
* Cheap due-time predicate, evaluated before `getRuntimeContext` (transcript access, model
|
|
@@ -35,15 +38,14 @@ export class MemoryMaintenanceScheduler {
|
|
|
35
38
|
this.options = options;
|
|
36
39
|
this.timer = null;
|
|
37
40
|
this.running = false;
|
|
41
|
+
this.orphansPruned = false;
|
|
38
42
|
this.nextIndex = 0;
|
|
43
|
+
this.startedAtMs = Date.now();
|
|
39
44
|
}
|
|
40
45
|
start() {
|
|
41
46
|
if (this.timer) {
|
|
42
47
|
return;
|
|
43
48
|
}
|
|
44
|
-
// `enabled` is re-checked on every tick inside `runOnce`, which is nearly free when
|
|
45
|
-
// disabled (one cached settings read, no channel scan). Gating `start()` on it too would
|
|
46
|
-
// mean flipping `memoryMaintenance.enabled` on at runtime never actually starts the timer.
|
|
47
49
|
this.timer = setInterval(() => {
|
|
48
50
|
void this.runOnce().catch((error) => {
|
|
49
51
|
log.logWarn("memory.scheduler.tick_failed", "Memory maintenance tick failed", {
|
|
@@ -71,6 +73,15 @@ export class MemoryMaintenanceScheduler {
|
|
|
71
73
|
if (conversations.length === 0) {
|
|
72
74
|
return;
|
|
73
75
|
}
|
|
76
|
+
await this.syncSearchIndexesOnce(conversations);
|
|
77
|
+
// Digest newly closed archived tasks per unique desk (B1). Recurring instances cost
|
|
78
|
+
// zero LLM calls; if a one-off task runs reflect, spend this tick's single LLM call
|
|
79
|
+
// there and return.
|
|
80
|
+
if (settings.memoryMaintenance.enabled) {
|
|
81
|
+
const usedLlmForTask = await this.digestArchivedTasksOnce(conversations, settings, now);
|
|
82
|
+
if (usedLlmForTask)
|
|
83
|
+
return;
|
|
84
|
+
}
|
|
74
85
|
// One conversation per tick, round-robin: a reflect pass is an LLM call, and the first
|
|
75
86
|
// due conversation is as good a place to spend it as any.
|
|
76
87
|
let selected;
|
|
@@ -92,6 +103,61 @@ export class MemoryMaintenanceScheduler {
|
|
|
92
103
|
this.running = false;
|
|
93
104
|
}
|
|
94
105
|
}
|
|
106
|
+
async syncSearchIndexesOnce(conversations) {
|
|
107
|
+
const { appHomeDir, syncSearchIndex = syncDeskSearchIndex } = this.options;
|
|
108
|
+
if (!this.orphansPruned) {
|
|
109
|
+
this.orphansPruned = true;
|
|
110
|
+
try {
|
|
111
|
+
await pruneOrphanSearchIndexes(appHomeDir, dirname(conversations[0].deskDir));
|
|
112
|
+
}
|
|
113
|
+
catch (error) {
|
|
114
|
+
log.logWarn("memory.search_index.prune_failed", "Search index prune failed", {
|
|
115
|
+
reason: errorMessage(error),
|
|
116
|
+
});
|
|
117
|
+
}
|
|
118
|
+
}
|
|
119
|
+
const desks = new Map(conversations.map(({ desk, deskDir }) => [desk, deskDir]));
|
|
120
|
+
for (const [desk, deskDir] of desks) {
|
|
121
|
+
try {
|
|
122
|
+
await syncSearchIndex({ appHomeDir, desk, deskDir });
|
|
123
|
+
}
|
|
124
|
+
catch (error) {
|
|
125
|
+
log.logWarn("memory.search_index.sync_failed", "Search index sync failed", {
|
|
126
|
+
reason: errorMessage(error),
|
|
127
|
+
fields: { desk },
|
|
128
|
+
});
|
|
129
|
+
}
|
|
130
|
+
}
|
|
131
|
+
}
|
|
132
|
+
async digestArchivedTasksOnce(conversations, settings, now) {
|
|
133
|
+
const seenDesks = new Set();
|
|
134
|
+
const maintenance = resolveMemoryMaintenanceSettings(settings.memoryMaintenance);
|
|
135
|
+
for (const conversation of conversations) {
|
|
136
|
+
if (seenDesks.has(conversation.desk))
|
|
137
|
+
continue;
|
|
138
|
+
seenDesks.add(conversation.desk);
|
|
139
|
+
const result = await digestTaskArchives({
|
|
140
|
+
target: conversation,
|
|
141
|
+
now,
|
|
142
|
+
initialWatermarkMs: this.startedAtMs,
|
|
143
|
+
failureBackoffMinutes: maintenance.failureBackoffMinutes,
|
|
144
|
+
loadReflectRuntime: async () => {
|
|
145
|
+
const context = await this.options.getRuntimeContext(conversation);
|
|
146
|
+
if (!context)
|
|
147
|
+
return null;
|
|
148
|
+
return {
|
|
149
|
+
workspaceDir: context.workspaceDir,
|
|
150
|
+
model: context.model,
|
|
151
|
+
modelRequests: context.modelRequests,
|
|
152
|
+
resolveFallbackModel: context.resolveFallbackModel,
|
|
153
|
+
};
|
|
154
|
+
},
|
|
155
|
+
});
|
|
156
|
+
if (result.usedLlm)
|
|
157
|
+
return true;
|
|
158
|
+
}
|
|
159
|
+
return false;
|
|
160
|
+
}
|
|
95
161
|
async runConversationOnce(conversation, now) {
|
|
96
162
|
if (this.options.isChannelActive(conversation.channelId)) {
|
|
97
163
|
return;
|
|
@@ -109,6 +175,7 @@ export class MemoryMaintenanceScheduler {
|
|
|
109
175
|
settings: context.settings,
|
|
110
176
|
model: context.model,
|
|
111
177
|
modelRequests: context.modelRequests,
|
|
178
|
+
resolveFallbackModel: context.resolveFallbackModel,
|
|
112
179
|
messages: context.messages,
|
|
113
180
|
sessionEntries: context.sessionEntries,
|
|
114
181
|
});
|
|
@@ -0,0 +1,15 @@
|
|
|
1
|
+
type Sqlite = typeof import("node:sqlite");
|
|
2
|
+
type Database = InstanceType<Sqlite["DatabaseSync"]>;
|
|
3
|
+
export interface SearchIndexHandle {
|
|
4
|
+
db: Database;
|
|
5
|
+
ino: number;
|
|
6
|
+
}
|
|
7
|
+
export declare function getSearchIndexDir(appHomeDir: string): string;
|
|
8
|
+
export declare function getSearchIndexPath(appHomeDir: string, desk: string): string;
|
|
9
|
+
export declare class SearchIndexUnavailableError extends Error {
|
|
10
|
+
}
|
|
11
|
+
export declare function transaction<T>(db: Database, work: () => T): T;
|
|
12
|
+
export declare function closeSearchIndexes(): Promise<void>;
|
|
13
|
+
export declare function removeSearchIndex(path: string): Promise<void>;
|
|
14
|
+
export declare function withSearchIndex<T>(path: string, job: (handle: SearchIndexHandle) => Promise<T>): Promise<T>;
|
|
15
|
+
export {};
|