Local-first AI coding agent desktop: Electron + Rust host core + pi Agent Harness + user-installable plugins
TypeScript ai-agentcoding-agentdesktop-appelectronglobali18nlocal-firstmcppipi-agentpi-desktoppluginsreactrusttypescript
fix(modes): validate integrated workflows and approval fixtures
vastsa990442fb8c3d
diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.ymlindex a1e345dd4..2395e5fa6 100644--- a/.github/workflows/ci.yml+++ b/.github/workflows/ci.yml@@ -168,6 +168,11 @@ jobs:- name: Build host-corerun: cargo build -p host-core --locked+ - name: Run staged mode Host/process E2E+ env:+ PI_SCRATCH_DIR: ${{ runner.temp }}+ run: node scripts/e2e-mode-definitions.mjs+- name: Run plugin project enumeration Host/process E2Erun: pnpm test:e2e:plugin-projectsdiff --git a/apps/desktop/test/asktool-resolve-clears-host-input.test.mjs b/apps/desktop/test/asktool-resolve-clears-host-input.test.mjsindex 8e384ceee..428559ee2 100644--- a/apps/desktop/test/asktool-resolve-clears-host-input.test.mjs+++ b/apps/desktop/test/asktool-resolve-clears-host-input.test.mjs@@ -1,3 +1,4 @@+import { builtinModeRuns } from "./helpers/builtin-mode-runs.mjs";import assert from "node:assert/strict";import test from "node:test";import { dirname } from "node:path";@@ -158,6 +159,7 @@ test("a Host-owned answer does not re-enter its own IPC handler", async (t) => {const noop = () => undefined;registerAgentIpc({+ modeRuns: builtinModeRuns,registrar,getHost: () => null,getSidecar: () => sidecar,diff --git a/apps/desktop/test/composer-agent-mention.test.mjs b/apps/desktop/test/composer-agent-mention.test.mjsindex 0111cc8af..257de6312 100644--- a/apps/desktop/test/composer-agent-mention.test.mjs+++ b/apps/desktop/test/composer-agent-mention.test.mjs@@ -1,3 +1,4 @@+import { builtinModeRuns } from "./helpers/builtin-mode-runs.mjs";import assert from "node:assert/strict";import { mkdtemp, rm, writeFile } from "node:fs/promises";import { tmpdir } from "node:os";@@ -23,6 +24,7 @@ function promptFixture({ mode = "agent", projectPath = null, skills = [], templaassert.fail(`unexpected RPC ${method}`);} };registerAgentIpc({+ modeRuns: builtinModeRuns,registrar: { handle: (channel, handler) => handlers.set(channel, handler) },getHost: () => host,getSidecar: () => ({ setProjectInstructionRoot() {}, async call(method, params) {diff --git a/apps/desktop/test/composer-mcp.test.mjs b/apps/desktop/test/composer-mcp.test.mjsindex 51c248e31..a3cf7ea72 100644--- a/apps/desktop/test/composer-mcp.test.mjs+++ b/apps/desktop/test/composer-mcp.test.mjs@@ -1,3 +1,4 @@+import { builtinModeRuns } from "./helpers/builtin-mode-runs.mjs";import assert from "node:assert/strict";import test from "node:test";import { fileURLToPath } from "node:url";@@ -63,6 +64,7 @@ function promptFixture(commandService, projectPath = "/repo", remoteWorkspace) {assert.fail(`unexpected RPC ${method}`);} };registerAgentIpc({+ modeRuns: builtinModeRuns,registrar: { handle: (channel, handler) => handlers.set(channel, handler) },getHost: () => host,getSidecar: () => ({ setProjectInstructionRoot() {}, async call(method, params) {diff --git a/apps/desktop/test/helpers/builtin-mode-runs.mjs b/apps/desktop/test/helpers/builtin-mode-runs.mjsnew file mode 100644index 000000000..86633e838--- /dev/null+++ b/apps/desktop/test/helpers/builtin-mode-runs.mjs@@ -0,0 +1,17 @@+/** Mode service boundary for pre-existing Agent/Plan IPC fixtures.+ * Staged-mode dispatch is covered by mode-runs-main.test.mjs.+ */+export const builtinModeRuns = {+ async definitionForPrompt(id) {+ if (id !== "agent" && id !== "plan") throw new Error(`Unsupported fixture mode: ${id}`);+ return undefined;+ },+ async canContinue() { return false; },+ async prepareTurn({ sessionMode }) {+ if (sessionMode !== "agent" && sessionMode !== "plan") {+ throw new Error(`Unsupported fixture mode: ${sessionMode}`);+ }+ return undefined;+ },+ async abandonTurn() {},+};diff --git a/apps/desktop/test/helpers/live-work-production.mjs b/apps/desktop/test/helpers/live-work-production.mjsindex 5b8c65190..db49c23ba 100644--- a/apps/desktop/test/helpers/live-work-production.mjs+++ b/apps/desktop/test/helpers/live-work-production.mjs@@ -1,3 +1,4 @@+import { builtinModeRuns } from "./builtin-mode-runs.mjs";import assert from "node:assert/strict";import { IPC } from "@pi-desktop/shared";import { sessionWorkspaceIdentity } from "@pi-desktop/host-runtime";@@ -54,6 +55,7 @@ export async function createProductionWorkHarness(t, server, options = {}) {},};registerAgentIpc({+ modeRuns: builtinModeRuns,registrar: { handle: (channel, handler) => registeredHandlers.set(channel, handler) },getHost: () => host,getSidecar: () => ({diff --git a/apps/desktop/test/native-pi-sessions.test.mjs b/apps/desktop/test/native-pi-sessions.test.mjsindex a6af9c6d4..33052ed0e 100644--- a/apps/desktop/test/native-pi-sessions.test.mjs+++ b/apps/desktop/test/native-pi-sessions.test.mjs@@ -1,3 +1,4 @@+import { builtinModeRuns } from "./helpers/builtin-mode-runs.mjs";import assert from "node:assert/strict";import test from "node:test";import { readFile } from "node:fs/promises";@@ -59,6 +60,7 @@ test("unsupported native agent IPC never reaches host or queue", async () => {const forbidden = () => assert.fail("native operation reached Desktop backend");const backend = new Proxy({}, { get: () => forbidden });registerAgentIpc({+ modeRuns: builtinModeRuns,registrar: { handle: (channel, handler) => handlers.set(channel, handler) },getHost: () => backend, getSidecar: () => backend, getAgentHostBridge: () => backend,});@@ -126,6 +128,7 @@ test("queue remove/prioritize preserve the Desktop opaque host turnId contract",const handlers = new Map();const calls = [];registerAgentIpc({+ modeRuns: builtinModeRuns,registrar: { handle: (channel, handler) => handlers.set(channel, handler) },getHost: () => null, getSidecar: () => null,getAgentHostBridge: () => ({ queue: {@@ -144,6 +147,7 @@ test("native prompt only dispatches sidecar and cannot create a host queue entryconst backend = new Proxy({}, { get: () => forbidden });const calls = [];registerAgentIpc({+ modeRuns: builtinModeRuns,registrar: { handle: (channel, handler) => handlers.set(channel, handler) },getHost: () => backend, getAgentHostBridge: () => backend, setNotificationViewingSessionId() {},getSidecar: () => ({ call: async (...args) => { calls.push(args); return { accepted: true, turnId: "native-turn" }; } }),diff --git a/apps/desktop/test/plugin-skills.test.mjs b/apps/desktop/test/plugin-skills.test.mjsindex 1fa672d0b..590dba2bd 100644--- a/apps/desktop/test/plugin-skills.test.mjs+++ b/apps/desktop/test/plugin-skills.test.mjs@@ -165,14 +165,14 @@ test("plugin dev tools resolve paths inside the workspace and report failures",assert.match(devToolsSrc, /loadPlugin\(target\.path, permissions\)/);});-test("only PluginCheck is available outside agent mode", () => {+test("plugin creation and packaging require agent-level tool policy", () => {const builderEnd = agentRuntimeSrc.indexOf("const builtins = tools.map(exec)",);const builderStart = agentRuntimeSrc.lastIndexOf("const tools =", builderEnd);assert.ok(builderStart >= 0 && builderEnd > builderStart);const builder = agentRuntimeSrc.slice(builderStart, builderEnd);- const agentBranchStart = builder.indexOf('if (this.mode === "agent")');+ const agentBranchStart = builder.indexOf("if (agentLevel) tools.push");assert.ok(agentBranchStart >= 0);const nonAgentBranch = builder.slice(0, agentBranchStart);assert.match(nonAgentBranch, /"PluginCheck"/);diff --git a/apps/desktop/test/session-message-input.test.mjs b/apps/desktop/test/session-message-input.test.mjsindex 7b88a2ff4..92ebdce12 100644--- a/apps/desktop/test/session-message-input.test.mjs+++ b/apps/desktop/test/session-message-input.test.mjs@@ -1,3 +1,4 @@+import { builtinModeRuns } from "./helpers/builtin-mode-runs.mjs";import assert from "node:assert/strict";import { register } from "node:module";import test from "node:test";@@ -78,6 +79,7 @@ test("prompt IPC persists original session text, skips slash expansion and binds};let released = false;registerAgentIpc({+ modeRuns: builtinModeRuns,registrar: { handle: (channel, handler) => handlers.set(channel, handler) },getHost: () => host,getSidecar: () => ({@@ -136,6 +138,7 @@ test("abort waits for prompt admission before dispatching to the sidecar", asyncconst sidecarCalls = [];const finishedTurns = [];registerAgentIpc({+ modeRuns: builtinModeRuns,registrar: { handle: (channel, handler) => handlers.set(channel, handler) },getHost: () => host,getSidecar: () => ({diff --git a/crates/host-core/src/db.rs b/crates/host-core/src/db.rsindex 37aaaafbb..11a2dc898 100644--- a/crates/host-core/src/db.rs+++ b/crates/host-core/src/db.rs@@ -16,8 +16,8 @@ pub const PLAN_APPROVAL_TIMEOUT_MS: i64 = 30 * 60 * 1000;pub const NOTIFICATION_KEEP: i64 = 200;mod migrations;-mod model;mod mode_runs_migration;+mod model;mod model_discovery_migration;mod plugin_providers_migration;mod project_groups;diff --git a/crates/host-core/src/mode_runs.rs b/crates/host-core/src/mode_runs.rsindex f45fd3e04..cffc1b31f 100644--- a/crates/host-core/src/mode_runs.rs+++ b/crates/host-core/src/mode_runs.rs@@ -19,13 +19,11 @@ mod repository;mod snapshot;pub use engine::{- claim_turn, configure_session_mode, control, open_run, prepare_session_mode, recover,- resolve, settle_turn, start, store_session_snapshot, verify_gate_command, PreparedMode,+ claim_turn, configure_session_mode, control, open_run, prepare_session_mode, recover, resolve,+ settle_turn, start, store_session_snapshot, verify_gate_command, PreparedMode,};pub use gates::{complete_stage, gate_result, GateExecution, GateExecutions};-pub use model::{- CompleteStageParams, GateResultParams, ModeRun, SessionParams, StartParams,-};+pub use model::{CompleteStageParams, GateResultParams, ModeRun, SessionParams, StartParams};pub use policy::{authorization, tool_policy, tool_policy_conn, ToolPolicy};/// Mode ids are `^[a-z][a-z0-9-]{0,39}$`, shared with `MODE_ID_RE` indiff --git a/crates/host-core/src/mode_runs/artifacts.rs b/crates/host-core/src/mode_runs/artifacts.rsindex 01513a71b..4f59e2777 100644--- a/crates/host-core/src/mode_runs/artifacts.rs+++ b/crates/host-core/src/mode_runs/artifacts.rs@@ -28,7 +28,9 @@ fn canonical_root(workspace: &Path) -> Result<PathBuf> {/// `root/relative` after the lexical rules. Nothing is touched on disk.fn lexical_target(root: &Path, relative: &str) -> Result<PathBuf> {if !valid_artifact_path(relative) {- return Err(path_error(format!("`{relative}` is not a workspace-relative path")));+ return Err(path_error(format!(+ "`{relative}` is not a workspace-relative path"+ )));}let mut target = root.to_path_buf();for segment in relative.split('/') {@@ -166,11 +168,7 @@ fn heading_text(line: &str) -> Option<String> {if !rest.starts_with(|ch: char| ch.is_whitespace()) {return None;}- let text = rest- .trim()- .trim_end_matches('#')- .trim_end()- .to_string();+ let text = rest.trim().trim_end_matches('#').trim_end().to_string();Some(text)}diff --git a/crates/host-core/src/mode_runs/engine.rs b/crates/host-core/src/mode_runs/engine.rsindex ed0acda5c..e0f515645 100644--- a/crates/host-core/src/mode_runs/engine.rs+++ b/crates/host-core/src/mode_runs/engine.rs@@ -72,7 +72,11 @@ fn finish(run: &mut ModeRun, state: RunState) {}/// Session-side effect of a closed run.-pub(super) fn apply_finish(conn: &Connection, run: &ModeRun, definition: &ModeDefinition) -> Result<()> {+pub(super) fn apply_finish(+ conn: &Connection,+ run: &ModeRun,+ definition: &ModeDefinition,+) -> Result<()> {if run.state.is_open() {return Ok(());}@@ -468,7 +472,9 @@ pub fn verify_gate_command(.ok().and_then(|index| snapshot.definition.stage(&run.stage_id)?.exit.get(index));match expected {- Some(snapshot::ModeGate::Run { command: expected, .. }) if expected == command => Ok(()),+ Some(snapshot::ModeGate::Run {+ command: expected, ..+ }) if expected == command => Ok(()),_ => Err(mismatch()),}}@@ -482,7 +488,9 @@ pub struct PreparedMode {impl PreparedMode {pub fn snapshot_hash(&self) -> Option<&str> {- self.snapshot.as_ref().map(|snapshot| snapshot.hash.as_str())+ self.snapshot+ .as_ref()+ .map(|snapshot| snapshot.hash.as_str())}}@@ -516,10 +524,7 @@ pub fn prepare_session_mode(}}}- Ok(PreparedMode {- snapshot,- pause,- })+ Ok(PreparedMode { snapshot, pause })}/// Persist the snapshot before the session row references it.diff --git a/crates/host-core/src/mode_runs/gates.rs b/crates/host-core/src/mode_runs/gates.rsindex ae08b5032..6d0dc95b0 100644--- a/crates/host-core/src/mode_runs/gates.rs+++ b/crates/host-core/src/mode_runs/gates.rs@@ -63,8 +63,10 @@ impl GateExecutions {self.entries.remove(&key);}}- self.entries- .insert((session_id.to_string(), tool_call_id.to_string()), execution);+ self.entries.insert(+ (session_id.to_string(), tool_call_id.to_string()),+ execution,+ );}fn get(&self, session_id: &str, tool_call_id: &str) -> Option<&GateExecution> {diff --git a/crates/host-core/src/mode_runs/policy.rs b/crates/host-core/src/mode_runs/policy.rsindex 5b6b524bc..22f3dac39 100644--- a/crates/host-core/src/mode_runs/policy.rs+++ b/crates/host-core/src/mode_runs/policy.rs@@ -81,7 +81,12 @@ fn session_row(conn: &Connection, session_id: &str) -> Result<Option<(String, Op/// Resolution order: the open run of the session's mode (its stage's/// permission), then the session snapshot of that mode, then the builtin/// names. Any other id fails closed to `Contract`.-fn resolve(conn: &Connection, session_id: &str, mode: &str, hash: Option<&str>) -> Result<ToolPolicy> {+fn resolve(+ conn: &Connection,+ session_id: &str,+ mode: &str,+ hash: Option<&str>,+) -> Result<ToolPolicy> {if let Some(run) = repository::open_run(conn, session_id)? {if run.mode_id == mode {let snapshot = snapshot::require(conn, &run.snapshot_hash)?;diff --git a/crates/host-core/src/mode_runs/repository.rs b/crates/host-core/src/mode_runs/repository.rsindex 8f7ebc8c0..f4cbc5294 100644--- a/crates/host-core/src/mode_runs/repository.rs+++ b/crates/host-core/src/mode_runs/repository.rs@@ -17,7 +17,10 @@ const COLUMNS: &str = "id, session_id, mode_id, snapshot_hash, input, stage_id,const OPEN_STATES: &str = "('running', 'waiting', 'paused', 'budget_exhausted')";-fn conversion(index: usize, error: impl std::error::Error + Send + Sync + 'static) -> rusqlite::Error {+fn conversion(+ index: usize,+ error: impl std::error::Error + Send + Sync + 'static,+) -> rusqlite::Error {rusqlite::Error::FromSqlConversionFailure(index, rusqlite::types::Type::Text, Box::new(error))}@@ -198,9 +201,7 @@ pub struct GateRecord<'a> {}pub fn record_gate(conn: &Connection, run_id: &str, record: GateRecord<'_>) -> Result<()> {- let evidence = record- .evidence- .map(|text| tail(text, MAX_EVIDENCE_BYTES));+ let evidence = record.evidence.map(|text| tail(text, MAX_EVIDENCE_BYTES));conn.prepare_cached("INSERT INTO mode_gate_results(run_id, stage_id, gate_index, action, passed, evidence, tool_call_id, created_at)diff --git a/crates/host-core/src/mode_runs/snapshot.rs b/crates/host-core/src/mode_runs/snapshot.rsindex 9ff6e3e0e..4e7577701 100644--- a/crates/host-core/src/mode_runs/snapshot.rs+++ b/crates/host-core/src/mode_runs/snapshot.rs@@ -90,7 +90,11 @@ pub struct ModeStage {}#[derive(Debug, Clone, Deserialize)]-#[serde(tag = "kind", rename_all = "lowercase", rename_all_fields = "camelCase")]+#[serde(+ tag = "kind",+ rename_all = "lowercase",+ rename_all_fields = "camelCase"+)]pub enum ModeGate {Require {artifact: String,@@ -210,7 +214,10 @@ fn check(definition: &ModeDefinition, mode: &str) -> Result<()> {return Err(invalid(format!("artifact id `{}` is invalid", artifact.id)));}if !valid_artifact_path(&artifact.path) {- return Err(invalid(format!("artifact `{}` has an unsafe path", artifact.id)));+ return Err(invalid(format!(+ "artifact `{}` has an unsafe path",+ artifact.id+ )));}if artifact.required_headings.len() > MAX_HEADINGS|| artifact.required_headings.iter().any(|heading| {diff --git a/crates/host-core/src/mode_runs/snapshot_tests.rs b/crates/host-core/src/mode_runs/snapshot_tests.rsindex 573955ee8..54abf01c7 100644--- a/crates/host-core/src/mode_runs/snapshot_tests.rs+++ b/crates/host-core/src/mode_runs/snapshot_tests.rs@@ -91,14 +91,12 @@ fn each_invalid_rule_is_rejected() {"kind": "run", "command": "x".repeat(2001), "timeoutMinutes": 5, "onFail": { "retries": 0 }}])});- rejects(|v| {- v["stages"][0]["exit"] =- json!([{ "kind": "run", "command": "true", "timeoutMinutes": 61, "onFail": { "retries": 0 } }])- });- rejects(|v| {- v["stages"][0]["exit"] =- json!([{ "kind": "run", "command": "true", "timeoutMinutes": 0, "onFail": { "retries": 0 } }])- });+ rejects(+ |v| v["stages"][0]["exit"] = json!([{ "kind": "run", "command": "true", "timeoutMinutes": 61, "onFail": { "retries": 0 } }]),+ );+ rejects(+ |v| v["stages"][0]["exit"] = json!([{ "kind": "run", "command": "true", "timeoutMinutes": 0, "onFail": { "retries": 0 } }]),+ );rejects(|v| {v["stages"][0]["exit"] = json!([{ "kind": "ask" },diff --git a/crates/host-core/src/mode_runs/tests.rs b/crates/host-core/src/mode_runs/tests.rsindex 18a0b458a..307f09ab6 100644--- a/crates/host-core/src/mode_runs/tests.rs+++ b/crates/host-core/src/mode_runs/tests.rs@@ -123,7 +123,12 @@ pub(super) fn claim(fx: &Fixture, run: &ModeRun, turn: &str, origin: Origin) ->.unwrap()}-pub(super) fn settle(fx: &Fixture, run: &ModeRun, turn: &str, outcome: TurnOutcome) -> ContinueResult {+pub(super) fn settle(+ fx: &Fixture,+ run: &ModeRun,+ turn: &str,+ outcome: TurnOutcome,+) -> ContinueResult {settle_turn(&fx.db,SettleParams {@@ -157,7 +162,11 @@ pub(super) fn complete()}-fn control_run(fx: &Fixture, run: &ModeRun, action: ControlAction) -> anyhow::Result<ContinueResult> {+fn control_run(+ fx: &Fixture,+ run: &ModeRun,+ action: ControlAction,+) -> anyhow::Result<ContinueResult> {control(&fx.db,ControlParams {@@ -220,7 +229,9 @@ fn full_lifecycle_returns_the_session_to_its_return_mode() {other => panic!("expected failed, got {other:?}"),}let headings = complete(&fx, &run, "t1", plan_artifact("# Plan\nonly")).unwrap();- assert!(matches!(headings.status, StageStatus::Blocked { ref message } if message.contains("Risks")));+ assert!(+ matches!(headings.status, StageStatus::Blocked { ref message } if message.contains("Risks"))+ );// A blocked stage waits for the user; Host continuation is refused.let blocked = settle(&fx, &headings.run, "t1", TurnOutcome::Completed);assert!(!blocked.continue_run);@@ -248,7 +259,10 @@ fn full_lifecycle_returns_the_session_to_its_return_mode() {let settled = settle(&fx, &advanced.run, "t2", TurnOutcome::Completed);assert!(settled.continue_run, "an advanced stage continues");let again = settle(&fx, &settled.run, "t2", TurnOutcome::Completed);- assert!(!again.continue_run && !again.changed, "settle is idempotent");+ assert!(+ !again.continue_run && !again.changed,+ "settle is idempotent"+ );assert_eq!(again.run.rounds_completed, 2);let host = claim(&fx, &settled.run, "t3", Origin::Host);@@ -269,7 +283,11 @@ fn full_lifecycle_returns_the_session_to_its_return_mode() {let gates: i64 = fx.db.conn()- .query_row("SELECT COUNT(*) FROM mode_gate_results WHERE run_id = ?1", [&run.id], |r| r.get(0))+ .query_row(+ "SELECT COUNT(*) FROM mode_gate_results WHERE run_id = ?1",+ [&run.id],+ |r| r.get(0),+ ).unwrap();assert_eq!(gates, 3);}@@ -289,11 +307,16 @@ fn goto_moves_to_the_named_stage_and_continues() {configure(&fx.db, &sid, "loopback", Some(&def)).unwrap();let run = start_run(&fx, &sid, "t1").run;let first = settle(&fx, &run, "t1", TurnOutcome::Completed);- assert!(first.continue_run, "a stage without gates passes at turn end");+ assert!(+ first.continue_run,+ "a stage without gates passes at turn end"+ );assert_eq!(first.run.stage_id, "check");let claimed = claim(&fx, &first.run, "t2", Origin::Host);let outcome = complete(&fx, &claimed.run, "t2", None).unwrap();- assert!(matches!(outcome.status, StageStatus::Goto { ref next_stage_id, .. } if next_stage_id == "draft"));+ assert!(+ matches!(outcome.status, StageStatus::Goto { ref next_stage_id, .. } if next_stage_id == "draft")+ );assert_eq!(outcome.run.stage_id, "draft");assert!(settle(&fx, &outcome.run, "t2", TurnOutcome::Completed).continue_run);}@@ -403,7 +426,11 @@ fn pause_resume_stop_and_turn_outcomes() {let run = start_run(&fx, &sid, "t1").run;let paused = control_run(&fx, &run, ControlAction::Pause).unwrap();assert_eq!(paused.run.state, RunState::Paused);- assert_eq!(paused.run.active_turn_id.as_deref(), Some("t1"), "the turn runs to its end");+ assert_eq!(+ paused.run.active_turn_id.as_deref(),+ Some("t1"),+ "the turn runs to its end"+ );let settled = settle(&fx, &paused.run, "t1", TurnOutcome::Completed);assert!(!settled.continue_run);assert_eq!(settled.run.state, RunState::Paused);@@ -413,7 +440,11 @@ fn pause_resume_stop_and_turn_outcomes() {let aborted = claim(&fx, &resumed.run, "t2", Origin::Approval);let aborted = settle(&fx, &aborted.run, "t2", TurnOutcome::Aborted);- assert_eq!(aborted.run.state, RunState::Paused, "composer Stop pauses the run");+ assert_eq!(+ aborted.run.state,+ RunState::Paused,+ "composer Stop pauses the run"+ );let failed = claim(&fx, &aborted.run, "t3", Origin::User);let failed = settle(&fx, &failed.run, "t3", TurnOutcome::Error);assert_eq!(failed.run.wait_reason, Some(WaitReason::Error));@@ -429,18 +460,21 @@ fn pause_resume_stop_and_turn_outcomes() {},);assert_eq!(stale.unwrap_err().to_string(), "MODE_REVISION_CONFLICT");- assert!(!claim_turn(- &fx.db,- ClaimParams {- session_id: sid.clone(),- run_id: run.id.clone(),- expected_revision: run.revision,- turn_id: "t4".into(),- origin: Origin::User,- },- )- .unwrap()- .claimed, "a stale claim is refused, not an error");+ assert!(+ !claim_turn(+ &fx.db,+ ClaimParams {+ session_id: sid.clone(),+ run_id: run.id.clone(),+ expected_revision: run.revision,+ turn_id: "t4".into(),+ origin: Origin::User,+ },+ )+ .unwrap()+ .claimed,+ "a stale claim is refused, not an error"+ );let stopped = control_run(&fx, &failed.run, ControlAction::Stop).unwrap();assert_eq!(stopped.run.state, RunState::Stopped);@@ -475,7 +509,9 @@ fn configure_while_a_run_is_open() {configure(&fx.db, &sid, "flow", Some(&flow())).unwrap();let run = start_run(&fx, &sid, "t1").run;settle(&fx, &run, "t1", TurnOutcome::Completed);- assert!(configure(&fx.db, &sid, "flow", Some(&flow())).unwrap().is_none());+ assert!(configure(&fx.db, &sid, "flow", Some(&flow()))+ .unwrap()+ .is_none());let other = definition("other","agent",@@ -521,7 +557,9 @@ fn configure_while_a_run_is_open() {"MODE_RUN_ACTIVE");assert_eq!(- configure(&fx.db, &sid, "custom", None).unwrap_err().to_string(),+ configure(&fx.db, &sid, "custom", None)+ .unwrap_err()+ .to_string(),"MODE_SNAPSHOT_REQUIRED");}@@ -615,7 +653,9 @@ fn completing_a_stage_requires_the_claim_and_declared_artifacts() {configure(&fx.db, &sid, "flow", Some(&flow())).unwrap();let run = start_run(&fx, &sid, "t1").run;assert_eq!(- complete(&fx, &run, "other-turn", None).unwrap_err().to_string(),+ complete(&fx, &run, "other-turn", None)+ .unwrap_err()+ .to_string(),"MODE_CLAIM_MISMATCH");let unknown = Some(BTreeMap::from([("nope".to_string(), "x".to_string())]));diff --git a/crates/host-core/src/rpc/modes_rpc.rs b/crates/host-core/src/rpc/modes_rpc.rsindex f9883bd22..5bb6a5237 100644--- a/crates/host-core/src/rpc/modes_rpc.rs+++ b/crates/host-core/src/rpc/modes_rpc.rs@@ -17,7 +17,8 @@ use crate::state::AppState;use crate::tools::ToolsExecuteParams;fn parse<T: DeserializeOwned>(value: Value) -> Result<T, JsonRpcError> {- serde_json::from_value(value).map_err(|error| rpc_err(1002, error.to_string(), "INVALID_PARAMS"))+ serde_json::from_value(value)+ .map_err(|error| rpc_err(1002, error.to_string(), "INVALID_PARAMS"))}/// `MODE_*` failures keep their code as the wire `errorCode`; anything else@@ -26,7 +27,11 @@ pub(super) fn error(error: anyhow::Error) -> JsonRpcError {let message = error.to_string();let code = message.split(':').next().unwrap_or_default().trim();if code.starts_with("MODE_") && code.chars().all(|ch| ch.is_ascii_uppercase() || ch == '_') {- let rpc_code = if code.ends_with("_NOT_FOUND") { 1007 } else { 1002 };+ let rpc_code = if code.ends_with("_NOT_FOUND") {+ 1007+ } else {+ 1002+ };let code = code.to_string();rpc_err(rpc_code, message, &code)} else {diff --git a/crates/host-core/src/rpc/modes_rpc_tests.rs b/crates/host-core/src/rpc/modes_rpc_tests.rsindex db120ef7d..67f5f1c35 100644--- a/crates/host-core/src/rpc/modes_rpc_tests.rs+++ b/crates/host-core/src/rpc/modes_rpc_tests.rs@@ -87,7 +87,12 @@ impl Harness {.unwrap()}- async fn bash(&self, call_id: &str, command: &str, gate: Option<Value>) -> Result<Value, Value> {+ async fn bash(+ &self,+ call_id: &str,+ command: &str,+ gate: Option<Value>,+ ) -> Result<Value, Value> {let shell = crate::tools::shell::default_shell_id();let mut params = json!({"sessionId": self.session_id,@@ -222,13 +227,50 @@ async fn run_gates_use_the_exit_code_tools_execute_recorded() {.await.unwrap();assert_eq!(verify["status"], "run");- let failed = h- .bash(- "gate-1",- FAIL,- Some(json!({ "runId": run_id, "gateIndex": 0 })),- )+ // Host-origin continuations use accept-edits even in an Auto session.+ // Resolve the real permission request instead of leaving this test waiting.+ let state = h.state.clone();+ let tx = h.tx.clone();+ let shell = crate::tools::shell::default_shell_id();+ let execute = tokio::spawn(handle_request(+ state,+ "tools.execute",+ json!({+ "sessionId": h.session_id, "turnId": "t2", "toolCallId": "gate-1",+ "toolName": "Bash", "args": { "command": FAIL }, "mode": "agent",+ "expectedCommandShellId": shell,+ "expectedCommandShellDialect": crate::tools::shell::dialect_for_id(shell),+ "modeGate": { "runId": run_id, "gateIndex": 0 }+ }),+ tx,+ ));+ let mut observed_mode_events = Vec::new();+ let approval = tokio::time::timeout(std::time::Duration::from_secs(5), async {+ loop {+ let line = h.rx.recv().await.expect("permission stream remains open");+ let event: Value = serde_json::from_str(&line).unwrap();+ if event["method"] == "modes.changed" {+ observed_mode_events.push(event["params"].clone());+ }+ if event["method"] == "permissions.request" {+ break event;+ }+ }+ })+ .await+ .expect("host continuation must request approval");+ h.call(+ "permissions.resolve",+ json!({+ "requestId": approval["params"]["requestId"], "decision": "allow-once"+ }),+ )+ .await+ .unwrap();+ let failed = tokio::time::timeout(std::time::Duration::from_secs(10), execute).await+ .unwrap()+ .unwrap().unwrap();assert_eq!(failed["ok"], false);let blocked = h@@ -239,10 +281,14 @@ async fn run_gates_use_the_exit_code_tools_execute_recorded() {.await.unwrap();assert_eq!(blocked["status"], "blocked");- assert!(blocked["message"].as_str().unwrap().contains("exited with code 3"));+ assert!(blocked["message"]+ .as_str()+ .unwrap()+ .contains("exited with code 3"));assert_eq!(blocked["run"]["state"], "waiting");assert_eq!(blocked["run"]["waitReason"], "retries");- assert!(h.mode_events().len() >= 6);+ observed_mode_events.extend(h.mode_events());+ assert!(observed_mode_events.len() >= 6);let got = h.call("modes.get", json!({ "sessionId": h.session_id }))@@ -313,7 +359,9 @@ async fn configure_validates_the_mode_snapshot() {assert_eq!(configured["session"]["mode"], "checks");let st = h.state.lock().await;assert_eq!(- sessions::session_mode(&st.db, &h.session_id).unwrap().as_deref(),+ sessions::session_mode(&st.db, &h.session_id)+ .unwrap()+ .as_deref(),Some("checks"));}@@ -346,7 +394,9 @@ async fn legacy_goal_activation_is_disabled() {assert_eq!(error_code(&submitted), "PLAN_GOAL_ACTIVATION_DISABLED");let st = h.state.lock().await;assert_eq!(- sessions::session_mode(&st.db, &h.session_id).unwrap().as_deref(),+ sessions::session_mode(&st.db, &h.session_id)+ .unwrap()+ .as_deref(),Some("agent"));}diff --git a/docs/adr/mode-definitions.md b/docs/adr/mode-definitions.mdindex a6ba5c048..3493334d1 100644--- a/docs/adr/mode-definitions.md+++ b/docs/adr/mode-definitions.md@@ -1,6 +1,6 @@# ADR: User-definable modes as staged workflows-- Status: Proposed+- Status: Implemented candidate- Date: 2026-11-07- Supersedes: hard-coded `Mode = "plan" | "goal" | "agent"` behavior(contract-mode grouping D198). The Plan approval flow in ADR 0053 is@@ -209,7 +209,7 @@ One migration after the current schema:- `mode_gate_results`: run, stage, gate index, action, result, evidence andtimestamp.- Existing `plan_approvals` rows stay valid. The builtin `plan` reads them in- its `ask: user` gate.+ the existing Plan proposal pipeline.### 9. Builtins and compatibilitydiff --git a/docs/spec/03-runtime/04-data-storage.md b/docs/spec/03-runtime/04-data-storage.mdindex 3813c1c4f..775f5fde7 100644--- a/docs/spec/03-runtime/04-data-storage.md+++ b/docs/spec/03-runtime/04-data-storage.md@@ -2114,3 +2114,20 @@ coordinates and finite context. The existing 512 KiB-per-image, 4000-total-linesper side, 2,000,000-middle-cell, and context serialization caps are unchanged.This affects new captures only; missing historical previews are not reconstructedfrom current disk contents.+++## User-defined mode runs (schema 29)++ADR `mode-definitions` adds one v28-to-v29 migration. It backs up the existing+database before adding `mode_snapshots`, `mode_runs`, `mode_gate_results` and+`sessions.mode_snapshot_hash`. Existing sessions and Plan approvals are retained.+Mode ids remain in `sessions.mode`; `chat` still normalizes to `plan`.++A run references an immutable definition snapshot, its current stage, revision,+claim, permission origin, budgets, token usage and completed-round count.+Gate results record the stage, action, outcome and bounded evidence. At most+one open run exists per session. Restart clears in-flight claims and pauses+those runs without replaying work. Deleting a session cascades its run records.++Host-started turns evaluate Auto as Accept edits. A run's original snapshot+remains authoritative even when its source file changes.diff --git a/docs/spec/03-runtime/06-host-rpc-protocol.md b/docs/spec/03-runtime/06-host-rpc-protocol.mdindex aae69aac8..6a412d525 100644--- a/docs/spec/03-runtime/06-host-rpc-protocol.md+++ b/docs/spec/03-runtime/06-host-rpc-protocol.md@@ -1616,3 +1616,29 @@ Host limitation; other failures must not be silently converted into an emptylist. This additive protocol preserves the existing desktop RPC shapes.The supervisor gives an observed exit precedence over a pending stop and preserves that exit outcome while draining the pipes. Elapsed time freezes when the final state and output are published.+++## User-defined mode run RPC++ADR `mode-definitions` adds the following Host methods. Parameters use camelCase.++| Method | Parameters | Result |+| --- | --- | --- |+| `modes.get` | `sessionId` | `{ run }`, null when no open run exists |+| `modes.start` | `sessionId, input, turnId` | `{ claimed, run, enteredStage, definition }` |+| `modes.claimTurn` | `sessionId, runId, expectedRevision, turnId, origin` | claim result; origins: user, approval, host |+| `modes.completeStage` | `sessionId, runId, turnId, summary, artifacts?` | failed, run, awaiting_approval, advanced, goto, blocked or finished outcome |+| `modes.gateResult` | `sessionId, runId, turnId, gateIndex, toolCallId` | next stage outcome |+| `modes.settleTurn` | `sessionId, runId, turnId, tokens, outcome, error?` | `{ run, continue }` |+| `modes.control` | `sessionId, runId, expectedRevision, action` | `{ run, continue }`; pause, resume or stop |+| `modes.resolve` | `sessionId, runId, expectedRevision, action` | `{ run, continue }`; approve or reject |++`session.configure` accepts an optional validated `modeSnapshot`. Custom mode+ids require a snapshot. Agent and Plan retain their builtin policies. Host+notifications use `modes.changed { sessionId, run }`. Renderer catalog editing+uses the `pi-desktop/modes/*` IPC channels and never writes SQLite directly.++`tools.execute` accepts `modeGate { runId, gateIndex }` only for the exact+pending Bash gate command. The Host records the exit code; a model-supplied+verdict cannot pass a command gate. Stage completion may write only declared+artifacts within the workspace. Staged runs reject remote workspaces.diff --git a/docs/spec/06-delivery/04-e2e-test-plan.md b/docs/spec/06-delivery/04-e2e-test-plan.mdindex 56e01f62e..7599c5539 100644--- a/docs/spec/06-delivery/04-e2e-test-plan.md+++ b/docs/spec/06-delivery/04-e2e-test-plan.md@@ -20381,3 +20381,27 @@ Bounded tail pages include compactions appended after the last message. Middle p#### E2E-ISSUE-2164While a checkpoint estimate supplies context occupancy, use its recorded provider/model capacity, or the current exact session binding for legacy checkpoints. Keep historical request usage unchanged. Unknown capacity is marked approximate. Verify 20,619 / 1,000,000 = 2%, unknown routes, legacy records and usage after a newer request with `compaction-context-usage.test.mjs`.+++## User-defined mode workflow acceptance++Candidate command: `PI_DESKTOP_HOST_BIN=<candidate-host> node scripts/e2e-mode-definitions.mjs`+with `PI_SCRATCH_DIR` set to an isolated test directory. No model API is called.++1. Configure a session with a two-stage definition snapshot. Start a durable+ turn and claim the first contract stage.+2. Request completion without its required artifact; observe a failed gate.+3. Supply the artifact through stage completion; verify its exact disk content+ and the waiting-for-approval state.+4. Settle the first turn, approve with the current revision and claim the next+ stage with approval provenance.+5. Submit the stage's command gate. A changed command must fail with+ `MODE_GATE_MISMATCH` before execution.+6. Execute the exact command through `tools.execute`; consume the Host-recorded+ result and observe finished, no open run, and session mode Agent.++Companion tests: `mode_runs::*` and `rpc::modes_rpc::tests::*` cover migration,+recovery, CAS, budget and permission caps; desktop `mode-definitions-user-path`,+`mode-definitions-renderer` and `mode-runs-main` cover source editing, selection,+run controls and Main dispatch. Runtime `modes/*` covers stage completion and+compaction injection.diff --git a/packages/agent-runtime/src/modes/complete-stage-tool.test.ts b/packages/agent-runtime/src/modes/complete-stage-tool.test.tsindex a9c14716b..f3393bdfc 100644--- a/packages/agent-runtime/src/modes/complete-stage-tool.test.ts+++ b/packages/agent-runtime/src/modes/complete-stage-tool.test.ts@@ -77,7 +77,7 @@ describe("CompleteStage", () => {const { tool, endTurn } = harness({"modes.completeStage": [{ status: "failed", gateIndex: 0, message: "missing heading Evidence", retriesLeft: 2, run: RUN }],});- const result = await tool.execute("call-1", { summary: "Done" }) as { isError?: boolean; terminate?: boolean; content: never };+ const result = await tool.execute("call-1", { summary: "Done" }) as { isError?: boolean; terminate?: boolean; content: Array<{ type: string; text?: string }> };expect(text(result)).toContain("Exit check 1 failed: missing heading Evidence");expect(text(result)).toContain("2 retries left");@@ -94,7 +94,7 @@ describe("CompleteStage", () => {{ status: "advanced", nextStageId: "review", run: RUN },],});- const result = await tool.execute("model-call", { summary: "Done" }) as { terminate?: boolean; content: never };+ const result = await tool.execute("model-call", { summary: "Done" }) as { terminate?: boolean; content: Array<{ type: string; text?: string }> };expect(gates.map((gate) => [gate.command, gate.modeGate, gate.timeoutSeconds])).toEqual([["npm test", { runId: "run-1", gateIndex: 0 }, 300],@@ -116,7 +116,7 @@ describe("CompleteStage", () => {"modes.completeStage": [{ status: "run", gateIndex: 0, command: "npm test", timeoutMinutes: 5, run: RUN }],"modes.gateResult": [{ status: "failed", gateIndex: 0, message: "exit code 1: 2 tests failed", retriesLeft: 1, run: RUN }],}, { gate: async () => ({ isError: true, text: "2 tests failed" }) });- const result = await tool.execute("call-1", { summary: "Done" }) as { isError?: boolean; content: never };+ const result = await tool.execute("call-1", { summary: "Done" }) as { isError?: boolean; content: Array<{ type: string; text?: string }> };expect(text(result)).toContain("exit code 1: 2 tests failed");expect(text(result)).toContain("1 retry left");@@ -132,7 +132,7 @@ describe("CompleteStage", () => {[{ status: "finished", run: RUN }, "the run is finished"],])("ends the turn gracefully on %o", async (outcome, fragment) => {const { tool, endTurn } = harness({ "modes.completeStage": [outcome] });- const result = await tool.execute("call-1", { summary: "Done" }) as { isError?: boolean; terminate?: boolean; content: never };+ const result = await tool.execute("call-1", { summary: "Done" }) as { isError?: boolean; terminate?: boolean; content: Array<{ type: string; text?: string }> };expect(text(result)).toContain(fragment);expect(text(result)).toContain("this turn ends now");@@ -143,7 +143,7 @@ describe("CompleteStage", () => {it("refuses without a run claim and never calls the Host", async () => {const { host, tool } = harness({}, { claimed: false });- const result = await tool.execute("call-1", { summary: "Done" }) as { isError?: boolean; content: never };+ const result = await tool.execute("call-1", { summary: "Done" }) as { isError?: boolean; content: Array<{ type: string; text?: string }> };expect(result.isError).toBe(true);expect(text(result)).toContain("only in a turn of an active mode run");expect(host.call).not.toHaveBeenCalled();@@ -152,7 +152,7 @@ describe("CompleteStage", () => {it("ends the turn when the Host says the claim is gone", async () => {const lost = Object.assign(new Error("claim mismatch"), { data: { errorCode: "MODE_CLAIM_MISMATCH" } });const { tool, endTurn } = harness({ "modes.completeStage": [lost] });- const result = await tool.execute("call-1", { summary: "Done" }) as { terminate?: boolean; content: never };+ const result = await tool.execute("call-1", { summary: "Done" }) as { terminate?: boolean; content: Array<{ type: string; text?: string }> };expect(text(result)).toContain("MODE_CLAIM_MISMATCH");expect(result.terminate).toBe(true);expect(endTurn).toHaveBeenCalledTimes(1);@@ -163,7 +163,7 @@ describe("CompleteStage", () => {"modes.completeStage": [{ status: "run", gateIndex: 0, command: "npm test", timeoutMinutes: 5, run: RUN }],"modes.gateResult": [{ status: "run", gateIndex: 0, command: "npm test", timeoutMinutes: 5, run: RUN }],});- const result = await tool.execute("call-1", { summary: "Done" }) as { isError?: boolean; content: never };+ const result = await tool.execute("call-1", { summary: "Done" }) as { isError?: boolean; content: Array<{ type: string; text?: string }> };expect(gates).toHaveLength(1);expect(result.isError).toBe(true);expect(text(result)).toContain("MODE_OUTCOME_INVALID");diff --git a/scripts/e2e-mode-definitions.mjs b/scripts/e2e-mode-definitions.mjsnew file mode 100644index 000000000..574de861a--- /dev/null+++ b/scripts/e2e-mode-definitions.mjs@@ -0,0 +1,74 @@+#!/usr/bin/env node+/** Offline staged-mode acceptance against a real isolated Host process. */+import assert from "node:assert/strict";+import { mkdir, readFile } from "node:fs/promises";+import { join } from "node:path";+import { resolveHostBinary } from "./e2e/host.mjs";+import { withScenario } from "./e2e/fixture.mjs";+import { beginTurn, createSession, endTurn } from "./e2e/session.mjs";++const root = process.env.PI_SCRATCH_DIR;+assert.ok(root, "PI_SCRATCH_DIR is required for isolated test state");+const temp = join(root, "mode-e2e");+await mkdir(temp, { recursive: true });+await withScenario("mode-workflow", async ({ host, workspace }) => {+ const session = await createSession(host, workspace, "Mode acceptance");+ const sessionId = session.id;+ const definition = {+ version: 1, id: "acceptance", label: "Acceptance", description: "Offline test",+ source: "user", permission: "agent", prompt: "Verify the requested change.",+ artifacts: [{ id: "spec", path: ".pi/runs/{{run.id}}/spec.md", requiredHeadings: ["Goal", "Evidence"] }],+ budget: { maxTurns: 20, maxTokens: null }, returnTo: "agent",+ stages: [+ { id: "draft", permission: "contract", prompt: "Draft the spec.", loop: false,+ onEnter: [], onCompaction: [], next: "verify",+ exit: [{ kind: "require", artifact: "spec", onFail: { retries: 2 } }, { kind: "ask" }] },+ { id: "verify", permission: "agent", prompt: "Verify.", loop: true,+ onEnter: [], onCompaction: [],+ exit: [{ kind: "run", command: "echo mode-gate-ok", timeoutMinutes: 1, onFail: { retries: 0 } }] },+ ],+ };+ await host.call("session.configure", { id: sessionId, mode: definition.id, modeSnapshot: definition, permissionMode: "auto" });+ const turnId = await beginTurn(host, sessionId);+ const claim = await host.call("modes.start", { sessionId, turnId, input: "Produce and verify a spec" });+ assert.equal(claim.claimed, true);+ const runId = claim.run.id;+ const failed = await host.call("modes.completeStage", { sessionId, runId, turnId, summary: "Not ready" });+ assert.equal(failed.status, "failed");+ const markdown = "# Goal\nProduce a spec.\n# Evidence\nValidated offline.\n";+ const approval = await host.call("modes.completeStage", { sessionId, runId, turnId, summary: "Ready", artifacts: { spec: markdown } });+ assert.equal(approval.status, "awaiting_approval");+ assert.equal(await readFile(join(workspace, claim.run.artifactPaths.spec), "utf8"), markdown);+ await endTurn(host, turnId);+ const settled = await host.call("modes.settleTurn", { sessionId, runId, turnId, tokens: 12, outcome: "completed" });+ assert.equal(settled.continue, false);+ const resolved = await host.call("modes.resolve", { sessionId, runId, expectedRevision: settled.run.revision, action: "approve" });+ assert.equal(resolved.continue, true);+ const secondTurn = await beginTurn(host, sessionId);+ const secondClaim = await host.call("modes.claimTurn", {+ sessionId, runId, expectedRevision: resolved.run.revision, turnId: secondTurn, origin: "approval",+ });+ assert.equal(secondClaim.run.stageId, "verify");+ const gate = await host.call("modes.completeStage", { sessionId, runId, turnId: secondTurn, summary: "Verify" });+ assert.equal(gate.status, "run");+ const shell = (await host.call("commandShells.list")).effective;+ const toolCallId = "mode-verify-command";+ await assert.rejects(host.call("tools.execute", {+ sessionId, turnId: secondTurn, toolCallId: "wrong-command", toolName: "Bash", mode: "agent",+ args: { command: "echo wrong" }, modeGate: { runId, gateIndex: gate.gateIndex },+ expectedCommandShellId: shell.id, expectedCommandShellDialect: shell.dialect,+ }), (error) => error.errorCode === "MODE_GATE_MISMATCH");+ const executed = await host.call("tools.execute", {+ sessionId, turnId: secondTurn, toolCallId, toolName: "Bash", mode: "agent",+ args: { command: gate.command }, modeGate: { runId, gateIndex: gate.gateIndex },+ expectedCommandShellId: shell.id, expectedCommandShellDialect: shell.dialect,+ });+ assert.equal(executed.ok, true);+ const finished = await host.call("modes.gateResult", { sessionId, runId, turnId: secondTurn, gateIndex: gate.gateIndex, toolCallId });+ assert.equal(finished.status, "finished");+ await endTurn(host, secondTurn);+ await host.call("modes.settleTurn", { sessionId, runId, turnId: secondTurn, tokens: 3, outcome: "completed" });+ assert.equal((await host.call("session.get", { id: sessionId, messageLimit: 1 })).session.mode, "agent");+ assert.equal((await host.call("modes.get", { sessionId })).run, null);+ console.log("PASS mode snapshot -> artifact checks -> approval -> command gate -> completion -> Agent");+}, resolveHostBinary(), temp);