@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
@@ -122,9 +122,18 @@ export const SUBAGENTS_SECTION = {
122
122
  maxChars: 2_400,
123
123
  overflow: "truncate-items",
124
124
  render: (context) => {
125
- // No predefined agents: the section carries nothing worth its cost (spec 026 §6.3).
125
+ // Two-state (spec 032 D1): an empty predefined catalog must not delete the runtime
126
+ // guidance that lives in this section — only the catalog itself is optional. This
127
+ // inline-usage text is runtime-authored, not user content; keep it under 40 units
128
+ // (it does not count toward the 700/1200 unit budget — see builder.ts's
129
+ // RUNTIME_AUTHORED_SECTION_IDS — so it must not be padded just because it is "free").
126
130
  if (context.subAgents.length === 0) {
127
- return undefined;
131
+ return [
132
+ "## Sub-Agents",
133
+ "Delegate with `subagent`: pass an inline `systemPrompt` (no predefined agent is required).",
134
+ "A sub-agent starts blank — state goal, scope, paths, constraints, acceptance criteria in `task`.",
135
+ "Read task-delegation.md before non-trivial delegation.",
136
+ ].join("\n");
128
137
  }
129
138
  return [
130
139
  "## Predefined Sub-Agents",
@@ -27,10 +27,16 @@ export type PromptCacheClass = "runtime-stable" | "workspace-versioned" | "sessi
27
27
  * `error` is for runtime-authored text: overflowing it is a development error, not a user problem.
28
28
  */
29
29
  export type PromptOverflowPolicy = "error" | "truncate-head-tail" | "truncate-items" | "omit";
30
+ /**
31
+ * A registered tool, as the prompt builder sees it. There is no per-tool prose here and no
32
+ * section renders this list: spec 026 §3.2 removed `## Available Tools` because the model
33
+ * already receives each tool's name, description and schema with every request. The list is
34
+ * kept because the builder still needs it to decide whether a mechanism is reachable —
35
+ * gating sections (`requiresAllTools`), filtering playbooks, and reporting via `/context`.
36
+ */
30
37
  export interface ToolDescriptor {
31
38
  name: string;
32
39
  description: string;
33
- hint?: string;
34
40
  }
35
41
  export interface SubAgentSummary {
36
42
  name: string;
@@ -1,3 +1,4 @@
1
+ import type { MediaSender } from "../runtime/channel-context.js";
1
2
  import type { AgentRunner } from "./types.js";
2
3
  export interface RunnerFactoryPaths {
3
4
  appHomeDir: string;
@@ -5,6 +6,12 @@ export interface RunnerFactoryPaths {
5
6
  modelsConfigPath: string;
6
7
  /** Optional, side-effect-free observer used by the behavior-eval harness. */
7
8
  onSessionEvent?: (event: unknown, channelId: string) => void;
9
+ /**
10
+ * Transport that can deliver file attachments (the DingTalk bot, or the terminal).
11
+ * Present enables the `send_media` tool; absent, the tool is not built. Not part
12
+ * of the runner cache key — it is a stable per-process transport handle.
13
+ */
14
+ mediaSender?: MediaSender;
8
15
  }
9
16
  export declare function getOrCreateRunner(channelId: string, channelDir: string, paths: RunnerFactoryPaths): AgentRunner;
10
17
  export declare function resetRunner(channelId: string, paths?: RunnerFactoryPaths, channelDir?: string): void;
@@ -1,6 +1,8 @@
1
1
  import * as log from "../log.js";
2
2
  import { extractLabelFromArgs, truncate } from "../shared/text-utils.js";
3
3
  import { isRecord } from "../shared/type-guards.js";
4
+ import { toolResultDetails } from "../tools/tool-details.js";
5
+ import { isEffectfulTool, noteChannelEffect } from "./effect-ledger.js";
4
6
  import { extractToolResultText, formatProgressEntry } from "./progress-formatter.js";
5
7
  import { extractCustomCommandResultText, isAssistantEventMessage, isAutoCompactionEndEvent, isAutoCompactionStartEvent, isAutoRetryStartEvent, isMessageEndEvent, isMessageStartEvent, isSubAgentToolDetails, isTextPart, isThinkingPart, isToolExecutionEndEvent, isToolExecutionStartEvent, isToolExecutionUpdateEvent, isTurnEndEvent, } from "./type-guards.js";
6
8
  function isSkillManageDetails(value) {
@@ -121,7 +123,7 @@ export async function handleSessionEvent(event, context) {
121
123
  },
122
124
  }) ?? Promise.resolve(), "sub-agent run log");
123
125
  }
124
- const details = isRecord(event.result) && "details" in event.result ? event.result.details : null;
126
+ const details = toolResultDetails(event.result);
125
127
  if (isSkillManageDetails(details)) {
126
128
  if (details.requiresResourceRefresh && context.refreshSessionResources) {
127
129
  queue.enqueue(() => context.refreshSessionResources?.() ?? Promise.resolve(), "refresh skills");
@@ -130,13 +132,27 @@ export async function handleSessionEvent(event, context) {
130
132
  queue.enqueue(() => ctx.respondInThread(details.notice ?? ""), "skill notice");
131
133
  }
132
134
  }
135
+ // A recoverable rejection (bad arguments, unmet precondition the model can fix) is not a
136
+ // fault: the model normally corrects it on the next call. It is logged so the retry is
137
+ // still diagnosable, but never rendered to the user — a red bubble would report a failure
138
+ // that never happened and make the assistant look broken mid-turn. Rejections the *user*
139
+ // must resolve (an approval gate, a guard refusal) stay plain errors and remain visible.
140
+ const rejected = details?.recoverable === true;
133
141
  const treatAsError = event.isError || Boolean(subAgentDetails?.failed);
134
142
  if (treatAsError) {
135
143
  log.logToolError(logCtx, event.toolName, durationMs, resultStr);
136
144
  }
145
+ else if (rejected) {
146
+ log.logToolRejected(logCtx, event.toolName, durationMs, resultStr);
147
+ }
137
148
  else {
138
149
  log.logToolSuccess(logCtx, event.toolName, durationMs, resultStr);
139
150
  }
151
+ // A tool that actually changed something outside the task ledger is the evidence the task
152
+ // governor judges progress by (spec 031, D7).
153
+ if (!treatAsError && !rejected && isEffectfulTool(event.toolName, details)) {
154
+ noteChannelEffect(logCtx.channelId);
155
+ }
140
156
  if (treatAsError && showProgress) {
141
157
  queue.enqueue(() => ctx.respond(formatProgressEntry("error", truncate(resultStr, 200)), false), "tool error");
142
158
  }
@@ -231,6 +247,9 @@ export async function handleSessionEvent(event, context) {
231
247
  if (runState.finalOutcome.kind === "final" && runState.finalOutcome.text.trim() === trimmedFinalText) {
232
248
  return;
233
249
  }
250
+ // A real answer to the user is a visible result even when no file changed (D7);
251
+ // a [SILENT] turn above deliberately does not reach here.
252
+ noteChannelEffect(logCtx.channelId);
234
253
  runState.finalOutcome = { kind: "final", text: finalText };
235
254
  memoryLifecycle.noteCompletedAssistantTurn();
236
255
  log.logResponse(logCtx, finalText);
package/dist/index.d.ts CHANGED
@@ -23,7 +23,7 @@ export type { ChannelContext, ChannelContext as DingTalkContext, FinalDelivery,
23
23
  export { ensureChannelDir, getChannelDir, getChannelDirName, } from "./runtime/channel-paths.js";
24
24
  export { createDingTalkContext } from "./runtime/delivery.js";
25
25
  export { type BusyMessageDefaultConfig, type BusyMessageMode, DingTalkBot, type DingTalkConfig, type DingTalkEvent, type DingTalkHandler, finalDeliveryOf, isBusyMessageDefaultConfig, isResponseModeConfig, normalizeBusyMessageDefault, normalizeResponseMode, progressStyleOf, type ResponseMode, } from "./runtime/dingtalk.js";
26
- export { createEventsWatcher, type EventAction, EventsWatcher, type ImmediateEvent, type OneShotEvent, type PeriodicEvent, type ScheduledEvent, } from "./runtime/events.js";
26
+ export { createEventsWatcher, type EventAction, EventsWatcher, type OneShotEvent, type PeriodicEvent, type ScheduledEvent, } from "./runtime/events.js";
27
27
  export { ChannelStore, type LoggedMessage, type LoggedSubAgentRun } from "./runtime/store.js";
28
28
  export { type PipiclawMemoryGrowthSettings, type PipiclawMemoryMaintenanceSettings, type PipiclawMemoryRecallSettings, type PipiclawSessionMemorySettings, type PipiclawSettings, PipiclawSettingsManager, } from "./settings.js";
29
29
  export { discoverSubAgents, formatSubAgentList, getSubAgentsDir, type ResolvedSubAgentConfig, resolveSubAgentConfig, type SubAgentConfig, type SubAgentContextMode, type SubAgentDiscoveryResult, type SubAgentInvocationOverrides, type SubAgentMemoryMode, type SubAgentToolName, } from "./subagents/discovery.js";
package/dist/log.d.ts CHANGED
@@ -27,6 +27,12 @@ export declare function flushLogging(): Promise<void>;
27
27
  export declare function logEvent(level: LogLevel, event: string, message: string, options?: LogOptions): void;
28
28
  export declare function logToolStart(ctx: LogContext, toolName: string, label: string, args: Record<string, unknown>): void;
29
29
  export declare function logToolSuccess(ctx: LogContext, toolName: string, durationMs: number, result: string): void;
30
+ /**
31
+ * A tool call the model can fix itself (bad arguments, unmet precondition). Logged at debug,
32
+ * not warn: it is an expected step in a self-correcting turn, not an operator problem. Kept
33
+ * distinct from success so a model looping on the same rejection is still visible in the log.
34
+ */
35
+ export declare function logToolRejected(ctx: LogContext, toolName: string, durationMs: number, reason: string): void;
30
36
  export declare function logToolError(ctx: LogContext, toolName: string, durationMs: number, error: string): void;
31
37
  export declare function logResponseStart(ctx: LogContext): void;
32
38
  export declare function logThinking(ctx: LogContext, thinking: string): void;
package/dist/log.js CHANGED
@@ -187,6 +187,18 @@ export function logToolSuccess(ctx, toolName, durationMs, result) {
187
187
  fields: { tool: toolName, durationMs, resultLength: result.length },
188
188
  });
189
189
  }
190
+ /**
191
+ * A tool call the model can fix itself (bad arguments, unmet precondition). Logged at debug,
192
+ * not warn: it is an expected step in a self-correcting turn, not an operator problem. Kept
193
+ * distinct from success so a model looping on the same rejection is still visible in the log.
194
+ */
195
+ export function logToolRejected(ctx, toolName, durationMs, reason) {
196
+ logEvent("debug", "agent.tool.rejected", "Tool rejected the call", {
197
+ ctx,
198
+ details: reason,
199
+ fields: { tool: toolName, durationMs, reason },
200
+ });
201
+ }
190
202
  export function logToolError(ctx, toolName, durationMs, error) {
191
203
  logEvent("warn", "agent.tool.failed", "Tool failed", {
192
204
  ctx,
@@ -2,6 +2,7 @@ import type { AgentMessage } from "@earendil-works/pi-agent-core";
2
2
  import type { Api, Model } from "@earendil-works/pi-ai";
3
3
  import { type SessionEntry } from "@earendil-works/pi-coding-agent";
4
4
  import type { PipiclawMemoryMaintenanceSettings } from "../settings.js";
5
+ import { type MemoryPromotionCandidate } from "./promotion.js";
5
6
  import type { MemorySourceWindow } from "./source-window.js";
6
7
  export type ConsolidationMode = "idle" | "boundary";
7
8
  export interface ConsolidationRunOptions {
@@ -14,11 +15,15 @@ export interface ConsolidationRunOptions {
14
15
  sourceWindow?: MemorySourceWindow;
15
16
  mode?: ConsolidationMode;
16
17
  usageCorrelationId?: string;
18
+ /** Durable-write bar; defaults to the same threshold the growth review uses. */
19
+ minAutoWriteConfidence?: number;
17
20
  }
18
21
  export interface InlineConsolidationResult {
19
22
  skipped: boolean;
20
23
  appendedMemoryEntries: number;
21
24
  appendedHistoryBlock: boolean;
25
+ /** Candidates the confidence gate turned down, surfaced for the review log. */
26
+ rejectedMemoryOps: MemoryPromotionCandidate[];
22
27
  }
23
28
  export interface StructuralMaintenanceStats {
24
29
  memoryCleanupNeeded: boolean;
@@ -1,9 +1,9 @@
1
- import { getLatestCompactionEntry, serializeConversation, } from "@earendil-works/pi-coding-agent";
2
- import { parseJsonObject } from "../shared/llm-json.js";
1
+ import { getLatestCompactionEntry } from "@earendil-works/pi-coding-agent";
3
2
  import { splitH2Sections } from "../shared/markdown-sections.js";
4
- import { clipText } from "../shared/text-utils.js";
5
- import { appendChannelHistoryArchive, appendChannelHistoryBlock, applyChannelMemoryOps, parseChannelMemoryEntries, readChannelHistory, readChannelMemory, readChannelSession, rewriteChannelHistory, rewriteChannelMemory, } from "./files.js";
6
- import { runRetriedSidecarTask, runSidecarTask } from "./sidecar-worker.js";
3
+ import { runMemoryExtraction, toMemoryOp } from "./extraction.js";
4
+ import { appendChannelHistoryArchive, appendChannelHistoryBlock, applyChannelMemoryOps, parseChannelMemoryEntries, rewriteChannelHistory, rewriteChannelMemory, } from "./files.js";
5
+ import { DEFAULT_MEMORY_AUTO_WRITE_CONFIDENCE, shouldAutoWriteMemory, } from "./promotion.js";
6
+ import { runSidecarTask } from "./sidecar-worker.js";
7
7
  import { sanitizeMessagesForMemory } from "./transcript.js";
8
8
  const INLINE_TRANSCRIPT_MAX_CHARS = 28_000;
9
9
  const MEMORY_CLEANUP_LENGTH_THRESHOLD = 5_000;
@@ -14,56 +14,6 @@ const HISTORY_RECENT_BLOCKS_TO_KEEP = 3;
14
14
  const INLINE_CONSOLIDATION_TIMEOUT_MS = 20_000;
15
15
  const MEMORY_CLEANUP_TIMEOUT_MS = 120_000;
16
16
  const HISTORY_FOLDING_TIMEOUT_MS = 120_000;
17
- const MEMORY_OPS_RULES = `- memoryOps entries operate on the durable channel MEMORY.md:
18
- - {"op":"add","content":"...","kind":"fact|preference|decision|constraint|open-loop|lesson"} for a genuinely new durable fact.
19
- - {"op":"supersede","targetId":"m-xxxx","content":"...","kind":"..."} when new information updates or contradicts an existing entry (use its id).
20
- - {"op":"invalidate","targetId":"m-xxxx","reason":"..."} when an existing entry is now obsolete or resolved.
21
- - Only reference targetId values that appear in the current MEMORY.md entries shown below.
22
- - Durable = stable facts, decisions, preferences, constraints, or medium-horizon open loops.
23
- - 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.
24
- - Do not add content already present in SESSION.md or MEMORY.md; prefer supersede/invalidate over piling on near-duplicates.
25
- - Do not promote active execution state, temporary debugging observations, completed worklog, raw transcript quotes, acknowledgements, or formatting instructions.`;
26
- const BOUNDARY_INLINE_CONSOLIDATION_SYSTEM_PROMPT = `You are a runtime memory consolidation worker for Pipiclaw.
27
-
28
- Return strict JSON only. Do not wrap in Markdown fences.
29
-
30
- Output schema:
31
- {
32
- "memoryOps": [{"op": "add|supersede|invalidate", "targetId": "m-xxxx", "content": "string", "reason": "string"}],
33
- "historyBlock": "string"
34
- }
35
-
36
- Rules:
37
- ${MEMORY_OPS_RULES}
38
- - historyBlock: concise Markdown summarizing the conversation chunk for later recovery.
39
- - 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.
40
- - Prefer short bullets and short paragraphs.
41
- - If there is nothing worth storing, return an empty memoryOps array and empty historyBlock.
42
-
43
- Example output for a short useful exchange:
44
- {
45
- "memoryOps": [{"op": "add", "content": "User prefers dark mode in the dashboard"}],
46
- "historyBlock": "- User asked how to toggle dashboard theme; confirmed dark mode preference."
47
- }`;
48
- const IDLE_INLINE_CONSOLIDATION_SYSTEM_PROMPT = `You are a runtime memory consolidation worker for Pipiclaw.
49
-
50
- Return strict JSON only. Do not wrap in Markdown fences.
51
-
52
- Output schema:
53
- {
54
- "memoryOps": [{"op": "add|supersede|invalidate", "targetId": "m-xxxx", "content": "string", "reason": "string"}]
55
- }
56
-
57
- Rules:
58
- - This is an idle maintenance pass after a normal assistant turn.
59
- ${MEMORY_OPS_RULES}
60
- - Do not summarize the exchange for HISTORY.md. Idle consolidation never writes HISTORY.md.
61
- - If there is nothing durable enough to store, return an empty memoryOps array.
62
-
63
- Example output:
64
- {
65
- "memoryOps": [{"op": "add", "content": "User prefers dark mode in the dashboard"}]
66
- }`;
67
17
  const MEMORY_CLEANUP_SYSTEM_PROMPT = `You are rewriting a Pipiclaw channel MEMORY.md file.
68
18
 
69
19
  Return Markdown only. Do not use code fences.
@@ -103,45 +53,6 @@ function usageContextFor(channelId, correlationId) {
103
53
  function normalizeText(text) {
104
54
  return text.replace(/\r/g, "").trim();
105
55
  }
106
- function normalizeMemoryOp(value) {
107
- if (typeof value !== "object" || value === null) {
108
- return null;
109
- }
110
- const record = value;
111
- const content = typeof record.content === "string" ? record.content.trim() : "";
112
- const targetId = typeof record.targetId === "string" ? record.targetId.trim() : "";
113
- const kind = record.kind === "preference" ||
114
- record.kind === "decision" ||
115
- record.kind === "constraint" ||
116
- record.kind === "open-loop" ||
117
- record.kind === "lesson"
118
- ? record.kind
119
- : "fact";
120
- const metadata = { kind, sourceType: "agent", trust: "inferred" };
121
- if (record.op === "supersede" && targetId && content) {
122
- return { op: "supersede", targetId, content, metadata };
123
- }
124
- if (record.op === "invalidate" && targetId) {
125
- return {
126
- op: "invalidate",
127
- targetId,
128
- reason: typeof record.reason === "string" ? record.reason.trim() : undefined,
129
- };
130
- }
131
- // Default to add for "add" or any unrecognized op that still carries content.
132
- if (content) {
133
- return { op: "add", content, metadata };
134
- }
135
- return null;
136
- }
137
- function parseConsolidationResponse(text) {
138
- const parsed = parseJsonObject(text);
139
- const rawOps = Array.isArray(parsed.memoryOps) ? parsed.memoryOps : [];
140
- return {
141
- memoryOps: rawOps.map(normalizeMemoryOp).filter((op) => op !== null),
142
- historyBlock: typeof parsed.historyBlock === "string" ? parsed.historyBlock.trim() : "",
143
- };
144
- }
145
56
  function isMessage(entry) {
146
57
  return entry.type === "message";
147
58
  }
@@ -212,68 +123,44 @@ async function runWorkerPrompt(name, model, resolveApiKey, systemPrompt, prompt,
212
123
  });
213
124
  return result.output;
214
125
  }
215
- function renderMemoryEntriesForPrompt(rawMemory) {
216
- const entries = parseChannelMemoryEntries(rawMemory);
217
- if (entries.length === 0) {
218
- return "";
219
- }
220
- return entries.map((entry) => `${entry.id} — ${entry.content}`).join("\n");
221
- }
222
- async function buildInlineConsolidationResponse(options, messages) {
126
+ export async function runInlineConsolidation(options) {
223
127
  const mode = options.mode ?? "boundary";
224
- const transcript = clipText(serializeConversation(messages), INLINE_TRANSCRIPT_MAX_CHARS, { headRatio: 0.35 });
225
- const rawMemory = await readChannelMemory(options.channelDir);
226
- const currentMemory = clipText(renderMemoryEntriesForPrompt(rawMemory), 8_000, { headRatio: 0.35 });
227
- const currentSession = clipText(await readChannelSession(options.channelDir), 8_000, { headRatio: 0.35 });
228
- const currentHistory = clipText(await readChannelHistory(options.channelDir), 8_000, { headRatio: 0.35 });
229
- const prompt = `Current SESSION.md:
230
- ${currentSession || "(empty)"}
231
-
232
- Current MEMORY.md entries (id — content; reference ids in supersede/invalidate):
233
- ${currentMemory || "(empty)"}
234
-
235
- Channel history file:
236
- ${currentHistory || "(empty)"}
237
-
238
- Conversation chunk to persist:
239
- ${transcript || "(empty)"}`;
240
- const result = await runRetriedSidecarTask({
128
+ const sourceEntries = options.sourceWindow?.entries ?? entriesAfterLatestCompactionBoundary(options.sessionEntries ?? []);
129
+ const relevantMessages = options.sourceWindow?.messages ??
130
+ (sourceEntries.length > 0 ? extractMessagesFromSessionEntries(sourceEntries) : options.messages);
131
+ if (!hasMeaningfulMessages(sanitizeMessagesForMemory(relevantMessages))) {
132
+ return { skipped: true, appendedMemoryEntries: 0, appendedHistoryBlock: false, rejectedMemoryOps: [] };
133
+ }
134
+ const correlationId = options.sourceWindow?.windowId ?? options.usageCorrelationId;
135
+ const response = await runMemoryExtraction({
241
136
  name: "memory-inline-consolidation",
137
+ channelId: options.channelId,
138
+ channelDir: options.channelDir,
139
+ messages: relevantMessages,
242
140
  model: options.model,
243
141
  resolveApiKey: options.resolveApiKey,
244
- systemPrompt: mode === "idle" ? IDLE_INLINE_CONSOLIDATION_SYSTEM_PROMPT : BOUNDARY_INLINE_CONSOLIDATION_SYSTEM_PROMPT,
245
- prompt,
246
142
  timeoutMs: INLINE_CONSOLIDATION_TIMEOUT_MS,
247
- usageContext: usageContextFor(options.channelId, options.sourceWindow?.windowId ?? options.usageCorrelationId),
248
- parse: (text) => text.trim(),
143
+ transcriptMaxChars: INLINE_TRANSCRIPT_MAX_CHARS,
144
+ // Idle passes never write HISTORY.md; only real boundaries summarize the chunk.
145
+ includeHistoryBlock: mode === "boundary",
146
+ includeSkills: false,
147
+ usageContext: usageContextFor(options.channelId, correlationId),
249
148
  });
250
- const rawResponse = result.output;
251
- return parseConsolidationResponse(rawResponse);
252
- }
253
- export async function runInlineConsolidation(options) {
254
- const mode = options.mode ?? "boundary";
255
- const sourceEntries = options.sourceWindow?.entries ?? entriesAfterLatestCompactionBoundary(options.sessionEntries ?? []);
256
- const relevantMessages = sanitizeMessagesForMemory(options.sourceWindow?.messages ??
257
- (sourceEntries.length > 0 ? extractMessagesFromSessionEntries(sourceEntries) : options.messages));
258
- if (!hasMeaningfulMessages(relevantMessages)) {
259
- return { skipped: true, appendedMemoryEntries: 0, appendedHistoryBlock: false };
260
- }
261
- const response = await buildInlineConsolidationResponse(options, relevantMessages);
262
149
  const timestamp = new Date().toISOString();
150
+ // The same bar the growth review applies. Consolidation used to write whatever the model
151
+ // returned, which is how transient state reached durable memory: the strictest reviewer
152
+ // was gated behind a keyword scan while the ungated paths wrote freely. Rejected material
153
+ // is not lost — historyBlock and cold storage still carry it.
154
+ const threshold = options.minAutoWriteConfidence ?? DEFAULT_MEMORY_AUTO_WRITE_CONFIDENCE;
155
+ const accepted = [];
156
+ const rejectedMemoryOps = [];
157
+ for (const candidate of response.memoryOps) {
158
+ (shouldAutoWriteMemory(candidate, threshold) ? accepted : rejectedMemoryOps).push(candidate);
159
+ }
263
160
  let appliedMemoryOps = 0;
264
- if (response.memoryOps.length > 0 && !options.sourceWindow?.hasExternalToolContent) {
161
+ if (accepted.length > 0 && !options.sourceWindow?.hasExternalToolContent) {
265
162
  const sourceEntryIds = options.sourceWindow?.entries.map((entry) => entry.id) ?? [];
266
- const ops = response.memoryOps.map((op) => op.op === "add" || op.op === "supersede"
267
- ? {
268
- ...op,
269
- sourceEntryIds,
270
- metadata: {
271
- ...op.metadata,
272
- sourceCorrelationId: options.sourceWindow?.windowId ?? options.usageCorrelationId,
273
- },
274
- }
275
- : op);
276
- const applied = await applyChannelMemoryOps(options.channelDir, ops, timestamp);
163
+ const applied = await applyChannelMemoryOps(options.channelDir, accepted.map((candidate) => toMemoryOp(candidate, { sourceEntryIds, correlationId })), timestamp);
277
164
  appliedMemoryOps = applied.added + applied.superseded + applied.invalidated + applied.downgradedToAdd;
278
165
  }
279
166
  if (mode === "boundary" && response.historyBlock.trim()) {
@@ -286,6 +173,7 @@ export async function runInlineConsolidation(options) {
286
173
  skipped: false,
287
174
  appendedMemoryEntries: appliedMemoryOps,
288
175
  appendedHistoryBlock: mode === "boundary" && response.historyBlock.trim().length > 0,
176
+ rejectedMemoryOps,
289
177
  };
290
178
  }
291
179
  export class MemoryCleanupRejectedError extends Error {
@@ -0,0 +1,45 @@
1
+ import type { AgentMessage } from "@earendil-works/pi-agent-core";
2
+ import type { Api, Model } from "@earendil-works/pi-ai";
3
+ import { type MemoryOp } from "./files.js";
4
+ import type { MemoryEntryKind } from "./metadata.js";
5
+ import type { MemoryPromotionCandidate, SkillPromotionCandidate } from "./promotion.js";
6
+ export interface MemoryExtractionPromptOptions {
7
+ includeHistoryBlock: boolean;
8
+ includeSkills: boolean;
9
+ }
10
+ export declare function buildMemoryExtractionSystemPrompt(options: MemoryExtractionPromptOptions): string;
11
+ export interface MemoryExtractionResult {
12
+ memoryOps: MemoryPromotionCandidate[];
13
+ skillCandidates: SkillPromotionCandidate[];
14
+ historyBlock: string;
15
+ discarded: Array<{
16
+ content: string;
17
+ reason: string;
18
+ }>;
19
+ }
20
+ export declare function normalizeMemoryEntryKind(value: unknown): MemoryEntryKind;
21
+ export declare function parseMemoryExtractionResult(value: unknown): MemoryExtractionResult;
22
+ /** Turn an accepted candidate into a write op, stamping shared provenance metadata. */
23
+ export declare function toMemoryOp(candidate: MemoryPromotionCandidate, provenance: {
24
+ sourceEntryIds?: string[];
25
+ correlationId?: string;
26
+ }): MemoryOp;
27
+ export interface MemoryExtractionRequest extends MemoryExtractionPromptOptions {
28
+ name: string;
29
+ channelId?: string;
30
+ channelDir: string;
31
+ messages: AgentMessage[];
32
+ model: Model<Api>;
33
+ resolveApiKey: (model: Model<Api>) => Promise<string>;
34
+ timeoutMs: number;
35
+ transcriptMaxChars: number;
36
+ loadedSkills?: Array<{
37
+ name: string;
38
+ description?: string;
39
+ }>;
40
+ usageContext?: {
41
+ channelId: string;
42
+ correlationId?: string;
43
+ };
44
+ }
45
+ export declare function runMemoryExtraction(request: MemoryExtractionRequest): Promise<MemoryExtractionResult>;