@oyasmi/pipiclaw 0.8.8 → 0.8.9-beta.2
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 +8 -3
- package/dist/agent/channel-runner.d.ts +1 -0
- package/dist/agent/channel-runner.js +3 -2
- package/dist/agent/effect-ledger.d.ts +11 -0
- package/dist/agent/effect-ledger.js +42 -0
- package/dist/agent/job-manager.d.ts +90 -13
- package/dist/agent/job-manager.js +235 -20
- package/dist/agent/prompt/sections.js +11 -2
- package/dist/agent/prompt/types.d.ts +7 -1
- package/dist/agent/runner-factory.d.ts +7 -0
- package/dist/agent/session-events.js +20 -1
- package/dist/index.d.ts +1 -1
- package/dist/log.d.ts +6 -0
- package/dist/log.js +12 -0
- package/dist/memory/consolidation.d.ts +5 -0
- package/dist/memory/consolidation.js +35 -147
- package/dist/memory/extraction.d.ts +45 -0
- package/dist/memory/extraction.js +227 -0
- package/dist/memory/lifecycle.js +5 -0
- package/dist/memory/maintenance-jobs.js +7 -0
- package/dist/memory/post-turn-review.d.ts +3 -1
- package/dist/memory/post-turn-review.js +20 -189
- package/dist/memory/recall.d.ts +0 -1
- package/dist/memory/recall.js +135 -77
- package/dist/memory/sidecar-worker.d.ts +7 -0
- package/dist/memory/sidecar-worker.js +23 -5
- package/dist/memory/task-digest.js +1 -1
- package/dist/paths.d.ts +1 -0
- package/dist/paths.js +11 -0
- package/dist/playbooks/background-jobs.md +40 -0
- package/dist/playbooks/catalog.d.ts +1 -7
- package/dist/playbooks/catalog.js +4 -14
- package/dist/playbooks/event-scheduling.md +8 -4
- package/dist/playbooks/memory-and-learning.md +1 -1
- package/dist/playbooks/outbound-media.md +45 -0
- package/dist/playbooks/runtime-orientation.md +1 -1
- package/dist/playbooks/task-closeout.md +12 -11
- package/dist/playbooks/task-delegation.md +11 -5
- package/dist/playbooks/task-driving.md +54 -21
- package/dist/playbooks/task-planning.md +46 -19
- package/dist/runtime/bootstrap.js +29 -4
- package/dist/runtime/channel-context.d.ts +33 -0
- package/dist/runtime/dingtalk.d.ts +22 -2
- package/dist/runtime/dingtalk.js +141 -0
- package/dist/runtime/durable-dispatch.d.ts +10 -0
- package/dist/runtime/durable-dispatch.js +42 -1
- package/dist/runtime/event-validation.d.ts +48 -0
- package/dist/runtime/event-validation.js +81 -0
- package/dist/runtime/events.d.ts +17 -8
- package/dist/runtime/events.js +96 -22
- package/dist/runtime/store.d.ts +1 -1
- package/dist/runtime/task-commands.js +29 -51
- package/dist/runtime/task-driver.d.ts +5 -8
- package/dist/runtime/task-driver.js +120 -93
- package/dist/runtime/task-migration.d.ts +11 -0
- package/dist/runtime/task-migration.js +70 -0
- package/dist/settings.d.ts +11 -0
- package/dist/settings.js +12 -0
- package/dist/shared/recoverable-error.d.ts +26 -0
- package/dist/shared/recoverable-error.js +29 -0
- package/dist/shared/task-events.d.ts +0 -26
- package/dist/shared/task-events.js +0 -15
- package/dist/shared/task-ledger.d.ts +32 -8
- package/dist/shared/task-ledger.js +66 -17
- package/dist/subagents/builtin/explorer.md +16 -0
- package/dist/subagents/builtin/researcher.md +17 -0
- package/dist/subagents/builtin/verifier.md +17 -0
- package/dist/subagents/discovery.d.ts +17 -3
- package/dist/subagents/discovery.js +88 -15
- package/dist/subagents/tool.d.ts +21 -1
- package/dist/subagents/tool.js +140 -12
- package/dist/tasks/control.d.ts +4 -0
- package/dist/tasks/control.js +3 -0
- package/dist/tasks/store.d.ts +28 -1
- package/dist/tasks/store.js +63 -6
- package/dist/tasks/transitions.d.ts +40 -0
- package/dist/tasks/transitions.js +82 -0
- package/dist/tools/bash.d.ts +2 -0
- package/dist/tools/bash.js +18 -5
- package/dist/tools/event-manage.js +28 -77
- package/dist/tools/index.d.ts +4 -0
- package/dist/tools/index.js +7 -2
- package/dist/tools/job.js +2 -2
- package/dist/tools/memory-manage.js +0 -1
- package/dist/tools/registry.d.ts +29 -8
- package/dist/tools/registry.js +39 -22
- package/dist/tools/send-media.d.ts +28 -0
- package/dist/tools/send-media.js +88 -0
- package/dist/tools/task-manage/create.d.ts +2 -0
- package/dist/tools/task-manage/create.js +35 -0
- package/dist/tools/task-manage/lifecycle.d.ts +6 -0
- package/dist/tools/task-manage/lifecycle.js +197 -0
- package/dist/tools/task-manage/schema.d.ts +43 -0
- package/dist/tools/task-manage/schema.js +90 -0
- package/dist/tools/task-manage/shared.d.ts +36 -0
- package/dist/tools/task-manage/shared.js +247 -0
- package/dist/tools/task-manage/types.d.ts +53 -0
- package/dist/tools/task-manage/types.js +1 -0
- package/dist/tools/task-manage/verification.d.ts +16 -0
- package/dist/tools/task-manage/verification.js +112 -0
- package/dist/tools/task-manage.d.ts +9 -89
- package/dist/tools/task-manage.js +8 -696
- package/dist/tools/tool-details.d.ts +44 -0
- package/dist/tools/tool-details.js +62 -0
- package/dist/tui/app.js +2 -0
- package/dist/tui/terminal-media-sender.d.ts +9 -0
- package/dist/tui/terminal-media-sender.js +15 -0
- package/package.json +2 -2
- package/dist/playbooks/task-recurring.md +0 -41
- package/dist/playbooks/task-repair.md +0 -45
|
@@ -0,0 +1,227 @@
|
|
|
1
|
+
import { serializeConversation } from "@earendil-works/pi-coding-agent";
|
|
2
|
+
import { parseJsonObject } from "../shared/llm-json.js";
|
|
3
|
+
import { clipText } from "../shared/text-utils.js";
|
|
4
|
+
import { isRecord } from "../shared/type-guards.js";
|
|
5
|
+
import { parseChannelMemoryEntries, readChannelHistory, readChannelMemory, readChannelSession, } from "./files.js";
|
|
6
|
+
import { runRetriedSidecarTask } from "./sidecar-worker.js";
|
|
7
|
+
import { sanitizeMessagesForMemory } from "./transcript.js";
|
|
8
|
+
/**
|
|
9
|
+
* The single LLM extraction pass behind every durable-memory writer.
|
|
10
|
+
*
|
|
11
|
+
* Boundary consolidation, idle consolidation, and the growth review used to run three
|
|
12
|
+
* separate prompts with three schemas and three quality bars — and because two of them
|
|
13
|
+
* applied no confidence gate at all, the standard for MEMORY.md was set by whichever
|
|
14
|
+
* writer happened to fire. They now share this prompt, this schema, and (via
|
|
15
|
+
* `shouldAutoWriteMemory`) one bar. Callers still own their own side effects: only
|
|
16
|
+
* boundaries write HISTORY.md, only the growth review proposes skills.
|
|
17
|
+
*/
|
|
18
|
+
const MEMORY_OPS_RULES = `- memoryOps entries operate on the durable channel MEMORY.md:
|
|
19
|
+
- {"op":"add","content":"...","kind":"fact|preference|decision|constraint|open-loop|lesson"} for a genuinely new durable fact.
|
|
20
|
+
- {"op":"supersede","targetId":"m-xxxx","content":"...","kind":"..."} when new information updates or contradicts an existing entry (use its id).
|
|
21
|
+
- {"op":"invalidate","targetId":"m-xxxx","reason":"..."} when an existing entry is now obsolete or resolved.
|
|
22
|
+
- Only reference targetId values that appear in the current MEMORY.md entries shown below.
|
|
23
|
+
- Durable = stable facts, decisions, preferences, constraints, or medium-horizon open loops.
|
|
24
|
+
- Each content string must be a standalone, keyword-rich sentence fragment suitable for a Markdown bullet (no leading "-"). Write it so future keyword search can find it.
|
|
25
|
+
- Do not add content already present in SESSION.md or MEMORY.md; prefer supersede/invalidate over piling on near-duplicates.
|
|
26
|
+
- Do not promote active execution state, temporary debugging observations, completed worklog, raw transcript quotes, acknowledgements, or formatting instructions.
|
|
27
|
+
- Every memoryOp must carry a calibrated confidence (0.0-1.0) and a necessity of "low", "medium", or "high".
|
|
28
|
+
- necessity is "high" only when future turns would go wrong without this entry. Routine progress is "low".
|
|
29
|
+
- Be conservative. Empty arrays are correct when nothing should be stored. Put anything you considered and rejected in "discarded".`;
|
|
30
|
+
const HISTORY_BLOCK_RULES = `- historyBlock: concise Markdown summarizing the conversation chunk for later recovery.
|
|
31
|
+
- For any conversation that contains at least one meaningful user request and one meaningful assistant reply, return a non-empty historyBlock with at least one bullet.
|
|
32
|
+
- Prefer short bullets and short paragraphs. historyBlock is not gated by confidence, so it is the safe place for context that is real but not durable.`;
|
|
33
|
+
const SKILL_RULES = `- Workspace skills are procedural memory: reusable workflows, checklists, playbooks, templates, or scripts.
|
|
34
|
+
- Propose skill writes only when the workflow is clearly reusable across future tasks.
|
|
35
|
+
- Use action=create only for new self-contained skills with YAML frontmatter and a non-empty body.
|
|
36
|
+
- Skill names must be lowercase kebab-case.`;
|
|
37
|
+
export function buildMemoryExtractionSystemPrompt(options) {
|
|
38
|
+
const schemaFields = [
|
|
39
|
+
` "memoryOps": [{"op": "add|supersede|invalidate", "targetId": "required for supersede/invalidate", "content": "standalone durable memory bullet without '-'", "kind": "fact|preference|decision|constraint|open-loop|lesson", "confidence": 0.0, "necessity": "low|medium|high", "reason": "why it should or should not be stored"}]`,
|
|
40
|
+
];
|
|
41
|
+
if (options.includeHistoryBlock) {
|
|
42
|
+
schemaFields.push(` "historyBlock": "string"`);
|
|
43
|
+
}
|
|
44
|
+
if (options.includeSkills) {
|
|
45
|
+
schemaFields.push(` "skillCandidates": [{"action": "create|patch|write_file", "name": "skill-name", "content": "full SKILL.md or supporting file content", "filePath": "optional supporting file path", "find": "exact patch find text", "replace": "exact patch replacement text", "confidence": 0.0, "necessity": "low|medium|high", "reason": "why this procedural memory matters"}]`);
|
|
46
|
+
}
|
|
47
|
+
schemaFields.push(` "discarded": [{"content": "string", "reason": "string"}]`);
|
|
48
|
+
return [
|
|
49
|
+
"You are Pipiclaw's durable memory extraction worker.",
|
|
50
|
+
"",
|
|
51
|
+
"Return strict JSON only. Do not wrap in Markdown fences.",
|
|
52
|
+
"",
|
|
53
|
+
"Output schema:",
|
|
54
|
+
"{",
|
|
55
|
+
schemaFields.join(",\n"),
|
|
56
|
+
"}",
|
|
57
|
+
"",
|
|
58
|
+
"Rules:",
|
|
59
|
+
MEMORY_OPS_RULES,
|
|
60
|
+
...(options.includeHistoryBlock ? [HISTORY_BLOCK_RULES] : []),
|
|
61
|
+
...(options.includeSkills ? [SKILL_RULES] : []),
|
|
62
|
+
].join("\n");
|
|
63
|
+
}
|
|
64
|
+
function normalizeConfidence(value) {
|
|
65
|
+
return typeof value === "number" && Number.isFinite(value) ? Math.max(0, Math.min(1, value)) : 0;
|
|
66
|
+
}
|
|
67
|
+
function normalizeNecessity(value) {
|
|
68
|
+
return value === "high" || value === "medium" || value === "low" ? value : "low";
|
|
69
|
+
}
|
|
70
|
+
export function normalizeMemoryEntryKind(value) {
|
|
71
|
+
return value === "preference" ||
|
|
72
|
+
value === "decision" ||
|
|
73
|
+
value === "constraint" ||
|
|
74
|
+
value === "open-loop" ||
|
|
75
|
+
value === "lesson"
|
|
76
|
+
? value
|
|
77
|
+
: "fact";
|
|
78
|
+
}
|
|
79
|
+
function normalizeMemoryCandidate(value) {
|
|
80
|
+
if (!isRecord(value)) {
|
|
81
|
+
return null;
|
|
82
|
+
}
|
|
83
|
+
// `target` is legacy: channel MEMORY.md is the only durable target. Reject an explicit
|
|
84
|
+
// foreign target, but do not require the field.
|
|
85
|
+
if (value.target !== undefined && value.target !== "channel-memory") {
|
|
86
|
+
return null;
|
|
87
|
+
}
|
|
88
|
+
const op = value.op === "supersede" || value.op === "invalidate" ? value.op : "add";
|
|
89
|
+
const targetId = typeof value.targetId === "string" ? value.targetId.trim() : undefined;
|
|
90
|
+
const content = typeof value.content === "string" ? value.content.trim() : undefined;
|
|
91
|
+
if ((op === "invalidate" && !targetId) || (op !== "invalidate" && !content)) {
|
|
92
|
+
return null;
|
|
93
|
+
}
|
|
94
|
+
return {
|
|
95
|
+
target: "channel-memory",
|
|
96
|
+
op,
|
|
97
|
+
targetId,
|
|
98
|
+
content,
|
|
99
|
+
kind: normalizeMemoryEntryKind(value.kind),
|
|
100
|
+
confidence: normalizeConfidence(value.confidence),
|
|
101
|
+
necessity: normalizeNecessity(value.necessity),
|
|
102
|
+
reason: typeof value.reason === "string" ? value.reason.trim() : "",
|
|
103
|
+
};
|
|
104
|
+
}
|
|
105
|
+
function normalizeSkillCandidate(value) {
|
|
106
|
+
if (!isRecord(value)) {
|
|
107
|
+
return null;
|
|
108
|
+
}
|
|
109
|
+
const action = value.action;
|
|
110
|
+
if (action !== "create" && action !== "patch" && action !== "write_file") {
|
|
111
|
+
return null;
|
|
112
|
+
}
|
|
113
|
+
const name = typeof value.name === "string" ? value.name.trim() : "";
|
|
114
|
+
if (!name) {
|
|
115
|
+
return null;
|
|
116
|
+
}
|
|
117
|
+
return {
|
|
118
|
+
action,
|
|
119
|
+
name,
|
|
120
|
+
content: typeof value.content === "string" ? value.content : undefined,
|
|
121
|
+
filePath: typeof value.filePath === "string" ? value.filePath : undefined,
|
|
122
|
+
find: typeof value.find === "string" ? value.find : undefined,
|
|
123
|
+
replace: typeof value.replace === "string" ? value.replace : undefined,
|
|
124
|
+
confidence: normalizeConfidence(value.confidence),
|
|
125
|
+
necessity: normalizeNecessity(value.necessity),
|
|
126
|
+
reason: typeof value.reason === "string" ? value.reason.trim() : "",
|
|
127
|
+
};
|
|
128
|
+
}
|
|
129
|
+
export function parseMemoryExtractionResult(value) {
|
|
130
|
+
const record = isRecord(value) ? value : {};
|
|
131
|
+
// `memoryCandidates` is an older field name still emitted by some models.
|
|
132
|
+
const rawMemoryOps = Array.isArray(record.memoryOps)
|
|
133
|
+
? record.memoryOps
|
|
134
|
+
: Array.isArray(record.memoryCandidates)
|
|
135
|
+
? record.memoryCandidates
|
|
136
|
+
: [];
|
|
137
|
+
return {
|
|
138
|
+
memoryOps: rawMemoryOps
|
|
139
|
+
.map(normalizeMemoryCandidate)
|
|
140
|
+
.filter((item) => item !== null),
|
|
141
|
+
skillCandidates: Array.isArray(record.skillCandidates)
|
|
142
|
+
? record.skillCandidates
|
|
143
|
+
.map(normalizeSkillCandidate)
|
|
144
|
+
.filter((item) => item !== null)
|
|
145
|
+
: [],
|
|
146
|
+
historyBlock: typeof record.historyBlock === "string" ? record.historyBlock.trim() : "",
|
|
147
|
+
discarded: Array.isArray(record.discarded)
|
|
148
|
+
? record.discarded
|
|
149
|
+
.filter(isRecord)
|
|
150
|
+
.map((item) => ({
|
|
151
|
+
content: typeof item.content === "string" ? item.content : "",
|
|
152
|
+
reason: typeof item.reason === "string" ? item.reason : "",
|
|
153
|
+
}))
|
|
154
|
+
.filter((item) => item.content.trim() || item.reason.trim())
|
|
155
|
+
: [],
|
|
156
|
+
};
|
|
157
|
+
}
|
|
158
|
+
/** Turn an accepted candidate into a write op, stamping shared provenance metadata. */
|
|
159
|
+
export function toMemoryOp(candidate, provenance) {
|
|
160
|
+
if (candidate.op === "invalidate") {
|
|
161
|
+
return { op: "invalidate", targetId: candidate.targetId ?? "", reason: candidate.reason };
|
|
162
|
+
}
|
|
163
|
+
const metadata = {
|
|
164
|
+
kind: candidate.kind,
|
|
165
|
+
sourceType: "agent",
|
|
166
|
+
trust: "inferred",
|
|
167
|
+
sourceCorrelationId: provenance.correlationId,
|
|
168
|
+
};
|
|
169
|
+
if (candidate.op === "supersede") {
|
|
170
|
+
return {
|
|
171
|
+
op: "supersede",
|
|
172
|
+
targetId: candidate.targetId ?? "",
|
|
173
|
+
content: candidate.content ?? "",
|
|
174
|
+
sourceEntryIds: provenance.sourceEntryIds,
|
|
175
|
+
metadata,
|
|
176
|
+
};
|
|
177
|
+
}
|
|
178
|
+
return {
|
|
179
|
+
op: "add",
|
|
180
|
+
content: candidate.content ?? "",
|
|
181
|
+
sourceEntryIds: provenance.sourceEntryIds,
|
|
182
|
+
metadata,
|
|
183
|
+
};
|
|
184
|
+
}
|
|
185
|
+
/** Entries rendered as `id — content` so supersede/invalidate can reference real ids. */
|
|
186
|
+
function renderMemoryEntriesForPrompt(rawMemory) {
|
|
187
|
+
const entries = parseChannelMemoryEntries(rawMemory);
|
|
188
|
+
if (entries.length === 0) {
|
|
189
|
+
return "";
|
|
190
|
+
}
|
|
191
|
+
return entries.map((entry) => `${entry.id} — ${entry.content}`).join("\n");
|
|
192
|
+
}
|
|
193
|
+
export async function runMemoryExtraction(request) {
|
|
194
|
+
const [currentSession, rawMemory, currentHistory] = await Promise.all([
|
|
195
|
+
readChannelSession(request.channelDir),
|
|
196
|
+
readChannelMemory(request.channelDir),
|
|
197
|
+
readChannelHistory(request.channelDir),
|
|
198
|
+
]);
|
|
199
|
+
const transcript = clipText(serializeConversation(sanitizeMessagesForMemory(request.messages)), request.transcriptMaxChars, { headRatio: 0.35 });
|
|
200
|
+
const currentMemory = clipText(renderMemoryEntriesForPrompt(rawMemory), 8_000, { headRatio: 0.35 });
|
|
201
|
+
const promptSections = [
|
|
202
|
+
`Current SESSION.md:\n${clipText(currentSession, 8_000, { headRatio: 0.35 }) || "(empty)"}`,
|
|
203
|
+
`Current MEMORY.md entries (id — content; reference ids in supersede/invalidate):\n${currentMemory || "(empty)"}`,
|
|
204
|
+
`Channel history file:\n${clipText(currentHistory, 8_000, { headRatio: 0.35 }) || "(empty)"}`,
|
|
205
|
+
];
|
|
206
|
+
if (request.includeSkills) {
|
|
207
|
+
const skills = (request.loadedSkills ?? [])
|
|
208
|
+
.map((skill) => `- ${skill.name}${skill.description ? `: ${skill.description}` : ""}`)
|
|
209
|
+
.join("\n");
|
|
210
|
+
promptSections.push(`Loaded workspace skills:\n${skills || "(none)"}`);
|
|
211
|
+
}
|
|
212
|
+
promptSections.push(`Conversation chunk to persist:\n${transcript || "(empty)"}`);
|
|
213
|
+
const result = await runRetriedSidecarTask({
|
|
214
|
+
name: request.name,
|
|
215
|
+
model: request.model,
|
|
216
|
+
resolveApiKey: request.resolveApiKey,
|
|
217
|
+
systemPrompt: buildMemoryExtractionSystemPrompt({
|
|
218
|
+
includeHistoryBlock: request.includeHistoryBlock,
|
|
219
|
+
includeSkills: request.includeSkills,
|
|
220
|
+
}),
|
|
221
|
+
prompt: promptSections.join("\n\n"),
|
|
222
|
+
timeoutMs: request.timeoutMs,
|
|
223
|
+
usageContext: request.usageContext,
|
|
224
|
+
parse: (text) => parseMemoryExtractionResult(parseJsonObject(text)),
|
|
225
|
+
});
|
|
226
|
+
return result.output;
|
|
227
|
+
}
|
package/dist/memory/lifecycle.js
CHANGED
|
@@ -172,6 +172,11 @@ export class MemoryLifecycle {
|
|
|
172
172
|
else if (reason === "idle") {
|
|
173
173
|
skipped.push({ target: "HISTORY.md", reason: "idle does not write HISTORY.md" });
|
|
174
174
|
}
|
|
175
|
+
// Defensive: review-log bookkeeping runs after the consolidation has already been
|
|
176
|
+
// applied and checkpointed, so a shape surprise here must not report success as failure.
|
|
177
|
+
for (const candidate of result.rejectedMemoryOps ?? []) {
|
|
178
|
+
skipped.push({ target: "MEMORY.md", candidate, reason: "below auto-write confidence" });
|
|
179
|
+
}
|
|
175
180
|
await this.appendReviewLog({ reason, actions, skipped });
|
|
176
181
|
}
|
|
177
182
|
async runPreflightConsolidation(reason, messages, sessionEntries, firstKeptEntryId) {
|
|
@@ -60,6 +60,8 @@ function makeRunOptions(input, usageCorrelationId) {
|
|
|
60
60
|
messages: input.messages,
|
|
61
61
|
sessionEntries: input.sessionEntries,
|
|
62
62
|
usageCorrelationId,
|
|
63
|
+
// One durable-write bar across consolidation and the growth review.
|
|
64
|
+
minAutoWriteConfidence: input.settings.memoryGrowth.minMemoryAutoWriteConfidence,
|
|
63
65
|
};
|
|
64
66
|
}
|
|
65
67
|
function backoffUntil(now, settings) {
|
|
@@ -187,6 +189,11 @@ export async function runDurableConsolidationJob(input) {
|
|
|
187
189
|
}
|
|
188
190
|
: {
|
|
189
191
|
actions: [{ target: "MEMORY.md", action: "append", entries: result.appendedMemoryEntries }],
|
|
192
|
+
skipped: (result.rejectedMemoryOps ?? []).map((candidate) => ({
|
|
193
|
+
target: "MEMORY.md",
|
|
194
|
+
candidate,
|
|
195
|
+
reason: "below auto-write confidence",
|
|
196
|
+
})),
|
|
190
197
|
correlationId: sourceWindow.windowId,
|
|
191
198
|
}, now);
|
|
192
199
|
return ran("durable-consolidation");
|
|
@@ -1,5 +1,6 @@
|
|
|
1
1
|
import type { AgentMessage } from "@earendil-works/pi-agent-core";
|
|
2
2
|
import type { Api, Model } from "@earendil-works/pi-ai";
|
|
3
|
+
import { parseMemoryExtractionResult } from "./extraction.js";
|
|
3
4
|
import { type PostTurnReviewResult } from "./promotion.js";
|
|
4
5
|
export interface PostTurnReviewOptions {
|
|
5
6
|
channelId: string;
|
|
@@ -36,6 +37,7 @@ export type PostTurnReviewRunResult = {
|
|
|
36
37
|
status: "failed";
|
|
37
38
|
error: string;
|
|
38
39
|
};
|
|
39
|
-
|
|
40
|
+
/** Re-exported so existing callers and tests keep one parser for the shared schema. */
|
|
41
|
+
export declare const parsePostTurnReviewResult: typeof parseMemoryExtractionResult;
|
|
40
42
|
export declare function applyPostTurnReviewResult(options: PostTurnReviewOptions, review: PostTurnReviewResult): Promise<PostTurnReviewApplyResult>;
|
|
41
43
|
export declare function runPostTurnReview(options: PostTurnReviewOptions): Promise<PostTurnReviewRunResult>;
|
|
@@ -1,177 +1,30 @@
|
|
|
1
|
-
import {
|
|
2
|
-
import { parseJsonObject } from "../shared/llm-json.js";
|
|
3
|
-
import { clipText, errorMessage } from "../shared/text-utils.js";
|
|
4
|
-
import { isRecord } from "../shared/type-guards.js";
|
|
1
|
+
import { errorMessage } from "../shared/text-utils.js";
|
|
5
2
|
import { manageWorkspaceSkill } from "../tools/skill-manage.js";
|
|
6
|
-
import {
|
|
3
|
+
import { parseMemoryExtractionResult, runMemoryExtraction, toMemoryOp } from "./extraction.js";
|
|
4
|
+
import { applyChannelMemoryOps } from "./files.js";
|
|
7
5
|
import { containsSecret } from "./policy.js";
|
|
8
6
|
import { shouldAutoWriteMemory, shouldAutoWriteSkill, } from "./promotion.js";
|
|
9
7
|
import { appendMemoryReviewLog } from "./review-log.js";
|
|
10
|
-
|
|
11
|
-
|
|
12
|
-
const
|
|
13
|
-
|
|
14
|
-
Return strict JSON only:
|
|
15
|
-
{
|
|
16
|
-
"memoryOps": [
|
|
17
|
-
{
|
|
18
|
-
"target": "channel-memory",
|
|
19
|
-
"op": "add|supersede|invalidate",
|
|
20
|
-
"targetId": "required for supersede/invalidate",
|
|
21
|
-
"content": "standalone durable memory bullet without '-'",
|
|
22
|
-
"kind": "fact|preference|decision|constraint|open-loop|lesson",
|
|
23
|
-
"confidence": 0.0,
|
|
24
|
-
"necessity": "low|medium|high",
|
|
25
|
-
"reason": "why it should or should not be stored"
|
|
26
|
-
}
|
|
27
|
-
],
|
|
28
|
-
"skillCandidates": [
|
|
29
|
-
{
|
|
30
|
-
"action": "create|patch|write_file",
|
|
31
|
-
"name": "skill-name",
|
|
32
|
-
"content": "full SKILL.md or supporting file content",
|
|
33
|
-
"filePath": "optional supporting file path",
|
|
34
|
-
"find": "exact patch find text",
|
|
35
|
-
"replace": "exact patch replacement text",
|
|
36
|
-
"confidence": 0.0,
|
|
37
|
-
"necessity": "low|medium|high",
|
|
38
|
-
"reason": "why this procedural memory matters"
|
|
39
|
-
}
|
|
40
|
-
],
|
|
41
|
-
"discarded": [{"content": "string", "reason": "string"}]
|
|
42
|
-
}
|
|
43
|
-
|
|
44
|
-
Rules:
|
|
45
|
-
- Channel MEMORY.md is only for durable facts, durable decisions, user/team preferences, stable constraints, and medium-horizon open loops.
|
|
46
|
-
- Do not promote current step-by-step execution state, short-lived debugging observations, completed worklog, or acknowledgement chatter.
|
|
47
|
-
- Workspace skills are procedural memory: reusable workflows, checklists, playbooks, templates, or scripts.
|
|
48
|
-
- Propose skill writes only when the workflow is clearly reusable across future tasks.
|
|
49
|
-
- Use action=create only for new self-contained skills with YAML frontmatter and a non-empty body.
|
|
50
|
-
- Skill names must be lowercase kebab-case.
|
|
51
|
-
- Be conservative. Empty arrays are correct when nothing should be stored.`;
|
|
52
|
-
function normalizeConfidence(value) {
|
|
53
|
-
return typeof value === "number" && Number.isFinite(value) ? Math.max(0, Math.min(1, value)) : 0;
|
|
54
|
-
}
|
|
55
|
-
function normalizeNecessity(value) {
|
|
56
|
-
return value === "high" || value === "medium" || value === "low" ? value : "low";
|
|
57
|
-
}
|
|
58
|
-
function normalizeMemoryCandidate(value) {
|
|
59
|
-
if (!isRecord(value)) {
|
|
60
|
-
return null;
|
|
61
|
-
}
|
|
62
|
-
if (value.target !== "channel-memory") {
|
|
63
|
-
return null;
|
|
64
|
-
}
|
|
65
|
-
const target = "channel-memory";
|
|
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)) {
|
|
77
|
-
return null;
|
|
78
|
-
}
|
|
79
|
-
return {
|
|
80
|
-
target,
|
|
81
|
-
op,
|
|
82
|
-
targetId,
|
|
83
|
-
content,
|
|
84
|
-
kind,
|
|
85
|
-
confidence: normalizeConfidence(value.confidence),
|
|
86
|
-
necessity: normalizeNecessity(value.necessity),
|
|
87
|
-
reason: typeof value.reason === "string" ? value.reason.trim() : "",
|
|
88
|
-
};
|
|
89
|
-
}
|
|
90
|
-
function normalizeSkillCandidate(value) {
|
|
91
|
-
if (!isRecord(value)) {
|
|
92
|
-
return null;
|
|
93
|
-
}
|
|
94
|
-
const action = value.action;
|
|
95
|
-
if (action !== "create" && action !== "patch" && action !== "write_file") {
|
|
96
|
-
return null;
|
|
97
|
-
}
|
|
98
|
-
const name = typeof value.name === "string" ? value.name.trim() : "";
|
|
99
|
-
if (!name) {
|
|
100
|
-
return null;
|
|
101
|
-
}
|
|
102
|
-
return {
|
|
103
|
-
action,
|
|
104
|
-
name,
|
|
105
|
-
content: typeof value.content === "string" ? value.content : undefined,
|
|
106
|
-
filePath: typeof value.filePath === "string" ? value.filePath : undefined,
|
|
107
|
-
find: typeof value.find === "string" ? value.find : undefined,
|
|
108
|
-
replace: typeof value.replace === "string" ? value.replace : undefined,
|
|
109
|
-
confidence: normalizeConfidence(value.confidence),
|
|
110
|
-
necessity: normalizeNecessity(value.necessity),
|
|
111
|
-
reason: typeof value.reason === "string" ? value.reason.trim() : "",
|
|
112
|
-
};
|
|
113
|
-
}
|
|
114
|
-
export function parsePostTurnReviewResult(value) {
|
|
115
|
-
const record = isRecord(value) ? value : {};
|
|
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)
|
|
123
|
-
: [];
|
|
124
|
-
const skillCandidates = Array.isArray(record.skillCandidates)
|
|
125
|
-
? record.skillCandidates.map(normalizeSkillCandidate).filter((item) => !!item)
|
|
126
|
-
: [];
|
|
127
|
-
const discarded = Array.isArray(record.discarded)
|
|
128
|
-
? record.discarded
|
|
129
|
-
.filter(isRecord)
|
|
130
|
-
.map((item) => ({
|
|
131
|
-
content: typeof item.content === "string" ? item.content : "",
|
|
132
|
-
reason: typeof item.reason === "string" ? item.reason : "",
|
|
133
|
-
}))
|
|
134
|
-
.filter((item) => item.content.trim() || item.reason.trim())
|
|
135
|
-
: [];
|
|
136
|
-
return { memoryOps, skillCandidates, discarded };
|
|
137
|
-
}
|
|
8
|
+
const POST_TURN_TRANSCRIPT_MAX_CHARS = 22_000;
|
|
9
|
+
/** Re-exported so existing callers and tests keep one parser for the shared schema. */
|
|
10
|
+
export const parsePostTurnReviewResult = parseMemoryExtractionResult;
|
|
138
11
|
async function runPostTurnReviewWorker(options) {
|
|
139
|
-
|
|
140
|
-
readChannelSession(options.channelDir),
|
|
141
|
-
readChannelMemory(options.channelDir),
|
|
142
|
-
readChannelHistory(options.channelDir),
|
|
143
|
-
]);
|
|
144
|
-
const transcript = clipText(serializeConversation(sanitizeMessagesForMemory(options.messages)), 22_000, {
|
|
145
|
-
headRatio: 0.35,
|
|
146
|
-
});
|
|
147
|
-
const skills = options.loadedSkills
|
|
148
|
-
.map((skill) => `- ${skill.name}${skill.description ? `: ${skill.description}` : ""}`)
|
|
149
|
-
.join("\n");
|
|
150
|
-
const prompt = `Current SESSION.md:
|
|
151
|
-
${clipText(currentSession, 6_000, { headRatio: 0.5 }) || "(empty)"}
|
|
152
|
-
|
|
153
|
-
Current channel MEMORY.md:
|
|
154
|
-
${clipText(currentMemory, 6_000, { headRatio: 0.5 }) || "(empty)"}
|
|
155
|
-
|
|
156
|
-
Current channel HISTORY.md:
|
|
157
|
-
${clipText(currentHistory, 2_000, { headRatio: 0.3 }) || "(empty)"}
|
|
158
|
-
|
|
159
|
-
Loaded workspace skills:
|
|
160
|
-
${skills || "(none)"}
|
|
161
|
-
|
|
162
|
-
Recent transcript:
|
|
163
|
-
${transcript || "(empty)"}`;
|
|
164
|
-
const result = await runRetriedSidecarTask({
|
|
12
|
+
return runMemoryExtraction({
|
|
165
13
|
name: "memory-post-turn-review",
|
|
14
|
+
channelId: options.channelId,
|
|
15
|
+
channelDir: options.channelDir,
|
|
16
|
+
messages: options.messages,
|
|
166
17
|
model: options.model,
|
|
167
18
|
resolveApiKey: options.resolveApiKey,
|
|
168
|
-
systemPrompt: POST_TURN_REVIEW_SYSTEM_PROMPT,
|
|
169
|
-
prompt,
|
|
170
19
|
timeoutMs: options.timeoutMs,
|
|
20
|
+
transcriptMaxChars: POST_TURN_TRANSCRIPT_MAX_CHARS,
|
|
21
|
+
// The growth review is the only path that proposes procedural memory, and the only one
|
|
22
|
+
// that does not summarize into HISTORY.md.
|
|
23
|
+
includeHistoryBlock: false,
|
|
24
|
+
includeSkills: true,
|
|
25
|
+
loadedSkills: options.loadedSkills,
|
|
171
26
|
usageContext: { channelId: options.channelId, correlationId: options.correlationId },
|
|
172
|
-
parse: (text) => parsePostTurnReviewResult(parseJsonObject(text)),
|
|
173
27
|
});
|
|
174
|
-
return result.output;
|
|
175
28
|
}
|
|
176
29
|
async function applyMemoryCandidate(options, candidate, result, timestamp) {
|
|
177
30
|
if (options.suppressAutomaticWrites ||
|
|
@@ -184,32 +37,10 @@ async function applyMemoryCandidate(options, candidate, result, timestamp) {
|
|
|
184
37
|
result.skipped.push({ type: "memory", candidate: { ...candidate, content: "[REDACTED]" }, reason: "secret" });
|
|
185
38
|
return;
|
|
186
39
|
}
|
|
187
|
-
const op = candidate
|
|
188
|
-
|
|
189
|
-
:
|
|
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
|
-
};
|
|
40
|
+
const op = toMemoryOp(candidate, {
|
|
41
|
+
sourceEntryIds: options.sourceEntryIds,
|
|
42
|
+
correlationId: options.correlationId,
|
|
43
|
+
});
|
|
213
44
|
const applied = await applyChannelMemoryOps(options.channelDir, [op], timestamp);
|
|
214
45
|
if (applied.blockedByPolicy > 0 || applied.blockedByTombstone > 0) {
|
|
215
46
|
result.skipped.push({ type: "memory", entry: candidate.targetId, reason: "blocked by memory policy" });
|
package/dist/memory/recall.d.ts
CHANGED