@oyasmi/pipiclaw 0.8.9-beta.3 → 0.8.10-beta.1

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 (71) hide show
  1. package/dist/agent/channel-runner.d.ts +1 -0
  2. package/dist/agent/channel-runner.js +6 -10
  3. package/dist/agent/maintenance-context.d.ts +0 -1
  4. package/dist/agent/maintenance-context.js +0 -7
  5. package/dist/agent/session-events.d.ts +1 -0
  6. package/dist/agent/session-events.js +10 -0
  7. package/dist/agent/types.d.ts +7 -0
  8. package/dist/agent/types.js +2 -0
  9. package/dist/index.d.ts +1 -1
  10. package/dist/memory/consolidation.js +0 -1
  11. package/dist/memory/extraction.d.ts +1 -7
  12. package/dist/memory/extraction.js +2 -46
  13. package/dist/memory/lifecycle.js +3 -3
  14. package/dist/memory/maintenance-gates.d.ts +4 -16
  15. package/dist/memory/maintenance-gates.js +11 -51
  16. package/dist/memory/maintenance-jobs.d.ts +3 -14
  17. package/dist/memory/maintenance-jobs.js +12 -103
  18. package/dist/memory/maintenance-state.d.ts +2 -6
  19. package/dist/memory/maintenance-state.js +14 -10
  20. package/dist/memory/promotion.d.ts +0 -22
  21. package/dist/memory/promotion.js +1 -8
  22. package/dist/memory/review-log.d.ts +1 -1
  23. package/dist/memory/scheduler.d.ts +1 -9
  24. package/dist/memory/scheduler.js +3 -15
  25. package/dist/memory/source-window.d.ts +2 -2
  26. package/dist/memory/task-digest.js +0 -2
  27. package/dist/models/utils.d.ts +5 -0
  28. package/dist/models/utils.js +10 -0
  29. package/dist/playbooks/task-closeout.md +2 -0
  30. package/dist/playbooks/task-delegation.md +4 -4
  31. package/dist/playbooks/task-driving.md +3 -3
  32. package/dist/playbooks/task-planning.md +6 -5
  33. package/dist/runtime/bootstrap.js +1 -4
  34. package/dist/runtime/task-commands.js +35 -16
  35. package/dist/runtime/task-driver.js +3 -1
  36. package/dist/settings.d.ts +4 -14
  37. package/dist/settings.js +2 -26
  38. package/dist/shared/task-ledger.d.ts +11 -0
  39. package/dist/shared/task-ledger.js +185 -3
  40. package/dist/subagents/discovery.d.ts +41 -7
  41. package/dist/subagents/discovery.js +74 -24
  42. package/dist/subagents/tool.d.ts +2 -7
  43. package/dist/subagents/tool.js +17 -19
  44. package/dist/tasks/control.d.ts +17 -6
  45. package/dist/tasks/control.js +42 -19
  46. package/dist/tasks/store.d.ts +1 -0
  47. package/dist/tasks/store.js +8 -0
  48. package/dist/tasks/transitions.d.ts +1 -1
  49. package/dist/tasks/transitions.js +1 -0
  50. package/dist/tools/registry.js +2 -0
  51. package/dist/tools/task-manage/create.js +2 -1
  52. package/dist/tools/task-manage/lifecycle.d.ts +7 -0
  53. package/dist/tools/task-manage/lifecycle.js +55 -14
  54. package/dist/tools/task-manage/schema.d.ts +2 -4
  55. package/dist/tools/task-manage/schema.js +14 -16
  56. package/dist/tools/task-manage/shared.d.ts +1 -0
  57. package/dist/tools/task-manage/shared.js +10 -9
  58. package/dist/tools/task-manage/types.d.ts +3 -1
  59. package/dist/tools/task-manage/verification.js +1 -2
  60. package/dist/tools/task-manage.js +4 -2
  61. package/examples/sub-agents/README.md +19 -14
  62. package/examples/sub-agents/explorer.md +32 -8
  63. package/examples/sub-agents/git-committer.md +53 -40
  64. package/examples/sub-agents/researcher.md +31 -8
  65. package/examples/sub-agents/reviewer.md +53 -0
  66. package/examples/sub-agents/verifier.md +39 -9
  67. package/package.json +1 -1
  68. package/dist/memory/post-turn-review.d.ts +0 -43
  69. package/dist/memory/post-turn-review.js +0 -136
  70. package/dist/memory/promotion-signals.d.ts +0 -5
  71. package/dist/memory/promotion-signals.js +0 -33
@@ -2,10 +2,8 @@ import { errorMessage } from "../shared/text-utils.js";
2
2
  import { getDefaultChannelMemoryQueue } from "./channel-maintenance-queue.js";
3
3
  import { cleanupChannelMemory, foldChannelHistory, getStructuralMaintenanceStats, runInlineConsolidation, } from "./consolidation.js";
4
4
  import { readChannelHistory, readChannelMemory } from "./files.js";
5
- import { shouldRunDurableConsolidation, shouldRunGrowthReview, shouldRunSessionRefresh, shouldRunStructuralMaintenance, } from "./maintenance-gates.js";
5
+ import { shouldRunMemoryCheckpoint, shouldRunSessionRefresh, shouldRunStructuralMaintenance, } from "./maintenance-gates.js";
6
6
  import { readMemoryMaintenanceState, updateMemoryMaintenanceState } from "./maintenance-state.js";
7
- import { runPostTurnReview } from "./post-turn-review.js";
8
- import { scanPromotionSignals } from "./promotion-signals.js";
9
7
  import { appendMemoryReviewLog } from "./review-log.js";
10
8
  import { updateChannelSessionMemory } from "./session.js";
11
9
  import { buildIncrementalMemorySourceWindow } from "./source-window.js";
@@ -48,9 +46,6 @@ function hasMeaningfulMessages(messages) {
48
46
  }
49
47
  return false;
50
48
  }
51
- function renderMessagesForSignalScan(messages) {
52
- return sanitizeMessagesForMemory(messages).map(messageToText).join("\n");
53
- }
54
49
  function makeRunOptions(input, usageCorrelationId) {
55
50
  return {
56
51
  channelId: input.channelId,
@@ -60,8 +55,7 @@ function makeRunOptions(input, usageCorrelationId) {
60
55
  messages: input.messages,
61
56
  sessionEntries: input.sessionEntries,
62
57
  usageCorrelationId,
63
- // One durable-write bar across consolidation and the growth review.
64
- minAutoWriteConfidence: input.settings.memoryGrowth.minMemoryAutoWriteConfidence,
58
+ minAutoWriteConfidence: input.settings.memoryMaintenance.minMemoryAutoWriteConfidence,
65
59
  };
66
60
  }
67
61
  function backoffUntil(now, settings) {
@@ -144,19 +138,18 @@ export async function runSessionRefreshJob(input) {
144
138
  }
145
139
  });
146
140
  }
147
- export async function runDurableConsolidationJob(input) {
141
+ export async function runMemoryCheckpointJob(input) {
148
142
  return runQueued(input, async () => {
149
143
  const now = input.now ?? new Date();
150
144
  const state = await readMemoryMaintenanceState(input.appHomeDir, input.channelId);
151
145
  const sourceWindow = buildIncrementalMemorySourceWindow({
152
146
  entries: input.sessionEntries,
153
- lastEntryId: state.lastConsolidatedEntryId,
147
+ lastEntryId: state.lastCheckpointEntryId,
154
148
  sourceKind: "idle",
155
149
  fallbackMessages: input.messages,
156
150
  });
157
151
  const newEntries = sourceWindow.entries;
158
- const latestId = latestEntryId(input.sessionEntries);
159
- const decision = shouldRunDurableConsolidation({
152
+ const decision = shouldRunMemoryCheckpoint({
160
153
  now,
161
154
  state,
162
155
  maintenance: input.settings.memoryMaintenance,
@@ -164,10 +157,9 @@ export async function runDurableConsolidationJob(input) {
164
157
  hasNewEntry: newEntries.length > 0,
165
158
  hasMeaningfulExchange: hasMeaningfulMessages(sourceWindow.messages),
166
159
  batchSize: newEntries.length,
167
- coveredByGrowthReview: Boolean(latestId && state.lastReviewedEntryId === latestId),
168
160
  });
169
161
  if (!decision.allowed) {
170
- await appendJobReviewLog(input.channelDir, input.channelId, "durable-consolidation-job", { skipped: [{ target: "consolidation", reason: decision.skipReason }] }, now);
162
+ await appendJobReviewLog(input.channelDir, input.channelId, "memory-checkpoint-job", { skipped: [{ target: "consolidation", reason: decision.skipReason }] }, now);
171
163
  return skipped(decision.jobKind, decision.skipReason ?? "skipped");
172
164
  }
173
165
  try {
@@ -178,11 +170,11 @@ export async function runDurableConsolidationJob(input) {
178
170
  });
179
171
  await updateMemoryMaintenanceState(input.appHomeDir, input.channelId, (current) => ({
180
172
  ...current,
181
- lastDurableConsolidationAt: now.toISOString(),
182
- lastConsolidatedEntryId: sourceWindow.throughEntryId ?? current.lastConsolidatedEntryId,
173
+ lastCheckpointAt: now.toISOString(),
174
+ lastCheckpointEntryId: sourceWindow.throughEntryId ?? current.lastCheckpointEntryId,
183
175
  failureBackoffUntil: null,
184
176
  }));
185
- await appendJobReviewLog(input.channelDir, input.channelId, "durable-consolidation-job", result.skipped
177
+ await appendJobReviewLog(input.channelDir, input.channelId, "memory-checkpoint-job", result.skipped
186
178
  ? {
187
179
  skipped: [{ target: "consolidation", reason: "no meaningful snapshot" }],
188
180
  correlationId: sourceWindow.windowId,
@@ -196,98 +188,15 @@ export async function runDurableConsolidationJob(input) {
196
188
  })),
197
189
  correlationId: sourceWindow.windowId,
198
190
  }, now);
199
- return ran("durable-consolidation");
200
- }
201
- catch (error) {
202
- await updateMemoryMaintenanceState(input.appHomeDir, input.channelId, (current) => ({
203
- ...current,
204
- failureBackoffUntil: backoffUntil(now, input.settings.memoryMaintenance),
205
- }));
206
- const result = failed("durable-consolidation", error);
207
- await appendJobReviewLog(input.channelDir, input.channelId, "durable-consolidation-job", { error: result.error, skipped: [{ target: "consolidation", reason: "failed" }] }, now);
208
- return result;
209
- }
210
- });
211
- }
212
- export async function runGrowthReviewJob(input) {
213
- return runQueued(input, async () => {
214
- const now = input.now ?? new Date();
215
- const state = await readMemoryMaintenanceState(input.appHomeDir, input.channelId);
216
- const sourceWindow = buildIncrementalMemorySourceWindow({
217
- entries: input.sessionEntries,
218
- lastEntryId: state.lastReviewedEntryId,
219
- sourceKind: "growth-review",
220
- fallbackMessages: input.messages,
221
- });
222
- const newEntries = sourceWindow.entries;
223
- const signalScan = scanPromotionSignals(renderMessagesForSignalScan(sourceWindow.messages));
224
- const decision = shouldRunGrowthReview({
225
- now,
226
- state,
227
- memoryGrowth: input.settings.memoryGrowth,
228
- maintenance: input.settings.memoryMaintenance,
229
- channelActive: input.channelActive,
230
- hasNewEntry: newEntries.length > 0,
231
- hasMeaningfulMaterial: hasMeaningfulMessages(sourceWindow.messages),
232
- hasPromotionSignal: signalScan.hasSignal,
233
- });
234
- if (!decision.allowed) {
235
- await appendJobReviewLog(input.channelDir, input.channelId, "growth-review-job", { skipped: [{ target: "post-turn-review", reason: decision.skipReason }] }, now);
236
- return skipped(decision.jobKind, decision.skipReason ?? "skipped");
237
- }
238
- try {
239
- const notices = [];
240
- const result = await runPostTurnReview({
241
- channelId: input.channelId,
242
- channelDir: input.channelDir,
243
- workspaceDir: input.workspaceDir,
244
- messages: sourceWindow.messages,
245
- sourceEntryIds: sourceWindow.entries.map((entry) => entry.id),
246
- suppressAutomaticWrites: sourceWindow.hasExternalToolContent,
247
- model: input.model,
248
- resolveApiKey: input.resolveApiKey,
249
- timeoutMs: input.settings.sessionMemory.timeoutMs,
250
- autoWriteChannelMemory: input.settings.memoryGrowth.autoWriteChannelMemory,
251
- autoWriteWorkspaceSkills: input.settings.memoryGrowth.autoWriteWorkspaceSkills,
252
- minMemoryAutoWriteConfidence: input.settings.memoryGrowth.minMemoryAutoWriteConfidence,
253
- minSkillAutoWriteConfidence: input.settings.memoryGrowth.minSkillAutoWriteConfidence,
254
- loadedSkills: input.loadedSkills,
255
- correlationId: sourceWindow.windowId,
256
- emitNotice: async (notice) => {
257
- notices.push(notice);
258
- },
259
- refreshWorkspaceResources: input.refreshWorkspaceResources,
260
- });
261
- if (result.status === "failed") {
262
- throw new Error(`Growth review failed: ${result.error}. Retry this memory window after backoff.`);
263
- }
264
- const appliedResult = result.result;
265
- await updateMemoryMaintenanceState(input.appHomeDir, input.channelId, (current) => ({
266
- ...current,
267
- lastGrowthReviewAt: now.toISOString(),
268
- turnsSinceGrowthReview: 0,
269
- toolCallsSinceGrowthReview: 0,
270
- lastReviewedEntryId: sourceWindow.throughEntryId ?? current.lastReviewedEntryId,
271
- failureBackoffUntil: null,
272
- }));
273
- if (notices.length > 0) {
274
- const uniqueNotices = Array.from(new Set(notices));
275
- await input.emitNotice?.(uniqueNotices.join("\n"));
276
- }
277
- await appendJobReviewLog(input.channelDir, input.channelId, "growth-review-job", {
278
- actions: appliedResult.actions,
279
- skipped: appliedResult.skipped,
280
- correlationId: sourceWindow.windowId,
281
- }, now);
282
- return ran("growth-review");
191
+ return ran("memory-checkpoint");
283
192
  }
284
193
  catch (error) {
285
194
  await updateMemoryMaintenanceState(input.appHomeDir, input.channelId, (current) => ({
286
195
  ...current,
287
196
  failureBackoffUntil: backoffUntil(now, input.settings.memoryMaintenance),
288
197
  }));
289
- const result = failed("growth-review", error);
290
- await appendJobReviewLog(input.channelDir, input.channelId, "growth-review-job", { error: result.error, skipped: [{ target: "post-turn-review", reason: "failed" }] }, now);
198
+ const result = failed("memory-checkpoint", error);
199
+ await appendJobReviewLog(input.channelDir, input.channelId, "memory-checkpoint-job", { error: result.error, skipped: [{ target: "consolidation", reason: "failed" }] }, now);
291
200
  return result;
292
201
  }
293
202
  });
@@ -4,17 +4,13 @@ export interface MemoryMaintenanceState {
4
4
  lastActivityAt?: string;
5
5
  eligibleAfter?: string;
6
6
  lastSessionRefreshAt?: string;
7
- lastDurableConsolidationAt?: string;
8
- lastGrowthReviewAt?: string;
7
+ lastCheckpointAt?: string;
9
8
  lastStructuralMaintenanceAt?: string;
10
9
  turnsSinceSessionRefresh: number;
11
10
  toolCallsSinceSessionRefresh: number;
12
- turnsSinceGrowthReview: number;
13
- toolCallsSinceGrowthReview: number;
14
11
  lastSessionEntryId?: string;
15
12
  lastSessionRefreshedEntryId?: string;
16
- lastConsolidatedEntryId?: string;
17
- lastReviewedEntryId?: string;
13
+ lastCheckpointEntryId?: string;
18
14
  failureBackoffUntil?: string | null;
19
15
  }
20
16
  export type MemoryActivityKind = "user-turn-started" | "tool-call" | "assistant-turn-completed" | "boundary";
@@ -17,8 +17,6 @@ function createDefaultState(channelId) {
17
17
  dirty: false,
18
18
  turnsSinceSessionRefresh: 0,
19
19
  toolCallsSinceSessionRefresh: 0,
20
- turnsSinceGrowthReview: 0,
21
- toolCallsSinceGrowthReview: 0,
22
20
  failureBackoffUntil: null,
23
21
  };
24
22
  }
@@ -34,6 +32,13 @@ function normalizeOptionalNullableString(value) {
34
32
  function normalizeCounter(value) {
35
33
  return typeof value === "number" && Number.isFinite(value) && value > 0 ? Math.floor(value) : 0;
36
34
  }
35
+ function laterTimestamp(a, b) {
36
+ if (!a)
37
+ return b;
38
+ if (!b)
39
+ return a;
40
+ return Date.parse(a) >= Date.parse(b) ? a : b;
41
+ }
37
42
  function normalizeState(channelId, value) {
38
43
  if (!value || typeof value !== "object" || Array.isArray(value)) {
39
44
  return createDefaultState(channelId);
@@ -45,17 +50,18 @@ function normalizeState(channelId, value) {
45
50
  lastActivityAt: normalizeOptionalString(record.lastActivityAt),
46
51
  eligibleAfter: normalizeOptionalString(record.eligibleAfter),
47
52
  lastSessionRefreshAt: normalizeOptionalString(record.lastSessionRefreshAt),
48
- lastDurableConsolidationAt: normalizeOptionalString(record.lastDurableConsolidationAt),
49
- lastGrowthReviewAt: normalizeOptionalString(record.lastGrowthReviewAt),
53
+ // Legacy states carried separate consolidation/growth-review fields; fold them
54
+ // into the merged checkpoint so cadence and cursor survive the migration.
55
+ lastCheckpointAt: normalizeOptionalString(record.lastCheckpointAt) ??
56
+ laterTimestamp(normalizeOptionalString(record.lastDurableConsolidationAt), normalizeOptionalString(record.lastGrowthReviewAt)),
50
57
  lastStructuralMaintenanceAt: normalizeOptionalString(record.lastStructuralMaintenanceAt),
51
58
  turnsSinceSessionRefresh: normalizeCounter(record.turnsSinceSessionRefresh),
52
59
  toolCallsSinceSessionRefresh: normalizeCounter(record.toolCallsSinceSessionRefresh),
53
- turnsSinceGrowthReview: normalizeCounter(record.turnsSinceGrowthReview),
54
- toolCallsSinceGrowthReview: normalizeCounter(record.toolCallsSinceGrowthReview),
55
60
  lastSessionEntryId: normalizeOptionalString(record.lastSessionEntryId),
56
61
  lastSessionRefreshedEntryId: normalizeOptionalString(record.lastSessionRefreshedEntryId),
57
- lastConsolidatedEntryId: normalizeOptionalString(record.lastConsolidatedEntryId),
58
- lastReviewedEntryId: normalizeOptionalString(record.lastReviewedEntryId),
62
+ lastCheckpointEntryId: normalizeOptionalString(record.lastCheckpointEntryId) ??
63
+ normalizeOptionalString(record.lastConsolidatedEntryId) ??
64
+ normalizeOptionalString(record.lastReviewedEntryId),
59
65
  failureBackoffUntil: normalizeOptionalNullableString(record.failureBackoffUntil) ?? null,
60
66
  };
61
67
  }
@@ -94,12 +100,10 @@ export function applyMemoryActivityToState(state, event) {
94
100
  if (event.kind === "tool-call") {
95
101
  next.dirty = true;
96
102
  next.toolCallsSinceSessionRefresh += 1;
97
- next.toolCallsSinceGrowthReview += 1;
98
103
  }
99
104
  if (event.kind === "assistant-turn-completed") {
100
105
  next.dirty = true;
101
106
  next.turnsSinceSessionRefresh += 1;
102
- next.turnsSinceGrowthReview += 1;
103
107
  }
104
108
  if (event.kind === "boundary") {
105
109
  next.dirty = true;
@@ -1,5 +1,4 @@
1
1
  export type MemoryPromotionTarget = "channel-memory";
2
- export type SkillPromotionAction = "create" | "patch" | "write_file";
3
2
  export interface MemoryPromotionCandidate {
4
3
  target: MemoryPromotionTarget;
5
4
  op: "add" | "supersede" | "invalidate";
@@ -10,26 +9,5 @@ export interface MemoryPromotionCandidate {
10
9
  reason: string;
11
10
  necessity: "low" | "medium" | "high";
12
11
  }
13
- export interface SkillPromotionCandidate {
14
- action: SkillPromotionAction;
15
- name: string;
16
- content?: string;
17
- filePath?: string;
18
- find?: string;
19
- replace?: string;
20
- confidence: number;
21
- necessity: "low" | "medium" | "high";
22
- reason: string;
23
- }
24
- export interface PostTurnReviewResult {
25
- memoryOps: MemoryPromotionCandidate[];
26
- skillCandidates: SkillPromotionCandidate[];
27
- discarded: Array<{
28
- content: string;
29
- reason: string;
30
- }>;
31
- }
32
12
  export declare const DEFAULT_MEMORY_AUTO_WRITE_CONFIDENCE = 0.85;
33
- export declare const DEFAULT_SKILL_AUTO_WRITE_CONFIDENCE = 0.9;
34
13
  export declare function shouldAutoWriteMemory(candidate: MemoryPromotionCandidate, threshold?: number): boolean;
35
- export declare function shouldAutoWriteSkill(candidate: SkillPromotionCandidate, threshold?: number): boolean;
@@ -1,13 +1,6 @@
1
1
  export const DEFAULT_MEMORY_AUTO_WRITE_CONFIDENCE = 0.85;
2
- export const DEFAULT_SKILL_AUTO_WRITE_CONFIDENCE = 0.9;
3
- function isHighNecessity(value) {
4
- return value === "high";
5
- }
6
2
  export function shouldAutoWriteMemory(candidate, threshold = DEFAULT_MEMORY_AUTO_WRITE_CONFIDENCE) {
7
3
  return (candidate.confidence >= threshold &&
8
- isHighNecessity(candidate.necessity) &&
4
+ candidate.necessity === "high" &&
9
5
  (candidate.op === "invalidate" ? Boolean(candidate.targetId) : Boolean(candidate.content?.trim())));
10
6
  }
11
- export function shouldAutoWriteSkill(candidate, threshold = DEFAULT_SKILL_AUTO_WRITE_CONFIDENCE) {
12
- return candidate.confidence >= threshold && candidate.necessity === "high";
13
- }
@@ -1,4 +1,4 @@
1
- export type MemoryReviewReason = "idle" | "compaction" | "new-session" | "shutdown" | "post-turn" | "session-refresh-job" | "durable-consolidation-job" | "growth-review-job" | "structural-maintenance-job" | "user-forget";
1
+ export type MemoryReviewReason = "idle" | "compaction" | "new-session" | "shutdown" | "session-refresh-job" | "memory-checkpoint-job" | "structural-maintenance-job" | "user-forget";
2
2
  export interface MemoryReviewLogEntry {
3
3
  timestamp: string;
4
4
  channelId: string;
@@ -1,25 +1,18 @@
1
1
  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
- import type { PipiclawMemoryGrowthSettings, PipiclawMemoryMaintenanceSettings, PipiclawSessionMemorySettings } from "../settings.js";
4
+ import type { PipiclawMemoryMaintenanceSettings, PipiclawSessionMemorySettings } from "../settings.js";
5
5
  export interface MemoryMaintenanceRuntimeContext {
6
6
  channelId: string;
7
7
  channelDir: string;
8
- workspaceDir: string;
9
8
  messages: AgentMessage[];
10
9
  sessionEntries: SessionEntry[];
11
10
  model: Model<Api>;
12
11
  resolveApiKey: (model: Model<Api>) => Promise<string>;
13
12
  settings: {
14
13
  sessionMemory: PipiclawSessionMemorySettings;
15
- memoryGrowth: PipiclawMemoryGrowthSettings;
16
14
  memoryMaintenance: PipiclawMemoryMaintenanceSettings;
17
15
  };
18
- loadedSkills: Array<{
19
- name: string;
20
- description?: string;
21
- }>;
22
- refreshWorkspaceResources?: () => Promise<void>;
23
16
  }
24
17
  export interface MemoryMaintenanceSchedulerOptions {
25
18
  appHomeDir: string;
@@ -30,7 +23,6 @@ export interface MemoryMaintenanceSchedulerOptions {
30
23
  getSettings: () => {
31
24
  memoryMaintenance: PipiclawMemoryMaintenanceSettings;
32
25
  };
33
- emitNotice?: (channelId: string, notice: string) => Promise<void>;
34
26
  intervalMs?: number;
35
27
  }
36
28
  export declare function discoverMemoryMaintenanceChannels(input: {
@@ -2,7 +2,7 @@ import { readdir } from "node:fs/promises";
2
2
  import { basename } from "node:path";
3
3
  import * as log from "../log.js";
4
4
  import { errorMessage } from "../shared/text-utils.js";
5
- import { runDurableConsolidationJob, runGrowthReviewJob, runSessionRefreshJob, runStructuralMaintenanceJob, } from "./maintenance-jobs.js";
5
+ import { runMemoryCheckpointJob, runSessionRefreshJob, runStructuralMaintenanceJob } from "./maintenance-jobs.js";
6
6
  import { getMemoryMaintenanceStateDir } from "./maintenance-state.js";
7
7
  const DEFAULT_TICK_INTERVAL_MS = 60_000;
8
8
  const CHANNEL_ID_PATTERN = /^(dm|group)_[A-Za-z0-9._:-]+$/;
@@ -131,20 +131,8 @@ export class MemoryMaintenanceScheduler {
131
131
  if (session.ran) {
132
132
  return;
133
133
  }
134
- const durable = await runDurableConsolidationJob(common);
135
- if (durable.ran) {
136
- return;
137
- }
138
- const growth = await runGrowthReviewJob({
139
- ...common,
140
- workspaceDir: context.workspaceDir,
141
- loadedSkills: context.loadedSkills,
142
- emitNotice: this.options.emitNotice
143
- ? async (notice) => this.options.emitNotice?.(channelId, notice)
144
- : undefined,
145
- refreshWorkspaceResources: context.refreshWorkspaceResources,
146
- });
147
- if (growth.ran) {
134
+ const checkpoint = await runMemoryCheckpointJob(common);
135
+ if (checkpoint.ran) {
148
136
  return;
149
137
  }
150
138
  await runStructuralMaintenanceJob(common);
@@ -1,6 +1,6 @@
1
1
  import type { AgentMessage } from "@earendil-works/pi-agent-core";
2
2
  import type { SessionEntry } from "@earendil-works/pi-coding-agent";
3
- export type MemorySourceKind = "idle" | "compaction" | "new-session" | "shutdown" | "growth-review";
3
+ export type MemorySourceKind = "idle" | "compaction" | "new-session" | "shutdown";
4
4
  export interface MemorySourceWindow {
5
5
  sourceKind: MemorySourceKind;
6
6
  fromEntryId?: string;
@@ -14,7 +14,7 @@ export declare function entriesSince(entries: SessionEntry[], lastEntryId: strin
14
14
  export declare function buildIncrementalMemorySourceWindow(options: {
15
15
  entries: SessionEntry[];
16
16
  lastEntryId?: string;
17
- sourceKind: Extract<MemorySourceKind, "idle" | "new-session" | "shutdown" | "growth-review">;
17
+ sourceKind: Extract<MemorySourceKind, "idle" | "new-session" | "shutdown">;
18
18
  fallbackMessages?: AgentMessage[];
19
19
  }): MemorySourceWindow;
20
20
  export declare function buildCompactionMemorySourceWindow(options: {
@@ -25,8 +25,6 @@ function renderLine(entry, now) {
25
25
  parts.push(`priority ${control.priority}`);
26
26
  parts.push(`attempt ${control.usage.attempts}/${control.budget.maxAttempts}`);
27
27
  parts.push(`verify ${control.verification.mode}/${control.verification.status}`);
28
- if (control.isolation !== "shared")
29
- parts.push(`isolation ${control.isolation}`);
30
28
  if (control.sideEffects !== "workspace") {
31
29
  parts.push(`effects ${control.sideEffects}/${control.externalApproval}`);
32
30
  }
@@ -17,6 +17,11 @@ export declare function createModelRuntime(options: {
17
17
  */
18
18
  export declare function wrapModelRegistry(modelRuntime: ModelRuntime): ModelRegistry;
19
19
  export declare function formatModelReference(model: Model<Api>): string;
20
+ /**
21
+ * Pi fills omitted custom-model pricing with zero rates. An all-zero table therefore
22
+ * means "price unavailable", not reliably "free".
23
+ */
24
+ export declare function hasKnownModelPricing(model: Model<Api> | undefined): boolean;
20
25
  export declare function findExactModelReferenceMatch(modelReference: string, availableModels: Model<Api>[]): {
21
26
  match?: Model<Api>;
22
27
  ambiguous: boolean;
@@ -23,6 +23,16 @@ export function wrapModelRegistry(modelRuntime) {
23
23
  export function formatModelReference(model) {
24
24
  return `${model.provider}/${model.id}`;
25
25
  }
26
+ /**
27
+ * Pi fills omitted custom-model pricing with zero rates. An all-zero table therefore
28
+ * means "price unavailable", not reliably "free".
29
+ */
30
+ export function hasKnownModelPricing(model) {
31
+ if (!model?.cost)
32
+ return false;
33
+ const rates = [model.cost, ...(model.cost.tiers ?? [])];
34
+ return rates.some((rate) => rate.input > 0 || rate.output > 0 || rate.cacheRead > 0 || rate.cacheWrite > 0);
35
+ }
26
36
  export function findExactModelReferenceMatch(modelReference, availableModels) {
27
37
  const trimmedReference = modelReference.trim();
28
38
  if (!trimmedReference) {
@@ -43,6 +43,8 @@ FAIL 后用 progress 记录失败证据、status 回 active,修复后重新 ca
43
43
 
44
44
  `task_manage done` 需要 summary 和可查证 evidence,可附 residualRisk。它检查 checkbox、依赖、child、外部授权、独立 PASS,再记录收尾、清理临时 task events;一次性任务归档,有 `schedule` frontmatter 的周期任务算出下一次 `wake` 并原地睡眠。
45
45
 
46
+ 周期 occurrence 因去重、同一产物已由更早触发完成等原因无需执行时,用 `task_manage skip` + reason。skip 只关闭本次 occurrence,不要求虚勾 DoD、不写 completion evidence,也不会取消后续 schedule。
47
+
46
48
  放弃用 `cancel` + reason,不伪装 done。cancel 要求先处理 child,随后归档并删除全部 task-owned events。
47
49
 
48
50
  完成结论必须来自证据:具体命令、测试结果、review、外部确认或明确的未运行理由。“看起来可以”不是 evidence。
@@ -19,9 +19,9 @@ priority: 45
19
19
 
20
20
  ## 配置 subagent
21
21
 
22
- 不需要预先配置:不传 `agent` 时给 `systemPrompt` 即可发起委派,`workspaceDir/sub-agents/` 为空不影响这条路径。若需要可复用角色,把 Markdown 配置放入该目录;runtime 只加载实际存在的配置。仓库提供 explorer、researcher、verifier、git-committer 四份可复制模板,见 `examples/sub-agents/`。选择明确适合的配置 agent;没有时使用聚焦的 inline `systemPrompt`。task 描述必须包含目标、范围、相关路径、约束、验收方法和返回格式,因为子代理看不到主对话。
22
+ 不需要预先配置:不传 `agent` 时给 `systemPrompt` 即可发起委派,`workspaceDir/sub-agents/` 为空不影响这条路径。若需要可复用角色,把 Markdown 配置放入该目录;runtime 只加载实际存在的配置。仓库提供 explorer、researcher、reviewer、verifier、git-committer 五份可复制模板,见 `examples/sub-agents/`。选择明确适合的配置 agent;没有时使用聚焦的 inline `systemPrompt`。task 描述必须包含目标、范围、相关路径、约束、验收方法和返回格式,因为子代理看不到主对话。
23
23
 
24
- 用 `maxTurns`、`maxToolCalls`、`maxWallTimeSec` 限幅。进程内 subagent 同回合同步返回,不需要回访事件;主 agent 负责验收结果和更新台账,子代理不驱动 task/event 台账。触顶时子代理会收敛输出已完成的结论而不是整段丢弃,但预算仍然是真实上限,不要依赖它兜底过大的任务。
24
+ 执行预算用 `effort` 三档:`quick`(窄查找)、`standard`(默认)、`deep`(长程分析);精确的轮数/调用数/墙钟数值只在 workspace 配置的 frontmatter 里调,调用时不必给。上下文注入用 `context`:`none`(默认,完全隔离)、`session`、`relevant`。进程内 subagent 同回合同步返回,不需要回访事件;主 agent 负责验收结果和更新台账,子代理不驱动 task/event 台账。触顶时子代理会收敛输出已完成的结论而不是整段丢弃,但预算仍然是真实上限,不要依赖它兜底过大的任务。
25
25
 
26
26
  独立验收必须 `purpose: verify` + `taskId`,见 `task-closeout.md`。
27
27
 
@@ -33,9 +33,9 @@ priority: 45
33
33
 
34
34
  ## worktree 隔离
35
35
 
36
- 写密集 child 设置 `control.isolation: worktree`,委派时传 `isolation: worktree` 和 taskId。runtime 从 committed HEAD 创建 `pipiclaw-task/<task>/<run>` 分支,把路径/分支记录进 task control。
36
+ 写密集 child 委派时传 `isolation: worktree` 和 taskId——隔离在委派点声明一次即可,任务本身不需要预先标注。runtime 从 committed HEAD 创建 `pipiclaw-task/<task>/<run>` 分支,把路径/分支记录进 task control。
37
37
 
38
- 已有 worktree 可传 `worktreePath`,但必须位于该 channel 的 `tasks/worktrees/` 下。worktree 不自动删除;父代理必须 review、merge、验证,然后清理 worktree 与分支。创建前处理好主 checkout 的未提交前置改动。
38
+ 同一 taskId 的后续委派自动复用台账里记录的 worktree,不需要也无法手工指定路径;台账记录的路径若已不在磁盘上则新建,若指向 `tasks/worktrees/` 之外则报错,需先用 `task_manage` 清理该元数据。worktree 不自动删除;父代理必须 review、merge、验证,然后清理 worktree 与分支。创建前处理好主 checkout 的未提交前置改动。
39
39
 
40
40
  ## 外部 agent 工具
41
41
 
@@ -20,7 +20,7 @@ priority: 41
20
20
 
21
21
  仍开放且正文或进展发生变化时,用 `task_manage progress` 一次性记录:发生了什么、看到了什么证据、下一步是什么、status 与 `wake`。
22
22
 
23
- 以下生命周期动作本身就是原子 checkpoint,不要再追加 progress:`candidate`、`done`、`cancel`。
23
+ 以下生命周期动作本身就是原子 checkpoint,不要再追加 progress:`candidate`、`done`、`skip`、`cancel`。
24
24
 
25
25
  `verify` 只更新 control、不改正文。PASS 后若还要等外部审批(approval),用 `task_manage set wake=<合理时间>` 停留在 `verifying` 车道——**只改 wake、不换状态**,离开 verifying 会作废 PASS——并请用户 `/tasks approve <id>`。门禁的绑定规则见 `task-closeout.md`。除此之外不要用 `set` 代替正常进度日志。
26
26
 
@@ -36,13 +36,13 @@ priority: 41
36
36
 
37
37
  ## 汇报与静默
38
38
 
39
- 有用户需要知道的结果、风险、审批请求时正常汇报。纯内部周期检查且没有新结果时返回 `[SILENT]`,避免发空状态卡。完成时走 `task-closeout.md`。
39
+ 有用户需要知道的结果、风险、审批请求时正常汇报。周期 occurrence 因去重或产物已存在而明确不执行时,调用 `task_manage skip` 写入简短原因、让任务重新休眠,然后返回 `[SILENT]`;不能只静默而把周期留在 active。除此之外,确实不需要改变任务状态且没有新结果时直接返回 `[SILENT]`。完成时走 `task-closeout.md`。
40
40
 
41
41
  ---
42
42
 
43
43
  # 诊断与修复
44
44
 
45
- 先用 `task_manage list` 看结构化状态;让用户用 `/tasks doctor` 看带 Next step 的一致性检查,用 `/tasks stats <id>` 看 attempts/token/cost/wall time、最近结果和 verifier 状态。
45
+ 先用 `task_manage list` 看结构化状态;让用户用 `/tasks doctor` 看带 Next step 的一致性检查,用 `/tasks stats <id>` 看本周期与累计 attempts/token/cost/wall time、最近结果和 verifier 状态。`cost: unavailable` 表示参与运行的模型缺少价格元数据,不表示免费。
46
46
 
47
47
  ## 被治理器暂停(paused + pausedBy=governor)
48
48
 
@@ -28,15 +28,16 @@ priority: 40
28
28
 
29
29
  - `priority` / `deadline`:表达调度重要性和硬期限,不用 `wake` 冒充 deadline。
30
30
  - `nextAction`:下一条可执行动作,避免写抽象愿望。
31
- - `maxAttempts` / `maxTokens` / `maxCostUsd` / `maxWallTimeMinutes`:按风险和规模收紧;预算是停止条件,不是目标。
32
- - `sideEffects`:`read-only`、`workspace` 或 `external`。发送、发布、部署、修改外部系统必须选 `external`。
33
- - `isolation: worktree`:写密集型子任务需要隔离共享 checkout 时使用,见 `task-delegation.md`。
31
+ - `maxAttempts` / `maxTokens` / `maxCostUsd` / `maxWallTimeMinutes`:按风险和规模收紧;这些是**本周期、回合边界检查**的停止条件,不会中断正在运行的单个回合。模型没有价格元数据时不能使用 `maxCostUsd`,改用 `maxTokens`。
32
+ - `sideEffects`:`workspace` 或 `external`。发送、发布、部署、修改外部系统必须选 `external`,它会要求用户 `/tasks approve` 后才能 done。
34
33
  - `parent` / `dependsOn`:只用于真实分解;`parent` 表归属,`dependsOn` 表执行前置。
35
34
 
36
35
  创建和 `set` 会拒绝不存在的关联、自指、parent 环和 dependency 环。父任务可以 `dependsOn` 自己的 child 表达 join;父任务有未闭环 child 时不能 done。
37
36
 
38
37
  外部副作用与独立验收并存时,DoD/Verification 要验收"**待执行动作及其输入已准备正确**"(内容、目标、参数、预演、回滚方案),不要把尚未获批的外部动作本身写成 candidate 前必须勾选的项——否则会形成"先执行才能勾选"与"先验收批准才能执行"的死循环。实际执行结果由审批记录和 done evidence 收口。
39
38
 
39
+ DoD 描述最终可验收结果,不把未执行动作写成 `[x] skipped`。存在条件分支时,用一个结果项表达“完成 A,或在条件不成立时交付 B 并附理由”;执行哪条路径由 evidence 证明。
40
+
40
41
  ## 六个状态与时间
41
42
 
42
43
  每个状态只对应一种 driver 行为:
@@ -52,7 +53,7 @@ priority: 40
52
53
 
53
54
  ## 周期性任务(schedule)
54
55
 
55
- 一个周期任务就是**一个文件**:`tasks/<id>.md`。节奏写在 frontmatter 的 `schedule`(五段 cron,按主机时区解释),做法与跨周期经验写在正文。没有配套事件,也没有 `.schedule` 命名约定。`recurrence` 只是给人看的可选标注(如 `每周一`),没有机器语义——**周期性 = `schedule` 是否存在**。
56
+ 一个周期任务就是**一个文件**:`tasks/<id>.md`。节奏写在 frontmatter 的 `schedule`(五段 cron,按主机时区解释;部署时用 `TZ` 固定所需 IANA 时区),做法与跨周期经验写在正文。没有配套事件,也没有 `.schedule` 命名约定。`recurrence` 只是给人看的可选标注(如 `每周一`),没有机器语义——**周期性 = `schedule` 是否存在**。
56
57
 
57
58
  ```
58
59
  task_manage create id=weekly-report title=... goal=... dod=... schedule="30 9 * * 1"
@@ -62,7 +63,7 @@ cron 最密每 30 分钟一次,落盘前校验。纯提醒不建 task,用普
62
63
 
63
64
  **首次执行遵循 cron 语义**:不显式传 `wake` 时,create 会把 `wake` 预约到下一次 occurrence,任务处于 `active` + 未来 `wake`——像 crontab 一样,创建不等于立刻跑。需要立刻开跑就显式传一个当下或过去的 `wake`。
64
65
 
65
- 到点后 **runtime 直接开下一周期**,不需要(也没有)手工开周期的动作:折叠上一周期日志入 History、清空本周期用量与验收授权元数据、置 `active`,然后派发一条普通驱动唤醒。你醒来面对的就是一个待推进的新周期,和其他唤醒无异。
66
+ 到点后 **runtime 直接开下一周期**,不需要(也没有)手工开周期的动作:折叠上一周期日志和 evidence 入 History、限制工作正文只保留最近周期、清空本周期用量与验收授权元数据、置 `active`,然后派发一条普通驱动唤醒。累计审计 usage 不会清零。你醒来面对的就是一个待推进的新周期,和其他唤醒无异。
66
67
 
67
68
  - 改节奏:`task_manage set schedule="<新 cron>"`;任务当前是 done 时写盘会重算 `wake`。一处真相。
68
69
  - 暂停 / 恢复:`/tasks pause <id>` / `/tasks resume <id>`。
@@ -642,6 +642,7 @@ export function createRuntimeContext(options) {
642
642
  await finishTaskAttempt(getChannelDir(options.paths.workspaceDir, event.channelId), taskDriverMatch[1], {
643
643
  tokens: result.usage.total,
644
644
  costUsd: result.usage.cost.total,
645
+ costKnown: result.costKnown === true,
645
646
  wallTimeMinutes: result.durationMs / 60_000,
646
647
  failed: result.stopReason === "error" || result.stopReason === "aborted",
647
648
  silent: result.silent,
@@ -711,7 +712,6 @@ export function createRuntimeContext(options) {
711
712
  return loadDetachedMaintenanceContext({
712
713
  channelId,
713
714
  channelDir: getChannelDir(options.paths.workspaceDir, channelId),
714
- workspaceDir: options.paths.workspaceDir,
715
715
  authConfigPath: options.paths.authConfigPath,
716
716
  modelsConfigPath: options.paths.modelsConfigPath,
717
717
  settingsManager: runtimeSettingsManager,
@@ -724,9 +724,6 @@ export function createRuntimeContext(options) {
724
724
  memoryMaintenance: runtimeSettingsManager.getMemoryMaintenanceSettings(),
725
725
  };
726
726
  },
727
- emitNotice: async (channelId, notice) => {
728
- await bot.sendPlain(channelId, notice);
729
- },
730
727
  intervalMs: options.memoryMaintenanceSchedulerIntervalMs,
731
728
  });
732
729
  const taskDriver = options.createTaskDriver