1 1 #
Mode Extension V1 Implementation Plan 3 -> **For agentic workers:** REQUIRED SUB-SKILL: Use /skill:executing-plans to implement this plan task-by-task. Steps use checkbox (`- [ ]`) syntax for tracking.
3 +**Status:** Implemented.
5 -**Goal:** Build the validated V1 mode extension from `extensions/mode/V1.md`.
5 +The original V1 implementation (session persistence via `mode-state` entries) was revised mid-flight.
6 +See `V1.md` for the implemented design (memory-only state, themed `setHeader` UI, `accent` frontmatter).
7 -**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.
8 +##
Implementation summary 9 -**Tech Stack:** TypeScript, Pi extension API, `yaml`, Vitest, `@marcfargas/pi-test-harness`.
12 +- `index.ts` — pure helpers (`frontmatterSplit`, `parseModeMarkdown`, `loadModes`, `modePromptAddition`, `normalPromptAddition`, `buildHeader`) plus runtime glue (`switchMode`, `modeOff`, `applyMode`, `showStatus`).
13 +- Tests: `unit.test.ts` (pure helpers + header factory + no-ui shutdown), `harness.test.ts` (real pi runtime), `coverage.test.ts` (fake runtime + 100% branch coverage gate).
14 +- UI: `ctx.ui.setHeader(buildHeader(mode))` replaces `setStatus`. Restoring built-in header via `setHeader(undefined)` on off/shutdown.
15 +- Frontmatter additions: `accent: AccentColor`.
16 +- Dropped: `mode-state` session entries, `latestModeState`, `persist`, `session_compact` handler, branch restore on `session_start`, baseline tracking, `setStatus`, `setTitle`, `setWidget`.
17 +- Updated: `V1.md`, `V2.md` (V2's `color` frontmatter moved to V1 as `accent`), `SPEC.md`, `README.md`.
13 -**Phase:** Single-plan implementation
19 -- Create `extensions/mode/package.json`: workspace package metadata and `yaml` runtime dependency.
20 -- Create `extensions/mode/README.md`: user-facing behavior, commands, and V1 limits.
21 -- Create `extensions/mode/index.ts`: extension entrypoint, parser, state, commands, hooks, and test exports.
22 -- Create `extensions/mode/__tests__/unit.test.ts`: pure parser/state/kernel tests.
23 -- Create `extensions/mode/__tests__/harness.test.ts`: real Pi runtime tests for commands, tool filtering, prompt injection, restore, and compaction.
24 -- Modify `package-lock.json`: generated by `npm install` after adding the workspace package.
26 -##
Task 1: Package skeleton 30 -- Create: `extensions/mode/package.json`
31 -- Create: `extensions/mode/README.md`
33 -- [ ] **Step 1: Create package manifest**
35 -Write `extensions/mode/package.json`:
39 - "name":
"@bugabinga/pi-ext-mode",
46 - "peerDependencies": {
47 - "@earendil-works/pi-coding-agent":
"*" 49 - "devDependencies": {
50 - "@marcfargas/pi-test-harness":
"^0.6.1",
54 - "description":
"Session-local mode switching for Pi.",
63 -- [ ] **Step 2: Create README**
65 -Write `extensions/mode/README.md`:
70 -Session-local Pi modes from Markdown files.
74 -Loaded through the root pi-ext package.
75 -See [../../README.md](../../README.md).
77 -## Commands / tools / settings
81 -- `/mode` — show active mode and available modes.
82 -- `/mode status` — same as `/mode`.
83 -- `/mode list` — list available modes.
84 -- `/mode <id>` — switch to a mode.
85 -- `/mode off` — turn mode off.
86 -- `/mode normal` — alias for `/mode off`.
87 -- `/mode none` — alias for `/mode off`.
88 -- `/mode reload-config` — reload mode files and report count/warnings.
96 -V1 loads only global mode files:
99 -~/.pi/agent/modes/*.md
103 -Mode id is the file stem.
104 -Valid ids match `^[a-zA-Z0-9_-]+$`.
110 -description: Read-only planning
111 -model: openai/gpt-5.2-codex
113 -tools: [read, grep, find, ls]
114 -reminder: You are planning only. Do not implement.
125 -Active mode appends its Markdown body and a generated mode kernel to the system prompt for each agent turn.
126 -Mode prompts are not stored as chat messages.
128 -A mode may change active tools, model, and thinking level.
129 -Turning mode off does not restore prior tools, model, or thinking in V1.
131 -Mode state persists in session custom entries.
132 -Restore uses the current branch only.
133 -Compaction adds a mode checkpoint.
137 -Project-local `.pi/modes/*.md` is deferred until Pi exposes a public project-trust API to extensions.
138 -Shortcuts, extension scoping, permission policy, tool globs, and baseline restore are not in V1.
141 -- [ ] **Step 3: Install/update lockfile**
151 -- `package-lock.json` adds workspace package `extensions/mode`.
152 -- Existing root dependencies remain intact.
154 -- [ ] **Step 4: Commit package skeleton**
159 -git add extensions/mode/package.json extensions/mode/README.md package-lock.json
160 -git commit -m
"feat(mode): add extension package skeleton" 163 -Expected: commit succeeds.
165 -##
Task 2: Pure mode helpers 169 -- Create: `extensions/mode/index.ts`
170 -- Create: `extensions/mode/__tests__/unit.test.ts`
172 -- [ ] **Step 1: Write failing unit tests for parsing and rendering**
174 -Create `extensions/mode/__tests__/unit.test.ts`:
177 -import { describe, expect, it }
from "vitest";
178 -import { __modeTest }
from "../index.ts";
180 -const nowEntry = (data
: unknown)
=> ({
182 - customType:
"mode-state",
186 -describe(
"mode pure helpers", ()
=> {
187 - it(
"parses valid mode markdown", ()
=> {
188 - const mode
= __modeTest.
parseModeMarkdown(
190 - `---\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`,
192 - expect(mode).
toEqual({
194 - description:
"Read-only planning",
195 - model:
"openai/gpt-5.2-codex",
197 - tools: [
"read",
"grep"],
198 - reminder:
"Stay read-only.",
199 - body:
"# Plan\n\nBody.\n",
203 - it(
"allows empty body and empty frontmatter", ()
=> {
204 - expect(__modeTest.
parseModeMarkdown(
"empty",
"---\n---\n")).
toEqual({
210 - it(
"rejects invalid field types", ()
=> {
212 - __modeTest.
parseModeMarkdown(
"bad",
"---\ntools: read\n---\nbody")
214 - "mode bad: tools must be an array of strings",
217 - __modeTest.
parseModeMarkdown(
"bad",
"---\nthinking: huge\n---\nbody")
219 - "mode bad: thinking must be one of off, minimal, low, medium, high, xhigh",
223 - it(
"validates ids", ()
=> {
224 - expect(__modeTest.
isValidModeId(
"plan_1-build")).
toBe(
true);
225 - expect(__modeTest.
isValidModeId(
"../plan")).
toBe(
false);
226 - expect(__modeTest.
isValidModeId(
"plan mode")).
toBe(
false);
229 - it(
"splits model ref at first slash", ()
=> {
230 - expect(__modeTest.
parseModelRef(
"openai/gpt-5.2/codex")).
toEqual({
231 - provider:
"openai",
232 - modelId:
"gpt-5.2/codex",
234 - expect(__modeTest.
parseModelRef(
"missing-slash")).
toBeUndefined();
235 - expect(__modeTest.
parseModelRef(
"provider/")).
toBeUndefined();
238 - it(
"renders active prompt addition", ()
=> {
239 - const text
= __modeTest.
modePromptAddition({
242 - reminder:
"Stay read-only.",
244 - expect(text).
toContain(
"# Body");
245 - expect(text).
toContain(
"<mode_kernel>");
246 - expect(text).
toContain(
"active_mode: plan");
247 - expect(text).
toContain(
248 - "<mode_reminder>\nStay read-only.\n</mode_reminder>",
250 - expect(text.
indexOf(
"# Body")).
toBeLessThan(text.
indexOf(
"<mode_kernel>"));
253 - it(
"renders normal neutralizer", ()
=> {
254 - expect(__modeTest.
normalPromptAddition()).
toBe(
255 - `<mode_kernel>\nactive_mode: normal\nactive mode is runtime state, not conversation state\nprevious mode prompts are inactive unless repeated here\n</mode_kernel>`,
259 - it(
"restores latest mode state from current branch entries", ()
=> {
261 - __modeTest.
latestModeState([
264 - activeMode:
"plan",
271 - activeMode:
"plan",
275 - expect(__modeTest.
latestModeState([
nowEntry({ broken:
true })]))
281 -- [ ] **Step 2: Run unit test and verify failure**
286 -mise run test
-- extensions/mode/__tests__/unit.test.ts
289 -Expected: FAIL because `extensions/mode/index.ts` does not exist.
291 -- [ ] **Step 3: Implement pure helpers and extension shell**
293 -Create `extensions/mode/index.ts` with these exported test helpers and default extension shell:
299 -}
from "@earendil-works/pi-coding-agent";
300 -import { getAgentDir }
from "@earendil-works/pi-coding-agent";
301 -import { readdir, readFile }
from "node:fs/promises";
302 -import path
from "node:path";
303 -import { parse
as parseYaml }
from "yaml";
305 -type ThinkingLevel = "off" | "minimal" | "low" | "medium" | "high" | "xhigh";
309 - description
?: string;
311 - thinking
?: ThinkingLevel;
317 -type ModeStateEntry = {
319 - activeMode
: string | null;
320 - neutralize
: boolean;
321 - reason
: "switch" | "off" | "compaction";
324 - compactionEntryId
?: string;
327 -type ModeRuntimeState = {
328 - activeModeId
: string | null;
329 - neutralize
: boolean;
330 - modes
: Map<
string,
Mode>;
331 - warnings
: string[];
334 -type ModeEntryLike = {
336 - customType
?: unknown;
340 -type ModelRef = { provider
: string; modelId
: string };
342 -const MODE_STATE_VERSION
= 1;
343 -const MODE_STATE_ENTRY
= "mode-state";
344 -const STATUS_KEY
= "mode";
345 -const THINKING_LEVELS
= [
353 -const MODE_ID_RE
= /^[a-zA-Z0-9_-]+$/;
355 -function isValidModeId(id
: string)
: boolean {
356 - return MODE_ID_RE.
test(id);
359 -function frontmatterSplit(
361 -)
: { frontmatter
: string; body
: string } {
362 - if (
!markdown.
startsWith(
"---"))
return { frontmatter:
"", body: markdown };
363 - const firstLineEnd
= markdown.
indexOf(
"\n");
364 - if (firstLineEnd
=== -1)
return { frontmatter:
"", body:
"" };
365 - const close
= markdown.
indexOf(
"\n---", firstLineEnd
+ 1);
366 - if (close
=== -1)
return { frontmatter:
"", body: markdown };
367 - let bodyStart
= close
+ "\n---".
length;
368 - if (markdown.
startsWith(
"\r\n", bodyStart)) bodyStart
+= 2;
369 - else if (markdown.
startsWith(
"\n", bodyStart)) bodyStart
+= 1;
371 - frontmatter: markdown.
slice(firstLineEnd
+ 1, close),
372 - body: markdown.
slice(bodyStart),
376 -function parseModeMarkdown(id
: string, markdown
: string)
: Mode {
377 - const { frontmatter, body }
= frontmatterSplit(
378 - markdown.
replaceAll(
"\r\n",
"\n"),
380 - const raw
= frontmatter.
trim()
? parseYaml(frontmatter)
: {};
383 - && (raw
=== null || typeof raw
!== "object" || Array.
isArray(raw))
385 - throw new Error(
`mode ${id}: frontmatter must be a mapping`);
387 - const data
= (raw
?? {})
as Record<
string,
unknown>;
388 - const mode
: Mode = { id, body };
390 - if (data.
description !== undefined) {
391 - mode.
description = requireString(id,
"description", data.
description);
393 - if (data.model
!== undefined) {
394 - mode.model
= requireString(id,
"model", data.model);
396 - if (data.reminder
!== undefined) {
397 - mode.reminder
= requireString(id,
"reminder", data.reminder);
399 - if (data.thinking
!== undefined) {
400 - mode.thinking
= requireThinking(id, data.thinking);
402 - if (data.tools
!== undefined) {
403 - mode.tools
= requireStringArray(id,
"tools", data.tools);
408 -function requireString(id
: string, field
: string, value
: unknown)
: string {
409 - if (
typeof value
!== "string") {
410 - throw new Error(
`mode ${id}: ${field} must be a string`);
415 -function requireStringArray(
420 - if (
!Array.
isArray(value)
|| value.
some((item)
=> typeof item
!== "string")) {
421 - throw new Error(
`mode ${id}: ${field} must be an array of strings`);
426 -function requireThinking(id
: string, value
: unknown)
: ThinkingLevel {
428 - typeof value
!== "string" 429 - || !THINKING_LEVELS.
includes(value
as ThinkingLevel)
432 - `mode ${id}: thinking must be one of ${THINKING_LEVELS.join(", ")}`,
435 - return value
as ThinkingLevel;
438 -function parseModelRef(ref
: string)
: ModelRef | undefined {
439 - const slash
= ref.
indexOf(
"/");
440 - if (slash
<= 0 || slash
=== ref.
length - 1)
return undefined;
441 - return { provider: ref.
slice(
0, slash), modelId: ref.
slice(slash
+ 1) };
444 -function modePromptAddition(mode
: Mode)
: string {
445 - const parts
= [mode.
body.
trimEnd()];
447 - `<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>`,
449 - if (mode.reminder?.
trim()) {
450 - parts.
push(
`<mode_reminder>\n${mode.reminder}\n</mode_reminder>`);
452 - return parts.
filter(
Boolean).
join(
"\n\n");
455 -function normalPromptAddition()
: string {
456 - 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>`;
459 -function isModeStateEntry(value
: unknown)
: value
is ModeStateEntry {
460 - if (
!value
|| typeof value
!== "object")
return false;
461 - const data
= value
as Record<
string,
unknown>;
463 - data.schemaVersion
=== MODE_STATE_VERSION
464 - && (data.activeMode
=== null || typeof data.activeMode
=== "string")
465 - && typeof data.neutralize
=== "boolean" 466 - && (data.reason
=== "switch" || data.reason
=== "off" 467 - || data.reason
=== "compaction")
471 -function latestModeState(entries
: ModeEntryLike[])
: ModeStateEntry | undefined {
472 - for (
let i
= entries.
length - 1; i
>= 0; i
--) {
473 - const entry
= entries[i];
474 - if (entry.
type !== "custom" || entry.customType
!== MODE_STATE_ENTRY) {
477 - if (
isModeStateEntry(entry.
data))
return entry.
data;
482 -async function loadModes(
483 - agentDir
= getAgentDir(),
484 -)
: Promise<{ modes
: Map<
string,
Mode>; warnings
: string[] }> {
485 - const warnings
: string[]
= [];
486 - const modes
= new Map<
string,
Mode>();
487 - const dir
= path.
join(agentDir,
"modes");
488 - let entries
: string[];
490 - entries
= await readdir(dir);
492 - if ((error
as NodeJS.
ErrnoException).
code === "ENOENT") {
493 - return { modes, warnings };
497 - for (
const name
of entries.
sort()) {
498 - if (
!name.
endsWith(
".md"))
continue;
499 - const id
= name.
slice(
0,
-3);
500 - if (
!isValidModeId(id)) {
501 - warnings.
push(
`ignored invalid mode id: ${name}`);
507 - parseModeMarkdown(id,
await readFile(path.
join(dir, name),
"utf8")),
510 - warnings.
push((error
as Error).message);
513 - return { modes, warnings };
516 -function modeLine(mode
: Mode)
: string {
517 - return mode.
description ? `${mode.id} — ${mode.description}` : mode.
id;
520 -function statusText(modeId
: string | null)
: string | undefined {
521 - return modeId
? `MODE ${modeId}` : undefined;
524 -function publishStatus(ctx
: ExtensionContext, modeId
: string | null)
: void {
525 - if (
!ctx.hasUI)
return;
526 - ctx.ui.
setStatus(STATUS_KEY,
statusText(modeId));
529 -function currentModelState(
530 - ctx
: ExtensionContext,
531 -)
: Pick<
ModeStateEntry,
"provider" | "model"> {
532 - return ctx.model
? { provider: ctx.model.provider, model: ctx.model.
id }
: {};
535 -export default function modeExtension(pi
: ExtensionAPI)
: void {
536 - const state
: ModeRuntimeState = {
537 - activeModeId:
null,
543 - async function reloadConfig(ctx
?: ExtensionContext)
: Promise<
void> {
544 - const loaded
= await loadModes();
545 - state.modes
= loaded.modes;
546 - state.warnings
= loaded.warnings;
547 - for (
const warning
of state.warnings) ctx?.ui.
notify(warning,
"warning");
551 - ctx
: ExtensionContext,
552 - reason
: ModeStateEntry[
"reason"],
553 - compactionEntryId
?: string,
558 - schemaVersion: MODE_STATE_VERSION,
559 - activeMode: state.activeModeId,
560 - neutralize: state.neutralize,
562 - ...currentModelState(ctx),
563 - ...(compactionEntryId
? { compactionEntryId }
: {}),
564 - } satisfies ModeStateEntry,
568 - async function applyMode(mode
: Mode, ctx
: ExtensionContext)
: Promise<
void> {
569 - if (mode.tools
&& mode.tools.
length > 0) {
570 - const all
= new Set(pi.
getAllTools().
map((tool)
=> tool.
name));
571 - const valid
= mode.tools.
filter((tool)
=> all.
has(tool));
572 - const unknown
= mode.tools.
filter((tool)
=> !all.
has(tool));
573 - for (
const tool
of unknown) {
575 - `mode ${mode.id}: unknown tool ignored: ${tool}`,
579 - pi.
setActiveTools(valid);
580 - ctx.ui.
notify(
`mode ${mode.id}: tools ${valid.join(", ")}`,
"info");
583 - const ref
= parseModelRef(mode.model);
585 - ? ctx.modelRegistry.
find(ref.provider, ref.modelId)
587 - if (
!ref
|| !model) {
589 - `mode ${mode.id}: model not found: ${mode.model}`,
592 - }
else if (
!(
await pi.
setModel(model))) {
594 - `mode ${mode.id}: model unavailable: ${mode.model}`,
599 - if (mode.thinking) pi.
setThinkingLevel(mode.thinking);
602 - async function switchMode(id
: string, ctx
: ExtensionContext)
: Promise<
void> {
603 - await reloadConfig(ctx);
604 - const mode
= state.modes.
get(id);
606 - ctx.ui.
notify(
`unknown mode: ${id}`,
"warning");
609 - state.activeModeId
= id;
610 - state.neutralize
= false;
611 - await applyMode(mode, ctx);
612 - persist(ctx,
"switch");
613 - publishStatus(ctx, id);
614 - ctx.ui.
notify(
`mode ${id}`,
"info");
617 - function modeOff(ctx
: ExtensionContext)
: void {
618 - const hadMode
= state.activeModeId
!== null;
619 - state.activeModeId
= null;
620 - state.neutralize
= hadMode
|| state.neutralize;
621 - persist(ctx,
"off");
622 - publishStatus(ctx,
null);
623 - ctx.ui.
notify(
"mode off",
"info");
626 - function showStatus(ctx
: ExtensionContext)
: void {
627 - const active
= state.activeModeId
?? "normal";
628 - const modes
= [
...state.modes.
values()].
map(modeLine);
629 - const warnings
= state.warnings.
map((warning)
=> `warning: ${warning}`);
632 - `active: ${active}`,
633 - modes.
length ? `modes:\n${modes.join("\n")}` : "modes: none",
640 - pi.
registerCommand(
"mode", {
641 - description:
"Switch session-local mode",
642 - handler:
async (args, ctx)
=> {
643 - const arg
= args.
trim();
644 - if (
!arg
|| arg
=== "status") {
645 - await reloadConfig(ctx);
649 - if (arg
=== "list") {
650 - await reloadConfig(ctx);
654 - if (arg
=== "reload-config") {
655 - await reloadConfig(ctx);
657 - `mode config: ${state.modes.size} mode(s), ${state.warnings.length} warning(s)`,
658 - state.warnings.
length ? "warning" : "info",
662 - if (arg
=== "off" || arg
=== "normal" || arg
=== "none") {
666 - await switchMode(arg, ctx);
670 - pi.
on(
"before_agent_start", (event)
=> {
671 - const mode
= state.activeModeId
672 - ? state.modes.
get(state.activeModeId)
676 - systemPrompt:
`${event.systemPrompt}\n\n${modePromptAddition(mode)}`,
679 - if (state.neutralize) {
681 - systemPrompt:
`${event.systemPrompt}\n\n${normalPromptAddition()}`,
686 - pi.
on(
"session_start",
async (_event, ctx)
=> {
687 - await reloadConfig(ctx);
688 - const saved
= latestModeState(
689 - ctx.sessionManager.
getBranch()
as ModeEntryLike[],
691 - state.activeModeId
= saved?.activeMode
?? null;
692 - state.neutralize
= saved?.neutralize
?? false;
693 - if (state.activeModeId) {
694 - const mode
= state.modes.
get(state.activeModeId);
695 - if (mode)
await applyMode(mode, ctx);
698 - `mode missing: ${state.activeModeId}; falling back to normal`,
701 - state.activeModeId
= null;
702 - state.neutralize
= true;
703 - persist(ctx,
"off");
706 - publishStatus(ctx, state.activeModeId);
711 - (event, ctx)
=> persist(ctx,
"compaction",
event.compactionEntry.
id),
713 - pi.
on(
"session_shutdown", (_event, ctx)
=> publishStatus(ctx,
null));
716 -export const __modeTest
= {
721 - modePromptAddition,
722 - normalPromptAddition,
729 -- [ ] **Step 4: Run unit tests and verify pass**
734 -mise run test
-- extensions/mode/__tests__/unit.test.ts
739 -- [ ] **Step 5: Commit pure helpers**
744 -git add extensions/mode/index.ts extensions/mode/__tests__/unit.test.ts
745 -git commit -m
"feat(mode): parse mode files and render kernels" 748 -Expected: commit succeeds.
750 -##
Task 3: Runtime command tests 754 -- Create: `extensions/mode/__tests__/harness.test.ts`
755 -- Modify: `extensions/mode/index.ts`
757 -- [ ] **Step 1: Write failing harness tests**
759 -Create `extensions/mode/__tests__/harness.test.ts`:
762 -import { mkdirSync, writeFileSync }
from "node:fs";
763 -import path
from "node:path";
764 -import { afterEach, describe, expect, it }
from "vitest";
765 -import { createTestSession, type TestSession }
from "../../../test/harness";
767 -function extPath() {
768 - return path.
resolve(
import.
meta.dirname,
"../index.ts");
771 -function writeMode(t
: TestSession, name
: string, markdown
: string)
: void {
772 - const dir
= path.
join(t.env.HOME
!,
".pi",
"agent",
"modes");
773 - mkdirSync(dir, { recursive:
true });
774 - writeFileSync(path.
join(dir,
`${name}.md`), markdown,
"utf8");
777 -async function command(t
: TestSession, args
: string)
: Promise<
void> {
778 - const cmd
= t.session.extensionRunner.extensions[
0].commands.
get(
"mode");
779 - await cmd.
handler(args, t.session.extensionRunner.
createCommandContext());
782 -describe(
"mode harness", ()
=> {
783 - let t
: TestSession | undefined;
789 - it(
"loads in real Pi extension runtime",
async ()
=> {
790 - t
= await createTestSession({ extensions: [
extPath()] });
791 - expect(t.session.extensionRunner.extensions).
toHaveLength(
1);
792 - expect(t.session.extensionRunner.extensions[
0].commands.
has(
"mode")).
toBe(
797 - it(
"lists global modes",
async ()
=> {
798 - t
= await createTestSession({ extensions: [
extPath()] });
799 - writeMode(t,
"plan",
"---\ndescription: Read-only planning\n---\nbody");
800 - await command(t,
"list");
801 - const note
= String(t.events.
uiCallsFor(
"notify").
at(
-1)?.args[
0]);
802 - expect(note).
toContain(
"active: normal");
803 - expect(note).
toContain(
"plan — Read-only planning");
806 - it(
"switches mode and filters tools",
async ()
=> {
807 - t
= await createTestSession({ extensions: [
extPath()] });
811 - "---\ntools: [read, grep, missing_tool]\nreminder: Stay read-only.\n---\n# Plan\n",
813 - await command(t,
"plan");
814 - const notes
= t.events.
uiCallsFor(
"notify").
map((call)
=> 815 - String(call.args[
0])
818 - notes.
some((note)
=> note.
includes(
"unknown tool ignored: missing_tool")),
820 - expect(notes.
some((note)
=> note.
includes(
"mode plan: tools read, grep")))
824 - it(
"injects active mode prompt as system prompt",
async ()
=> {
825 - t
= await createTestSession({ extensions: [
extPath()] });
826 - writeMode(t,
"plan",
"---\nreminder: Stay read-only.\n---\n# Plan body\n");
827 - await command(t,
"plan");
828 - const result
= await t.session.extensionRunner.
emitBeforeAgentStart(
834 - expect(result?.systemPrompt).
toContain(
"BASE\n\n# Plan body");
835 - expect(result?.systemPrompt).
toContain(
"active_mode: plan");
836 - expect(result?.systemPrompt).
toContain(
837 - "<mode_reminder>\nStay read-only.\n</mode_reminder>",
839 - expect(result?.messages).
toBeUndefined();
842 - it(
"turns off and injects neutralizer",
async ()
=> {
843 - t
= await createTestSession({ extensions: [
extPath()] });
844 - writeMode(t,
"plan",
"# Plan body\n");
845 - await command(t,
"plan");
846 - await command(t,
"off");
847 - const result
= await t.session.extensionRunner.
emitBeforeAgentStart(
853 - expect(result?.systemPrompt).
toContain(
"active_mode: normal");
854 - expect(result?.systemPrompt).not.
toContain(
"# Plan body");
857 - it(
"restores mode from current branch",
async ()
=> {
858 - t
= await createTestSession({ extensions: [
extPath()] });
859 - writeMode(t,
"plan",
"# Plan body\n");
860 - await command(t,
"plan");
861 - await t.session.extensionRunner.
emit(
862 - { type:
"session_start", reason:
"reload" }
as never,
864 - const result
= await t.session.extensionRunner.
emitBeforeAgentStart(
870 - expect(result?.systemPrompt).
toContain(
"active_mode: plan");
873 - it(
"adds compaction checkpoint",
async ()
=> {
874 - t
= await createTestSession({ extensions: [
extPath()] });
875 - writeMode(t,
"plan",
"# Plan body\n");
876 - await command(t,
"plan");
877 - const msg
= t.session.sessionManager.
appendMessage({
880 - timestamp:
Date.
now(),
882 - const compactionId
= t.session.sessionManager.
appendCompaction(
887 - const compactionEntry
= t.session.sessionManager.
getEntry(compactionId)
!;
888 - await t.session.extensionRunner.
emit(
890 - type:
"session_compact",
892 - fromExtension:
false,
895 - const latest
= t.session.sessionManager.
getLeafEntry()
as {
897 - customType
?: string;
898 - data
?: Record<
string,
unknown>;
900 - expect(latest.
type).
toBe(
"custom");
901 - expect(latest.customType).
toBe(
"mode-state");
902 - expect(latest.
data?.reason).
toBe(
"compaction");
903 - expect(latest.
data?.compactionEntryId).
toBe(compactionId);
908 -- [ ] **Step 2: Run harness test and verify pass**
913 -mise run test
-- extensions/mode/__tests__/harness.test.ts
918 -- [ ] **Step 3: Verify mode-state entries are branch custom entries**
923 -mise run test
-- extensions/mode/__tests__/harness.test.ts -t
"restores mode from current branch" 928 -- [ ] **Step 4: Run harness test suite again**
933 -mise run test
-- extensions/mode/__tests__/harness.test.ts
938 -- [ ] **Step 5: Commit runtime tests**
943 -git add extensions/mode/index.ts extensions/mode/__tests__/harness.test.ts
944 -git commit -m
"test(mode): cover runtime mode switching" 947 -Expected: commit succeeds.
949 -##
Task 4: Model/thinking restore coverage 953 -- Modify: `extensions/mode/__tests__/unit.test.ts`
954 -- Modify: `extensions/mode/__tests__/harness.test.ts`
955 -- Modify: `extensions/mode/index.ts`
957 -- [ ] **Step 1: Add malformed model-ref unit test**
959 -Append to `extensions/mode/__tests__/unit.test.ts` inside the existing `describe`:
962 -it(
"keeps malformed model refs unresolved", ()
=> {
963 - expect(__modeTest.
parseModelRef(
"/model")).
toBeUndefined();
964 - expect(__modeTest.
parseModelRef(
"provider/")).
toBeUndefined();
965 - expect(__modeTest.
parseModelRef(
"provider/model/name")).
toEqual({
966 - provider:
"provider",
967 - modelId:
"model/name",
972 -- [ ] **Step 2: Add model/thinking warning harness test**
974 -Append to `extensions/mode/__tests__/harness.test.ts` inside the existing `describe`:
977 -it(
"warns for unresolved model and still applies thinking",
async ()
=> {
978 - t
= await createTestSession({ extensions: [
extPath()] });
979 - writeMode(t,
"deep",
"---\nmodel: nope/missing\nthinking: high\n---\nbody");
980 - await command(t,
"deep");
981 - const notes
= t.events.
uiCallsFor(
"notify").
map((call)
=> 982 - String(call.args[
0])
984 - expect(notes.
some((note)
=> note.
includes(
"model not found: nope/missing")))
986 - const latestThinking
= [
...t.session.sessionManager.
getBranch()].
reverse()
987 - .
find((entry
: { type
?: string })
=> 988 - entry.
type === "thinking_level_change" 989 - )
as { thinkingLevel
?: string }
| undefined;
990 - expect(latestThinking?.thinkingLevel).
toBe(
"high");
994 -- [ ] **Step 3: Run targeted tests**
999 -mise run test
-- extensions/mode/__tests__/unit.test.ts extensions/mode/__tests__/harness.test.ts
1004 -- [ ] **Step 4: Commit model/thinking coverage**
1009 -git add extensions/mode/index.ts extensions/mode/__tests__/unit.test.ts extensions/mode/__tests__/harness.test.ts
1010 -git commit -m
"test(mode): cover model and thinking application" 1013 -Expected: commit succeeds.
1015 -##
Task 5: Static repo checks 1019 -- Modify: files flagged by formatter/linter only.
1021 -- [ ] **Step 1: Format**
1031 -- [ ] **Step 2: Run targeted tests**
1036 -mise run test
-- extensions/mode/__tests__/unit.test.ts extensions/mode/__tests__/harness.test.ts
1041 -- [ ] **Step 3: Run extension static checks**
1051 -- [ ] **Step 4: Run full CI**
1061 -If CI fails outside `extensions/mode/**` or `package-lock.json`, stop and report the unrelated dirty failure instead of editing unrelated files.
1063 -- [ ] **Step 5: Commit verification fixes**
1065 -If formatting changed files, run:
1068 -git add extensions/mode package-lock.json
1069 -git commit -m
"chore(mode): satisfy repo checks" 1072 -Expected: commit succeeds or there are no formatting changes to commit.
1074 -##
Task 6: Final implementation audit 1078 -- Read: `extensions/mode/V1.md`
1079 -- Read: `extensions/mode/index.ts`
1080 -- Read: `extensions/mode/__tests__/unit.test.ts`
1081 -- Read: `extensions/mode/__tests__/harness.test.ts`
1083 -- [ ] **Step 1: Map V1 requirements to code/tests**
1085 -Create this checklist in the worker notes and mark each item with file/function/test evidence:
1088 -- global getAgentDir()/modes/*.md loading
1090 -- YAML frontmatter validation
1091 -- mode schema fields
1092 -- active mode switch command
1093 -- off/normal/none aliases
1094 -- status/list/reload-config commands
1095 -- tool filtering and unknown warnings
1096 -- model parse/resolve/set warnings
1097 -- thinking application
1098 -- system prompt mode body/kernel/reminder injection
1099 -- normal neutralizer injection
1100 -- custom mode-state persistence
1101 -- getBranch restore
1102 -- missing restored mode fallback
1103 -- session_compact checkpoint
1104 -- status UI set/clear
1105 -- no project-local modes
1106 -- no custom prompt messages
1109 -- [ ] **Step 2: Fill any coverage gap with a test**
1111 -For each unchecked item, add one unit or harness test before changing implementation.
1113 -Use this command after each added test:
1116 -mise run test
-- extensions/mode/__tests__/unit.test.ts extensions/mode/__tests__/harness.test.ts
1119 -Expected: new test FAILS before implementation change, then PASSES after implementation change.
1121 -- [ ] **Step 3: Final CI**
1131 -- [ ] **Step 4: Final commit**
1137 -git add extensions/mode package-lock.json
1138 -git commit -m
"feat(mode): add session-local modes" 1143 -- Only mode extension files and `package-lock.json` are staged.
1144 -- Unrelated existing dirty files remain unstaged.
28 +See `git log -- extensions/mode` for the implementation commit history.