@xzzpig/pi-subagents 0.7.0 → 0.9.0

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 (234) hide show
  1. package/CHANGELOG.md +456 -4
  2. package/README.md +3 -3
  3. package/agents/claude-code-writer.md +15 -0
  4. package/agents/claude-code.md +15 -0
  5. package/agents/codex-exec-writer.md +15 -0
  6. package/agents/codex-exec.md +15 -0
  7. package/agents/cursor-agent-writer.md +14 -0
  8. package/agents/cursor-agent.md +14 -0
  9. package/agents/reviewer.md +13 -3
  10. package/agents/scout.md +1 -1
  11. package/docs/agents.md +154 -42
  12. package/docs/configuration.md +85 -26
  13. package/docs/extension-api.md +81 -16
  14. package/docs/missions.md +2 -0
  15. package/docs/models.md +75 -11
  16. package/docs/observability.md +34 -21
  17. package/docs/tool-reference.md +142 -18
  18. package/docs/watchdog.md +92 -114
  19. package/docs/workflows.md +148 -4
  20. package/index.ts +10 -1
  21. package/install.mjs +1 -1
  22. package/package.json +7 -6
  23. package/prompts/council.md +19 -7
  24. package/prompts/parallel-review.md +5 -1
  25. package/prompts/review-loop.md +11 -7
  26. package/skills/council-mode/SKILL.md +44 -215
  27. package/skills/council-mode/references/pass-contracts.md +150 -0
  28. package/skills/pi-subagents/SKILL.md +90 -32
  29. package/skills/pi-subagents/references/constraints-and-recipes.md +34 -223
  30. package/skills/pi-subagents/references/execution-controls.md +104 -19
  31. package/skills/pi-subagents/references/management-authoring-rpc.md +5 -5
  32. package/skills/pi-subagents/references/multi-lane-orchestration.md +16 -4
  33. package/skills/pi-subagents/references/prompting-and-roles.md +71 -36
  34. package/skills/pi-subagents/references/review-and-validation.md +73 -0
  35. package/src/agents/agent-management.ts +471 -114
  36. package/src/agents/agent-refinements.ts +4 -4
  37. package/src/agents/agent-serializer.ts +16 -4
  38. package/src/agents/agents.ts +1076 -351
  39. package/src/agents/builtin-names.ts +6 -0
  40. package/src/agents/runtime-agent-events.ts +70 -0
  41. package/src/agents/runtime-agent-registry.ts +31 -20
  42. package/src/api/agents.ts +10 -5
  43. package/src/api/background-work.ts +12 -3
  44. package/src/api/capability-ceiling.ts +0 -1
  45. package/src/api/{pi-args.ts → child-tool-plan.ts} +1 -1
  46. package/src/api/delegation.ts +0 -7
  47. package/src/api/external-job-provider.ts +10 -1
  48. package/src/api/external-runs.ts +67 -4
  49. package/src/api/preflight.ts +97 -34
  50. package/src/api/project-panes.ts +2 -0
  51. package/src/api/shared-types.ts +6 -0
  52. package/src/extension/config.ts +90 -0
  53. package/src/extension/doctor.ts +15 -13
  54. package/src/extension/fanout-child.ts +17 -16
  55. package/src/extension/index.ts +139 -41
  56. package/src/extension/public-execution.ts +113 -22
  57. package/src/extension/rpc.ts +182 -13
  58. package/src/extension/schemas.ts +63 -21
  59. package/src/extension/tool-description.ts +48 -23
  60. package/src/extension/tool-result.ts +19 -0
  61. package/src/inspectors/herdr/actions.ts +2 -1
  62. package/src/inspectors/herdr/client.ts +3 -3
  63. package/src/inspectors/herdr/focus.ts +55 -0
  64. package/src/inspectors/herdr/inspector-runner.ts +21 -23
  65. package/src/inspectors/herdr/project-panes.ts +228 -44
  66. package/src/inspectors/herdr/session-roots-codec.ts +42 -0
  67. package/src/integrations/herdr-status.ts +75 -5
  68. package/src/intercom/native-supervisor-channel.ts +138 -60
  69. package/src/intercom/result-intercom.ts +2 -0
  70. package/src/intercom/supervisor-ui.ts +243 -0
  71. package/src/profiles/profiles.ts +5 -6
  72. package/src/runs/background/active-async-capacity.ts +103 -18
  73. package/src/runs/background/async-execution.ts +492 -125
  74. package/src/runs/background/async-job-tracker.ts +127 -28
  75. package/src/runs/background/async-resume.ts +67 -29
  76. package/src/runs/background/async-retention.ts +21 -4
  77. package/src/runs/background/async-status-snapshot.ts +23 -261
  78. package/src/runs/background/async-status.ts +199 -14
  79. package/src/runs/background/auto-drain.ts +1 -1
  80. package/src/runs/background/chain-append.ts +8 -3
  81. package/src/runs/background/chain-root-attachment.ts +79 -8
  82. package/src/runs/background/control-channel.ts +101 -214
  83. package/src/runs/background/fleet-view.ts +38 -22
  84. package/src/runs/background/inspect-rpc.ts +8 -8
  85. package/src/runs/background/notify.ts +295 -8
  86. package/src/runs/background/process-terminal.ts +16 -0
  87. package/src/runs/background/result-delivery-ownership.ts +45 -0
  88. package/src/runs/background/result-files.ts +28 -14
  89. package/src/runs/background/result-watcher.ts +43 -19
  90. package/src/runs/background/resume-guidance.ts +2 -2
  91. package/src/runs/background/retained-children.ts +1 -1
  92. package/src/runs/background/run-child-session.ts +613 -0
  93. package/src/runs/background/run-status.ts +99 -18
  94. package/src/runs/background/runner-aliases.ts +125 -0
  95. package/src/runs/background/runner-child-sessions.ts +31 -0
  96. package/src/runs/background/scheduled-runs.ts +174 -18
  97. package/src/runs/background/stale-run-reconciler.ts +13 -4
  98. package/src/runs/background/steering.ts +8 -15
  99. package/src/runs/background/subagent-runner.ts +959 -1159
  100. package/src/runs/background/subagent-wait.ts +86 -31
  101. package/src/runs/background/terminal-run-index.ts +1 -1
  102. package/src/runs/background/wait-completions.ts +45 -2
  103. package/src/runs/background/wait-config.ts +23 -9
  104. package/src/runs/background/wait-tool.ts +27 -19
  105. package/src/runs/foreground/async-steering-action.ts +3 -19
  106. package/src/runs/foreground/async-stop-action.ts +23 -2
  107. package/src/runs/foreground/execution.ts +585 -481
  108. package/src/runs/foreground/foreground-control.ts +13 -0
  109. package/src/runs/foreground/foreground-history.ts +26 -3
  110. package/src/runs/foreground/subagent-executor.ts +1549 -410
  111. package/src/runs/foreground/workflow-detach-reconcile.ts +141 -104
  112. package/src/runs/foreground/workflow-foreground-steering.ts +24 -98
  113. package/src/runs/shared/abort-recovery.ts +119 -0
  114. package/src/runs/shared/acceptance.ts +147 -39
  115. package/src/runs/shared/agent-contract.ts +1 -1
  116. package/src/runs/shared/async-status-projection.ts +565 -0
  117. package/src/runs/shared/background-process-options.ts +9 -0
  118. package/src/runs/shared/capability-ceiling.ts +2 -2
  119. package/src/runs/shared/child-hooks.ts +25 -0
  120. package/src/runs/shared/child-identity.ts +62 -0
  121. package/src/runs/shared/child-launch-plan.ts +151 -0
  122. package/src/runs/shared/child-launch.ts +314 -0
  123. package/src/runs/shared/child-lifecycle.ts +25 -0
  124. package/src/runs/shared/child-runtime-config.ts +126 -0
  125. package/src/runs/shared/child-session.ts +342 -0
  126. package/src/runs/shared/child-tool-plan.ts +540 -0
  127. package/src/runs/shared/claude-code-adapter.ts +133 -0
  128. package/src/runs/shared/codex-exec-adapter.ts +129 -0
  129. package/src/runs/shared/completion-evidence.ts +89 -0
  130. package/src/runs/shared/completion-guard.ts +57 -6
  131. package/src/runs/shared/cursor-agent-adapter.ts +114 -0
  132. package/src/runs/shared/dynamic-fanout.ts +4 -4
  133. package/src/runs/shared/extension-bindings.ts +78 -0
  134. package/src/runs/shared/external-cli-contract.ts +167 -0
  135. package/src/runs/shared/external-cli-preflight.ts +138 -0
  136. package/src/runs/shared/external-cli-runner.ts +349 -54
  137. package/src/runs/shared/external-job-bridge.ts +53 -37
  138. package/src/runs/shared/external-job-runner.ts +126 -23
  139. package/src/runs/shared/fast-mode-extension.ts +10 -0
  140. package/src/runs/shared/host-step-status.ts +231 -0
  141. package/src/runs/shared/lane-metadata.ts +126 -0
  142. package/src/runs/shared/launch-cwd.ts +16 -0
  143. package/src/runs/shared/long-running-guard.ts +2 -1
  144. package/src/runs/shared/mcp-config-sources.ts +422 -0
  145. package/src/runs/shared/mcp-direct-tool-allowlist.ts +222 -158
  146. package/src/runs/shared/mcp-direct-tool-grant.ts +194 -0
  147. package/src/runs/shared/model-exclusions.ts +141 -10
  148. package/src/runs/shared/model-fallback.ts +187 -33
  149. package/src/runs/shared/model-scope.ts +106 -39
  150. package/src/runs/shared/mutation-evidence.ts +199 -0
  151. package/src/runs/shared/nested-events.ts +38 -48
  152. package/src/runs/shared/nested-path.ts +0 -14
  153. package/src/runs/shared/nested-render.ts +9 -5
  154. package/src/runs/shared/orca-progress-tabs.ts +83 -16
  155. package/src/runs/shared/parallel-handoff.ts +423 -7
  156. package/src/runs/shared/parallel-utils.ts +28 -5
  157. package/src/runs/shared/permissions.ts +1 -14
  158. package/src/runs/shared/pi-spawn.ts +69 -35
  159. package/src/runs/shared/process-signal.ts +16 -0
  160. package/src/runs/shared/run-fanout-budget.ts +0 -13
  161. package/src/runs/shared/run-history.ts +21 -1
  162. package/src/runs/shared/runtime-acknowledged-extensions.ts +0 -27
  163. package/src/runs/shared/single-output.ts +89 -22
  164. package/src/runs/shared/structured-output.ts +61 -7
  165. package/src/runs/shared/subagent-control.ts +6 -2
  166. package/src/runs/shared/subagent-prompt-runtime.ts +216 -360
  167. package/src/runs/shared/task-intent.ts +21 -7
  168. package/src/runs/shared/tool-availability.ts +18 -64
  169. package/src/runs/shared/tool-budget.ts +0 -14
  170. package/src/runs/shared/tool-timeout.ts +1 -1
  171. package/src/runs/shared/workflow-graph.ts +16 -0
  172. package/src/runs/shared/worktree-cleanup-plan.ts +866 -0
  173. package/src/runs/shared/worktree.ts +571 -62
  174. package/src/shared/atomic-json.ts +3 -1
  175. package/src/shared/child-session-name.ts +46 -0
  176. package/src/shared/extension-context.ts +24 -0
  177. package/src/shared/fork-context.ts +21 -12
  178. package/src/shared/fork-session-cwd.ts +27 -0
  179. package/src/shared/formatters.ts +18 -3
  180. package/src/shared/jsonl-writer.ts +11 -0
  181. package/src/shared/launch-contract.ts +20 -6
  182. package/src/shared/pruned-fork.ts +450 -0
  183. package/src/shared/session-file-trust.ts +19 -0
  184. package/src/shared/session-tokens.ts +14 -3
  185. package/src/shared/settings.ts +21 -102
  186. package/src/shared/shortcuts.ts +17 -0
  187. package/src/shared/thinking-ceiling.ts +46 -0
  188. package/src/shared/types.ts +644 -75
  189. package/src/shared/utils.ts +60 -93
  190. package/src/shared/workflow-child-permit.ts +207 -0
  191. package/src/slash/delegation-adapters.ts +1 -9
  192. package/src/slash/delegation-request.ts +0 -4
  193. package/src/slash/prompt-template-bridge.ts +37 -1
  194. package/src/slash/slash-bridge.ts +1 -2
  195. package/src/slash/slash-commands.ts +383 -116
  196. package/src/slash/slash-live-state.ts +22 -11
  197. package/src/slash/subagents-admin.ts +29 -12
  198. package/src/tui/fleet-native-transcript.ts +4 -0
  199. package/src/tui/fleet-status.ts +278 -90
  200. package/src/tui/fleet-transcript.ts +11 -5
  201. package/src/tui/fleet.ts +54 -28
  202. package/src/tui/render-helpers.ts +31 -0
  203. package/src/tui/render.ts +1433 -166
  204. package/src/watchdog/change-signature.ts +40 -1
  205. package/src/watchdog/child-status.ts +54 -34
  206. package/src/watchdog/diff-tool.ts +77 -0
  207. package/src/watchdog/emission-guard.ts +5 -3
  208. package/src/watchdog/guidance.ts +20 -0
  209. package/src/watchdog/permission-arbiter.ts +59 -52
  210. package/src/watchdog/register-child.ts +28 -25
  211. package/src/watchdog/register-main.ts +10 -9
  212. package/src/watchdog/render.ts +4 -5
  213. package/src/watchdog/review.ts +15 -4
  214. package/src/watchdog/rules.ts +70 -0
  215. package/src/watchdog/runtime.ts +75 -92
  216. package/src/watchdog/scope.ts +0 -11
  217. package/src/watchdog/settings.ts +48 -104
  218. package/src/watchdog/turn-delta.ts +1 -1
  219. package/src/watchdog/types.ts +18 -32
  220. package/src/watchdog/warning-format.ts +0 -1
  221. package/src/workflows/chat-progress.ts +7 -3
  222. package/src/workflows/host-command.ts +235 -0
  223. package/src/workflows/scripted-workflow.ts +1142 -69
  224. package/src/workflows/workflow-checklist.ts +439 -0
  225. package/src/workflows/workflow-child-summary.ts +121 -0
  226. package/src/workflows/workflow-preflight.ts +297 -0
  227. package/src/workflows/workflow-receipt.ts +232 -6
  228. package/src/workflows/workflow-resources.ts +150 -0
  229. package/src/workflows/workflow-settlement.ts +246 -0
  230. package/src/runs/shared/child-protocol.ts +0 -401
  231. package/src/runs/shared/pi-args.ts +0 -858
  232. package/src/runs/shared/subagent-startup-retry.ts +0 -116
  233. package/src/runs/shared/turn-budget.ts +0 -98
  234. package/src/shared/post-exit-stdio-guard.ts +0 -85
@@ -1,6 +1,7 @@
1
1
  import { spawnSync } from "node:child_process";
2
2
  import { createHash } from "node:crypto";
3
3
  import * as fs from "node:fs";
4
+ import * as os from "node:os";
4
5
  import * as path from "node:path";
5
6
  import { PROJECT_SUBAGENTS_RELATIVE_DIR } from "../shared/artifacts.ts";
6
7
 
@@ -11,6 +12,7 @@ const IGNORED_CHANGE_SEGMENTS = new Set([".git", "node_modules"]);
11
12
  const DEFAULT_MAX_HASH_FILE_BYTES = 64 * 1024 * 1024;
12
13
  const DEFAULT_MAX_HASH_TOTAL_BYTES = 64 * 1024 * 1024;
13
14
  const DEFAULT_MAX_HASH_ENTRIES = 2_000;
15
+ const TRACKED_ENTRY_PROBE_MAX_BYTES = 1_024;
14
16
 
15
17
  function positiveEnvNumber(name: string, fallback: number): number {
16
18
  const parsed = Number(process.env[name]);
@@ -43,6 +45,37 @@ function git(cwd: string, args: string[]): string | undefined {
43
45
  return result.stdout;
44
46
  }
45
47
 
48
+ function comparablePath(value: string): string {
49
+ let resolved = path.resolve(value);
50
+ try {
51
+ resolved = fs.realpathSync.native(resolved);
52
+ } catch {
53
+ // Keep the lexical path when canonicalization is unavailable.
54
+ }
55
+ return process.platform === "win32" ? resolved.toLowerCase() : resolved;
56
+ }
57
+
58
+ function isHomeRepoRoot(root: string): boolean {
59
+ return comparablePath(root) === comparablePath(os.homedir());
60
+ }
61
+
62
+ /**
63
+ * Probe the index without asking Git to inspect the working tree. The output
64
+ * cap keeps this check bounded even for repositories with a very large index;
65
+ * an ENOBUFS result still proves that at least one tracked path exists.
66
+ */
67
+ function hasTrackedEntries(root: string): boolean | undefined {
68
+ const result = spawnSync("git", ["-C", root, "ls-files", "--cached", "--error-unmatch", "--", "."], {
69
+ encoding: "utf-8",
70
+ maxBuffer: TRACKED_ENTRY_PROBE_MAX_BYTES,
71
+ windowsHide: true,
72
+ });
73
+ const errorCode = (result.error as NodeJS.ErrnoException | undefined)?.code;
74
+ if (result.status === 0 || errorCode === "ENOBUFS") return true;
75
+ if (result.status === 1) return false;
76
+ return undefined;
77
+ }
78
+
46
79
  function normalizeRelPath(value: string): string {
47
80
  return value.replaceAll(path.sep, "/").replace(/^\.\//, "");
48
81
  }
@@ -181,7 +214,13 @@ function buildRepoChangeSignature(root: string, statusOutput: string): WatchdogR
181
214
  export function computeWatchdogRepoChangeSignature(cwd: string): WatchdogRepoChangeSignature | undefined {
182
215
  const root = git(cwd, ["rev-parse", "--show-toplevel"])?.trim();
183
216
  if (!root) return undefined;
184
- const statusOutput = git(root, ["status", "--porcelain=v1", "-z", "--untracked-files=all"]);
217
+ const skipUntracked = isHomeRepoRoot(root) || hasTrackedEntries(root) === false;
218
+ const statusOutput = git(root, [
219
+ "status",
220
+ "--porcelain=v1",
221
+ "-z",
222
+ `--untracked-files=${skipUntracked ? "no" : "all"}`,
223
+ ]);
185
224
  if (statusOutput === undefined) return undefined;
186
225
  try {
187
226
  return buildRepoChangeSignature(root, statusOutput);
@@ -1,13 +1,14 @@
1
- import type { ResolvedWatchdogConfig, WatchdogLspConfig } from "./types.ts";
1
+ import type { ChildWatchdogProgress, ChildWatchdogWarningSummary } from "../shared/types.ts";
2
+ import { SUBAGENT_WATCHDOG_WARNING_TYPE, type ResolvedWatchdogConfig, type WatchdogCadenceConfig, type WatchdogCategory, type WatchdogLspConfig } from "./types.ts";
3
+
4
+ export const CHILD_WATCHDOG_WARNING_LIMIT = 20;
2
5
 
3
- export const CHILD_WATCHDOG_CONFIG_ENV = "PI_SUBAGENT_WATCHDOG_CHILD_CONFIG";
4
6
  export const CHILD_WATCHDOG_STATUS_EVENT = "subagent.watchdog.status";
5
7
 
6
- export const CHILD_WATCHDOG_PHASES = ["idle", "reviewing", "autofollow", "settling", "stale", "failed"] as const;
8
+ export const CHILD_WATCHDOG_PHASES = ["idle", "reviewing", "stale", "failed"] as const;
7
9
  export type ChildWatchdogPhase = typeof CHILD_WATCHDOG_PHASES[number];
8
10
 
9
11
  export interface ChildWatchdogConfig {
10
- enabled: boolean;
11
12
  runId?: string;
12
13
  agent?: string;
13
14
  childIndex?: number;
@@ -17,9 +18,9 @@ export interface ChildWatchdogConfig {
17
18
  model?: string;
18
19
  thinking?: string | false;
19
20
  lsp: WatchdogLspConfig;
20
- autoFollowBlockers: boolean;
21
- autoFollowMaxAttempts: number | null;
22
21
  stalemateRepeats: number;
22
+ /** Mid-run review cadence; everyNTools null means boundary reviews only. */
23
+ cadence: WatchdogCadenceConfig;
23
24
  }
24
25
 
25
26
  export interface ChildWatchdogStatusEvent {
@@ -31,18 +32,10 @@ export interface ChildWatchdogStatusEvent {
31
32
  seq: number;
32
33
  phase: ChildWatchdogPhase;
33
34
  ts: number;
34
- followUpPending: boolean;
35
35
  reason?: string;
36
36
  }
37
37
 
38
- export interface ChildWatchdogStateSnapshot {
39
- phase: ChildWatchdogPhase;
40
- seq: number;
41
- lastUpdate: number;
42
- followUpPending: boolean;
43
- reason?: string;
44
- timedOut?: boolean;
45
- }
38
+ export type ChildWatchdogStateSnapshot = ChildWatchdogProgress;
46
39
 
47
40
  export function resolveChildWatchdogConfig(input: {
48
41
  config: ResolvedWatchdogConfig;
@@ -55,8 +48,8 @@ export function resolveChildWatchdogConfig(input: {
55
48
  if (!enabled) return undefined;
56
49
  const model = override?.model ?? input.config.children.model;
57
50
  const thinking = override?.thinking ?? input.config.children.thinking;
51
+ const cadence = override?.cadence ?? input.config.children.cadence ?? input.config.cadence;
58
52
  return {
59
- enabled: true,
60
53
  ...(input.runId ? { runId: input.runId } : {}),
61
54
  ...(input.agent ? { agent: input.agent } : {}),
62
55
  ...(input.childIndex !== undefined ? { childIndex: input.childIndex } : {}),
@@ -66,16 +59,11 @@ export function resolveChildWatchdogConfig(input: {
66
59
  ...(model ? { model } : {}),
67
60
  ...(thinking !== undefined ? { thinking } : {}),
68
61
  lsp: { ...input.config.lsp },
69
- autoFollowBlockers: input.config.children.autoFollow.blockers,
70
- autoFollowMaxAttempts: input.config.children.autoFollow.maxAttempts,
71
- stalemateRepeats: input.config.children.autoFollow.stalemateRepeats,
62
+ stalemateRepeats: input.config.stalemateRepeats,
63
+ cadence: { everyNTools: cadence.everyNTools ?? null },
72
64
  };
73
65
  }
74
66
 
75
- export function encodeChildWatchdogConfig(config: ChildWatchdogConfig | undefined): string | undefined {
76
- return config ? JSON.stringify(config) : undefined;
77
- }
78
-
79
67
  function childConfigObject(value: unknown, field: string): Record<string, unknown> {
80
68
  if (value && typeof value === "object" && !Array.isArray(value)) return value as Record<string, unknown>;
81
69
  throw new Error(`Invalid child watchdog config: ${field} must be an object.`);
@@ -108,10 +96,12 @@ function childConfigNullableNonNegativeInteger(input: Record<string, unknown>, f
108
96
  throw new Error(`Invalid child watchdog config: ${field} must be null or a non-negative integer.`);
109
97
  }
110
98
 
111
- function childConfigBoolean(input: Record<string, unknown>, field: string): boolean {
112
- const value = input[field];
113
- if (typeof value === "boolean") return value;
114
- throw new Error(`Invalid child watchdog config: ${field} must be a boolean.`);
99
+ function childConfigCadence(value: unknown): WatchdogCadenceConfig {
100
+ const input = childConfigObject(value, "cadence");
101
+ const everyNTools = input.everyNTools;
102
+ if (everyNTools === null) return { everyNTools: null };
103
+ if (typeof everyNTools === "number" && Number.isInteger(everyNTools) && everyNTools >= 5) return { everyNTools };
104
+ throw new Error("Invalid child watchdog config: cadence.everyNTools must be null or an integer >= 5.");
115
105
  }
116
106
 
117
107
  function childConfigLsp(value: unknown): WatchdogLspConfig {
@@ -138,7 +128,7 @@ export function decodeChildWatchdogConfig(raw: string | undefined): ChildWatchdo
138
128
  if (!raw) return undefined;
139
129
  const parsed = childConfigObject(JSON.parse(raw), "root");
140
130
  if (parsed.enabled === false) return undefined;
141
- if (parsed.enabled !== true) throw new Error("Invalid child watchdog config: enabled must be true or false.");
131
+ if ("enabled" in parsed && parsed.enabled !== true) throw new Error("Invalid child watchdog config: enabled must be true or false.");
142
132
  const thinking = parsed.thinking;
143
133
  if (thinking !== undefined && typeof thinking !== "string" && thinking !== false) {
144
134
  throw new Error("Invalid child watchdog config: thinking must be a string or false.");
@@ -148,7 +138,6 @@ export function decodeChildWatchdogConfig(raw: string | undefined): ChildWatchdo
148
138
  const childIndex = childConfigOptionalIndex(parsed, "childIndex");
149
139
  const model = childConfigOptionalString(parsed, "model");
150
140
  return {
151
- enabled: true,
152
141
  ...(runId ? { runId } : {}),
153
142
  ...(agent ? { agent } : {}),
154
143
  ...(childIndex !== undefined ? { childIndex } : {}),
@@ -158,9 +147,8 @@ export function decodeChildWatchdogConfig(raw: string | undefined): ChildWatchdo
158
147
  ...(model ? { model } : {}),
159
148
  ...(thinking !== undefined ? { thinking: thinking as string | false } : {}),
160
149
  lsp: childConfigLsp(parsed.lsp),
161
- autoFollowBlockers: childConfigBoolean(parsed, "autoFollowBlockers"),
162
- autoFollowMaxAttempts: childConfigNullableNonNegativeInteger(parsed, "autoFollowMaxAttempts"),
163
150
  stalemateRepeats: childConfigPositiveInteger(parsed, "stalemateRepeats"),
151
+ cadence: childConfigCadence(parsed.cadence),
164
152
  };
165
153
  }
166
154
 
@@ -173,14 +161,13 @@ export function isChildWatchdogStatusEvent(value: unknown): value is ChildWatchd
173
161
  && event.seq >= 0
174
162
  && typeof event.ts === "number"
175
163
  && Number.isFinite(event.ts)
176
- && typeof event.followUpPending === "boolean"
177
164
  && typeof event.phase === "string"
178
165
  && (CHILD_WATCHDOG_PHASES as readonly string[]).includes(event.phase);
179
166
  }
180
167
 
181
168
  export function childWatchdogIsActive(snapshot: ChildWatchdogStateSnapshot | undefined): boolean {
182
169
  if (!snapshot) return false;
183
- return snapshot.followUpPending || snapshot.phase === "reviewing" || snapshot.phase === "autofollow" || snapshot.phase === "settling";
170
+ return snapshot.phase === "reviewing";
184
171
  }
185
172
 
186
173
  export function acceptChildWatchdogEvent(input: {
@@ -199,7 +186,40 @@ export function acceptChildWatchdogEvent(input: {
199
186
  phase: input.event.phase,
200
187
  seq: input.event.seq,
201
188
  lastUpdate: input.event.ts,
202
- followUpPending: input.event.followUpPending,
203
189
  ...(input.event.reason ? { reason: input.event.reason } : {}),
190
+ ...(input.current?.warnings?.length ? { warnings: input.current.warnings } : {}),
204
191
  };
205
192
  }
193
+
194
+ function childWatchdogWarningFromMessage(message: unknown): ChildWatchdogWarningSummary | undefined {
195
+ const candidate = message as { role?: unknown; customType?: unknown; details?: Record<string, unknown> } | undefined;
196
+ if (candidate?.role !== "custom" || candidate.customType !== SUBAGENT_WATCHDOG_WARNING_TYPE) return undefined;
197
+ const details = candidate.details ?? {};
198
+ if (details.severity !== "concern" && details.severity !== "blocker") return undefined;
199
+ if (typeof details.summary !== "string" || typeof details.evidence !== "string" || typeof details.recommendedAction !== "string") return undefined;
200
+ return {
201
+ severity: details.severity,
202
+ category: details.category as WatchdogCategory,
203
+ summary: details.summary,
204
+ evidence: details.evidence,
205
+ recommendedAction: details.recommendedAction,
206
+ ...(typeof details.displayedAt === "string" ? { displayedAt: details.displayedAt } : {}),
207
+ addressed: false,
208
+ stalemate: details.state === "stalemate",
209
+ };
210
+ }
211
+
212
+ /** A watchdog warning message is appended; an assistant turn marks earlier warnings addressed. Undefined when unchanged. */
213
+ export function applyChildWatchdogMessage(current: ChildWatchdogStateSnapshot | undefined, message: unknown, now = Date.now()): ChildWatchdogStateSnapshot | undefined {
214
+ const warning = childWatchdogWarningFromMessage(message);
215
+ if (warning) {
216
+ const warnings = [...(current?.warnings ?? []), warning].slice(-CHILD_WATCHDOG_WARNING_LIMIT);
217
+ return current ? { ...current, warnings } : { phase: "idle", seq: 0, lastUpdate: now, warnings };
218
+ }
219
+ if ((message as { role?: unknown } | undefined)?.role !== "assistant" || !current?.warnings?.some((entry) => !entry.addressed)) return undefined;
220
+ return { ...current, warnings: current.warnings.map((entry) => entry.addressed ? entry : { ...entry, addressed: true }) };
221
+ }
222
+
223
+ export function unresolvedChildWatchdogBlockers(progress: Pick<ChildWatchdogProgress, "warnings"> | undefined): ChildWatchdogWarningSummary[] {
224
+ return (progress?.warnings ?? []).filter((warning) => warning.severity === "blocker" && (!warning.addressed || warning.stalemate));
225
+ }
@@ -0,0 +1,77 @@
1
+ import { spawnSync } from "node:child_process";
2
+ import * as path from "node:path";
3
+ import type { AgentTool } from "@earendil-works/pi-agent-core";
4
+ import { Type, type Static } from "typebox";
5
+
6
+ export const WATCHDOG_DIFF_TOOL_NAME = "watchdog_diff";
7
+ export const WATCHDOG_DIFF_MAX_CHARS = 24_000;
8
+ const MAX_UNTRACKED_FILES = 50;
9
+
10
+ export interface WatchdogDiffBaseline {
11
+ root: string;
12
+ ref: string;
13
+ }
14
+
15
+ const WatchdogDiffParams = Type.Object({
16
+ path: Type.Optional(Type.String({ description: "Restrict the diff to one file or directory, relative to the repo root." })),
17
+ stat: Type.Optional(Type.Boolean({ description: "Return per-file change counts instead of the full diff." })),
18
+ }, { additionalProperties: false });
19
+
20
+ type WatchdogDiffParams = Static<typeof WatchdogDiffParams>;
21
+
22
+ function runGit(root: string, args: string[]): { ok: boolean; stdout: string; stderr: string } {
23
+ const result = spawnSync("git", ["-C", root, ...args], { encoding: "utf-8", maxBuffer: 16 * 1024 * 1024, windowsHide: true });
24
+ return { ok: result.status === 0, stdout: result.stdout ?? "", stderr: (result.stderr ?? "").trim() };
25
+ }
26
+
27
+ /** HEAD at session start, so later child commits still show in the diff. */
28
+ export function captureWatchdogDiffBaseline(cwd: string): WatchdogDiffBaseline | undefined {
29
+ const toplevel = runGit(cwd, ["rev-parse", "--show-toplevel"]);
30
+ if (!toplevel.ok) return undefined;
31
+ const head = runGit(cwd, ["rev-parse", "HEAD"]);
32
+ if (!head.ok) return undefined;
33
+ const root = toplevel.stdout.trim();
34
+ const ref = head.stdout.trim();
35
+ return root && ref ? { root, ref } : undefined;
36
+ }
37
+
38
+ function validatePath(value: string | undefined): string | undefined {
39
+ const trimmed = value?.trim();
40
+ if (!trimmed) return undefined;
41
+ if (trimmed.startsWith("-")) throw new Error("watchdog_diff path must not start with '-'.");
42
+ if (path.isAbsolute(trimmed)) throw new Error("watchdog_diff path must be relative to the repo root.");
43
+ if (trimmed.split(/[\\/]/).includes("..")) throw new Error("watchdog_diff path must not contain '..'.");
44
+ return trimmed;
45
+ }
46
+
47
+ function bound(text: string): string {
48
+ if (text.length <= WATCHDOG_DIFF_MAX_CHARS) return text;
49
+ const marker = `\n\n[... ${text.length - WATCHDOG_DIFF_MAX_CHARS} characters omitted; call again with a narrower path ...]`;
50
+ return `${text.slice(0, WATCHDOG_DIFF_MAX_CHARS - marker.length)}${marker}`;
51
+ }
52
+
53
+ /** In a shared cwd, changes already pending when the session started also appear. */
54
+ export function createWatchdogDiffTool(baseline: WatchdogDiffBaseline): AgentTool<typeof WatchdogDiffParams, { chars: number }> {
55
+ return {
56
+ name: WATCHDOG_DIFF_TOOL_NAME,
57
+ label: "Watchdog diff",
58
+ description: "Show the repository diff since the review baseline, plus untracked file paths. Optional path narrows it; stat:true returns per-file counts only.",
59
+ parameters: WatchdogDiffParams,
60
+ executionMode: "sequential",
61
+ async execute(_toolCallId, params: WatchdogDiffParams) {
62
+ const pathFilter = validatePath(params.path);
63
+ const diff = runGit(baseline.root, ["diff", "--no-color", "--no-ext-diff", ...(params.stat === true ? ["--stat"] : []), baseline.ref, "--", ...(pathFilter ? [pathFilter] : [])]);
64
+ if (!diff.ok) throw new Error(`git diff failed: ${diff.stderr || "unknown error"}`);
65
+ const untrackedResult = runGit(baseline.root, ["ls-files", "--others", "--exclude-standard", "-z", "--", ...(pathFilter ? [pathFilter] : [])]);
66
+ const untracked = untrackedResult.ok ? untrackedResult.stdout.split("\0").filter(Boolean) : [];
67
+ const sections = [diff.stdout.trimEnd()];
68
+ if (untracked.length) {
69
+ const shown = untracked.slice(0, MAX_UNTRACKED_FILES);
70
+ sections.push(["Untracked files (use read to inspect):", ...shown.map((file) => ` ${file}`)].join("\n"));
71
+ if (untracked.length > shown.length) sections.push(`... ${untracked.length - shown.length} more untracked files`);
72
+ }
73
+ const text = bound(sections.filter(Boolean).join("\n\n")) || `No changes since baseline ${baseline.ref.slice(0, 12)}.`;
74
+ return { content: [{ type: "text", text }], details: { chars: text.length } };
75
+ },
76
+ };
77
+ }
@@ -88,7 +88,8 @@ export class WatchdogEmissionGuard {
88
88
  this.startModelUpdate();
89
89
  }
90
90
 
91
- evaluate(warning: WatchdogWarning): WatchdogEmissionDecision {
91
+ /** `allowRepeatOf`: one already-accepted identity that may repeat (boundary re-findings before stalemate). */
92
+ evaluate(warning: WatchdogWarning, options: { allowRepeatOf?: string } = {}): WatchdogEmissionDecision {
92
93
  if (isContentFree(warning.summary) || isContentFree(warning.evidence) || isContentFree(warning.recommendedAction)) {
93
94
  return { accepted: false, reason: "content-free" };
94
95
  }
@@ -102,8 +103,9 @@ export class WatchdogEmissionGuard {
102
103
  && warning.severity === "blocker";
103
104
  if (!updateEscalation) return { accepted: false, reason: "update-budget", identity, underlyingIdentity };
104
105
  }
105
- if (priorSeverity !== undefined && !escalation) return { accepted: false, reason: "duplicate", identity, underlyingIdentity };
106
- if (this.maxWarnings !== null && this.acceptedCount >= this.maxWarnings && !escalation) {
106
+ const repeat = priorSeverity !== undefined && options.allowRepeatOf === identity;
107
+ if (priorSeverity !== undefined && !escalation && !repeat) return { accepted: false, reason: "duplicate", identity, underlyingIdentity };
108
+ if (this.maxWarnings !== null && this.acceptedCount >= this.maxWarnings && !escalation && !repeat) {
107
109
  return { accepted: false, reason: "max-warnings", identity, underlyingIdentity };
108
110
  }
109
111
 
@@ -0,0 +1,20 @@
1
+ import * as fs from "node:fs";
2
+ import * as path from "node:path";
3
+ import { getAgentDir, getProjectConfigDir } from "../shared/utils.ts";
4
+
5
+ export const WATCHDOG_GUIDANCE_MAX_CHARS = 8_000;
6
+
7
+ function readOptional(filePath: string): string {
8
+ try {
9
+ return fs.readFileSync(filePath, "utf-8").trim();
10
+ } catch {
11
+ return "";
12
+ }
13
+ }
14
+
15
+ /** Read fresh on every review; project file first, then user file. */
16
+ export function loadWatchdogGuidance(cwd: string, enabled: boolean): string {
17
+ if (!enabled) return "";
18
+ const sections = [getProjectConfigDir(cwd), getAgentDir()].map((dir) => readOptional(path.join(dir, "WATCHDOG.md"))).filter(Boolean);
19
+ return sections.join("\n\n").slice(0, WATCHDOG_GUIDANCE_MAX_CHARS);
20
+ }
@@ -3,7 +3,6 @@ import { convertToLlm, type ExtensionContext } from "@earendil-works/pi-coding-a
3
3
  import { streamSimple } from "@earendil-works/pi-ai/compat";
4
4
  import { Type, type Static } from "typebox";
5
5
  import { appendPermissionAudit, permissionArgsPreview } from "../runs/shared/permissions.ts";
6
- import { agentStreamOptions } from "../shared/agent-stream-options.ts";
7
6
  import { decodeChildWatchdogConfig } from "./child-status.ts";
8
7
  import { childResolvedConfig } from "./register-child.ts";
9
8
  import { resolveWatchdogReviewModel } from "./review.ts";
@@ -45,7 +44,11 @@ export function createWatchdogPermissionArbiter(options: WatchdogPermissionArbit
45
44
  const createdAt = Date.now();
46
45
  const auditBase = { type: "permission.request", createdAt, toolName: request.toolName, preview, matchedRule: "ask", decisionSource: "watchdog" };
47
46
  appendPermissionAudit(request.auditPath, auditBase);
47
+ let completed = false;
48
48
  const finish = (approved: boolean, reason: string, decision: string): WatchdogPermissionResult => {
49
+ const concise = conciseReason(reason);
50
+ if (completed) return { approved, reason: concise, source: "watchdog" };
51
+ completed = true;
49
52
  appendPermissionAudit(request.auditPath, {
50
53
  type: "permission.decision",
51
54
  createdAt: Date.now(),
@@ -54,9 +57,9 @@ export function createWatchdogPermissionArbiter(options: WatchdogPermissionArbit
54
57
  decision,
55
58
  approved,
56
59
  decisionSource: "watchdog",
57
- reason: conciseReason(reason),
60
+ reason: concise,
58
61
  });
59
- return { approved, reason: conciseReason(reason), source: "watchdog" };
62
+ return { approved, reason: concise, source: "watchdog" };
60
63
  };
61
64
 
62
65
  let childConfig;
@@ -84,61 +87,65 @@ export function createWatchdogPermissionArbiter(options: WatchdogPermissionArbit
84
87
 
85
88
  let timeout: ReturnType<typeof setTimeout> | undefined;
86
89
  let agent: Agent | undefined;
90
+ let abort: (() => void) | undefined;
87
91
  try {
88
- const config = childResolvedConfig(childConfig);
89
- const selection = await resolveWatchdogReviewModel(request.ctx, config);
90
- const auth = selection.auth;
91
- const registeredProvider = (request.ctx.modelRegistry as {
92
- getRegisteredProviderConfig?: (provider: string) => { api?: string; streamSimple?: StreamFn } | undefined;
93
- }).getRegisteredProviderConfig?.(selection.model.provider);
94
- const baseStreamFn = options.streamFn ?? (registeredProvider?.streamSimple && registeredProvider.api === selection.model.api
95
- ? registeredProvider.streamSimple
96
- : streamSimple);
97
- const streamFn: StreamFn = (model, context, streamOptions) => baseStreamFn(model, context, {
98
- ...streamOptions,
99
- ...(auth.apiKey ? { apiKey: auth.apiKey } : {}),
100
- env: auth.env || streamOptions?.env ? { ...(auth.env ?? {}), ...(streamOptions?.env ?? {}) } : undefined,
101
- headers: { ...(streamOptions?.headers ?? {}), ...(auth.headers ?? {}) },
102
- });
103
- agent = new Agent({
104
- initialState: {
105
- systemPrompt: [
106
- "You are the pi-subagents watchdog permission arbiter.",
107
- "Decide only whether this exact non-bash child tool call should proceed.",
108
- "Call watchdog_permission_decision exactly once with approve or deny and a concise reason.",
109
- "Deny when uncertain. Do not produce freeform advice or ask the parent orchestrator.",
110
- ].join("\n"),
111
- model: selection.model,
112
- thinkingLevel: selection.thinkingLevel,
113
- tools: [tool],
114
- },
115
- convertToLlm,
116
- streamFn: streamFn,
117
- getApiKey: (providerName) => providerName === selection.model.provider ? auth.apiKey : undefined,
118
- beforeToolCall: async ({ toolCall }) => toolCall.name === tool.name ? undefined : { block: true, reason: `Permission arbiter tool '${toolCall.name}' is not allowed.` },
119
- toolExecution: "sequential",
120
- });
121
- const abort = () => agent?.abort();
122
- request.signal?.addEventListener("abort", abort, { once: true });
123
- request.ctx.signal?.addEventListener("abort", abort, { once: true });
124
- try {
125
- const prompt = `Tool: ${request.toolName}\nRedacted arguments: ${preview}`;
126
- await Promise.race([
127
- agent.prompt(prompt),
128
- new Promise<never>((_, reject) => { timeout = setTimeout(() => { agent?.abort(); reject(new Error("Watchdog permission decision timed out.")); }, childConfig.agentEndTimeoutMs); }),
129
- ]);
130
- } finally {
131
- request.signal?.removeEventListener("abort", abort);
132
- request.ctx.signal?.removeEventListener("abort", abort);
133
- }
134
- if (!decision) return finish(false, "Watchdog permission arbiter returned no decision.", "malformed");
135
- const approved = decision.decision === "approve";
136
- return finish(approved, decision.reason, decision.decision);
92
+ const run = async (): Promise<WatchdogPermissionResult> => {
93
+ const config = childResolvedConfig(childConfig);
94
+ const selection = await resolveWatchdogReviewModel(request.ctx, config);
95
+ const auth = selection.auth;
96
+ const registeredProvider = (request.ctx.modelRegistry as {
97
+ getRegisteredProviderConfig?: (provider: string) => { api?: string; streamSimple?: StreamFn } | undefined;
98
+ }).getRegisteredProviderConfig?.(selection.model.provider);
99
+ const baseStreamFn = options.streamFn ?? (registeredProvider?.streamSimple && registeredProvider.api === selection.model.api
100
+ ? registeredProvider.streamSimple
101
+ : streamSimple);
102
+ const streamFn: StreamFn = (model, context, streamOptions) => baseStreamFn(model, context, {
103
+ ...streamOptions,
104
+ ...(auth.apiKey ? { apiKey: auth.apiKey } : {}),
105
+ env: auth.env || streamOptions?.env ? { ...(auth.env ?? {}), ...(streamOptions?.env ?? {}) } : undefined,
106
+ headers: { ...(streamOptions?.headers ?? {}), ...(auth.headers ?? {}) },
107
+ });
108
+ agent = new Agent({
109
+ initialState: {
110
+ systemPrompt: [
111
+ "You are the pi-subagents watchdog permission arbiter.",
112
+ "Decide only whether this exact non-bash child tool call should proceed.",
113
+ "Call watchdog_permission_decision exactly once with approve or deny and a concise reason.",
114
+ "Deny when uncertain. Do not produce freeform advice or ask the parent orchestrator.",
115
+ ].join("\n"),
116
+ model: selection.model,
117
+ thinkingLevel: selection.thinkingLevel,
118
+ tools: [tool],
119
+ },
120
+ convertToLlm,
121
+ streamFn: streamFn,
122
+ getApiKey: (providerName) => providerName === selection.model.provider ? auth.apiKey : undefined,
123
+ beforeToolCall: async ({ toolCall }) => toolCall.name === tool.name ? undefined : { block: true, reason: `Permission arbiter tool '${toolCall.name}' is not allowed.` },
124
+ toolExecution: "sequential",
125
+ });
126
+ await agent.prompt(`Tool: ${request.toolName}\nRedacted arguments: ${preview}`);
127
+ if (!decision) return finish(false, "Watchdog permission arbiter returned no decision.", "malformed");
128
+ const approved = decision.decision === "approve";
129
+ return finish(approved, decision.reason, decision.decision);
130
+ };
131
+ return await Promise.race([
132
+ run(),
133
+ new Promise<WatchdogPermissionResult>((resolve) => { timeout = setTimeout(() => { agent?.abort(); resolve(finish(false, "Watchdog permission decision timed out.", "timeout")); }, childConfig.agentEndTimeoutMs); }),
134
+ new Promise<WatchdogPermissionResult>((resolve) => {
135
+ abort = () => { agent?.abort(); resolve(finish(false, "Watchdog permission decision was cancelled.", "cancelled")); };
136
+ request.signal?.addEventListener("abort", abort, { once: true });
137
+ request.ctx.signal?.addEventListener("abort", abort, { once: true });
138
+ }),
139
+ ]);
137
140
  } catch (error) {
138
141
  const reason = error instanceof Error ? error.message : String(error);
139
142
  return finish(false, `Watchdog permission arbiter failed closed: ${reason}`, reason.includes("timed out") ? "timeout" : "error");
140
143
  } finally {
141
144
  if (timeout) clearTimeout(timeout);
145
+ if (abort) {
146
+ request.signal?.removeEventListener("abort", abort);
147
+ request.ctx.signal?.removeEventListener("abort", abort);
148
+ }
142
149
  }
143
150
  };
144
151
  }
@@ -1,14 +1,14 @@
1
1
  import type { ExtensionAPI, ExtensionContext } from "@earendil-works/pi-coding-agent";
2
+ import { captureWatchdogDiffBaseline, type WatchdogDiffBaseline } from "./diff-tool.ts";
2
3
  import { MainWatchdogRuntime } from "./runtime.ts";
3
4
  import { createMainWatchdogReview } from "./review.ts";
4
5
  import { DEFAULT_WATCHDOG_CONFIG } from "./settings.ts";
5
6
  import { createWatchdogWarningMessage } from "./warning-format.ts";
6
7
  import {
7
- CHILD_WATCHDOG_CONFIG_ENV,
8
8
  CHILD_WATCHDOG_STATUS_EVENT,
9
- decodeChildWatchdogConfig,
10
9
  type ChildWatchdogConfig,
11
10
  type ChildWatchdogPhase,
11
+ type ChildWatchdogStatusEvent,
12
12
  } from "./child-status.ts";
13
13
  import type { ResolvedWatchdogConfig, WatchdogWarningDetails } from "./types.ts";
14
14
 
@@ -23,11 +23,8 @@ export function childResolvedConfig(config: ChildWatchdogConfig): ResolvedWatchd
23
23
  ...(config.model ? { model: config.model } : {}),
24
24
  ...(config.thinking !== undefined ? { thinking: config.thinking } : {}),
25
25
  },
26
- autoFollow: {
27
- blockers: config.autoFollowBlockers,
28
- maxAttempts: config.autoFollowMaxAttempts,
29
- stalemateRepeats: config.stalemateRepeats,
30
- },
26
+ stalemateRepeats: config.stalemateRepeats,
27
+ cadence: { ...config.cadence },
31
28
  children: {
32
29
  ...DEFAULT_WATCHDOG_CONFIG.children,
33
30
  watchdogTailTimeoutMs: config.watchdogTailTimeoutMs,
@@ -45,20 +42,22 @@ function childWarningDetails(details: WatchdogWarningDetails, config: ChildWatch
45
42
  };
46
43
  }
47
44
 
48
- function writeStatus(event: unknown): void {
49
- try {
50
- process.stdout.write(`${JSON.stringify(event)}\n`);
51
- } catch {
52
- // Child watchdog status is advisory; stdout failures are handled by the child process itself.
53
- }
54
- }
55
-
56
- export function registerChildWatchdog(pi: ExtensionAPI, rawConfig = process.env[CHILD_WATCHDOG_CONFIG_ENV]): MainWatchdogRuntime | undefined {
57
- const childConfig = decodeChildWatchdogConfig(rawConfig);
58
- if (!childConfig?.enabled) return undefined;
45
+ /**
46
+ * Register the child-side watchdog. Status events go to the sink the hosting
47
+ * process passed in the child runtime config; the host folds them into the
48
+ * child's event stream.
49
+ */
50
+ export function registerChildWatchdog(
51
+ pi: ExtensionAPI,
52
+ childConfig: ChildWatchdogConfig | undefined,
53
+ writeStatus: ((event: ChildWatchdogStatusEvent) => void) | undefined,
54
+ ): MainWatchdogRuntime | undefined {
55
+ if (!childConfig) return undefined;
56
+ if (!writeStatus) throw new Error("Child watchdog status sink is missing; the host must pass ChildRuntimeConfig.watchdogStatus.");
59
57
  let currentContext: ExtensionContext | undefined;
58
+ let diffBaseline: WatchdogDiffBaseline | undefined;
60
59
  let seq = 0;
61
- const emitStatus = (phase: ChildWatchdogPhase, followUpPending = false, reason?: string): void => {
60
+ const emitStatus = (phase: ChildWatchdogPhase, reason?: string): void => {
62
61
  writeStatus({
63
62
  type: CHILD_WATCHDOG_STATUS_EVENT,
64
63
  ...(childConfig.runId ? { runId: childConfig.runId } : {}),
@@ -67,19 +66,18 @@ export function registerChildWatchdog(pi: ExtensionAPI, rawConfig = process.env[
67
66
  seq: ++seq,
68
67
  phase,
69
68
  ts: Date.now(),
70
- followUpPending,
71
69
  ...(reason ? { reason } : {}),
72
70
  });
73
71
  };
74
72
  const resolved = childResolvedConfig(childConfig);
75
73
  const runtime = new MainWatchdogRuntime({
76
74
  resolveConfig: () => ({ ok: true, config: resolved, errors: [], sources: [{ scope: "session", exists: true }] }),
77
- review: createMainWatchdogReview(() => currentContext, { getThinkingLevel: () => pi.getThinkingLevel() }),
75
+ review: createMainWatchdogReview(() => currentContext, { getThinkingLevel: () => pi.getThinkingLevel(), diffBaseline: () => diffBaseline }),
78
76
  reviewDescription: "child model review",
79
77
  reviewChangesOnly: true,
80
- displayWarning: (details) => {
78
+ displayWarning: (details, options) => {
81
79
  const childDetails = childWarningDetails(details, childConfig);
82
- pi.sendMessage(createWatchdogWarningMessage(childDetails, { display: true, details: childDetails }));
80
+ pi.sendMessage(createWatchdogWarningMessage(childDetails, { display: true, details: childDetails }), options);
83
81
  },
84
82
  });
85
83
  const rememberContext = (ctx: ExtensionContext) => {
@@ -88,6 +86,7 @@ export function registerChildWatchdog(pi: ExtensionAPI, rawConfig = process.env[
88
86
  const onRuntimeEvent = pi.on as unknown as (event: string, handler: (event: unknown, ctx: ExtensionContext) => unknown) => void;
89
87
  onRuntimeEvent("session_start", (_event, ctx) => {
90
88
  rememberContext(ctx);
89
+ diffBaseline = captureWatchdogDiffBaseline(ctx.cwd);
91
90
  runtime.bindSession(ctx);
92
91
  emitStatus("idle");
93
92
  });
@@ -99,13 +98,17 @@ export function registerChildWatchdog(pi: ExtensionAPI, rawConfig = process.env[
99
98
  rememberContext(ctx);
100
99
  runtime.handleTurnEnd(event, ctx);
101
100
  });
101
+ onRuntimeEvent("tool_result", (_event, ctx) => {
102
+ rememberContext(ctx);
103
+ runtime.handleToolResult(ctx);
104
+ });
102
105
  onRuntimeEvent("agent_end", async (event, ctx) => {
103
106
  rememberContext(ctx);
104
107
  emitStatus("reviewing");
105
108
  await runtime.handleAgentEnd(event, ctx);
106
109
  const snapshot = runtime.getSnapshot(ctx.cwd);
107
- if (snapshot.status === "failed") emitStatus("failed", false, snapshot.lastError);
108
- else if (snapshot.status === "stale") emitStatus("stale", false, "review stale");
110
+ if (snapshot.status === "failed") emitStatus("failed", snapshot.lastError);
111
+ else if (snapshot.status === "stale") emitStatus("stale", "review stale");
109
112
  else emitStatus("idle");
110
113
  });
111
114
  onRuntimeEvent("session_shutdown", () => {