@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
@@ -2,6 +2,7 @@ import type { ExtensionAPI, ExtensionCommandContext, ExtensionContext } from "@e
2
2
  import { Text } from "@earendil-works/pi-tui";
3
3
  import { resolveEffectiveThinking, splitKnownThinkingSuffix, THINKING_LEVELS, type ThinkingLevel } from "../shared/model-info.ts";
4
4
  import { SLASH_TEXT_RESULT_TYPE } from "../shared/types.ts";
5
+ import { captureWatchdogDiffBaseline, type WatchdogDiffBaseline } from "./diff-tool.ts";
5
6
  import { recommendStrongWatchdogModel, resolveWatchdogModelInput, parseWatchdogThinkingInput } from "./model-selection.ts";
6
7
  import { renderWatchdogWarning } from "./render.ts";
7
8
  import { createMainWatchdogReview } from "./review.ts";
@@ -120,7 +121,8 @@ export function buildWatchdogStatus(snapshot: ReturnType<MainWatchdogRuntime["ge
120
121
  childrenLine(snapshot),
121
122
  recommendationLine(ctx),
122
123
  `Agent-end timeout: ${snapshot.config.agentEndTimeoutMs}ms`,
123
- `Auto-follow: ${snapshot.enabled && snapshot.config.autoFollow.blockers ? "on for blockers" : "off"} · attempts ${snapshot.autoFollowAttempts}${snapshot.config.autoFollow.maxAttempts === null ? "" : `/${snapshot.config.autoFollow.maxAttempts}`}${snapshot.autoFollowQueued ? " · queued" : ""}${snapshot.autoFollowStalemate ? " · stalemate" : ""}`,
124
+ `Stalemate: ${snapshot.boundaryRepeats}/${snapshot.config.stalemateRepeats}${snapshot.stalemate ? " · stopped" : ""}`,
125
+ `Rules: ${snapshot.config.rules ? `${Object.keys(snapshot.config.rules.roleModels).length} role models · ${snapshot.config.rules.action}` : "none"}`,
124
126
  `Review model call: ${snapshot.reviewDescription}`,
125
127
  ];
126
128
  if (snapshot.failedReviews > 0) lines.push(`Failed reviews: ${snapshot.failedReviews}`);
@@ -238,7 +240,7 @@ function createTestWarning(severity: "concern" | "blocker", text: string): Watch
238
240
  summary: text,
239
241
  evidence: `Manual /subagents-watchdog test ${severity} message from the main session.`,
240
242
  recommendedAction: severity === "blocker"
241
- ? "Verify the renderer, transcript delivery, and auto-follow policy."
243
+ ? "Verify the renderer and transcript delivery."
242
244
  : "Verify the renderer and transcript delivery; decide manually whether any action is needed.",
243
245
  };
244
246
  }
@@ -376,17 +378,15 @@ async function handleWatchdogCommand(
376
378
 
377
379
  export function registerMainWatchdog(pi: ExtensionAPI, options: RegisterMainWatchdogOptions = {}): MainWatchdogRuntime {
378
380
  let currentContext: ExtensionContext | undefined;
381
+ let diffBaseline: WatchdogDiffBaseline | undefined;
379
382
  const rememberContext = (ctx: ExtensionContext) => {
380
383
  currentContext = ctx;
381
384
  };
382
385
  const runtime = options.runtime ?? new MainWatchdogRuntime({
383
- review: options.review ?? createMainWatchdogReview(() => currentContext, { getThinkingLevel: () => pi.getThinkingLevel() }),
386
+ review: options.review ?? createMainWatchdogReview(() => currentContext, { getThinkingLevel: () => pi.getThinkingLevel(), diffBaseline: () => diffBaseline }),
384
387
  reviewDescription: options.review ? "injected seam" : "real model review",
385
388
  reviewChangesOnly: true,
386
- displayWarning: (details, delivery) => {
387
- pi.sendMessage(createWatchdogWarningMessage(details, { display: true, details }), delivery?.deliverAs === "steer" ? { deliverAs: "steer" } : undefined);
388
- },
389
- sendUserMessage: (message) => pi.sendUserMessage(message),
389
+ displayWarning: (details, options) => pi.sendMessage(createWatchdogWarningMessage(details, { display: true, details }), options),
390
390
  });
391
391
 
392
392
  pi.registerMessageRenderer<WatchdogWarningDetails>(SUBAGENT_WATCHDOG_WARNING_TYPE, (message, renderOptions, theme) => {
@@ -410,6 +410,7 @@ export function registerMainWatchdog(pi: ExtensionAPI, options: RegisterMainWatc
410
410
 
411
411
  pi.on("session_start", (_event, ctx) => {
412
412
  rememberContext(ctx);
413
+ diffBaseline = captureWatchdogDiffBaseline(ctx.cwd);
413
414
  runtime.bindSession(ctx);
414
415
  });
415
416
  pi.on("before_agent_start", (event, ctx) => {
@@ -428,8 +429,8 @@ export function registerMainWatchdog(pi: ExtensionAPI, options: RegisterMainWatc
428
429
  rememberContext(ctx);
429
430
  return runtime.handleAgentEnd(event, ctx);
430
431
  });
431
- pi.on("session_before_switch", () => runtime.reset("session switch", { clearReviewInputSignature: true, clearLspLedger: true, clearScope: true, resetAutoFollow: true }));
432
- pi.on("session_before_fork", () => runtime.reset("session fork", { clearReviewInputSignature: true, clearLspLedger: true, clearScope: true, resetAutoFollow: true }));
432
+ pi.on("session_before_switch", () => runtime.reset("session switch", { clearReviewInputSignature: true, clearLspLedger: true, clearScope: true }));
433
+ pi.on("session_before_fork", () => runtime.reset("session fork", { clearReviewInputSignature: true, clearLspLedger: true, clearScope: true }));
433
434
  pi.on("session_compact", () => runtime.reset("session compact", { clearScope: true }));
434
435
  pi.on("session_shutdown", () => {
435
436
  currentContext = undefined;
@@ -13,10 +13,9 @@ function titleCase(value: string): string {
13
13
  function stateLabels(warning: WatchdogWarningDetails): string[] {
14
14
  const labels: string[] = [];
15
15
  if (warning.state === "displayed") labels.push("displayed");
16
- if (warning.stale || warning.state === "stale") labels.push("stale · no auto-follow");
16
+ if (warning.stale || warning.state === "stale") labels.push("stale");
17
17
  if (warning.state === "failed") labels.push("failed review");
18
- if (warning.state === "stalemate") labels.push("stalemate · auto-follow stopped");
19
- if (warning.autoFollowAttempt !== undefined) labels.push(`auto-follow attempt ${warning.autoFollowAttempt}`);
18
+ if (warning.state === "stalemate") labels.push("stalemate");
20
19
  return labels;
21
20
  }
22
21
 
@@ -31,9 +30,9 @@ export function formatWatchdogWarningRenderText(warning: WatchdogWarningDetails)
31
30
  ];
32
31
  if (warning.state === "failed" && warning.error) lines.push(`Failure: ${warning.error}`);
33
32
  if (warning.state === "stalemate" && warning.stalemateRepeats !== undefined) {
34
- lines.push(`Auto-follow stopped after ${warning.stalemateRepeats} repeated blocker warning${warning.stalemateRepeats === 1 ? "" : "s"}.`);
33
+ lines.push(`Same warning ${warning.stalemateRepeats} time${warning.stalemateRepeats === 1 ? "" : "s"} in a row; the watchdog stopped continuing the run.`);
35
34
  }
36
- if (warning.stale || warning.state === "stale") lines.push("This warning arrived after the watchdog catch-up timeout and must not auto-follow.");
35
+ if (warning.stale || warning.state === "stale") lines.push("This warning arrived after the watchdog catch-up timeout.");
37
36
  return lines.join("\n");
38
37
  }
39
38
 
@@ -6,6 +6,8 @@ import { Type, type Static } from "typebox";
6
6
  import { resolveModelCandidate } from "../runs/shared/model-fallback.ts";
7
7
  import { agentStreamOptions } from "../shared/agent-stream-options.ts";
8
8
  import { resolveEffectiveThinking, splitKnownThinkingSuffix, THINKING_LEVELS, toModelInfo } from "../shared/model-info.ts";
9
+ import { createWatchdogDiffTool, WATCHDOG_DIFF_TOOL_NAME, type WatchdogDiffBaseline } from "./diff-tool.ts";
10
+ import { loadWatchdogGuidance } from "./guidance.ts";
9
11
  import type { WatchdogReviewFunction, WatchdogReviewRequest } from "./runtime.ts";
10
12
  import {
11
13
  WATCHDOG_WARNING_CATEGORIES,
@@ -18,7 +20,7 @@ import {
18
20
  type WatchdogWarning,
19
21
  } from "./types.ts";
20
22
 
21
- const WATCHDOG_ALLOWED_TOOL_NAMES = new Set(["read", "grep", "find", "ls", "watchdog_warn"]);
23
+ const WATCHDOG_ALLOWED_TOOL_NAMES = new Set(["read", "grep", "find", "ls", "watchdog_warn", WATCHDOG_DIFF_TOOL_NAME]);
22
24
 
23
25
  const WatchdogWarnParams = Type.Object({
24
26
  severity: Type.String({ enum: WATCHDOG_WARNING_SEVERITIES, description: "concern for actionable risk, blocker for a likely wrong or unsafe outcome" }),
@@ -52,6 +54,7 @@ export interface CreateMainWatchdogReviewOptions {
52
54
  streamFn?: StreamFn;
53
55
  createReadOnlyTools?: (cwd: string) => AgentTool[];
54
56
  getThinkingLevel?: () => ThinkingLevel | undefined;
57
+ diffBaseline?: () => WatchdogDiffBaseline | undefined;
55
58
  }
56
59
 
57
60
  function fullModelId(model: Pick<RegistryModel, "provider" | "id">): string {
@@ -205,18 +208,20 @@ function createWatchdogWarnTool(request: WatchdogReviewRequest): AgentTool<typeo
205
208
  };
206
209
  }
207
210
 
208
- function buildWatchdogSystemPrompt(ctx: ExtensionContext, options: { hasScope?: boolean } = {}): string {
211
+ export function buildWatchdogSystemPrompt(ctx: Pick<ExtensionContext, "cwd">, options: { hasScope?: boolean; guidance?: string; hasDiff?: boolean } = {}): string {
212
+ const guidance = options.guidance?.trim();
209
213
  return [
210
214
  "You are the main-session subagent watchdog for Pi.",
211
215
  `Working directory: ${ctx.cwd}`,
212
216
  "Review only the supplied parent turn delta. Inspect repository files only when needed to verify a concrete concern.",
213
217
  options.hasScope ? "When the review input includes a Current scope block, treat newer scope prompts as superseding/mutating older prompts and use category='scope-drift' for work that serves no current scope item." : undefined,
214
- "You are read-only. You may use read, grep, find, and ls. Do not edit files, run shell commands, spawn agents, or mutate state.",
218
+ `You are read-only. You may use ${options.hasDiff ? "read, grep, find, ls, and watchdog_diff (the full repo diff since the session baseline; pass a path to narrow it)" : "read, grep, find, and ls"}. Do not edit files, run shell commands, spawn agents, or mutate state.`,
215
219
  "Emit warnings only by calling watchdog_warn. Freeform assistant text is ignored and must not be used to report warnings.",
216
220
  "Emit only medium/high confidence actionable concerns or blockers: missed user constraints, correctness risks, test gaps that matter, unsafe changes, stale facts, loop risks, or scope drift.",
217
221
  "Do not emit nits, style preferences, low-confidence guesses, informational notes, praise, or summaries.",
218
222
  "If the turn is clean, call no tools and end normally.",
219
223
  "Use severity='blocker' only when the issue should stop acceptance until addressed; otherwise use severity='concern'.",
224
+ guidance ? `\nStanding instructions from WATCHDOG.md (project first, then user):\n${guidance}` : undefined,
220
225
  ].filter((line): line is string => Boolean(line)).join("\n");
221
226
  }
222
227
 
@@ -269,13 +274,19 @@ export function createMainWatchdogReview(provider: WatchdogContextProvider, opti
269
274
  env: auth.env || streamOptions?.env ? { ...(auth.env ?? {}), ...(streamOptions?.env ?? {}) } : undefined,
270
275
  headers: { ...(streamOptions?.headers ?? {}), ...(auth.headers ?? {}) },
271
276
  });
277
+ const diffBaseline = options.diffBaseline?.();
272
278
  const tools = [
273
279
  ...(options.createReadOnlyTools ?? createReadOnlyTools)(ctx.cwd).filter((tool) => WATCHDOG_ALLOWED_TOOL_NAMES.has(tool.name) && tool.name !== "watchdog_warn"),
274
280
  createWatchdogWarnTool(request),
281
+ ...(diffBaseline ? [createWatchdogDiffTool(diffBaseline)] : []),
275
282
  ];
276
283
  const agent = new Agent({
277
284
  initialState: {
278
- systemPrompt: buildWatchdogSystemPrompt(ctx, { hasScope: request.hasScope }),
285
+ systemPrompt: buildWatchdogSystemPrompt(ctx, {
286
+ hasScope: request.hasScope,
287
+ guidance: loadWatchdogGuidance(ctx.cwd, request.config.guidance.watchdogMd),
288
+ hasDiff: diffBaseline !== undefined,
289
+ }),
279
290
  model: selection.model,
280
291
  thinkingLevel: selection.thinkingLevel,
281
292
  tools,
@@ -0,0 +1,70 @@
1
+ import type { ExtensionAPI } from "@earendil-works/pi-coding-agent";
2
+ import { splitKnownThinkingSuffix } from "../shared/model-info.ts";
3
+ import { resolveWatchdogConfig } from "./settings.ts";
4
+ import type { WatchdogRulesConfig, WatchdogWarning } from "./types.ts";
5
+ import { createWatchdogWarningMessage } from "./warning-format.ts";
6
+
7
+ export interface WatchdogRuleViolation {
8
+ agent: string;
9
+ summary: string;
10
+ evidence: string;
11
+ recommendedAction: string;
12
+ }
13
+
14
+ function loadWatchdogLaunchRules(cwd: string): WatchdogRulesConfig | undefined {
15
+ const result = resolveWatchdogConfig(cwd);
16
+ return result.ok ? result.config.rules : undefined;
17
+ }
18
+
19
+ /** `*` matches any run of characters, `?` one character; anchored, case-sensitive. */
20
+ export function watchdogGlobMatch(pattern: string, value: string): boolean {
21
+ const source = pattern.split("").map((char) => char === "*" ? ".*" : char === "?" ? "." : char.replace(/[.+^${}()|[\]\\]/g, "\\$&")).join("");
22
+ return new RegExp(`^${source}$`).test(value);
23
+ }
24
+
25
+ function modelMatches(patterns: string[], model: string): string | undefined {
26
+ const base = splitKnownThinkingSuffix(model).baseModel;
27
+ return patterns.find((pattern) => watchdogGlobMatch(pattern, model) || watchdogGlobMatch(pattern, base));
28
+ }
29
+
30
+ /** Deny wins over allow; an unknown model cannot be judged. */
31
+ export function evaluateLaunchRule(rules: WatchdogRulesConfig | undefined, agent: string, model: string | undefined): WatchdogRuleViolation | undefined {
32
+ const roleRule = rules?.roleModels[agent];
33
+ if (!roleRule || !model) return undefined;
34
+ const note = roleRule.note ? ` ${roleRule.note}` : "";
35
+ const denied = roleRule.deny?.length ? modelMatches(roleRule.deny, model) : undefined;
36
+ if (denied !== undefined) {
37
+ return {
38
+ agent,
39
+ summary: `Agent '${agent}' was launched with denied model '${model}'.`,
40
+ evidence: `subagents.watchdog.rules.roleModels.${agent}.deny matches '${denied}'.${note}`,
41
+ recommendedAction: roleRule.allow?.length ? `Use one of: ${roleRule.allow.join(", ")}.` : "Choose a different model for this role.",
42
+ };
43
+ }
44
+ if (!roleRule.allow?.length || modelMatches(roleRule.allow, model) !== undefined) return undefined;
45
+ return {
46
+ agent,
47
+ summary: `Agent '${agent}' was launched with model '${model}', which is not in its allowed list.`,
48
+ evidence: `subagents.watchdog.rules.roleModels.${agent}.allow is [${roleRule.allow.join(", ")}].${note}`,
49
+ recommendedAction: `Use one of: ${roleRule.allow.join(", ")}.`,
50
+ };
51
+ }
52
+
53
+ export function ruleViolationWarning(violation: WatchdogRuleViolation): WatchdogWarning {
54
+ return { severity: "concern", category: "missed-constraint", confidence: "high", source: "main", ...violation };
55
+ }
56
+
57
+ export function applyWatchdogLaunchRules(input: { cwd: string; agent: string; model?: string; warn?: (violation: WatchdogRuleViolation) => void }): string | undefined {
58
+ const rules = loadWatchdogLaunchRules(input.cwd);
59
+ const violation = evaluateLaunchRule(rules, input.agent, input.model);
60
+ if (!violation) return undefined;
61
+ if (rules?.action === "block") return `Launch blocked by subagents.watchdog.rules: ${violation.summary}`;
62
+ input.warn?.(violation);
63
+ return undefined;
64
+ }
65
+
66
+ /** For launch paths without a main watchdog runtime (background chain steps). */
67
+ export function sendRuleViolationWarning(pi: Pick<ExtensionAPI, "sendMessage">, violation: WatchdogRuleViolation): void {
68
+ const warning = ruleViolationWarning(violation);
69
+ pi.sendMessage(createWatchdogWarningMessage(warning, { display: true, details: { state: "displayed", displayedAt: new Date().toISOString() } }), { deliverAs: "steer" });
70
+ }
@@ -9,7 +9,8 @@ import {
9
9
  watchdogWarningFromLspDiagnostics,
10
10
  type WatchdogLspDiagnosticsFunction,
11
11
  } from "./lsp-diagnostics.ts";
12
- import { WatchdogScopeArtifact, isWatchdogAutoFollowPromptEvent } from "./scope.ts";
12
+ import { ruleViolationWarning, type WatchdogRuleViolation } from "./rules.ts";
13
+ import { WatchdogScopeArtifact } from "./scope.ts";
13
14
  import { resolveWatchdogConfig } from "./settings.ts";
14
15
  import { formatWatchdogTurnDelta } from "./turn-delta.ts";
15
16
  import {
@@ -62,9 +63,8 @@ export interface WatchdogRuntimeSnapshot {
62
63
  staleReviews: number;
63
64
  reviewConnected: boolean;
64
65
  reviewDescription: string;
65
- autoFollowQueued: boolean;
66
- autoFollowAttempts: number;
67
- autoFollowStalemate: boolean;
66
+ boundaryRepeats: number;
67
+ stalemate: boolean;
68
68
  reviewTrigger: "turn-delta" | "repo-edits";
69
69
  changedPaths?: string[];
70
70
  lsp: WatchdogLspRuntimeSnapshot;
@@ -80,20 +80,29 @@ interface MainWatchdogRuntimeOptions {
80
80
  resolveConfig?: (cwd: string, options?: { session?: Record<string, unknown> }) => WatchdogSettingsResult;
81
81
  review?: WatchdogReviewFunction;
82
82
  reviewDescription?: string;
83
- displayWarning?: (warning: WatchdogWarningDetails, options?: { deliverAs?: "steer" }) => void;
84
- sendUserMessage?: (message: string) => void | Promise<void>;
83
+ displayWarning?: (warning: WatchdogWarningDetails, options?: WatchdogWarningSendOptions) => void;
85
84
  reviewChangesOnly?: boolean;
86
85
  lspDiagnostics?: WatchdogLspDiagnosticsFunction;
87
86
  repoChangeSignature?: typeof computeWatchdogRepoChangeSignature;
88
87
  }
89
88
 
89
+ export type WatchdogWarningSendOptions = { deliverAs: "steer" } | { triggerTurn: false };
90
+
90
91
  type ContextLike = Pick<ExtensionContext, "cwd">;
91
92
  type ReviewDeltaOutcome = "completed" | "timeout" | "stale";
92
93
 
93
94
  const DEFAULT_REVIEW: WatchdogReviewFunction = () => ({ warnings: [] });
94
95
  const MAX_REVIEW_INPUT_CHARS = 24_000;
96
+ const REVIEW_INPUT_HEAD_CHARS = 6_000;
95
97
  const REVIEW_DELTA_SEPARATOR = "\n\n---\n\n";
96
98
 
99
+ export function boundWatchdogReviewText(text: string, cap = MAX_REVIEW_INPUT_CHARS): string {
100
+ if (text.length <= cap) return text;
101
+ const head = Math.min(REVIEW_INPUT_HEAD_CHARS, Math.floor(cap / 4));
102
+ const marker = `\n\n[... about ${text.length - cap} characters omitted ...]\n\n`;
103
+ return `${text.slice(0, head)}${marker}${text.slice(text.length - (cap - head - marker.length))}`;
104
+ }
105
+
97
106
  function errorMessage(error: unknown): string {
98
107
  return error instanceof Error ? error.message : String(error);
99
108
  }
@@ -116,8 +125,7 @@ export class MainWatchdogRuntime {
116
125
  private readonly review: WatchdogReviewFunction;
117
126
  private readonly reviewConnected: boolean;
118
127
  private readonly reviewDescription: string;
119
- private readonly displayWarning: ((warning: WatchdogWarningDetails, options?: { deliverAs?: "steer" }) => void) | undefined;
120
- private readonly sendUserMessage: ((message: string) => void | Promise<void>) | undefined;
128
+ private readonly displayWarning: ((warning: WatchdogWarningDetails, options?: WatchdogWarningSendOptions) => void) | undefined;
121
129
  private readonly reviewChangesOnly: boolean;
122
130
  private readonly lspDiagnostics: WatchdogLspDiagnosticsFunction;
123
131
  private readonly repoChangeSignature: typeof computeWatchdogRepoChangeSignature;
@@ -145,7 +153,6 @@ export class MainWatchdogRuntime {
145
153
  private userPrompt: string | undefined;
146
154
  private waiters: Waiter[] = [];
147
155
  private lastWarning: WatchdogWarningDetails | undefined;
148
- private displayedWarningSequence = 0;
149
156
  private lastError: string | undefined;
150
157
  private lastReviewInputSignature: string | undefined;
151
158
  private turnStartChangeSignature: WatchdogRepoChangeSignature | undefined;
@@ -155,12 +162,10 @@ export class MainWatchdogRuntime {
155
162
  private observedRepoEditThisTurn = false;
156
163
  private toolResultsThisRun = 0;
157
164
  private midRunReviewing = false;
158
- private autoFollowQueued = false;
159
- private autoFollowAttempts = 0;
160
- private consecutiveAutoFollowIdentity: string | undefined;
161
- private consecutiveAutoFollowRepeats = 0;
162
- private autoFollowStalemate = false;
163
- private pendingAutoFollowPrompts: string[] = [];
165
+ private lastBoundaryIdentity: string | undefined;
166
+ private boundaryRepeats = 0;
167
+ private stalemate = false;
168
+ private ruleWarningsThisRun = new Set<string>();
164
169
  private midRunGeneration = 0;
165
170
  private activeReviewAbortController: AbortController | undefined;
166
171
  private failedReviews = 0;
@@ -173,7 +178,6 @@ export class MainWatchdogRuntime {
173
178
  this.reviewConnected = Boolean(options.review);
174
179
  this.reviewDescription = options.reviewDescription ?? (options.review ? "injected seam" : "not wired");
175
180
  this.displayWarning = options.displayWarning;
176
- this.sendUserMessage = options.sendUserMessage;
177
181
  this.reviewChangesOnly = options.reviewChangesOnly === true;
178
182
  this.lspDiagnostics = options.lspDiagnostics ?? collectWatchdogLspDiagnostics;
179
183
  this.repoChangeSignature = options.repoChangeSignature ?? computeWatchdogRepoChangeSignature;
@@ -189,7 +193,8 @@ export class MainWatchdogRuntime {
189
193
  this.sessionOverrideEnabled = undefined;
190
194
  this.sessionModelOverride = undefined;
191
195
  this.refreshConfig(ctx.cwd);
192
- this.reset("session_start", { clearReviewInputSignature: true, resetChangeSignature: true, clearLspLedger: true, clearScope: true, resetAutoFollow: true });
196
+ this.reset("session_start", { clearReviewInputSignature: true, resetChangeSignature: true, clearLspLedger: true, clearScope: true });
197
+ this.resetBoundaryRepeats();
193
198
  }
194
199
 
195
200
  refreshConfig(cwd = this.cwd): WatchdogSettingsResult {
@@ -247,7 +252,7 @@ export class MainWatchdogRuntime {
247
252
  return this.getSnapshot();
248
253
  }
249
254
 
250
- reset(_reason = "reset", options: { clearReviewInputSignature?: boolean; resetChangeSignature?: boolean; clearLspLedger?: boolean; clearScope?: boolean; resetAutoFollow?: boolean } = {}): void {
255
+ reset(_reason = "reset", options: { clearReviewInputSignature?: boolean; resetChangeSignature?: boolean; clearLspLedger?: boolean; clearScope?: boolean } = {}): void {
251
256
  this.abortActiveAgentEnd();
252
257
  this.epoch++;
253
258
  this.status = "idle";
@@ -263,16 +268,12 @@ export class MainWatchdogRuntime {
263
268
  this.observedRepoEditThisTurn = false;
264
269
  this.toolResultsThisRun = 0;
265
270
  this.midRunReviewing = false;
266
- this.autoFollowQueued = false;
271
+ this.ruleWarningsThisRun.clear();
267
272
  if (options.clearLspLedger) {
268
273
  this.lspLedger.reset();
269
274
  this.lastLspSnapshot = undefined;
270
275
  }
271
- if (options.clearScope) {
272
- this.scope.reset();
273
- this.pendingAutoFollowPrompts = [];
274
- }
275
- if (options.resetAutoFollow) this.resetAutoFollowState();
276
+ if (options.clearScope) this.scope.reset();
276
277
  if (options.clearReviewInputSignature) this.lastReviewInputSignature = undefined;
277
278
  if (options.resetChangeSignature) this.resetRepoChangeBaseline({ reviewed: true });
278
279
  this.guard.reset();
@@ -297,22 +298,17 @@ export class MainWatchdogRuntime {
297
298
  this.observedRepoEditThisTurn = false;
298
299
  this.toolResultsThisRun = 0;
299
300
  this.midRunReviewing = false;
300
- this.autoFollowQueued = false;
301
301
  this.resolveWaiters(false);
302
302
  }
303
303
 
304
304
  handleBeforeAgentStart(event: unknown, ctx: ContextLike): void {
305
305
  if (this.disposed) return;
306
306
  const incomingPrompt = promptFromBeforeAgentStart(event);
307
- // Only exact queued auto-follow text is treated as an auto-follow turn; a real user
308
- // prompt racing in ahead of one stays real and the pending matches survive for later.
309
- const pendingIndex = incomingPrompt === undefined ? -1 : this.pendingAutoFollowPrompts.indexOf(incomingPrompt);
310
- const autoFollowPrompt = pendingIndex >= 0 || isWatchdogAutoFollowPromptEvent(event);
311
- if (pendingIndex >= 0) this.pendingAutoFollowPrompts.splice(pendingIndex, 1);
312
- this.reset("before_agent_start", { resetAutoFollow: !autoFollowPrompt });
307
+ this.reset("before_agent_start");
308
+ this.resetBoundaryRepeats();
313
309
  this.refreshConfig(ctx.cwd);
314
310
  this.userPrompt = incomingPrompt;
315
- if (!autoFollowPrompt && this.userPrompt?.trim()) {
311
+ if (this.userPrompt?.trim()) {
316
312
  this.includeUserPromptInNextDelta = true;
317
313
  this.scope.addPrompt(this.userPrompt);
318
314
  } else {
@@ -383,8 +379,6 @@ export class MainWatchdogRuntime {
383
379
  const lspAbortController = new AbortController();
384
380
  this.activeAgentEndId = agentEndId;
385
381
  this.activeAgentEndAbortController = lspAbortController;
386
- let displayedDuringAgentEnd: WatchdogWarningDetails | undefined;
387
- const previousDisplayedSequence = this.displayedWarningSequence;
388
382
  try {
389
383
  this.guard.startModelUpdate();
390
384
  const lspBlock = await this.collectLspDiagnostics(changeSignature, {
@@ -425,8 +419,6 @@ export class MainWatchdogRuntime {
425
419
  this.currentChangedPaths = changeSignature?.changedPaths;
426
420
  this.status = "idle";
427
421
  }
428
- displayedDuringAgentEnd = this.displayedWarningSequence !== previousDisplayedSequence ? this.lastWarning : undefined;
429
- this.queueAutoFollowIfNeeded(displayedDuringAgentEnd);
430
422
  this.resolveWaiters(true);
431
423
  } finally {
432
424
  if (this.activeAgentEndAbortController === lspAbortController) this.activeAgentEndAbortController = undefined;
@@ -434,6 +426,14 @@ export class MainWatchdogRuntime {
434
426
  }
435
427
  }
436
428
 
429
+ displayRuleWarning(violation: WatchdogRuleViolation): void {
430
+ if (this.disposed || this.ruleWarningsThisRun.has(violation.summary)) return;
431
+ this.ruleWarningsThisRun.add(violation.summary);
432
+ const details = normalizeWatchdogWarningDetails(ruleViolationWarning(violation), { state: "displayed", displayedAt: new Date().toISOString() });
433
+ this.lastWarning = details;
434
+ this.displayWarning?.(details, { deliverAs: "steer" });
435
+ }
436
+
437
437
  recordDisplayedWarning(warning: WatchdogWarning): WatchdogWarningDetails {
438
438
  const details = normalizeWatchdogWarningDetails(warning, { state: "displayed", source: warning.source ?? "main" });
439
439
  this.lastWarning = details;
@@ -460,9 +460,8 @@ export class MainWatchdogRuntime {
460
460
  staleReviews: this.staleReviews,
461
461
  reviewConnected: this.reviewConnected,
462
462
  reviewDescription: this.reviewDescription,
463
- autoFollowQueued: this.autoFollowQueued,
464
- autoFollowAttempts: this.autoFollowAttempts,
465
- autoFollowStalemate: this.autoFollowStalemate,
463
+ boundaryRepeats: this.boundaryRepeats,
464
+ stalemate: this.stalemate,
466
465
  reviewTrigger: this.reviewChangesOnly ? "repo-edits" : "turn-delta",
467
466
  ...(this.currentChangedPaths?.length ? { changedPaths: [...this.currentChangedPaths] } : {}),
468
467
  lsp: this.lspSnapshot(),
@@ -497,7 +496,7 @@ export class MainWatchdogRuntime {
497
496
 
498
497
  private acceptWarning(epoch: number, reviewId: number, warning: WatchdogWarning): boolean {
499
498
  if (!this.isCurrent(epoch, reviewId) || !this.isEnabled() || !this.warningMeetsThreshold(warning)) return false;
500
- const decision = this.guard.evaluate(warning);
499
+ const decision = this.guard.evaluate(warning, { allowRepeatOf: this.repeatableBoundaryIdentity() });
501
500
  if (!decision.accepted) return false;
502
501
  const details = normalizeWatchdogWarningDetails(warning, {
503
502
  state: "candidate",
@@ -511,7 +510,7 @@ export class MainWatchdogRuntime {
511
510
 
512
511
  private displayBoundaryWarning(warning: WatchdogWarning): boolean {
513
512
  if (!this.isEnabled() || !this.warningMeetsThreshold(warning)) return false;
514
- const decision = this.guard.evaluate(warning);
513
+ const decision = this.guard.evaluate(warning, { allowRepeatOf: this.repeatableBoundaryIdentity() });
515
514
  if (!decision.accepted) return false;
516
515
  const details = normalizeWatchdogWarningDetails(warning, {
517
516
  state: "displayed",
@@ -519,9 +518,7 @@ export class MainWatchdogRuntime {
519
518
  identity: decision.identity,
520
519
  displayedAt: new Date().toISOString(),
521
520
  });
522
- this.lastWarning = details;
523
- this.displayedWarningSequence++;
524
- this.displayWarning?.(details);
521
+ this.deliverBoundaryWarning(details);
525
522
  return true;
526
523
  }
527
524
 
@@ -635,51 +632,41 @@ export class MainWatchdogRuntime {
635
632
  state: "displayed",
636
633
  displayedAt: new Date().toISOString(),
637
634
  };
638
- this.lastWarning = details;
639
- this.displayedWarningSequence++;
640
- this.displayWarning?.(details, correction ? { deliverAs: "steer" } : undefined);
641
- }
642
-
643
- private resetAutoFollowState(): void {
644
- this.autoFollowQueued = false;
645
- this.autoFollowAttempts = 0;
646
- this.consecutiveAutoFollowIdentity = undefined;
647
- this.consecutiveAutoFollowRepeats = 0;
648
- this.autoFollowStalemate = false;
635
+ if (correction) {
636
+ this.lastWarning = details;
637
+ this.displayWarning?.(details, { deliverAs: "steer" });
638
+ return;
639
+ }
640
+ this.deliverBoundaryWarning(details);
649
641
  }
650
642
 
651
- private queueAutoFollowIfNeeded(warning: WatchdogWarningDetails | undefined): void {
652
- if (!warning || warning.severity !== "blocker" || warning.stale || !this.configResult.config.autoFollow.blockers || !this.isEnabled()) return;
653
- const identity = warning.identity ?? reviewInputSignature([warning.severity, warning.summary, warning.evidence].join("\n"));
654
- if (this.consecutiveAutoFollowIdentity === identity) this.consecutiveAutoFollowRepeats++;
643
+ // A displayed boundary warning continues the run; the same identity back from consecutive
644
+ // boundaries means no progress, so it is shown held instead of continuing again.
645
+ private deliverBoundaryWarning(details: WatchdogWarningDetails): void {
646
+ const identity = details.identity ?? reviewInputSignature([details.severity, details.summary, details.evidence].join("\n"));
647
+ if (this.lastBoundaryIdentity === identity) this.boundaryRepeats++;
655
648
  else {
656
- this.consecutiveAutoFollowIdentity = identity;
657
- this.consecutiveAutoFollowRepeats = 1;
658
- }
659
- if (this.consecutiveAutoFollowRepeats >= this.configResult.config.autoFollow.stalemateRepeats) {
660
- this.autoFollowStalemate = true;
661
- this.lastWarning = { ...warning, state: "stalemate", stalemateRepeats: this.consecutiveAutoFollowRepeats };
662
- return;
649
+ this.lastBoundaryIdentity = identity;
650
+ this.boundaryRepeats = 1;
663
651
  }
664
- const maxAttempts = this.configResult.config.autoFollow.maxAttempts;
665
- if (maxAttempts !== null && this.autoFollowAttempts >= maxAttempts) return;
666
- if (!this.sendUserMessage) return;
667
- this.autoFollowAttempts++;
668
- this.autoFollowQueued = true;
669
- const prompt = [
670
- "Watchdog auto-follow: address this blocker before continuing.",
671
- `Summary: ${warning.summary}`,
672
- `Evidence: ${warning.evidence}`,
673
- `Recommended action: ${warning.recommendedAction}`,
674
- ].join("\n");
675
- this.pendingAutoFollowPrompts.push(prompt);
676
- if (this.pendingAutoFollowPrompts.length > 8) this.pendingAutoFollowPrompts.shift();
677
- void Promise.resolve(this.sendUserMessage(prompt)).catch((error) => {
678
- this.autoFollowQueued = false;
679
- const index = this.pendingAutoFollowPrompts.indexOf(prompt);
680
- if (index >= 0) this.pendingAutoFollowPrompts.splice(index, 1);
681
- this.lastError = `Watchdog auto-follow failed: ${errorMessage(error)}`;
682
- });
652
+ const stalemate = this.boundaryRepeats >= this.configResult.config.stalemateRepeats;
653
+ const delivered: WatchdogWarningDetails = stalemate
654
+ ? { ...details, state: "stalemate", stalemateRepeats: this.boundaryRepeats }
655
+ : details;
656
+ this.stalemate = stalemate;
657
+ this.lastWarning = delivered;
658
+ this.displayWarning?.(delivered, stalemate ? { triggerTurn: false } : undefined);
659
+ }
660
+
661
+ // The previous boundary finding is a repeat to count, not a duplicate, until stalemate.
662
+ private repeatableBoundaryIdentity(): string | undefined {
663
+ return this.waitingAtAgentEnd && !this.stalemate ? this.lastBoundaryIdentity : undefined;
664
+ }
665
+
666
+ private resetBoundaryRepeats(): void {
667
+ this.lastBoundaryIdentity = undefined;
668
+ this.boundaryRepeats = 0;
669
+ this.stalemate = false;
683
670
  }
684
671
 
685
672
  private currentRepoChangeSignature(cwd = this.cwd): WatchdogRepoChangeSignature | undefined {
@@ -783,7 +770,7 @@ export class MainWatchdogRuntime {
783
770
  private appendBoundedDelta(delta: string): void {
784
771
  let entry = delta.trim();
785
772
  if (!entry) return;
786
- if (entry.length > MAX_REVIEW_INPUT_CHARS) entry = entry.slice(-MAX_REVIEW_INPUT_CHARS);
773
+ if (entry.length > MAX_REVIEW_INPUT_CHARS) entry = boundWatchdogReviewText(entry);
787
774
  this.pendingDeltas.push(entry);
788
775
  this.pendingDeltaChars += entry.length;
789
776
  while (this.pendingDeltas.length > 1 && this.pendingDeltaChars + (this.pendingDeltas.length - 1) * REVIEW_DELTA_SEPARATOR.length > MAX_REVIEW_INPUT_CHARS) {
@@ -799,7 +786,7 @@ export class MainWatchdogRuntime {
799
786
  ? ["Changed repo paths:", ...changeSignature.changedPaths.slice(0, 200).map((file) => `- ${file}`)].join("\n")
800
787
  : "";
801
788
  const contextPieces = [scopeBlock, changes, lspBlock].filter(Boolean);
802
- if (!contextPieces.length) return input.length > MAX_REVIEW_INPUT_CHARS ? input.slice(-MAX_REVIEW_INPUT_CHARS) : input;
789
+ if (!contextPieces.length) return boundWatchdogReviewText(input);
803
790
 
804
791
  const maxContextLength = Math.floor(MAX_REVIEW_INPUT_CHARS / 2);
805
792
  const maxPieceLength = Math.max(1_000, Math.floor(maxContextLength / contextPieces.length));
@@ -808,11 +795,7 @@ export class MainWatchdogRuntime {
808
795
  : piece).join(REVIEW_DELTA_SEPARATOR);
809
796
  const separatorLength = input ? REVIEW_DELTA_SEPARATOR.length : 0;
810
797
  const inputBudget = MAX_REVIEW_INPUT_CHARS - boundedContext.length - separatorLength;
811
- const boundedInput = inputBudget <= 0
812
- ? ""
813
- : input.length > inputBudget
814
- ? input.slice(-inputBudget)
815
- : input;
798
+ const boundedInput = inputBudget <= 0 ? "" : boundWatchdogReviewText(input, inputBudget);
816
799
  return [boundedContext, boundedInput].filter(Boolean).join(REVIEW_DELTA_SEPARATOR);
817
800
  }
818
801
 
@@ -1,5 +1,3 @@
1
- export const WATCHDOG_AUTO_FOLLOW_PROMPT_MARKER = Symbol("subagent-watchdog-auto-follow-prompt");
2
-
3
1
  const MAX_SCOPE_ENTRIES = 8;
4
2
  const MAX_SCOPE_ENTRY_CHARS = 2_000;
5
3
  const MAX_SCOPE_TOTAL_CHARS = 16_000;
@@ -51,12 +49,3 @@ export class WatchdogScopeArtifact {
51
49
  }
52
50
  }
53
51
  }
54
-
55
- export function isWatchdogAutoFollowPromptEvent(event: unknown): boolean {
56
- return Boolean(event && typeof event === "object" && (event as { [WATCHDOG_AUTO_FOLLOW_PROMPT_MARKER]?: unknown })[WATCHDOG_AUTO_FOLLOW_PROMPT_MARKER]);
57
- }
58
-
59
- export function markWatchdogAutoFollowPromptEvent<T extends object>(event: T): T {
60
- Object.defineProperty(event, WATCHDOG_AUTO_FOLLOW_PROMPT_MARKER, { value: true });
61
- return event;
62
- }