@oyasmi/pipiclaw 0.8.9-beta.1 → 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.
Files changed (90) hide show
  1. package/README.md +8 -3
  2. package/dist/agent/channel-runner.d.ts +1 -0
  3. package/dist/agent/channel-runner.js +3 -2
  4. package/dist/agent/effect-ledger.d.ts +11 -0
  5. package/dist/agent/effect-ledger.js +42 -0
  6. package/dist/agent/job-manager.d.ts +90 -13
  7. package/dist/agent/job-manager.js +235 -20
  8. package/dist/agent/prompt/sections.js +11 -2
  9. package/dist/agent/prompt/types.d.ts +7 -1
  10. package/dist/agent/runner-factory.d.ts +7 -0
  11. package/dist/agent/session-events.js +20 -1
  12. package/dist/index.d.ts +1 -1
  13. package/dist/log.d.ts +6 -0
  14. package/dist/log.js +12 -0
  15. package/dist/memory/consolidation.d.ts +5 -0
  16. package/dist/memory/consolidation.js +35 -147
  17. package/dist/memory/extraction.d.ts +45 -0
  18. package/dist/memory/extraction.js +227 -0
  19. package/dist/memory/lifecycle.js +5 -0
  20. package/dist/memory/maintenance-jobs.js +7 -0
  21. package/dist/memory/post-turn-review.d.ts +3 -1
  22. package/dist/memory/post-turn-review.js +20 -189
  23. package/dist/memory/recall.d.ts +0 -1
  24. package/dist/memory/recall.js +135 -77
  25. package/dist/memory/sidecar-worker.d.ts +7 -0
  26. package/dist/memory/sidecar-worker.js +23 -5
  27. package/dist/paths.d.ts +1 -0
  28. package/dist/paths.js +11 -0
  29. package/dist/playbooks/background-jobs.md +40 -0
  30. package/dist/playbooks/catalog.d.ts +1 -7
  31. package/dist/playbooks/catalog.js +4 -14
  32. package/dist/playbooks/event-scheduling.md +8 -4
  33. package/dist/playbooks/memory-and-learning.md +1 -1
  34. package/dist/playbooks/outbound-media.md +45 -0
  35. package/dist/playbooks/runtime-orientation.md +1 -1
  36. package/dist/playbooks/task-closeout.md +1 -1
  37. package/dist/playbooks/task-delegation.md +10 -4
  38. package/dist/playbooks/task-driving.md +52 -18
  39. package/dist/playbooks/task-planning.md +43 -18
  40. package/dist/runtime/bootstrap.js +24 -3
  41. package/dist/runtime/channel-context.d.ts +33 -0
  42. package/dist/runtime/dingtalk.d.ts +22 -2
  43. package/dist/runtime/dingtalk.js +141 -0
  44. package/dist/runtime/durable-dispatch.d.ts +10 -0
  45. package/dist/runtime/durable-dispatch.js +42 -1
  46. package/dist/runtime/event-validation.d.ts +48 -0
  47. package/dist/runtime/event-validation.js +81 -0
  48. package/dist/runtime/events.d.ts +17 -8
  49. package/dist/runtime/events.js +96 -22
  50. package/dist/runtime/store.d.ts +1 -1
  51. package/dist/runtime/task-driver.d.ts +5 -0
  52. package/dist/runtime/task-driver.js +38 -12
  53. package/dist/settings.d.ts +11 -0
  54. package/dist/settings.js +12 -0
  55. package/dist/shared/recoverable-error.d.ts +26 -0
  56. package/dist/shared/recoverable-error.js +29 -0
  57. package/dist/shared/task-ledger.d.ts +9 -7
  58. package/dist/shared/task-ledger.js +1 -1
  59. package/dist/subagents/builtin/explorer.md +16 -0
  60. package/dist/subagents/builtin/researcher.md +17 -0
  61. package/dist/subagents/builtin/verifier.md +17 -0
  62. package/dist/subagents/discovery.d.ts +17 -3
  63. package/dist/subagents/discovery.js +88 -15
  64. package/dist/subagents/tool.d.ts +21 -1
  65. package/dist/subagents/tool.js +140 -12
  66. package/dist/tasks/transitions.js +3 -2
  67. package/dist/tools/bash.d.ts +2 -0
  68. package/dist/tools/bash.js +18 -5
  69. package/dist/tools/event-manage.js +28 -77
  70. package/dist/tools/index.d.ts +4 -0
  71. package/dist/tools/index.js +7 -2
  72. package/dist/tools/job.js +2 -2
  73. package/dist/tools/memory-manage.js +0 -1
  74. package/dist/tools/registry.d.ts +29 -8
  75. package/dist/tools/registry.js +39 -22
  76. package/dist/tools/send-media.d.ts +28 -0
  77. package/dist/tools/send-media.js +88 -0
  78. package/dist/tools/task-manage/create.js +5 -4
  79. package/dist/tools/task-manage/lifecycle.js +12 -11
  80. package/dist/tools/task-manage/schema.js +2 -1
  81. package/dist/tools/task-manage/shared.js +13 -12
  82. package/dist/tools/task-manage/verification.js +14 -13
  83. package/dist/tools/tool-details.d.ts +44 -0
  84. package/dist/tools/tool-details.js +62 -0
  85. package/dist/tui/app.js +2 -0
  86. package/dist/tui/terminal-media-sender.d.ts +9 -0
  87. package/dist/tui/terminal-media-sender.js +15 -0
  88. package/package.json +2 -2
  89. package/dist/playbooks/task-recurring.md +0 -44
  90. 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
+ }
@@ -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
- export declare function parsePostTurnReviewResult(value: unknown): PostTurnReviewResult;
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 { serializeConversation } from "@earendil-works/pi-coding-agent";
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 { applyChannelMemoryOps, readChannelHistory, readChannelMemory, readChannelSession, } from "./files.js";
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
- import { runRetriedSidecarTask } from "./sidecar-worker.js";
11
- import { sanitizeMessagesForMemory } from "./transcript.js";
12
- const POST_TURN_REVIEW_SYSTEM_PROMPT = `You are Pipiclaw's post-turn memory reviewer.
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
- const [currentSession, currentMemory, currentHistory] = await Promise.all([
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.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
- };
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" });
@@ -17,7 +17,6 @@ export interface RecallRequest {
17
17
  */
18
18
  maxUnits?: number;
19
19
  rerankWithModel: boolean | "auto";
20
- autoRerank?: boolean;
21
20
  model: Model<Api>;
22
21
  resolveApiKey: (model: Model<Api>) => Promise<string>;
23
22
  candidateStore?: MemoryCandidateStore;