Skip to content
This repository was archived by the owner on Jul 13, 2026. It is now read-only.

Commit ffcc52a

Browse files
Fix round-3 audit blockers: Pi grounding gate (cortexkit#2), config-lock sync block (cortexkit#1), sentinel-on-notify-failure (cortexkit#7)
cortexkit#2 (BLOCK, was a dead counter): the Pi grounding gate incremented toolCallCount on a "tool_result_end" event that DOES NOT EXIST in Pi's vocabulary (confirmed against Pi source via the PI peer — the real tool event is tool_execution_end). The counter never fired, so every Pi refresh-primers answer was silently rejected as closed-book. Replaced it with countToolCalls(), which sums "toolCall" content parts across assistant message_end turns (role-filtered to assistant, counted on message_end not message_update), reading agent_end's authoritative array when present else the accumulated stream — robust to the tool-event name entirely. cortexkit#1 (BLOCK, unanimous): the config-location migration lock used an Atomics.wait busy-wait that could block plugin init up to ~5s under multi-instance contention (and Atomics.wait can throw on the Node main thread). Migration is not correctness-critical per run (loaders read-legacy-on-conflict when the shared base is absent), so the lock now NEVER blocks init: a live competing holder returns null immediately (skip this run, retry next init), and only a stale (crashed-holder) lock is reclaimed in a single one-shot retry. No busy-wait, no synchronous sleep. +live-holder no-block test. cortexkit#7 (fast-follow): every command path ends in throwSentinel() (the 204 that suppresses the log leak and stops the command reaching the LLM). A sendNotification throw before it would skip the sentinel, forwarding the raw command to the model plus logging an error. Wrapped sendNotification once at handler construction so a delivery failure is logged and swallowed, never preempting the sentinel (covers the handler and the standalone executeAugmentation/executeDreaming via the shared deps ref). Gate: plugin tsc clean, migrate-config-location 11/0, command-handler 20/0, Pi subagent-runner 42/0, all lint clean. Co-authored-by: Alfonso [Magic Context] <[email protected]>
1 parent 0d88107 commit ffcc52a

5 files changed

Lines changed: 152 additions & 52 deletions

File tree

‎packages/pi-plugin/src/subagent-runner.test.ts‎

Lines changed: 22 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -406,29 +406,43 @@ describe("PiSubagentRunner spawn lifecycle", () => {
406406
meta: { stderr: undefined },
407407
});
408408
});
409-
it("counts tool_result_end events into toolCallCount (refresh-primers grounding gate)", async () => {
409+
it("counts toolCall content parts from assistant message_end into toolCallCount (grounding gate)", async () => {
410410
// The grounding gate (refresh-primers) treats toolCallCount === 0 as a
411-
// closed-book paraphrase and refuses to commit. Pi's facade carries only
412-
// the final assistant text, so the runner must surface the investigation
413-
// count for that gate to work on Pi at all.
411+
// closed-book paraphrase and refuses to commit. The count is derived from
412+
// `toolCall` CONTENT parts on assistant message_end turns — NOT a tool
413+
// event name. Pi has no `tool_result_end` (its real tool event is
414+
// `tool_execution_end`), so content-part counting is robust to event-name
415+
// drift. (Confirmed against Pi source via the PI peer.)
414416
const child = createMockChild();
415417
const { runner } = runnerWith(child);
416418

417419
const resultPromise = runner.run(baseOptions);
420+
// Two intermediate tool-calling assistant turns (one toolCall part each).
418421
child.writeStdoutLine({
419-
type: "tool_result_end",
422+
type: "message_end",
423+
message: {
424+
role: "assistant",
425+
content: [{ type: "toolCall", toolName: "read", toolCallId: "c1" }],
426+
stopReason: "toolUse",
427+
},
428+
});
429+
// A toolResult message_end (role: "tool") must NOT be counted.
430+
child.writeStdoutLine({
431+
type: "message_end",
420432
message: {
421433
role: "tool",
422434
content: [{ type: "toolResult", text: "read ok" }],
423435
},
424436
});
425437
child.writeStdoutLine({
426-
type: "tool_result_end",
438+
type: "message_end",
427439
message: {
428-
role: "tool",
429-
content: [{ type: "toolResult", text: "grep ok" }],
440+
role: "assistant",
441+
content: [{ type: "toolCall", toolName: "grep", toolCallId: "c2" }],
442+
stopReason: "toolUse",
430443
},
431444
});
445+
// Terminal assistant turn: text only, no toolCall → not counted.
432446
child.writeStdoutLine({
433447
type: "message_end",
434448
message: {

‎packages/pi-plugin/src/subagent-runner.ts‎

Lines changed: 44 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -508,10 +508,14 @@ export class PiSubagentRunner implements SubagentRunner {
508508
let finalStopReason: string | null = null;
509509
let sawAgentEnd = false;
510510
let parseError: string | null = null;
511-
// Count tool invocations across the run so callers that gate on
512-
// "the agent actually investigated" (refresh-primers grounding gate)
513-
// work on Pi, whose result otherwise carries only the final text.
514-
let toolCallCount = 0;
511+
// Tool-invocation count for the grounding gate (refresh-primers:
512+
// 0 tool calls = closed-book paraphrase, rejected). Derived at settle
513+
// from the accumulated assistant message CONTENT (toolCall parts) via
514+
// countToolCalls — NOT from a discrete tool-event, since Pi's --print
515+
// stdout has no reliable tool-completion event name. The authoritative
516+
// source is agent_end's full message array when present, else the
517+
// accumulated message_end messages.
518+
let agentEndMessages: unknown[] | null = null;
515519

516520
// Terminal-drain state. Set when we detect the final assistant
517521
// turn, used to short-circuit the full-timeout wait on Pi's
@@ -619,6 +623,7 @@ export class PiSubagentRunner implements SubagentRunner {
619623
// it as authoritative. Older Pi versions may have done this.
620624
if (e.type === "agent_end" && Array.isArray(e.messages)) {
621625
sawAgentEnd = true;
626+
agentEndMessages = e.messages;
622627
const result = extractFinalAssistant(e.messages);
623628
finalAssistantText = result.text;
624629
finalStopReason = result.stopReason;
@@ -681,14 +686,6 @@ export class PiSubagentRunner implements SubagentRunner {
681686
}
682687
}
683688

684-
if (e.type === "tool_result_end" && e.message) {
685-
accumulatedMessages.push(e.message);
686-
// Each completed tool result is one investigation step. Used by
687-
// the grounding gate (count > 0 = real investigation, not a
688-
// closed-book paraphrase).
689-
toolCallCount += 1;
690-
}
691-
692689
// Pi's print mode finishes the agent loop but does NOT always
693690
// exit the child process cleanly afterwards — observed
694691
// pattern: assistant message_end with stopReason="stop"
@@ -831,7 +828,12 @@ export class PiSubagentRunner implements SubagentRunner {
831828
settle({
832829
ok: true,
833830
assistantText: trimmedAssistantText,
834-
toolCallCount,
831+
// Prefer agent_end's authoritative full array; else the
832+
// accumulated message_end stream. Counting toolCall content
833+
// parts is event-name-independent (see countToolCalls).
834+
toolCallCount: countToolCalls(
835+
agentEndMessages ?? accumulatedMessages,
836+
),
835837
durationMs: Date.now() - startTime,
836838
meta: { stderr: stderr.length > 0 ? stderr : undefined },
837839
});
@@ -1098,6 +1100,35 @@ export function extractFinalAssistant(messages: unknown[]): {
10981100
return { text: null, stopReason: null, errorMessage: null };
10991101
}
11001102

1103+
/**
1104+
* Count tool invocations across a run from the assistant messages themselves —
1105+
* each `toolCall` content part is one invocation. We derive the count from
1106+
* message CONTENT (which `message_end` always carries, and `agent_end` carries
1107+
* in its final array) rather than a discrete tool-completion EVENT, because
1108+
* Pi's --print stdout vocabulary is message_start / message_end /
1109+
* tool_execution_* (no `tool_result_end`), so keying on an event name is
1110+
* fragile. The grounding gate only needs "did the agent call tools at all"
1111+
* (count > 0), so counting requested toolCall parts is the robust signal.
1112+
*/
1113+
export function countToolCalls(messages: unknown[]): number {
1114+
let count = 0;
1115+
for (const msg of messages) {
1116+
if (typeof msg !== "object" || msg === null) continue;
1117+
const m = msg as { role?: string; content?: unknown };
1118+
if (m.role !== "assistant" || !Array.isArray(m.content)) continue;
1119+
for (const part of m.content) {
1120+
if (
1121+
typeof part === "object" &&
1122+
part !== null &&
1123+
(part as { type?: unknown }).type === "toolCall"
1124+
) {
1125+
count += 1;
1126+
}
1127+
}
1128+
}
1129+
return count;
1130+
}
1131+
11011132
export function parsePiEventLine(
11021133
line: string,
11031134
): { ok: true; event: unknown } | { ok: false; error: string } {

‎packages/plugin/src/config/migrate-config-location.test.ts‎

Lines changed: 48 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,13 @@
11
import { describe, expect, it } from "bun:test";
2-
import { existsSync, mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from "node:fs";
2+
import {
3+
existsSync,
4+
mkdirSync,
5+
mkdtempSync,
6+
readFileSync,
7+
rmSync,
8+
utimesSync,
9+
writeFileSync,
10+
} from "node:fs";
311
import { tmpdir } from "node:os";
412
import { join } from "node:path";
513
import {
@@ -34,32 +42,64 @@ describe("migrateConfigFile (location migration)", () => {
3442
}
3543
});
3644

37-
it("reclaims a stale (crashed-holder) lock within a bounded budget instead of freezing or throwing", () => {
45+
it("reclaims a stale (crashed-holder) lock in one shot without blocking init", () => {
3846
const dir = tmp();
3947
try {
4048
const target = join(dir, ".cortexkit", "magic-context.jsonc");
4149
const legacy = join(dir, "magic-context.jsonc");
4250
writeFileSync(legacy, '{"enabled":false}');
43-
// A leftover lock dir from a crashed holder. The old design (60s
44-
// stale / 30s timeout) made reclaim unreachable — a waiter froze
45-
// init for 30s then THREW. The fix keeps stale < timeout so the
46-
// waiter reclaims and proceeds, bounded and never throwing.
47-
mkdirSync(`${target}.lock`, { recursive: true });
51+
// A leftover lock dir from a crashed holder, aged past the stale
52+
// threshold. The non-blocking lock removes it and re-attempts mkdir
53+
// once (no busy-wait, no synchronous sleep), so migration proceeds
54+
// and init is never frozen.
55+
const lockDir = `${target}.lock`;
56+
mkdirSync(lockDir, { recursive: true });
57+
// Backdate the lock dir's mtime well past CONFIG_LOCK_STALE_MS (4s).
58+
const old = Date.now() - 60_000;
59+
utimesSync(lockDir, new Date(old), new Date(old));
4860
const start = Date.now();
4961
const r = migrateConfigFile({
5062
scope: "project",
5163
targetPath: target,
5264
legacySources: [src(legacy)],
5365
});
5466
const elapsed = Date.now() - start;
55-
expect(elapsed).toBeLessThan(8_000);
67+
// Effectively instant — no timeout budget is ever waited.
68+
expect(elapsed).toBeLessThan(1_000);
5669
expect(r.migrated).toBe(true);
5770
expect(existsSync(target)).toBe(true);
5871
} finally {
5972
rmSync(dir, { recursive: true, force: true });
6073
}
6174
});
6275

76+
it("skips migration this run (no block) when a LIVE holder owns the lock", () => {
77+
const dir = tmp();
78+
try {
79+
const target = join(dir, ".cortexkit", "magic-context.jsonc");
80+
const legacy = join(dir, "magic-context.jsonc");
81+
writeFileSync(legacy, '{"enabled":false}');
82+
// A FRESH lock dir (live holder, not stale): we must not block waiting
83+
// for it — return immediately with migrated:false and leave the
84+
// target absent (the loader read-legacy-on-conflict covers this run;
85+
// the next init retries once the holder releases).
86+
mkdirSync(`${target}.lock`, { recursive: true });
87+
const start = Date.now();
88+
const r = migrateConfigFile({
89+
scope: "project",
90+
targetPath: target,
91+
legacySources: [src(legacy)],
92+
});
93+
const elapsed = Date.now() - start;
94+
expect(elapsed).toBeLessThan(1_000);
95+
expect(r.migrated).toBe(false);
96+
expect(r.conflict).toBe(false);
97+
expect(existsSync(target)).toBe(false);
98+
} finally {
99+
rmSync(dir, { recursive: true, force: true });
100+
}
101+
});
102+
63103
it("moves a single legacy source to the target and leaves a .MOVED_READPLEASE marker", () => {
64104
const dir = tmp();
65105
try {

‎packages/plugin/src/config/migrate-config-location.ts‎

Lines changed: 17 additions & 23 deletions
Original file line numberDiff line numberDiff line change
@@ -280,31 +280,23 @@ function fileSemanticsMatch(a: string, b: string): boolean {
280280

281281
// ── Cross-process lock (Desktop runs many instances concurrently) ────────────
282282

283-
function sleepSync(ms: number): void {
284-
Atomics.wait(new Int32Array(new SharedArrayBuffer(4)), 0, 0, ms);
285-
}
286-
287283
// A real migration is a sub-second rename+write, so a lock older than this was
288-
// almost certainly left by a crashed holder and is safe to reclaim. Kept BELOW
289-
// the overall timeout so stale reclaim is actually reachable within one waiter's
290-
// budget (the previous 60s-stale / 30s-timeout pair made reclaim unreachable).
284+
// almost certainly left by a crashed holder and is safe to reclaim.
291285
const CONFIG_LOCK_STALE_MS = 4_000;
292-
// Hard cap on how long acquisition may block plugin init. Migration is NOT
293-
// correctness-critical this run — the loaders read-legacy-on-conflict when the
294-
// CortexKit base is absent — so on timeout we SKIP (return null) rather than
295-
// freeze init: another instance is migrating, or the next init retries.
296-
const CONFIG_LOCK_TIMEOUT_MS = 5_000;
297286

298287
/**
299288
* Directory-mkdir lock. `mkdir` is atomic; EEXIST means another instance holds
300-
* it — busy-wait with a stale-reclaim (a crashed holder's dir is removed) and a
301-
* short overall timeout. Returns the release fn, or null on timeout (caller
302-
* skips migration this run). The loser that does acquire then sees
303-
* target-exists+matches (no-op) or the source already renamed away.
289+
* it. We do NOT block plugin init: migration is not correctness-critical this
290+
* run (the loaders read-legacy-on-conflict when the CortexKit base is absent),
291+
* so on a LIVE competing holder we return null immediately and skip migration
292+
* this run — the holder finishes its sub-second rename+write, and the next init
293+
* sees target-present and consolidates. The ONLY retry is a single one-shot
294+
* stale reclaim: a crashed holder's lock dir (older than the stale threshold) is
295+
* removed and we re-attempt mkdir once. No busy-wait, no synchronous sleep — the
296+
* init path never blocks on lock contention.
304297
*/
305298
function acquireConfigMigrationLock(lockDir: string): (() => void) | null {
306-
const deadline = Date.now() + CONFIG_LOCK_TIMEOUT_MS;
307-
while (true) {
299+
for (let attempt = 0; attempt < 2; attempt++) {
308300
try {
309301
mkdirSync(lockDir, { recursive: false });
310302
return () => {
@@ -317,21 +309,23 @@ function acquireConfigMigrationLock(lockDir: string): (() => void) | null {
317309
} catch (err) {
318310
const code = (err as { code?: unknown })?.code;
319311
if (code !== "EEXIST") throw err;
312+
// EEXIST: another instance holds the lock. Reclaim ONLY if it's stale
313+
// (crashed holder) and retry mkdir once; otherwise a live holder owns
314+
// it → skip this run rather than block init.
320315
try {
321316
const ageMs = Date.now() - statSync(lockDir).mtimeMs;
322317
if (ageMs > CONFIG_LOCK_STALE_MS) {
323318
rmSync(lockDir, { recursive: true, force: true });
324319
continue;
325320
}
326321
} catch {
327-
// Lock vanished between attempts — retry immediately.
328-
}
329-
if (Date.now() >= deadline) {
330-
return null;
322+
// Lock vanished between stat and now — retry mkdir once.
323+
continue;
331324
}
332-
sleepSync(25);
325+
return null;
333326
}
334327
}
328+
return null;
335329
}
336330

337331
// ── Atomic writes ────────────────────────────────────────────

‎packages/plugin/src/hooks/magic-context/command-handler.ts‎

Lines changed: 21 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -406,6 +406,27 @@ export function createMagicContextCommandHandler(deps: {
406406
runManual: (task?: DreamTaskName) => Promise<ManualRunResult>;
407407
};
408408
}) {
409+
// Notification delivery MUST NOT bypass the sentinel. Every command path
410+
// ends in throwSentinel() (the 204 that suppresses the error-log leak and
411+
// stops the command reaching the LLM). If sendNotification throws — RPC down,
412+
// client gone, transient post failure — that throw would skip the pending
413+
// throwSentinel and the raw command would be forwarded to the model (and a
414+
// real error logged). Wrap it once so a delivery failure is logged and
415+
// swallowed, never preempting the sentinel. Reassigning the deps method
416+
// covers the handler AND the standalone executeAugmentation/executeDreaming,
417+
// which receive this same deps reference.
418+
const rawSendNotification = deps.sendNotification;
419+
deps.sendNotification = async (sessionId, text, params) => {
420+
try {
421+
await rawSendNotification(sessionId, text, params);
422+
} catch (err) {
423+
sessionLog(
424+
sessionId,
425+
`command notification delivery failed (continuing to sentinel): ${err instanceof Error ? err.message : String(err)}`,
426+
);
427+
}
428+
};
429+
409430
const isStatusCommand = (command: string): boolean => command === "ctx-status";
410431
const isFlushCommand = (command: string): boolean => command === "ctx-flush";
411432
const isRecompCommand = (command: string): boolean => command === "ctx-recomp";

0 commit comments

Comments
 (0)