@xzzpig/pi-subagents 0.1.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 (196) hide show
  1. package/CHANGELOG.md +1621 -0
  2. package/LICENSE +21 -0
  3. package/README.md +118 -0
  4. package/agents/delegate.md +14 -0
  5. package/agents/oracle.md +74 -0
  6. package/agents/researcher.md +52 -0
  7. package/agents/reviewer.md +79 -0
  8. package/agents/scout.md +50 -0
  9. package/agents/worker.md +58 -0
  10. package/index.ts +1 -0
  11. package/inspector-runner.mjs +11 -0
  12. package/install.mjs +93 -0
  13. package/package.json +105 -0
  14. package/prompts/gather-context-and-clarify.md +13 -0
  15. package/prompts/parallel-cleanup.md +59 -0
  16. package/prompts/parallel-research.md +50 -0
  17. package/prompts/parallel-review.md +54 -0
  18. package/prompts/review-loop.md +43 -0
  19. package/skills/pi-subagents/SKILL.md +41 -0
  20. package/skills/pi-subagents/references/constraints-and-recipes.md +251 -0
  21. package/skills/pi-subagents/references/execution-controls.md +428 -0
  22. package/skills/pi-subagents/references/management-authoring-rpc.md +161 -0
  23. package/skills/pi-subagents/references/prompting-and-roles.md +242 -0
  24. package/src/agents/agent-management.ts +1256 -0
  25. package/src/agents/agent-memory.ts +254 -0
  26. package/src/agents/agent-refinements.ts +624 -0
  27. package/src/agents/agent-scope.ts +6 -0
  28. package/src/agents/agent-selection.ts +25 -0
  29. package/src/agents/agent-serializer.ts +163 -0
  30. package/src/agents/agents.ts +1889 -0
  31. package/src/agents/chain-serializer.ts +280 -0
  32. package/src/agents/frontmatter.ts +149 -0
  33. package/src/agents/identity.ts +30 -0
  34. package/src/agents/proactive-skills.ts +194 -0
  35. package/src/agents/skills.ts +761 -0
  36. package/src/api/background-work.ts +197 -0
  37. package/src/api/capability-ceiling.ts +17 -0
  38. package/src/api/control-channel.ts +4 -0
  39. package/src/api/delegation.ts +119 -0
  40. package/src/api/external-runs.ts +129 -0
  41. package/src/api/intercom-bridge.ts +3 -0
  42. package/src/api/pi-args.ts +5 -0
  43. package/src/api/preflight.ts +403 -0
  44. package/src/api/shared-types.ts +19 -0
  45. package/src/extension/config.ts +76 -0
  46. package/src/extension/control-notices.ts +58 -0
  47. package/src/extension/doctor.ts +230 -0
  48. package/src/extension/fanout-child.ts +201 -0
  49. package/src/extension/index.ts +805 -0
  50. package/src/extension/public-execution.ts +71 -0
  51. package/src/extension/rpc.ts +653 -0
  52. package/src/extension/schemas.ts +375 -0
  53. package/src/extension/steering-notices.ts +35 -0
  54. package/src/extension/tool-description.ts +164 -0
  55. package/src/inspectors/herdr/actions.ts +229 -0
  56. package/src/inspectors/herdr/client.ts +130 -0
  57. package/src/inspectors/herdr/inspector-runner.ts +141 -0
  58. package/src/inspectors/herdr/project-panes.ts +154 -0
  59. package/src/integrations/herdr-status.ts +330 -0
  60. package/src/intercom/intercom-bridge.ts +187 -0
  61. package/src/intercom/native-supervisor-channel.ts +715 -0
  62. package/src/intercom/result-intercom.ts +421 -0
  63. package/src/missions/actions.ts +410 -0
  64. package/src/missions/goal-driver.ts +162 -0
  65. package/src/missions/lifecycle.ts +346 -0
  66. package/src/missions/store.ts +507 -0
  67. package/src/missions/types.ts +157 -0
  68. package/src/missions/workflow-state.ts +250 -0
  69. package/src/policy/authority.ts +46 -0
  70. package/src/profiles/profiles.ts +661 -0
  71. package/src/runs/background/async-execution.ts +1574 -0
  72. package/src/runs/background/async-job-tracker.ts +511 -0
  73. package/src/runs/background/async-resume.ts +539 -0
  74. package/src/runs/background/async-status.ts +542 -0
  75. package/src/runs/background/auto-drain.ts +67 -0
  76. package/src/runs/background/chain-append.ts +328 -0
  77. package/src/runs/background/chain-root-attachment.ts +199 -0
  78. package/src/runs/background/completion-batcher.ts +168 -0
  79. package/src/runs/background/completion-dedupe.ts +54 -0
  80. package/src/runs/background/control-channel.ts +692 -0
  81. package/src/runs/background/fleet-view.ts +540 -0
  82. package/src/runs/background/notify.ts +332 -0
  83. package/src/runs/background/parallel-groups.ts +45 -0
  84. package/src/runs/background/process-terminal.ts +280 -0
  85. package/src/runs/background/result-watcher.ts +414 -0
  86. package/src/runs/background/retained-children.ts +68 -0
  87. package/src/runs/background/run-id-resolver.ts +167 -0
  88. package/src/runs/background/run-status.ts +504 -0
  89. package/src/runs/background/scheduled-runs.ts +753 -0
  90. package/src/runs/background/stale-run-reconciler.ts +396 -0
  91. package/src/runs/background/steering.ts +239 -0
  92. package/src/runs/background/subagent-runner.ts +4718 -0
  93. package/src/runs/background/subagent-wait.ts +661 -0
  94. package/src/runs/background/top-level-async.ts +14 -0
  95. package/src/runs/background/wait-completions.ts +112 -0
  96. package/src/runs/background/wait-config.ts +36 -0
  97. package/src/runs/background/wait-subscriptions.ts +253 -0
  98. package/src/runs/background/wait-tool.ts +34 -0
  99. package/src/runs/foreground/async-steering-action.ts +256 -0
  100. package/src/runs/foreground/async-stop-action.ts +65 -0
  101. package/src/runs/foreground/chain-clarify.ts +1354 -0
  102. package/src/runs/foreground/chain-execution.ts +1527 -0
  103. package/src/runs/foreground/execution.ts +1868 -0
  104. package/src/runs/foreground/foreground-control.ts +132 -0
  105. package/src/runs/foreground/subagent-executor.ts +5532 -0
  106. package/src/runs/shared/acceptance.ts +1365 -0
  107. package/src/runs/shared/agent-contract.ts +38 -0
  108. package/src/runs/shared/capability-ceiling.ts +209 -0
  109. package/src/runs/shared/chain-outputs.ts +118 -0
  110. package/src/runs/shared/child-protocol.ts +401 -0
  111. package/src/runs/shared/completion-guard.ts +95 -0
  112. package/src/runs/shared/context-mode.ts +44 -0
  113. package/src/runs/shared/dynamic-fanout.ts +297 -0
  114. package/src/runs/shared/external-cli-runner.ts +130 -0
  115. package/src/runs/shared/long-running-guard.ts +220 -0
  116. package/src/runs/shared/mcp-direct-tool-allowlist.ts +406 -0
  117. package/src/runs/shared/model-fallback.ts +336 -0
  118. package/src/runs/shared/model-scope.ts +128 -0
  119. package/src/runs/shared/nested-events.ts +1076 -0
  120. package/src/runs/shared/nested-path.ts +52 -0
  121. package/src/runs/shared/nested-render.ts +123 -0
  122. package/src/runs/shared/parallel-handoff.ts +238 -0
  123. package/src/runs/shared/parallel-utils.ts +256 -0
  124. package/src/runs/shared/permissions.ts +95 -0
  125. package/src/runs/shared/pi-args.ts +808 -0
  126. package/src/runs/shared/pi-spawn.ts +163 -0
  127. package/src/runs/shared/process-signal.ts +19 -0
  128. package/src/runs/shared/run-history.ts +181 -0
  129. package/src/runs/shared/runtime-acknowledged-extensions.ts +71 -0
  130. package/src/runs/shared/session-lease.ts +299 -0
  131. package/src/runs/shared/single-output.ts +235 -0
  132. package/src/runs/shared/spawn-budget.ts +128 -0
  133. package/src/runs/shared/structured-output.ts +182 -0
  134. package/src/runs/shared/subagent-control.ts +231 -0
  135. package/src/runs/shared/subagent-prompt-runtime.ts +588 -0
  136. package/src/runs/shared/subagent-startup-retry.ts +104 -0
  137. package/src/runs/shared/task-intent.ts +181 -0
  138. package/src/runs/shared/tool-availability.ts +83 -0
  139. package/src/runs/shared/tool-budget.ts +80 -0
  140. package/src/runs/shared/turn-budget.ts +98 -0
  141. package/src/runs/shared/usage-budget.ts +65 -0
  142. package/src/runs/shared/workflow-graph.ts +231 -0
  143. package/src/runs/shared/worktree.ts +759 -0
  144. package/src/shared/accessible-dir.ts +47 -0
  145. package/src/shared/artifacts.ts +285 -0
  146. package/src/shared/atomic-json.ts +61 -0
  147. package/src/shared/child-transcript.ts +264 -0
  148. package/src/shared/file-coalescer.ts +40 -0
  149. package/src/shared/file-system-retry.ts +47 -0
  150. package/src/shared/fork-context.ts +213 -0
  151. package/src/shared/formatters.ts +133 -0
  152. package/src/shared/jsonl-writer.ts +81 -0
  153. package/src/shared/launch-contract.ts +124 -0
  154. package/src/shared/model-info.ts +81 -0
  155. package/src/shared/post-exit-stdio-guard.ts +85 -0
  156. package/src/shared/session-identity.ts +10 -0
  157. package/src/shared/session-tokens.ts +44 -0
  158. package/src/shared/settings.ts +501 -0
  159. package/src/shared/status-format.ts +55 -0
  160. package/src/shared/types.ts +2069 -0
  161. package/src/shared/utils.ts +613 -0
  162. package/src/slash/delegation-adapters.ts +434 -0
  163. package/src/slash/delegation-json.ts +108 -0
  164. package/src/slash/delegation-request.ts +166 -0
  165. package/src/slash/prompt-template-bridge.ts +383 -0
  166. package/src/slash/prompt-workflows.ts +300 -0
  167. package/src/slash/selector.ts +147 -0
  168. package/src/slash/slash-bridge.ts +192 -0
  169. package/src/slash/slash-commands.ts +994 -0
  170. package/src/slash/slash-live-state.ts +296 -0
  171. package/src/slash/subagents-admin.ts +432 -0
  172. package/src/tui/fleet-status.ts +564 -0
  173. package/src/tui/fleet-transcript.ts +577 -0
  174. package/src/tui/fleet.ts +879 -0
  175. package/src/tui/render-helpers.ts +80 -0
  176. package/src/tui/render.ts +2029 -0
  177. package/src/types/pi-runtime-compat.d.ts +8 -0
  178. package/src/watchdog/change-signature.ts +220 -0
  179. package/src/watchdog/child-status.ts +205 -0
  180. package/src/watchdog/emission-guard.ts +123 -0
  181. package/src/watchdog/lsp-diagnostics.ts +537 -0
  182. package/src/watchdog/model-selection.ts +167 -0
  183. package/src/watchdog/permission-arbiter.ts +145 -0
  184. package/src/watchdog/register-child.ts +117 -0
  185. package/src/watchdog/register-main.ts +440 -0
  186. package/src/watchdog/render.ts +54 -0
  187. package/src/watchdog/review.ts +302 -0
  188. package/src/watchdog/runtime.ts +868 -0
  189. package/src/watchdog/scope.ts +62 -0
  190. package/src/watchdog/settings.ts +568 -0
  191. package/src/watchdog/tool-actions.ts +155 -0
  192. package/src/watchdog/turn-delta.ts +161 -0
  193. package/src/watchdog/types.ts +198 -0
  194. package/src/watchdog/warning-format.ts +73 -0
  195. package/src/workflows/chat-progress.ts +140 -0
  196. package/src/workflows/scripted-workflow.ts +506 -0
@@ -0,0 +1,868 @@
1
+ import { createHash } from "node:crypto";
2
+ import type { ExtensionContext } from "@earendil-works/pi-coding-agent";
3
+ import { computeWatchdogRepoChangeSignature, eventIndicatesRepoEdit, type WatchdogRepoChangeSignature } from "./change-signature.ts";
4
+ import { WatchdogEmissionGuard } from "./emission-guard.ts";
5
+ import {
6
+ collectWatchdogLspDiagnostics,
7
+ formatWatchdogLspDiagnosticsBlock,
8
+ WatchdogLspDiagnosticsLedger,
9
+ watchdogWarningFromLspDiagnostics,
10
+ type WatchdogLspDiagnosticsFunction,
11
+ } from "./lsp-diagnostics.ts";
12
+ import { WatchdogScopeArtifact, isWatchdogAutoFollowPromptEvent } from "./scope.ts";
13
+ import { resolveWatchdogConfig } from "./settings.ts";
14
+ import { formatWatchdogTurnDelta } from "./turn-delta.ts";
15
+ import {
16
+ type ResolvedWatchdogConfig,
17
+ type WatchdogEndpointConfig,
18
+ type WatchdogLspRuntimeSnapshot,
19
+ type WatchdogRuntimeStatus,
20
+ type WatchdogSettingsError,
21
+ type WatchdogSettingsResult,
22
+ type WatchdogSettingsSource,
23
+ type WatchdogWarning,
24
+ type WatchdogWarningDetails,
25
+ } from "./types.ts";
26
+ import { normalizeWatchdogWarningDetails } from "./warning-format.ts";
27
+
28
+ type ReviewStopReason = "stop" | "error" | "aborted" | "length";
29
+
30
+ export interface WatchdogReviewResult {
31
+ warnings?: WatchdogWarning[];
32
+ stopReason?: ReviewStopReason;
33
+ }
34
+
35
+ export interface WatchdogReviewRequest {
36
+ delta: string;
37
+ epoch: number;
38
+ hasScope: boolean;
39
+ reviewId: number;
40
+ config: ResolvedWatchdogConfig;
41
+ emitWarning(warning: WatchdogWarning): boolean;
42
+ signal?: AbortSignal;
43
+ }
44
+
45
+ export type WatchdogReviewFunction = (request: WatchdogReviewRequest) => Promise<WatchdogReviewResult | void> | WatchdogReviewResult | void;
46
+
47
+ export interface WatchdogRuntimeSnapshot {
48
+ status: WatchdogRuntimeStatus;
49
+ enabled: boolean;
50
+ config: ResolvedWatchdogConfig;
51
+ configOk: boolean;
52
+ errors: WatchdogSettingsError[];
53
+ sources: WatchdogSettingsSource[];
54
+ bufferedDeltas: number;
55
+ epoch: number;
56
+ activeReviewId?: number;
57
+ sessionOverride?: boolean;
58
+ sessionModelOverride?: Partial<Pick<WatchdogEndpointConfig, "model" | "thinking">>;
59
+ lastWarning?: WatchdogWarningDetails;
60
+ lastError?: string;
61
+ failedReviews: number;
62
+ staleReviews: number;
63
+ reviewConnected: boolean;
64
+ reviewDescription: string;
65
+ autoFollowQueued: boolean;
66
+ autoFollowAttempts: number;
67
+ autoFollowStalemate: boolean;
68
+ reviewTrigger: "turn-delta" | "repo-edits";
69
+ changedPaths?: string[];
70
+ lsp: WatchdogLspRuntimeSnapshot;
71
+ }
72
+
73
+ interface Waiter {
74
+ resolve(settled: boolean): void;
75
+ timer: ReturnType<typeof setTimeout>;
76
+ }
77
+
78
+ interface MainWatchdogRuntimeOptions {
79
+ cwd?: string;
80
+ resolveConfig?: (cwd: string, options?: { session?: Record<string, unknown> }) => WatchdogSettingsResult;
81
+ review?: WatchdogReviewFunction;
82
+ reviewDescription?: string;
83
+ displayWarning?: (warning: WatchdogWarningDetails, options?: { deliverAs?: "steer" }) => void;
84
+ sendUserMessage?: (message: string) => void | Promise<void>;
85
+ reviewChangesOnly?: boolean;
86
+ lspDiagnostics?: WatchdogLspDiagnosticsFunction;
87
+ repoChangeSignature?: typeof computeWatchdogRepoChangeSignature;
88
+ }
89
+
90
+ type ContextLike = Pick<ExtensionContext, "cwd">;
91
+ type ReviewDeltaOutcome = "completed" | "timeout" | "stale";
92
+
93
+ const DEFAULT_REVIEW: WatchdogReviewFunction = () => ({ warnings: [] });
94
+ const MAX_REVIEW_INPUT_CHARS = 24_000;
95
+ const REVIEW_DELTA_SEPARATOR = "\n\n---\n\n";
96
+
97
+ function errorMessage(error: unknown): string {
98
+ return error instanceof Error ? error.message : String(error);
99
+ }
100
+
101
+ function promptFromBeforeAgentStart(event: unknown): string | undefined {
102
+ if (!event || typeof event !== "object") return undefined;
103
+ const input = event as { prompt?: unknown; systemPrompt?: unknown };
104
+ if (typeof input.prompt === "string") return input.prompt;
105
+ if (typeof input.systemPrompt === "string") return input.systemPrompt;
106
+ return undefined;
107
+ }
108
+
109
+ function reviewInputSignature(input: string): string {
110
+ return createHash("sha256").update(input).digest("hex");
111
+ }
112
+
113
+ export class MainWatchdogRuntime {
114
+ private cwd: string;
115
+ private readonly resolveConfig: (cwd: string, options?: { session?: Record<string, unknown> }) => WatchdogSettingsResult;
116
+ private readonly review: WatchdogReviewFunction;
117
+ private readonly reviewConnected: boolean;
118
+ 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;
121
+ private readonly reviewChangesOnly: boolean;
122
+ private readonly lspDiagnostics: WatchdogLspDiagnosticsFunction;
123
+ private readonly repoChangeSignature: typeof computeWatchdogRepoChangeSignature;
124
+ private readonly lspLedger = new WatchdogLspDiagnosticsLedger();
125
+ private readonly scope = new WatchdogScopeArtifact();
126
+ private configResult: WatchdogSettingsResult;
127
+ private sessionOverrideEnabled: boolean | undefined;
128
+ private sessionModelOverride: Partial<Pick<WatchdogEndpointConfig, "model" | "thinking">> | undefined;
129
+ private status: WatchdogRuntimeStatus = "idle";
130
+ private pendingDeltas: string[] = [];
131
+ private pendingDeltaChars = 0;
132
+ private guard = new WatchdogEmissionGuard();
133
+ private guardMaxWarnings: number | null = null;
134
+ private epoch = 0;
135
+ private reviewIdCounter = 0;
136
+ private agentEndIdCounter = 0;
137
+ private activeAgentEndId: number | undefined;
138
+ private activeAgentEndAbortController: AbortController | undefined;
139
+ private activeReviewId: number | undefined;
140
+ private activeReviewWarning: WatchdogWarningDetails | undefined;
141
+ private reviewing = false;
142
+ private waitingAtAgentEnd = false;
143
+ private disposed = false;
144
+ private includeUserPromptInNextDelta = false;
145
+ private userPrompt: string | undefined;
146
+ private waiters: Waiter[] = [];
147
+ private lastWarning: WatchdogWarningDetails | undefined;
148
+ private displayedWarningSequence = 0;
149
+ private lastError: string | undefined;
150
+ private lastReviewInputSignature: string | undefined;
151
+ private turnStartChangeSignature: WatchdogRepoChangeSignature | undefined;
152
+ private lastReviewedChangeSignature: string | undefined;
153
+ private currentChangedPaths: string[] | undefined;
154
+ private lastLspSnapshot: WatchdogLspRuntimeSnapshot | undefined;
155
+ private observedRepoEditThisTurn = false;
156
+ private toolResultsThisRun = 0;
157
+ 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[] = [];
164
+ private midRunGeneration = 0;
165
+ private activeReviewAbortController: AbortController | undefined;
166
+ private failedReviews = 0;
167
+ private staleReviews = 0;
168
+
169
+ constructor(options: MainWatchdogRuntimeOptions = {}) {
170
+ this.cwd = options.cwd ?? process.cwd();
171
+ this.resolveConfig = options.resolveConfig ?? resolveWatchdogConfig;
172
+ this.review = options.review ?? DEFAULT_REVIEW;
173
+ this.reviewConnected = Boolean(options.review);
174
+ this.reviewDescription = options.reviewDescription ?? (options.review ? "injected seam" : "not wired");
175
+ this.displayWarning = options.displayWarning;
176
+ this.sendUserMessage = options.sendUserMessage;
177
+ this.reviewChangesOnly = options.reviewChangesOnly === true;
178
+ this.lspDiagnostics = options.lspDiagnostics ?? collectWatchdogLspDiagnostics;
179
+ this.repoChangeSignature = options.repoChangeSignature ?? computeWatchdogRepoChangeSignature;
180
+ this.configResult = this.resolveConfig(this.cwd);
181
+ this.guardMaxWarnings = this.configResult.config.maxWarnings;
182
+ this.guard = new WatchdogEmissionGuard({ maxWarnings: this.guardMaxWarnings });
183
+ this.turnStartChangeSignature = this.currentRepoChangeSignature();
184
+ this.lastReviewedChangeSignature = this.turnStartChangeSignature?.key;
185
+ }
186
+
187
+ bindSession(ctx: ContextLike): void {
188
+ this.cwd = ctx.cwd;
189
+ this.sessionOverrideEnabled = undefined;
190
+ this.sessionModelOverride = undefined;
191
+ this.refreshConfig(ctx.cwd);
192
+ this.reset("session_start", { clearReviewInputSignature: true, resetChangeSignature: true, clearLspLedger: true, clearScope: true, resetAutoFollow: true });
193
+ }
194
+
195
+ refreshConfig(cwd = this.cwd): WatchdogSettingsResult {
196
+ this.cwd = cwd;
197
+ const wasEnabled = this.isEnabled();
198
+ const session = this.sessionOverrideEnabled === undefined && this.sessionModelOverride === undefined
199
+ ? undefined
200
+ : {
201
+ ...(this.sessionOverrideEnabled === undefined ? {} : { enabled: this.sessionOverrideEnabled }),
202
+ main: {
203
+ ...(this.sessionOverrideEnabled === undefined ? {} : { enabled: this.sessionOverrideEnabled }),
204
+ ...(this.sessionModelOverride ?? {}),
205
+ },
206
+ };
207
+ this.configResult = this.resolveConfig(this.cwd, session === undefined ? undefined : { session });
208
+ if (this.configResult.config.maxWarnings !== this.guardMaxWarnings) {
209
+ this.guardMaxWarnings = this.configResult.config.maxWarnings;
210
+ this.guard = new WatchdogEmissionGuard({ maxWarnings: this.guardMaxWarnings });
211
+ }
212
+ if (wasEnabled && !this.isEnabled()) this.invalidateActiveReview("watchdog disabled");
213
+ return this.configResult;
214
+ }
215
+
216
+ setSessionEnabled(enabled: boolean, cwd = this.cwd): WatchdogRuntimeSnapshot {
217
+ this.sessionOverrideEnabled = enabled;
218
+ this.reset("session override");
219
+ this.refreshConfig(cwd);
220
+ return this.getSnapshot();
221
+ }
222
+
223
+ setSessionModel(patch: { model?: string | null; thinking?: WatchdogEndpointConfig["thinking"] | null }, cwd = this.cwd): WatchdogRuntimeSnapshot {
224
+ const next = { ...(this.sessionModelOverride ?? {}) };
225
+ if (patch.model === null) delete next.model;
226
+ else if (patch.model !== undefined) next.model = patch.model;
227
+ if (patch.thinking === null) delete next.thinking;
228
+ else if (patch.thinking !== undefined) next.thinking = patch.thinking;
229
+ this.sessionModelOverride = next.model === undefined && next.thinking === undefined ? undefined : next;
230
+ this.reset("session model override");
231
+ this.refreshConfig(cwd);
232
+ return this.getSnapshot();
233
+ }
234
+
235
+ clearSessionModel(cwd = this.cwd): WatchdogRuntimeSnapshot {
236
+ this.sessionModelOverride = undefined;
237
+ this.reset("session model override cleared");
238
+ this.refreshConfig(cwd);
239
+ return this.getSnapshot();
240
+ }
241
+
242
+ clearSessionOverride(cwd = this.cwd): WatchdogRuntimeSnapshot {
243
+ this.sessionOverrideEnabled = undefined;
244
+ this.sessionModelOverride = undefined;
245
+ this.reset("session override cleared");
246
+ this.refreshConfig(cwd);
247
+ return this.getSnapshot();
248
+ }
249
+
250
+ reset(_reason = "reset", options: { clearReviewInputSignature?: boolean; resetChangeSignature?: boolean; clearLspLedger?: boolean; clearScope?: boolean; resetAutoFollow?: boolean } = {}): void {
251
+ this.abortActiveAgentEnd();
252
+ this.epoch++;
253
+ this.status = "idle";
254
+ this.clearPendingDeltas();
255
+ this.reviewing = false;
256
+ this.waitingAtAgentEnd = false;
257
+ this.activeReviewId = undefined;
258
+ this.activeReviewWarning = undefined;
259
+ this.includeUserPromptInNextDelta = false;
260
+ this.userPrompt = undefined;
261
+ this.lastError = undefined;
262
+ this.currentChangedPaths = undefined;
263
+ this.observedRepoEditThisTurn = false;
264
+ this.toolResultsThisRun = 0;
265
+ this.midRunReviewing = false;
266
+ this.autoFollowQueued = false;
267
+ if (options.clearLspLedger) {
268
+ this.lspLedger.reset();
269
+ this.lastLspSnapshot = undefined;
270
+ }
271
+ if (options.clearScope) {
272
+ this.scope.reset();
273
+ this.pendingAutoFollowPrompts = [];
274
+ }
275
+ if (options.resetAutoFollow) this.resetAutoFollowState();
276
+ if (options.clearReviewInputSignature) this.lastReviewInputSignature = undefined;
277
+ if (options.resetChangeSignature) this.resetRepoChangeBaseline({ reviewed: true });
278
+ this.guard.reset();
279
+ this.resolveWaiters(true);
280
+ }
281
+
282
+ dispose(): void {
283
+ this.disposed = true;
284
+ this.abortActiveAgentEnd();
285
+ this.epoch++;
286
+ this.status = "idle";
287
+ this.clearPendingDeltas();
288
+ this.reviewing = false;
289
+ this.waitingAtAgentEnd = false;
290
+ this.activeReviewId = undefined;
291
+ this.activeReviewWarning = undefined;
292
+ this.lastReviewInputSignature = undefined;
293
+ this.currentChangedPaths = undefined;
294
+ this.lastLspSnapshot = undefined;
295
+ this.lspLedger.reset();
296
+ this.scope.reset();
297
+ this.observedRepoEditThisTurn = false;
298
+ this.toolResultsThisRun = 0;
299
+ this.midRunReviewing = false;
300
+ this.autoFollowQueued = false;
301
+ this.resolveWaiters(false);
302
+ }
303
+
304
+ handleBeforeAgentStart(event: unknown, ctx: ContextLike): void {
305
+ if (this.disposed) return;
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 });
313
+ this.refreshConfig(ctx.cwd);
314
+ this.userPrompt = incomingPrompt;
315
+ if (!autoFollowPrompt && this.userPrompt?.trim()) {
316
+ this.includeUserPromptInNextDelta = true;
317
+ this.scope.addPrompt(this.userPrompt);
318
+ } else {
319
+ this.includeUserPromptInNextDelta = false;
320
+ }
321
+ this.resetRepoChangeBaseline();
322
+ }
323
+
324
+ handleTurnEnd(event: unknown, ctx: ContextLike): void {
325
+ if (this.disposed) return;
326
+ this.refreshConfig(ctx.cwd);
327
+ if (!this.isEnabled()) return;
328
+ try {
329
+ this.observedRepoEditThisTurn ||= eventIndicatesRepoEdit(event);
330
+ const delta = formatWatchdogTurnDelta({
331
+ includeUserPrompt: this.includeUserPromptInNextDelta,
332
+ userPrompt: this.userPrompt,
333
+ events: [event],
334
+ });
335
+ this.includeUserPromptInNextDelta = false;
336
+ this.enqueueDelta(delta);
337
+ } catch (error) {
338
+ this.fail(`Failed to format watchdog turn delta: ${errorMessage(error)}`);
339
+ }
340
+ }
341
+
342
+ enqueueDelta(delta: string): void {
343
+ if (this.disposed || !delta.trim() || !this.isEnabled()) return;
344
+ this.appendBoundedDelta(delta);
345
+ if (!this.reviewing && !this.waitingAtAgentEnd && !this.midRunReviewing) this.status = "queued";
346
+ }
347
+
348
+ handleToolResult(ctx: ContextLike): void {
349
+ if (this.disposed) return;
350
+ this.refreshConfig(ctx.cwd);
351
+ if (!this.isEnabled()) return;
352
+ const everyNTools = this.configResult.config.cadence.everyNTools;
353
+ if (everyNTools === null) return;
354
+ this.toolResultsThisRun++;
355
+ if (this.toolResultsThisRun % everyNTools !== 0) return;
356
+ if (this.reviewing || this.waitingAtAgentEnd || this.midRunReviewing) return;
357
+ const delta = this.buildReviewInput(undefined, "");
358
+ if (!delta.trim()) return;
359
+ void this.reviewMidRunDelta(delta);
360
+ }
361
+
362
+ async handleAgentEnd(_event: unknown, ctx: ContextLike): Promise<void> {
363
+ if (this.disposed) return;
364
+ this.refreshConfig(ctx.cwd);
365
+ if (!this.isEnabled()) return;
366
+ const changeSignature = this.resolveReviewChangeSignature(ctx.cwd);
367
+ if (this.reviewChangesOnly && !changeSignature) {
368
+ this.clearPendingDeltas();
369
+ if (this.status === "queued") this.status = "idle";
370
+ this.resolveWaiters(true);
371
+ return;
372
+ }
373
+ if (changeSignature && changeSignature.key === this.lastReviewedChangeSignature) {
374
+ this.clearPendingDeltas();
375
+ this.status = "idle";
376
+ this.resolveWaiters(true);
377
+ return;
378
+ }
379
+ this.cancelMidRunReview();
380
+ this.waitingAtAgentEnd = true;
381
+ const agentEndEpoch = this.epoch;
382
+ const agentEndId = ++this.agentEndIdCounter;
383
+ const lspAbortController = new AbortController();
384
+ this.activeAgentEndId = agentEndId;
385
+ this.activeAgentEndAbortController = lspAbortController;
386
+ let displayedDuringAgentEnd: WatchdogWarningDetails | undefined;
387
+ const previousDisplayedSequence = this.displayedWarningSequence;
388
+ try {
389
+ this.guard.startModelUpdate();
390
+ const lspBlock = await this.collectLspDiagnostics(changeSignature, {
391
+ epoch: agentEndEpoch,
392
+ agentEndId,
393
+ signal: lspAbortController.signal,
394
+ });
395
+ if (this.activeAgentEndAbortController === lspAbortController) this.activeAgentEndAbortController = undefined;
396
+ if (!this.isAgentEndCurrent(agentEndEpoch, agentEndId)) return;
397
+ const delta = this.buildReviewInput(changeSignature, lspBlock);
398
+ this.clearPendingDeltas();
399
+ if (!delta.trim()) {
400
+ this.waitingAtAgentEnd = false;
401
+ if (this.status === "queued") this.status = "idle";
402
+ this.resolveWaiters(true);
403
+ return;
404
+ }
405
+ const signature = reviewInputSignature(delta);
406
+ if (!this.reviewChangesOnly && signature === this.lastReviewInputSignature) {
407
+ this.waitingAtAgentEnd = false;
408
+ this.status = "idle";
409
+ this.resolveWaiters(true);
410
+ return;
411
+ }
412
+ const outcome = await this.reviewDelta(delta, this.configResult.config.agentEndTimeoutMs);
413
+ this.waitingAtAgentEnd = false;
414
+ if (outcome === "timeout") {
415
+ this.staleReviews++;
416
+ this.invalidateActiveReview("agent-end timeout");
417
+ this.status = "stale";
418
+ this.markLastWarningStale();
419
+ this.resolveWaiters(true);
420
+ return;
421
+ }
422
+ if (outcome === "completed" && this.status !== "failed" && this.status !== "stale") {
423
+ this.lastReviewInputSignature = signature;
424
+ if (changeSignature) this.lastReviewedChangeSignature = changeSignature.key;
425
+ this.currentChangedPaths = changeSignature?.changedPaths;
426
+ this.status = "idle";
427
+ }
428
+ displayedDuringAgentEnd = this.displayedWarningSequence !== previousDisplayedSequence ? this.lastWarning : undefined;
429
+ this.queueAutoFollowIfNeeded(displayedDuringAgentEnd);
430
+ this.resolveWaiters(true);
431
+ } finally {
432
+ if (this.activeAgentEndAbortController === lspAbortController) this.activeAgentEndAbortController = undefined;
433
+ if (this.activeAgentEndId === agentEndId) this.activeAgentEndId = undefined;
434
+ }
435
+ }
436
+
437
+ recordDisplayedWarning(warning: WatchdogWarning): WatchdogWarningDetails {
438
+ const details = normalizeWatchdogWarningDetails(warning, { state: "displayed", source: warning.source ?? "main" });
439
+ this.lastWarning = details;
440
+ return details;
441
+ }
442
+
443
+ getSnapshot(cwd?: string): WatchdogRuntimeSnapshot {
444
+ if (cwd) this.refreshConfig(cwd);
445
+ return {
446
+ status: this.status,
447
+ enabled: this.isEnabled(),
448
+ config: this.configResult.config,
449
+ configOk: this.configResult.ok,
450
+ errors: [...this.configResult.errors],
451
+ sources: [...this.configResult.sources],
452
+ bufferedDeltas: this.pendingDeltas.length,
453
+ epoch: this.epoch,
454
+ ...(this.activeReviewId !== undefined ? { activeReviewId: this.activeReviewId } : {}),
455
+ ...(this.sessionOverrideEnabled !== undefined ? { sessionOverride: this.sessionOverrideEnabled } : {}),
456
+ ...(this.sessionModelOverride !== undefined ? { sessionModelOverride: { ...this.sessionModelOverride } } : {}),
457
+ ...(this.lastWarning ? { lastWarning: this.lastWarning } : {}),
458
+ ...(this.lastError ? { lastError: this.lastError } : {}),
459
+ failedReviews: this.failedReviews,
460
+ staleReviews: this.staleReviews,
461
+ reviewConnected: this.reviewConnected,
462
+ reviewDescription: this.reviewDescription,
463
+ autoFollowQueued: this.autoFollowQueued,
464
+ autoFollowAttempts: this.autoFollowAttempts,
465
+ autoFollowStalemate: this.autoFollowStalemate,
466
+ reviewTrigger: this.reviewChangesOnly ? "repo-edits" : "turn-delta",
467
+ ...(this.currentChangedPaths?.length ? { changedPaths: [...this.currentChangedPaths] } : {}),
468
+ lsp: this.lspSnapshot(),
469
+ };
470
+ }
471
+
472
+ async waitForIdle(timeoutMs = 1_000): Promise<boolean> {
473
+ return this.waitForSettled(timeoutMs);
474
+ }
475
+
476
+ private isEnabled(): boolean {
477
+ return this.configResult.ok && this.configResult.config.main.enabled;
478
+ }
479
+
480
+ private abortActiveAgentEnd(): void {
481
+ this.activeAgentEndAbortController?.abort();
482
+ this.activeAgentEndAbortController = undefined;
483
+ this.activeAgentEndId = undefined;
484
+ }
485
+
486
+ private isAgentEndCurrent(epoch: number, agentEndId: number): boolean {
487
+ return !this.disposed && this.epoch === epoch && this.activeAgentEndId === agentEndId && this.waitingAtAgentEnd && this.isEnabled();
488
+ }
489
+
490
+ private isCurrent(epoch: number, reviewId: number): boolean {
491
+ return !this.disposed && this.epoch === epoch && this.activeReviewId === reviewId;
492
+ }
493
+
494
+ private warningMeetsThreshold(warning: WatchdogWarning): boolean {
495
+ return this.configResult.config.severityThreshold === "concern" || warning.severity === "blocker";
496
+ }
497
+
498
+ private acceptWarning(epoch: number, reviewId: number, warning: WatchdogWarning): boolean {
499
+ if (!this.isCurrent(epoch, reviewId) || !this.isEnabled() || !this.warningMeetsThreshold(warning)) return false;
500
+ const decision = this.guard.evaluate(warning);
501
+ if (!decision.accepted) return false;
502
+ const details = normalizeWatchdogWarningDetails(warning, {
503
+ state: "candidate",
504
+ source: warning.source ?? "main",
505
+ identity: decision.identity,
506
+ });
507
+ this.lastWarning = details;
508
+ this.activeReviewWarning = details;
509
+ return true;
510
+ }
511
+
512
+ private displayBoundaryWarning(warning: WatchdogWarning): boolean {
513
+ if (!this.isEnabled() || !this.warningMeetsThreshold(warning)) return false;
514
+ const decision = this.guard.evaluate(warning);
515
+ if (!decision.accepted) return false;
516
+ const details = normalizeWatchdogWarningDetails(warning, {
517
+ state: "displayed",
518
+ source: warning.source ?? "main",
519
+ identity: decision.identity,
520
+ displayedAt: new Date().toISOString(),
521
+ });
522
+ this.lastWarning = details;
523
+ this.displayedWarningSequence++;
524
+ this.displayWarning?.(details);
525
+ return true;
526
+ }
527
+
528
+ private invalidateActiveReview(_reason: string): void {
529
+ this.abortActiveAgentEnd();
530
+ this.epoch++;
531
+ this.status = "idle";
532
+ this.clearPendingDeltas();
533
+ this.reviewing = false;
534
+ this.waitingAtAgentEnd = false;
535
+ this.activeReviewId = undefined;
536
+ this.activeReviewWarning = undefined;
537
+ }
538
+
539
+ private async reviewMidRunDelta(delta: string): Promise<void> {
540
+ if (this.midRunReviewing || this.reviewing || this.waitingAtAgentEnd || this.disposed) return;
541
+ this.midRunReviewing = true;
542
+ const generation = this.midRunGeneration;
543
+ try {
544
+ const outcome = await this.reviewDelta(delta, this.configResult.config.agentEndTimeoutMs, { correction: true });
545
+ if (generation !== this.midRunGeneration) return;
546
+ if (outcome === "timeout") {
547
+ this.staleReviews++;
548
+ this.status = "stale";
549
+ this.markLastWarningStale();
550
+ }
551
+ } finally {
552
+ if (generation === this.midRunGeneration) {
553
+ this.midRunReviewing = false;
554
+ if (this.status === "reviewing") this.status = this.pendingDeltas.length ? "queued" : "idle";
555
+ this.resolveWaiters(this.isSettled());
556
+ }
557
+ }
558
+ }
559
+
560
+ // The agent-end boundary review is authoritative; an in-flight cadence review is superseded.
561
+ private cancelMidRunReview(): void {
562
+ if (!this.midRunReviewing) return;
563
+ this.midRunGeneration++;
564
+ this.activeReviewAbortController?.abort();
565
+ this.activeReviewAbortController = undefined;
566
+ this.staleReviews++;
567
+ this.reviewing = false;
568
+ this.midRunReviewing = false;
569
+ this.activeReviewId = undefined;
570
+ this.activeReviewWarning = undefined;
571
+ }
572
+
573
+ private async reviewDelta(delta: string, timeoutMs: number, options: { correction?: boolean } = {}): Promise<ReviewDeltaOutcome> {
574
+ if (this.reviewing || this.disposed) return "stale";
575
+ this.reviewing = true;
576
+ const reviewEpoch = this.epoch;
577
+ const reviewId = ++this.reviewIdCounter;
578
+ this.activeReviewId = reviewId;
579
+ this.activeReviewWarning = undefined;
580
+ this.status = "reviewing";
581
+ let timeout: ReturnType<typeof setTimeout> | undefined;
582
+ const abortController = new AbortController();
583
+ this.activeReviewAbortController = abortController;
584
+ const reviewPromise = Promise.resolve().then(() => this.review({
585
+ delta,
586
+ epoch: reviewEpoch,
587
+ reviewId,
588
+ config: this.configResult.config,
589
+ hasScope: this.scopeBlock().trim().length > 0,
590
+ signal: abortController.signal,
591
+ emitWarning: (warning) => this.acceptWarning(reviewEpoch, reviewId, warning),
592
+ }));
593
+ try {
594
+ const result = await Promise.race([
595
+ reviewPromise,
596
+ new Promise<"timeout">((resolve) => {
597
+ timeout = setTimeout(() => resolve("timeout"), timeoutMs);
598
+ }),
599
+ ]);
600
+ if (result === "timeout") {
601
+ abortController.abort();
602
+ return "timeout";
603
+ }
604
+ if (!this.isCurrent(reviewEpoch, reviewId)) return "stale";
605
+ if (!result) return "stale";
606
+ for (const warning of result.warnings ?? []) this.acceptWarning(reviewEpoch, reviewId, warning);
607
+ if (result.stopReason && result.stopReason !== "stop") {
608
+ this.fail(`Watchdog review ended with stop reason '${result.stopReason}'.`);
609
+ return "completed";
610
+ }
611
+ this.displayAcceptedReviewWarning(options.correction);
612
+ return "completed";
613
+ } catch (error) {
614
+ if (this.isCurrent(reviewEpoch, reviewId)) {
615
+ this.fail(`Watchdog review failed: ${errorMessage(error)}`);
616
+ return "completed";
617
+ }
618
+ return "stale";
619
+ } finally {
620
+ if (timeout) clearTimeout(timeout);
621
+ if (this.activeReviewAbortController === abortController) this.activeReviewAbortController = undefined;
622
+ if (this.epoch === reviewEpoch && this.activeReviewId === reviewId) {
623
+ this.reviewing = false;
624
+ this.activeReviewId = undefined;
625
+ this.activeReviewWarning = undefined;
626
+ }
627
+ this.resolveWaiters(this.isSettled());
628
+ }
629
+ }
630
+
631
+ private displayAcceptedReviewWarning(correction = false): void {
632
+ if (!this.activeReviewWarning) return;
633
+ const details: WatchdogWarningDetails = {
634
+ ...this.activeReviewWarning,
635
+ state: "displayed",
636
+ displayedAt: new Date().toISOString(),
637
+ };
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;
649
+ }
650
+
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++;
655
+ 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;
663
+ }
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
+ });
683
+ }
684
+
685
+ private currentRepoChangeSignature(cwd = this.cwd): WatchdogRepoChangeSignature | undefined {
686
+ return this.reviewChangesOnly && this.isEnabled() ? this.repoChangeSignature(cwd) : undefined;
687
+ }
688
+
689
+ private resetRepoChangeBaseline(options: { cwd?: string; reviewed?: boolean } = {}): void {
690
+ this.turnStartChangeSignature = this.currentRepoChangeSignature(options.cwd ?? this.cwd);
691
+ if (options.reviewed) this.lastReviewedChangeSignature = this.turnStartChangeSignature?.key;
692
+ else this.lastReviewedChangeSignature ??= this.turnStartChangeSignature?.key;
693
+ this.currentChangedPaths = this.turnStartChangeSignature?.changedPaths;
694
+ this.observedRepoEditThisTurn = false;
695
+ }
696
+
697
+ private resolveReviewChangeSignature(cwd = this.cwd): WatchdogRepoChangeSignature | undefined {
698
+ if (!this.reviewChangesOnly) return undefined;
699
+ const current = this.currentRepoChangeSignature(cwd);
700
+ if (current) {
701
+ this.currentChangedPaths = current.changedPaths;
702
+ if (current.key === this.turnStartChangeSignature?.key) return undefined;
703
+ if (current.changedPaths.length === 0) return undefined;
704
+ return current;
705
+ }
706
+ return this.observedRepoEditThisTurn
707
+ ? { root: cwd, key: `observed-edit:${this.epoch}:${this.reviewIdCounter}:${this.pendingDeltaChars}`, changedPaths: [] }
708
+ : undefined;
709
+ }
710
+
711
+ private async collectLspDiagnostics(changeSignature: WatchdogRepoChangeSignature | undefined, current: { epoch: number; agentEndId: number; signal: AbortSignal }): Promise<string> {
712
+ const config = this.configResult.config.lsp;
713
+ if (!config.enabled || !changeSignature?.changedPaths.length) {
714
+ this.lastLspSnapshot = {
715
+ enabled: config.enabled,
716
+ status: config.enabled ? "skipped" : "disabled",
717
+ checkedPaths: [],
718
+ skippedPaths: [],
719
+ diagnostics: [],
720
+ diagnosticCount: 0,
721
+ freshDiagnosticCount: 0,
722
+ updatedAt: new Date().toISOString(),
723
+ };
724
+ return "";
725
+ }
726
+ try {
727
+ const raw = await this.lspDiagnostics({
728
+ cwd: this.cwd,
729
+ root: changeSignature.root,
730
+ changedPaths: changeSignature.changedPaths,
731
+ config,
732
+ signal: current.signal,
733
+ });
734
+ if (!this.isAgentEndCurrent(current.epoch, current.agentEndId)) return "";
735
+ const diagnosticCount = raw.diagnostics.length;
736
+ const fresh = this.lspLedger.reduce(raw);
737
+ this.lastLspSnapshot = {
738
+ ...fresh,
739
+ enabled: true,
740
+ diagnosticCount,
741
+ freshDiagnosticCount: fresh.diagnostics.length,
742
+ updatedAt: new Date().toISOString(),
743
+ };
744
+ const warning = watchdogWarningFromLspDiagnostics(fresh);
745
+ if (warning) this.displayBoundaryWarning(warning);
746
+ return formatWatchdogLspDiagnosticsBlock(fresh);
747
+ } catch (error) {
748
+ if (!this.isAgentEndCurrent(current.epoch, current.agentEndId)) return "";
749
+ this.lastLspSnapshot = {
750
+ enabled: true,
751
+ status: "failed",
752
+ checkedPaths: [],
753
+ skippedPaths: changeSignature.changedPaths,
754
+ diagnostics: [],
755
+ diagnosticCount: 0,
756
+ freshDiagnosticCount: 0,
757
+ message: `LSP diagnostics failed: ${errorMessage(error)}`,
758
+ updatedAt: new Date().toISOString(),
759
+ };
760
+ return "";
761
+ }
762
+ }
763
+
764
+ private lspSnapshot(): WatchdogLspRuntimeSnapshot {
765
+ if (this.lastLspSnapshot) return {
766
+ ...this.lastLspSnapshot,
767
+ checkedPaths: [...this.lastLspSnapshot.checkedPaths],
768
+ skippedPaths: [...this.lastLspSnapshot.skippedPaths],
769
+ diagnostics: [...this.lastLspSnapshot.diagnostics],
770
+ };
771
+ const enabled = this.isEnabled() && this.configResult.config.lsp.enabled;
772
+ return {
773
+ enabled,
774
+ status: enabled ? "skipped" : "disabled",
775
+ checkedPaths: [],
776
+ skippedPaths: [],
777
+ diagnostics: [],
778
+ diagnosticCount: 0,
779
+ freshDiagnosticCount: 0,
780
+ };
781
+ }
782
+
783
+ private appendBoundedDelta(delta: string): void {
784
+ let entry = delta.trim();
785
+ if (!entry) return;
786
+ if (entry.length > MAX_REVIEW_INPUT_CHARS) entry = entry.slice(-MAX_REVIEW_INPUT_CHARS);
787
+ this.pendingDeltas.push(entry);
788
+ this.pendingDeltaChars += entry.length;
789
+ while (this.pendingDeltas.length > 1 && this.pendingDeltaChars + (this.pendingDeltas.length - 1) * REVIEW_DELTA_SEPARATOR.length > MAX_REVIEW_INPUT_CHARS) {
790
+ const removed = this.pendingDeltas.shift();
791
+ if (removed) this.pendingDeltaChars -= removed.length;
792
+ }
793
+ }
794
+
795
+ private buildReviewInput(changeSignature?: WatchdogRepoChangeSignature, lspBlock = ""): string {
796
+ const input = this.pendingDeltas.join(REVIEW_DELTA_SEPARATOR);
797
+ const scopeBlock = this.scopeBlock();
798
+ const changes = changeSignature?.changedPaths.length
799
+ ? ["Changed repo paths:", ...changeSignature.changedPaths.slice(0, 200).map((file) => `- ${file}`)].join("\n")
800
+ : "";
801
+ 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;
803
+
804
+ const maxContextLength = Math.floor(MAX_REVIEW_INPUT_CHARS / 2);
805
+ const maxPieceLength = Math.max(1_000, Math.floor(maxContextLength / contextPieces.length));
806
+ const boundedContext = contextPieces.map((piece) => piece.length > maxPieceLength
807
+ ? `${piece.slice(0, maxPieceLength - 6)}\n- ...`
808
+ : piece).join(REVIEW_DELTA_SEPARATOR);
809
+ const separatorLength = input ? REVIEW_DELTA_SEPARATOR.length : 0;
810
+ 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;
816
+ return [boundedContext, boundedInput].filter(Boolean).join(REVIEW_DELTA_SEPARATOR);
817
+ }
818
+
819
+ private scopeBlock(): string {
820
+ return this.configResult.config.scope.enabled ? this.scope.render() : "";
821
+ }
822
+
823
+ private clearPendingDeltas(): void {
824
+ this.pendingDeltas = [];
825
+ this.pendingDeltaChars = 0;
826
+ }
827
+
828
+ private fail(message: string): void {
829
+ this.failedReviews++;
830
+ this.lastError = message;
831
+ this.status = "failed";
832
+ this.clearPendingDeltas();
833
+ this.resolveWaiters(true);
834
+ }
835
+
836
+ private markLastWarningStale(): void {
837
+ if (!this.lastWarning || this.lastWarning.state === "displayed") return;
838
+ this.lastWarning = { ...this.lastWarning, stale: true, state: "stale" };
839
+ }
840
+
841
+ private isSettled(): boolean {
842
+ return !this.reviewing && this.pendingDeltas.length === 0;
843
+ }
844
+
845
+ private waitForSettled(timeoutMs: number): Promise<boolean> {
846
+ if (this.isSettled()) return Promise.resolve(true);
847
+ return new Promise((resolve) => {
848
+ const waiter: Waiter = {
849
+ resolve,
850
+ timer: setTimeout(() => {
851
+ this.waiters = this.waiters.filter((entry) => entry !== waiter);
852
+ resolve(false);
853
+ }, timeoutMs),
854
+ };
855
+ this.waiters.push(waiter);
856
+ });
857
+ }
858
+
859
+ private resolveWaiters(settled: boolean): void {
860
+ if (!settled && !this.disposed) return;
861
+ const waiters = this.waiters;
862
+ this.waiters = [];
863
+ for (const waiter of waiters) {
864
+ clearTimeout(waiter.timer);
865
+ waiter.resolve(settled);
866
+ }
867
+ }
868
+ }