import test, { type TestContext } from "node:test";
import assert from "node:assert/strict";
import { mkdtempSync, mkdirSync, writeFileSync, readFileSync, rmSync } from "node:fs";
import { tmpdir } from "node:os";
import path from "node:path";
import type { ExtensionContext } from "@earendil-works/pi-coding-agent";
import { createGoal, goalFocusDetails, cloneGoal, normalizeGoalRecord } from "../extensions/goal-record.ts";
import { writeActiveGoalFile, parseGoalFile } from "../extensions/storage/goal-files.ts";
import { invalidateGoalSettingsCache } from "../extensions/settings/files.ts";
import { loadGoalSettings } from "../extensions/settings/resolve.ts";
import { newGoalScheduler, normalizeGoalScheduler, schedulerSummary } from "../extensions/goal-scheduler-state.ts";
import { clearGoalDrafting, hasActiveDraft, startGoalDrafting } from "../extensions/goal-drafting.ts";
import { createExtensionHarness } from "./support/extension-harness.ts";
import { writeProjectSettings, parseSettings } from "./support/settings.ts";

async function fixture(t: TestContext, limit?: number, owner = "owner", existing?: string, strict = true, idleBackoff = false) {
	const cwd = existing ?? mkdtempSync(path.join(tmpdir(), "goal-scheduler-"));
	const prior = process.env.PI_GOAL_GLOBAL_SETTINGS_FILE;
	process.env.PI_GOAL_GLOBAL_SETTINGS_FILE = path.join(cwd, "absent-global.json");
	if (!existing) {
		mkdirSync(path.join(cwd, ".pi"), { recursive: true });
		writeFileSync(path.join(cwd, ".pi", "pi-goal-x-settings.json"), JSON.stringify({ strictExecutionContract: strict, ...(idleBackoff ? { idleContinuationBackoff: true } : {}), ...(limit !== undefined ? { maxAutonomousRuns: limit } : {}) }));
	}
	invalidateGoalSettingsCache();
	const goal = createGoal({ objective: "Test explicit scheduling", autoContinue: true, sisyphus: false });
	goal.id = "scheduler-fixture";
	if (!existing) writeActiveGoalFile({ cwd }, goal);
	const listeners = new Map<string, Function>();
	const events = { on: (name: string, fn: Function) => { listeners.set(name, fn); return () => listeners.delete(name); }, emit: (name: string, event: unknown) => listeners.get(name)?.(event) };
	const harness = createExtensionHarness({
		cwd,
		sessionId: owner,
		sessionEntries: [{ type: "custom", customType: "pi-goal-focus", data: goalFocusDetails(goal.id, "created") }],
		pi: { getActiveTools: () => ["read", "write", "bash"], events },
	});
	const { core, ctx } = harness;
	await core.focus.load(ctx);
	core.scheduler.attach(ctx);
	t.after(() => {
		core.scheduler.shutdown(); core.runtime.clearContinuationState();
		if (!existing) rmSync(cwd, { recursive: true, force: true });
		if (prior === undefined) delete process.env.PI_GOAL_GLOBAL_SETTINGS_FILE; else process.env.PI_GOAL_GLOBAL_SETTINGS_FILE = prior;
		invalidateGoalSettingsCache();
	});
	const begin = () => core.scheduler.begin(ctx);
	const admit = () => { begin(); core.scheduler.message(ctx, { ...harness.sentMessages.at(-1), role: "custom" }); };
	const ready = () => core.scheduler.declare(ctx, { kind: "ready" });
	const wait = () => core.scheduler.declare(ctx, { kind: "wait", reason: "Await fixture job", deadline: new Date(Date.now() + 10000).toISOString(), polling: { interval_seconds: 1, max_checks: 2 } });
	return Object.assign(harness, { cwd, events, handlers: Object.fromEntries(harness.handlers) as Record<string, Function>, sent: harness.sentMessages, begin, admit, ready, wait, aborts: () => harness.abortCount });
}

/** The usage line only goes out with a token budget or showContextUsage, so these tests ask for it. */
function showUsageLine(cwd: string): void {
	const file = path.join(cwd, ".pi", "pi-goal-x-settings.json");
	writeFileSync(file, JSON.stringify({ ...JSON.parse(readFileSync(file, "utf8")), showContextUsage: true }));
	invalidateGoalSettingsCache();
}

test("explicit zero means no automatic model runs, even for missing disposition", async t => {
	const h = await fixture(t, 0);
	t.mock.timers.enable({ apis: ["setTimeout", "Date"] });
	h.begin();
	assert.equal(h.ready().terminate, false);
	h.core.scheduler.settled(h.ctx);
	t.mock.timers.tick(10000);
	assert.equal(h.sent.length, 0);
	assert.equal(h.core.state.goal?.status, "paused");
	assert.match(h.core.state.goal?.pauseReason ?? "", /disabled by maxAutonomousRuns=0/);
});

for (const start of ["creation", "resume"] as const) {
	test(`strict ${start} starts automatically and still allows only one repair`, async t => {
		const h = await fixture(t);
		t.mock.timers.enable({ apis: ["setTimeout", "Date"] });
		if (start === "creation") h.core.lifecycle.create({ objective: "Work automatically", autoContinue: true, sisyphus: false }, h.ctx);
		else assert.equal(h.core.scheduler.resume(h.ctx), true);
		t.mock.timers.tick(1);
		assert.equal(h.sent.length, 1);
		h.admit(); h.core.scheduler.settled(h.ctx); t.mock.timers.tick(1);
		assert.equal(h.core.state.goal?.scheduler?.dispatch?.kind, "repair");
		h.admit(); h.core.scheduler.settled(h.ctx); t.mock.timers.tick(10000);
		assert.equal(h.sent.length, 2);
		assert.equal(h.core.state.goal?.status, "paused");
		assert.match(h.core.state.goal?.pauseReason ?? "", /No execution disposition/);
	});
}

test("uncapped ready runs keep counting when limits are added and removed", async t => {
	const h = await fixture(t);
	t.mock.timers.enable({ apis: ["setTimeout", "Date"] });
	h.begin();
	for (let used = 1; used <= 5; used++) {
		assert.equal(h.ready().terminate, true);
		h.core.scheduler.settled(h.ctx); t.mock.timers.tick(1); h.admit();
		assert.equal(h.core.state.goal?.scheduler?.used, used);
	}
	// Uncapped runs still count. The summary reports nothing while the allowance is
	// unlimited, because there is no limit to report.
	assert.equal(h.core.state.goal?.scheduler?.used, 5);
	assert.equal(schedulerSummary(h.core.state.goal?.scheduler), "");
	assert.match(schedulerSummary(h.core.state.goal?.scheduler, 5), /5\/5/);
	writeProjectSettings(h.cwd, { maxAutonomousRuns: 5 });
	assert.equal(h.ready().terminate, false, "adding a cap includes previously uncapped dispatches");
	writeProjectSettings(h.cwd, {});
	assert.equal(h.ready().terminate, true, "removing the cap re-enables continuation");
	h.core.scheduler.settled(h.ctx); t.mock.timers.tick(1); h.admit();
	assert.equal(h.core.state.goal?.scheduler?.used, 6);
	writeProjectSettings(h.cwd, { maxAutonomousRuns: 6 });
	h.core.scheduler.settled(h.ctx); t.mock.timers.tick(1);
	assert.equal(h.sent.length, 6);
	assert.equal(h.core.state.goal?.status, "paused");
	assert.equal(h.core.state.goal?.scheduler?.used, 6);
});

test("every tool category requires the same declaration; one repair then pause", async t => {
	const h = await fixture(t, 10);
	t.mock.timers.enable({ apis: ["setTimeout", "Date"] });
	for (const name of ["read", "write", "bash", "custom_tool", "update_goal_task"]) {
		h.core.scheduler.resume(h.ctx); t.mock.timers.tick(1); h.admit();
		await h.handlers.tool_call!({ toolName: name, args: {} }, h.ctx);
		h.core.scheduler.settled(h.ctx); t.mock.timers.tick(1);
		assert.equal(h.core.state.goal?.scheduler?.dispatch?.kind, "repair", name);
		h.admit(); h.core.scheduler.settled(h.ctx); t.mock.timers.tick(1);
		assert.equal(h.core.state.goal?.status, "paused", name);
		assert.equal(h.core.state.goal?.scheduler?.used, 2, name);
	}
});

test("declarations persist before termination, claim once, and settings changes never reset spent runs", async t => {
	const h = await fixture(t, 2);
	t.mock.timers.enable({ apis: ["setTimeout", "Date"] });
	h.begin(); assert.equal(h.ready().terminate, true);
	const disk = parseGoalFile(path.resolve(h.cwd, h.core.state.goal!.activePath!));
	assert.equal(disk?.scheduler?.phase, "ready");
	assert.equal(h.sent.length, 0);
	h.core.scheduler.settled(h.ctx); t.mock.timers.tick(1);
	assert.equal(h.core.state.goal?.scheduler?.used, 1);
	h.admit(); assert.equal(h.ready().terminate, true); h.core.scheduler.settled(h.ctx); t.mock.timers.tick(1);
	assert.equal(h.core.state.goal?.scheduler?.used, 2);
	h.admit(); assert.equal(h.ready().terminate, false);
	writeProjectSettings(h.cwd, { maxAutonomousRuns: 3 });
	assert.equal(h.ready().terminate, true);
	h.core.scheduler.settled(h.ctx); t.mock.timers.tick(1);
	assert.equal(h.core.state.goal?.scheduler?.used, 3);
	assert.equal(h.sent.length, 3);
	h.core.scheduler.message(h.ctx, { ...h.sent[0], role: "custom" });
	assert.equal(h.aborts(), 1, "duplicate or stale generation is rejected");
});

test("early wake and check timer race produce one claimed run", async t => {
	const h = await fixture(t, 5);
	t.mock.timers.enable({ apis: ["setTimeout", "Date"] });
	h.begin(); assert.equal(h.wait().terminate, true);
	const w = h.core.state.goal!.scheduler!.wait!;
	h.events.emit("pi-goal:wake", { goalId: h.core.state.goal!.id, waitToken: w.token });
	assert.equal(h.sent.length, 0, "signal before settlement must not start a run");
	h.core.scheduler.settled(h.ctx); t.mock.timers.tick(1);
	h.events.emit("pi-goal:wake", { goalId: h.core.state.goal!.id, waitToken: w.token });
	t.mock.timers.tick(1000);
	assert.equal(h.sent.length, 1);
	assert.equal(h.core.state.goal?.scheduler?.dispatch?.kind, "wake");
	assert.equal(h.core.state.goal?.scheduler?.wait?.remainingChecks, 2);
});

test("checks retain identity, deadline and finite count across redeclaration", async t => {
	const h = await fixture(t, 5);
	t.mock.timers.enable({ apis: ["setTimeout", "Date"] });
	h.begin(); h.wait();
	const first = structuredClone(h.core.state.goal!.scheduler!.wait!);
	h.core.scheduler.settled(h.ctx); t.mock.timers.tick(999); assert.equal(h.sent.length, 0); t.mock.timers.tick(2);
	assert.equal(h.sent.length, 1); h.admit();
	assert.equal(h.wait().terminate, false, "new wait cannot reset an existing check");
	const redeclare = () => h.core.scheduler.declare(h.ctx, { kind: "wait", wait_id: first.id, reason: first.reason, deadline: new Date(first.deadline).toISOString() });
	assert.equal(redeclare().terminate, true);
	assert.equal(h.core.state.goal?.scheduler?.wait?.remainingChecks, 1);
	h.core.scheduler.settled(h.ctx); t.mock.timers.tick(1001); h.admit();
	assert.equal(redeclare().terminate, true);
	h.core.scheduler.settled(h.ctx);
	assert.equal(h.core.state.goal?.status, "paused");
	assert.match(h.core.state.goal?.pauseReason ?? "", /check allowance exhausted/);
	assert.equal(h.sent.length, 2);
});

test("waiting restores with no catch-up; claimed dispatch never replays", async t => {
	const h = await fixture(t, 5);
	t.mock.timers.enable({ apis: ["setTimeout", "Date"] });
	h.begin(); h.wait(); h.core.scheduler.settled(h.ctx); h.core.scheduler.shutdown();
	t.mock.timers.tick(4000);
	const resumed = await fixture(t, undefined, "owner", h.cwd);
	resumed.core.scheduler.restore(resumed.ctx); t.mock.timers.tick(1);
	assert.equal(resumed.sent.length, 1, "missed checks coalesce into one");
	resumed.core.scheduler.shutdown();
	const interrupted = await fixture(t, undefined, "owner", h.cwd);
	interrupted.core.scheduler.restore(interrupted.ctx); t.mock.timers.tick(10000);
	assert.equal(interrupted.sent.length, 0);
	assert.equal(interrupted.core.state.goal?.status, "paused");
});

test("deadline expiration and another session cannot wake a sleeping goal", async t => {
	const h = await fixture(t, 5);
	t.mock.timers.enable({ apis: ["setTimeout", "Date"] });
	h.begin(); h.core.scheduler.declare(h.ctx, { kind: "wait", reason: "External event", deadline: new Date(Date.now() + 2000).toISOString() });
	h.core.scheduler.settled(h.ctx);
	const other = await fixture(t, undefined, "other-owner", h.cwd);
	other.core.scheduler.restore(other.ctx);
	assert.equal(other.ready().terminate, false);
	t.mock.timers.tick(2000);
	assert.equal(h.sent.length + other.sent.length, 0);
	assert.match(h.core.state.goal?.pauseReason ?? "", /deadline/);
});

test("a later model turn invalidates a decision and user takeover cancels delivery", async t => {
	const h = await fixture(t, 5);
	t.mock.timers.enable({ apis: ["setTimeout", "Date"] });
	h.begin(); h.ready(); h.core.scheduler.turn(h.ctx);
	assert.equal(h.core.state.goal?.scheduler?.decision, undefined);
	h.ready(); h.core.scheduler.settled(h.ctx);
	h.core.scheduler.takeover(h.ctx); t.mock.timers.tick(10000);
	assert.equal(h.sent.length, 0);
	assert.equal(h.core.state.goal?.scheduler?.used, 0);
});

test("update_goal rejects mixed forms and scheduler cloning protects rollback", async t => {
	const h = await fixture(t, 5);
	h.begin();
	const tool = h.tools.get("update_goal");
	const mixed = await tool.execute("mixed", { status: "complete", continuation: { kind: "wait", reason: "external job", deadline: "2099-01-01T00:00:00Z" } }, undefined, undefined, h.ctx);
	assert.equal(mixed.terminate, false);
	assert.equal(mixed.isError, true);
	h.ready();
	const before = structuredClone(h.core.state.goal!.scheduler);
	const clone = cloneGoal(h.core.state.goal!); clone.scheduler!.used = 999;
	assert.deepEqual(h.core.state.goal!.scheduler, before);
	assert.deepEqual(normalizeGoalRecord(h.core.state.goal)?.scheduler, before);
	const invalid = normalizeGoalScheduler({ ...before, used: -1 });
	assert.equal(invalid?.phase, "interrupted");
	assert.equal(invalid?.used, Number.MAX_SAFE_INTEGER);
});

test("maxAutonomousRuns is strictly parsed, layered, and removable", async t => {
	const h = await fixture(t);
	for (const n of [-1, 1.1, "1x", Number.MAX_SAFE_INTEGER + 1]) assert.equal(parseSettings({ maxAutonomousRuns: n }).maxAutonomousRuns, undefined);
	for (const n of [0, "0", 1, "25", Number.MAX_SAFE_INTEGER]) assert.equal(parseSettings({ maxAutonomousRuns: n }).maxAutonomousRuns, Number(n));
	writeProjectSettings(h.cwd, { maxAutonomousRuns: 4 }); assert.equal(loadGoalSettings(h.cwd).maxAutonomousRuns, 4);
	writeProjectSettings(h.cwd, {}); assert.equal(loadGoalSettings(h.cwd).maxAutonomousRuns, undefined);
});

test("project zero disables an inherited allowance without renewing consumption", async t => {
	const h = await fixture(t);
	writeFileSync(process.env.PI_GOAL_GLOBAL_SETTINGS_FILE!, JSON.stringify({ maxAutonomousRuns: 20 }));
	invalidateGoalSettingsCache();
	t.mock.timers.enable({ apis: ["setTimeout", "Date"] });
	h.begin(); h.ready(); h.core.scheduler.settled(h.ctx); t.mock.timers.tick(1); h.admit();
	assert.equal(h.core.state.goal?.scheduler?.used, 1);
	h.ready(); h.core.scheduler.settled(h.ctx);
	writeProjectSettings(h.cwd, { maxAutonomousRuns: 0 });
	invalidateGoalSettingsCache();
	assert.equal(loadGoalSettings(h.cwd).maxAutonomousRuns, 0, "zero survives persistence and overrides global 20");
	assert.match(schedulerSummary(h.core.state.goal?.scheduler, 0), /1\/0 \(automatic continuation disabled\)/);
	t.mock.timers.tick(1);
	assert.equal(h.sent.length, 1, "pending delivery is cancelled");
	assert.equal(h.core.state.goal?.status, "paused");
	assert.equal(h.core.scheduler.resume(h.ctx), false);
	writeProjectSettings(h.cwd, {});
	assert.equal(loadGoalSettings(h.cwd).maxAutonomousRuns, 20, "unsetting restores inheritance");
	assert.equal(h.core.state.goal?.scheduler?.used, 1);
	assert.equal(h.sent.length, 1);
});

for (const kind of ["recovery", "repair"] as const) {
	for (const expiry of ["before scheduling", "before delivery"] as const) {
		test(`${kind} respects an outstanding wait deadline expiring ${expiry}`, async t => {
			const h = await fixture(t, 10);
			t.mock.timers.enable({ apis: ["setTimeout", "Date"] });
			h.begin();
			assert.equal(h.core.scheduler.declare(h.ctx, { kind: "wait", reason: "Await job", deadline: new Date(Date.now() + 3000).toISOString(), polling: { interval_seconds: 1, max_checks: 2 } }).terminate, true);
			h.core.scheduler.settled(h.ctx); t.mock.timers.tick(1001); h.admit();
			let busy = true;
			const ctx = { ...h.ctx, isIdle: () => !busy };
			if (expiry === "before scheduling") t.mock.timers.tick(2000);
			h.core.scheduler.settled(ctx, kind === "repair");
			if (kind === "recovery") h.core.scheduler.recover(ctx);
			if (expiry === "before delivery") {
				assert.equal(h.core.state.goal?.scheduler?.phase, "ready");
				assert.equal(h.core.state.goal?.scheduler?.decision?.kind, "ready");
				t.mock.timers.tick(2000);
			}
			busy = false; t.mock.timers.tick(50);
			assert.equal(h.sent.length, 1, "no dispatch after the polling check");
			assert.equal(h.core.state.goal?.scheduler?.used, 1, "denied dispatch spends no allowance");
			assert.equal(h.core.state.goal?.status, "paused");
			assert.match(h.core.state.goal?.pauseReason ?? "", /Wait deadline reached/);
		});
	}
}

test("network backoff crossing a wait deadline cannot dispatch recovery", async t => {
	const h = await fixture(t);
	t.mock.timers.enable({ apis: ["setTimeout", "Date"] });
	h.begin();
	h.core.scheduler.declare(h.ctx, { kind: "wait", reason: "Await job", deadline: new Date(Date.now() + 3000).toISOString(), polling: { interval_seconds: 1, max_checks: 2 } });
	h.core.scheduler.settled(h.ctx); t.mock.timers.tick(1001); h.admit();
	h.core.scheduler.settled(h.ctx, false);
	const plan = h.core.runtime.scheduleNetworkErrorRetry(h.ctx, h.core.state.goal!);
	assert.equal(plan?.delayMs, 5000);
	t.mock.timers.tick(5001);
	assert.equal(h.sent.length, 1);
	assert.equal(h.core.state.goal?.scheduler?.used, 1);
	assert.equal(h.core.state.goal?.status, "paused");
	assert.match(h.core.state.goal?.pauseReason ?? "", /Wait deadline reached/);
});

test("lowering allowance before delivery stops the wake without resetting usage", async t => {
	const h = await fixture(t, 2);
	t.mock.timers.enable({ apis: ["setTimeout", "Date"] });
	h.begin(); h.ready(); h.core.scheduler.settled(h.ctx);
	writeProjectSettings(h.cwd, { maxAutonomousRuns: 0 });
	t.mock.timers.tick(1);
	assert.equal(h.sent.length, 0);
	assert.equal(h.core.state.goal?.scheduler?.used, 0);
	assert.equal(h.core.state.goal?.status, "paused");
});

test("a previous owner's callback cannot dispatch or pause the new owner's goal", async t => {
	const h = await fixture(t, 5);
	t.mock.timers.enable({ apis: ["setTimeout", "Date"] });
	h.begin(); h.ready(); h.core.scheduler.settled(h.ctx);
	const other = await fixture(t, undefined, "new-owner", h.cwd);
	assert.equal(other.core.scheduler.resume(other.ctx), true);
	t.mock.timers.tick(1);
	assert.equal(h.sent.length, 0);
	assert.equal(other.sent.length, 1);
	assert.equal(other.core.state.goal?.status, "active");
	assert.equal(parseGoalFile(path.resolve(h.cwd, other.core.state.goal!.activePath!))?.status, "active");
});

test("persistence rejection cannot report a saved decision or dispatch", async t => {
	const h = await fixture(t, 5);
	h.begin();
	const apply = h.core.goalService.apply.bind(h.core.goalService);
	h.core.goalService.apply = () => ({ ok: false, message: "Injected storage conflict" });
	assert.equal(h.ready().terminate, false);
	assert.equal(h.core.state.goal?.scheduler?.decision, undefined);
	assert.equal(h.sent.length, 0);
	h.core.goalService.apply = apply;
});

test("readiness polling, failure after claim, and active-time waiting", async t => {
	const h = await fixture(t, 5);
	t.mock.timers.enable({ apis: ["setTimeout", "Date"] });
	let busy = true;
	const ctx = { ...h.ctx, hasPendingMessages: () => busy };
	h.core.scheduler.begin(ctx); h.core.scheduler.declare(ctx, { kind: "ready" }); h.core.scheduler.settled(ctx);
	t.mock.timers.tick(200);
	assert.equal(h.sent.length, 0);
	assert.equal(h.core.state.goal?.scheduler?.used, 0);
	busy = false; t.mock.timers.tick(50);
	assert.equal(h.sent.length, 1);
	assert.equal(h.core.state.goal?.scheduler?.used, 1);
	h.core.scheduler.failedDispatch(ctx);
	assert.equal(h.core.state.goal?.status, "paused");
	assert.equal(h.core.state.goal?.scheduler?.used, 1);
	h.core.scheduler.resume(ctx); t.mock.timers.tick(1); h.admit(); h.wait(); h.core.scheduler.settled(ctx);
	const before = h.core.state.goal!.usage.activeSeconds;
	t.mock.timers.tick(500);
	assert.equal(h.core.view.goalForDisplay()?.usage.activeSeconds, before);
});


test("explicit resume during an execution waits for settlement and dispatches kickoff, not repair", async t => {
	const h = await fixture(t, 2);
	t.mock.timers.enable({ apis: ["setTimeout", "Date"] });
	h.begin();
	assert.equal(h.core.scheduler.resume(h.ctx), true);
	t.mock.timers.tick(100);
	assert.equal(h.sent.length, 0);
	h.core.scheduler.settled(h.ctx);
	t.mock.timers.tick(1);
	assert.equal(h.core.state.goal?.scheduler?.dispatch?.kind, "kickoff");
	assert.equal(h.core.state.goal?.scheduler?.used, 1);
});

// Default policy preserves immediate reasoning-only and final-task wrap-up runs.
test("implicit executions continue without tools through task completion and wrap-up", async t => {
	const h = await fixture(t, undefined, "owner", undefined, false);
	t.mock.timers.enable({ apis: ["setTimeout", "Date"] });
	h.core.goalService.apply(h.ctx, {mutate: g => ({...g, taskList: {proposedAt: new Date().toISOString(), tasks: [{id: "one", title: "One", status: "pending"}, {id: "two", title: "Two", status: "pending"}], blockCompletion: false}})});
	h.begin();
	for (const id of [undefined, "one", "two", undefined]) {
		if (id) await h.tools.get("update_goal_task").execute("test", {task_id: id, status: "complete"}, undefined, undefined, h.ctx);
		h.core.scheduler.settled(h.ctx); t.mock.timers.tick(1);
		assert.equal(h.core.state.goal?.scheduler?.dispatch?.kind, "ready");
		assert.equal(h.core.state.goal?.status, "active");
		h.admit();
	}
	assert.equal(h.sent.length, 4);
	assert.equal(h.core.state.goal?.scheduler?.used, 4);
	assert.ok(h.core.state.goal?.taskList?.tasks.every(task => task.status === "complete"));
});

test("default continuation does not inspect goal content or delay reasoning/custom tools", async t => {
	const h = await fixture(t, undefined, "owner", undefined, false);
	t.mock.timers.enable({ apis: ["setTimeout", "Date"] });
	(h.core.scheduler as unknown as { goalContent: () => never }).goalContent = () => { throw new Error("Default must skip pacing snapshots"); };
	h.begin();
	for (let i = 0; i < 12; i++) {
		if (i % 2) await h.handlers.tool_call!({ toolName: "publish_report", input: { stage: i } }, h.ctx);
		h.core.scheduler.settled(h.ctx); t.mock.timers.tick(1);
		assert.equal(h.sent.length, i + 1);
		assert.equal(h.core.state.goal?.scheduler?.idle, undefined);
		h.admit();
	}
});

test("old saved delays without explicit opt-in are ignored on restore and in status", async t => {
	const h = await fixture(t, undefined, "owner", undefined, false);
	t.mock.timers.enable({ apis: ["setTimeout", "Date"] });
	h.core.goalService.apply(h.ctx, { mutate: g => ({ ...g, scheduler: { ...newGoalScheduler("owner"), used: 7, phase: "ready", decision: { kind: "ready", purpose: "ready" }, idle: { runs: 4, nextAt: Date.now() + 120000 } } }) });
	assert.doesNotMatch(schedulerSummary(h.core.state.goal?.scheduler), /Next automatic|delay off/);
	assert.equal(h.core.scheduler.isWaiting(), false);
	h.core.scheduler.restore(h.ctx); t.mock.timers.tick(1);
	assert.equal(h.sent.length, 1);
	assert.equal(h.core.state.goal?.scheduler?.used, 8);
	assert.equal(h.core.state.goal?.scheduler?.idle, undefined);
});

test("disabling a pending delay dispatches promptly without renewing spent allowance", async t => {
	const h = await fixture(t, 20, "owner", undefined, false, true);
	t.mock.timers.enable({ apis: ["setTimeout", "Date"] });
	h.begin(); h.core.scheduler.settled(h.ctx); t.mock.timers.tick(1); h.admit(); h.core.scheduler.settled(h.ctx);
	assert.equal(h.core.scheduler.isWaiting(), true);
	writeProjectSettings(h.cwd, { idleContinuationBackoff: false, maxAutonomousRuns: 20 });
	h.core.scheduler.refreshSettings(h.ctx); t.mock.timers.tick(1);
	assert.equal(h.sent.length, 2);
	assert.equal(h.core.state.goal?.scheduler?.used, 2);
	assert.equal(h.core.state.goal?.scheduler?.idle, undefined);
	h.admit();
	t.mock.timers.tick(30000);
	assert.equal(h.sent.length, 2, "obsolete idle timer cannot spend twice");
});

test("enabling during work and off/on edits do not retroactively classify an execution", async t => {
	const h = await fixture(t, undefined, "owner", undefined, false);
	const idle = () => h.core.state.goal?.scheduler?.idle;
	t.mock.timers.enable({ apis: ["setTimeout", "Date"] });
	h.begin();
	writeProjectSettings(h.cwd, { idleContinuationBackoff: true });
	h.core.scheduler.refreshSettings(h.ctx);
	h.core.scheduler.settled(h.ctx); t.mock.timers.tick(1); h.admit();
	assert.equal(idle(), undefined);
	h.core.scheduler.settled(h.ctx); t.mock.timers.tick(1); h.admit();
	assert.equal(idle()?.runs, 1);
	writeProjectSettings(h.cwd, { idleContinuationBackoff: false }); h.core.scheduler.refreshSettings(h.ctx);
	writeProjectSettings(h.cwd, { idleContinuationBackoff: true }); h.core.scheduler.refreshSettings(h.ctx);
	h.core.scheduler.settled(h.ctx); t.mock.timers.tick(1);
	assert.equal(h.sent.length, 3);
	assert.equal(idle(), undefined);
});

test("claim drops a saved delay if the preference was disabled after scheduling", async t => {
	const h = await fixture(t, undefined, "owner", undefined, false, true);
	t.mock.timers.enable({ apis: ["setTimeout", "Date"] });
	h.begin(); h.core.scheduler.settled(h.ctx);
	h.core.goalService.apply(h.ctx, { mutate: g => ({ ...g, scheduler: { ...g.scheduler!, used: 3, idle: { runs: 2, nextAt: Date.now() + 30000 } } }) });
	writeProjectSettings(h.cwd, { idleContinuationBackoff: false });
	t.mock.timers.tick(1);
	assert.equal(h.sent.length, 1);
	assert.equal(h.core.state.goal?.scheduler?.used, 4);
	assert.equal(h.core.state.goal?.scheduler?.idle, undefined);
});

test("repeated opted-in idle executions back off durably, cap at five minutes and spend only on delivery", async t => {
	const h = await fixture(t, undefined, "owner", undefined, false, true);
	t.mock.timers.enable({ apis: ["setTimeout", "Date"] });
	h.begin();
	for (const [index, delay] of [0, 30_000, 60_000, 120_000, 240_000, 300_000, 300_000].entries()) {
		h.core.scheduler.settled(h.ctx);
		assert.equal(h.core.state.goal?.status, "active");
		assert.equal(h.core.state.goal?.scheduler?.used, index);
		if (delay) {
			assert.match(schedulerSummary(h.core.state.goal?.scheduler, undefined, true, true), /Next automatic attempt in .*s/);
			const disk = parseGoalFile(path.resolve(h.cwd, h.core.state.goal!.activePath!));
			assert.deepEqual(disk?.scheduler, h.core.state.goal?.scheduler, "pacing is saved before waiting");
			h.core.scheduler.schedule(h.ctx);
			t.mock.timers.tick(delay - 1);
			assert.equal(h.sent.length, index, "rescheduling cannot skip a saved delay");
		}
		t.mock.timers.tick(1);
		assert.equal(h.sent.length, index + 1);
		assert.equal(h.core.state.goal?.scheduler?.used, index + 1);
		h.admit();
	}
});

test("work in an earlier tool turn resets idle pacing for the entire logical run", async t => {
	const h = await fixture(t, undefined, "owner", undefined, false, true);
	t.mock.timers.enable({ apis: ["setTimeout", "Date"] });
	h.begin(); h.core.scheduler.settled(h.ctx); t.mock.timers.tick(1); h.admit();
	await h.handlers.turn_start!({}, h.ctx);
	await h.handlers.tool_call!({ toolName: "write", input: { path: "result.txt", content: "done" } }, h.ctx);
	// A second agent_start can occur during native retry or compaction.
	h.begin();
	await h.handlers.turn_start!({}, h.ctx);
	assert.equal(h.core.state.goalWorkToolCalledThisTurn, false, "last-turn flag alone misses earlier work");
	h.core.goalService.flushTurn(h.ctx);
	h.core.scheduler.settled(h.ctx); t.mock.timers.tick(1);
	assert.equal(h.sent.length, 2, "the completed execution continues immediately");
	h.admit(); h.core.scheduler.settled(h.ctx); t.mock.timers.tick(1);
	assert.equal(h.sent.length, 3, "work reset the single idle grace execution");
});

for (const [toolName, input] of [
	["get_goal", {}], ["read", { path: ".pi/goals/active_goal_fixture.md" }],
	["bash", { command: "echo 'Standing by'" }], ["bg_wait", { id: "running-job" }],
	["subagent", { action: "status", id: "running-job" }],
] as const) test(`inspection-only ${toolName} does not erase idle pacing`, async t => {
	const h = await fixture(t, undefined, "owner", undefined, false, true);
	t.mock.timers.enable({ apis: ["setTimeout", "Date"] });
	h.begin(); h.core.scheduler.settled(h.ctx); t.mock.timers.tick(1); h.admit();
	await h.handlers.tool_call!({ toolName, input }, h.ctx);
	// Accounting/persistence and scheduler admission always bump revisions.
	h.core.goalService.apply(h.ctx, { mutate: g => ({ ...g, usage: { tokensUsed: 1000, activeSeconds: 3 } }) });
	h.core.scheduler.settled(h.ctx); t.mock.timers.tick(29_999);
	assert.equal(h.sent.length, 1);
	t.mock.timers.tick(1);
	assert.equal(h.sent.length, 2);
});

test("optional default ready decisions do not bypass repeated-idle pacing", async t => {
	const h = await fixture(t, undefined, "owner", undefined, false, true);
	t.mock.timers.enable({ apis: ["setTimeout", "Date"] });
	h.begin(); h.ready(); h.core.scheduler.settled(h.ctx); t.mock.timers.tick(1); h.admit();
	h.ready(); h.core.scheduler.settled(h.ctx); t.mock.timers.tick(29_999);
	assert.equal(h.sent.length, 1);
	t.mock.timers.tick(1);
	assert.equal(h.sent.length, 2);
});

test("restoring a paced goal preserves its deadline; explicit resume clears it", async t => {
	const h = await fixture(t, undefined, "owner", undefined, false, true);
	t.mock.timers.enable({ apis: ["setTimeout", "Date"] });
	h.begin(); h.core.scheduler.settled(h.ctx); t.mock.timers.tick(1); h.admit();
	h.core.scheduler.settled(h.ctx);
	t.mock.timers.tick(10_000);
	h.core.scheduler.shutdown();
	await h.core.focus.load(h.ctx);
	h.core.scheduler.restore(h.ctx);
	t.mock.timers.tick(19_999);
	assert.equal(h.sent.length, 1);
	t.mock.timers.tick(1);
	assert.equal(h.sent.length, 2);
	h.admit(); h.core.scheduler.settled(h.ctx);
	assert.equal(h.core.scheduler.resume(h.ctx), true);
	t.mock.timers.tick(1);
	assert.equal(h.sent.length, 3, "user resume takes effect promptly");
	assert.equal(h.core.state.goal?.scheduler?.used, 1, "only resume renews allowance");
});

test("producer messages take over idle pacing without renewing allowance", async t => {
	const h = await fixture(t, 10, "owner", undefined, false, true);
	t.mock.timers.enable({ apis: ["setTimeout", "Date"] });
	h.begin(); h.core.scheduler.settled(h.ctx); t.mock.timers.tick(1); h.admit();
	h.core.scheduler.settled(h.ctx);
	h.begin(); h.core.scheduler.message(h.ctx, { role: "custom", customType: "producer-result", content: "Job finished" });
	h.core.scheduler.settled(h.ctx); t.mock.timers.tick(1);
	assert.equal(h.sent.length, 2);
	assert.equal(h.core.state.goal?.scheduler?.used, 2);
	t.mock.timers.tick(30_000);
	assert.equal(h.sent.length, 2, "superseded idle timer cannot send another marker");
});

test("claim rechecks a newly postponed idle deadline before spending allowance", async t => {
	const h = await fixture(t, undefined, "owner", undefined, false, true);
	t.mock.timers.enable({ apis: ["setTimeout", "Date"] });
	h.begin(); h.core.scheduler.settled(h.ctx);
	// Runtime has a queued ready callback, but the authoritative record changes
	// before delivery. Admission must use the later due time from disk.
	h.core.goalService.apply(h.ctx, { mutate: g => ({ ...g, scheduler: { ...g.scheduler!, idle: { runs: 2, nextAt: Date.now() + 30_000 } } }) });
	t.mock.timers.tick(1);
	assert.equal(h.sent.length, 0);
	assert.equal(h.core.state.goal?.scheduler?.used, 0);
	assert.equal(h.core.state.goal?.status, "active");
	t.mock.timers.tick(29_999);
	assert.equal(h.sent.length, 1);
	assert.equal(h.core.state.goal?.scheduler?.used, 1);
});

test("idle pacing excludes waiting time from accounting and respects changed run limits", async t => {
	const h = await fixture(t, undefined, "owner", undefined, false, true);
	t.mock.timers.enable({ apis: ["setTimeout", "Date"] });
	h.begin(); h.core.scheduler.settled(h.ctx); t.mock.timers.tick(1); h.admit();
	h.core.scheduler.settled(h.ctx);
	const before = h.core.state.goal!.usage.activeSeconds;
	h.core.progress.begin();
	t.mock.timers.tick(20_000);
	assert.equal(h.core.view.goalForDisplay()?.usage.activeSeconds, before);
	writeProjectSettings(h.cwd, { maxAutonomousRuns: 1 });
	t.mock.timers.tick(10_000);
	assert.equal(h.sent.length, 1);
	assert.equal(h.core.state.goal?.status, "paused");
	assert.match(h.core.state.goal?.pauseReason ?? "", /allowance exhausted/);
});

for (const action of ["pause", "unfocus", "replace", "shutdown"] as const) test(`${action} invalidates an idle continuation`, async t => {
	const h = await fixture(t, undefined, "owner", undefined, false, true);
	t.mock.timers.enable({ apis: ["setTimeout", "Date"] });
	h.begin(); h.core.scheduler.settled(h.ctx); t.mock.timers.tick(1); h.admit();
	h.core.scheduler.settled(h.ctx);
	if (action === "pause") h.core.pauseActiveGoal(h.ctx);
	else if (action === "unfocus") h.core.focus.setFocus(null, h.ctx, "unfocused");
	else if (action === "replace") h.core.lifecycle.create({ objective: "Replacement goal", autoContinue: false, sisyphus: false }, h.ctx);
	else h.core.scheduler.shutdown();
	t.mock.timers.tick(300_000);
	assert.equal(h.sent.length, 1);
});

test("an old stale settlement cannot consume the current execution's continuation", async t => {
	const h = await fixture(t, undefined, "owner", undefined, false);
	t.mock.timers.enable({ apis: ["setTimeout", "Date"] });
	h.begin();
	await h.handlers.agent_end!({ messages: [{ role: "assistant", stopReason: "stop" }] }, h.ctx);
	const stale = { get sessionManager() { throw new Error("This extension ctx is stale after session replacement or reload."); } };
	await h.handlers.agent_settled!({}, stale);
	t.mock.timers.tick(1);
	assert.equal(h.sent.length, 0);
	await h.handlers.agent_settled!({}, h.ctx);
	t.mock.timers.tick(1);
	assert.equal(h.sent.length, 1);
});

test("pacing metadata is optional, round-trips and rejects corrupt idle state", () => {
	const base = newGoalScheduler("owner");
	assert.deepEqual(normalizeGoalScheduler(base), base);
	const paced = { ...base, idle: { runs: 3, nextAt: Date.now() + 60_000 } };
	assert.deepEqual(normalizeGoalScheduler(paced), paced);
	for (const idle of [null, false, 0, {}, { runs: 0, nextAt: 0 }, { runs: 7, nextAt: 0 }, { runs: 1.5, nextAt: 0 }, { runs: 2, nextAt: Infinity }, { runs: 2, nextAt: -1 }]) {
		assert.equal(normalizeGoalScheduler({ ...base, idle })?.phase, "interrupted", JSON.stringify(idle));
	}
});

test("default rejects new waits without terminating or mutating; optional ready succeeds", async t => {
	const h = await fixture(t, 4, "owner", undefined, false);
	h.begin();
	const before = structuredClone(h.core.state.goal);
	const result = h.wait();
	assert.equal(result.terminate, false);
	assert.match(JSON.stringify(result.content), /strictExecutionContract=true/);
	assert.deepEqual(h.core.state.goal, before);
	assert.equal(h.ready().terminate, true);
});

for (const stage of ["schedule", "claim"] as const) {
	test(`disabling strict mode converts queued repair at ${stage} without renewing allowance`, async t => {
		const h = await fixture(t, 5);
		t.mock.timers.enable({ apis: ["setTimeout", "Date"] });
		h.begin(); h.core.scheduler.settled(h.ctx);
		assert.equal(h.core.state.goal?.scheduler?.decision?.kind, "ready");
		writeProjectSettings(h.cwd, {maxAutonomousRuns: 5, strictExecutionContract: false});
		if (stage === "schedule") h.core.scheduler.schedule(h.ctx);
		t.mock.timers.tick(1);
		assert.equal(h.core.state.goal?.scheduler?.dispatch?.kind, "ready");
		assert.equal(h.core.state.goal?.scheduler?.used, 1);
		assert.doesNotMatch(JSON.stringify(h.core.state.goal?.scheduler?.decision), /repair prompt/);
		h.admit(); h.core.scheduler.settled(h.ctx); t.mock.timers.tick(1);
		assert.equal(h.core.state.goal?.scheduler?.used, 2);
	});
}

test("existing waits keep identity, deadline and repair bounds after opt-out", async t => {
	const h = await fixture(t, 8);
	t.mock.timers.enable({ apis: ["setTimeout", "Date"] });
	h.begin(); h.wait();
	const wait = structuredClone(h.core.state.goal!.scheduler!.wait!);
	writeProjectSettings(h.cwd, {strictExecutionContract: false, maxAutonomousRuns: 8});
	h.core.scheduler.settled(h.ctx); t.mock.timers.tick(1001); h.admit();
	assert.equal(h.core.scheduler.declare(h.ctx, {kind: "wait", wait_id: wait.id, reason: wait.reason, deadline: new Date(wait.deadline).toISOString()}).terminate, true);
	assert.equal(h.core.state.goal?.scheduler?.wait?.remainingChecks, 1);
	assert.equal(h.core.state.goal?.scheduler?.wait?.deadline, wait.deadline);
	h.core.scheduler.settled(h.ctx); t.mock.timers.tick(1001); h.admit();
	h.core.scheduler.settled(h.ctx); t.mock.timers.tick(1);
	assert.equal(h.core.state.goal?.scheduler?.dispatch?.kind, "repair");
	h.admit(); h.core.scheduler.settled(h.ctx);
	assert.equal(h.core.state.goal?.status, "paused");
	assert.match(h.core.state.goal?.pauseReason ?? "", /No execution disposition/);
});

test("enabling strict mode at settlement requires a disposition without resetting usage", async t => {
	const h = await fixture(t, 5, "owner", undefined, false);
	t.mock.timers.enable({ apis: ["setTimeout", "Date"] });
	h.begin(); h.core.scheduler.settled(h.ctx); t.mock.timers.tick(1); h.admit();
	writeProjectSettings(h.cwd, {strictExecutionContract: true, maxAutonomousRuns: 5});
	h.core.scheduler.settled(h.ctx); t.mock.timers.tick(1);
	assert.equal(h.core.state.goal?.scheduler?.dispatch?.kind, "repair");
	assert.equal(h.core.state.goal?.scheduler?.used, 2);
	h.admit(); h.core.scheduler.settled(h.ctx);
	assert.equal(h.core.state.goal?.status, "paused");
	writeProjectSettings(h.cwd, {strictExecutionContract: false});
	h.core.scheduler.restore(h.ctx); t.mock.timers.tick(1000);
	assert.equal(h.core.state.goal?.status, "paused");
	assert.equal(h.sent.length, 2);
});

test("default settings inherit strict mode with explicit false overriding global true", async t => {
	const h = await fixture(t, undefined, "owner", undefined, false);
	writeProjectSettings(h.cwd, {});
	assert.equal(loadGoalSettings(h.cwd).strictExecutionContract, false);
	writeFileSync(process.env.PI_GOAL_GLOBAL_SETTINGS_FILE!, JSON.stringify({strictExecutionContract: true}));
	invalidateGoalSettingsCache();
	assert.equal(loadGoalSettings(h.cwd).strictExecutionContract, true);
	writeProjectSettings(h.cwd, {strictExecutionContract: false});
	assert.equal(loadGoalSettings(h.cwd).strictExecutionContract, false);
	writeProjectSettings(h.cwd, {});
	assert.equal(loadGoalSettings(h.cwd).strictExecutionContract, true);
	assert.deepEqual(parseSettings({strictExecutionContract: false}), {strictExecutionContract: false});
	assert.equal(parseSettings({strictExecutionContract: "invalid"}).strictExecutionContract, undefined);
});

test("showAutonomousRuns is a layered boolean that defaults to on", async t => {
	const h = await fixture(t);
	assert.equal(loadGoalSettings(h.cwd).showAutonomousRuns, true);
	writeProjectSettings(h.cwd, { showAutonomousRuns: false });
	invalidateGoalSettingsCache();
	assert.equal(loadGoalSettings(h.cwd).showAutonomousRuns, false);
	writeFileSync(process.env.PI_GOAL_GLOBAL_SETTINGS_FILE!, JSON.stringify({ showAutonomousRuns: true }));
	invalidateGoalSettingsCache();
	assert.equal(loadGoalSettings(h.cwd).showAutonomousRuns, false, "project false beats global true");
	writeProjectSettings(h.cwd, { showAutonomousRuns: true });
	invalidateGoalSettingsCache();
	assert.equal(loadGoalSettings(h.cwd).showAutonomousRuns, true, "project true beats global true");
	writeProjectSettings(h.cwd, {});
	invalidateGoalSettingsCache();
	assert.equal(loadGoalSettings(h.cwd).showAutonomousRuns, true, "global value applies when the project is unset");
	for (const bad of ["yes", 1, null, {}]) assert.equal(parseSettings({ showAutonomousRuns: bad }).showAutonomousRuns, undefined);
	assert.equal(parseSettings({ showAutonomousRuns: false }).showAutonomousRuns, false);
});

test("the runs line is omitted when unlimited and controlled by the setting when finite", async t => {
	const h = await fixture(t);
	const s = { ...normalizeGoalScheduler({ version: 1, owner: "owner", generation: "gen", used: 4, phase: "idle", repairUsed: false })!, used: 4 };

	// Unlimited: no line at all, because there is no limit to report.
	assert.equal(schedulerSummary(s), "");
	assert.equal(schedulerSummary(s, undefined), "");
	assert.equal(schedulerSummary(s, undefined, true), "", "the setting cannot force a line when there is no limit");

	// Finite: reported by default.
	assert.match(schedulerSummary(s, 20), /Autonomous runs: 4\/20\./);
	assert.match(schedulerSummary(h.core.state.goal?.scheduler, 20), /Autonomous runs/);

	// Finite with the setting off.
	assert.equal(schedulerSummary(s, 20, false), "");

	// Zero is a finite allowance, so the disabled suffix still reports.
	assert.match(schedulerSummary(s, 0), /4\/0 \(automatic continuation disabled\)/);
	assert.equal(schedulerSummary(s, 0, false), "");

	assert.match(schedulerSummary(undefined, 20), /Autonomous runs: 0\/20\./);
});

test("a ready disposition needs no next action and the schema no longer accepts one", async t => {
	const h = await fixture(t);
	const schema = JSON.stringify(h.tools.get("update_goal")?.parameters ?? {});
	assert.ok(!/next_action/.test(schema), `update_goal schema must not expose next_action: ${schema.slice(0, 400)}`);

	const result = h.core.scheduler.declare(h.ctx, { kind: "ready" });
	assert.equal(result.terminate, true, "ready with no next action succeeds");
	const declaredText = (result.content ?? []).map((part) => (part && "text" in part ? String(part.text) : "")).join(" ");
	assert.match(declaredText, /Scheduling decision saved/);
	assert.deepEqual(h.core.state.goal?.scheduler?.decision, { kind: "ready", purpose: "ready" }, "purpose is kept and no nextAction is stored");
	assert.ok(!/Next action/.test(declaredText), "the declaration result renders no next-action line");
	assert.doesNotMatch(schedulerSummary(h.core.state.goal?.scheduler, 20), /Next action/);
});

test("a goal saved with decision.nextAction loads and strips the field", () => {
	const legacy = {
		version: 1,
		owner: "legacy-owner",
		generation: "legacy-gen",
		used: 3,
		phase: "ready",
		decision: { kind: "ready", nextAction: "Continue pursuing the goal, then verify and complete it when satisfied.", purpose: "repair" },
		repairUsed: false,
	};
	const normalized = normalizeGoalScheduler(legacy);
	assert.ok(normalized, "a legacy scheduler state must still normalize");
	assert.equal(normalized!.phase, "ready");
	assert.equal(normalized!.used, 3, "spent allowance is preserved");
	assert.deepEqual(normalized!.decision, { kind: "ready", purpose: "repair" }, "purpose is preserved and nextAction is stripped");
	assert.ok(!("nextAction" in (normalized!.decision as object)));
	assert.equal(JSON.stringify(normalized).includes("nextAction"), false, "the stripped field is never written back");
	for (const purpose of ["ready", "repair", "kickoff", "recovery"] as const) {
		const s = normalizeGoalScheduler({ ...legacy, decision: { kind: "ready", nextAction: "x", purpose } });
		assert.equal((s?.decision as { purpose?: string } | undefined)?.purpose, purpose);
	}
	assert.equal(normalizeGoalScheduler({ ...legacy, decision: { kind: "ready", purpose: "bogus" } })?.phase, "interrupted", "an invalid decision is still rejected");
});

test("prompt cache: normal and custom runs preserve history while refreshing all live goal state", async t => {
	const h = await fixture(t);
	showUsageLine(h.cwd);
	const history: any[] = [{role: "user", content: "Work on the goal", timestamp: 1}];
	const original = structuredClone(history);
	const request = async () => (await h.handlers.context_with_system!({messages: history}, h.ctx)).messages;
	const preflight = await h.handlers.before_agent_start!({prompt: "continue", systemPrompt: "host policy"}, h.ctx);
	assert.equal(preflight, undefined, "goal state never rewrites the system prefix");
	const first = await request();
	assert.deepEqual(first.slice(0, -2), original, "the policy block and the request-only usage line ride as two tails");
	assert.equal(first.filter((m: any) => m.customType === "pi-goal-live-context").length, 2);
	assert.match(first.at(-2).content, /PI GOAL ACTIVE/);
	assert.match(first.at(-1).content, /Goal snapshot:/);
	const wire: any = {messages: [{role: "user", content: "Work on the goal"}, {role: "user", content: [{type: "text", text: first.at(-2).content}]}, {role: "user", content: [{type: "text", text: first.at(-1).content, cache_control: {type: "ephemeral"}}]}]};
	await h.handlers.before_provider_request!({payload: wire}, h.ctx);
	assert.equal(wire.messages[0].content[0].cache_control.type, "ephemeral", "registered provider hook places the breakpoint on history");
	assert.equal(wire.messages[1].content[0].cache_control, undefined, "stable tail is transient");
	assert.equal(wire.messages[2].content[0].cache_control, undefined, "volatile tail is transient");
	h.core.state.goal!.usage.tokensUsed = 12345;
	h.core.state.goal!.scheduler = { ...newGoalScheduler("owner"), used: 7 };
	const toolCall = {role: "assistant", content: [{type: "toolCall", id: "call-1", name: "read", arguments: {path: "README.md"}}], timestamp: 2};
	const toolResult = {role: "toolResult", toolCallId: "call-1", toolName: "read", content: [{type: "text", text: "file contents"}], isError: false, timestamp: 3};
	history.push(toolCall, toolResult);
	const second = await request();
	assert.deepEqual(second.slice(0, first.length - 1), first.slice(0, -1), "the advanced request literally extends the previous one, up to its request-only usage line");
	assert.deepEqual(second.slice(2, 4), [toolCall, toolResult], "tool call and result stay adjacent");
	assert.match(second[1].content, /PI GOAL ACTIVE/);
	assert.equal(second.filter((m: any) => m.customType === "pi-goal-live-context").length, 2, "usage changes only the request-only line; the policy block is retained, not resent");
	assert.match(second.at(-1).content, /12345 tokens/);
	assert.doesNotMatch(second.at(-1).content, /Autonomous runs/, "an unlimited allowance reports no runs line");
	// An objective edit adds a new policy block at the end. The earlier blocks stay,
	// so the request still extends the previous one and the cache holds.
	h.core.state.goal!.objective = "Changed objective";
	const third = await request();
	assert.equal(third.filter((m: any) => m.customType === "pi-goal-live-context").length, 3);
	assert.deepEqual(third.slice(0, second.length - 1), second.slice(0, -1));
	assert.match(third.at(-2).content, /Changed objective/);
	assert.match(third.at(-1).content, /Goal snapshot:/);
	h.core.scheduler.begin(h.ctx); // Custom-message run bypassing preflight.
	for (let i = 0; i < 4; i++) {
		history.push({role: "custom", customType: "pi-goal-event", content: "legacy full prompt", details: {goalId: h.core.state.goal!.id, kind: "checkpoint"}, timestamp: i + 4});
		const current = await request();
		assert.deepEqual(current.slice(0, third.length - 1), third.slice(0, -1));
		assert.equal(current.filter((m: any) => m.customType === "pi-goal-live-context").length, 3, "retained tails are re-sent in place, never duplicated per request");
		const before = current.slice(0, -1);
		const again = await request();
		assert.deepEqual(again.slice(0, -1), before);
	}
	assert.deepEqual(history[0], original[0], "request transforms never mutate stored history");
	for (const status of ["paused", "blocked", "budget_limited"] as const) {
		h.core.state.goal!.status = status;
		const stopped = await request();
		const policy = stopped.filter((m: any) => m.customType === "pi-goal-live-context").at(-2);
		assert.match(policy.content, new RegExp(status.replace("_", " ").toUpperCase()));
		assert.doesNotMatch(policy.content, /PI GOAL ACTIVE/);
		assert.match(stopped.at(-1).content, /Only the latest goal policy block above applies/, "the model is told which policy block counts");
	}
});

test("prompt cache: interleaved sessions keep per-session transient sets", async t => {
	const h = await fixture(t);
	showUsageLine(h.cwd);
	const history: any[] = [{role: "user", content: "Work on the goal", timestamp: 1}];
	const ctxB = {...h.ctx, sessionManager: {...h.ctx.sessionManager, getSessionId: () => "owner-B"}} as unknown as ExtensionContext;
	const first: any[] = (await h.handlers.context_with_system!({messages: history}, h.ctx)).messages;
	// Session B advances the same goal so its transient set differs from A's.
	h.core.state.goal!.usage.tokensUsed = 12345;
	h.core.state.goal!.scheduler = {...newGoalScheduler("owner"), used: 7};
	await h.handlers.context_with_system!({messages: history}, ctxB);
	const wire: any = {messages: [{role: "user", content: "Work on the goal"}, {role: "user", content: [{type: "text", text: first.at(-2).content}]}, {role: "user", content: [{type: "text", text: first.at(-1).content, cache_control: {type: "ephemeral"}}]}]};
	await h.handlers.before_provider_request!({payload: wire}, h.ctx);
	assert.equal(wire.messages[0].content[0].cache_control?.type, "ephemeral", "session A's request relocates with A's set even after B overwrote its own");
	assert.equal(wire.messages[2].content[0].cache_control, undefined, "A's live tail stays transient");
});

test("prompt cache: cleared scheduling instructions vanish from retained history", async t => {
	const h = await fixture(t);
	const history: any[] = [{role: "user", content: "Work on the goal", timestamp: 1}];
	// The standing instruction is a saved wait reason. A ready decision no longer
	// carries text: next actions were removed.
	h.core.state.goal!.scheduler = {...newGoalScheduler("owner"), phase: "waiting", decision: {kind: "wait"}, wait: {id: "w1", token: "t1", reason: "Publish release v1", deadline: Date.now() + 60_000}};
	const first: any[] = (await h.handlers.context_with_system!({messages: history}, h.ctx)).messages;
	assert.ok(first.some((m: any) => typeof m.content === "string" && m.content.includes("Publish release v1")), "standing instruction rides the live state");
	// Cleared by omission: a plain scheduler with no decision must not re-issue the order.
	h.core.state.goal!.scheduler = {...newGoalScheduler("owner"), used: 1};
	const advanced = [...history, {role: "assistant", content: "ack", timestamp: 2}];
	const second: any[] = (await h.handlers.context_with_system!({messages: advanced}, h.ctx)).messages;
	assert.ok(!second.some((m: any) => typeof m.content === "string" && m.content.includes("Publish release v1")), "no retained tail re-issues the cancelled order");
});


test("prompt cache: model changes and missing identities cannot replay another request's counters", async t => {
	const h = await fixture(t);
	showUsageLine(h.cwd);
	await h.handlers.session_start!({}, h.ctx);
	const history = [{role: "user", content: "inspect", timestamp: 1}];
	const request = async (ctx: ExtensionContext) => (await h.handlers.context_with_system!({messages: history}, ctx)).messages as any[];
	const initial = {...h.ctx, model: {provider: "provider-a", id: "model-a"}} as ExtensionContext;
	await request(initial);
	h.core.state.goal!.usage.tokensUsed = 123456;
	for (const model of [{provider: "provider-a", id: "model-b"}, {provider: "provider-b", id: "model-b"}]) {
		const out = await request({...h.ctx, model} as ExtensionContext);
		assert.equal(out.filter(m => m.customType === "pi-goal-live-context").length, 2);
		assert.match(out.at(-1).content, /123456 tokens/);
	}
	const unknown = {...h.ctx, sessionManager: {...h.ctx.sessionManager, getSessionId: () => undefined}} as unknown as ExtensionContext;
	await h.handlers.session_start!({}, unknown);
	await request(unknown);
	h.core.state.goal!.usage.tokensUsed = 234567;
	const next = await request(unknown);
	assert.equal(next.filter(m => m.customType === "pi-goal-live-context").length, 2);
	assert.ok(!JSON.stringify(next).includes("123456 tokens"));
	await h.handlers.session_shutdown!({}, unknown);
	await h.handlers.session_start!({}, initial);
	const restarted = await request(initial);
	assert.equal(restarted.filter(m => m.customType === "pi-goal-live-context").length, 2);
	assert.match(restarted.at(-1).content, /234567 tokens/);
});

for (const order of ['prepare-first', 'agent-first']) test(`rejected checkpoints preserve a replacement goal through ${order} startup and cancellation`, async t => {
	const h=await fixture(t,10);
	const before=readFileSync(path.join(h.cwd,h.core.state.goal!.activePath!),'utf8');
	const ctx={...h.ctx,signal:AbortSignal.abort()};
	h.core.runningGoalId='previous-goal';
	if(order==='agent-first')h.begin();
	await h.handlers.before_agent_start!({prompt:'<pi_goal_continuation goal_id="previous-goal" kind="checkpoint"/>',systemPrompt:'base',systemPromptOptions:{}},ctx);
	if(order==='prepare-first')h.begin();
	assert.equal(h.core.runningGoalId,null,'rejected startup does not bind to the replacement goal');
	assert.equal((await h.handlers.tool_call!({toolName:'write',input:{path:'wrong'}},ctx)).block,true);
	await h.handlers.turn_start!({},ctx);
	const message={role:'assistant',stopReason:'aborted',usage:{input:50,output:50,totalTokens:100}};
	await h.handlers.message_end!({message},ctx);
	await h.handlers.turn_end!({message},ctx);
	await h.handlers.agent_end!({messages:[message]},ctx);
	await h.handlers.agent_settled!({aborted:true},ctx);
	assert.equal(h.core.scheduler.isDenied(),false);
	assert.equal(h.core.state.goal?.status,'active');
	assert.equal(readFileSync(path.join(h.cwd,h.core.state.goal!.activePath!),'utf8'),before,'no pause, accounting or scheduler changes leak into the replacement');
	await h.handlers.before_agent_start!({prompt:'Continue the current goal',systemPrompt:'base',systemPromptOptions:{}},h.ctx);
	h.begin();
	assert.equal(h.core.runningGoalId,h.core.state.goal?.id,'the next legitimate run binds normally');
});

test('rejection cancels timers without losing the replacement goal\'s saved dispatch', async t => {
	const h=await fixture(t,10);
	t.mock.timers.enable({apis:['setTimeout','Date']});
	assert.equal(h.core.scheduler.resume(h.ctx),true);
	const before=JSON.stringify(h.core.state.goal?.scheduler);
	h.core.scheduler.rejectCheckpoint(h.ctx);
	h.begin();
	h.core.scheduler.schedule(h.ctx);
	t.mock.timers.tick(1000);
	assert.equal(h.sent.length,0);
	assert.equal(JSON.stringify(h.core.state.goal?.scheduler),before);
	await h.handlers.agent_settled!({aborted:true},h.ctx);
	t.mock.timers.tick(1);
	assert.equal(h.sent.length,1,'existing intent dispatches once after the rejection settles');
	assert.equal(h.core.state.goal?.scheduler?.used,1);
});

test('a rejected dispatch cannot release a user turn hold or renew its allowance', async t => {
	const h=await fixture(t,10);
	writeProjectSettings(h.cwd,{pauseOrder:'turn-first'});
	h.core.interruption.pause(h.ctx);
	const before=JSON.stringify(h.core.state.goal?.scheduler);
	h.core.scheduler.rejectCheckpoint(h.ctx);
	h.begin();
	await h.handlers.agent_settled!({aborted:true},h.ctx);
	assert.equal(h.core.interruption.isHeld(),true);
	assert.equal(JSON.stringify(h.core.state.goal?.scheduler),before);
	assert.equal(h.sent.length,0);
});

test('native retries retain the original run while a replacement waits for its own kickoff', async t => {
	const h=await fixture(t,10);
	t.mock.timers.enable({apis:['setTimeout','Date']});
	const original=h.core.state.goal!.id;
	h.begin();
	h.core.lifecycle.create({objective:'Replacement work',autoContinue:true,sisyphus:false},h.ctx);
	const replacement=h.core.state.goal!.id;
	assert.notEqual(replacement,original);
	h.core.progress.charge(h.ctx,{completedTurnTokens:128});
	assert.equal(h.core.state.goal?.usage.tokensUsed,0,'an old run cannot charge the replacement');
	assert.equal(h.core.accounting.goalId,null,'replacement time starts with its own run');
	assert.deepEqual(h.core.state.goal?.scheduler?.decision,{kind:'ready',purpose:'kickoff'});
	h.core.runningGoalId=replacement; // before_agent_start can run again during host retry
	h.begin();
	assert.equal(h.core.runningGoalId,original);
	t.mock.timers.tick(1000);
	assert.equal(h.sent.length,0,'replacement work waits for the original execution to settle');
	h.core.scheduler.settled(h.ctx,false);
	t.mock.timers.tick(1);
	assert.equal(h.sent.length,1,'saved creation intent starts a fresh run');
	h.admit();
	assert.equal(h.core.runningGoalId,replacement);
	assert.equal(h.core.state.goal?.scheduler?.used,1);
});

test("no automatic continuation is sent while a draft is in progress", async t => {
	const h = await fixture(t);
	t.mock.timers.enable({ apis: ["setTimeout", "Date"] });
	h.core.lifecycle.create({ objective: "Work automatically", autoContinue: true, sisyphus: false }, h.ctx);
	await startGoalDrafting(h.core, h.ctx, "tweak", "Add a constraint", h.core.state.goal!);
	assert.equal(hasActiveDraft(h.core), true);
	h.core.scheduler.settled(h.ctx);
	t.mock.timers.tick(10000);
	assert.equal(h.sent.length, 0, "nothing is sent while drafting");
	clearGoalDrafting(h.core, h.ctx);
	h.core.scheduler.settled(h.ctx);
	t.mock.timers.tick(10000);
	assert.ok(h.sent.length > 0, "continuations resume once the draft ends");
});

test("idle-turn breaker: automatic turns with no tool call pause the goal after maxIdleTurns", async t => {
	const h = await fixture(t, undefined, "owner", undefined, false);
	t.mock.timers.enable({ apis: ["setTimeout", "Date"] });
	assert.equal(h.core.scheduler.resume(h.ctx), true);
	t.mock.timers.tick(1);
	for (let turn = 1; turn <= 3; turn++) {
		assert.equal(h.sent.length, turn);
		h.admit(); h.core.scheduler.settled(h.ctx); t.mock.timers.tick(1);
		assert.equal(h.core.state.goal?.status, "active", `still active after idle turn ${turn}`);
	}
	assert.equal(h.sent.length, 4);
	h.admit(); h.core.scheduler.settled(h.ctx); t.mock.timers.tick(1000);
	assert.equal(h.sent.length, 4, "no fifth request is queued");
	assert.equal(h.core.state.goal?.status, "paused");
	assert.match(h.core.state.goal?.pauseReason ?? "", /no tool call in 4 automatic turns/);
});

test("idle-turn breaker: a tool call resets the streak, and get_goal-free turns do not count as work", async t => {
	const h = await fixture(t, undefined, "owner", undefined, false);
	t.mock.timers.enable({ apis: ["setTimeout", "Date"] });
	h.core.scheduler.resume(h.ctx); t.mock.timers.tick(1);
	for (let turn = 0; turn < 12; turn++) {
		h.admit();
		if (turn % 3 === 2) h.core.scheduler.noteTool();
		h.core.scheduler.settled(h.ctx); t.mock.timers.tick(1);
	}
	assert.equal(h.core.state.goal?.status, "active");
	assert.equal(h.sent.length, 13);
});

test("idle-turn breaker: maxIdleTurns 0 never pauses", async t => {
	const h = await fixture(t, undefined, "owner", undefined, false);
	writeProjectSettings(h.cwd, { strictExecutionContract: false, maxIdleTurns: 0 });
	invalidateGoalSettingsCache();
	t.mock.timers.enable({ apis: ["setTimeout", "Date"] });
	h.core.scheduler.resume(h.ctx); t.mock.timers.tick(1);
	for (let turn = 0; turn < 10; turn++) { h.admit(); h.core.scheduler.settled(h.ctx); t.mock.timers.tick(1); }
	assert.equal(h.core.state.goal?.status, "active");
});

test("busy hold: no continuation is queued while background work runs, and one goes out when it drains", async t => {
	const h = await fixture(t, undefined, "owner", undefined, false);
	t.mock.timers.enable({ apis: ["setTimeout", "Date"] });
	h.events.emit("pi-goal:busy", { source: "subagents", count: 2 });
	h.core.scheduler.resume(h.ctx); t.mock.timers.tick(1000);
	assert.equal(h.sent.length, 0, "held while busy");
	assert.equal(h.core.state.goal?.status, "active");
	assert.equal(h.core.state.goal?.scheduler?.used, 0, "a hold spends no run allowance");
	h.events.emit("pi-goal:busy", { source: "subagents", count: 1 });
	t.mock.timers.tick(1000);
	assert.equal(h.sent.length, 0);
	h.events.emit("pi-goal:busy", { source: "subagents", count: 0 });
	t.mock.timers.tick(1);
	assert.equal(h.sent.length, 1, "released exactly once");
	h.events.emit("pi-goal:busy", { source: "subagents", count: 0 });
	t.mock.timers.tick(1000);
	assert.equal(h.sent.length, 1, "a repeated release does not queue a second turn");
});

test("busy hold: a job that never reports idle cannot hold the goal past the fallback", async t => {
	const h = await fixture(t, undefined, "owner", undefined, false);
	t.mock.timers.enable({ apis: ["setTimeout", "Date"] });
	h.events.emit("pi-goal:busy", { source: "stuck", count: 1 });
	h.core.scheduler.resume(h.ctx);
	t.mock.timers.tick(59 * 60_000);
	assert.equal(h.sent.length, 0);
	t.mock.timers.tick(2 * 60_000);
	assert.equal(h.sent.length, 1);
});

test("busy hold: bad payloads are ignored and two sources must both drain", async t => {
	const h = await fixture(t, undefined, "owner", undefined, false);
	t.mock.timers.enable({ apis: ["setTimeout", "Date"] });
	h.events.emit("pi-goal:busy", null);
	h.events.emit("pi-goal:busy", { source: 5, count: "x" });
	h.core.scheduler.resume(h.ctx); t.mock.timers.tick(1);
	assert.equal(h.sent.length, 1, "nonsense payloads never hold");
	h.admit(); h.core.scheduler.noteTool();
	h.events.emit("pi-goal:busy", { source: "a", count: 1 });
	h.events.emit("pi-goal:busy", { source: "b", count: 1 });
	h.core.scheduler.settled(h.ctx);
	t.mock.timers.tick(1000);
	h.events.emit("pi-goal:busy", { source: "a", count: 0 });
	t.mock.timers.tick(1000);
	assert.equal(h.sent.length, 1);
	h.events.emit("pi-goal:busy", { source: "b", count: 0 });
	t.mock.timers.tick(1);
	assert.equal(h.sent.length, 2);
});

test("goal time limit: an automatic turn is not queued once the goal has used its minutes", async t => {
	const h = await fixture(t, undefined, "owner", undefined, false);
	writeProjectSettings(h.cwd, { strictExecutionContract: false, maxGoalMinutes: 30 });
	t.mock.timers.enable({ apis: ["setTimeout", "Date"] });
	h.core.scheduler.resume(h.ctx); t.mock.timers.tick(1);
	assert.equal(h.sent.length, 1, "under the limit, work goes on");
	h.admit(); h.core.scheduler.noteTool();
	h.core.goalService.apply(h.ctx, { reconcile: false, mutate: g => ({ ...g, usage: { ...g.usage, activeSeconds: 30 * 60 } }) });
	h.core.scheduler.settled(h.ctx); t.mock.timers.tick(1000);
	assert.equal(h.sent.length, 1, "no turn after the limit");
	assert.equal(h.core.state.goal?.status, "paused");
	assert.match(h.core.state.goal?.pauseReason ?? "", /time limit of 30 minutes/);
});
