repositories / dotfiles

dotfiles

bugabingas dorkfiles

owned by bugabinga

rework devil debate sessions

641f91c882e4325e48062801be26a46622406b10

Oliver Jan Krylow <oliver@bugabinga.net> ·

unsigned

Browse filesCompare with HEAD

Changed files (2)

pi/agent/extensions/devil/README.md

Modified
22 22 | Aspect | Behavior |
23 23 |--------|----------|
24 24 | Session state | Stateless. Each debate is independent. |
25 -| Conversation context | Automatically includes working dir, recent conversation, current contents of recently touched files. |
25 +| Conversation context | Includes cwd, system prompt, context usage, recent conversation, and current contents of recently touched files. |
26 26 | Model | Uses `devil.model` if configured, else current model. |
27 27 | UI | Opens interactive progress UI, then result editor. |
28 -| Results | Edited verdict is appended as `devil-result` session state and submitted as user text. |
28 +| Results | Edited verdict is appended as `devil-result`; main agent receives it as advisory-only and must ask approval before edits. |
30 30 ## Configuration
36 36 "devil": {
37 37 "model": "zai/glm-5.1",
38 - "maxRounds": 5,
38 + "maxRounds": 2,
39 39 "stoppingConditions": "consensus",
40 40 "concessionThreshold": 0.7,
41 41 "onBlocking": "surface"
46 46 CLI flags:
48 48 ```bash
49 -pi --devil-max-rounds 3 --devil-stop max_rounds
49 +pi --devil-rounds 3 --devil-stop max_rounds
52 +Debate sub-agents run from an ephemeral current-branch Pi session. They load normal Pi resources/extensions and can use every available tool except `write` and `edit`.
52 54 ## Output
54 56 Synthesis includes:

pi/agent/extensions/devil/index.ts

Modified
12 12 * "devil": {
13 13 * "model": "zai/glm-5.1", // Optional: specific model
14 - * "maxRounds": 5, // Maximum debate rounds
14 + * "maxRounds": 2, // Maximum debate rounds
15 15 * "stoppingConditions": "consensus", // consensus | blocking_found | max_rounds
16 16 * "concessionThreshold": 0.7, // 0.0-1.0 for concession detection
17 17 * "onBlocking": "surface" // surface | escalate | ignore
22 -import * as fs from "node:fs";
23 -import * as path from "node:path";
24 -import { complete } from "@earendil-works/pi-ai";
22 +import { chmodSync, mkdtempSync, readdirSync, rmSync, statSync, writeFileSync } from "node:fs";
23 +import { tmpdir } from "node:os";
24 +import { join } from "node:path";
25 +import { randomUUID } from "node:crypto";
26 +import { complete, type Model } from "@earendil-works/pi-ai";
25 27 import {
26 - convertToLlm,
27 - serializeConversation,
28 + createAgentSession,
29 + DefaultResourceLoader,
30 + getAgentDir,
31 + SessionManager,
32 + SettingsManager,
28 33 } from "@earendil-works/pi-coding-agent";
29 34 import type {
30 35 ExtensionAPI,
31 36 ExtensionContext,
32 - Model,
33 - SessionEntry,
34 37 } from "@earendil-works/pi-coding-agent";
35 38 import type { Theme } from "@earendil-works/pi-coding-agent";
36 39 import {
56 59 CONSENSUS_ROUNDS_REQUIRED,
57 60 } from "./helpers";
62 +type AnyModel = Model<any>;
59 64 const DEVIL_SYSTEM_PROMPT = `Devil advocate. STRESS TEST ideas. Find blocking issues.
61 66 CLASSIFICATION:
121 126 - Otherwise: "proceed_with_caution"`;
123 128 // Default settings
124 -const DEFAULT_MAX_ROUNDS = 5;
129 +const DEFAULT_MAX_ROUNDS = 2;
125 130 const DEFAULT_STOPPING_CONDITIONS = "consensus";
126 131 const DEFAULT_CONCESSION_THRESHOLD = 0.7;
127 132 const DEFAULT_ON_BLOCKING = "surface";
135 140 onBlocking?: "surface" | "escalate" | "ignore";
143 +interface SettingsAPI extends ExtensionAPI {
144 + settingsManager?: { getSettings(): Record<string, unknown> | undefined };
138 147 interface SynthesisResult {
139 148 recommendation: "proceed" | "proceed_with_caution" | "revise" | "abandon";
140 149 summary: string;
148 157 interface RunDebateOptions {
149 158 idea: string;
150 159 context?: Record<string, string>;
151 - model: Model;
160 + model: AnyModel;
161 + ctx: ExtensionContext;
152 162 apiKey: string;
153 163 headers?: Record<string, string>;
154 164 maxRounds: number;
156 166 concessionThreshold: number;
157 167 signal?: AbortSignal;
158 168 onStatus?: (status: string, round: number, maxRounds: number, blocking: number) => void;
169 + /** Fires while either agent streams */
170 + onPartial?: (
171 + role: DebateRole,
172 + round: number,
173 + maxRounds: number,
174 + blocking: number,
175 + text: string,
176 + ) => void;
159 177 /** Fires after devil responds, before proposer responds (mid-round update) */
160 178 onChallenge?: (
161 179 round: number,
181 199 round: number;
182 200 text: string;
183 201 blocking: number;
202 + final: boolean;
186 205 interface DebateLiveState {
196 215 // ── Helpers ───────────────────────────────────────────────────────────
198 -const MAX_FILE_CHARS = 3000; // per-file cap for context injection
199 -const MAX_FILES = 10; // max files to include
200 -const FILE_TOOL_NAMES = new Set(["read", "edit", "write"]);
202 -interface ToolCallBlock {
203 - type: "toolCall";
204 - name: string;
205 - arguments: Record<string, unknown>;
217 +const DISABLED_SUBAGENT_TOOLS = new Set(["write", "edit"]);
218 +const DEVIL_TMP_PREFIX = "pi-devil-";
219 +const DEVIL_TMP_TTL_MS = 24 * 60 * 60 * 1000;
208 221 export function createDebateState(idea: string, maxRounds: number): DebateLiveState {
209 222 return {
228 241 state.blocking = blocking;
231 -function addDebateEntry(
244 +function upsertDebateEntry(
232 245 state: DebateLiveState,
233 246 role: DebateRole,
234 247 round: number,
235 248 blocking: number,
236 249 text: string,
250 + final: boolean,
238 252 state.currentRound = round;
239 253 state.blocking = blocking;
240 - state.entries.push({ role, round, blocking, text });
254 + const existing = state.entries.find((entry) => entry.role === role && entry.round === round);
255 + if (existing) {
256 + existing.blocking = blocking;
257 + existing.text = text;
258 + existing.final = final;
259 + return;
261 + state.entries.push({ role, round, blocking, text, final });
243 264 // ── State helpers ───────────────────────────────────────────────────
280 301 for (const entry of entries) {
281 302 const icon = entry.role === "devil" ? "⚑" : "✓";
282 303 const label = entry.role === "devil" ? "Devil" : "Defense";
283 - lines.push(theme.fg(entry.role === "devil" ? "warning" : "success", truncateToWidth(`${icon} R${entry.round} ${label}`, usableWidth)));
304 + const stateLabel = entry.final ? "final" : "streaming…";
305 + lines.push(theme.fg(entry.role === "devil" ? "warning" : "success", truncateToWidth(`${icon} R${entry.round} ${label} · ${stateLabel}`, usableWidth)));
285 307 const bodyWidth = Math.max(1, usableWidth - 2);
286 308 const body = cleanTranscriptText(entry.text, options.compact ? 700 : 20000);
350 372 this.refresh();
351 373 return;
353 - if (matchesKey(data, "pageup") || matchesKey(data, "ctrl+u")) {
375 + if (matchesKey(data, "pageUp") || matchesKey(data, "ctrl+u")) {
354 376 this.followMode = false;
355 377 this.scrollOffset = Math.max(0, this.scrollOffset - 10);
356 378 this.refresh();
357 379 return;
359 - if (matchesKey(data, "pagedown") || matchesKey(data, "ctrl+d")) {
381 + if (matchesKey(data, "pageDown") || matchesKey(data, "ctrl+d")) {
360 382 this.scrollOffset += 10;
361 383 this.refresh();
362 384 return;
438 460 function gatherContext(ctx: ExtensionContext): Record<string, string> {
439 - const context: Record<string, string> = {};
440 - context["working_directory"] = ctx.cwd;
442 - const branch = ctx.sessionManager.getBranch();
444 - // ── Part 1: Extract file paths from assistant toolCall blocks, read current contents ──
445 - // Tool arguments (file paths) live in assistant messages' content[type=toolCall].arguments
446 - // NOT in toolResult messages (those only have output text, no input).
447 - // Pattern from summarize.ts: scan assistant content for toolCall blocks.
448 - const filePaths = new Set<string>();
450 - for (const entry of branch) {
451 - if (entry.type !== "message") continue;
452 - const msg = entry.message;
453 - if (!msg || msg.role !== "assistant" || !Array.isArray(msg.content)) continue;
455 - for (const block of msg.content) {
456 - const tc = block as ToolCallBlock;
457 - if (tc.type !== "toolCall" || !FILE_TOOL_NAMES.has(tc.name)) continue;
459 - // read/edit/write all use "path" (edit may also have "file_path" in older sessions)
460 - const filePath = (tc.arguments.path ?? tc.arguments.file_path) as string | undefined;
461 - if (typeof filePath !== "string" || !filePath.trim()) continue;
463 - const resolved = path.resolve(ctx.cwd, filePath.trim());
464 - try {
465 - if (fs.existsSync(resolved) && fs.statSync(resolved).isFile()) {
466 - filePaths.add(resolved);
467 - }
468 - } catch {
469 - // skip inaccessible files
470 - }
471 - }
472 - }
474 - if (filePaths.size > 0) {
475 - const files = [...filePaths].slice(0, MAX_FILES);
476 - const fileContents = files
477 - .map((fp) => {
478 - try {
479 - let content = fs.readFileSync(fp, "utf-8");
480 - if (content.length > MAX_FILE_CHARS) {
481 - content = content.slice(0, MAX_FILE_CHARS) + "\n... (truncated)";
482 - }
483 - const rel = path.relative(ctx.cwd, fp);
484 - return `### ${rel}\n\`\`\`\n${content}\n\`\`\``;
485 - } catch {
486 - return null;
487 - }
488 - })
489 - .filter((c): c is string => c !== null);
490 - if (fileContents.length > 0) {
491 - context["relevant_files"] = fileContents.join("\n\n");
492 - }
493 - }
495 - // ── Part 2: Recent conversation (last 20 messages) ──
496 - const messages = branch
497 - .filter(
498 - (entry): entry is SessionEntry & { type: "message" } =>
499 - entry.type === "message",
500 - )
501 - .map((entry) => entry.message);
503 - if (messages.length > 0) {
504 - const recent = messages.slice(-20);
505 - const llmMessages = convertToLlm(recent);
506 - context["conversation"] = serializeConversation(llmMessages);
507 - }
461 + const context: Record<string, string> = {
462 + working_directory: ctx.cwd,
463 + session_context: "This debate runs in an ephemeral full fork of the current Pi session. Use the existing conversation, tool results, context files, skills, and loaded extensions already present in this fork.",
464 + };
465 + const usage = ctx.getContextUsage();
466 + if (usage) context["context_usage"] = JSON.stringify(usage);
509 467 return context;
470 +function gcEphemeralForks() {
471 + const now = Date.now();
472 + for (const name of readdirSync(tmpdir())) {
473 + if (!name.startsWith(DEVIL_TMP_PREFIX)) continue;
474 + const dir = join(tmpdir(), name);
475 + try {
476 + if (now - statSync(dir).mtimeMs > DEVIL_TMP_TTL_MS) rmSync(dir, { recursive: true, force: true });
477 + } catch {}
481 +function createEphemeralFork(ctx: ExtensionContext): { manager: SessionManager; cleanup: () => void } {
482 + const dir = mkdtempSync(join(tmpdir(), DEVIL_TMP_PREFIX));
483 + chmodSync(dir, 0o700);
484 + const file = join(dir, "branch.jsonl");
485 + const header = ctx.sessionManager.getHeader() ?? {
486 + type: "session",
487 + version: 3,
488 + id: randomUUID(),
489 + timestamp: new Date().toISOString(),
490 + cwd: ctx.cwd,
491 + };
492 + const entries = [
493 + { ...header, cwd: ctx.cwd, parentSession: ctx.sessionManager.getSessionFile() },
494 + ...ctx.sessionManager.getBranch(),
495 + ];
496 + writeFileSync(file, entries.map((entry) => JSON.stringify(entry)).join("\n") + "\n", { encoding: "utf-8", mode: 0o600 });
498 + return {
499 + manager: SessionManager.open(file, dir, ctx.cwd),
500 + cleanup: () => rmSync(dir, { recursive: true, force: true }),
501 + };
514 504 function formatSynthesis(s: SynthesisResult): string {
515 505 const recEmoji: Record<string, string> = {
550 540 function resolveDebateModel(
551 541 ctx: ExtensionContext,
552 542 modelSetting?: string,
553 -): Model | null {
543 +): AnyModel | null {
554 544 const current = ctx.model ?? null;
556 546 if (modelSetting) {
614 604 // ── Debate orchestration ────────────────────────────────────────────
606 +function extractAssistantText(messages: Array<{ role?: string; content?: unknown }>): string {
607 + const chunks = messages
608 + .filter((message) => message.role === "assistant")
609 + .map((message) => textFromContent(message.content as Array<{ type: string; text?: string }>).trim())
610 + .filter(Boolean);
611 + return chunks.at(-1) ?? chunks.join("\n\n");
614 +async function runRoleAgent(opts: {
615 + ctx: ExtensionContext;
616 + model: AnyModel;
617 + systemPrompt: string;
618 + userPrompt: string;
619 + signal?: AbortSignal;
620 + onTool?: (toolName: string) => void;
621 + onText?: (text: string) => void;
622 + onStatus?: (status: string) => void;
623 +}): Promise<string> {
624 + const agentDir = getAgentDir();
625 + opts.onStatus?.("loading settings");
626 + const settingsManager = SettingsManager.create(opts.ctx.cwd, agentDir);
627 + const loader = new DefaultResourceLoader({
628 + cwd: opts.ctx.cwd,
629 + agentDir,
630 + settingsManager,
631 + systemPromptOverride: (base) => [base, opts.systemPrompt].filter(Boolean).join("\n\n"),
632 + });
633 + opts.onStatus?.("loading extensions/resources");
634 + await loader.reload();
636 + opts.onStatus?.("forking session");
637 + const fork = createEphemeralFork(opts.ctx);
638 + opts.onStatus?.("starting sub-agent");
639 + const { session } = await createAgentSession({
640 + cwd: opts.ctx.cwd,
641 + agentDir,
642 + model: opts.model,
643 + thinkingLevel: "medium",
644 + modelRegistry: opts.ctx.modelRegistry,
645 + resourceLoader: loader,
646 + sessionManager: fork.manager,
647 + settingsManager,
648 + });
649 + await session.bindExtensions({});
650 + opts.onStatus?.("selecting tools");
652 + const activeTools = session
653 + .getAllTools()
654 + .map((tool) => tool.name)
655 + .filter((name) => !DISABLED_SUBAGENT_TOOLS.has(name));
656 + session.setActiveToolsByName(activeTools);
658 + const before = session.messages.length;
659 + let streamed = "";
660 + let lastEmit = 0;
661 + const emitText = (force = false) => {
662 + const now = Date.now();
663 + if (!force && now - lastEmit < 80) return;
664 + lastEmit = now;
665 + if (streamed.trim()) opts.onText?.(streamed);
666 + };
667 + const unsubscribe = session.subscribe((event) => {
668 + if (event.type === "tool_execution_start") opts.onTool?.(event.toolName);
669 + if (event.type === "message_update" && event.assistantMessageEvent.type === "text_delta") {
670 + streamed += event.assistantMessageEvent.delta;
671 + emitText();
673 + });
674 + const abort = () => void session.abort();
675 + opts.signal?.addEventListener("abort", abort, { once: true });
677 + try {
678 + opts.onStatus?.("streaming");
679 + await session.prompt(opts.userPrompt, { source: "extension" });
680 + const text = extractAssistantText(session.messages.slice(before)) || streamed;
681 + if (text) opts.onText?.(text);
682 + return text || "No response.";
683 + } finally {
684 + opts.signal?.removeEventListener("abort", abort);
685 + unsubscribe();
686 + session.dispose();
687 + fork.cleanup();
615 691 async function runRound(
616 692 round: number,
617 693 maxRounds: number,
618 694 idea: string,
619 695 contextText: string,
620 696 roundHistory: string,
621 - model: Model,
622 - apiKey: string,
623 - headers: Record<string, string> | undefined,
697 + model: AnyModel,
698 + ctx: ExtensionContext,
624 699 signal: AbortSignal | undefined,
625 700 onStatus: RunDebateOptions["onStatus"],
701 + onChallenge: RunDebateOptions["onChallenge"],
702 + onPartial: RunDebateOptions["onPartial"],
626 703 ): Promise<{
627 704 devilOutput: string;
628 705 proposerOutput: string;
632 709 onStatus?.(`Round ${round}/${maxRounds} · devil challenging`, round, maxRounds, 0);
634 711 const devilUserText = buildRoundPrompt(round, maxRounds, idea, contextText, roundHistory);
635 - const devilResponse = await complete(model, { systemPrompt: DEVIL_SYSTEM_PROMPT, messages: [{ role: "user", content: [{ type: "text", text: devilUserText }], timestamp: Date.now() }] }, { apiKey, headers, signal });
636 - const devilOutput = textFromContent(devilResponse.content);
712 + const devilOutput = await runRoleAgent({
713 + ctx,
714 + model,
715 + systemPrompt: DEVIL_SYSTEM_PROMPT,
716 + userPrompt: devilUserText,
717 + signal,
718 + onStatus: (phase) => onStatus?.(`Round ${round}/${maxRounds} · Devil ${phase}`, round, maxRounds, 0),
719 + onTool: (toolName) => onStatus?.(`Round ${round}/${maxRounds} · Devil using ${toolName}`, round, maxRounds, 0),
720 + onText: (text) => onPartial?.("devil", round, maxRounds, countBlockingIssues(text), text),
721 + });
637 722 const roundBlockingCount = countBlockingIssues(devilOutput);
723 + onChallenge?.(round, maxRounds, roundBlockingCount, devilOutput);
639 - onStatus?.(`Round ${round}/${maxRounds} · proposer defending`, round, maxRounds, roundBlockingCount);
725 + onStatus?.(`Round ${round}/${maxRounds} · Defense starting`, round, maxRounds, roundBlockingCount);
641 727 const proposerUserText = buildProposerPrompt(idea, roundHistory, round, devilOutput);
642 - const proposerResponse = await complete(model, { systemPrompt: PROPOSER_SYSTEM_PROMPT, messages: [{ role: "user", content: [{ type: "text", text: proposerUserText }], timestamp: Date.now() }] }, { apiKey, headers, signal });
643 - const proposerOutput = textFromContent(proposerResponse.content);
728 + const proposerOutput = await runRoleAgent({
729 + ctx,
730 + model,
731 + systemPrompt: PROPOSER_SYSTEM_PROMPT,
732 + userPrompt: proposerUserText,
733 + signal,
734 + onStatus: (phase) => onStatus?.(`Round ${round}/${maxRounds} · Defense ${phase}`, round, maxRounds, roundBlockingCount),
735 + onTool: (toolName) => onStatus?.(`Round ${round}/${maxRounds} · Defense using ${toolName}`, round, maxRounds, roundBlockingCount),
736 + onText: (text) => onPartial?.("proposer", round, maxRounds, roundBlockingCount, text),
737 + });
645 739 return { devilOutput, proposerOutput, roundBlockingCount, aborted: !!signal?.aborted };
649 743 async function synthesizeDebate(
650 744 idea: string,
651 745 roundsData: string[],
652 - model: Model,
746 + model: AnyModel,
653 747 apiKey: string,
654 748 headers: Record<string, string> | undefined,
655 749 signal: AbortSignal | undefined,
675 769 // ── Core debate logic ─────────────────────────────────────────────────
677 771 async function runDebate(opts: RunDebateOptions): Promise<DebateOutput> {
678 - const { idea, context, model, apiKey, headers, maxRounds, stoppingConditions, concessionThreshold, signal, onStatus, onChallenge, onRound } = opts;
772 + const { idea, context, model, ctx, apiKey, headers, maxRounds, stoppingConditions, concessionThreshold, signal, onStatus, onChallenge, onPartial, onRound } = opts;
680 774 const contextText = buildContextText(context);
681 775 const roundsData: string[] = [];
689 783 if (earlyExit) return earlyExit;
691 785 const { devilOutput, proposerOutput, roundBlockingCount, aborted } = await runRound(
692 - round, maxRounds, idea, contextText, roundHistory, model, apiKey, headers, signal, onStatus,
786 + round, maxRounds, idea, contextText, roundHistory, model, ctx, signal, onStatus, onChallenge, onPartial,
694 788 if (aborted) return abortedResult(roundsData, blockingIssuesFound);
696 790 blockingIssuesFound += roundBlockingCount;
697 - onChallenge?.(round, maxRounds, blockingIssuesFound, devilOutput);
699 792 roundsData.push(`### Round ${round}\n\n**Challenge:**\n${devilOutput}\n\n**Response:**\n${proposerOutput}`);
700 793 roundHistory += `### Round ${round}\n**Challenge:** ${devilOutput.slice(0, ROUND_HISTORY_TRUNCATE)}\n**Response:** ${proposerOutput.slice(0, ROUND_HISTORY_TRUNCATE)}\n\n`;
748 841 return `${output.synthesis}${blockingNote}\n\n${meta}`;
844 +function buildMainAgentHandoff(idea: string, verdict: string): string {
845 + return [
846 + "Devil's Advocate report follows. Treat it as advisory evidence, not truth.",
847 + "Critically evaluate it against current repo/session context. Call out anything wrong, overstated, stale, or unsupported.",
848 + "Do not change files or run bash from this report alone. Present a concrete plan first; user can cancel or redirect before execution.",
849 + `Original idea:\n${idea}`,
850 + `Report:\n${verdict}`,
851 + ].join("\n\n");
751 854 // ── Extension entry ───────────────────────────────────────────────────
753 856 export default async function (pi: ExtensionAPI) {
754 - const settings = pi.settingsManager?.getSettings();
755 - const devilSettings: DevilSettings = settings?.devil ?? {};
857 + gcEphemeralForks();
858 + const settings = (pi as SettingsAPI).settingsManager?.getSettings();
859 + const devilSettings: DevilSettings = (settings?.devil ?? {}) as DevilSettings;
756 860 const activeControllers = new Set<AbortController>();
758 862 // ── Flags ─────────────────────────────────────────────────────────
760 - pi.registerFlag("devil-max-rounds", {
761 - description: "Override max debate rounds (1-10)",
762 - type: "number",
763 - default: devilSettings.maxRounds ?? DEFAULT_MAX_ROUNDS,
864 + pi.registerFlag("devil-rounds", {
865 + description: "Override max debate rounds (1-5)",
866 + type: "string",
867 + default: String(devilSettings.maxRounds ?? DEFAULT_MAX_ROUNDS),
766 870 pi.registerFlag("devil-stop", {
775 879 activeControllers.clear();
778 883 // ── Command: /devil ────────────────────────────────────────────────
780 885 pi.registerCommand("devil", {
801 906 return;
804 - const maxRounds = pi.getFlag("devil-max-rounds") as number ?? devilSettings.maxRounds ?? DEFAULT_MAX_ROUNDS;
909 + const usage = ctx.getContextUsage();
910 + if (usage?.percent !== null && usage?.percent !== undefined && usage.percent > 85) {
911 + const ok = await ctx.ui.confirm(
912 + "Large context",
913 + `Current session uses ${usage.percent.toFixed(1)}% of ${model.id}'s context. Continue Devil anyway?`,
914 + );
915 + if (!ok) return;
918 + const maxRounds = Math.max(1, Math.min(5, Number(pi.getFlag("devil-rounds") ?? devilSettings.maxRounds ?? DEFAULT_MAX_ROUNDS) || DEFAULT_MAX_ROUNDS));
805 919 const stoppingConditions = ((pi.getFlag("devil-stop") as string) ??
806 920 devilSettings.stoppingConditions ??
807 921 DEFAULT_STOPPING_CONDITIONS) as "consensus" | "blocking_found" | "max_rounds";
825 939 context: debateContext,
826 940 model,
941 + ctx,
827 942 apiKey: auth.apiKey!,
828 943 headers: auth.headers,
829 944 maxRounds,
835 950 setDebateStatus(live, status, round, blocking);
836 951 review.refresh();
953 + onPartial: (role, round, _max, blocking, text) => {
954 + if (!review.isActive()) return;
955 + upsertDebateEntry(live, role, round, blocking, text, false);
956 + review.refresh();
957 + },
838 958 onChallenge: (round, _max, blocking, devilOutput) => {
839 959 if (!review.isActive()) return;
840 - addDebateEntry(live, "devil", round, blocking, devilOutput);
960 + upsertDebateEntry(live, "devil", round, blocking, devilOutput, true);
841 961 review.refresh();
843 963 onRound: (round, _max, blocking, _status, _devilOutput, proposerOutput) => {
844 964 if (!review.isActive()) return;
845 - addDebateEntry(live, "proposer", round, blocking, proposerOutput);
965 + upsertDebateEntry(live, "proposer", round, blocking, proposerOutput, true);
846 966 review.refresh();
872 992 const outputText = formatDebateOutput(result, onBlocking);
874 - // Modal editor: Enter submits directly, Esc discards.
875 994 const edited = await ctx.ui.editor(
876 - `🗡️ ${result.recommendation.replace(/_/g, " ")} · ${result.blockingRaised} raised · ${result.blockingRemaining} unresolved`,
995 + `🗡️ ${result.recommendation.replace(/_/g, " ")} · Enter sends · Ctrl+G editor · Esc discards`,
877 996 outputText,
891 1010 blockingRemaining: result.blockingRemaining,
892 1011 timestamp: Date.now(),
894 - pi.sendUserMessage(edited);
1013 + pi.sendUserMessage(buildMainAgentHandoff(idea, edited));