@ftrdotdev/pi-delegates 0.0.0-stage → 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 (116) hide show
  1. package/CHANGELOG.md +77 -0
  2. package/LICENSE +21 -0
  3. package/OPERATIONS.md +57 -0
  4. package/README.md +448 -2
  5. package/ROADMAP.md +158 -0
  6. package/TESTING.md +1061 -0
  7. package/agents.ts +8 -0
  8. package/examples/README.md +114 -0
  9. package/examples/gated.ts +28 -0
  10. package/index.ts +9 -0
  11. package/package.json +93 -4
  12. package/skills/pi-delegates/SKILL.md +147 -0
  13. package/skills/pi-delegates/references/control.md +159 -0
  14. package/skills/pi-delegates/references/definitions.md +163 -0
  15. package/skills/pi-delegates/references/gates.md +175 -0
  16. package/skills/pi-delegates/references/launch.md +156 -0
  17. package/src/domain/definitions.test.ts +41 -0
  18. package/src/domain/definitions.ts +161 -0
  19. package/src/domain/ids.ts +13 -0
  20. package/src/domain/names.ts +35 -0
  21. package/src/domain/orchestration/admission.ts +78 -0
  22. package/src/domain/orchestration/control.test.ts +1298 -0
  23. package/src/domain/orchestration/control.ts +436 -0
  24. package/src/domain/orchestration/fanout.test.ts +419 -0
  25. package/src/domain/orchestration/fanout.ts +334 -0
  26. package/src/domain/orchestration/gates.test.ts +686 -0
  27. package/src/domain/orchestration/gates.ts +360 -0
  28. package/src/domain/orchestration/launch.test.ts +173 -0
  29. package/src/domain/orchestration/launch.ts +581 -0
  30. package/src/domain/orchestration/requests.test.ts +700 -0
  31. package/src/domain/orchestration/requests.ts +769 -0
  32. package/src/domain/orchestration/review.test.ts +214 -0
  33. package/src/domain/orchestration/review.ts +168 -0
  34. package/src/domain/orchestration/run-wait.test.ts +262 -0
  35. package/src/domain/orchestration/run-wait.ts +256 -0
  36. package/src/domain/orchestration/workflow-section.test.ts +62 -0
  37. package/src/domain/orchestration/workflow-section.ts +99 -0
  38. package/src/domain/orchestration/workflow.test.ts +1425 -0
  39. package/src/domain/orchestration/workflow.ts +705 -0
  40. package/src/domain/run-records.test.ts +27 -0
  41. package/src/domain/run-records.ts +527 -0
  42. package/src/domain/shapes.test.ts +165 -0
  43. package/src/domain/skills.test.ts +466 -0
  44. package/src/domain/skills.ts +97 -0
  45. package/src/domain/tool-schema.test.ts +46 -0
  46. package/src/domain/tool-schema.ts +20 -0
  47. package/src/domain/toolkit.test.ts +201 -0
  48. package/src/domain/toolkit.ts +379 -0
  49. package/src/domain/view.test.ts +739 -0
  50. package/src/domain/view.ts +459 -0
  51. package/src/example.test.ts +15 -0
  52. package/src/extension/commands.test.ts +481 -0
  53. package/src/extension/commands.ts +227 -0
  54. package/src/extension/entry.test.ts +1118 -0
  55. package/src/extension/entry.ts +342 -0
  56. package/src/extension/gate-alerts.test.ts +235 -0
  57. package/src/extension/gate-alerts.ts +143 -0
  58. package/src/extension/guard.test.ts +48 -0
  59. package/src/extension/guard.ts +31 -0
  60. package/src/extension/host-signals.test.ts +20 -0
  61. package/src/extension/host-signals.ts +13 -0
  62. package/src/extension/inspector-command.test.ts +1191 -0
  63. package/src/extension/inspector-command.ts +638 -0
  64. package/src/extension/prompt.test.ts +110 -0
  65. package/src/extension/prompt.ts +50 -0
  66. package/src/extension/request-alerts.test.ts +183 -0
  67. package/src/extension/request-alerts.ts +181 -0
  68. package/src/extension/revocation.test.ts +81 -0
  69. package/src/extension/revocation.ts +84 -0
  70. package/src/extension/shortcut.test.ts +64 -0
  71. package/src/extension/shortcut.ts +105 -0
  72. package/src/extension/tools.test.ts +993 -0
  73. package/src/extension/tools.ts +505 -0
  74. package/src/extension/version.test.ts +123 -0
  75. package/src/extension/version.ts +97 -0
  76. package/src/harness-policy.test.ts +74 -0
  77. package/src/package-manifest.test.ts +157 -0
  78. package/src/presentation/actions.test.ts +221 -0
  79. package/src/presentation/actions.ts +85 -0
  80. package/src/presentation/activity.test.ts +387 -0
  81. package/src/presentation/activity.ts +66 -0
  82. package/src/presentation/close.test.ts +361 -0
  83. package/src/presentation/inspector.test.ts +679 -0
  84. package/src/presentation/inspector.ts +440 -0
  85. package/src/presentation/overlay.test.ts +555 -0
  86. package/src/presentation/overlay.ts +229 -0
  87. package/src/presentation/repaint.test.ts +329 -0
  88. package/src/presentation/shortcut.ts +2 -0
  89. package/src/presentation/snapshot.test.ts +530 -0
  90. package/src/presentation/snapshot.ts +306 -0
  91. package/src/presentation/strip.test.ts +196 -0
  92. package/src/presentation/strip.ts +74 -0
  93. package/src/presentation/wording.test.ts +238 -0
  94. package/src/presentation/wording.ts +222 -0
  95. package/src/runtime/bridge.test.ts +131 -0
  96. package/src/runtime/bridge.ts +134 -0
  97. package/src/runtime/config.test.ts +44 -0
  98. package/src/runtime/config.ts +87 -0
  99. package/src/runtime/context.test.ts +19 -0
  100. package/src/runtime/context.ts +9 -0
  101. package/src/runtime/execution-env.test.ts +35 -0
  102. package/src/runtime/execution-env.ts +15 -0
  103. package/src/runtime/extensions.test.ts +86 -0
  104. package/src/runtime/extensions.ts +140 -0
  105. package/src/runtime/log.test.ts +128 -0
  106. package/src/runtime/log.ts +68 -0
  107. package/src/runtime/mcp.test.ts +1453 -0
  108. package/src/runtime/mcp.ts +938 -0
  109. package/src/runtime/models.test.ts +145 -0
  110. package/src/runtime/models.ts +259 -0
  111. package/src/runtime/observe.test.ts +50 -0
  112. package/src/runtime/observe.ts +150 -0
  113. package/src/runtime/session.test.ts +359 -0
  114. package/src/runtime/session.ts +425 -0
  115. package/src/runtime/timers.test.ts +31 -0
  116. package/src/runtime/timers.ts +10 -0
@@ -0,0 +1,342 @@
1
+ import type { ExtensionAPI, ExtensionContext } from "@earendil-works/pi-coding-agent";
2
+ import { getAgentDir } from "@earendil-works/pi-coding-agent";
3
+ import { existsSync } from "node:fs";
4
+ import { join } from "node:path";
5
+ import { createCatalogue, type AgentDefinition } from "../domain/definitions.ts";
6
+ import { viewSession, type SessionView } from "../domain/view.ts";
7
+ import { fileLogSink, errorFields, nullLogSink, type LogSink } from "../runtime/log.ts";
8
+ import { HostModelAdapter } from "../runtime/models.ts";
9
+ import {
10
+ openReadOnlyRuntime,
11
+ openSessionRuntime,
12
+ storePathFor,
13
+ type SessionRuntime,
14
+ } from "../runtime/session.ts";
15
+ import { DEFAULTS } from "../runtime/config.ts";
16
+ import { registerDelegatesCommand } from "./commands.ts";
17
+ import { coexistenceVerdict } from "./guard.ts";
18
+ import { startGateAlerts, type GateAlertWatch } from "./gate-alerts.ts";
19
+ import { requestHostFor, startRequestAlerts, type RequestAlertWatch } from "./request-alerts.ts";
20
+ import {
21
+ ensureInspector,
22
+ hostFor,
23
+ registerInspectorOverlay,
24
+ restoreInspector,
25
+ runDelegatesCommand,
26
+ syncInspectorBranch,
27
+ teardownInspector,
28
+ type InspectorCommandDeps,
29
+ type InspectorOverrides,
30
+ } from "./inspector-command.ts";
31
+ import { readHostSignals } from "./host-signals.ts";
32
+ import { registerPromptSection } from "./prompt.ts";
33
+ import {
34
+ closeWithin,
35
+ reportRefusal,
36
+ revokeTools,
37
+ REVOCATION_CLOSE_MS,
38
+ type RefusedVerdict,
39
+ type RevocationState,
40
+ } from "./revocation.ts";
41
+ import { resolveInspectShortcut } from "./shortcut.ts";
42
+ import { registerDelegateTools, hostFrom } from "./tools.ts";
43
+ import type { HostDefaults } from "../domain/orchestration/launch.ts";
44
+ import {
45
+ readVersionSignals,
46
+ resolveFromPackage,
47
+ versionVerdict,
48
+ type VersionVerdict,
49
+ } from "./version.ts";
50
+
51
+ /**
52
+ * Options for the extension factory. `definitions` is the production option;
53
+ * the rest are host overrides and test seams.
54
+ */
55
+ export interface CreateDelegatesOptions {
56
+ /**
57
+ * Definitions registered in addition to the built-in presets. A definition
58
+ * whose name matches a preset overrides that preset.
59
+ */
60
+ readonly definitions?: readonly AgentDefinition[];
61
+ /** The Pi agent directory; default `getAgentDir()` in a real host. */
62
+ readonly agentDir?: string;
63
+ /** Observes the session runtime for host integration and reload tests. */
64
+ readonly onRuntime?: (runtime: SessionRuntime | undefined) => void;
65
+ /** Overrides the version verdict in tests. */
66
+ readonly version?: VersionVerdict;
67
+ /** Test seam: the inspector's observation, clock and view doubles. */
68
+ readonly inspector?: InspectorOverrides;
69
+ /** Overrides the resolved overlay shortcut; defaults to `ctrl+space`. */
70
+ readonly inspectorShortcut?: string;
71
+ /** How long a refusal waits for the previous runtime; default `REVOCATION_CLOSE_MS`. */
72
+ readonly revocationCloseMs?: number;
73
+ }
74
+
75
+ /**
76
+ * The only place that registers Pi surfaces: the three delegate tools, the
77
+ * prompt section, `/delegates` and the inspector. Pass custom definitions in
78
+ * `options.definitions`; each definition's toolkit is committed at launch.
79
+ *
80
+ * Both guards gate registration: the version guard runs at load, the
81
+ * coexistence guard runs at every session start until it refuses. A refusal
82
+ * latches for this instance: before registration it keeps only the commands,
83
+ * after registration it withdraws its tools and closes its runtime.
84
+ * Pi rejects host reads until the factory returns, so the coexistence signals
85
+ * are only readable from an event handler. The runtime is composed once per
86
+ * session and torn down on shutdown.
87
+ */
88
+ export const createDelegatesExtension =
89
+ (options: CreateDelegatesOptions = {}) =>
90
+ (pi: ExtensionAPI): void => {
91
+ const version = options.version ?? versionVerdict(readVersionSignals(resolveFromPackage));
92
+ if (version.kind === "refused") throw new Error(version.message);
93
+
94
+ const catalogue = createCatalogue(options.definitions);
95
+ const fallbackHost: HostDefaults = {
96
+ model: { provider: "", modelId: "" },
97
+ thinkingLevel: "low",
98
+ };
99
+ let currentHost: HostDefaults = fallbackHost;
100
+ const inspectorShortcut = resolveInspectShortcut(options.inspectorShortcut);
101
+ let runtime: SessionRuntime | undefined;
102
+ let gateAlerts: GateAlertWatch | undefined;
103
+ let requestAlerts: RequestAlertWatch | undefined;
104
+ const state: RevocationState = {};
105
+ let surface: "none" | "commands" | "full" = "none";
106
+ /** Runtimes whose close outlived the bound; `session_shutdown` drains them. */
107
+ const closing: SessionRuntime[] = [];
108
+
109
+ const inspectorDeps = (): InspectorCommandDeps => ({
110
+ runtime: () => runtime,
111
+ host: (ctx) => hostFor(pi, ctx, () => runtime?.log ?? nullLogSink),
112
+ shortcut: inspectorShortcut,
113
+ ...(options.inspector === undefined ? {} : { inspector: options.inspector }),
114
+ });
115
+
116
+ const stopGateAlerts = async (): Promise<void> => {
117
+ const current = gateAlerts;
118
+ gateAlerts = undefined;
119
+ await current?.close();
120
+ };
121
+
122
+ const stopRequestAlerts = async (): Promise<void> => {
123
+ const current = requestAlerts;
124
+ requestAlerts = undefined;
125
+ await current?.close();
126
+ };
127
+
128
+ const logFor = (ctx: ExtensionContext): LogSink =>
129
+ fileLogSink(join(ctx.sessionManager.getSessionDir(), "delegates.log"));
130
+
131
+ /** The store behind a refused session, opened for reading only. */
132
+ const readStore = async (ctx: ExtensionContext): Promise<SessionView | undefined> => {
133
+ const storePath = storePathFor({
134
+ sessionId: ctx.sessionManager.getSessionId(),
135
+ sessionDir: ctx.sessionManager.getSessionDir(),
136
+ cwd: ctx.cwd,
137
+ agentDir: options.agentDir ?? getAgentDir(),
138
+ });
139
+ if (!existsSync(storePath)) return undefined;
140
+ const viewer = await openReadOnlyRuntime({
141
+ storePath,
142
+ models: new HostModelAdapter(ctx.modelRegistry),
143
+ });
144
+ try {
145
+ return await viewSession(viewer);
146
+ } finally {
147
+ await viewer.close();
148
+ }
149
+ };
150
+
151
+ const registerCommands = (): void => {
152
+ if (surface !== "none") return;
153
+ surface = "commands";
154
+ registerDelegatesCommand(pi, {
155
+ definitions: catalogue.all,
156
+ log: () => nullLogSink,
157
+ revoked: () => state.verdict,
158
+ reader: readStore,
159
+ });
160
+ };
161
+
162
+ const registerFull = (): void => {
163
+ if (surface === "full") return;
164
+ surface = "full";
165
+
166
+ registerDelegatesCommand(pi, {
167
+ definitions: catalogue.all,
168
+ runtime: () => runtime,
169
+ log: () => runtime?.log ?? nullLogSink,
170
+ inspector: (ctx) => runDelegatesCommand(inspectorDeps(), ctx),
171
+ revoked: () => state.verdict,
172
+ reader: readStore,
173
+ });
174
+ registerInspectorOverlay(pi, inspectorDeps());
175
+ registerPromptSection(pi, {
176
+ catalogue,
177
+ revoked: () => state.verdict !== undefined,
178
+ });
179
+
180
+ registerDelegateTools(pi, {
181
+ runtime: () => {
182
+ if (runtime === undefined) {
183
+ throw new Error("The delegation runtime is not ready; start a session first.");
184
+ }
185
+ return runtime;
186
+ },
187
+ catalogue,
188
+ host: { model: { provider: "", modelId: "" }, thinkingLevel: "low" },
189
+ launchWaitMs: () => runtime?.config.launchWaitMs ?? DEFAULTS.launchWaitMs,
190
+ log: () => runtime?.log ?? nullLogSink,
191
+ onRunCreated: (ctx) => ensureInspector(inspectorDeps(), ctx),
192
+ });
193
+ };
194
+
195
+ pi.on("model_select", (_event, ctx) => {
196
+ currentHost = hostFrom(ctx, currentHost);
197
+ });
198
+
199
+ pi.on("thinking_level_select", (_event, ctx) => {
200
+ currentHost = hostFrom(ctx, currentHost);
201
+ });
202
+
203
+ const refuse = async (ctx: ExtensionContext, verdict: RefusedVerdict): Promise<void> => {
204
+ state.verdict = verdict;
205
+ const removed = revokeTools(pi);
206
+ reportRefusal({ ctx, verdict, removed, log: logFor(ctx) });
207
+ if (surface !== "full") {
208
+ registerCommands();
209
+ return;
210
+ }
211
+ await stopGateAlerts();
212
+ await stopRequestAlerts();
213
+ await teardownInspector({ markOff: false });
214
+ const previous = runtime;
215
+ runtime = undefined;
216
+ if (previous === undefined) return;
217
+ options.onRuntime?.(undefined);
218
+ await closeWithin(
219
+ () => previous.close(),
220
+ options.revocationCloseMs ?? REVOCATION_CLOSE_MS,
221
+ (error) => {
222
+ const log = logFor(ctx);
223
+ if (error === undefined) {
224
+ // The handle stays owned: a provider that ignores its abort keeps close pending.
225
+ closing.push(previous);
226
+ log.write("warn", "revocation.close_timeout", {
227
+ detail: "the runtime did not close within the bound; the shutdown retries it",
228
+ });
229
+ } else {
230
+ log.write("error", "revocation.close_failed", errorFields(error));
231
+ }
232
+ },
233
+ );
234
+ };
235
+
236
+ pi.on("session_start", async (event, ctx) => {
237
+ if (state.verdict !== undefined) {
238
+ // The host builds a set per session; keep the tools out of it.
239
+ revokeTools(pi);
240
+ return;
241
+ }
242
+ const verdict = coexistenceVerdict(readHostSignals(pi));
243
+ if (verdict.kind === "refused") {
244
+ await refuse(ctx, verdict);
245
+ return;
246
+ }
247
+ registerFull();
248
+ // A second start without a shutdown (a reload the host did not announce)
249
+ // must tear the previous activation down before its runtime closes.
250
+ await stopGateAlerts();
251
+ await stopRequestAlerts();
252
+ await teardownInspector({ markOff: false });
253
+ currentHost = hostFrom(ctx, fallbackHost);
254
+ const previous = runtime;
255
+ if (previous !== undefined) {
256
+ runtime = undefined;
257
+ options.onRuntime?.(undefined);
258
+ await previous.close();
259
+ }
260
+ const log = logFor(ctx);
261
+ if (version.kind === "clear" && version.note === "unverified") {
262
+ log.write("warn", "version.unverified", {
263
+ detail: "The pi-ai version could not be read; the identity check did not run.",
264
+ });
265
+ }
266
+ runtime = await openSessionRuntime({
267
+ identity: {
268
+ sessionId: ctx.sessionManager.getSessionId(),
269
+ sessionDir: ctx.sessionManager.getSessionDir(),
270
+ cwd: ctx.cwd,
271
+ agentDir: options.agentDir ?? getAgentDir(),
272
+ },
273
+ models: new HostModelAdapter(ctx.modelRegistry),
274
+ catalogue,
275
+ host: () => currentHost,
276
+ log,
277
+ projectTrusted: ctx.isProjectTrusted(),
278
+ notify: (message) => ctx.ui.notify(message, "warning"),
279
+ skills: {
280
+ cwd: ctx.cwd,
281
+ agentDir: options.agentDir ?? getAgentDir(),
282
+ skillPaths: pi.getSettings().skills ?? [],
283
+ },
284
+ });
285
+ options.onRuntime?.(runtime);
286
+ const failures = runtime.mcp.failures;
287
+ if (failures.length > 0) {
288
+ ctx.ui.notify(
289
+ `MCP servers are not connected: ${failures.map((failure) => failure.server).join(", ")}. ` +
290
+ "The log has the reason; a definition that selects their tools fails at launch.",
291
+ "warning",
292
+ );
293
+ }
294
+ try {
295
+ gateAlerts = startGateAlerts({
296
+ runtime,
297
+ host: inspectorDeps().host(ctx),
298
+ shortcut: inspectorShortcut,
299
+ });
300
+ } catch (error) {
301
+ runtime.log.write("warn", "inspector.gate_alert_failed", {
302
+ detail: error instanceof Error ? error.message : String(error),
303
+ });
304
+ }
305
+ try {
306
+ requestAlerts = startRequestAlerts({
307
+ runtime,
308
+ host: requestHostFor(ctx.mode, inspectorDeps().host(ctx), runtime.log),
309
+ });
310
+ } catch (error) {
311
+ runtime.log.write("warn", "inspector.request_alert_failed", {
312
+ detail: error instanceof Error ? error.message : String(error),
313
+ });
314
+ }
315
+ await restoreInspector(inspectorDeps(), ctx, {
316
+ reason: event.reason,
317
+ });
318
+ });
319
+
320
+ // A discovered package can register its tools after the start event, so the
321
+ // guard reads the host once more before the first turn and refuses there.
322
+ pi.on("before_agent_start", async (_event, ctx) => {
323
+ if (state.verdict !== undefined) return;
324
+ const verdict = coexistenceVerdict(readHostSignals(pi));
325
+ if (verdict.kind === "refused") await refuse(ctx, verdict);
326
+ });
327
+
328
+ pi.on("session_tree", async (_event, ctx) => {
329
+ await syncInspectorBranch(inspectorDeps(), ctx);
330
+ });
331
+
332
+ pi.on("session_shutdown", async () => {
333
+ await stopGateAlerts();
334
+ await stopRequestAlerts();
335
+ await teardownInspector({ markOff: false });
336
+ await runtime?.close();
337
+ runtime = undefined;
338
+ options.onRuntime?.(undefined);
339
+ // A close that settled after the bound was never retried by `closeWithin`.
340
+ for (const overdue of closing.splice(0)) await overdue.close();
341
+ });
342
+ };
@@ -0,0 +1,235 @@
1
+ import { BACKGROUND_CONTEXT } from "@earendil-works/chord/context";
2
+ import type { ExtensionContext, SessionEntry } from "@earendil-works/pi-coding-agent";
3
+ import { MemoryStorage } from "@earendil-works/pi-durable";
4
+ import { mkdtemp } from "node:fs/promises";
5
+ import { tmpdir } from "node:os";
6
+ import { join } from "node:path";
7
+ import { assert, it } from "@effect/vitest";
8
+ import { GateDoc, GateIndexDoc, gateKey } from "../domain/orchestration/gates.ts";
9
+ import { HostModelAdapter } from "../runtime/models.ts";
10
+ import { openSessionRuntime, type SessionRuntime } from "../runtime/session.ts";
11
+ import type { LogFields, LogLevel, LogSink } from "../runtime/log.ts";
12
+ import { makeStubPi, type StubPi } from "../../test-support/stub-pi.ts";
13
+ import { stubHostSource } from "../../test-support/stub-model-source.ts";
14
+ import { waitFor } from "../../test-support/wait.ts";
15
+ import {
16
+ GATE_ALERT_ENTRY,
17
+ hostFor,
18
+ readGateAlerts,
19
+ runDelegatesCommand,
20
+ teardownInspector,
21
+ } from "./inspector-command.ts";
22
+ import type { InspectorCommandDeps } from "./inspector-command.ts";
23
+ import { startGateAlerts } from "./gate-alerts.ts";
24
+ import { fakeObservations } from "../../test-support/fake-observations.ts";
25
+ import { inspectorClock } from "../../test-support/inspector-clock.ts";
26
+
27
+ const openRuntime = async (log?: LogSink): Promise<SessionRuntime> => {
28
+ const sessionDir = await mkdtemp(join(tmpdir(), "delegates-gate-alerts-"));
29
+ return openSessionRuntime({
30
+ identity: { sessionId: "s-1", sessionDir, cwd: sessionDir, agentDir: sessionDir },
31
+ models: new HostModelAdapter(stubHostSource()),
32
+ storage: new MemoryStorage(),
33
+ ...(log === undefined ? {} : { log }),
34
+ });
35
+ };
36
+
37
+ const seedGate = async (
38
+ runtime: SessionRuntime,
39
+ input: {
40
+ readonly runId: string;
41
+ readonly gate: string;
42
+ readonly childRunIds?: readonly string[];
43
+ },
44
+ ): Promise<void> => {
45
+ await runtime.harness.commit(async (tx) => {
46
+ const index = await tx.doc(GateIndexDoc);
47
+ const key = gateKey(input.runId, input.gate);
48
+ const doc = await tx.doc(GateDoc, key, { runId: input.runId, gate: input.gate });
49
+ doc.status = "pending";
50
+ doc.requestedAt = 1_000;
51
+ doc.childRunIds = [...(input.childRunIds ?? [])];
52
+ if (!index.keys.includes(key)) index.keys.push(key);
53
+ }, BACKGROUND_CONTEXT);
54
+ };
55
+
56
+ const seedEmptyIndex = async (runtime: SessionRuntime): Promise<void> => {
57
+ await runtime.harness.commit(async (tx) => {
58
+ await tx.doc(GateIndexDoc);
59
+ }, BACKGROUND_CONTEXT);
60
+ };
61
+
62
+ const start = (stub: StubPi, runtime: SessionRuntime) =>
63
+ startGateAlerts({
64
+ runtime,
65
+ host: hostFor(stub.api, stub.context as ExtensionContext, () => runtime.log),
66
+ shortcut: "ctrl+space",
67
+ });
68
+
69
+ it("a pending gate alerts while the inspector is off", async () => {
70
+ const stub = makeStubPi({ mode: "tui" });
71
+ const runtime = await openRuntime();
72
+ await seedEmptyIndex(runtime);
73
+ const watch = start(stub, runtime);
74
+ try {
75
+ await seedGate(runtime, {
76
+ runId: "run:fan",
77
+ gate: "deploy",
78
+ childRunIds: ["run:fan:child:0"],
79
+ });
80
+
81
+ await waitFor(() => stub.notices.length === 1, "the gate warning landed");
82
+ await waitFor(() => stub.messages.length === 1, "the gate message landed");
83
+ assert.ok(stub.notices[0]?.message.includes("gate deploy on run run:fan"));
84
+ assert.ok(stub.notices[0]?.message.includes("run:fan:child:0"));
85
+ assert.strictEqual(stub.notices[0]?.severity, "warning");
86
+ assert.strictEqual(
87
+ (stub.messages[0]?.message as { readonly customType?: string } | undefined)?.customType,
88
+ "delegates.gate",
89
+ );
90
+ assert.deepStrictEqual(stub.messages[0]?.options, {
91
+ deliverAs: "followUp",
92
+ triggerTurn: true,
93
+ });
94
+ } finally {
95
+ await watch.close();
96
+ await runtime.close();
97
+ }
98
+ });
99
+
100
+ it("closing before the index exists clears the retry", async () => {
101
+ const stub = makeStubPi({ mode: "tui" });
102
+ const runtime = await openRuntime();
103
+ const watch = start(stub, runtime);
104
+ await watch.close();
105
+ await runtime.close();
106
+ assert.deepStrictEqual(stub.notices, []);
107
+ });
108
+
109
+ it("a gate already pending when the watcher starts alerts once", async () => {
110
+ const stub = makeStubPi({ mode: "tui" });
111
+ const runtime = await openRuntime();
112
+ await seedGate(runtime, { runId: "run:fan", gate: "deploy" });
113
+ const watch = start(stub, runtime);
114
+ try {
115
+ await waitFor(() => stub.notices.length === 1, "the existing gate warning landed");
116
+ assert.strictEqual(stub.messages.length, 1);
117
+ } finally {
118
+ await watch.close();
119
+ await runtime.close();
120
+ }
121
+ });
122
+
123
+ it("the watcher attaches after the first gate creates the index", async () => {
124
+ const stub = makeStubPi({ mode: "tui" });
125
+ const runtime = await openRuntime();
126
+ const watch = start(stub, runtime);
127
+ try {
128
+ await seedGate(runtime, { runId: "run:fan", gate: "deploy" });
129
+ await waitFor(() => stub.notices.length === 1, "the retry attached and alerted", 3_000);
130
+ } finally {
131
+ await watch.close();
132
+ await runtime.close();
133
+ }
134
+ });
135
+
136
+ it("a restarted watcher does not repeat an announced gate", async () => {
137
+ const stub = makeStubPi({ mode: "tui" });
138
+ const runtime = await openRuntime();
139
+ await seedGate(runtime, { runId: "run:fan", gate: "deploy" });
140
+ const first = start(stub, runtime);
141
+ try {
142
+ await waitFor(() => stub.notices.length === 1, "the first warning landed");
143
+ } finally {
144
+ await first.close();
145
+ }
146
+
147
+ const second = start(stub, runtime);
148
+ try {
149
+ await new Promise((resolve) => setTimeout(resolve, 50));
150
+ assert.strictEqual(stub.notices.length, 1);
151
+ assert.strictEqual(stub.messages.length, 1);
152
+ assert.deepStrictEqual(
153
+ stub.entries
154
+ .filter((entry) => entry.type === "custom" && entry.customType === GATE_ALERT_ENTRY)
155
+ .map((entry) => (entry as { data?: { gateId?: string } }).data?.gateId),
156
+ ["gate:run:fan:deploy"],
157
+ );
158
+ } finally {
159
+ await second.close();
160
+ await runtime.close();
161
+ }
162
+ });
163
+
164
+ it("the active inspector does not duplicate the watcher's alert", async () => {
165
+ const stub = makeStubPi({ mode: "tui" });
166
+ const runtime = await openRuntime();
167
+ await seedEmptyIndex(runtime);
168
+ const fake = fakeObservations();
169
+ const deps: InspectorCommandDeps = {
170
+ runtime: () => runtime,
171
+ host: (ctx) => hostFor(stub.api, ctx, () => runtime.log),
172
+ shortcut: "ctrl+space",
173
+ inspector: {
174
+ observe: fake,
175
+ view: async () => ({ runs: [], lanes: [], gates: [], requests: [], reviews: [] }),
176
+ now: () => 4_000,
177
+ timers: inspectorClock(),
178
+ },
179
+ };
180
+ const watch = start(stub, runtime);
181
+ try {
182
+ await runDelegatesCommand(deps, stub.context as ExtensionContext);
183
+ await seedGate(runtime, { runId: "run:fan", gate: "deploy" });
184
+ await waitFor(() => stub.notices.length === 1, "the watcher warning landed");
185
+ assert.strictEqual(stub.messages.length, 1);
186
+ } finally {
187
+ await teardownInspector({ markOff: false });
188
+ await watch.close();
189
+ await runtime.close();
190
+ }
191
+ });
192
+
193
+ it("a rejected agent message is logged without dropping the toast", async () => {
194
+ const stub = makeStubPi({ mode: "tui" });
195
+ const runtime = await openRuntime();
196
+ const entries: { level: LogLevel; code: string; fields: LogFields }[] = [];
197
+ const sink: LogSink = {
198
+ write: (level, code, fields = {}) => {
199
+ entries.push({ level, code, fields });
200
+ },
201
+ };
202
+ const host = hostFor(stub.api, stub.context as ExtensionContext, () => sink);
203
+ const send = stub.api.sendMessage.bind(stub.api);
204
+ (stub.api as { sendMessage: unknown }).sendMessage = () => {
205
+ throw new Error("agent channel closed");
206
+ };
207
+ try {
208
+ host.notifyGate(
209
+ {
210
+ id: "gate:run:fan:deploy",
211
+ runId: "run:fan",
212
+ gate: "deploy",
213
+ childRunIds: [],
214
+ },
215
+ "ctrl+space",
216
+ );
217
+ assert.strictEqual(stub.notices.length, 1);
218
+ assert.deepStrictEqual(
219
+ entries.map((entry) => [entry.level, entry.code, entry.fields.surface]),
220
+ [["warn", "inspector.notify_failed", "agent"]],
221
+ );
222
+ } finally {
223
+ (stub.api as { sendMessage: unknown }).sendMessage = send;
224
+ await runtime.close();
225
+ }
226
+ });
227
+
228
+ it("readGateAlerts ignores malformed entries", () => {
229
+ const entries = [
230
+ { type: "custom", customType: GATE_ALERT_ENTRY, data: { gateId: "gate:one" } },
231
+ { type: "custom", customType: GATE_ALERT_ENTRY, data: { gateId: 4 } },
232
+ { type: "label" },
233
+ ] as unknown as readonly SessionEntry[];
234
+ assert.deepStrictEqual([...readGateAlerts(entries)], ["gate:one"]);
235
+ });