@oyasmi/pipiclaw 0.9.2 → 0.9.3-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 (178) hide show
  1. package/README.en.md +250 -0
  2. package/README.md +3 -1
  3. package/dist/agent/channel-runner.d.ts +59 -2
  4. package/dist/agent/channel-runner.js +177 -76
  5. package/dist/agent/job-manager.d.ts +76 -21
  6. package/dist/agent/job-manager.js +447 -63
  7. package/dist/agent/maintenance-context.js +4 -5
  8. package/dist/agent/prompt/manifest.d.ts +0 -2
  9. package/dist/agent/prompt/manifest.js +2 -3
  10. package/dist/agent/prompt/sections.js +3 -3
  11. package/dist/agent/session-events.js +4 -8
  12. package/dist/agent/turn-prompt.d.ts +7 -7
  13. package/dist/agent/turn-prompt.js +6 -9
  14. package/dist/agent/types.d.ts +12 -0
  15. package/dist/agent/types.js +1 -0
  16. package/dist/channel/channel-context.d.ts +13 -0
  17. package/dist/channel/channel-context.js +21 -1
  18. package/dist/commands/catalog.js +47 -20
  19. package/dist/memory/commands.d.ts +8 -0
  20. package/dist/memory/commands.js +113 -148
  21. package/dist/memory/index-budget.d.ts +27 -0
  22. package/dist/memory/index-budget.js +99 -0
  23. package/dist/memory/journal.d.ts +20 -0
  24. package/dist/memory/journal.js +78 -0
  25. package/dist/memory/lifecycle.d.ts +9 -15
  26. package/dist/memory/lifecycle.js +55 -145
  27. package/dist/memory/maintenance-gates.d.ts +13 -47
  28. package/dist/memory/maintenance-gates.js +13 -92
  29. package/dist/memory/maintenance-state.d.ts +10 -16
  30. package/dist/memory/maintenance-state.js +12 -59
  31. package/dist/memory/maintenance-tuning.d.ts +7 -27
  32. package/dist/memory/maintenance-tuning.js +11 -28
  33. package/dist/memory/migrate.d.ts +15 -0
  34. package/dist/memory/migrate.js +364 -0
  35. package/dist/memory/reflect-job.d.ts +43 -0
  36. package/dist/memory/reflect-job.js +117 -0
  37. package/dist/memory/reflect.d.ts +52 -0
  38. package/dist/memory/reflect.js +313 -0
  39. package/dist/memory/render.d.ts +19 -0
  40. package/dist/memory/render.js +35 -0
  41. package/dist/memory/review-log.d.ts +2 -1
  42. package/dist/memory/scheduler.d.ts +2 -3
  43. package/dist/memory/scheduler.js +14 -49
  44. package/dist/memory/search.d.ts +35 -0
  45. package/dist/memory/search.js +297 -0
  46. package/dist/memory/session-search.js +1 -1
  47. package/dist/memory/store.d.ts +108 -0
  48. package/dist/memory/store.js +418 -0
  49. package/dist/memory/task-digest.d.ts +2 -2
  50. package/dist/memory/task-digest.js +29 -36
  51. package/dist/memory/tombstones.d.ts +0 -11
  52. package/dist/memory/tombstones.js +6 -37
  53. package/dist/memory/transcript.js +12 -5
  54. package/dist/playbooks/agent-delegation.md +37 -9
  55. package/dist/playbooks/background-jobs.md +1 -1
  56. package/dist/playbooks/event-scheduling.md +6 -2
  57. package/dist/playbooks/memory-and-learning.md +36 -12
  58. package/dist/playbooks/outbound-media.md +1 -1
  59. package/dist/playbooks/runtime-orientation.md +9 -8
  60. package/dist/playbooks/task-loop.md +110 -0
  61. package/dist/runtime/bootstrap.d.ts +3 -3
  62. package/dist/runtime/bootstrap.js +66 -41
  63. package/dist/runtime/events.d.ts +9 -0
  64. package/dist/runtime/events.js +43 -4
  65. package/dist/runtime/task-commands.d.ts +14 -15
  66. package/dist/runtime/task-commands.js +249 -485
  67. package/dist/runtime/task-driver.d.ts +41 -29
  68. package/dist/runtime/task-driver.js +170 -317
  69. package/dist/runtime/task-migration.d.ts +34 -30
  70. package/dist/runtime/task-migration.js +229 -183
  71. package/dist/runtime/task-wake.d.ts +6 -3
  72. package/dist/runtime/task-wake.js +26 -19
  73. package/dist/settings.d.ts +0 -29
  74. package/dist/settings.js +12 -35
  75. package/dist/shared/markdown-sections.d.ts +0 -1
  76. package/dist/shared/markdown-sections.js +0 -3
  77. package/dist/subagents/discovery.d.ts +2 -2
  78. package/dist/subagents/discovery.js +21 -10
  79. package/dist/subagents/external/progress-tail.js +6 -1
  80. package/dist/subagents/external/run.js +1 -0
  81. package/dist/subagents/runs.d.ts +19 -2
  82. package/dist/subagents/runs.js +73 -4
  83. package/dist/subagents/tool.d.ts +10 -8
  84. package/dist/subagents/tool.js +55 -94
  85. package/dist/tasks/brief.d.ts +17 -0
  86. package/dist/tasks/brief.js +57 -0
  87. package/dist/tasks/budget.d.ts +26 -0
  88. package/dist/tasks/budget.js +59 -0
  89. package/dist/tasks/cycle.d.ts +48 -0
  90. package/dist/tasks/cycle.js +94 -0
  91. package/dist/tasks/frontmatter.d.ts +73 -0
  92. package/dist/tasks/frontmatter.js +175 -0
  93. package/dist/tasks/ledger.d.ts +66 -106
  94. package/dist/tasks/ledger.js +90 -546
  95. package/dist/tasks/log.d.ts +88 -0
  96. package/dist/tasks/log.js +97 -0
  97. package/dist/tasks/rounds.d.ts +41 -0
  98. package/dist/tasks/rounds.js +53 -0
  99. package/dist/tasks/session-path.d.ts +9 -0
  100. package/dist/tasks/session-path.js +16 -0
  101. package/dist/tasks/steer.d.ts +8 -0
  102. package/dist/tasks/steer.js +79 -0
  103. package/dist/tasks/store.d.ts +60 -35
  104. package/dist/tasks/store.js +166 -107
  105. package/dist/tasks/ticket.d.ts +102 -0
  106. package/dist/tasks/ticket.js +209 -0
  107. package/dist/tasks/verification.d.ts +47 -0
  108. package/dist/tasks/verification.js +60 -1
  109. package/dist/tools/index.d.ts +13 -4
  110. package/dist/tools/index.js +5 -10
  111. package/dist/tools/memory-manage.d.ts +6 -16
  112. package/dist/tools/memory-manage.js +108 -129
  113. package/dist/tools/presentation.js +2 -1
  114. package/dist/tools/registry.d.ts +11 -2
  115. package/dist/tools/registry.js +17 -6
  116. package/dist/tools/subagent-manage.d.ts +0 -9
  117. package/dist/tools/subagent-manage.js +8 -17
  118. package/dist/tools/task-manage/create.js +2 -2
  119. package/dist/tools/task-manage/lifecycle.d.ts +9 -4
  120. package/dist/tools/task-manage/lifecycle.js +136 -188
  121. package/dist/tools/task-manage/log-view.d.ts +8 -0
  122. package/dist/tools/task-manage/log-view.js +24 -0
  123. package/dist/tools/task-manage/schema.d.ts +38 -14
  124. package/dist/tools/task-manage/schema.js +46 -27
  125. package/dist/tools/task-manage/shared.d.ts +35 -31
  126. package/dist/tools/task-manage/shared.js +130 -141
  127. package/dist/tools/task-manage/step-end.d.ts +11 -0
  128. package/dist/tools/task-manage/step-end.js +134 -0
  129. package/dist/tools/task-manage/types.d.ts +23 -32
  130. package/dist/tools/task-manage.d.ts +4 -3
  131. package/dist/tools/task-manage.js +30 -15
  132. package/dist/tools/tool-details.d.ts +1 -1
  133. package/dist/tui/app.js +0 -2
  134. package/examples/sub-agents/README.md +54 -38
  135. package/examples/sub-agents/builder-hard.md +21 -12
  136. package/examples/sub-agents/builder.md +24 -16
  137. package/examples/sub-agents/explorer.md +17 -15
  138. package/examples/sub-agents/git-committer.md +8 -6
  139. package/examples/sub-agents/planner.md +17 -16
  140. package/examples/sub-agents/reviewer.md +11 -9
  141. package/examples/sub-agents/verifier.md +22 -16
  142. package/examples/sub-agents/worker.md +22 -6
  143. package/package.json +1 -1
  144. package/dist/agent/effect-ledger.d.ts +0 -32
  145. package/dist/agent/effect-ledger.js +0 -89
  146. package/dist/memory/bootstrap.d.ts +0 -17
  147. package/dist/memory/bootstrap.js +0 -120
  148. package/dist/memory/candidates.d.ts +0 -26
  149. package/dist/memory/candidates.js +0 -202
  150. package/dist/memory/consolidation.d.ts +0 -54
  151. package/dist/memory/consolidation.js +0 -292
  152. package/dist/memory/extraction.d.ts +0 -54
  153. package/dist/memory/extraction.js +0 -240
  154. package/dist/memory/files.d.ts +0 -71
  155. package/dist/memory/files.js +0 -419
  156. package/dist/memory/maintenance-jobs.d.ts +0 -41
  157. package/dist/memory/maintenance-jobs.js +0 -265
  158. package/dist/memory/metadata.d.ts +0 -57
  159. package/dist/memory/metadata.js +0 -142
  160. package/dist/memory/probation.d.ts +0 -17
  161. package/dist/memory/probation.js +0 -44
  162. package/dist/memory/promotion.d.ts +0 -38
  163. package/dist/memory/promotion.js +0 -36
  164. package/dist/memory/recall.d.ts +0 -59
  165. package/dist/memory/recall.js +0 -746
  166. package/dist/memory/session.d.ts +0 -24
  167. package/dist/memory/session.js +0 -273
  168. package/dist/playbooks/task-driving.md +0 -92
  169. package/dist/playbooks/task-planning.md +0 -58
  170. package/dist/tasks/control.d.ts +0 -56
  171. package/dist/tasks/control.js +0 -169
  172. package/dist/tasks/transitions.d.ts +0 -16
  173. package/dist/tasks/transitions.js +0 -48
  174. package/dist/tools/task-manage/verification.d.ts +0 -19
  175. package/dist/tools/task-manage/verification.js +0 -91
  176. package/examples/sub-agents/documenter.md +0 -50
  177. package/examples/sub-agents/log-sifter.md +0 -47
  178. package/examples/sub-agents/scout.md +0 -34
@@ -24,35 +24,16 @@ export interface PipiclawRetrySettings {
24
24
  maxRetries: number;
25
25
  baseDelayMs: number;
26
26
  }
27
- export interface PipiclawMemoryRecallSettings {
28
- enabled: boolean;
29
- maxCandidates: number;
30
- maxInjected: number;
31
- maxChars: number;
32
- rerankWithModel: boolean | "auto";
33
- }
34
27
  export interface PipiclawTaskDigestSettings {
35
28
  maxTasks: number;
36
29
  maxChars: number;
37
30
  }
38
31
  export interface PipiclawTaskDriverSettings {
39
- /** Earliest continuation after a task changed during its previous run. */
40
- continuationDelayMinutes: number;
41
- /** Retry delay when a dispatched task made no observable ledger progress. */
42
- stalledRetryMinutes: number;
43
32
  /** Global enqueue cap per scan, with round-robin fairness across channels. */
44
33
  maxDispatchesPerTick: number;
45
34
  /** Cap on idle sleep between scans; also the upper bound on how late a manual edit is noticed. */
46
35
  maxSleepMinutes: number;
47
36
  }
48
- export interface PipiclawSessionMemorySettings {
49
- enabled: boolean;
50
- minTurnsBetweenUpdate: number;
51
- minToolCallsBetweenUpdate: number;
52
- timeoutMs: number;
53
- forceRefreshBeforeCompact: boolean;
54
- forceRefreshBeforeNewSession: boolean;
55
- }
56
37
  export type PipiclawMemoryMaintenanceSettings = MemoryMaintenanceTuning & {
57
38
  enabled: boolean;
58
39
  };
@@ -108,14 +89,6 @@ export interface PipiclawSettings {
108
89
  retry?: {
109
90
  enabled?: boolean;
110
91
  };
111
- memoryRecall?: {
112
- enabled?: boolean;
113
- /** Costs an extra LLM call, so it stays a user decision rather than a constant. */
114
- rerankWithModel?: boolean | "auto";
115
- };
116
- sessionMemory?: {
117
- enabled?: boolean;
118
- };
119
92
  memoryMaintenance?: {
120
93
  enabled?: boolean;
121
94
  };
@@ -174,8 +147,6 @@ export declare class PipiclawSettingsManager {
174
147
  getCompactionEnabled(): boolean;
175
148
  setCompactionEnabled(enabled: boolean): void;
176
149
  getRetrySettings(): PipiclawRetrySettings;
177
- getMemoryRecallSettings(): PipiclawMemoryRecallSettings;
178
- getSessionMemorySettings(): PipiclawSessionMemorySettings;
179
150
  getMemoryMaintenanceSettings(): PipiclawMemoryMaintenanceSettings;
180
151
  getSessionSearchSettings(): PipiclawSessionSearchSettings;
181
152
  getLoggingSettings(): PipiclawLoggingSettings;
package/dist/settings.js CHANGED
@@ -9,7 +9,7 @@
9
9
  import { existsSync, mkdirSync, readFileSync } from "fs";
10
10
  import { dirname, join } from "path";
11
11
  import * as log from "./log.js";
12
- import { getMemoryMaintenanceTuning, getSessionRefreshCadence, } from "./memory/maintenance-tuning.js";
12
+ import { getMemoryMaintenanceTuning } from "./memory/maintenance-tuning.js";
13
13
  import { writeFileAtomicallySync } from "./shared/atomic-file.js";
14
14
  import { fileStamp } from "./shared/file-stamp.js";
15
15
  const DEFAULT_TUI = {
@@ -28,36 +28,19 @@ const DEFAULT_RETRY = {
28
28
  maxRetries: 3,
29
29
  baseDelayMs: 2000,
30
30
  };
31
- const DEFAULT_MEMORY_RECALL = {
32
- enabled: true,
33
- maxCandidates: 12,
34
- maxInjected: 5,
35
- maxChars: 5000,
36
- rerankWithModel: "auto",
37
- };
38
31
  // Cheap and high-value: reading a handful of task frontmatters and always surfacing
39
32
  // the in-flight agenda is worth more than the tokens it costs, so it defaults on.
40
33
  export const TASK_DIGEST_SETTINGS = {
41
34
  maxTasks: 8,
42
35
  maxChars: 1000,
43
36
  };
44
- // The driver makes `wake` an executable task property rather than a convention
45
- // that requires users to install a heartbeat event and sensor script. A changed
46
- // task can continue promptly; an unchanged task backs off to avoid token loops.
37
+ // Only the two knobs the scan itself needs. The retry/backoff tiers are gone with the governor
38
+ // (spec 051, D6): a task continues immediately or stops on a budget it can see, so there is no
39
+ // longer a "how long to wait before guessing again" question to answer.
47
40
  export const TASK_DRIVER_SETTINGS = {
48
- continuationDelayMinutes: 5,
49
- stalledRetryMinutes: 60,
50
41
  maxDispatchesPerTick: 4,
51
42
  maxSleepMinutes: 15,
52
43
  };
53
- const DEFAULT_SESSION_MEMORY = {
54
- enabled: true,
55
- minTurnsBetweenUpdate: 2,
56
- minToolCallsBetweenUpdate: 4,
57
- timeoutMs: 30_000,
58
- forceRefreshBeforeCompact: true,
59
- forceRefreshBeforeNewSession: true,
60
- };
61
44
  const DEFAULT_SESSION_SEARCH = {
62
45
  maxFiles: 12,
63
46
  maxChunks: 80,
@@ -89,9 +72,16 @@ const RETIRED_SETTINGS_KEYS = [
89
72
  "compaction.keepRecentTokens",
90
73
  "retry.maxRetries",
91
74
  "retry.baseDelayMs",
75
+ // Spec 050: per-turn recall is retired (D1) — the whole memoryRecall section is gone, not
76
+ // just its numeric params.
77
+ "memoryRecall.enabled",
78
+ "memoryRecall.rerankWithModel",
92
79
  "memoryRecall.maxCandidates",
93
80
  "memoryRecall.maxInjected",
94
81
  "memoryRecall.maxChars",
82
+ // Spec 050: SESSION.md is retired (the journal replaces it), so the whole sessionMemory
83
+ // section — including its own top-level enable switch — is gone, not just its params.
84
+ "sessionMemory.enabled",
95
85
  "sessionMemory.minTurnsBetweenUpdate",
96
86
  "sessionMemory.minToolCallsBetweenUpdate",
97
87
  "sessionMemory.timeoutMs",
@@ -101,6 +91,7 @@ const RETIRED_SETTINGS_KEYS = [
101
91
  "memoryMaintenance.minIdleMinutesBeforeLlmWork",
102
92
  "memoryMaintenance.sessionRefreshIntervalMinutes",
103
93
  "memoryMaintenance.checkpointIntervalMinutes",
94
+ "memoryMaintenance.reflectIntervalMinutes",
104
95
  "memoryMaintenance.minMemoryAutoWriteConfidence",
105
96
  "memoryMaintenance.structuralMaintenanceIntervalHours",
106
97
  "memoryMaintenance.maxConcurrentChannels",
@@ -320,20 +311,6 @@ export class PipiclawSettingsManager {
320
311
  enabled: this.settings.retry?.enabled ?? DEFAULT_RETRY.enabled,
321
312
  };
322
313
  }
323
- getMemoryRecallSettings() {
324
- return {
325
- ...DEFAULT_MEMORY_RECALL,
326
- enabled: this.settings.memoryRecall?.enabled ?? DEFAULT_MEMORY_RECALL.enabled,
327
- rerankWithModel: this.settings.memoryRecall?.rerankWithModel ?? DEFAULT_MEMORY_RECALL.rerankWithModel,
328
- };
329
- }
330
- getSessionMemorySettings() {
331
- return {
332
- ...DEFAULT_SESSION_MEMORY,
333
- ...getSessionRefreshCadence(),
334
- enabled: this.settings.sessionMemory?.enabled ?? DEFAULT_SESSION_MEMORY.enabled,
335
- };
336
- }
337
314
  getMemoryMaintenanceSettings() {
338
315
  return {
339
316
  ...getMemoryMaintenanceTuning(),
@@ -2,5 +2,4 @@ export interface MarkdownSection {
2
2
  heading: string;
3
3
  content: string;
4
4
  }
5
- export declare function splitH1Sections(content: string): MarkdownSection[];
6
5
  export declare function splitH2Sections(content: string): MarkdownSection[];
@@ -32,9 +32,6 @@ function splitSectionsByHeading(content, headingPrefix) {
32
32
  flush();
33
33
  return sections;
34
34
  }
35
- export function splitH1Sections(content) {
36
- return splitSectionsByHeading(content, "# ");
37
- }
38
35
  export function splitH2Sections(content) {
39
36
  return splitSectionsByHeading(content, "## ");
40
37
  }
@@ -2,7 +2,7 @@ import type { Api, Model } from "@earendil-works/pi-ai";
2
2
  import type { SecurityConfig } from "../security/types.js";
3
3
  declare const ALLOWED_SUB_AGENT_TOOLS: readonly ["read", "grep", "bash", "edit", "write", "web_search", "web_fetch"];
4
4
  declare const ALLOWED_CONTEXT_MODES: readonly ["isolated", "contextual"];
5
- declare const ALLOWED_MEMORY_MODES: readonly ["none", "session", "relevant"];
5
+ declare const ALLOWED_MEMORY_MODES: readonly ["none", "index"];
6
6
  declare const ALLOWED_THINKING_LEVELS: readonly ["off", "minimal", "low", "medium", "high", "xhigh", "max"];
7
7
  declare const ALLOWED_RUNTIMES: readonly ["internal", "external"];
8
8
  declare const ALLOWED_HARNESSES: readonly ["claude-code", "codex-cli", "exec"];
@@ -50,7 +50,7 @@ export type SubAgentEffort = keyof typeof SUB_AGENT_EFFORT_PRESETS;
50
50
  * surface collapses them into one enum. The dropped state — contextual with `memory: none`,
51
51
  * i.e. paths-only injection — remains expressible in frontmatter.
52
52
  */
53
- declare const ALLOWED_CONTEXT_CHOICES: readonly ["none", "session", "relevant"];
53
+ declare const ALLOWED_CONTEXT_CHOICES: readonly ["none", "index"];
54
54
  export type SubAgentContextChoice = (typeof ALLOWED_CONTEXT_CHOICES)[number];
55
55
  export interface SubAgentConfig {
56
56
  name: string;
@@ -19,7 +19,9 @@ const DEFAULT_EXTERNAL_MAX_WALL_TIME_SEC = 3600;
19
19
  const MAX_SUB_AGENT_TASK_CHARS = 12000;
20
20
  const MAX_SUB_AGENT_SYSTEM_PROMPT_CHARS = 16000;
21
21
  const ALLOWED_CONTEXT_MODES = ["isolated", "contextual"];
22
- const ALLOWED_MEMORY_MODES = ["none", "session", "relevant"];
22
+ const ALLOWED_MEMORY_MODES = ["none", "index"];
23
+ /** Spec 050, D12: `session`/`relevant` are retired — both collapse to `index`. */
24
+ const LEGACY_MEMORY_MODE_ALIASES = { session: "index", relevant: "index" };
23
25
  // "max" is a real SDK ThinkingLevel; pipiclaw's own whitelist previously omitted it (spec 040, D4).
24
26
  const ALLOWED_THINKING_LEVELS = ["off", "minimal", "low", "medium", "high", "xhigh", "max"];
25
27
  const ALLOWED_RUNTIMES = ["internal", "external"];
@@ -50,7 +52,7 @@ const ALLOWED_EFFORTS = Object.keys(SUB_AGENT_EFFORT_PRESETS);
50
52
  * surface collapses them into one enum. The dropped state — contextual with `memory: none`,
51
53
  * i.e. paths-only injection — remains expressible in frontmatter.
52
54
  */
53
- const ALLOWED_CONTEXT_CHOICES = ["none", "session", "relevant"];
55
+ const ALLOWED_CONTEXT_CHOICES = ["none", "index"];
54
56
  /** Internal work/verify default, aligned with the main agent's DEFAULT_MAIN_THINKING_LEVEL
55
57
  * (channel-runner.ts). External work leaves thinkingLevel unset instead (see resolveSubAgentConfig):
56
58
  * pipiclaw has no standing to pick a reasoning effort for another CLI's own configuration. */
@@ -204,6 +206,13 @@ function parseMemoryMode(raw, defaultValue) {
204
206
  if (ALLOWED_MEMORY_MODES.includes(normalized)) {
205
207
  return { value: normalized };
206
208
  }
209
+ // Frontmatter lives in the user's workspace, not under this codebase's control, so a role
210
+ // written against the retired `session`/`relevant` values keeps loading — with a warning —
211
+ // instead of being dropped (spec 050, D12).
212
+ const legacy = LEGACY_MEMORY_MODE_ALIASES[normalized];
213
+ if (legacy) {
214
+ return { value: legacy, warning: `memory: "${normalized}" is retired; treating it as "${legacy}"` };
215
+ }
207
216
  return {
208
217
  value: defaultValue,
209
218
  error: `Unknown memory "${normalized}". Allowed values: ${ALLOWED_MEMORY_MODES.join(", ")}`,
@@ -350,7 +359,7 @@ function parseInternalAgent(entryName, filePath, frontmatter, body, name, descri
350
359
  const contextMode = parseContextMode(frontmatter.contextMode);
351
360
  if (contextMode.error)
352
361
  return { warning: `${entryName}: ${contextMode.error}` };
353
- const memoryMode = parseMemoryMode(frontmatter.memory, contextMode.value === "contextual" ? "relevant" : "none");
362
+ const memoryMode = parseMemoryMode(frontmatter.memory, contextMode.value === "contextual" ? "index" : "none");
354
363
  if (memoryMode.error)
355
364
  return { warning: `${entryName}: ${memoryMode.error}` };
356
365
  const parsedPaths = parseStringList(frontmatter.paths, "paths");
@@ -393,7 +402,9 @@ function parseInternalAgent(entryName, filePath, frontmatter, body, name, descri
393
402
  const bashWithoutMutatesWarning = toolParse.tools.includes("bash") && mutates.value === undefined
394
403
  ? 'tools include bash but "mutates" is not declared; if this role writes to the workspace, declare mutates: write so it participates in the workspace write lease'
395
404
  : undefined;
396
- const combinedWarningBody = [numericWarning, bashWithoutMutatesWarning].filter(Boolean).join("; ");
405
+ const combinedWarningBody = [numericWarning, memoryMode.warning, bashWithoutMutatesWarning]
406
+ .filter(Boolean)
407
+ .join("; ");
397
408
  return {
398
409
  warning: combinedWarningBody ? `${entryName}: ${combinedWarningBody}` : undefined,
399
410
  agent: {
@@ -462,13 +473,13 @@ function parseExternalAgent(entryName, filePath, frontmatter, body, name, descri
462
473
  return { warning: `${entryName}: ${contextMode.error}` };
463
474
  // Spec 042 D4: external default is always "none", never following contextMode the way internal
464
475
  // does — a role that only wants `paths` injected (contextMode: contextual) should not also
465
- // silently start sending session/memory content to a third-party process. Explicitly declaring
466
- // `memory: session|relevant` is a real, informed choice; it gets a disclosure warning below.
476
+ // silently start sending memory content to a third-party process. Explicitly declaring
477
+ // `memory: index` is a real, informed choice; it gets a disclosure warning below.
467
478
  const memoryMode = parseMemoryMode(frontmatter.memory, "none");
468
479
  if (memoryMode.error)
469
480
  return { warning: `${entryName}: ${memoryMode.error}` };
470
481
  const memoryDisclosureWarning = memoryMode.value !== "none"
471
- ? `${entryName}: memory: ${memoryMode.value} sends channel session state / recalled memory content to this external process`
482
+ ? `${entryName}: memory: ${memoryMode.value} sends the channel memory index / journal content to this external process`
472
483
  : undefined;
473
484
  const maxWallTimeSec = parsePositiveInteger(frontmatter.maxWallTimeSec, DEFAULT_EXTERNAL_MAX_WALL_TIME_SEC);
474
485
  const trimmedBody = body.trim();
@@ -494,9 +505,9 @@ function parseExternalAgent(entryName, filePath, frontmatter, body, name, descri
494
505
  const modelPlaceholderWarning = command.includes("$MODEL") && !externalModelRef
495
506
  ? `${entryName}: command references $MODEL but no "model" is configured; that argv token will be dropped on every dispatch`
496
507
  : undefined;
497
- // Both are non-fatal (the role still loads); joined rather than picking one so an unlucky
508
+ // All non-fatal (the role still loads); joined rather than picking one so an unlucky
498
509
  // combination never silently loses one of them.
499
- const combinedWarning = [memoryDisclosureWarning, modelPlaceholderWarning].filter(Boolean).join("; ") || undefined;
510
+ const combinedWarning = [memoryMode.warning, memoryDisclosureWarning, modelPlaceholderWarning].filter(Boolean).join("; ") || undefined;
500
511
  return {
501
512
  warning: combinedWarning,
502
513
  agent: {
@@ -708,7 +719,7 @@ subagentDefaultModelRef) {
708
719
  return { error: contextOverride.error };
709
720
  }
710
721
  const contextMode = contextOverride.value?.contextMode ?? "isolated";
711
- const memory = contextOverride.value?.memory ?? (contextMode === "contextual" ? "relevant" : "none");
722
+ const memory = contextOverride.value?.memory ?? (contextMode === "contextual" ? "index" : "none");
712
723
  const thinkingLevelOverride = overrides.thinkingLevel ? parseThinkingLevel(overrides.thinkingLevel) : undefined;
713
724
  if (thinkingLevelOverride?.error) {
714
725
  return { error: thinkingLevelOverride.error };
@@ -73,7 +73,12 @@ export function startExternalProgressTail(input) {
73
73
  noticeCount++;
74
74
  input.onProgress(label);
75
75
  };
76
- const timer = setInterval(() => void tick(), POLL_MS);
76
+ // `tick` is async and its result is discarded: a rejection here (a throwing `onProgress`
77
+ // callback, say) would otherwise surface as an unhandled rejection and reach the process-level
78
+ // fatal handler. Swallow it — a failed tick just costs one skipped progress notice.
79
+ const timer = setInterval(() => {
80
+ tick().catch(() => undefined);
81
+ }, POLL_MS);
77
82
  timer.unref?.();
78
83
  return {
79
84
  stop() {
@@ -166,6 +166,7 @@ export async function launchExternalRun(input) {
166
166
  taskId: input.taskId,
167
167
  workingDirectory: input.workingDirectory,
168
168
  artifactDir: input.artifactDir,
169
+ channelDir: input.channelDir,
169
170
  leaseKey: input.leaseKey,
170
171
  mutates: input.mutates,
171
172
  });
@@ -96,6 +96,9 @@ export interface RunRecord extends RunUsage {
96
96
  settlementPending?: PendingSettlement;
97
97
  /** Set once this run's usage has been written to the ledger; guards against double billing. */
98
98
  usageRecorded?: boolean;
99
+ /** Set once this run's cost (and, for a verifier, its round) has been credited to its task.
100
+ * Separate from `usageRecorded` so a replayed settlement can never write a second round. */
101
+ taskAccounted?: boolean;
99
102
  /** Set once the completion wake has been hallmarked for delivery; guards against a duplicate wake. */
100
103
  wakeEnqueued?: boolean;
101
104
  /** Durable one-time relationship between the internally produced wake and task activation (T9). */
@@ -162,6 +165,10 @@ export interface RegisterRunInput {
162
165
  taskId?: string;
163
166
  workingDirectory: string;
164
167
  artifactDir: string;
168
+ /** This run's channel directory — where its owning task lives (spec 051, D7/D10). Set at
169
+ * registration for every runtime, so settlement can credit the task whether the run was
170
+ * internal or external; the external launch path re-persists it with the rest of its info. */
171
+ channelDir?: string;
165
172
  /** Set only when the caller already holds a workspace write lease for this run (D10.1). */
166
173
  leaseKey?: string;
167
174
  mutates?: RunMutates;
@@ -354,6 +361,18 @@ export declare class SubAgentRunManager {
354
361
  settle(runId: string, input: SettleInput, options: {
355
362
  announce: boolean;
356
363
  }): Promise<void>;
364
+ /**
365
+ * Credit one settled run to the task that owns it: cost onto the cycle, and — for a verifier —
366
+ * one round onto the rework ledger. Best-effort by design: a task whose file has since been
367
+ * archived or hand-deleted must not block the completion wake.
368
+ */
369
+ private creditOwningTask;
370
+ /**
371
+ * The `purpose=work` run this verdict most plausibly judged: the same task's latest work run
372
+ * started before the verifier. Left `undefined` rather than guessed when there is none — an
373
+ * unattributed round is honest, a wrong attribution is not.
374
+ */
375
+ private latestWorkRunFor;
357
376
  /**
358
377
  * Dispatch the completion wake. Durable-dispatch persists its own pending record before this
359
378
  * call can be interrupted (`DurableDispatchService.dispatch`), and `dispatch()` is idempotent on
@@ -413,8 +432,6 @@ export declare function stopSubAgentGarbageCollector(): void;
413
432
  /** Give runs their persistence root, wake delivery, ledger, and archive. Called once from bootstrap. */
414
433
  export declare function configureSubAgentRuntime(config: RunManagerOptions): void;
415
434
  export declare function getSubAgentRunManager(channelId: string): SubAgentRunManager;
416
- /** Read-only view for `/tasks doctor`, mirroring `channelJobTaskIds`. */
417
- export declare function channelDelegationTaskIds(channelId: string): Set<string>;
418
435
  /**
419
436
  * Re-adopt every channel's persisted runs at startup, settling any internal run still marked
420
437
  * `running` as `lost` (D10.3). Channels are discovered from the state directory itself, exactly
@@ -11,6 +11,10 @@ import { errorMessage } from "../shared/text-utils.js";
11
11
  import { isRecord } from "../shared/type-guards.js";
12
12
  import { createEmptyUsageTotals } from "../shared/types.js";
13
13
  import { beginWakeClaim, finishWakeClaim } from "../shared/wake-claim.js";
14
+ import { DEFAULT_TASK_BUDGET } from "../tasks/budget.js";
15
+ import { recordTaskCost, recordVerificationRound } from "../tasks/rounds.js";
16
+ import { readStoredTask } from "../tasks/store.js";
17
+ import { attestationRejectionReason } from "../tasks/verification.js";
14
18
  import { startExternalProgressTail } from "./external/progress-tail.js";
15
19
  import { finalizeExternalRun } from "./external/settlement.js";
16
20
  import { acquireWorkspaceLease, formatWorkspaceLeaseConflict, releaseWorkspaceLease } from "./workspace-lease.js";
@@ -560,6 +564,16 @@ export class SubAgentRunManager {
560
564
  });
561
565
  await this.persist(record);
562
566
  }
567
+ // Spec 051, D7/D10: credit this run to its task's cycle — cost always, and for a
568
+ // purpose=verify run also one rework round. Guarded by its own idempotency marker
569
+ // inside the same settlement lock, so a replay adds nothing.
570
+ if (!record.taskAccounted && record.taskId && record.channelDir) {
571
+ record.taskAccounted = true;
572
+ await this.creditOwningTask(record, input).catch((error) => {
573
+ log.logWarning(`Failed to credit task ${record.taskId} for run ${record.runId}`, errorMessage(error));
574
+ });
575
+ await this.persist(record);
576
+ }
563
577
  if (record.wakeEnqueued)
564
578
  return;
565
579
  if (!options.announce) {
@@ -570,6 +584,65 @@ export class SubAgentRunManager {
570
584
  await this.announce(record, input.outputText, outputSaved);
571
585
  });
572
586
  }
587
+ /**
588
+ * Credit one settled run to the task that owns it: cost onto the cycle, and — for a verifier —
589
+ * one round onto the rework ledger. Best-effort by design: a task whose file has since been
590
+ * archived or hand-deleted must not block the completion wake.
591
+ */
592
+ async creditOwningTask(record, input) {
593
+ const channelDir = record.channelDir;
594
+ const taskId = record.taskId;
595
+ if (!channelDir || !taskId)
596
+ return;
597
+ const usd = input.usage.cost.total;
598
+ const estimated = input.costKnown === false;
599
+ if (record.purpose === "verify" && record.verificationVerdict) {
600
+ // Fail closed: a PASS only counts once the on-disk attestation still binds to this task,
601
+ // this contract and this checkout — exactly the checks `task_verify` ran before it was
602
+ // retired. A rejected PASS is recorded as a fail *with its reason*, so the loop sees why
603
+ // instead of silently losing a round.
604
+ const task = await readStoredTask(channelDir, taskId).catch(() => undefined);
605
+ const rejection = task
606
+ ? await attestationRejectionReason({
607
+ channelDir,
608
+ taskId,
609
+ runId: record.runId,
610
+ taskBody: task.body,
611
+ trustedWorkingDirectory: record.workingDirectory,
612
+ })
613
+ : "task file is missing";
614
+ await recordVerificationRound({
615
+ channelDir,
616
+ taskId,
617
+ verifyRunId: record.runId,
618
+ verdict: rejection ? "fail" : record.verificationVerdict,
619
+ strength: record.verificationStrength ?? "advisory",
620
+ workRunId: this.latestWorkRunFor(taskId, record.startedAt),
621
+ usd,
622
+ usdEstimated: estimated,
623
+ reason: rejection,
624
+ }, DEFAULT_TASK_BUDGET.rounds);
625
+ return;
626
+ }
627
+ await recordTaskCost(channelDir, taskId, usd, estimated);
628
+ }
629
+ /**
630
+ * The `purpose=work` run this verdict most plausibly judged: the same task's latest work run
631
+ * started before the verifier. Left `undefined` rather than guessed when there is none — an
632
+ * unattributed round is honest, a wrong attribution is not.
633
+ */
634
+ latestWorkRunFor(taskId, before) {
635
+ let best;
636
+ for (const candidate of this.runs.values()) {
637
+ if (candidate.taskId !== taskId || candidate.purpose !== "work")
638
+ continue;
639
+ if (candidate.startedAt > before)
640
+ continue;
641
+ if (!best || candidate.startedAt > best.startedAt)
642
+ best = candidate;
643
+ }
644
+ return best?.runId;
645
+ }
573
646
  /**
574
647
  * Dispatch the completion wake. Durable-dispatch persists its own pending record before this
575
648
  * call can be interrupted (`DurableDispatchService.dispatch`), and `dispatch()` is idempotent on
@@ -1112,10 +1185,6 @@ export function getSubAgentRunManager(channelId) {
1112
1185
  }
1113
1186
  return manager;
1114
1187
  }
1115
- /** Read-only view for `/tasks doctor`, mirroring `channelJobTaskIds`. */
1116
- export function channelDelegationTaskIds(channelId) {
1117
- return managers.get(channelId)?.runningTaskIds() ?? new Set();
1118
- }
1119
1188
  /**
1120
1189
  * How deep the scan below looks for record files.
1121
1190
  *
@@ -3,9 +3,7 @@ import type { Api, Model } from "@earendil-works/pi-ai";
3
3
  import { Type } from "typebox";
4
4
  import type { Executor } from "../executor.js";
5
5
  import type { FileStore } from "../file-store.js";
6
- import type { MemoryCandidateStore } from "../memory/candidates.js";
7
6
  import type { SecurityConfig } from "../security/types.js";
8
- import type { PipiclawMemoryRecallSettings } from "../settings.js";
9
7
  import { type UsageTotals } from "../shared/types.js";
10
8
  import type { PipiclawWebToolsConfig } from "../tools/config.js";
11
9
  import { type ResolvedSubAgentConfig, type SubAgentConfig, type SubAgentDiscoveryResult } from "./discovery.js";
@@ -32,7 +30,7 @@ declare const subagentInlineSchema: Type.TObject<{
32
30
  tools: Type.TOptional<Type.TArray<Type.TString>>;
33
31
  model: Type.TOptional<Type.TString>;
34
32
  effort: Type.TOptional<Type.TUnion<[Type.TLiteral<"quick">, Type.TLiteral<"standard">, Type.TLiteral<"deep">]>>;
35
- context: Type.TOptional<Type.TUnion<[Type.TLiteral<"none">, Type.TLiteral<"session">, Type.TLiteral<"relevant">]>>;
33
+ context: Type.TOptional<Type.TUnion<[Type.TLiteral<"none">, Type.TLiteral<"index">]>>;
36
34
  thinkingLevel: Type.TOptional<Type.TUnion<[Type.TLiteral<"off">, Type.TLiteral<"minimal">, Type.TLiteral<"low">, Type.TLiteral<"medium">, Type.TLiteral<"high">, Type.TLiteral<"xhigh">, Type.TLiteral<"max">]>>;
37
35
  mutates: Type.TOptional<Type.TUnion<[Type.TLiteral<"read">, Type.TLiteral<"write">]>>;
38
36
  workingDirectory: Type.TOptional<Type.TString>;
@@ -86,10 +84,8 @@ export interface SubAgentToolOptions {
86
84
  workspaceDir: string;
87
85
  channelDir: string;
88
86
  getSubAgentDiscovery?: () => SubAgentDiscoveryResult;
89
- getMemoryRecallSettings?: () => PipiclawMemoryRecallSettings;
90
87
  /** `settings.subagentModel` (spec 032 D5); null/undefined means unset. */
91
88
  getSubAgentModelReference?: () => string | null;
92
- memoryCandidateStore?: MemoryCandidateStore;
93
89
  securityConfig?: SecurityConfig;
94
90
  webConfig?: PipiclawWebToolsConfig;
95
91
  rtkEnabled?: boolean;
@@ -173,10 +169,16 @@ export declare function assertVerifyAdmissible(config: Pick<ResolvedSubAgentConf
173
169
  export declare function buildSubAgentTask(task: string, config: Pick<SubAgentConfig, "name">, runtimeContext: SubAgentToolOptions["runtimeContext"], contextBlocks: string[], runContext: SubAgentRunContext): string;
174
170
  /** Exported for `subagent_run op=follow_up` (spec 042 D7) — same reason as `buildSubAgentTask`. */
175
171
  /** The slice of `SubAgentToolOptions` `buildContextualBlocks` actually reads — narrowed (spec 042
176
- * D7) so `subagent_run op=follow_up` only needs to wire these six fields, not the full tool
172
+ * D7) so `subagent_run op=follow_up` only needs to wire these three fields, not the full tool
177
173
  * option surface (executor, discovery, web config, etc. that a context-block build never touches). */
178
- export type ContextualBlocksOptions = Pick<SubAgentToolOptions, "channelDir" | "getMemoryRecallSettings" | "runtimeContext" | "workspaceDir" | "resolveApiKey" | "memoryCandidateStore">;
179
- export declare function buildContextualBlocks(task: string, config: Pick<SubAgentConfig, "contextMode" | "paths" | "memory" | "description">, options: ContextualBlocksOptions, currentModel: Model<Api>): Promise<string[]>;
174
+ export type ContextualBlocksOptions = Pick<SubAgentToolOptions, "channelDir" | "runtimeContext" | "workspaceDir">;
175
+ /**
176
+ * Spec 050, D12: `memory: index` injects the same three sections the main agent's first-turn
177
+ * bootstrap does — workspace MEMORY.md, the channel index, today's journal tail — at half the
178
+ * main agent's budget. No per-call LLM recall: a sub-agent task is short-lived, so there is no
179
+ * "first turn" to bootstrap once and reuse; it gets the same snapshot every dispatch.
180
+ */
181
+ export declare function buildContextualBlocks(config: Pick<SubAgentConfig, "contextMode" | "paths" | "memory">, options: ContextualBlocksOptions): Promise<string[]>;
180
182
  export declare function createSubAgentTool(options: SubAgentToolOptions): AgentTool<typeof subagentSchema, SubAgentToolFields>;
181
183
  export declare function createSubAgentInlineTool(options: SubAgentToolOptions): AgentTool<typeof subagentInlineSchema, SubAgentToolFields>;
182
184
  export {};