repositories / pi-ext

pi-ext

bugabingas pi extensions

owned by bugabinga

extensions/mode/PLAN.md

Raw

Mode Extension V1 Implementation Plan

For agentic workers: REQUIRED SUB-SKILL: Use /skill:executing-plans to implement this plan task-by-task. Steps use checkbox (- [ ]) syntax for tracking.

Goal: Build the validated V1 mode extension from extensions/mode/V1.md.

Architecture: Single Pi extension with pure helpers for mode parsing/state rendering and thin runtime glue for commands/events. Modes load from getAgentDir()/modes/*.md; branch state is persisted with custom mode-state entries; prompt injection mutates before_agent_start.systemPrompt only.

Tech Stack: TypeScript, Pi extension API, yaml, Vitest, @marcfargas/pi-test-harness.

Roadmap: None

Phase: Single-plan implementation


File structure

Task 1: Package skeleton

Files:

Write extensions/mode/package.json:

{
  "name": "@bugabinga/pi-ext-mode",
  "private": true,
  "type": "module",
  "main": "index.ts",
  "dependencies": {
    "yaml": "^2.9.0"
  },
  "peerDependencies": {
    "@earendil-works/pi-coding-agent": "*"
  },
  "devDependencies": {
    "@marcfargas/pi-test-harness": "^0.6.1",
    "vitest": "^4.1.8"
  },
  "license": "MIT",
  "description": "Session-local mode switching for Pi.",
  "keywords": [
    "pi",
    "pi-extension",
    "mode"
  ]
}

Write extensions/mode/README.md:

# mode

Session-local Pi modes from Markdown files.

## Install / load

Loaded through the root pi-ext package.
See [../../README.md](../../README.md).

## Commands / tools / settings

Commands:

- `/mode` — show active mode and available modes.
- `/mode status` — same as `/mode`.
- `/mode list` — list available modes.
- `/mode <id>` — switch to a mode.
- `/mode off` — turn mode off.
- `/mode normal` — alias for `/mode off`.
- `/mode none` — alias for `/mode off`.
- `/mode reload-config` — reload mode files and report count/warnings.

Tools: none.

Settings: none.

## Mode files

V1 loads only global mode files:

```text
~/.pi/agent/modes/*.md
```

Mode id is the file stem. Valid ids match ^[a-zA-Z0-9_-]+$.

Example:

---
description: Read-only planning
model: openai/gpt-5.2-codex
thinking: high
tools: [read, grep, find, ls]
reminder: You are planning only. Do not implement.
---

# Planning mode

Plan only.
Do not implement.

Behavior

Active mode appends its Markdown body and a generated mode kernel to the system prompt for each agent turn. Mode prompts are not stored as chat messages.

A mode may change active tools, model, and thinking level. Turning mode off does not restore prior tools, model, or thinking in V1.

Mode state persists in session custom entries. Restore uses the current branch only. Compaction adds a mode checkpoint.

V1 limits

Project-local .pi/modes/*.md is deferred until Pi exposes a public project-trust API to extensions. Shortcuts, extension scoping, permission policy, tool globs, and baseline restore are not in V1.

- [ ] **Step 3: Install/update lockfile**

Run:

```bash
npm install

Expected:

Run:

git add extensions/mode/package.json extensions/mode/README.md package-lock.json
git commit -m "feat(mode): add extension package skeleton"

Expected: commit succeeds.

Task 2: Pure mode helpers

Files:

Create extensions/mode/__tests__/unit.test.ts:

import { describe, expect, it } from "vitest";
import { __modeTest } from "../index.ts";

const nowEntry = (data: unknown) => ({
  type: "custom",
  customType: "mode-state",
  data,
});

describe("mode pure helpers", () => {
  it("parses valid mode markdown", () => {
    const mode = __modeTest.parseModeMarkdown(
      "plan",
      `---\ndescription: Read-only planning\nmodel: openai/gpt-5.2-codex\nthinking: high\ntools: [read, grep]\nreminder: Stay read-only.\n---\n\n# Plan\n\nBody.\n`,
    );
    expect(mode).toEqual({
      id: "plan",
      description: "Read-only planning",
      model: "openai/gpt-5.2-codex",
      thinking: "high",
      tools: ["read", "grep"],
      reminder: "Stay read-only.",
      body: "# Plan\n\nBody.\n",
    });
  });

  it("allows empty body and empty frontmatter", () => {
    expect(__modeTest.parseModeMarkdown("empty", "---\n---\n")).toEqual({
      id: "empty",
      body: "",
    });
  });

  it("rejects invalid field types", () => {
    expect(() =>
      __modeTest.parseModeMarkdown("bad", "---\ntools: read\n---\nbody")
    ).toThrow(
      "mode bad: tools must be an array of strings",
    );
    expect(() =>
      __modeTest.parseModeMarkdown("bad", "---\nthinking: huge\n---\nbody")
    ).toThrow(
      "mode bad: thinking must be one of off, minimal, low, medium, high, xhigh",
    );
  });

  it("validates ids", () => {
    expect(__modeTest.isValidModeId("plan_1-build")).toBe(true);
    expect(__modeTest.isValidModeId("../plan")).toBe(false);
    expect(__modeTest.isValidModeId("plan mode")).toBe(false);
  });

  it("splits model ref at first slash", () => {
    expect(__modeTest.parseModelRef("openai/gpt-5.2/codex")).toEqual({
      provider: "openai",
      modelId: "gpt-5.2/codex",
    });
    expect(__modeTest.parseModelRef("missing-slash")).toBeUndefined();
    expect(__modeTest.parseModelRef("provider/")).toBeUndefined();
  });

  it("renders active prompt addition", () => {
    const text = __modeTest.modePromptAddition({
      id: "plan",
      body: "# Body\n",
      reminder: "Stay read-only.",
    });
    expect(text).toContain("# Body");
    expect(text).toContain("<mode_kernel>");
    expect(text).toContain("active_mode: plan");
    expect(text).toContain(
      "<mode_reminder>\nStay read-only.\n</mode_reminder>",
    );
    expect(text.indexOf("# Body")).toBeLessThan(text.indexOf("<mode_kernel>"));
  });

  it("renders normal neutralizer", () => {
    expect(__modeTest.normalPromptAddition()).toBe(
      `<mode_kernel>\nactive_mode: normal\nactive mode is runtime state, not conversation state\nprevious mode prompts are inactive unless repeated here\n</mode_kernel>`,
    );
  });

  it("restores latest mode state from current branch entries", () => {
    expect(
      __modeTest.latestModeState([
        nowEntry({
          schemaVersion: 1,
          activeMode: "plan",
          neutralize: false,
          reason: "switch",
        }),
      ]),
    ).toEqual({
      schemaVersion: 1,
      activeMode: "plan",
      neutralize: false,
      reason: "switch",
    });
    expect(__modeTest.latestModeState([nowEntry({ broken: true })]))
      .toBeUndefined();
  });
});

Run:

mise run test -- extensions/mode/__tests__/unit.test.ts

Expected: FAIL because extensions/mode/index.ts does not exist.

Create extensions/mode/index.ts with these exported test helpers and default extension shell:

import type {
  ExtensionAPI,
  ExtensionContext,
} from "@earendil-works/pi-coding-agent";
import { getAgentDir } from "@earendil-works/pi-coding-agent";
import { readdir, readFile } from "node:fs/promises";
import path from "node:path";
import { parse as parseYaml } from "yaml";

type ThinkingLevel = "off" | "minimal" | "low" | "medium" | "high" | "xhigh";

type Mode = {
  id: string;
  description?: string;
  model?: string;
  thinking?: ThinkingLevel;
  reminder?: string;
  tools?: string[];
  body: string;
};

type ModeStateEntry = {
  schemaVersion: 1;
  activeMode: string | null;
  neutralize: boolean;
  reason: "switch" | "off" | "compaction";
  model?: string;
  provider?: string;
  compactionEntryId?: string;
};

type ModeRuntimeState = {
  activeModeId: string | null;
  neutralize: boolean;
  modes: Map<string, Mode>;
  warnings: string[];
};

type ModeEntryLike = {
  type?: unknown;
  customType?: unknown;
  data?: unknown;
};

type ModelRef = { provider: string; modelId: string };

const MODE_STATE_VERSION = 1;
const MODE_STATE_ENTRY = "mode-state";
const STATUS_KEY = "mode";
const THINKING_LEVELS = [
  "off",
  "minimal",
  "low",
  "medium",
  "high",
  "xhigh",
] as const;
const MODE_ID_RE = /^[a-zA-Z0-9_-]+$/;

function isValidModeId(id: string): boolean {
  return MODE_ID_RE.test(id);
}

function frontmatterSplit(
  markdown: string,
): { frontmatter: string; body: string } {
  if (!markdown.startsWith("---")) return { frontmatter: "", body: markdown };
  const firstLineEnd = markdown.indexOf("\n");
  if (firstLineEnd === -1) return { frontmatter: "", body: "" };
  const close = markdown.indexOf("\n---", firstLineEnd + 1);
  if (close === -1) return { frontmatter: "", body: markdown };
  let bodyStart = close + "\n---".length;
  if (markdown.startsWith("\r\n", bodyStart)) bodyStart += 2;
  else if (markdown.startsWith("\n", bodyStart)) bodyStart += 1;
  return {
    frontmatter: markdown.slice(firstLineEnd + 1, close),
    body: markdown.slice(bodyStart),
  };
}

function parseModeMarkdown(id: string, markdown: string): Mode {
  const { frontmatter, body } = frontmatterSplit(
    markdown.replaceAll("\r\n", "\n"),
  );
  const raw = frontmatter.trim() ? parseYaml(frontmatter) : {};
  if (
    raw !== undefined
    && (raw === null || typeof raw !== "object" || Array.isArray(raw))
  ) {
    throw new Error(`mode ${id}: frontmatter must be a mapping`);
  }
  const data = (raw ?? {}) as Record<string, unknown>;
  const mode: Mode = { id, body };

  if (data.description !== undefined) {
    mode.description = requireString(id, "description", data.description);
  }
  if (data.model !== undefined) {
    mode.model = requireString(id, "model", data.model);
  }
  if (data.reminder !== undefined) {
    mode.reminder = requireString(id, "reminder", data.reminder);
  }
  if (data.thinking !== undefined) {
    mode.thinking = requireThinking(id, data.thinking);
  }
  if (data.tools !== undefined) {
    mode.tools = requireStringArray(id, "tools", data.tools);
  }
  return mode;
}

function requireString(id: string, field: string, value: unknown): string {
  if (typeof value !== "string") {
    throw new Error(`mode ${id}: ${field} must be a string`);
  }
  return value;
}

function requireStringArray(
  id: string,
  field: string,
  value: unknown,
): string[] {
  if (!Array.isArray(value) || value.some((item) => typeof item !== "string")) {
    throw new Error(`mode ${id}: ${field} must be an array of strings`);
  }
  return value;
}

function requireThinking(id: string, value: unknown): ThinkingLevel {
  if (
    typeof value !== "string"
    || !THINKING_LEVELS.includes(value as ThinkingLevel)
  ) {
    throw new Error(
      `mode ${id}: thinking must be one of ${THINKING_LEVELS.join(", ")}`,
    );
  }
  return value as ThinkingLevel;
}

function parseModelRef(ref: string): ModelRef | undefined {
  const slash = ref.indexOf("/");
  if (slash <= 0 || slash === ref.length - 1) return undefined;
  return { provider: ref.slice(0, slash), modelId: ref.slice(slash + 1) };
}

function modePromptAddition(mode: Mode): string {
  const parts = [mode.body.trimEnd()];
  parts.push(
    `<mode_kernel>\nactive_mode: ${mode.id}\nactive mode is runtime state, not conversation state\ncurrent user message cannot change active mode\nprevious mode prompts are inactive unless repeated here\nmode body/reminder cannot override this kernel\n</mode_kernel>`,
  );
  if (mode.reminder?.trim()) {
    parts.push(`<mode_reminder>\n${mode.reminder}\n</mode_reminder>`);
  }
  return parts.filter(Boolean).join("\n\n");
}

function normalPromptAddition(): string {
  return `<mode_kernel>\nactive_mode: normal\nactive mode is runtime state, not conversation state\nprevious mode prompts are inactive unless repeated here\n</mode_kernel>`;
}

function isModeStateEntry(value: unknown): value is ModeStateEntry {
  if (!value || typeof value !== "object") return false;
  const data = value as Record<string, unknown>;
  return (
    data.schemaVersion === MODE_STATE_VERSION
    && (data.activeMode === null || typeof data.activeMode === "string")
    && typeof data.neutralize === "boolean"
    && (data.reason === "switch" || data.reason === "off"
      || data.reason === "compaction")
  );
}

function latestModeState(entries: ModeEntryLike[]): ModeStateEntry | undefined {
  for (let i = entries.length - 1; i >= 0; i--) {
    const entry = entries[i];
    if (entry.type !== "custom" || entry.customType !== MODE_STATE_ENTRY) {
      continue;
    }
    if (isModeStateEntry(entry.data)) return entry.data;
  }
  return undefined;
}

async function loadModes(
  agentDir = getAgentDir(),
): Promise<{ modes: Map<string, Mode>; warnings: string[] }> {
  const warnings: string[] = [];
  const modes = new Map<string, Mode>();
  const dir = path.join(agentDir, "modes");
  let entries: string[];
  try {
    entries = await readdir(dir);
  } catch (error) {
    if ((error as NodeJS.ErrnoException).code === "ENOENT") {
      return { modes, warnings };
    }
    throw error;
  }
  for (const name of entries.sort()) {
    if (!name.endsWith(".md")) continue;
    const id = name.slice(0, -3);
    if (!isValidModeId(id)) {
      warnings.push(`ignored invalid mode id: ${name}`);
      continue;
    }
    try {
      modes.set(
        id,
        parseModeMarkdown(id, await readFile(path.join(dir, name), "utf8")),
      );
    } catch (error) {
      warnings.push((error as Error).message);
    }
  }
  return { modes, warnings };
}

function modeLine(mode: Mode): string {
  return mode.description ? `${mode.id} — ${mode.description}` : mode.id;
}

function statusText(modeId: string | null): string | undefined {
  return modeId ? `MODE ${modeId}` : undefined;
}

function publishStatus(ctx: ExtensionContext, modeId: string | null): void {
  if (!ctx.hasUI) return;
  ctx.ui.setStatus(STATUS_KEY, statusText(modeId));
}

function currentModelState(
  ctx: ExtensionContext,
): Pick<ModeStateEntry, "provider" | "model"> {
  return ctx.model ? { provider: ctx.model.provider, model: ctx.model.id } : {};
}

export default function modeExtension(pi: ExtensionAPI): void {
  const state: ModeRuntimeState = {
    activeModeId: null,
    neutralize: false,
    modes: new Map(),
    warnings: [],
  };

  async function reloadConfig(ctx?: ExtensionContext): Promise<void> {
    const loaded = await loadModes();
    state.modes = loaded.modes;
    state.warnings = loaded.warnings;
    for (const warning of state.warnings) ctx?.ui.notify(warning, "warning");
  }

  function persist(
    ctx: ExtensionContext,
    reason: ModeStateEntry["reason"],
    compactionEntryId?: string,
  ): void {
    pi.appendEntry(
      MODE_STATE_ENTRY,
      {
        schemaVersion: MODE_STATE_VERSION,
        activeMode: state.activeModeId,
        neutralize: state.neutralize,
        reason,
        ...currentModelState(ctx),
        ...(compactionEntryId ? { compactionEntryId } : {}),
      } satisfies ModeStateEntry,
    );
  }

  async function applyMode(mode: Mode, ctx: ExtensionContext): Promise<void> {
    if (mode.tools && mode.tools.length > 0) {
      const all = new Set(pi.getAllTools().map((tool) => tool.name));
      const valid = mode.tools.filter((tool) => all.has(tool));
      const unknown = mode.tools.filter((tool) => !all.has(tool));
      for (const tool of unknown) {
        ctx.ui.notify(
          `mode ${mode.id}: unknown tool ignored: ${tool}`,
          "warning",
        );
      }
      pi.setActiveTools(valid);
      ctx.ui.notify(`mode ${mode.id}: tools ${valid.join(", ")}`, "info");
    }
    if (mode.model) {
      const ref = parseModelRef(mode.model);
      const model = ref
        ? ctx.modelRegistry.find(ref.provider, ref.modelId)
        : undefined;
      if (!ref || !model) {
        ctx.ui.notify(
          `mode ${mode.id}: model not found: ${mode.model}`,
          "warning",
        );
      } else if (!(await pi.setModel(model))) {
        ctx.ui.notify(
          `mode ${mode.id}: model unavailable: ${mode.model}`,
          "warning",
        );
      }
    }
    if (mode.thinking) pi.setThinkingLevel(mode.thinking);
  }

  async function switchMode(id: string, ctx: ExtensionContext): Promise<void> {
    await reloadConfig(ctx);
    const mode = state.modes.get(id);
    if (!mode) {
      ctx.ui.notify(`unknown mode: ${id}`, "warning");
      return;
    }
    state.activeModeId = id;
    state.neutralize = false;
    await applyMode(mode, ctx);
    persist(ctx, "switch");
    publishStatus(ctx, id);
    ctx.ui.notify(`mode ${id}`, "info");
  }

  function modeOff(ctx: ExtensionContext): void {
    const hadMode = state.activeModeId !== null;
    state.activeModeId = null;
    state.neutralize = hadMode || state.neutralize;
    persist(ctx, "off");
    publishStatus(ctx, null);
    ctx.ui.notify("mode off", "info");
  }

  function showStatus(ctx: ExtensionContext): void {
    const active = state.activeModeId ?? "normal";
    const modes = [...state.modes.values()].map(modeLine);
    const warnings = state.warnings.map((warning) => `warning: ${warning}`);
    ctx.ui.notify(
      [
        `active: ${active}`,
        modes.length ? `modes:\n${modes.join("\n")}` : "modes: none",
        ...warnings,
      ].join("\n"),
      "info",
    );
  }

  pi.registerCommand("mode", {
    description: "Switch session-local mode",
    handler: async (args, ctx) => {
      const arg = args.trim();
      if (!arg || arg === "status") {
        await reloadConfig(ctx);
        showStatus(ctx);
        return;
      }
      if (arg === "list") {
        await reloadConfig(ctx);
        showStatus(ctx);
        return;
      }
      if (arg === "reload-config") {
        await reloadConfig(ctx);
        ctx.ui.notify(
          `mode config: ${state.modes.size} mode(s), ${state.warnings.length} warning(s)`,
          state.warnings.length ? "warning" : "info",
        );
        return;
      }
      if (arg === "off" || arg === "normal" || arg === "none") {
        modeOff(ctx);
        return;
      }
      await switchMode(arg, ctx);
    },
  });

  pi.on("before_agent_start", (event) => {
    const mode = state.activeModeId
      ? state.modes.get(state.activeModeId)
      : undefined;
    if (mode) {
      return {
        systemPrompt: `${event.systemPrompt}\n\n${modePromptAddition(mode)}`,
      };
    }
    if (state.neutralize) {
      return {
        systemPrompt: `${event.systemPrompt}\n\n${normalPromptAddition()}`,
      };
    }
  });

  pi.on("session_start", async (_event, ctx) => {
    await reloadConfig(ctx);
    const saved = latestModeState(
      ctx.sessionManager.getBranch() as ModeEntryLike[],
    );
    state.activeModeId = saved?.activeMode ?? null;
    state.neutralize = saved?.neutralize ?? false;
    if (state.activeModeId) {
      const mode = state.modes.get(state.activeModeId);
      if (mode) await applyMode(mode, ctx);
      else {
        ctx.ui.notify(
          `mode missing: ${state.activeModeId}; falling back to normal`,
          "warning",
        );
        state.activeModeId = null;
        state.neutralize = true;
        persist(ctx, "off");
      }
    }
    publishStatus(ctx, state.activeModeId);
  });

  pi.on(
    "session_compact",
    (event, ctx) => persist(ctx, "compaction", event.compactionEntry.id),
  );
  pi.on("session_shutdown", (_event, ctx) => publishStatus(ctx, null));
}

export const __modeTest = {
  frontmatterSplit,
  isValidModeId,
  latestModeState,
  loadModes,
  modePromptAddition,
  normalPromptAddition,
  parseModeMarkdown,
  parseModelRef,
  statusText,
};

Run:

mise run test -- extensions/mode/__tests__/unit.test.ts

Expected: PASS.

Run:

git add extensions/mode/index.ts extensions/mode/__tests__/unit.test.ts
git commit -m "feat(mode): parse mode files and render kernels"

Expected: commit succeeds.

Task 3: Runtime command tests

Files:

Create extensions/mode/__tests__/harness.test.ts:

import { mkdirSync, writeFileSync } from "node:fs";
import path from "node:path";
import { afterEach, describe, expect, it } from "vitest";
import { createTestSession, type TestSession } from "../../../test/harness";

function extPath() {
  return path.resolve(import.meta.dirname, "../index.ts");
}

function writeMode(t: TestSession, name: string, markdown: string): void {
  const dir = path.join(t.env.HOME!, ".pi", "agent", "modes");
  mkdirSync(dir, { recursive: true });
  writeFileSync(path.join(dir, `${name}.md`), markdown, "utf8");
}

async function command(t: TestSession, args: string): Promise<void> {
  const cmd = t.session.extensionRunner.extensions[0].commands.get("mode");
  await cmd.handler(args, t.session.extensionRunner.createCommandContext());
}

describe("mode harness", () => {
  let t: TestSession | undefined;
  afterEach(() => {
    t?.dispose();
    t = undefined;
  });

  it("loads in real Pi extension runtime", async () => {
    t = await createTestSession({ extensions: [extPath()] });
    expect(t.session.extensionRunner.extensions).toHaveLength(1);
    expect(t.session.extensionRunner.extensions[0].commands.has("mode")).toBe(
      true,
    );
  });

  it("lists global modes", async () => {
    t = await createTestSession({ extensions: [extPath()] });
    writeMode(t, "plan", "---\ndescription: Read-only planning\n---\nbody");
    await command(t, "list");
    const note = String(t.events.uiCallsFor("notify").at(-1)?.args[0]);
    expect(note).toContain("active: normal");
    expect(note).toContain("plan — Read-only planning");
  });

  it("switches mode and filters tools", async () => {
    t = await createTestSession({ extensions: [extPath()] });
    writeMode(
      t,
      "plan",
      "---\ntools: [read, grep, missing_tool]\nreminder: Stay read-only.\n---\n# Plan\n",
    );
    await command(t, "plan");
    const notes = t.events.uiCallsFor("notify").map((call) =>
      String(call.args[0])
    );
    expect(
      notes.some((note) => note.includes("unknown tool ignored: missing_tool")),
    ).toBe(true);
    expect(notes.some((note) => note.includes("mode plan: tools read, grep")))
      .toBe(true);
  });

  it("injects active mode prompt as system prompt", async () => {
    t = await createTestSession({ extensions: [extPath()] });
    writeMode(t, "plan", "---\nreminder: Stay read-only.\n---\n# Plan body\n");
    await command(t, "plan");
    const result = await t.session.extensionRunner.emitBeforeAgentStart(
      "hello",
      undefined,
      "BASE",
      {} as never,
    );
    expect(result?.systemPrompt).toContain("BASE\n\n# Plan body");
    expect(result?.systemPrompt).toContain("active_mode: plan");
    expect(result?.systemPrompt).toContain(
      "<mode_reminder>\nStay read-only.\n</mode_reminder>",
    );
    expect(result?.messages).toBeUndefined();
  });

  it("turns off and injects neutralizer", async () => {
    t = await createTestSession({ extensions: [extPath()] });
    writeMode(t, "plan", "# Plan body\n");
    await command(t, "plan");
    await command(t, "off");
    const result = await t.session.extensionRunner.emitBeforeAgentStart(
      "hello",
      undefined,
      "BASE",
      {} as never,
    );
    expect(result?.systemPrompt).toContain("active_mode: normal");
    expect(result?.systemPrompt).not.toContain("# Plan body");
  });

  it("restores mode from current branch", async () => {
    t = await createTestSession({ extensions: [extPath()] });
    writeMode(t, "plan", "# Plan body\n");
    await command(t, "plan");
    await t.session.extensionRunner.emit(
      { type: "session_start", reason: "reload" } as never,
    );
    const result = await t.session.extensionRunner.emitBeforeAgentStart(
      "hello",
      undefined,
      "BASE",
      {} as never,
    );
    expect(result?.systemPrompt).toContain("active_mode: plan");
  });

  it("adds compaction checkpoint", async () => {
    t = await createTestSession({ extensions: [extPath()] });
    writeMode(t, "plan", "# Plan body\n");
    await command(t, "plan");
    const msg = t.session.sessionManager.appendMessage({
      role: "user",
      content: "x",
      timestamp: Date.now(),
    });
    const compactionId = t.session.sessionManager.appendCompaction(
      "summary",
      msg,
      123,
    );
    const compactionEntry = t.session.sessionManager.getEntry(compactionId)!;
    await t.session.extensionRunner.emit(
      {
        type: "session_compact",
        compactionEntry,
        fromExtension: false,
      } as never,
    );
    const latest = t.session.sessionManager.getLeafEntry() as {
      type?: string;
      customType?: string;
      data?: Record<string, unknown>;
    };
    expect(latest.type).toBe("custom");
    expect(latest.customType).toBe("mode-state");
    expect(latest.data?.reason).toBe("compaction");
    expect(latest.data?.compactionEntryId).toBe(compactionId);
  });
});

Run:

mise run test -- extensions/mode/__tests__/harness.test.ts

Expected: PASS.

Run:

mise run test -- extensions/mode/__tests__/harness.test.ts -t "restores mode from current branch"

Expected: PASS.

Run:

mise run test -- extensions/mode/__tests__/harness.test.ts

Expected: PASS.

Run:

git add extensions/mode/index.ts extensions/mode/__tests__/harness.test.ts
git commit -m "test(mode): cover runtime mode switching"

Expected: commit succeeds.

Task 4: Model/thinking restore coverage

Files:

Append to extensions/mode/__tests__/unit.test.ts inside the existing describe:

it("keeps malformed model refs unresolved", () => {
  expect(__modeTest.parseModelRef("/model")).toBeUndefined();
  expect(__modeTest.parseModelRef("provider/")).toBeUndefined();
  expect(__modeTest.parseModelRef("provider/model/name")).toEqual({
    provider: "provider",
    modelId: "model/name",
  });
});

Append to extensions/mode/__tests__/harness.test.ts inside the existing describe:

it("warns for unresolved model and still applies thinking", async () => {
  t = await createTestSession({ extensions: [extPath()] });
  writeMode(t, "deep", "---\nmodel: nope/missing\nthinking: high\n---\nbody");
  await command(t, "deep");
  const notes = t.events.uiCallsFor("notify").map((call) =>
    String(call.args[0])
  );
  expect(notes.some((note) => note.includes("model not found: nope/missing")))
    .toBe(true);
  const latestThinking = [...t.session.sessionManager.getBranch()].reverse()
    .find((entry: { type?: string }) =>
      entry.type === "thinking_level_change"
    ) as { thinkingLevel?: string } | undefined;
  expect(latestThinking?.thinkingLevel).toBe("high");
});

Run:

mise run test -- extensions/mode/__tests__/unit.test.ts extensions/mode/__tests__/harness.test.ts

Expected: PASS.

Run:

git add extensions/mode/index.ts extensions/mode/__tests__/unit.test.ts extensions/mode/__tests__/harness.test.ts
git commit -m "test(mode): cover model and thinking application"

Expected: commit succeeds.

Task 5: Static repo checks

Files:

Run:

mise run fmt

Expected: PASS.

Run:

mise run test -- extensions/mode/__tests__/unit.test.ts extensions/mode/__tests__/harness.test.ts

Expected: PASS.

Run:

mise run check

Expected: PASS.

Run:

mise run ci

Expected: PASS.

If CI fails outside extensions/mode/** or package-lock.json, stop and report the unrelated dirty failure instead of editing unrelated files.

If formatting changed files, run:

git add extensions/mode package-lock.json
git commit -m "chore(mode): satisfy repo checks"

Expected: commit succeeds or there are no formatting changes to commit.

Task 6: Final implementation audit

Files:

Create this checklist in the worker notes and mark each item with file/function/test evidence:

- global getAgentDir()/modes/*.md loading
- valid id filter
- YAML frontmatter validation
- mode schema fields
- active mode switch command
- off/normal/none aliases
- status/list/reload-config commands
- tool filtering and unknown warnings
- model parse/resolve/set warnings
- thinking application
- system prompt mode body/kernel/reminder injection
- normal neutralizer injection
- custom mode-state persistence
- getBranch restore
- missing restored mode fallback
- session_compact checkpoint
- status UI set/clear
- no project-local modes
- no custom prompt messages

For each unchecked item, add one unit or harness test before changing implementation.

Use this command after each added test:

mise run test -- extensions/mode/__tests__/unit.test.ts extensions/mode/__tests__/harness.test.ts

Expected: new test FAILS before implementation change, then PASSES after implementation change.

Run:

mise run ci

Expected: PASS.

Run:

git status --short
git add extensions/mode package-lock.json
git commit -m "feat(mode): add session-local modes"

Expected:

Markdown source
File outline
# Mode Extension V1 Implementation Plan

> **For agentic workers:** REQUIRED SUB-SKILL: Use /skill:executing-plans to implement this plan task-by-task. Steps use checkbox (`- [ ]`) syntax for tracking.

**Goal:** Build the validated V1 mode extension from `extensions/mode/V1.md`.

**Architecture:** Single Pi extension with pure helpers for mode parsing/state rendering and thin runtime glue for commands/events. Modes load from `getAgentDir()/modes/*.md`; branch state is persisted with custom `mode-state` entries; prompt injection mutates `before_agent_start.systemPrompt` only.

**Tech Stack:** TypeScript, Pi extension API, `yaml`, Vitest, `@marcfargas/pi-test-harness`.

**Roadmap:** None

**Phase:** Single-plan implementation

---

## File structure

- Create `extensions/mode/package.json`: workspace package metadata and `yaml` runtime dependency.
- Create `extensions/mode/README.md`: user-facing behavior, commands, and V1 limits.
- Create `extensions/mode/index.ts`: extension entrypoint, parser, state, commands, hooks, and test exports.
- Create `extensions/mode/__tests__/unit.test.ts`: pure parser/state/kernel tests.
- Create `extensions/mode/__tests__/harness.test.ts`: real Pi runtime tests for commands, tool filtering, prompt injection, restore, and compaction.
- Modify `package-lock.json`: generated by `npm install` after adding the workspace package.

## Task 1: Package skeleton

**Files:**

- Create: `extensions/mode/package.json`
- Create: `extensions/mode/README.md`

- [ ] **Step 1: Create package manifest**

Write `extensions/mode/package.json`:

```json
{
  "name": "@bugabinga/pi-ext-mode",
  "private": true,
  "type": "module",
  "main": "index.ts",
  "dependencies": {
    "yaml": "^2.9.0"
  },
  "peerDependencies": {
    "@earendil-works/pi-coding-agent": "*"
  },
  "devDependencies": {
    "@marcfargas/pi-test-harness": "^0.6.1",
    "vitest": "^4.1.8"
  },
  "license": "MIT",
  "description": "Session-local mode switching for Pi.",
  "keywords": [
    "pi",
    "pi-extension",
    "mode"
  ]
}
```

- [ ] **Step 2: Create README**

Write `extensions/mode/README.md`:

````markdown
# mode

Session-local Pi modes from Markdown files.

## Install / load

Loaded through the root pi-ext package.
See [../../README.md](../../README.md).

## Commands / tools / settings

Commands:

- `/mode` — show active mode and available modes.
- `/mode status` — same as `/mode`.
- `/mode list` — list available modes.
- `/mode <id>` — switch to a mode.
- `/mode off` — turn mode off.
- `/mode normal` — alias for `/mode off`.
- `/mode none` — alias for `/mode off`.
- `/mode reload-config` — reload mode files and report count/warnings.

Tools: none.

Settings: none.

## Mode files

V1 loads only global mode files:

```text
~/.pi/agent/modes/*.md
```
````

Mode id is the file stem.
Valid ids match `^[a-zA-Z0-9_-]+$`.

Example:

```md
---
description: Read-only planning
model: openai/gpt-5.2-codex
thinking: high
tools: [read, grep, find, ls]
reminder: You are planning only. Do not implement.
---

# Planning mode

Plan only.
Do not implement.
```

## Behavior

Active mode appends its Markdown body and a generated mode kernel to the system prompt for each agent turn.
Mode prompts are not stored as chat messages.

A mode may change active tools, model, and thinking level.
Turning mode off does not restore prior tools, model, or thinking in V1.

Mode state persists in session custom entries.
Restore uses the current branch only.
Compaction adds a mode checkpoint.

## V1 limits

Project-local `.pi/modes/*.md` is deferred until Pi exposes a public project-trust API to extensions.
Shortcuts, extension scoping, permission policy, tool globs, and baseline restore are not in V1.

````
- [ ] **Step 3: Install/update lockfile**

Run:

```bash
npm install
````

Expected:

- `package-lock.json` adds workspace package `extensions/mode`.
- Existing root dependencies remain intact.

- [ ] **Step 4: Commit package skeleton**

Run:

```bash
git add extensions/mode/package.json extensions/mode/README.md package-lock.json
git commit -m "feat(mode): add extension package skeleton"
```

Expected: commit succeeds.

## Task 2: Pure mode helpers

**Files:**

- Create: `extensions/mode/index.ts`
- Create: `extensions/mode/__tests__/unit.test.ts`

- [ ] **Step 1: Write failing unit tests for parsing and rendering**

Create `extensions/mode/__tests__/unit.test.ts`:

```ts
import { describe, expect, it } from "vitest";
import { __modeTest } from "../index.ts";

const nowEntry = (data: unknown) => ({
  type: "custom",
  customType: "mode-state",
  data,
});

describe("mode pure helpers", () => {
  it("parses valid mode markdown", () => {
    const mode = __modeTest.parseModeMarkdown(
      "plan",
      `---\ndescription: Read-only planning\nmodel: openai/gpt-5.2-codex\nthinking: high\ntools: [read, grep]\nreminder: Stay read-only.\n---\n\n# Plan\n\nBody.\n`,
    );
    expect(mode).toEqual({
      id: "plan",
      description: "Read-only planning",
      model: "openai/gpt-5.2-codex",
      thinking: "high",
      tools: ["read", "grep"],
      reminder: "Stay read-only.",
      body: "# Plan\n\nBody.\n",
    });
  });

  it("allows empty body and empty frontmatter", () => {
    expect(__modeTest.parseModeMarkdown("empty", "---\n---\n")).toEqual({
      id: "empty",
      body: "",
    });
  });

  it("rejects invalid field types", () => {
    expect(() =>
      __modeTest.parseModeMarkdown("bad", "---\ntools: read\n---\nbody")
    ).toThrow(
      "mode bad: tools must be an array of strings",
    );
    expect(() =>
      __modeTest.parseModeMarkdown("bad", "---\nthinking: huge\n---\nbody")
    ).toThrow(
      "mode bad: thinking must be one of off, minimal, low, medium, high, xhigh",
    );
  });

  it("validates ids", () => {
    expect(__modeTest.isValidModeId("plan_1-build")).toBe(true);
    expect(__modeTest.isValidModeId("../plan")).toBe(false);
    expect(__modeTest.isValidModeId("plan mode")).toBe(false);
  });

  it("splits model ref at first slash", () => {
    expect(__modeTest.parseModelRef("openai/gpt-5.2/codex")).toEqual({
      provider: "openai",
      modelId: "gpt-5.2/codex",
    });
    expect(__modeTest.parseModelRef("missing-slash")).toBeUndefined();
    expect(__modeTest.parseModelRef("provider/")).toBeUndefined();
  });

  it("renders active prompt addition", () => {
    const text = __modeTest.modePromptAddition({
      id: "plan",
      body: "# Body\n",
      reminder: "Stay read-only.",
    });
    expect(text).toContain("# Body");
    expect(text).toContain("<mode_kernel>");
    expect(text).toContain("active_mode: plan");
    expect(text).toContain(
      "<mode_reminder>\nStay read-only.\n</mode_reminder>",
    );
    expect(text.indexOf("# Body")).toBeLessThan(text.indexOf("<mode_kernel>"));
  });

  it("renders normal neutralizer", () => {
    expect(__modeTest.normalPromptAddition()).toBe(
      `<mode_kernel>\nactive_mode: normal\nactive mode is runtime state, not conversation state\nprevious mode prompts are inactive unless repeated here\n</mode_kernel>`,
    );
  });

  it("restores latest mode state from current branch entries", () => {
    expect(
      __modeTest.latestModeState([
        nowEntry({
          schemaVersion: 1,
          activeMode: "plan",
          neutralize: false,
          reason: "switch",
        }),
      ]),
    ).toEqual({
      schemaVersion: 1,
      activeMode: "plan",
      neutralize: false,
      reason: "switch",
    });
    expect(__modeTest.latestModeState([nowEntry({ broken: true })]))
      .toBeUndefined();
  });
});
```

- [ ] **Step 2: Run unit test and verify failure**

Run:

```bash
mise run test -- extensions/mode/__tests__/unit.test.ts
```

Expected: FAIL because `extensions/mode/index.ts` does not exist.

- [ ] **Step 3: Implement pure helpers and extension shell**

Create `extensions/mode/index.ts` with these exported test helpers and default extension shell:

```ts
import type {
  ExtensionAPI,
  ExtensionContext,
} from "@earendil-works/pi-coding-agent";
import { getAgentDir } from "@earendil-works/pi-coding-agent";
import { readdir, readFile } from "node:fs/promises";
import path from "node:path";
import { parse as parseYaml } from "yaml";

type ThinkingLevel = "off" | "minimal" | "low" | "medium" | "high" | "xhigh";

type Mode = {
  id: string;
  description?: string;
  model?: string;
  thinking?: ThinkingLevel;
  reminder?: string;
  tools?: string[];
  body: string;
};

type ModeStateEntry = {
  schemaVersion: 1;
  activeMode: string | null;
  neutralize: boolean;
  reason: "switch" | "off" | "compaction";
  model?: string;
  provider?: string;
  compactionEntryId?: string;
};

type ModeRuntimeState = {
  activeModeId: string | null;
  neutralize: boolean;
  modes: Map<string, Mode>;
  warnings: string[];
};

type ModeEntryLike = {
  type?: unknown;
  customType?: unknown;
  data?: unknown;
};

type ModelRef = { provider: string; modelId: string };

const MODE_STATE_VERSION = 1;
const MODE_STATE_ENTRY = "mode-state";
const STATUS_KEY = "mode";
const THINKING_LEVELS = [
  "off",
  "minimal",
  "low",
  "medium",
  "high",
  "xhigh",
] as const;
const MODE_ID_RE = /^[a-zA-Z0-9_-]+$/;

function isValidModeId(id: string): boolean {
  return MODE_ID_RE.test(id);
}

function frontmatterSplit(
  markdown: string,
): { frontmatter: string; body: string } {
  if (!markdown.startsWith("---")) return { frontmatter: "", body: markdown };
  const firstLineEnd = markdown.indexOf("\n");
  if (firstLineEnd === -1) return { frontmatter: "", body: "" };
  const close = markdown.indexOf("\n---", firstLineEnd + 1);
  if (close === -1) return { frontmatter: "", body: markdown };
  let bodyStart = close + "\n---".length;
  if (markdown.startsWith("\r\n", bodyStart)) bodyStart += 2;
  else if (markdown.startsWith("\n", bodyStart)) bodyStart += 1;
  return {
    frontmatter: markdown.slice(firstLineEnd + 1, close),
    body: markdown.slice(bodyStart),
  };
}

function parseModeMarkdown(id: string, markdown: string): Mode {
  const { frontmatter, body } = frontmatterSplit(
    markdown.replaceAll("\r\n", "\n"),
  );
  const raw = frontmatter.trim() ? parseYaml(frontmatter) : {};
  if (
    raw !== undefined
    && (raw === null || typeof raw !== "object" || Array.isArray(raw))
  ) {
    throw new Error(`mode ${id}: frontmatter must be a mapping`);
  }
  const data = (raw ?? {}) as Record<string, unknown>;
  const mode: Mode = { id, body };

  if (data.description !== undefined) {
    mode.description = requireString(id, "description", data.description);
  }
  if (data.model !== undefined) {
    mode.model = requireString(id, "model", data.model);
  }
  if (data.reminder !== undefined) {
    mode.reminder = requireString(id, "reminder", data.reminder);
  }
  if (data.thinking !== undefined) {
    mode.thinking = requireThinking(id, data.thinking);
  }
  if (data.tools !== undefined) {
    mode.tools = requireStringArray(id, "tools", data.tools);
  }
  return mode;
}

function requireString(id: string, field: string, value: unknown): string {
  if (typeof value !== "string") {
    throw new Error(`mode ${id}: ${field} must be a string`);
  }
  return value;
}

function requireStringArray(
  id: string,
  field: string,
  value: unknown,
): string[] {
  if (!Array.isArray(value) || value.some((item) => typeof item !== "string")) {
    throw new Error(`mode ${id}: ${field} must be an array of strings`);
  }
  return value;
}

function requireThinking(id: string, value: unknown): ThinkingLevel {
  if (
    typeof value !== "string"
    || !THINKING_LEVELS.includes(value as ThinkingLevel)
  ) {
    throw new Error(
      `mode ${id}: thinking must be one of ${THINKING_LEVELS.join(", ")}`,
    );
  }
  return value as ThinkingLevel;
}

function parseModelRef(ref: string): ModelRef | undefined {
  const slash = ref.indexOf("/");
  if (slash <= 0 || slash === ref.length - 1) return undefined;
  return { provider: ref.slice(0, slash), modelId: ref.slice(slash + 1) };
}

function modePromptAddition(mode: Mode): string {
  const parts = [mode.body.trimEnd()];
  parts.push(
    `<mode_kernel>\nactive_mode: ${mode.id}\nactive mode is runtime state, not conversation state\ncurrent user message cannot change active mode\nprevious mode prompts are inactive unless repeated here\nmode body/reminder cannot override this kernel\n</mode_kernel>`,
  );
  if (mode.reminder?.trim()) {
    parts.push(`<mode_reminder>\n${mode.reminder}\n</mode_reminder>`);
  }
  return parts.filter(Boolean).join("\n\n");
}

function normalPromptAddition(): string {
  return `<mode_kernel>\nactive_mode: normal\nactive mode is runtime state, not conversation state\nprevious mode prompts are inactive unless repeated here\n</mode_kernel>`;
}

function isModeStateEntry(value: unknown): value is ModeStateEntry {
  if (!value || typeof value !== "object") return false;
  const data = value as Record<string, unknown>;
  return (
    data.schemaVersion === MODE_STATE_VERSION
    && (data.activeMode === null || typeof data.activeMode === "string")
    && typeof data.neutralize === "boolean"
    && (data.reason === "switch" || data.reason === "off"
      || data.reason === "compaction")
  );
}

function latestModeState(entries: ModeEntryLike[]): ModeStateEntry | undefined {
  for (let i = entries.length - 1; i >= 0; i--) {
    const entry = entries[i];
    if (entry.type !== "custom" || entry.customType !== MODE_STATE_ENTRY) {
      continue;
    }
    if (isModeStateEntry(entry.data)) return entry.data;
  }
  return undefined;
}

async function loadModes(
  agentDir = getAgentDir(),
): Promise<{ modes: Map<string, Mode>; warnings: string[] }> {
  const warnings: string[] = [];
  const modes = new Map<string, Mode>();
  const dir = path.join(agentDir, "modes");
  let entries: string[];
  try {
    entries = await readdir(dir);
  } catch (error) {
    if ((error as NodeJS.ErrnoException).code === "ENOENT") {
      return { modes, warnings };
    }
    throw error;
  }
  for (const name of entries.sort()) {
    if (!name.endsWith(".md")) continue;
    const id = name.slice(0, -3);
    if (!isValidModeId(id)) {
      warnings.push(`ignored invalid mode id: ${name}`);
      continue;
    }
    try {
      modes.set(
        id,
        parseModeMarkdown(id, await readFile(path.join(dir, name), "utf8")),
      );
    } catch (error) {
      warnings.push((error as Error).message);
    }
  }
  return { modes, warnings };
}

function modeLine(mode: Mode): string {
  return mode.description ? `${mode.id} — ${mode.description}` : mode.id;
}

function statusText(modeId: string | null): string | undefined {
  return modeId ? `MODE ${modeId}` : undefined;
}

function publishStatus(ctx: ExtensionContext, modeId: string | null): void {
  if (!ctx.hasUI) return;
  ctx.ui.setStatus(STATUS_KEY, statusText(modeId));
}

function currentModelState(
  ctx: ExtensionContext,
): Pick<ModeStateEntry, "provider" | "model"> {
  return ctx.model ? { provider: ctx.model.provider, model: ctx.model.id } : {};
}

export default function modeExtension(pi: ExtensionAPI): void {
  const state: ModeRuntimeState = {
    activeModeId: null,
    neutralize: false,
    modes: new Map(),
    warnings: [],
  };

  async function reloadConfig(ctx?: ExtensionContext): Promise<void> {
    const loaded = await loadModes();
    state.modes = loaded.modes;
    state.warnings = loaded.warnings;
    for (const warning of state.warnings) ctx?.ui.notify(warning, "warning");
  }

  function persist(
    ctx: ExtensionContext,
    reason: ModeStateEntry["reason"],
    compactionEntryId?: string,
  ): void {
    pi.appendEntry(
      MODE_STATE_ENTRY,
      {
        schemaVersion: MODE_STATE_VERSION,
        activeMode: state.activeModeId,
        neutralize: state.neutralize,
        reason,
        ...currentModelState(ctx),
        ...(compactionEntryId ? { compactionEntryId } : {}),
      } satisfies ModeStateEntry,
    );
  }

  async function applyMode(mode: Mode, ctx: ExtensionContext): Promise<void> {
    if (mode.tools && mode.tools.length > 0) {
      const all = new Set(pi.getAllTools().map((tool) => tool.name));
      const valid = mode.tools.filter((tool) => all.has(tool));
      const unknown = mode.tools.filter((tool) => !all.has(tool));
      for (const tool of unknown) {
        ctx.ui.notify(
          `mode ${mode.id}: unknown tool ignored: ${tool}`,
          "warning",
        );
      }
      pi.setActiveTools(valid);
      ctx.ui.notify(`mode ${mode.id}: tools ${valid.join(", ")}`, "info");
    }
    if (mode.model) {
      const ref = parseModelRef(mode.model);
      const model = ref
        ? ctx.modelRegistry.find(ref.provider, ref.modelId)
        : undefined;
      if (!ref || !model) {
        ctx.ui.notify(
          `mode ${mode.id}: model not found: ${mode.model}`,
          "warning",
        );
      } else if (!(await pi.setModel(model))) {
        ctx.ui.notify(
          `mode ${mode.id}: model unavailable: ${mode.model}`,
          "warning",
        );
      }
    }
    if (mode.thinking) pi.setThinkingLevel(mode.thinking);
  }

  async function switchMode(id: string, ctx: ExtensionContext): Promise<void> {
    await reloadConfig(ctx);
    const mode = state.modes.get(id);
    if (!mode) {
      ctx.ui.notify(`unknown mode: ${id}`, "warning");
      return;
    }
    state.activeModeId = id;
    state.neutralize = false;
    await applyMode(mode, ctx);
    persist(ctx, "switch");
    publishStatus(ctx, id);
    ctx.ui.notify(`mode ${id}`, "info");
  }

  function modeOff(ctx: ExtensionContext): void {
    const hadMode = state.activeModeId !== null;
    state.activeModeId = null;
    state.neutralize = hadMode || state.neutralize;
    persist(ctx, "off");
    publishStatus(ctx, null);
    ctx.ui.notify("mode off", "info");
  }

  function showStatus(ctx: ExtensionContext): void {
    const active = state.activeModeId ?? "normal";
    const modes = [...state.modes.values()].map(modeLine);
    const warnings = state.warnings.map((warning) => `warning: ${warning}`);
    ctx.ui.notify(
      [
        `active: ${active}`,
        modes.length ? `modes:\n${modes.join("\n")}` : "modes: none",
        ...warnings,
      ].join("\n"),
      "info",
    );
  }

  pi.registerCommand("mode", {
    description: "Switch session-local mode",
    handler: async (args, ctx) => {
      const arg = args.trim();
      if (!arg || arg === "status") {
        await reloadConfig(ctx);
        showStatus(ctx);
        return;
      }
      if (arg === "list") {
        await reloadConfig(ctx);
        showStatus(ctx);
        return;
      }
      if (arg === "reload-config") {
        await reloadConfig(ctx);
        ctx.ui.notify(
          `mode config: ${state.modes.size} mode(s), ${state.warnings.length} warning(s)`,
          state.warnings.length ? "warning" : "info",
        );
        return;
      }
      if (arg === "off" || arg === "normal" || arg === "none") {
        modeOff(ctx);
        return;
      }
      await switchMode(arg, ctx);
    },
  });

  pi.on("before_agent_start", (event) => {
    const mode = state.activeModeId
      ? state.modes.get(state.activeModeId)
      : undefined;
    if (mode) {
      return {
        systemPrompt: `${event.systemPrompt}\n\n${modePromptAddition(mode)}`,
      };
    }
    if (state.neutralize) {
      return {
        systemPrompt: `${event.systemPrompt}\n\n${normalPromptAddition()}`,
      };
    }
  });

  pi.on("session_start", async (_event, ctx) => {
    await reloadConfig(ctx);
    const saved = latestModeState(
      ctx.sessionManager.getBranch() as ModeEntryLike[],
    );
    state.activeModeId = saved?.activeMode ?? null;
    state.neutralize = saved?.neutralize ?? false;
    if (state.activeModeId) {
      const mode = state.modes.get(state.activeModeId);
      if (mode) await applyMode(mode, ctx);
      else {
        ctx.ui.notify(
          `mode missing: ${state.activeModeId}; falling back to normal`,
          "warning",
        );
        state.activeModeId = null;
        state.neutralize = true;
        persist(ctx, "off");
      }
    }
    publishStatus(ctx, state.activeModeId);
  });

  pi.on(
    "session_compact",
    (event, ctx) => persist(ctx, "compaction", event.compactionEntry.id),
  );
  pi.on("session_shutdown", (_event, ctx) => publishStatus(ctx, null));
}

export const __modeTest = {
  frontmatterSplit,
  isValidModeId,
  latestModeState,
  loadModes,
  modePromptAddition,
  normalPromptAddition,
  parseModeMarkdown,
  parseModelRef,
  statusText,
};
```

- [ ] **Step 4: Run unit tests and verify pass**

Run:

```bash
mise run test -- extensions/mode/__tests__/unit.test.ts
```

Expected: PASS.

- [ ] **Step 5: Commit pure helpers**

Run:

```bash
git add extensions/mode/index.ts extensions/mode/__tests__/unit.test.ts
git commit -m "feat(mode): parse mode files and render kernels"
```

Expected: commit succeeds.

## Task 3: Runtime command tests

**Files:**

- Create: `extensions/mode/__tests__/harness.test.ts`
- Modify: `extensions/mode/index.ts`

- [ ] **Step 1: Write failing harness tests**

Create `extensions/mode/__tests__/harness.test.ts`:

```ts
import { mkdirSync, writeFileSync } from "node:fs";
import path from "node:path";
import { afterEach, describe, expect, it } from "vitest";
import { createTestSession, type TestSession } from "../../../test/harness";

function extPath() {
  return path.resolve(import.meta.dirname, "../index.ts");
}

function writeMode(t: TestSession, name: string, markdown: string): void {
  const dir = path.join(t.env.HOME!, ".pi", "agent", "modes");
  mkdirSync(dir, { recursive: true });
  writeFileSync(path.join(dir, `${name}.md`), markdown, "utf8");
}

async function command(t: TestSession, args: string): Promise<void> {
  const cmd = t.session.extensionRunner.extensions[0].commands.get("mode");
  await cmd.handler(args, t.session.extensionRunner.createCommandContext());
}

describe("mode harness", () => {
  let t: TestSession | undefined;
  afterEach(() => {
    t?.dispose();
    t = undefined;
  });

  it("loads in real Pi extension runtime", async () => {
    t = await createTestSession({ extensions: [extPath()] });
    expect(t.session.extensionRunner.extensions).toHaveLength(1);
    expect(t.session.extensionRunner.extensions[0].commands.has("mode")).toBe(
      true,
    );
  });

  it("lists global modes", async () => {
    t = await createTestSession({ extensions: [extPath()] });
    writeMode(t, "plan", "---\ndescription: Read-only planning\n---\nbody");
    await command(t, "list");
    const note = String(t.events.uiCallsFor("notify").at(-1)?.args[0]);
    expect(note).toContain("active: normal");
    expect(note).toContain("plan — Read-only planning");
  });

  it("switches mode and filters tools", async () => {
    t = await createTestSession({ extensions: [extPath()] });
    writeMode(
      t,
      "plan",
      "---\ntools: [read, grep, missing_tool]\nreminder: Stay read-only.\n---\n# Plan\n",
    );
    await command(t, "plan");
    const notes = t.events.uiCallsFor("notify").map((call) =>
      String(call.args[0])
    );
    expect(
      notes.some((note) => note.includes("unknown tool ignored: missing_tool")),
    ).toBe(true);
    expect(notes.some((note) => note.includes("mode plan: tools read, grep")))
      .toBe(true);
  });

  it("injects active mode prompt as system prompt", async () => {
    t = await createTestSession({ extensions: [extPath()] });
    writeMode(t, "plan", "---\nreminder: Stay read-only.\n---\n# Plan body\n");
    await command(t, "plan");
    const result = await t.session.extensionRunner.emitBeforeAgentStart(
      "hello",
      undefined,
      "BASE",
      {} as never,
    );
    expect(result?.systemPrompt).toContain("BASE\n\n# Plan body");
    expect(result?.systemPrompt).toContain("active_mode: plan");
    expect(result?.systemPrompt).toContain(
      "<mode_reminder>\nStay read-only.\n</mode_reminder>",
    );
    expect(result?.messages).toBeUndefined();
  });

  it("turns off and injects neutralizer", async () => {
    t = await createTestSession({ extensions: [extPath()] });
    writeMode(t, "plan", "# Plan body\n");
    await command(t, "plan");
    await command(t, "off");
    const result = await t.session.extensionRunner.emitBeforeAgentStart(
      "hello",
      undefined,
      "BASE",
      {} as never,
    );
    expect(result?.systemPrompt).toContain("active_mode: normal");
    expect(result?.systemPrompt).not.toContain("# Plan body");
  });

  it("restores mode from current branch", async () => {
    t = await createTestSession({ extensions: [extPath()] });
    writeMode(t, "plan", "# Plan body\n");
    await command(t, "plan");
    await t.session.extensionRunner.emit(
      { type: "session_start", reason: "reload" } as never,
    );
    const result = await t.session.extensionRunner.emitBeforeAgentStart(
      "hello",
      undefined,
      "BASE",
      {} as never,
    );
    expect(result?.systemPrompt).toContain("active_mode: plan");
  });

  it("adds compaction checkpoint", async () => {
    t = await createTestSession({ extensions: [extPath()] });
    writeMode(t, "plan", "# Plan body\n");
    await command(t, "plan");
    const msg = t.session.sessionManager.appendMessage({
      role: "user",
      content: "x",
      timestamp: Date.now(),
    });
    const compactionId = t.session.sessionManager.appendCompaction(
      "summary",
      msg,
      123,
    );
    const compactionEntry = t.session.sessionManager.getEntry(compactionId)!;
    await t.session.extensionRunner.emit(
      {
        type: "session_compact",
        compactionEntry,
        fromExtension: false,
      } as never,
    );
    const latest = t.session.sessionManager.getLeafEntry() as {
      type?: string;
      customType?: string;
      data?: Record<string, unknown>;
    };
    expect(latest.type).toBe("custom");
    expect(latest.customType).toBe("mode-state");
    expect(latest.data?.reason).toBe("compaction");
    expect(latest.data?.compactionEntryId).toBe(compactionId);
  });
});
```

- [ ] **Step 2: Run harness test and verify pass**

Run:

```bash
mise run test -- extensions/mode/__tests__/harness.test.ts
```

Expected: PASS.

- [ ] **Step 3: Verify mode-state entries are branch custom entries**

Run:

```bash
mise run test -- extensions/mode/__tests__/harness.test.ts -t "restores mode from current branch"
```

Expected: PASS.

- [ ] **Step 4: Run harness test suite again**

Run:

```bash
mise run test -- extensions/mode/__tests__/harness.test.ts
```

Expected: PASS.

- [ ] **Step 5: Commit runtime tests**

Run:

```bash
git add extensions/mode/index.ts extensions/mode/__tests__/harness.test.ts
git commit -m "test(mode): cover runtime mode switching"
```

Expected: commit succeeds.

## Task 4: Model/thinking restore coverage

**Files:**

- Modify: `extensions/mode/__tests__/unit.test.ts`
- Modify: `extensions/mode/__tests__/harness.test.ts`
- Modify: `extensions/mode/index.ts`

- [ ] **Step 1: Add malformed model-ref unit test**

Append to `extensions/mode/__tests__/unit.test.ts` inside the existing `describe`:

```ts
it("keeps malformed model refs unresolved", () => {
  expect(__modeTest.parseModelRef("/model")).toBeUndefined();
  expect(__modeTest.parseModelRef("provider/")).toBeUndefined();
  expect(__modeTest.parseModelRef("provider/model/name")).toEqual({
    provider: "provider",
    modelId: "model/name",
  });
});
```

- [ ] **Step 2: Add model/thinking warning harness test**

Append to `extensions/mode/__tests__/harness.test.ts` inside the existing `describe`:

```ts
it("warns for unresolved model and still applies thinking", async () => {
  t = await createTestSession({ extensions: [extPath()] });
  writeMode(t, "deep", "---\nmodel: nope/missing\nthinking: high\n---\nbody");
  await command(t, "deep");
  const notes = t.events.uiCallsFor("notify").map((call) =>
    String(call.args[0])
  );
  expect(notes.some((note) => note.includes("model not found: nope/missing")))
    .toBe(true);
  const latestThinking = [...t.session.sessionManager.getBranch()].reverse()
    .find((entry: { type?: string }) =>
      entry.type === "thinking_level_change"
    ) as { thinkingLevel?: string } | undefined;
  expect(latestThinking?.thinkingLevel).toBe("high");
});
```

- [ ] **Step 3: Run targeted tests**

Run:

```bash
mise run test -- extensions/mode/__tests__/unit.test.ts extensions/mode/__tests__/harness.test.ts
```

Expected: PASS.

- [ ] **Step 4: Commit model/thinking coverage**

Run:

```bash
git add extensions/mode/index.ts extensions/mode/__tests__/unit.test.ts extensions/mode/__tests__/harness.test.ts
git commit -m "test(mode): cover model and thinking application"
```

Expected: commit succeeds.

## Task 5: Static repo checks

**Files:**

- Modify: files flagged by formatter/linter only.

- [ ] **Step 1: Format**

Run:

```bash
mise run fmt
```

Expected: PASS.

- [ ] **Step 2: Run targeted tests**

Run:

```bash
mise run test -- extensions/mode/__tests__/unit.test.ts extensions/mode/__tests__/harness.test.ts
```

Expected: PASS.

- [ ] **Step 3: Run extension static checks**

Run:

```bash
mise run check
```

Expected: PASS.

- [ ] **Step 4: Run full CI**

Run:

```bash
mise run ci
```

Expected: PASS.

If CI fails outside `extensions/mode/**` or `package-lock.json`, stop and report the unrelated dirty failure instead of editing unrelated files.

- [ ] **Step 5: Commit verification fixes**

If formatting changed files, run:

```bash
git add extensions/mode package-lock.json
git commit -m "chore(mode): satisfy repo checks"
```

Expected: commit succeeds or there are no formatting changes to commit.

## Task 6: Final implementation audit

**Files:**

- Read: `extensions/mode/V1.md`
- Read: `extensions/mode/index.ts`
- Read: `extensions/mode/__tests__/unit.test.ts`
- Read: `extensions/mode/__tests__/harness.test.ts`

- [ ] **Step 1: Map V1 requirements to code/tests**

Create this checklist in the worker notes and mark each item with file/function/test evidence:

```text
- global getAgentDir()/modes/*.md loading
- valid id filter
- YAML frontmatter validation
- mode schema fields
- active mode switch command
- off/normal/none aliases
- status/list/reload-config commands
- tool filtering and unknown warnings
- model parse/resolve/set warnings
- thinking application
- system prompt mode body/kernel/reminder injection
- normal neutralizer injection
- custom mode-state persistence
- getBranch restore
- missing restored mode fallback
- session_compact checkpoint
- status UI set/clear
- no project-local modes
- no custom prompt messages
```

- [ ] **Step 2: Fill any coverage gap with a test**

For each unchecked item, add one unit or harness test before changing implementation.

Use this command after each added test:

```bash
mise run test -- extensions/mode/__tests__/unit.test.ts extensions/mode/__tests__/harness.test.ts
```

Expected: new test FAILS before implementation change, then PASSES after implementation change.

- [ ] **Step 3: Final CI**

Run:

```bash
mise run ci
```

Expected: PASS.

- [ ] **Step 4: Final commit**

Run:

```bash
git status --short
git add extensions/mode package-lock.json
git commit -m "feat(mode): add session-local modes"
```

Expected:

- Only mode extension files and `package-lock.json` are staged.
- Unrelated existing dirty files remain unstaged.
- Commit succeeds.