repositories / pi-ext

pi-ext

bugabingas pi extensions

owned by bugabinga

extensions/tune/index.ts

Raw
/**
 * tune — Autonomous experiment loop for Pi.
 *
 * Provides tools and a live dashboard for running optimization loops:
 * try an idea, benchmark it, keep improvements, revert regressions, repeat.
 *
 * State lives in .pi/tune/ — zero project-root litter.
 */

import { spawn } from "node:child_process";
import { randomBytes } from "node:crypto";
import * as fs from "node:fs";
import { createWriteStream } from "node:fs";
import { tmpdir } from "node:os";
import * as path from "node:path";
import { fileURLToPath } from "node:url";
import { StringEnum } from "@earendil-works/pi-ai";
import type {
	ExtensionAPI,
	ExtensionContext,
	SessionBeforeCompactEvent,
	Theme,
} from "@earendil-works/pi-coding-agent";
import {
	DEFAULT_MAX_BYTES,
	DEFAULT_MAX_LINES,
	formatSize,
	SettingsManager,
	truncateTail,
} from "@earendil-works/pi-coding-agent";
import {
	type AutocompleteItem,
	type AutocompleteSuggestions,
	matchesKey,
	Text,
	truncateToWidth,
	visibleWidth,
} from "@earendil-works/pi-tui";
import { Type } from "typebox";
import {
	buildTuneCompactionSummary,
	tuneSummaryPathsFor,
} from "./compaction.ts";
import { startTuneDashboard, type TuneDashboard } from "./dashboard.ts";
import {
	appendHookLogEntryIfConfigured,
	type HookPayload,
	runHook,
	type SessionSnapshot,
	steerMessageFor,
} from "./hooks.ts";
import {
	extractTuneSessionName,
	isTuneRunEntry,
	parseJsonlEntry,
	reconstructJsonlState,
} from "./jsonl.ts";
import { resolveTuneShortcuts, type TuneShortcuts } from "./shortcuts.ts";

// ── Constants ─────────────────────────────────────────────────────────────

const EXPERIMENT_MAX_LINES = 10;
const EXPERIMENT_MAX_BYTES = 4 * 1024;

const STATE_DIR = ".pi/tune";
const TUNE_TOOL_NAMES = [
	"init_experiment",
	"run_experiment",
	"log_experiment",
] as const;
const LOG_ASI_GUIDELINE =
	'Always include asi with {"hypothesis": "what you tried", "next_action_hint": "what to try next"}.';

const TUNE_SUBCOMMAND_COMPLETIONS: AutocompleteItem[] = [
	{ value: "off", label: "off", description: "Turn tune mode off" },
	{
		value: "clear",
		label: "clear",
		description: "Delete session.jsonl and stop",
	},
	{ value: "export", label: "export", description: "Open live dashboard" },
];

// ── Types ─────────────────────────────────────────────────────────────────

interface ASI {
	[key: string]: unknown;
}

interface ExperimentResult {
	commit: string;
	metric: number;
	metrics: Record<string, number>;
	status: "keep" | "discard" | "crash" | "checks_failed";
	description: string;
	timestamp: number;
	segment: number;
	confidence: number | null;
	asi?: ASI;
}

interface MetricDef {
	name: string;
	unit: string;
}

interface ExperimentState {
	results: ExperimentResult[];
	bestMetric: number | null;
	bestDirection: "lower" | "higher";
	metricName: string;
	metricUnit: string;
	secondaryMetrics: MetricDef[];
	name: string | null;
	currentSegment: number;
	maxExperiments: number | null;
	confidence: number | null;
}

interface RunDetails {
	command: string;
	exitCode: number | null;
	durationSeconds: number;
	passed: boolean;
	crashed: boolean;
	timedOut: boolean;
	tailOutput: string;
	checksPass: boolean | null;
	checksTimedOut: boolean;
	checksOutput: string;
	checksDuration: number;
	parsedMetrics: Record<string, number> | null;
	parsedPrimary: number | null;
	metricName: string;
	metricUnit: string;
}

interface LogDetails {
	experiment: ExperimentResult;
	state: ExperimentState;
	wallClockSeconds: number | null;
}

interface TuneRuntime {
	tuneMode: boolean;
	dashboardExpanded: boolean;
	experimentsThisSession: number;
	autoResumeTurns: number;
	lastRunChecks: { pass: boolean; output: string; duration: number } | null;
	lastRunDuration: number | null;
	runningExperiment: { startedAt: number; command: string } | null;
	state: ExperimentState;
	pendingResumeTimer: ReturnType<typeof setTimeout> | null;
	pendingResumeMessage: string | null;
}

// ── Tool parameter schemas ────────────────────────────────────────────────

const RunParams = Type.Object({
	timeout_seconds: Type.Optional(
		Type.Number({ description: "Kill after this many seconds (default: 600)" }),
	),
	checks_timeout_seconds: Type.Optional(
		Type.Number({
			description: "Kill checks.mjs after this many seconds (default: 300)",
		}),
	),
});

const InitParams = Type.Object({
	name: Type.String({
		description: 'Human-readable session name (e.g. "Optimize test speed")',
	}),
	metric_name: Type.String({
		description: 'Display name for the primary metric (e.g. "total_µs")',
	}),
	metric_unit: Type.Optional(
		Type.String({
			description: 'Unit for the primary metric. Default: ""',
		}),
	),
	direction: Type.Optional(
		Type.String({
			description: 'Whether "lower" or "higher" is better. Default: "lower".',
		}),
	),
});

export const LogParams = Type.Object({
	commit: Type.String({ description: "VCS commit hash (short, 7 chars)" }),
	metric: Type.Number({
		description: "Primary optimization metric value. 0 for crashes.",
	}),
	status: StringEnum(["keep", "discard", "crash", "checks_failed"] as const),
	description: Type.String({
		description: "Short description of what this experiment tried",
	}),
	metrics: Type.Optional(
		Type.Object(
			{},
			{
				additionalProperties: Type.Number(),
				description: "Additional metrics as { name: value } pairs",
			},
		),
	),
	force: Type.Optional(
		Type.Boolean({
			description:
				"Allow adding a new secondary metric that wasn't tracked before.",
		}),
	),
	asi: Type.Optional(
		Type.Object(
			{},
			{
				additionalProperties: Type.Unknown(),
				description:
					"Actionable Side Information — free-form key/value diagnostics.",
			},
		),
	),
});

// ── Metric line parsing ───────────────────────────────────────────────────

const METRIC_LINE_PREFIX = "METRIC";
const DENIED_METRIC_NAMES = new Set(["__proto__", "constructor", "prototype"]);

function parseMetricLines(output: string): Map<string, number> {
	const metrics = new Map<string, number>();
	const regex = new RegExp(
		`^${METRIC_LINE_PREFIX}\\s+([\\w.µ]+)=(\\S+)\\s*$`,
		"gm",
	);
	for (
		let match: RegExpExecArray | null = regex.exec(output);
		match;
		match = regex.exec(output)
	) {
		const name = match[1];
		if (DENIED_METRIC_NAMES.has(name)) continue;
		const value = Number(match[2]);
		if (Number.isFinite(value)) metrics.set(name, value);
	}
	return metrics;
}

// ── Formatting helpers ────────────────────────────────────────────────────

function commas(n: number): string {
	const s = String(Math.round(n));
	const parts: string[] = [];
	for (let i = s.length; i > 0; i -= 3) {
		parts.unshift(s.slice(Math.max(0, i - 3), i));
	}
	return parts.join(",");
}

function fmtNum(n: number, decimals = 0): string {
	if (decimals > 0) {
		const int = Math.floor(Math.abs(n));
		const frac = (Math.abs(n) - int).toFixed(decimals).slice(1);
		return (n < 0 ? "-" : "") + commas(int) + frac;
	}
	return commas(n);
}

function formatNum(value: number | null, unit: string): string {
	if (value === null) return "—";
	const u = unit || "";
	if (value === Math.round(value)) return fmtNum(value) + u;
	return fmtNum(value, 2) + u;
}

function formatElapsed(ms: number): string {
	const totalSec = Math.floor(ms / 1000);
	const m = Math.floor(totalSec / 60);
	const s = totalSec % 60;
	if (m > 0) return `${m}m ${String(s).padStart(2, "0")}s`;
	return `${s}s`;
}

// ── Misc helpers ──────────────────────────────────────────────────────────

const TASKKILL_PATH =
	process.platform === "win32"
		? path.join(
				process.env.SystemRoot ?? "C:\\Windows",
				"System32",
				"taskkill.exe",
			)
		: null;

async function killTree(
	pid: number,
	platform = process.platform,
	taskkillPath = TASKKILL_PATH,
): Promise<void> {
	if (platform === "win32" && taskkillPath && fs.existsSync(taskkillPath)) {
		const killed = await new Promise<boolean>((resolve) => {
			const killer = spawn(taskkillPath, ["/F", "/T", "/PID", String(pid)], {
				stdio: "ignore",
				windowsHide: true,
			});
			killer.once("error", () => resolve(false));
			killer.once("close", (code) => resolve(code === 0));
		});
		if (killed) return;
	}
	try {
		process.kill(platform === "win32" ? pid : -pid, "SIGTERM");
	} catch {
		try {
			process.kill(pid, "SIGTERM");
		} catch {
			// Already exited
		}
	}
}

function isBetter(
	current: number,
	best: number,
	direction: "lower" | "higher",
): boolean {
	return direction === "lower" ? current < best : current > best;
}

function sortedMedian(values: number[]): number {
	if (values.length === 0) return 0;
	const sorted = [...values].sort((a, b) => a - b);
	const mid = Math.floor(sorted.length / 2);
	return sorted.length % 2 === 0
		? (sorted[mid - 1] + sorted[mid]) / 2
		: sorted[mid];
}

function computeConfidence(
	results: ExperimentResult[],
	segment: number,
	direction: "lower" | "higher",
): number | null {
	const cur = currentResults(results, segment).filter((r) => r.metric > 0);
	if (cur.length < 3) return null;

	const values = cur.map((r) => r.metric);
	const median = sortedMedian(values);
	const deviations = values.map((v) => Math.abs(v - median));
	const mad = sortedMedian(deviations);
	if (mad === 0) return null;

	const baseline = findBaselineMetric(results, segment);
	if (baseline === null) return null;

	let bestKept: number | null = null;
	for (const r of cur) {
		if (r.status === "keep" && r.metric > 0) {
			if (bestKept === null || isBetter(r.metric, bestKept, direction)) {
				bestKept = r.metric;
			}
		}
	}
	if (bestKept === null || bestKept === baseline) return null;

	return Math.abs(bestKept - baseline) / mad;
}

function currentResults(
	results: ExperimentResult[],
	segment: number,
): ExperimentResult[] {
	return results.filter((r) => r.segment === segment);
}

function clamp(value: number, min: number, max: number): number {
	return Math.min(max, Math.max(min, value));
}

function createTempFileAllocator(): () => string {
	let p: string | undefined;
	return () => {
		if (!p) {
			const id = randomBytes(8).toString("hex");
			p = path.join(tmpdir(), `pi-experiment-${id}.log`);
		}
		return p;
	};
}

// ── State path helpers ────────────────────────────────────────────────────

const stateDir = (dir: string) => path.join(dir, STATE_DIR);
const tuneJsonlPath = (dir: string) =>
	path.join(stateDir(dir), "session.jsonl");
const tuneMdPath = (dir: string) => path.join(stateDir(dir), "session.md");
const tuneIdeasPath = (dir: string) => path.join(stateDir(dir), "ideas.md");
const tuneChecksPath = (dir: string) => path.join(stateDir(dir), "checks.mjs");
const tuneScriptPath = (dir: string) =>
	path.join(stateDir(dir), "benchmark.mjs");
const tuneLockPath = (dir: string) => path.join(stateDir(dir), "lock.json");

interface TuneLock {
	sessionId: string;
	createdAt: number;
}

function readTuneLock(cwd: string): TuneLock | null {
	try {
		const raw = JSON.parse(fs.readFileSync(tuneLockPath(cwd), "utf-8"));
		return typeof raw?.sessionId === "string" &&
			typeof raw?.createdAt === "number"
			? raw
			: null;
	} catch {
		return null;
	}
}

function acquireTuneLock(
	cwd: string,
	sessionId: string,
): { ok: true } | { ok: false; owner: string } {
	const existing = readTuneLock(cwd);
	if (existing && existing.sessionId !== sessionId) {
		return { ok: false, owner: existing.sessionId };
	}
	fs.mkdirSync(stateDir(cwd), { recursive: true });
	fs.writeFileSync(
		tuneLockPath(cwd),
		JSON.stringify({ sessionId, createdAt: Date.now() }) + "\n",
	);
	return { ok: true };
}

function ownsTuneLock(cwd: string, sessionId: string): boolean {
	return readTuneLock(cwd)?.sessionId === sessionId;
}

function releaseTuneLock(cwd: string, sessionId: string): boolean {
	if (!ownsTuneLock(cwd, sessionId)) return false;
	try {
		fs.unlinkSync(tuneLockPath(cwd));
		return true;
	} catch {
		return false;
	}
}

function findBaselineMetric(
	results: ExperimentResult[],
	segment: number,
): number | null {
	const cur = currentResults(results, segment);
	return cur.length > 0 ? cur[0].metric : null;
}

function findBestMetric(
	results: ExperimentResult[],
	segment: number,
	direction: "lower" | "higher",
): number | null {
	const kept = currentResults(results, segment)
		.filter((r) => r.status === "keep")
		.map((r) => r.metric);
	if (kept.length === 0) return null;
	return direction === "lower" ? Math.min(...kept) : Math.max(...kept);
}

function findBaselineRunNumber(
	results: ExperimentResult[],
	segment: number,
): number | null {
	const index = results.findIndex((result) => result.segment === segment);
	return index >= 0 ? index + 1 : null;
}

function findBaselineSecondary(
	results: ExperimentResult[],
	segment: number,
	knownMetrics?: MetricDef[],
): Record<string, number> {
	const cur = currentResults(results, segment);
	const base: Record<string, number> =
		cur.length > 0 ? { ...(cur[0].metrics ?? {}) } : {};

	if (knownMetrics) {
		for (const sm of knownMetrics) {
			if (base[sm.name] === undefined) {
				for (const r of cur) {
					const val = r.metrics?.[sm.name];
					if (val !== undefined) {
						base[sm.name] = val;
						break;
					}
				}
			}
		}
	}
	return base;
}

interface TuneSettings {
	maxIterations: number | null;
	autoResumeLimit: number | null;
	shortcuts: TuneShortcuts;
}

function positiveIntOrNull(value: unknown): number | null {
	return typeof value === "number" && Number.isFinite(value) && value > 0
		? Math.floor(value)
		: null;
}

function readTuneSettings(cwd = process.cwd()): TuneSettings {
	const manager = SettingsManager.create(cwd);
	const global = manager.getGlobalSettings() as Record<string, unknown>;
	const project = manager.getProjectSettings() as Record<string, unknown>;
	const globalTune =
		global.tune &&
		typeof global.tune === "object" &&
		!Array.isArray(global.tune)
			? (global.tune as Record<string, unknown>)
			: {};
	const projectTune =
		project.tune &&
		typeof project.tune === "object" &&
		!Array.isArray(project.tune)
			? (project.tune as Record<string, unknown>)
			: {};
	const tune: Record<string, unknown> = {
		...globalTune,
		...projectTune,
		shortcuts: {
			...(globalTune.shortcuts &&
			typeof globalTune.shortcuts === "object" &&
			!Array.isArray(globalTune.shortcuts)
				? globalTune.shortcuts
				: {}),
			...(projectTune.shortcuts &&
			typeof projectTune.shortcuts === "object" &&
			!Array.isArray(projectTune.shortcuts)
				? projectTune.shortcuts
				: {}),
		},
	};
	const settings = { ...global, ...project, tune };
	return {
		maxIterations: positiveIntOrNull(tune.maxIterations),
		autoResumeLimit: positiveIntOrNull(tune.autoResumeLimit),
		shortcuts: resolveTuneShortcuts(settings),
	};
}

// ── State factories ───────────────────────────────────────────────────────

function cloneExperimentState(state: ExperimentState): ExperimentState {
	return {
		...state,
		results: state.results.map((result) => ({
			...result,
			metrics: { ...result.metrics },
		})),
		secondaryMetrics: state.secondaryMetrics.map((metric) => ({ ...metric })),
	};
}

function createExperimentState(): ExperimentState {
	return {
		results: [],
		bestMetric: null,
		bestDirection: "lower",
		metricName: "metric",
		metricUnit: "",
		secondaryMetrics: [],
		name: null,
		currentSegment: 0,
		maxExperiments: null,
		confidence: null,
	};
}

function createSessionRuntime(): TuneRuntime {
	return {
		tuneMode: false,
		dashboardExpanded: false,
		experimentsThisSession: 0,
		autoResumeTurns: 0,
		lastRunChecks: null,
		lastRunDuration: null,
		runningExperiment: null,
		state: createExperimentState(),
		pendingResumeTimer: null,
		pendingResumeMessage: null,
	};
}

function createRuntimeStore() {
	const runtimes = new Map<string, TuneRuntime>();
	return {
		ensure(sessionKey: string): TuneRuntime {
			let runtime = runtimes.get(sessionKey);
			if (!runtime) {
				runtime = createSessionRuntime();
				runtimes.set(sessionKey, runtime);
			}
			return runtime;
		},
		clear(sessionKey: string): void {
			runtimes.delete(sessionKey);
		},
	};
}

type VcsKind = "jj" | "git";
interface ExecResultLike {
	code: number | null;
	stdout: string;
	stderr: string;
}
type VcsExec = (
	cmd: string,
	args: string[],
	opts: { cwd: string; timeout: number },
) => Promise<ExecResultLike>;

async function detectVcsKind(exec: VcsExec, cwd: string): Promise<VcsKind> {
	try {
		const jj = await exec("jj", ["root"], { cwd, timeout: 5000 });
		if (jj.code === 0) return "jj";
	} catch {
		// Fall through to git.
	}
	return "git";
}

async function readJjId(
	exec: VcsExec,
	cwd: string,
	template: string,
): Promise<string> {
	const result = await exec(
		"jj",
		["log", "--no-pager", "-r", "@", "-T", template],
		{
			cwd,
			timeout: 5000,
		},
	);
	return (result.stdout || "").trim();
}

async function keepVcsChanges(
	exec: VcsExec,
	cwd: string,
	message: string,
): Promise<{ kind: VcsKind; text: string; commit?: string }> {
	const kind = await detectVcsKind(exec, cwd);
	if (kind === "jj") {
		const describe = await exec("jj", ["describe", "@", "-m", message], {
			cwd,
			timeout: 10000,
		});
		if (describe.code !== 0) {
			throw new Error(
				`jj describe failed: ${(describe.stdout + describe.stderr).trim().slice(0, 200)}`,
			);
		}
		const change = await readJjId(exec, cwd, "change_id.short()");
		const commit = await readJjId(exec, cwd, "commit_id.short(7)");
		const next = await exec("jj", ["new", "@"], { cwd, timeout: 10000 });
		if (next.code !== 0) {
			throw new Error(
				`jj new failed: ${(next.stdout + next.stderr).trim().slice(0, 200)}`,
			);
		}
		return {
			kind,
			commit: commit || undefined,
			text: `\n📝 jj: kept change ${change || "?"}${commit ? ` ${commit}` : ""}`,
		};
	}

	const execOpts = { cwd, timeout: 10000 };
	const addResult = await exec("git", ["add", "-A"], execOpts);
	if (addResult.code !== 0) {
		const addErr = (addResult.stdout + addResult.stderr).trim();
		throw new Error(`git add failed: ${addErr.slice(0, 200)}`);
	}

	const diffResult = await exec(
		"git",
		["diff", "--cached", "--quiet"],
		execOpts,
	);
	if (diffResult.code === 0)
		return { kind, text: "\n📝 Git: nothing to commit" };

	const gitResult = await exec("git", ["commit", "-m", message], execOpts);
	const gitOutput = (gitResult.stdout + gitResult.stderr).trim();
	if (gitResult.code !== 0)
		return { kind, text: `\n⚠️ Git commit failed: ${gitOutput.slice(0, 200)}` };

	let commit: string | undefined;
	try {
		const shaResult = await exec("git", ["rev-parse", "--short=7", "HEAD"], {
			cwd,
			timeout: 5000,
		});
		const newSha = (shaResult.stdout || "").trim();
		if (newSha && newSha.length >= 7) commit = newSha;
	} catch {
		/* keep original hash */
	}
	return {
		kind,
		commit,
		text: `\n📝 Git: committed — ${gitOutput.split("\n")[0]}`,
	};
}

async function discardVcsChanges(
	exec: VcsExec,
	cwd: string,
	status: string,
): Promise<{ kind: VcsKind; text: string }> {
	const kind = await detectVcsKind(exec, cwd);
	if (kind === "jj") {
		const abandon = await exec("jj", ["abandon", "@"], { cwd, timeout: 10000 });
		if (abandon.code !== 0) {
			throw new Error(
				`jj abandon failed: ${(abandon.stdout + abandon.stderr).trim().slice(0, 200)}`,
			);
		}
		const next = await exec("jj", ["new", "@"], { cwd, timeout: 10000 });
		if (next.code !== 0) {
			throw new Error(
				`jj new failed: ${(next.stdout + next.stderr).trim().slice(0, 200)}`,
			);
		}
		return { kind, text: `\n📝 jj: abandoned change (${status})` };
	}

	const execOpts = { cwd, timeout: 10000 };
	const checkout = await exec(
		"git",
		[
			"checkout",
			"--",
			".",
			":(exclude,glob).pi/tune/**",
			":(exclude,glob).pi/tune/*",
		],
		execOpts,
	);
	if (checkout.code !== 0) {
		throw new Error(
			`git checkout failed: ${(checkout.stdout + checkout.stderr).trim().slice(0, 200)}`,
		);
	}
	const clean = await exec(
		"git",
		["clean", "-fd", "-e", ".pi/tune", "-e", ".pi/tune/**"],
		execOpts,
	);
	if (clean.code !== 0) {
		throw new Error(
			`git clean failed: ${(clean.stdout + clean.stderr).trim().slice(0, 200)}`,
		);
	}
	return {
		kind,
		text: `\n📝 Git: reverted changes (${status}) — .pi/tune/ preserved`,
	};
}

// ── TUI helpers ───────────────────────────────────────────────────────────

function truncateDisplayText(text: string, width: number): string {
	if (width <= 0) return "";
	return truncateToWidth(text, width, "…", true);
}

function joinPartsToWidth(parts: string[], width: number): string {
	let line = "";
	for (const part of parts) {
		if (!part) continue;
		const next = line + part;
		if (visibleWidth(next) <= width) {
			line = next;
			continue;
		}
		return truncateToWidth(line || part, width, "…", true);
	}
	return truncateToWidth(line, width, "…", true);
}

function appendRightAlignedAdaptiveHint(
	left: string,
	width: number,
	theme: Theme,
	candidates: string[],
): string {
	if (width <= 0) return "";
	const leftWidth = visibleWidth(left);
	for (const candidate of candidates) {
		const hint = theme.fg("dim", ` ${candidate}`);
		const hintWidth = visibleWidth(hint);
		if (hintWidth > width) continue;
		if (leftWidth + hintWidth <= width) {
			return (
				left + " ".repeat(Math.max(0, width - leftWidth - hintWidth)) + hint
			);
		}
		const availableLeftWidth = Math.max(0, width - hintWidth);
		const truncatedLeft = truncateToWidth(left, availableLeftWidth, "…", true);
		const truncatedLeftWidth = visibleWidth(truncatedLeft);
		return (
			truncatedLeft +
			" ".repeat(Math.max(0, width - truncatedLeftWidth - hintWidth)) +
			hint
		);
	}
	return truncateToWidth(left, width, "…", true);
}

function getTuiSize(tui: { terminal?: { columns?: number; rows?: number } }): {
	width: number;
	height: number;
} {
	return {
		width: tui.terminal?.columns ?? process.stdout.columns ?? 120,
		height: tui.terminal?.rows ?? process.stdout.rows ?? 40,
	};
}

// ── Dashboard renderer ────────────────────────────────────────────────────

function renderDashboardLines(
	st: ExperimentState,
	width: number,
	th: Theme,
	maxRows = 6,
	headerHints: string[] = [],
): string[] {
	const lines: string[] = [];
	if (st.results.length === 0) {
		lines.push(`  ${th.fg("dim", "No experiments yet.")}`);
		return lines;
	}

	const cur = currentResults(st.results, st.currentSegment);
	const kept = cur.filter((r) => r.status === "keep").length;
	const discarded = cur.filter((r) => r.status === "discard").length;
	const crashed = cur.filter((r) => r.status === "crash").length;
	const checksFailed = cur.filter((r) => r.status === "checks_failed").length;

	const baseline = st.bestMetric;
	const baselineRunNumber = findBaselineRunNumber(
		st.results,
		st.currentSegment,
	);
	const baselineSec = findBaselineSecondary(
		st.results,
		st.currentSegment,
		st.secondaryMetrics,
	);

	let bestPrimary: number | null = null;
	let bestSecondary: Record<string, number> = {};
	let bestRunNum = 0;
	for (let i = st.results.length - 1; i >= 0; i--) {
		const r = st.results[i];
		if (r.segment !== st.currentSegment) continue;
		if (r.status === "keep" && r.metric > 0) {
			if (
				bestPrimary === null ||
				isBetter(r.metric, bestPrimary, st.bestDirection)
			) {
				bestPrimary = r.metric;
				bestSecondary = r.metrics ?? {};
				bestRunNum = i + 1;
			}
		}
	}

	const confSuffix =
		st.confidence !== null
			? (() => {
					const confidence = st.confidence;
					const confStr = confidence.toFixed(1);
					const confColor: Parameters<typeof th.fg>[0] =
						confidence >= 2.0
							? "success"
							: confidence >= 1.0
								? "warning"
								: "error";
					return `  ${th.fg(confColor, `(conf: ${confStr}×)`)}`;
				})()
			: "";

	lines.push(
		truncateToWidth(
			`  ${th.fg("muted", "Runs:")} ${th.fg("text", String(st.results.length))}` +
				`  ${th.fg("success", `${kept} kept`)}` +
				confSuffix +
				(discarded > 0
					? `  ${th.fg("warning", `${discarded} discarded`)}`
					: "") +
				(crashed > 0 ? `  ${th.fg("error", `${crashed} crashed`)}` : "") +
				(checksFailed > 0
					? `  ${th.fg("error", `${checksFailed} checks failed`)}`
					: ""),
			width,
		),
	);

	const baselineSuffix =
		baselineRunNumber === null ? "" : ` #${baselineRunNumber}`;
	lines.push(
		truncateToWidth(
			`  ${th.fg("muted", "Baseline:")} ${th.fg("muted", `★ ${st.metricName}: ${formatNum(baseline, st.metricUnit)}${baselineSuffix}`)}`,
			width,
		),
	);

	if (bestPrimary !== null) {
		let progressLine = `  ${th.fg("muted", "Progress:")} ${th.fg("warning", th.bold(`★ ${st.metricName}: ${formatNum(bestPrimary, st.metricUnit)}`))}${th.fg("dim", ` #${bestRunNum}`)}`;
		if (baseline !== null && baseline !== 0 && bestPrimary !== baseline) {
			const pct = ((bestPrimary - baseline) / baseline) * 100;
			const sign = pct > 0 ? "+" : "";
			const color = isBetter(bestPrimary, baseline, st.bestDirection)
				? "success"
				: "error";
			progressLine += th.fg(color, ` (${sign}${pct.toFixed(1)}%)`);
		}
		lines.push(truncateToWidth(progressLine, width));

		if (st.secondaryMetrics.length > 0) {
			const indent = "            ";
			const maxLineW = width - 2 - indent.length;
			const secParts: string[] = [];
			for (const sm of st.secondaryMetrics) {
				const val = bestSecondary[sm.name];
				const bv = baselineSec[sm.name];
				if (val !== undefined) {
					let part = th.fg("muted", `${sm.name}: ${formatNum(val, sm.unit)}`);
					if (bv !== undefined && bv !== 0 && val !== bv) {
						const p = ((val - bv) / bv) * 100;
						const s = p > 0 ? "+" : "";
						const c = val <= bv ? "success" : "error";
						part += th.fg(c, ` ${s}${p.toFixed(1)}%`);
					}
					secParts.push(part);
				}
			}
			if (secParts.length > 0) {
				let curLine = "";
				let curVisW = 0;
				for (const part of secParts) {
					const partVisW = visibleWidth(part);
					const sep = curLine ? "  " : "";
					if (curLine && curVisW + sep.length + partVisW > maxLineW) {
						lines.push(
							truncateToWidth(`  ${th.fg("dim", indent)}${curLine}`, width),
						);
						curLine = part;
						curVisW = partVisW;
					} else {
						curLine += sep + part;
						curVisW += sep.length + partVisW;
					}
				}
				if (curLine) {
					lines.push(
						truncateToWidth(`  ${th.fg("dim", indent)}${curLine}`, width),
					);
				}
			}
		}
	}

	lines.push("");

	const effectiveMax = maxRows <= 0 ? st.results.length : maxRows;
	const startIdx = Math.max(0, st.results.length - effectiveMax);
	const rowsToRender = st.results.slice(startIdx);

	const secMetrics = st.secondaryMetrics.filter((sm) =>
		rowsToRender.some((r) => r.metrics?.[sm.name] !== undefined),
	);

	const primaryLabel = "★ " + (st.metricName || "metric");
	const primaryW = Math.max(
		11,
		Math.min(Math.floor(width * 0.25), visibleWidth(primaryLabel) + 1),
	);
	const col = { idx: 3, commit: 8, primary: primaryW, status: 15 };
	const minDescW = Math.max(10, Math.floor(width * 0.25));
	const fixedW = col.idx + col.commit + col.primary + col.status + 6;

	const secColWidths: number[] = secMetrics.map((sm) => {
		let maxW = visibleWidth(sm.name);
		for (const r of rowsToRender) {
			const val = r.metrics?.[sm.name];
			if (val !== undefined)
				maxW = Math.max(maxW, visibleWidth(formatNum(val, sm.unit)));
		}
		return maxW + 1;
	});

	const totalSecWidth = () =>
		secColWidths.slice(0, visibleSecMetrics.length).reduce((a, b) => a + b, 0);

	let visibleSecMetrics = secMetrics;
	while (
		visibleSecMetrics.length > 0 &&
		totalSecWidth() > width - fixedW - minDescW
	) {
		visibleSecMetrics = visibleSecMetrics.slice(0, -1);
	}

	const descW = Math.max(minDescW, width - fixedW - totalSecWidth());

	let headerLine =
		`  ${th.fg("muted", "#".padEnd(col.idx))}` +
		`${th.fg("muted", "commit".padEnd(col.commit))}` +
		`${th.fg("warning", th.bold(truncateToWidth(primaryLabel, col.primary - 1).padEnd(col.primary)))}`;

	for (let si = 0; si < visibleSecMetrics.length; si++) {
		const sm = visibleSecMetrics[si];
		headerLine += th.fg("muted", sm.name.padEnd(secColWidths[si]));
	}

	headerLine +=
		`${th.fg("muted", "status".padEnd(col.status))}` +
		`${th.fg("muted", "description")}`;

	lines.push(
		headerHints.length > 0
			? appendRightAlignedAdaptiveHint(headerLine, width, th, headerHints)
			: truncateToWidth(headerLine, width, "…", true),
	);
	lines.push(
		truncateToWidth(
			`  ${th.fg("borderMuted", "─".repeat(Math.max(0, width - 4)))}`,
			width,
		),
	);

	const baselinePrimary = findBaselineMetric(st.results, st.currentSegment);
	const baselineSecondary = findBaselineSecondary(
		st.results,
		st.currentSegment,
		st.secondaryMetrics,
	);

	if (startIdx > 0) {
		lines.push(
			truncateToWidth(
				`  ${th.fg("dim", `… ${startIdx} earlier run${startIdx === 1 ? "" : "s"}`)}`,
				width,
			),
		);
	}

	const baselineIndex = st.results.findIndex(
		(x) => x.segment === st.currentSegment,
	);

	for (let i = startIdx; i < st.results.length; i++) {
		const r = st.results[i];
		const isOld = r.segment !== st.currentSegment;
		const isBaseline = !isOld && i === baselineIndex;

		const color: Parameters<typeof th.fg>[0] = isOld
			? "dim"
			: r.status === "keep"
				? "success"
				: r.status === "crash" || r.status === "checks_failed"
					? "error"
					: "warning";

		const primaryStr = formatNum(r.metric, st.metricUnit);
		let primaryColor: Parameters<typeof th.fg>[0] = isOld ? "dim" : "text";
		if (!isOld) {
			if (isBaseline) {
				primaryColor = "text";
			} else if (
				baselinePrimary !== null &&
				r.status === "keep" &&
				r.metric > 0
			) {
				if (isBetter(r.metric, baselinePrimary, st.bestDirection)) {
					primaryColor = "success";
				} else if (r.metric !== baselinePrimary) {
					primaryColor = "error";
				}
			}
		}

		const idxStr = th.fg("dim", String(i + 1).padEnd(col.idx));
		const commitStr = isOld
			? "(old)".padEnd(col.commit)
			: r.status !== "keep"
				? "—".padStart(Math.ceil(col.commit / 2)).padEnd(col.commit)
				: r.commit.padEnd(col.commit);

		let rowLine =
			`  ${idxStr}` +
			`${th.fg(isOld ? "dim" : "accent", commitStr)}` +
			`${th.fg(primaryColor, isOld ? primaryStr.padEnd(col.primary) : th.bold(primaryStr.padEnd(col.primary)))}`;

		const rowMetrics = r.metrics ?? {};
		for (let si = 0; si < visibleSecMetrics.length; si++) {
			const sm = visibleSecMetrics[si];
			const colW = secColWidths[si];
			const val = rowMetrics[sm.name];
			if (val !== undefined) {
				const secStr = formatNum(val, sm.unit);
				let secColor: Parameters<typeof th.fg>[0] = "dim";
				if (!isOld) {
					const bv = baselineSecondary[sm.name];
					if (isBaseline) secColor = "text";
					else if (bv !== undefined && bv !== 0)
						secColor = val <= bv ? "success" : "error";
				}
				rowLine += th.fg(secColor, secStr.padEnd(colW));
			} else {
				rowLine += th.fg("dim", "—".padEnd(colW));
			}
		}

		rowLine +=
			`${th.fg(color, r.status.padEnd(col.status))}` +
			`${th.fg("muted", r.description.slice(0, descW))}`;

		lines.push(truncateToWidth(rowLine, width));
	}

	return lines;
}

// ── Dashboard template ────────────────────────────────────────────────────

function extensionRoot(): string {
	return fs.realpathSync(path.dirname(fileURLToPath(import.meta.url)));
}

function dashboardTemplatePath(): string {
	return path.join(extensionRoot(), "assets", "template.html");
}

function readDashboardTemplate(): string {
	const templateFile = dashboardTemplatePath();
	return fs.existsSync(templateFile)
		? fs.readFileSync(templateFile, "utf-8")
		: "";
}

function tuneArgumentCompletions(
	argumentPrefix: string,
): AutocompleteItem[] | null {
	const prefix = argumentPrefix.trimStart();
	if (/\s/.test(prefix)) return null;
	const matches = TUNE_SUBCOMMAND_COMPLETIONS.filter((item) =>
		item.value.startsWith(prefix),
	);
	return matches.length > 0 ? matches : null;
}

function tuneCommandArgumentSuggestions(
	lines: string[],
	cursorLine: number,
	cursorCol: number,
): AutocompleteSuggestions | null {
	const line = lines[cursorLine] ?? "";
	const beforeCursor = line.slice(0, cursorCol);
	const match = beforeCursor.match(/^\/tune\s+([^\s]*)$/);
	if (!match) return null;
	const prefix = match[1] ?? "";
	const items = tuneArgumentCompletions(prefix);
	return items ? { prefix, items } : null;
}

function setTuneToolsActive(pi: ExtensionAPI, active: boolean): void {
	const names = pi.getActiveTools();
	const tuneNames = new Set<string>(TUNE_TOOL_NAMES);
	const next = active
		? [...names, ...TUNE_TOOL_NAMES.filter((name) => !names.includes(name))]
		: names.filter((name) => !tuneNames.has(name));
	if (
		next.length === names.length &&
		next.every((name, i) => name === names[i])
	)
		return;
	pi.setActiveTools(next);
}

// ── Exported test helpers ─────────────────────────────────────────────────

export const __test = {
	parseMetricLines,
	formatNum,
	dashboardTemplatePath,
	tuneArgumentCompletions,
	tuneCommandArgumentSuggestions,
	setTuneToolsActive,
	acquireTuneLock,
	ownsTuneLock,
	releaseTuneLock,
	detectVcsKind,
	keepVcsChanges,
	discardVcsChanges,
	readTuneSettings,
	findBestMetric,
	LOG_ASI_GUIDELINE,
};

// ── Extension ─────────────────────────────────────────────────────────────

export default function tuneExtension(pi: ExtensionAPI) {
	const BENCHMARK_GUARDRAIL =
		"Be careful not to overfit to the benchmarks and do not cheat on the benchmarks.";
	const SETTLED_WINDOW_MS = 800;
	let settingsCwd = process.cwd();
	const tuneSettings = (): TuneSettings => readTuneSettings(settingsCwd);
	const shortcuts = tuneSettings().shortcuts;

	const dashboardHintVariants = (
		toggleAction: "expand" | "collapse",
	): string[] => {
		const shortcuts = tuneSettings().shortcuts;
		const toggle = shortcuts.toggleDashboard
			? `${shortcuts.toggleDashboard} ${toggleAction}`
			: null;
		const fullscreen = shortcuts.fullscreenDashboard
			? `${shortcuts.fullscreenDashboard} fullscreen`
			: null;
		if (toggle && fullscreen) {
			return [
				`${toggle} • ${fullscreen}`,
				`${toggle} • full: ${shortcuts.fullscreenDashboard}`,
				`${shortcuts.toggleDashboard} • ${shortcuts.fullscreenDashboard}`,
			];
		}
		return [toggle, fullscreen].filter((hint): hint is string => hint !== null);
	};

	const runtimeStore = createRuntimeStore();
	const getSessionKey = (ctx: ExtensionContext) =>
		ctx.sessionManager.getSessionId();
	const getRuntime = (ctx: ExtensionContext): TuneRuntime =>
		runtimeStore.ensure(getSessionKey(ctx));

	const isAgentSettled = (ctx: ExtensionContext): boolean =>
		ctx.isIdle() && !ctx.hasPendingMessages();

	const hasPendingResume = (runtime: TuneRuntime): boolean =>
		runtime.pendingResumeMessage !== null;

	const pausePendingResume = (runtime: TuneRuntime): void => {
		if (!runtime.pendingResumeTimer) return;
		clearTimeout(runtime.pendingResumeTimer);
		runtime.pendingResumeTimer = null;
	};

	const cancelPendingResume = (runtime: TuneRuntime): void => {
		pausePendingResume(runtime);
		runtime.pendingResumeMessage = null;
	};

	const markAutoResumeSent = (runtime: TuneRuntime): void => {
		runtime.autoResumeTurns++;
	};

	const sendPendingResumeIfReady = (
		ctx: ExtensionContext,
		runtime: TuneRuntime,
	): void => {
		const message = runtime.pendingResumeMessage;
		if (!message) return;
		if (!runtime.tuneMode) {
			cancelPendingResume(runtime);
			return;
		}
		if (!isAgentSettled(ctx)) return;
		const autoResumeLimit = reachedAutoResumeLimit(ctx, runtime);
		if (autoResumeLimit !== null) {
			cancelPendingResume(runtime);
			notifyAutoResumeLimitReached(ctx, autoResumeLimit);
			return;
		}
		cancelPendingResume(runtime);
		markAutoResumeSent(runtime);
		pi.sendUserMessage(message);
	};

	const schedulePendingResume = (
		ctx: ExtensionContext,
		runtime: TuneRuntime,
		message: string,
	): void => {
		pausePendingResume(runtime);
		runtime.pendingResumeMessage = message;
		runtime.pendingResumeTimer = setTimeout(
			() => sendPendingResumeIfReady(ctx, runtime),
			SETTLED_WINDOW_MS,
		);
	};

	const reschedulePendingResume = (
		ctx: ExtensionContext,
		runtime: TuneRuntime,
	): void => {
		const message = runtime.pendingResumeMessage;
		if (!hasPendingResume(runtime) || !message) return;
		schedulePendingResume(ctx, runtime, message);
	};

	const hasRunExperimentsThisSession = (runtime: TuneRuntime): boolean =>
		runtime.experimentsThisSession > 0;

	const shouldAutoResumeAfterTurn = (runtime: TuneRuntime): boolean =>
		runtime.tuneMode && hasRunExperimentsThisSession(runtime);

	const shouldAutoResumeAfterCompact = (runtime: TuneRuntime): boolean =>
		runtime.tuneMode;

	const reachedAutoResumeLimit = (
		_ctx: ExtensionContext,
		runtime: TuneRuntime,
	): number | null => {
		const limit = tuneSettings().autoResumeLimit;
		return limit !== null && runtime.autoResumeTurns >= limit ? limit : null;
	};

	const notifyAutoResumeLimitReached = (
		ctx: ExtensionContext,
		limit: number,
	): void => {
		ctx.ui.notify(`Tune auto-resume limit reached (${limit} turns)`, "info");
	};

	const composeResumeMessage = (_ctx: ExtensionContext): string => {
		return [
			"Run the next iteration now.",
			"Use the persisted tune state as needed, pick the most promising hypothesis, then call run_experiment + log_experiment.",
			BENCHMARK_GUARDRAIL,
		].join(" ");
	};

	const composeCompactionResumeMessage = (_ctx: ExtensionContext): string => {
		return [
			"Run the next iteration now.",
			"Pick the most promising hypothesis from the ideas backlog or the latest `next:` hints in recent runs, then call run_experiment + log_experiment.",
			"Do not re-read session.md or session.jsonl — the compaction summary already contains them.",
			BENCHMARK_GUARDRAIL,
		].join(" ");
	};

	const tuneCompactionFor = (
		ctx: ExtensionContext,
		event: SessionBeforeCompactEvent,
	) => {
		if (!getRuntime(ctx).tuneMode) return undefined;
		return {
			compaction: {
				summary: buildTuneCompactionSummary(tuneSummaryPathsFor(ctx.cwd)),
				firstKeptEntryId: event.preparation.firstKeptEntryId,
				tokensBefore: event.preparation.tokensBefore,
			},
		};
	};

	const sendWhenReady = (ctx: ExtensionContext, message: string): void => {
		if (ctx.isIdle()) {
			pi.sendUserMessage(message);
			return;
		}
		pi.sendUserMessage(message, { deliverAs: "followUp" });
	};

	const hasTuneRules = (ctx: ExtensionContext): boolean =>
		fs.existsSync(tuneMdPath(ctx.cwd));

	const readJsonlLines = (cwd: string): string[] => {
		const jsonlPath = tuneJsonlPath(cwd);
		if (!fs.existsSync(jsonlPath)) return [];
		return fs.readFileSync(jsonlPath, "utf-8").split("\n").filter(Boolean);
	};

	const readLastRun = (cwd: string): Record<string, unknown> | null => {
		const lines = readJsonlLines(cwd);
		for (let i = lines.length - 1; i >= 0; i--) {
			const entry = parseJsonlEntry(lines[i]);
			if (isTuneRunEntry(entry)) return entry;
		}
		return null;
	};

	const buildSessionSnapshot = (state: ExperimentState): SessionSnapshot => ({
		metric_name: state.metricName,
		metric_unit: state.metricUnit,
		direction: state.bestDirection,
		baseline_metric: state.bestMetric,
		best_metric: findBestMetric(
			state.results,
			state.currentSegment,
			state.bestDirection,
		),
		run_count: state.results.length,
		goal: state.name ?? "",
	});

	const fireHook = async (payload: HookPayload): Promise<string | null> => {
		const result = await runHook(payload);
		appendHookLogEntryIfConfigured(
			tuneJsonlPath(payload.cwd),
			payload.event,
			result,
		);
		return steerMessageFor(payload.event, result);
	};

	// ── Fullscreen overlay state ────────────────────────────────────────

	let overlayTui: { requestRender: () => void } | null = null;
	let spinnerInterval: ReturnType<typeof setInterval> | null = null;
	let spinnerFrame = 0;
	const SPINNER = ["⠋", "⠙", "⠹", "⠸", "⠼", "⠴", "⠦", "⠧", "⠇", "⠏"];

	const clearOverlay = () => {
		overlayTui = null;
		if (spinnerInterval) {
			clearInterval(spinnerInterval);
			spinnerInterval = null;
		}
	};

	const clearSessionUi = (ctx: ExtensionContext) => {
		clearOverlay();
		if (ctx.hasUI) ctx.ui.setWidget("tune", undefined);
	};

	const tuneHelp = () =>
		[
			"Usage: /tune [off|clear|export|<text>]",
			"",
			"<text> enters tune mode and starts or resumes the loop.",
			"off leaves tune mode.",
			"clear deletes session.jsonl and turns tune mode off.",
			"export opens a local live dashboard in your browser.",
			"",
			"Examples:",
			"  /tune optimize unit test runtime",
			"  /tune export",
		].join("\n");

	// ── State reconstruction ───────────────────────────────────────────

	const reconstructState = (ctx: ExtensionContext) => {
		const runtime = getRuntime(ctx);
		cancelPendingResume(runtime);
		runtime.lastRunChecks = null;
		runtime.lastRunDuration = null;
		runtime.runningExperiment = null;
		runtime.experimentsThisSession = 0;
		runtime.autoResumeTurns = 0;
		runtime.state = createExperimentState();

		const state = runtime.state;
		const jsonlPath = tuneJsonlPath(ctx.cwd);
		let loadedFromJsonl = false;
		try {
			if (fs.existsSync(jsonlPath)) {
				const reconstructed = reconstructJsonlState(
					fs.readFileSync(jsonlPath, "utf-8"),
				);
				state.name = reconstructed.name;
				state.metricName = reconstructed.metricName;
				state.metricUnit = reconstructed.metricUnit;
				state.bestDirection = reconstructed.bestDirection;
				state.currentSegment = reconstructed.currentSegment;
				state.results = reconstructed.results.map((result) => ({
					...result,
					metrics: { ...result.metrics },
				}));
				state.secondaryMetrics = reconstructed.secondaryMetrics.map(
					(metric) => ({
						...metric,
					}),
				);

				if (state.results.length > 0) {
					loadedFromJsonl = true;
					state.bestMetric = findBaselineMetric(
						state.results,
						state.currentSegment,
					);
					state.confidence = computeConfidence(
						state.results,
						state.currentSegment,
						state.bestDirection,
					);
				}
			}
		} catch {
			// Fall through
		}

		if (!loadedFromJsonl) {
			for (const entry of ctx.sessionManager.getBranch()) {
				if (entry.type !== "message") continue;
				const msg = entry.message;
				if (msg.role !== "toolResult" || msg.toolName !== "log_experiment")
					continue;
				const details = msg.details as LogDetails | undefined;
				if (details?.state) {
					runtime.state = cloneExperimentState(details.state);
					if (!runtime.state.secondaryMetrics)
						runtime.state.secondaryMetrics = [];
					for (const r of runtime.state.results) {
						if (!r.metrics) r.metrics = {};
						if (r.confidence === undefined) r.confidence = null;
					}
					if (runtime.state.confidence === undefined) {
						runtime.state.confidence = computeConfidence(
							runtime.state.results,
							runtime.state.currentSegment,
							runtime.state.bestDirection,
						);
					}
				}
			}
		}

		state.maxExperiments = tuneSettings().maxIterations;
		runtime.tuneMode =
			fs.existsSync(jsonlPath) && ownsTuneLock(ctx.cwd, getSessionKey(ctx));
		updateWidget(ctx);
	};

	// ── Widget ──────────────────────────────────────────────────────────

	const updateWidget = (ctx: ExtensionContext) => {
		if (!ctx.hasUI) return;
		const runtime = getRuntime(ctx);
		const state = runtime.state;

		if (!runtime.tuneMode) {
			ctx.ui.setWidget("tune", undefined);
			return;
		}

		if (state.results.length === 0 && !runtime.runningExperiment) {
			ctx.ui.setWidget("tune", undefined);
			return;
		}

		if (state.results.length === 0 && runtime.runningExperiment) {
			ctx.ui.setWidget("tune", (tui, theme) => ({
				render(width: number): string[] {
					const safeWidth = Math.max(1, width || getTuiSize(tui).width);
					return [
						joinPartsToWidth(
							[
								theme.fg("accent", "🔬"),
								theme.fg("warning", " running…"),
								state.name ? theme.fg("dim", ` │ ${state.name}`) : "",
								theme.fg(
									"dim",
									` │ ${runtime.runningExperiment?.command ?? ""}`,
								),
								theme.fg("dim", " │ waiting for first logged result"),
							],
							safeWidth,
						),
					];
				},
				invalidate(): void {},
			}));
			return;
		}

		if (runtime.dashboardExpanded) {
			ctx.ui.setWidget("tune", (tui, theme) => ({
				render(width: number): string[] {
					const safeWidth = Math.max(1, width || getTuiSize(tui).width);
					const title = truncateDisplayText(
						`🔬 tune${state.name ? `: ${state.name}` : ""}`,
						Math.max(0, safeWidth - 5),
					);
					const fillLen = Math.max(
						0,
						safeWidth - 3 - 1 - visibleWidth(title) - 1,
					);
					const rows = safeWidth < 95 ? 4 : 6;
					return [
						truncateToWidth(
							theme.fg("borderMuted", "───") +
								theme.fg("accent", ` ${title} `) +
								theme.fg("borderMuted", "─".repeat(fillLen)),
							safeWidth,
							"…",
							true,
						),
						...renderDashboardLines(
							state,
							safeWidth,
							theme,
							rows,
							dashboardHintVariants("collapse"),
						),
					];
				},
				invalidate(): void {},
			}));
		} else {
			ctx.ui.setWidget("tune", (tui, theme) => ({
				render(width: number): string[] {
					const safeWidth = Math.max(1, width || getTuiSize(tui).width);
					const cur = currentResults(state.results, state.currentSegment);
					const kept = cur.filter((r) => r.status === "keep").length;
					const crashed = cur.filter((r) => r.status === "crash").length;
					const checksFailed = cur.filter(
						(r) => r.status === "checks_failed",
					).length;
					const baseline = state.bestMetric;
					const baselineSec = findBaselineSecondary(
						state.results,
						state.currentSegment,
						state.secondaryMetrics,
					);

					let bestPrimary: number | null = null;
					let bestSec: Record<string, number> = {};
					let bestRunNum = 0;
					for (let i = state.results.length - 1; i >= 0; i--) {
						const r = state.results[i];
						if (r.segment !== state.currentSegment) continue;
						if (r.status === "keep" && r.metric > 0) {
							if (
								bestPrimary === null ||
								isBetter(r.metric, bestPrimary, state.bestDirection)
							) {
								bestPrimary = r.metric;
								bestSec = r.metrics ?? {};
								bestRunNum = i + 1;
							}
						}
					}

					const displayVal = bestPrimary ?? baseline;
					const essential = [
						theme.fg("accent", "🔬"),
						theme.fg("muted", ` ${state.results.length} runs`),
						theme.fg("success", ` ${kept} kept`),
						theme.fg("dim", " │ "),
						theme.fg(
							"warning",
							theme.bold(
								`★ ${state.metricName}: ${formatNum(displayVal, state.metricUnit)}`,
							),
						),
						bestRunNum > 0 ? theme.fg("dim", ` #${bestRunNum}`) : "",
					];

					const optional: string[] = [];
					if (crashed > 0) optional.push(theme.fg("error", ` ${crashed}💥`));
					if (checksFailed > 0)
						optional.push(theme.fg("error", ` ${checksFailed}⚠`));

					if (
						baseline !== null &&
						bestPrimary !== null &&
						baseline !== 0 &&
						bestPrimary !== baseline
					) {
						const pct = ((bestPrimary - baseline) / baseline) * 100;
						const sign = pct > 0 ? "+" : "";
						const deltaColor = isBetter(
							bestPrimary,
							baseline,
							state.bestDirection,
						)
							? "success"
							: "error";
						optional.push(theme.fg(deltaColor, ` (${sign}${pct.toFixed(1)}%)`));
					}

					if (state.confidence !== null) {
						const confStr = state.confidence.toFixed(1);
						const confColor: Parameters<typeof theme.fg>[0] =
							state.confidence >= 2.0
								? "success"
								: state.confidence >= 1.0
									? "warning"
									: "error";
						optional.push(theme.fg("dim", " │ "));
						optional.push(theme.fg(confColor, `conf: ${confStr}×`));
					}

					if (state.secondaryMetrics.length > 0) {
						for (const sm of state.secondaryMetrics) {
							const val = bestSec[sm.name];
							const bv = baselineSec[sm.name];
							if (val === undefined) continue;
							let secText = `${sm.name}: ${formatNum(val, sm.unit)}`;
							if (bv !== undefined && bv !== 0 && val !== bv) {
								const p = ((val - bv) / bv) * 100;
								const s = p > 0 ? "+" : "";
								const c = val <= bv ? "success" : "error";
								secText += theme.fg(c, ` ${s}${p.toFixed(1)}%`);
							}
							optional.push(theme.fg("dim", "  "));
							optional.push(theme.fg("muted", secText));
							break;
						}
					}

					if (state.name) optional.push(theme.fg("dim", ` │ ${state.name}`));

					const left = [...essential, ...optional].join("");
					const hintVariants = dashboardHintVariants("expand");
					return [
						hintVariants.length > 0
							? appendRightAlignedAdaptiveHint(
									left,
									safeWidth,
									theme,
									hintVariants,
								)
							: truncateToWidth(left, safeWidth, "…", true),
					];
				},
				invalidate(): void {},
			}));
		}
	};

	// ── Lifecycle hooks ─────────────────────────────────────────────────

	let warnedMissingTaskkill = false;
	pi.on("session_start", async (_e, ctx) => {
		settingsCwd = ctx.cwd;
		if (
			TASKKILL_PATH &&
			!warnedMissingTaskkill &&
			!fs.existsSync(TASKKILL_PATH)
		) {
			warnedMissingTaskkill = true;
			ctx.ui.notify(
				"taskkill.exe unavailable; Tune timeouts will kill only the benchmark process",
				"info",
			);
		}
		reconstructState(ctx);
		setTuneToolsActive(pi, getRuntime(ctx).tuneMode);
	});
	pi.on("session_start", async (_e, ctx) => {
		if (typeof ctx.ui.addAutocompleteProvider !== "function") return;
		ctx.ui.addAutocompleteProvider((current) => ({
			async getSuggestions(lines, cursorLine, cursorCol, options) {
				const suggestions = tuneCommandArgumentSuggestions(
					lines,
					cursorLine,
					cursorCol,
				);
				if (suggestions) return suggestions;
				return current.getSuggestions(lines, cursorLine, cursorCol, options);
			},
			applyCompletion(lines, cursorLine, cursorCol, item, prefix) {
				return current.applyCompletion(
					lines,
					cursorLine,
					cursorCol,
					item,
					prefix,
				);
			},
			shouldTriggerFileCompletion(lines, cursorLine, cursorCol) {
				if (tuneCommandArgumentSuggestions(lines, cursorLine, cursorCol))
					return true;
				return (
					current.shouldTriggerFileCompletion?.(lines, cursorLine, cursorCol) ??
					true
				);
			},
		}));
	});
	pi.on("session_tree", async (_e, ctx) => {
		reconstructState(ctx);
		setTuneToolsActive(pi, getRuntime(ctx).tuneMode);
	});
	pi.on("session_before_switch", async () => clearOverlay());
	pi.on("session_shutdown", async (_e, ctx) => {
		setTuneToolsActive(pi, false);
		clearSessionUi(ctx);
		cancelPendingResume(getRuntime(ctx));
		releaseTuneLock(ctx.cwd, getSessionKey(ctx));
		runtimeStore.clear(getSessionKey(ctx));
		stopDashboardServer();
	});

	pi.on("agent_start", async (_event, ctx) => {
		const runtime = getRuntime(ctx);
		runtime.experimentsThisSession = 0;
		pausePendingResume(runtime);
	});

	const ensurePendingResume = (
		ctx: ExtensionContext,
		gate: (runtime: TuneRuntime) => boolean,
		composeMessage: (ctx: ExtensionContext) => string = composeResumeMessage,
	): void => {
		const runtime = getRuntime(ctx);
		if (hasPendingResume(runtime)) {
			reschedulePendingResume(ctx, runtime);
			return;
		}
		if (!gate(runtime)) return;
		const autoResumeLimit = reachedAutoResumeLimit(ctx, runtime);
		if (autoResumeLimit !== null) {
			notifyAutoResumeLimitReached(ctx, autoResumeLimit);
			return;
		}
		schedulePendingResume(ctx, runtime, composeMessage(ctx));
	};

	pi.on("session_before_compact", async (event, ctx) => {
		pausePendingResume(getRuntime(ctx));
		return tuneCompactionFor(ctx, event);
	});

	pi.on("session_compact", async (_event, ctx) => {
		ensurePendingResume(
			ctx,
			shouldAutoResumeAfterCompact,
			composeCompactionResumeMessage,
		);
	});

	pi.on("agent_end", async (_event, ctx) => {
		const runtime = getRuntime(ctx);
		runtime.runningExperiment = null;
		if (overlayTui) overlayTui.requestRender();
		ensurePendingResume(ctx, shouldAutoResumeAfterTurn);
	});

	pi.on("before_agent_start", async (event, ctx) => {
		const runtime = getRuntime(ctx);
		if (!runtime.tuneMode) return;

		const mdPath = tuneMdPath(ctx.cwd);
		const ideasPath = tuneIdeasPath(ctx.cwd);
		const hasIdeas = fs.existsSync(ideasPath);
		const checksPath = tuneChecksPath(ctx.cwd);
		const hasChecks = fs.existsSync(checksPath);

		let extra =
			"\n\n## Tune Mode (ACTIVE)" +
			"\nYou are in tune mode. Optimize the primary metric through an autonomous experiment loop." +
			"\nUse init_experiment, run_experiment, and log_experiment tools. NEVER STOP until interrupted." +
			"\nTune takes an exclusive repo lock for this session; use a separate checkout/workspace for parallel tune runs." +
			`\nExperiment rules: ${mdPath} — read this file at the start of every session and after compaction.` +
			"\nWrite promising but deferred optimizations as bullet points to ideas.md — don't let good ideas get lost." +
			`\n${BENCHMARK_GUARDRAIL}` +
			"\nIf the user sends a follow-on message while an experiment is running, finish the current run_experiment + log_experiment cycle first, then address their message in the next iteration.";

		if (hasChecks) {
			extra +=
				"\n\n## Backpressure Checks (ACTIVE)" +
				`\n${checksPath} exists and runs automatically after every passing benchmark in run_experiment.` +
				"\nIf the benchmark passes but checks fail, run_experiment will report it clearly." +
				"\nUse status 'checks_failed' in log_experiment — it behaves like a crash (changes auto-discarded)." +
				"\nYou cannot use status 'keep' when checks have failed." +
				"\nThe checks execution time does NOT affect the primary metric.";
		}

		if (hasIdeas) {
			extra += `\n\n💡 Ideas backlog exists at ${ideasPath} — check it for promising experiment paths.`;
		}

		return { systemPrompt: event.systemPrompt + extra };
	});

	// ── init_experiment tool ────────────────────────────────────────────

	pi.registerTool({
		name: "init_experiment",
		label: "Init Experiment",
		description:
			"Initialize the experiment session. Call once before the first run_experiment.",
		promptSnippet:
			"Initialize experiment session (name, metric, unit, direction).",
		promptGuidelines: [
			"Call init_experiment exactly once at the start of a tune session.",
			"If session.jsonl already exists with a config, do NOT call init_experiment again.",
			"If the optimization target changes, call init_experiment again to insert a new config header.",
		],
		parameters: InitParams,

		async execute(_toolCallId, params, _signal, _onUpdate, ctx) {
			const runtime = getRuntime(ctx);
			if (!runtime.tuneMode) {
				return {
					content: [
						{
							type: "text",
							text: "❌ Tune is not active. Start with /tune <goal>.",
						},
					],
					details: {},
				};
			}
			const lock = acquireTuneLock(ctx.cwd, getSessionKey(ctx));
			if (!lock.ok) {
				return {
					content: [
						{
							type: "text",
							text: `❌ Tune already active in session ${lock.owner}`,
						},
					],
					details: {},
				};
			}
			const state = runtime.state;
			const isReinit = state.results.length > 0;

			state.name = params.name;
			state.metricName = params.metric_name;
			state.metricUnit = params.metric_unit ?? "";
			if (params.direction === "lower" || params.direction === "higher") {
				state.bestDirection = params.direction;
			}
			if (isReinit) state.currentSegment++;
			state.bestMetric = null;
			state.secondaryMetrics = [];
			state.confidence = null;
			state.maxExperiments = tuneSettings().maxIterations;

			// Ensure state directory exists
			const dir = stateDir(ctx.cwd);
			fs.mkdirSync(dir, { recursive: true });

			try {
				const jsonlPath = tuneJsonlPath(ctx.cwd);
				const config = JSON.stringify({
					type: "config",
					name: state.name,
					metricName: state.metricName,
					metricUnit: state.metricUnit,
					bestDirection: state.bestDirection,
				});
				if (fs.existsSync(jsonlPath)) {
					fs.appendFileSync(jsonlPath, config + "\n");
				} else {
					fs.writeFileSync(jsonlPath, config + "\n");
				}
				broadcastDashboardUpdate(ctx.cwd);
			} catch (e) {
				return {
					content: [
						{
							type: "text",
							text: `⚠️ Failed to write session.jsonl: ${e instanceof Error ? e.message : String(e)}`,
						},
					],
					details: {},
				};
			}

			const wasInactive = !runtime.tuneMode;
			runtime.tuneMode = true;
			updateWidget(ctx);

			if (wasInactive) {
				const steer = await fireHook({
					event: "before",
					cwd: ctx.cwd,
					next_run: state.results.length + 1,
					last_run: readLastRun(ctx.cwd),
					session: buildSessionSnapshot(state),
				});
				if (steer) pi.sendUserMessage(steer, { deliverAs: "steer" });
			}

			const reinitNote = isReinit
				? " (re-initialized — previous results archived, new baseline needed)"
				: "";
			const limitNote =
				state.maxExperiments !== null
					? `\nMax iterations: ${state.maxExperiments} (from settings.tune.maxIterations)`
					: "";
			return {
				content: [
					{
						type: "text",
						text: `✅ Experiment initialized: "${state.name}"${reinitNote}\nMetric: ${state.metricName} (${state.metricUnit || "unitless"}, ${state.bestDirection} is better)${limitNote}\nState dir: .pi/tune/\nConfig written to session.jsonl. Now run the baseline with run_experiment.`,
					},
				],
				details: { state: cloneExperimentState(state) },
			};
		},

		renderCall(args, theme) {
			return new Text(
				theme.fg("toolTitle", theme.bold("init_experiment ")) +
					theme.fg("accent", args.name ?? ""),
				0,
				0,
			);
		},

		renderResult(result, _options, _theme) {
			const t = result.content[0];
			return new Text(t?.type === "text" ? t.text : "", 0, 0);
		},
	});

	// ── run_experiment tool ─────────────────────────────────────────────

	pi.registerTool({
		name: "run_experiment",
		label: "Run Experiment",
		description: `Run .pi/tune/benchmark.mjs as an experiment. Times wall-clock duration, captures output, detects pass/fail. Output truncated to last ${EXPERIMENT_MAX_LINES} lines or ${EXPERIMENT_MAX_BYTES / 1024}KB.`,
		promptSnippet: "Run the timed benchmark.mjs experiment",
		promptGuidelines: [
			"Edit .pi/tune/benchmark.mjs, then call run_experiment without a command.",
			"After run_experiment, always call log_experiment to record the result.",
			"If the benchmark script outputs METRIC lines, run_experiment parses them automatically.",
		],
		parameters: RunParams,

		async execute(_toolCallId, params, signal, onUpdate, ctx) {
			const runtime = getRuntime(ctx);
			const state = runtime.state;
			const cwd = ctx.cwd;
			if (!runtime.tuneMode || !ownsTuneLock(cwd, getSessionKey(ctx))) {
				return {
					content: [
						{ type: "text", text: "❌ Tune is not active in this session." },
					],
					details: {},
				};
			}

			// Block if max experiments reached
			if (state.maxExperiments !== null) {
				const segCount = currentResults(
					state.results,
					state.currentSegment,
				).length;
				if (segCount >= state.maxExperiments) {
					return {
						content: [
							{
								type: "text",
								text: `🛑 Maximum experiments reached (${state.maxExperiments}). Call init_experiment to start a new segment.`,
							},
						],
						details: {},
					};
				}
			}

			const benchmarkPath = tuneScriptPath(cwd);
			if (!fs.existsSync(benchmarkPath)) {
				return {
					content: [
						{
							type: "text",
							text: "❌ Create .pi/tune/benchmark.mjs before run_experiment.",
						},
					],
					details: {},
				};
			}

			const benchmarkDisplay = "node .pi/tune/benchmark.mjs";
			runtime.runningExperiment = {
				startedAt: Date.now(),
				command: benchmarkDisplay,
			};
			updateWidget(ctx);
			if (overlayTui) overlayTui.requestRender();

			const timeout = Math.max(0, params.timeout_seconds ?? 600) * 1000;
			const t0 = Date.now();
			const getTempFile = createTempFileAllocator();

			const {
				exitCode,
				killed: timedOut,
				output,
				tempFilePath: streamTempFile,
				actualTotalBytes,
			} = await new Promise<{
				exitCode: number | null;
				killed: boolean;
				output: string;
				tempFilePath: string | undefined;
				actualTotalBytes: number;
			}>((resolve, reject) => {
				let processTimedOut = false;

				const child = spawn(process.execPath, [benchmarkPath], {
					cwd,
					detached: process.platform !== "win32",
					windowsHide: true,
					stdio: ["ignore", "pipe", "pipe"],
				});

				const chunks: Buffer[] = [];
				let chunksBytes = 0;
				const maxChunksBytes = DEFAULT_MAX_BYTES * 2;
				let tempFilePath: string | undefined;
				let tempFileStream: ReturnType<typeof createWriteStream> | undefined;
				let totalBytes = 0;
				let chunksGeneration = 0;
				let cachedGeneration = -1;
				let cachedText = "";

				function getBufferText(): string {
					if (cachedGeneration === chunksGeneration) return cachedText;
					cachedText = Buffer.concat(chunks).toString("utf-8");
					cachedGeneration = chunksGeneration;
					return cachedText;
				}

				const timerInterval = setInterval(() => {
					if (!onUpdate) return;
					const elapsed = formatElapsed(Date.now() - t0);
					const trunc = truncateTail(getBufferText(), {
						maxLines: DEFAULT_MAX_LINES,
						maxBytes: DEFAULT_MAX_BYTES,
					});
					onUpdate({
						content: [{ type: "text", text: trunc.content || "" }],
						details: {
							phase: "running",
							elapsed,
							truncation: trunc.truncated ? trunc : undefined,
							fullOutputPath: tempFilePath,
						},
					});
				}, 1000);

				const handleData = (data: Buffer) => {
					totalBytes += data.length;
					if (totalBytes > DEFAULT_MAX_BYTES && !tempFilePath) {
						tempFilePath = getTempFile();
						tempFileStream = createWriteStream(tempFilePath);
						for (const chunk of chunks) tempFileStream.write(chunk);
					}
					if (tempFileStream) tempFileStream.write(data);

					chunks.push(data);
					chunksBytes += data.length;
					while (chunksBytes > maxChunksBytes && chunks.length > 1) {
						const removed = chunks.shift();
						if (!removed) break;
						chunksBytes -= removed.length;
					}
					if (chunks.length > 0 && chunksBytes > maxChunksBytes) {
						const buf = chunks[0];
						const nlIdx = buf.indexOf(0x0a);
						if (nlIdx !== -1 && nlIdx < buf.length - 1) {
							chunks[0] = buf.subarray(nlIdx + 1);
							chunksBytes -= nlIdx + 1;
						}
					}
					chunksGeneration++;
				};

				if (child.stdout) child.stdout.on("data", handleData);
				if (child.stderr) child.stderr.on("data", handleData);

				let termination: Promise<void> | null = null;
				const terminateOnce = (): Promise<void> => {
					if (termination) return termination;
					termination = child.pid
						? killTree(child.pid)
						: new Promise((resolve) => {
								child.once("spawn", () => {
									if (child.pid) void killTree(child.pid).then(resolve);
									else resolve();
								});
								child.once("error", () => resolve());
							});
					return termination;
				};
				let timeoutHandle: ReturnType<typeof setTimeout> | undefined;
				if (timeout > 0) {
					timeoutHandle = setTimeout(() => {
						processTimedOut = true;
						void terminateOnce();
					}, timeout);
				}

				const onAbort = () => void terminateOnce();
				if (signal) {
					if (signal.aborted) onAbort();
					else signal.addEventListener("abort", onAbort, { once: true });
				}

				child.on("error", (err) => {
					clearInterval(timerInterval);
					if (timeoutHandle) clearTimeout(timeoutHandle);
					if (signal) signal.removeEventListener("abort", onAbort);
					if (tempFileStream) tempFileStream.end();
					reject(err);
				});

				child.on("close", async (code) => {
					clearInterval(timerInterval);
					if (timeoutHandle) clearTimeout(timeoutHandle);
					if (signal) signal.removeEventListener("abort", onAbort);
					if (termination) await termination;
					if (tempFileStream) tempFileStream.end();

					if (signal?.aborted) {
						reject(new Error("aborted"));
						return;
					}

					const fullBuffer = Buffer.concat(chunks);
					resolve({
						exitCode: code,
						killed: processTimedOut,
						output: fullBuffer.toString("utf-8"),
						tempFilePath,
						actualTotalBytes: totalBytes,
					});
				});
			}).finally(() => {
				runtime.runningExperiment = null;
				updateWidget(ctx);
				if (overlayTui) overlayTui.requestRender();
			});

			const durationSeconds = (Date.now() - t0) / 1000;
			runtime.lastRunDuration = durationSeconds;
			const benchmarkPassed = exitCode === 0 && !timedOut;

			// Run backpressure checks
			let checksPass: boolean | null = null;
			let checksTimedOut = false;
			let checksOutput = "";
			let checksDuration = 0;

			const checksPath = tuneChecksPath(cwd);
			if (benchmarkPassed && fs.existsSync(checksPath)) {
				const checksTimeout =
					Math.max(0, params.checks_timeout_seconds ?? 300) * 1000;
				const ct0 = Date.now();
				try {
					const checksResult = await pi.exec(process.execPath, [checksPath], {
						signal,
						timeout: checksTimeout,
						cwd,
					});
					checksDuration = (Date.now() - ct0) / 1000;
					checksTimedOut = !!checksResult.killed;
					checksPass = checksResult.code === 0 && !checksResult.killed;
					checksOutput = (
						checksResult.stdout +
						"\n" +
						checksResult.stderr
					).trim();
				} catch (e) {
					checksDuration = (Date.now() - ct0) / 1000;
					checksPass = false;
					checksOutput = e instanceof Error ? e.message : String(e);
				}
			}

			runtime.lastRunChecks =
				checksPass !== null
					? { pass: checksPass, output: checksOutput, duration: checksDuration }
					: null;

			const passed = benchmarkPassed && (checksPass === null || checksPass);

			let fullOutputPath: string | undefined = streamTempFile;
			const totalLines = output.split("\n").length;
			if (
				!fullOutputPath &&
				(actualTotalBytes > EXPERIMENT_MAX_BYTES ||
					totalLines > EXPERIMENT_MAX_LINES)
			) {
				fullOutputPath = getTempFile();
				fs.writeFileSync(fullOutputPath, output);
			}

			const displayTruncation = truncateTail(output, {
				maxLines: DEFAULT_MAX_LINES,
				maxBytes: DEFAULT_MAX_BYTES,
			});
			const llmTruncation = truncateTail(output, {
				maxLines: EXPERIMENT_MAX_LINES,
				maxBytes: EXPERIMENT_MAX_BYTES,
			});

			const parsedMetricMap = parseMetricLines(output);
			const parsedMetrics =
				parsedMetricMap.size > 0 ? Object.fromEntries(parsedMetricMap) : null;
			const parsedPrimary = parsedMetricMap.get(state.metricName) ?? null;

			const details: RunDetails = {
				command: benchmarkDisplay,
				exitCode,
				durationSeconds,
				passed,
				crashed: !passed,
				timedOut,
				tailOutput: displayTruncation.content,
				checksPass,
				checksTimedOut,
				checksOutput: checksOutput.split("\n").slice(-80).join("\n"),
				checksDuration,
				parsedMetrics,
				parsedPrimary,
				metricName: state.metricName,
				metricUnit: state.metricUnit,
			};

			let text = "";
			if (details.timedOut) {
				text += `⏰ TIMEOUT after ${durationSeconds.toFixed(1)}s\n`;
			} else if (!benchmarkPassed) {
				text += `💥 FAILED (exit code ${exitCode}) in ${durationSeconds.toFixed(1)}s\n`;
			} else if (checksTimedOut) {
				text += `✅ Benchmark PASSED in ${durationSeconds.toFixed(1)}s\n`;
				text += `⏰ CHECKS TIMEOUT after ${checksDuration.toFixed(1)}s\n`;
			} else if (checksPass === false) {
				text += `✅ Benchmark PASSED in ${durationSeconds.toFixed(1)}s\n`;
				text += `💥 CHECKS FAILED in ${checksDuration.toFixed(1)}s\n`;
			} else {
				text += `✅ PASSED in ${durationSeconds.toFixed(1)}s\n`;
				if (checksPass === true)
					text += `✅ Checks passed in ${checksDuration.toFixed(1)}s\n`;
			}

			const bestMetric = findBestMetric(
				state.results,
				state.currentSegment,
				state.bestDirection,
			);
			if (bestMetric !== null) {
				text += `📊 Current best ${state.metricName}: ${formatNum(bestMetric, state.metricUnit)}\n`;
			}

			if (parsedMetrics) {
				const secondary = Object.entries(parsedMetrics).filter(
					([k]) => k !== state.metricName,
				);
				text += `\n📐 Parsed metrics:`;
				if (parsedPrimary !== null) {
					text += ` ★ ${state.metricName}=${formatNum(parsedPrimary, state.metricUnit)}`;
				}
				for (const [name, value] of secondary) {
					const sm = state.secondaryMetrics.find((m) => m.name === name);
					text += ` ${name}=${formatNum(value, sm?.unit ?? "")}`;
				}
				text += `\nUse these values directly in log_experiment (metric: ${parsedPrimary ?? "?"}, metrics: {${secondary.map(([k, v]) => `"${k}": ${v}`).join(", ")}})\n`;
			}

			text += `\n${llmTruncation.content}`;

			if (llmTruncation.truncated) {
				if (llmTruncation.truncatedBy === "lines") {
					text += `\n\n[Showing last ${llmTruncation.outputLines} of ${llmTruncation.totalLines} lines.`;
				} else {
					text += `\n\n[Showing last ${llmTruncation.outputLines} lines (${formatSize(EXPERIMENT_MAX_BYTES)} limit).`;
				}
				if (fullOutputPath) text += ` Full output: ${fullOutputPath}`;
				text += `]`;
			}

			if (checksPass === false || checksTimedOut) {
				text += `\n\n── Checks output (last 80 lines) ──\n${details.checksOutput}`;
			}

			return {
				content: [{ type: "text", text }],
				details: {
					...details,
					truncation: llmTruncation.truncated ? llmTruncation : undefined,
					fullOutputPath,
				},
			};
		},

		renderCall(args, theme) {
			let text = theme.fg("toolTitle", theme.bold("run_experiment "));
			text += theme.fg("muted", ".pi/tune/benchmark.mjs");
			if (args.timeout_seconds !== undefined)
				text += theme.fg(
					"dim",
					` (timeout: ${Math.max(0, args.timeout_seconds)}s)`,
				);
			return new Text(text, 0, 0);
		},

		renderResult(result, { expanded, isPartial }, theme) {
			const PREVIEW_LINES = 5;

			if (isPartial) {
				const d = result.details as
					| { phase?: string; elapsed?: string }
					| undefined;
				const elapsed = d?.elapsed ?? "";
				const outputText =
					result.content[0]?.type === "text" ? result.content[0].text : "";
				let text = theme.fg(
					"warning",
					`⏳ Running${elapsed ? ` ${elapsed}` : ""}…`,
				);
				if (outputText) {
					const lines = outputText.split("\n");
					const maxLines = expanded ? 20 : PREVIEW_LINES;
					const tail = lines.slice(-maxLines).join("\n");
					if (tail.trim()) text += "\n" + theme.fg("dim", tail);
				}
				return new Text(text, 0, 0);
			}

			const d = result.details as
				| (RunDetails & { truncation?: any; fullOutputPath?: string })
				| undefined;
			if (!d) {
				const t = result.content[0];
				return new Text(t?.type === "text" ? t.text : "", 0, 0);
			}

			const appendOutput = (text: string, output: string): string => {
				if (!output) return text;
				const lines = output.split("\n");
				if (expanded) {
					text += "\n" + theme.fg("dim", output.slice(-2000));
				} else {
					const tail = lines.slice(-PREVIEW_LINES).join("\n");
					if (tail.trim()) {
						const hidden = lines.length - PREVIEW_LINES;
						if (hidden > 0)
							text += "\n" + theme.fg("muted", `… ${hidden} more lines`);
						text += "\n" + theme.fg("dim", tail);
					}
				}
				return text;
			};

			if (d.timedOut) {
				return new Text(
					appendOutput(
						theme.fg("error", `⏰ TIMEOUT ${d.durationSeconds.toFixed(1)}s`),
						d.tailOutput,
					),
					0,
					0,
				);
			}

			const parsedSuffix =
				d.parsedPrimary !== null
					? theme.fg(
							"accent",
							`, ${d.metricName}: ${formatNum(d.parsedPrimary, d.metricUnit)}`,
						)
					: "";

			if (d.checksTimedOut) {
				return new Text(
					theme.fg("success", `✅ wall: ${d.durationSeconds.toFixed(1)}s`) +
						parsedSuffix +
						theme.fg(
							"error",
							` ⏰ checks timeout ${d.checksDuration.toFixed(1)}s`,
						),
					0,
					0,
				);
			}

			if (d.checksPass === false) {
				return new Text(
					theme.fg("success", `✅ wall: ${d.durationSeconds.toFixed(1)}s`) +
						parsedSuffix +
						theme.fg(
							"error",
							` 💥 checks failed ${d.checksDuration.toFixed(1)}s`,
						),
					0,
					0,
				);
			}

			if (d.crashed) {
				return new Text(
					appendOutput(
						theme.fg(
							"error",
							`💥 FAIL exit=${d.exitCode} ${d.durationSeconds.toFixed(1)}s`,
						) + parsedSuffix,
						d.tailOutput,
					),
					0,
					0,
				);
			}

			let text = theme.fg("success", "✅ ");
			const parts: string[] = [`wall: ${d.durationSeconds.toFixed(1)}s`];
			if (d.parsedPrimary !== null)
				parts.push(
					`${d.metricName}: ${formatNum(d.parsedPrimary, d.metricUnit)}`,
				);
			text += theme.fg("accent", parts.join(", "));
			if (d.checksPass === true)
				text += theme.fg(
					"success",
					` ✓ checks ${d.checksDuration.toFixed(1)}s`,
				);

			text = appendOutput(text, d.tailOutput);
			return new Text(text, 0, 0);
		},
	});

	// ── log_experiment tool ─────────────────────────────────────────────

	pi.registerTool({
		name: "log_experiment",
		label: "Log Experiment",
		description:
			"Record an experiment result. Tracks metrics, updates widget and dashboard. Call after every run_experiment.",
		promptSnippet: "Log experiment result",
		promptGuidelines: [
			"Always call log_experiment after run_experiment.",
			"log_experiment keeps changes on 'keep', discards changes on 'discard'/'crash'/'checks_failed' using the repo VCS.",
			"Use status 'keep' if PRIMARY metric improved. 'discard' if worse. 'crash' if failed.",
			LOG_ASI_GUIDELINE,
		],
		parameters: LogParams,

		async execute(_toolCallId, params, _signal, _onUpdate, ctx) {
			const runtime = getRuntime(ctx);
			const state = runtime.state;
			const cwd = ctx.cwd;
			if (!runtime.tuneMode || !ownsTuneLock(cwd, getSessionKey(ctx))) {
				return {
					content: [
						{ type: "text", text: "❌ Tune is not active in this session." },
					],
					details: {},
				};
			}
			const secondaryMetrics = (params.metrics ?? {}) as Record<string, number>;

			// Gate: prevent "keep" when checks failed
			if (
				params.status === "keep" &&
				runtime.lastRunChecks &&
				!runtime.lastRunChecks.pass
			) {
				return {
					content: [
						{
							type: "text",
							text: `❌ Cannot keep — checks.mjs failed.\n\n${runtime.lastRunChecks.output.slice(-500)}\n\nLog as 'checks_failed' instead.`,
						},
					],
					details: {},
				};
			}

			// Validate secondary metrics
			if (state.secondaryMetrics.length > 0) {
				const knownNames = new Set(state.secondaryMetrics.map((m) => m.name));
				const providedNames = new Set(Object.keys(secondaryMetrics));
				const missing = [...knownNames].filter((n) => !providedNames.has(n));
				if (missing.length > 0) {
					return {
						content: [
							{
								type: "text",
								text: `❌ Missing secondary metrics: ${missing.join(", ")}\nExpected: ${[...knownNames].join(", ")}`,
							},
						],
						details: {},
					};
				}
				const newMetrics = [...providedNames].filter((n) => !knownNames.has(n));
				if (newMetrics.length > 0 && !params.force) {
					return {
						content: [
							{
								type: "text",
								text: `❌ New secondary metric(s): ${newMetrics.join(", ")}\nUse force: true to add.`,
							},
						],
						details: {},
					};
				}
			}

			const mergedASI =
				params.asi && Object.keys(params.asi).length > 0
					? (params.asi as ASI)
					: undefined;

			const experiment: ExperimentResult = {
				commit: params.commit.slice(0, 7),
				metric: params.metric,
				metrics: secondaryMetrics,
				status: params.status,
				description: params.description,
				timestamp: Date.now(),
				segment: state.currentSegment,
				confidence: null,
				asi: mergedASI,
			};

			state.results.push(experiment);
			runtime.experimentsThisSession++;

			// Register new secondary metrics
			for (const name of Object.keys(secondaryMetrics)) {
				if (!state.secondaryMetrics.find((m) => m.name === name)) {
					let unit = "";
					if (name.endsWith("µs")) unit = "µs";
					else if (name.endsWith("_ms")) unit = "ms";
					else if (name.endsWith("_s") || name.endsWith("_sec")) unit = "s";
					else if (name.endsWith("_kb")) unit = "kb";
					else if (name.endsWith("_mb")) unit = "mb";
					state.secondaryMetrics.push({ name, unit });
				}
			}

			state.bestMetric = findBaselineMetric(
				state.results,
				state.currentSegment,
			);
			state.confidence = computeConfidence(
				state.results,
				state.currentSegment,
				state.bestDirection,
			);
			experiment.confidence = state.confidence;

			const segmentCount = currentResults(
				state.results,
				state.currentSegment,
			).length;
			let text = `Logged #${state.results.length}: ${experiment.status} — ${experiment.description}`;

			if (state.bestMetric !== null) {
				text += `\nBaseline ${state.metricName}: ${formatNum(state.bestMetric, state.metricUnit)}`;
				if (segmentCount > 1 && params.status === "keep" && params.metric > 0) {
					const delta = params.metric - state.bestMetric;
					const pct = ((delta / state.bestMetric) * 100).toFixed(1);
					const sign = delta > 0 ? "+" : "";
					text += ` | this: ${formatNum(params.metric, state.metricUnit)} (${sign}${pct}%)`;
				}
			}

			if (Object.keys(secondaryMetrics).length > 0) {
				const baselines = findBaselineSecondary(
					state.results,
					state.currentSegment,
					state.secondaryMetrics,
				);
				const parts: string[] = [];
				for (const [name, value] of Object.entries(secondaryMetrics)) {
					const def = state.secondaryMetrics.find((m) => m.name === name);
					let part = `${name}: ${formatNum(value, def?.unit ?? "")}`;
					const bv = baselines[name];
					if (bv !== undefined && state.results.length > 1 && bv !== 0) {
						const d = value - bv;
						const p = ((d / bv) * 100).toFixed(1);
						const s = d > 0 ? "+" : "";
						part += ` (${s}${p}%)`;
					}
					parts.push(part);
				}
				text += `\nSecondary: ${parts.join("  ")}`;
			}

			if (mergedASI) {
				const asiParts: string[] = [];
				for (const [k, v] of Object.entries(mergedASI)) {
					const s = typeof v === "string" ? v : JSON.stringify(v);
					asiParts.push(`${k}: ${s.length > 80 ? s.slice(0, 77) + "…" : s}`);
				}
				if (asiParts.length > 0) text += `\n📋 ASI: ${asiParts.join(" | ")}`;
			}

			if (state.confidence !== null) {
				const confStr = state.confidence.toFixed(1);
				if (state.confidence >= 2.0)
					text += `\n📊 Confidence: ${confStr}× — improvement is likely real`;
				else if (state.confidence >= 1.0)
					text += `\n📊 Confidence: ${confStr}× — above noise but marginal`;
				else
					text += `\n⚠️ Confidence: ${confStr}× — within noise. Consider re-running.`;
			}

			text += `\n(${segmentCount} experiments`;
			if (state.maxExperiments !== null)
				text += ` / ${state.maxExperiments} max`;
			text += `)`;

			const vcsExec: VcsExec = (cmd, args, opts) => pi.exec(cmd, args, opts);

			// Auto-keep on keep
			if (params.status === "keep") {
				try {
					const resultData: Record<string, unknown> = {
						status: params.status,
						[state.metricName || "metric"]: params.metric,
						...secondaryMetrics,
					};
					const commitMsg = `${params.description}\n\nResult: ${JSON.stringify(resultData)}`;
					const kept = await keepVcsChanges(vcsExec, cwd, commitMsg);
					text += kept.text;
					if (kept.commit) experiment.commit = kept.commit;
				} catch (e) {
					text += `\n⚠️ VCS error: ${e instanceof Error ? e.message : String(e)}`;
				}
			}

			// Append to JSONL
			const jsonlEntry: Record<string, unknown> = {
				run: state.results.length,
				...experiment,
			};
			if (!mergedASI) delete jsonlEntry.asi;
			try {
				fs.appendFileSync(
					tuneJsonlPath(cwd),
					JSON.stringify(jsonlEntry) + "\n",
				);
				broadcastDashboardUpdate(cwd);
			} catch (e) {
				text += `\n⚠️ Failed to write session.jsonl: ${e instanceof Error ? e.message : String(e)}`;
			}

			// Auto-discard on non-keep (preserve .pi/tune/)
			if (params.status !== "keep") {
				try {
					const discarded = await discardVcsChanges(
						vcsExec,
						cwd,
						params.status,
					);
					text += discarded.text;
				} catch (e) {
					text += `\n⚠️ VCS discard failed: ${e instanceof Error ? e.message : String(e)}`;
				}
			}

			// Fire hooks
			const afterSteer = await fireHook({
				event: "after",
				cwd,
				run_entry: jsonlEntry,
				session: buildSessionSnapshot(state),
			});
			if (afterSteer) pi.sendUserMessage(afterSteer, { deliverAs: "steer" });

			const wallClockSeconds = runtime.lastRunDuration;
			runtime.runningExperiment = null;
			runtime.lastRunChecks = null;
			runtime.lastRunDuration = null;

			const limitReached =
				state.maxExperiments !== null && segmentCount >= state.maxExperiments;
			if (limitReached) {
				text += `\n\n🛑 Maximum experiments reached (${state.maxExperiments}). STOP.`;
				runtime.tuneMode = false;
				setTuneToolsActive(pi, false);
				releaseTuneLock(cwd, getSessionKey(ctx));
				ctx.abort();
			} else if (runtime.tuneMode) {
				const beforeSteer = await fireHook({
					event: "before",
					cwd,
					next_run: state.results.length + 1,
					last_run: jsonlEntry,
					session: buildSessionSnapshot(state),
				});
				if (beforeSteer)
					pi.sendUserMessage(beforeSteer, { deliverAs: "steer" });
			}

			updateWidget(ctx);
			if (overlayTui) overlayTui.requestRender();

			return {
				content: [{ type: "text", text }],
				details: {
					experiment: { ...experiment, metrics: { ...experiment.metrics } },
					state: cloneExperimentState(state),
					wallClockSeconds,
				} as LogDetails,
			};
		},

		renderCall(args, theme) {
			const color =
				args.status === "keep"
					? "success"
					: args.status === "crash" || args.status === "checks_failed"
						? "error"
						: "warning";
			return new Text(
				theme.fg("toolTitle", theme.bold("log_experiment ")) +
					theme.fg(color, args.status) +
					" " +
					theme.fg("dim", args.description),
				0,
				0,
			);
		},

		renderResult(result, _options, theme) {
			const d = result.details as LogDetails | undefined;
			if (!d) {
				const t = result.content[0];
				return new Text(t?.type === "text" ? t.text : "", 0, 0);
			}

			const { experiment: exp, state: s } = d;
			const color =
				exp.status === "keep"
					? "success"
					: exp.status === "crash" || exp.status === "checks_failed"
						? "error"
						: "warning";
			const icon =
				exp.status === "keep"
					? "✓"
					: exp.status === "crash"
						? "✗"
						: exp.status === "checks_failed"
							? "⚠"
							: "–";

			let text =
				theme.fg(color, `${icon} `) +
				theme.fg("accent", `#${s.results.length}`);

			const metricParts: string[] = [];
			if (d.wallClockSeconds != null)
				metricParts.push(`wall: ${d.wallClockSeconds.toFixed(1)}s`);
			if (exp.metric > 0)
				metricParts.push(
					`${s.metricName}: ${formatNum(exp.metric, s.metricUnit)}`,
				);
			if (metricParts.length > 0) {
				text +=
					theme.fg("dim", " (") +
					theme.fg("warning", metricParts.join(theme.fg("dim", ", "))) +
					theme.fg("dim", ")");
			}

			text += " " + theme.fg("muted", exp.description);

			if (s.bestMetric !== null) {
				let best = s.bestMetric;
				for (const r of s.results) {
					if (
						r.segment === s.currentSegment &&
						r.status === "keep" &&
						r.metric > 0
					) {
						if (isBetter(r.metric, best, s.bestDirection)) best = r.metric;
					}
				}
				text +=
					theme.fg("dim", " │ ") +
					theme.fg("warning", `★ best: ${formatNum(best, s.metricUnit)}`);
			}

			if (Object.keys(exp.metrics).length > 0) {
				const parts: string[] = [];
				for (const [name, value] of Object.entries(exp.metrics)) {
					const def = s.secondaryMetrics.find((m) => m.name === name);
					parts.push(`${name}=${formatNum(value, def?.unit ?? "")}`);
				}
				text += theme.fg("dim", `  ${parts.join(" ")}`);
			}

			return new Text(text, 0, 0);
		},
	});

	// ── Shortcuts ───────────────────────────────────────────────────────

	if (shortcuts.toggleDashboard) {
		pi.registerShortcut(
			shortcuts.toggleDashboard as Parameters<typeof pi.registerShortcut>[0],
			{
				description: "Toggle tune dashboard",
				handler: async (ctx) => {
					const runtime = getRuntime(ctx);
					if (runtime.state.results.length === 0) {
						ctx.ui.notify("No experiments yet", "info");
						return;
					}
					runtime.dashboardExpanded = !runtime.dashboardExpanded;
					updateWidget(ctx);
				},
			},
		);
	}

	if (shortcuts.fullscreenDashboard) {
		pi.registerShortcut(
			shortcuts.fullscreenDashboard as Parameters<
				typeof pi.registerShortcut
			>[0],
			{
				description: "Fullscreen tune dashboard",
				handler: async (ctx) => {
					const runtime = getRuntime(ctx);
					const state = runtime.state;
					if (state.results.length === 0) {
						ctx.ui.notify("No experiments yet", "info");
						return;
					}

					await ctx.ui.custom<void>(
						(tui, theme, _kb, done) => {
							let scrollOffset = 0;
							let lastViewportRows = 8;
							let lastTotalRows = 0;
							overlayTui = tui;

							spinnerInterval = setInterval(() => {
								spinnerFrame = (spinnerFrame + 1) % SPINNER.length;
								if (runtime.runningExperiment) tui.requestRender();
							}, 80);

							const buildOverlayContent = (renderWidth: number): string[] => {
								const content = renderDashboardLines(
									state,
									renderWidth,
									theme,
									0,
								);
								if (runtime.runningExperiment) {
									const elapsed = formatElapsed(
										Date.now() - runtime.runningExperiment.startedAt,
									);
									const frame = SPINNER[spinnerFrame % SPINNER.length];
									const nextIdx = state.results.length + 1;
									content.push(
										truncateToWidth(
											`  ${theme.fg("dim", String(nextIdx).padEnd(3))}` +
												theme.fg("warning", `${frame} running… ${elapsed}`),
											renderWidth,
											"…",
											true,
										),
									);
								}
								return content;
							};

							return {
								render(width: number): string[] {
									const { height } = getTuiSize(tui);
									const safeWidth = Math.max(1, width || getTuiSize(tui).width);
									const viewportRows = Math.max(4, height - 4);
									const content = buildOverlayContent(safeWidth);
									const totalRows = content.length;
									const maxScroll = Math.max(0, totalRows - viewportRows);
									scrollOffset = clamp(scrollOffset, 0, maxScroll);
									lastViewportRows = viewportRows;
									lastTotalRows = totalRows;

									const out: string[] = [];
									const title = truncateDisplayText(
										`🔬 tune${state.name ? `: ${state.name}` : ""}`,
										Math.max(0, safeWidth - 5),
									);
									const fillLen = Math.max(
										0,
										safeWidth - 3 - 1 - visibleWidth(title) - 1,
									);
									out.push(
										truncateToWidth(
											theme.fg("borderMuted", "───") +
												theme.fg("accent", ` ${title} `) +
												theme.fg("borderMuted", "─".repeat(fillLen)),
											safeWidth,
											"…",
											true,
										),
									);

									const visible = content.slice(
										scrollOffset,
										scrollOffset + viewportRows,
									);
									for (const line of visible)
										out.push(truncateToWidth(line, safeWidth, "…", true));
									for (let i = visible.length; i < viewportRows; i++)
										out.push("");

									const scrollInfo =
										totalRows > viewportRows
											? ` ${scrollOffset + 1}-${Math.min(scrollOffset + viewportRows, totalRows)}/${totalRows}`
											: "";
									const helpText =
										safeWidth >= 85
											? ` ↑↓/j/k scroll • pgup/pgdn • g/G • esc close${scrollInfo} `
											: ` j/k scroll • esc close${scrollInfo} `;
									const footFill = Math.max(
										0,
										safeWidth - visibleWidth(helpText),
									);
									out.push(
										truncateToWidth(
											theme.fg("borderMuted", "─".repeat(footFill)) +
												theme.fg("dim", helpText),
											safeWidth,
											"…",
											true,
										),
									);
									return out;
								},

								handleInput(data: string): void {
									const maxScroll = Math.max(
										0,
										lastTotalRows - lastViewportRows,
									);
									if (matchesKey(data, "escape") || data === "q") {
										done(undefined);
										return;
									}
									if (matchesKey(data, "up") || data === "k")
										scrollOffset = Math.max(0, scrollOffset - 1);
									else if (matchesKey(data, "down") || data === "j")
										scrollOffset = Math.min(maxScroll, scrollOffset + 1);
									else if (matchesKey(data, "pageUp") || data === "u")
										scrollOffset = Math.max(0, scrollOffset - lastViewportRows);
									else if (matchesKey(data, "pageDown") || data === "d")
										scrollOffset = Math.min(
											maxScroll,
											scrollOffset + lastViewportRows,
										);
									else if (data === "g") scrollOffset = 0;
									else if (data === "G") scrollOffset = maxScroll;
									tui.requestRender();
								},

								invalidate(): void {},
								dispose(): void {
									clearOverlay();
								},
							};
						},
						{
							overlay: true,
							overlayOptions: {
								width: "95%",
								maxHeight: "90%",
								anchor: "center" as const,
							},
						},
					);
				},
			},
		);
	}

	// ── Export dashboard server ─────────────────────────────────────────

	let dashboardServer: TuneDashboard | null = null;

	const TITLE_PLACEHOLDER = "__TUNE_TITLE__";

	function readTemplate(): string {
		return readDashboardTemplate();
	}

	function injectDataIntoTemplate(template: string, title: string): string {
		return template.replace(TITLE_PLACEHOLDER, () =>
			title.replace(/&/g, "&amp;").replace(/</g, "&lt;").replace(/>/g, "&gt;"),
		);
	}

	function broadcastDashboardUpdate(_cwd: string): void {
		dashboardServer?.broadcast();
	}

	function stopDashboardServer(): void {
		dashboardServer?.close();
		dashboardServer = null;
	}

	function openInBrowser(url: string): void {
		if (process.platform === "win32") {
			spawn("cmd", ["/c", "start", "", url], {
				detached: true,
				shell: true,
				stdio: "ignore",
			}).unref();
			return;
		}
		const openCmd = process.platform === "darwin" ? "open" : "xdg-open";
		spawn(openCmd, [url], { detached: true, stdio: "ignore" }).unref();
	}

	async function exportDashboard(ctx: ExtensionContext): Promise<void> {
		const jsonlPath = tuneJsonlPath(ctx.cwd);
		if (!fs.existsSync(jsonlPath)) {
			ctx.ui.notify(
				"No session.jsonl found — run some experiments first",
				"error",
			);
			return;
		}

		try {
			const template = readTemplate();
			if (!template) {
				ctx.ui.notify(
					"No dashboard template found (assets/template.html)",
					"error",
				);
				return;
			}

			const jsonlContent = fs.readFileSync(jsonlPath, "utf-8").trim();
			const sessionName = extractTuneSessionName(jsonlContent);
			const html = injectDataIntoTemplate(template, sessionName);
			if (dashboardServer) dashboardServer.update(html, jsonlPath);
			else dashboardServer = await startTuneDashboard(html, jsonlPath);

			openInBrowser(dashboardServer.url);
			ctx.ui.notify(
				`Dashboard at ${dashboardServer.url} (live updates)`,
				"info",
			);
		} catch (error) {
			ctx.ui.notify(
				`Export failed: ${error instanceof Error ? error.message : String(error)}`,
				"error",
			);
		}
	}

	// ── /tune command ───────────────────────────────────────────

	pi.registerCommand("tune", {
		description: "Start, stop, clear, or resume tune mode",
		getArgumentCompletions: tuneArgumentCompletions,
		handler: async (args, ctx) => {
			const runtime = getRuntime(ctx);
			const trimmedArgs = (args ?? "").trim();
			const command = trimmedArgs.toLowerCase();

			if (!trimmedArgs) {
				ctx.ui.notify(tuneHelp(), "info");
				return;
			}

			if (command === "off") {
				const wasRunning = !ctx.isIdle();
				releaseTuneLock(ctx.cwd, getSessionKey(ctx));
				runtime.tuneMode = false;
				setTuneToolsActive(pi, false);
				runtime.dashboardExpanded = false;
				runtime.autoResumeTurns = 0;
				runtime.experimentsThisSession = 0;
				runtime.lastRunChecks = null;
				runtime.lastRunDuration = null;
				runtime.runningExperiment = null;
				cancelPendingResume(runtime);
				stopDashboardServer();
				clearSessionUi(ctx);
				if (wasRunning) ctx.abort();
				ctx.ui.notify(
					wasRunning ? "Tune OFF — aborting current run" : "Tune OFF",
					"info",
				);
				return;
			}

			if (command === "export") {
				await exportDashboard(ctx);
				return;
			}

			if (command === "clear") {
				releaseTuneLock(ctx.cwd, getSessionKey(ctx));
				const jsonlPath = tuneJsonlPath(ctx.cwd);
				runtime.tuneMode = false;
				setTuneToolsActive(pi, false);
				runtime.dashboardExpanded = false;
				runtime.autoResumeTurns = 0;
				runtime.experimentsThisSession = 0;
				runtime.lastRunChecks = null;
				runtime.lastRunDuration = null;
				runtime.runningExperiment = null;
				cancelPendingResume(runtime);
				runtime.state = createExperimentState();
				stopDashboardServer();
				updateWidget(ctx);

				if (fs.existsSync(jsonlPath)) {
					try {
						fs.unlinkSync(jsonlPath);
						ctx.ui.notify("Deleted session.jsonl and turned tune OFF", "info");
					} catch (error) {
						ctx.ui.notify(
							`Failed to delete session.jsonl: ${error instanceof Error ? error.message : String(error)}`,
							"error",
						);
					}
				} else {
					ctx.ui.notify("No session.jsonl found. Tune OFF", "info");
				}
				return;
			}

			if (runtime.tuneMode) {
				ctx.ui.notify("Already active — use '/tune off' to stop", "info");
				return;
			}

			const lock = acquireTuneLock(ctx.cwd, getSessionKey(ctx));
			if (!lock.ok) {
				ctx.ui.notify(
					`Tune already active in session ${lock.owner}`,
					"warning",
				);
				return;
			}

			runtime.tuneMode = true;
			setTuneToolsActive(pi, true);
			runtime.autoResumeTurns = 0;

			const rulesLoaded = hasTuneRules(ctx);
			const kickoff = rulesLoaded
				? `Tune active. ${trimmedArgs} ${BENCHMARK_GUARDRAIL}`
				: `Start tune: ${trimmedArgs} ${BENCHMARK_GUARDRAIL}`;

			ctx.ui.notify(
				rulesLoaded
					? "Tune started — resumed from session.md"
					: "Tune started — setting up experiment loop",
				"info",
			);

			const activationSteer = await fireHook({
				event: "before",
				cwd: ctx.cwd,
				next_run: runtime.state.results.length + 1,
				last_run: readLastRun(ctx.cwd),
				session: buildSessionSnapshot(runtime.state),
			});

			sendWhenReady(
				ctx,
				activationSteer ? `${activationSteer}\n\n${kickoff}` : kickoff,
			);
		},
	});
}