Skip to content

armgit / avibe

Public Imported from GitHub
0

Make your computer a home for your AI partner. Avibe is the local-first Agent OS: Vibey, its built-in AI partner, works out of the box, and Claude Code, Codex & OpenCode run unchanged beside it — reach them from your browser, phone, or any chat app.

docs(harness): plan agent run architecture

cyh1c4894f55296
diff --git a/docs/plans/agent-harness-cli.md b/docs/plans/agent-harness-cli.md
deleted file mode 100644
index 9f026977a..000000000
--- a/docs/plans/agent-harness-cli.md
+++ /dev/null
@@ -1,256 +0,0 @@
-# Agent Harness CLI
-
-## Background
-
-Vibe Remote already exposes three harness-style primitives:
-
-- `vibe task ...`: persist a scheduled turn definition and execute it later
-- `vibe hook send ...`: queue one async turn into an existing Vibe session
-- `vibe watch ...`: run a waiter process and enqueue hooks when events happen
-
-These commands already form a usable local automation surface, but they are still
-session-oriented. They do not provide a first-class way for one backend agent to
-invoke another backend agent directly through Vibe Remote.
-
-The new goal is to make `vibe` itself the agent-native harness surface, so an
-agent can discover callable backends/subagents and invoke them directly through a
-stable CLI instead of relying on injected ad-hoc shell scripts or a separate MCP
-layer.
-
-## Current Execution Model
-
-### Existing commands
-
-- `task` persists a definition in `scheduled_tasks.json`
-- `task run` and `hook send` enqueue one request under `~/.vibe_remote/state/task_requests/`
-- `watch` persists watcher definitions in `watches.json`
-- `watch` completion and terminal failures enqueue `hook_send` requests
-- `ScheduledTaskService` drains queued requests and routes them into
- `message_handler.handle_scheduled_message(...)`
-
-### Important distinction
-
-`hook` is not a generic agent invocation API.
-
-Its real semantic meaning today is:
-
-- continue an existing Vibe session
-- inject one async prompt into that session
-- preserve the same scheduled-turn/session alias behavior as `task`
-
-This is different from direct agent invocation, whose semantic center is the
-target backend/agent rather than the destination session key.
-
-## Goals
-
-- Add a first-class `vibe agent` CLI surface.
-- Let any running backend agent discover callable agents across supported
- backends.
-- Let any running backend agent invoke another backend agent or subagent through
- a stable non-interactive CLI.
-- Keep `vibe` as the single harness interface for humans, scripts, and agents.
-- Preserve the existing `task` / `watch` / `hook` semantics unless we have a
- strong migration reason.
-
-## Non-Goals For V1
-
-- Do not merge `hook` into `agent` at the command surface yet.
-- Do not redesign the whole scheduled-turn pipeline.
-- Do not introduce a separate MCP-only invocation layer.
-- Do not solve multi-step orchestration, recursion control, or long-lived agent
- workflows in the first implementation.
-
-## Proposed V1 Command Surface
-
-### `vibe agent list`
-
-Purpose:
-
-- list callable agents visible from the current cwd
-
-Expected scope:
-
-- backend default agents
-- backend subagents
-- project-local definitions
-- global definitions when relevant
-
-Initial flags:
-
-- `--cwd <path>`
-- `--json`
-
-### `vibe agent run`
-
-Purpose:
-
-- invoke one target backend/agent directly and return its result
-
-Initial flags:
-
-- `--backend <opencode|claude|codex>`
-- `--agent <name>`
-- `--prompt <text>` or `--prompt-file <path>`
-- `--cwd <path>`
-- `--timeout <seconds>`
-- `--json`
-
-V1 intentionally excludes:
-
-- `--session-key`
-- `--post-to`
-- `--deliver-key`
-- detached async execution
-- stored invocation definitions
-- recursive orchestration policy
-
-## Why `hook` And `agent` Stay Separate In V1
-
-### `hook`
-
-Primary identity:
-
-- session-oriented
-
-Core question it answers:
-
-- which existing Vibe conversation/session should receive one async turn?
-
-Primary inputs:
-
-- `session_key`
-- optional delivery override
-- prompt
-
-### `agent`
-
-Primary identity:
-
-- agent-oriented
-
-Core question it answers:
-
-- which backend/agent should execute this work?
-
-Primary inputs:
-
-- backend
-- agent name
-- cwd
-- prompt
-
-If `agent run` also accepts `session_key` and delivery semantics in V1, the user
-and the calling agent will no longer have a clean mental model of whether the
-command means direct invocation or async session injection.
-
-## Likely Internal Direction
-
-Even if the CLI stays separate, the internal model should probably converge on a
-shared invocation abstraction later.
-
-Possible internal invocation kinds:
-
-- `session_turn`
-- `agent_run`
-
-This would let Vibe Remote keep clean external commands while still reusing queue,
-execution, receipts, policies, and observability internally.
-
-## Open Questions To Resolve Before Implementation
-
-### 1. Target identity
-
-- Should `--agent default` mean the backend's default top-level agent?
-- Or should the default top-level agent be represented with an empty agent name
- and only subagents appear in `list`?
-- Should `agent list` show both `backend` and `kind` (`default` vs `subagent`)?
-
-### 2. Execution model
-
-- Should `agent run` always be one-shot and stateless in V1?
-- Or should it optionally reuse backend-native sessions when possible?
-- If session reuse is allowed later, is that a separate flag or a separate
- command family?
-
-### 3. Output contract
-
-- Should `agent run --json` return only the final textual result?
-- Or should it also return structured fields like:
- - resolved backend
- - resolved agent
- - cwd
- - duration
- - exit status
- - files/artifacts
- - raw stderr / diagnostic summary
-- Should non-JSON mode be human-readable only, with JSON mode treated as the
- stable machine contract?
-
-### 4. Failure contract
-
-- What should count as command failure vs agent-level failure?
-- If the target agent ran successfully but returned an error message, should the
- CLI exit non-zero or still return `ok: true` with an agent error payload?
-
-### 5. Backend coverage
-
-- Must V1 support OpenCode, Claude, and Codex equally on day one?
-- Or is it acceptable to ship one backend first if the command contract is
- already backend-neutral?
-
-### 6. Discovery scope
-
-- Should `agent list` include only agents that are currently enabled in Vibe
- config?
-- Or should it include all discovered definitions and annotate whether each one
- is runnable right now?
-
-### 7. Prompt layering
-
-- When invoking a target subagent, what prompt layers apply?
-- Expected candidates:
- - explicit `--prompt`
- - target subagent instructions
- - project `AGENTS.md` / `CLAUDE.md`
- - backend-native defaults
-- Do we want `vibe agent run` to mimic the backend's normal behavior as closely
- as possible, or establish a Vibe-owned wrapper prompt?
-
-### 8. Working directory semantics
-
-- Should `--cwd` be required or optional?
-- If omitted, should it default to the current shell cwd, Vibe runtime default
- cwd, or the caller's current conversation cwd when invoked from inside Vibe?
-
-### 9. Recursion policy
-
-- Can an agent invoked through `vibe agent run` call `vibe agent run` again?
-- If yes, what depth limit or loop protection is required?
-- If no, how will the command communicate that restriction?
-
-### 10. Relationship to existing harness primitives
-
-- Should `task` and `watch` remain session-turn producers only in V1?
-- Or do we want a near-term follow-up where they can trigger `agent_run`
- invocations instead of only `hook`-style session turns?
-
-## Recommended V1 Decisions
-
-- Keep `hook` unchanged as the async session-turn primitive.
-- Ship `agent list` and `agent run` as a separate command family.
-- Keep V1 synchronous and one-shot.
-- Make `--json` the stable machine interface.
-- Avoid session/delivery flags on `agent run` until the direct invocation model
- is proven.
-
-## Todo
-
-1. Resolve the open questions above.
-2. Finalize the V1 command contract and JSON schema.
-3. Design the internal backend-neutral invocation interface.
-4. Decide whether V1 executes inline in the CLI process or reuses a local Vibe
- runtime service path.
-5. Implement `vibe agent list`.
-6. Implement `vibe agent run`.
-7. Add tests for discovery, invocation, JSON output, and failure behavior.
-8. Update CLI docs and injected prompt guidance.
diff --git a/docs/plans/agent-run-harness.md b/docs/plans/agent-run-harness.md
new file mode 100644
index 000000000..78cd33503
--- /dev/null
+++ b/docs/plans/agent-run-harness.md
@@ -0,0 +1,857 @@
+# Agent Run Harness
+
+## Background
+
+Vibe Remote needs three user-facing automation surfaces:
+
+- manual/external Agent execution;
+- scheduled execution;
+- watched/condition-triggered execution.
+
+These are different product entry points, but they should share the same
+execution schema, status model, history, and management logic.
+
+The old `vibe hook send` command is better understood as "enqueue one Agent
+Run" rather than as a separate product concept. This plan replaces hook with an
+Agent Run harness.
+
+## Product Model
+
+```text
+Agent Run = execute one Agent job.
+Task = a time trigger that creates Agent Runs.
+Watch = a condition trigger that creates Agent Runs.
+```
+
+This gives the Web UI a clean shape:
+
+- Agent Runs tab: runs created by CLI, webhook, manual action, or API.
+- Scheduled Tasks tab: time-based trigger definitions.
+- Watches tab: waiter/monitor trigger definitions.
+
+The shared primitive is the run record, not the task.
+
+## Goals
+
+- Replace `vibe hook send` with `vibe agent run`.
+- Use `--message` / `--message-file`, not `--prompt`, for Agent Run user message.
+- Support synchronous and asynchronous Agent Runs.
+- Support running inside an existing `session_id`.
+- Support creating a new session and returning the reserved Session ID.
+- Let Agent Run, Task, and Watch all accept `--agent <name>` as the command-level
+ Vibe Agent selector.
+- Let tasks and watches reuse the same run spec and run history.
+- Prepare for webhook-triggered Agent Runs.
+
+## CLI Design
+
+### `vibe agent run`
+
+Synchronous Agent Run:
+
+```bash
+vibe agent run --agent release-reviewer --message "Review this diff."
+```
+
+Asynchronous Agent Run:
+
+```bash
+vibe agent run --agent release-reviewer --async --message-file request.md
+```
+
+Continue an existing session:
+
+```bash
+vibe agent run --session-id sesk8m4q2p7x --message "Continue the investigation."
+```
+
+Create a new session and deliver to a scope:
+
+```bash
+vibe agent run \
+ --create-session \
+ --deliver-key slack::channel::C123 \
+ --message "Start a fresh incident triage."
+```
+
+Rules:
+
+- Use `--message` and `--message-file` for the user/task message.
+- `--prompt` / `--prompt-file` are deprecated compatibility inputs. If a user
+ passes them, reject the command with a clear message that points to
+ `--message` / `--message-file`.
+- Exactly one message source is required.
+- `--session-id` continues a conversation by public Vibe Session ID.
+- `--create-session` reserves a new Vibe Session ID. With `--deliver-key`, the
+ session also has a delivery Scope; without `--deliver-key`, a direct Agent Run
+ creates a private/no-delivery session for agent harness or sub-agent usage and
+ requires explicit `--agent`, then returns `session_id` for later continuation.
+- `--agent <name>` selects the Vibe Agent for this run. If omitted, resolve the
+ Agent from the session or delivery Scope defaults.
+- `--deliver-key <scope-id>` sends the result to an IM scope.
+- `--async` returns after the run is queued.
+- Without `--async`, the command waits for completion and prints the result.
+
+Optional execution controls:
+
+- `--cwd <path>` can override the working directory for this run. If omitted,
+ use the scope/session workdir when a scope/session is present; otherwise use
+ the caller's shell cwd.
+- `--wait-timeout <seconds>` controls how long a synchronous command waits; it
+ does not terminate the run. There is no fixed default wait limit; if a
+ synchronous run exceeds 30 minutes, the CLI returns an accepted response and
+ the run continues asynchronously. The 30-minute threshold is a system
+ protection threshold, not a user-visible default timeout.
+- `--json` is the stable machine-readable contract. Non-JSON output is for
+ humans and may be more compact.
+
+### Deprecating `vibe hook send`
+
+Compatibility window:
+
+```bash
+vibe hook send ... -> vibe agent run --async ...
+```
+
+Rules:
+
+- Keep accepting the old command temporarily.
+- Return a deprecation warning.
+- Do not teach `vibe hook` in new prompt guidance or docs.
+
+### `vibe task`
+
+`vibe task` manages saved time triggers. It does not execute work directly; it
+creates or manages `run_definitions` rows with `definition_type=scheduled`.
+
+Create a recurring task:
+
+```bash
+vibe task add \
+ --cron "0 9 * * *" \
+ --agent release-reviewer \
+ --message "Prepare the daily release review."
+```
+
+Create a one-shot managed task:
+
+```bash
+vibe task add \
+ --at "2026-06-01T09:00:00+08:00" \
+ --create-session \
+ --deliver-key slack::channel::C123 \
+ --message-file request.md
+```
+
+Manage a task:
+
+```bash
+vibe task list
+vibe task show <task-id>
+vibe task update <task-id> --cron "*/30 * * * *"
+vibe task run <task-id>
+vibe task pause <task-id>
+vibe task resume <task-id>
+vibe task remove <task-id>
+```
+
+Rules:
+
+- Exactly one schedule source is required: `--cron` or `--at`.
+- Exactly one message source is required: `--message` or `--message-file`.
+- `--agent <name>` selects the Vibe Agent stored in this task definition.
+- If `--agent` is omitted, resolve the Agent from the target Scope/session when
+ the task is created.
+- `task update <id> --agent <name>` changes future runs of that task; historical
+ `agent_runs` keep their captured run spec.
+- Existing `--prompt` / `--prompt-file` should be recognized only to return a
+ deprecation error that points to `--message` / `--message-file`.
+- `--create-session-per-run` is valid for recurring tasks and rejected for
+ `--at` one-shot tasks.
+- `task run <id>` creates an immediate `agent_runs` row from the saved
+ definition; it does not mutate the schedule.
+- `pause` disables future scheduled firing without deleting history.
+- `remove` soft-deletes the definition.
+
+### `vibe watch`
+
+`vibe watch` manages saved condition triggers. A watch runs a waiter command,
+observes its terminal state, and creates an Agent Run when there is something to
+report.
+
+Create a one-shot watch:
+
+```bash
+vibe watch add \
+ --agent release-reviewer \
+ --message "The export finished. Summarize the result." \
+ -- python3 scripts/wait_for_export.py
+```
+
+Create a long-running watch:
+
+```bash
+vibe watch add \
+ --forever \
+ --retry-exit-code 75 \
+ --retry-delay 60 \
+ --create-session-per-run \
+ --deliver-key slack::channel::C123 \
+ --message "A CI event finished. Review the waiter output." \
+ -- python3 scripts/wait_for_ci.py
+```
+
+Manage a watch:
+
+```bash
+vibe watch list
+vibe watch show <watch-id>
+vibe watch pause <watch-id>
+vibe watch resume <watch-id>
+vibe watch remove <watch-id>
+```
+
+Rules:
+
+- Watch definitions live in `run_definitions` with `definition_type=watch`.
+- The waiter command is part of the trigger configuration.
+- `--agent <name>` selects the Vibe Agent stored in this watch definition.
+- If `--agent` is omitted, resolve the Agent from the target Scope/session when
+ the watch is created.
+- `--message` / `--message-file` is the instruction template for the Agent Run that
+ is created after the waiter reaches a reportable state.
+- Existing `--prefix` can remain as a compatibility alias for prepending an
+ instruction before waiter stdout, but the target schema should store this as
+ `message.text` plus structured waiter output.
+- `--forever` watches continue running until paused, removed, lifetime timeout,
+ or a non-retryable terminal failure.
+- Watch runtime process state may continue to use `run_type=watch_runtime`, but
+ user-visible follow-up executions should use `run_type=watch`.
+
+### One-Off Agent Run vs One-Off Task
+
+`vibe agent run --async` and `vibe task add --at ...` can both execute once, but
+they answer different product needs:
+
+- Agent Run: execute now; no saved definition; managed through run history.
+- One-shot Task: execute later; saved definition; can be listed, shown,
+ updated, paused, resumed, removed, or manually run before its scheduled time.
+
+## RunSpec
+
+All immediate runs, scheduled tasks, watches, and future webhook triggers should
+share a common run spec.
+
+```text
+RunSpec
+ agent_target:
+ mode: named_agent | session
+ agent_name
+ session_id
+ session_target:
+ mode: none | existing | create_once | create_per_run
+ session_id
+ scope_id
+ delivery_target:
+ mode: none | scope | post_to
+ scope_id
+ post_to
+ message:
+ text
+ payload_json
+ execution:
+ mode: sync | async
+```
+
+Notes:
+
+- `message.text` is user/task message, not system prompt.
+- Agent system prompt comes from the Vibe Agent catalog.
+- `payload_json` is reserved for webhook/API structured input.
+- `create_per_run` belongs to trigger definitions, not one-off direct runs.
+
+## Session And Delivery Targeting
+
+Background commands must keep three identities separate:
+
+- Agent Session: the Vibe session to continue or create.
+- Delivery Scope: the IM scope where output should be delivered.
+- Agent Definition: the Vibe Agent that supplies backend/model/effort/prompt.
+
+### Scope ID
+
+`--deliver-key` should mean `scopes.id`. It is not a session key.
+
+Example shape:
+
+```text
+<platform>::<scope_type>::<native_id>
+```
+
+Examples:
+
+```text
+slack::channel::C123
+slack::user::U123
+lark::channel::oc_...
+```
+
+No separate thread anchor parameter is needed. If thread becomes a first-class
+Scope later, the same `--deliver-key <scope-id>` mechanism covers it.
+
+### Session Policies
+
+Existing session:
+
+```bash
+--session-id <agent-session-id>
+```
+
+Create one reusable session:
+
+```bash
+--create-session --deliver-key <scope-id>
+```
+
+Create a fresh session for every trigger execution:
+
+```bash
+--create-session-per-run --deliver-key <scope-id>
+```
+
+Rules:
+
+- `--session-id`, `--create-session`, and `--create-session-per-run` are
+ mutually exclusive.
+- `vibe agent run --create-session` may omit `--deliver-key` to create a
+ private/no-delivery Session, but it must explicitly pass `--agent`. Managed
+ task/watch definitions that use `--create-session` or `--create-session-per-run`
+ require `--deliver-key`.
+- `--create-session` reserves a Vibe Session ID immediately. Runtime binds
+ backend-native state on the first execution.
+- `--create-session-per-run` stores a policy on `run_definitions`; every
+ execution creates a new Vibe Session ID and records it on the corresponding
+ `agent_runs` row.
+- Reject `--create-session-per-run` for one-shot `task add --at`, because it is
+ equivalent to `--create-session` but less clear.
+- Immediate `vibe agent run` only needs `--create-session`; per-run has no
+ separate meaning for a single direct run.
+
+### Parameter Mutual-Exclusion Matrix
+
+| Parameter combination | `vibe agent run` | `vibe task add/update` | `vibe watch add` | Rule |
+| --- | --- | --- | --- | --- |
+| `--message` + `--message-file` | Reject | Reject | Reject | Each definition or execution has exactly one message source. |
+| `--prompt` / `--prompt-file` + any message parameter | Reject | Reject | Reject | Legacy parameters only produce deprecated guidance. |
+| `--session-id` + `--create-session` | Reject | Reject | Reject | A run has one Session policy. |
+| `--session-id` + `--create-session-per-run` | Reject | Reject | Reject | `existing` conflicts with `create_per_run`. |
+| `--create-session` + `--create-session-per-run` | Reject | Reject | Reject | `create_once` conflicts with `create_per_run`. |
+| `--create-session` without `--deliver-key` | Allow only with `--agent` | Reject | Reject | Direct Agent Runs may create private/no-delivery Sessions, but the Agent must be explicit; managed definitions need a Scope when creating Sessions. |
+| `--create-session-per-run` without `--deliver-key` | N/A | Reject | Reject | Every per-run Session needs a Scope. |
+| `--create-session-per-run` + `task add --at` | N/A | Reject | N/A | One-shot tasks run once; use `--create-session`. |
+| `--deliver-key` + `--post-to` | Reject | Reject | Reject | One is an explicit Scope; the other is a shortcut. |
+| `--agent` + `--session-id` | Allow if backend matches | Allow if backend matches | Allow if backend matches | `--agent` only overrides this run/definition and does not mutate the Session; reject if Agent backend differs from Session backend. |
+| `--agent` + `--deliver-key` | Allow | Allow | Allow | `--agent` overrides the Scope default Agent; `--deliver-key` controls delivery. |
+| `--async` + `--wait-timeout` | Reject | N/A | N/A | `--wait-timeout` only controls synchronous CLI waiting and does not control async run lifetime. |
+
+### Delivery Policies
+
+For newly created sessions that should deliver to IM,
+`--deliver-key <scope-id>` is required because the CLI cannot infer an IM
+context safely. Direct `vibe agent run --create-session` without `--deliver-key`
+does not deliver to IM; it returns run/session output only.
+
+For existing sessions:
+
+- default delivery comes from the session;
+- `--post-to thread|channel` remains a convenience shortcut;
+- `--deliver-key <scope-id>` is the explicit delivery override;
+- `--post-to` and `--deliver-key` are mutually exclusive.
+
+### Runtime Target Resolution
+
+Background commands should not accept backend/model/effort override flags.
+Runtime target resolution is:
+
+1. If `--agent <name>` is provided, load that Vibe Agent.
+2. Otherwise, if `--session-id` is provided, use the session's current Agent
+ identity.
+3. Otherwise, resolve `--deliver-key` to a Scope and load the Scope's selected
+ Vibe Agent.
+4. If no Scope Agent exists, use the configured system default Agent.
+5. If both `--agent` and `--session-id` are provided, verify that the Agent
+ backend matches the Session backend; reject on mismatch because cross-backend
+ continuation cannot preserve context.
+6. Use the resolved Agent backend/model/effort/system prompt.
+7. Use the Scope/session workdir unless overridden by `--cwd` for this run.
+
+This makes `--agent` a command-level override of the Scope default Agent, not a
+backend/model/effort override. When combined with `--session-id`, it only affects
+the current run and does not mutate the Session's future default Agent.
+
+## Storage Model
+
+Rename and evolve the existing two background tables:
+
+- `background_tasks` -> `run_definitions`: definition table for reusable
+ managed triggers.
+- `background_runs` -> `agent_runs`: execution table for every actual run.
+
+### `run_definitions`: Definitions
+
+`run_definitions` stores definitions that may create runs later. It is the
+unified definition table for tasks, watches, and future webhooks.
+
+Recommended `definition_type` values:
+
+- `scheduled`: cron or one-shot scheduled task;
+- `watch`: managed waiter that produces a follow-up run when it reaches a
+ terminal condition;
+- `webhook`: future external trigger definition.
+
+Immediate `vibe agent run` does not create a `run_definitions` row. It creates
+a `agent_runs` row directly.
+
+Core definition semantics should be stored as first-class columns. Field
+details:
+
+| Field | Status | Definition | Design intent |
+| --- | --- | --- | --- |
+| `id` | Existing | Definition ID. | Stable management handle for task/watch/webhook definitions. |
+| `definition_type` | Existing field renamed, extended values | Definition type: `scheduled`, `watch`, or future `webhook`. | Rename from `task_type` so watch/webhook definitions are not called tasks. |
+| `name` | Existing | User-visible definition name. | Show readable names in CLI and Web UI. |
+| `agent_name` | New | Vibe Agent selected for future runs. | Make task/watch Agent selection explicit; if omitted, store the resolved Scope/session default. |
+| `session_policy` | New | `existing`, `create_once`, or `create_per_run`. | Persist the lifecycle semantics for Session reuse/creation. |
+| `session_id` | Existing | Existing or reserved Vibe Session ID when policy uses one. | Let future executions continue the same Vibe Session. |
+| `legacy_session_key` | Existing, compatibility | Legacy target from old records and commands. | Migration/display only; new writes prefer `session_id` / `deliver_key`. |
+| `deliver_key` | Existing, revised semantics | Delivery Scope ID. Domain/API name can be `delivery_scope_id` or `scope_id`. | Decouple delivery target from Session identity while keeping migration small. |
+| `post_to` | Existing | Delivery shortcut such as `thread` or `channel`. | Cover common delivery overrides without requiring full Scope IDs. |
+| `prompt` | Existing, compatibility | Legacy message template field. | Read/write compatibility during migration; target schema uses `message`. |
+| `message` | New | Stored Agent message template. | Align storage with `--message` and separate user message from Agent system prompt. |
+| `message_payload_json` | New | Optional structured message payload. | Support webhook/API structured input without overloading text. |
+| `schedule_type` | Existing | `cron` or `at`. | Distinguish recurring and one-shot schedules. |
+| `cron` | Existing | Cron expression. | Store recurring schedule. |
+| `run_at` | Existing | One-shot scheduled time. | Store one-time schedule. |
+| `timezone` | Existing | Schedule timezone. | Make schedule interpretation reproducible. |
+| `command_json` | Existing | Watch waiter argv. | Store structured command without shell quoting ambiguity. |
+| `shell_command` | Existing | Watch waiter shell command. | Support shell mode and legacy command shapes. |
+| `prefix` | Existing, compatibility | Legacy watch follow-up instruction prefix. | Keep `--prefix` compatibility; target semantics fold this into `message`. |
+| `cwd` | Existing | Watch/runtime working directory. | Background execution should not depend on service process cwd. |
+| `mode` | Existing | Watch mode such as `once` or `forever`. | Persist watch lifecycle. |
+| `timeout_seconds` | Existing | Per-run or per-cycle timeout. | Bound individual execution time. |
+| `lifetime_timeout_seconds` | Existing | Overall watch lifetime timeout. | Bound long-running watch lifetime. |
+| `retry_exit_codes_json` | Existing | Retryable waiter exit codes. | Distinguish keep-waiting from terminal failure. |
+| `retry_delay_seconds` | Existing | Retry delay for retryable waiters. | Control retry cadence for forever watches. |
+| `enabled` | Existing | Whether the definition may create future runs. | Support pause/resume without deleting history. |
+| `deleted_at` | Existing | Soft-delete timestamp. | Hide removed definitions while keeping historical runs. |
+| `created_at` | Existing | Creation time. | Audit and ordering. |
+| `updated_at` | Existing | Latest update time. | Management UI, sync, and debugging. |
+| `last_started_at` | Existing | Latest execution start time. | Fast list summary. |
+| `last_finished_at` | Existing | Latest execution finish time. | Fast completion summary. |
+| `last_event_at` | Existing | Latest watch event time. | Watch list summary. |
+| `last_run_at` | Existing | Latest scheduled trigger time. | Task list summary. |
+| `last_error` | Existing | Latest error summary. | Surface actionable failures in lists. |
+| `last_exit_code` | Existing | Latest waiter/process exit code. | Watch/debug summary. |
+| `last_run_id` | New | Latest user-visible run created by this definition. | Fast navigation between definition and run history. |
+| `metadata_json` | Existing, extension | Non-core extension data. | Store only non-queryable backend-specific metadata, UI hints, or experimental fields. |
+
+`metadata_json` remains available for non-core extension data only:
+
+- backend-specific import metadata;
+- UI display hints that do not affect execution;
+- webhook auth/source metadata that has no query requirement yet;
+- experimental fields before they graduate to columns.
+
+Implementation can migrate incrementally by keeping the existing `prompt` column
+as a compatibility alias for `message` until a schema migration renames or
+duplicates it.
+
+Definition table migration priority:
+
+1. Add `agent_name`, `session_policy`, `message`, `message_payload_json`, and
+ `last_run_id`.
+2. For new definitions, write the new columns and any required compatibility
+ columns such as `prompt`.
+3. When reading old definitions, derive `message` from `prompt` if `message` is
+ empty.
+4. After the compatibility window, decide whether to remove or hide legacy
+ semantic fields such as `prompt` and `prefix`.
+
+### `agent_runs`: Executions
+
+`agent_runs` stores every actual execution:
+
+- immediate `vibe agent run`;
+- async `vibe agent run --async`;
+- scheduled task fire;
+- watch terminal event/follow-up;
+- future webhook invocation.
+
+Recommended `run_type` values:
+
+- `agent_run`: direct agent invocation, usually with `definition_id = null`;
+- `scheduled`: execution created from a scheduled `run_definitions` row;
+- `watch`: execution created from a watch `run_definitions` row;
+- `webhook`: execution created from a webhook `run_definitions` row;
+- `watch_runtime`: legacy/runtime waiter bookkeeping if still needed.
+
+Target domain statuses:
+
+- `queued`;
+- `running`;
+- `succeeded`;
+- `failed`;
+- `canceled`.
+
+The storage layer can initially map these to existing values such as `pending`,
+`processing`, and `completed`; the public output schema should use the domain
+statuses above.
+
+Field details:
+
+| Field | Status | Definition | Design intent |
+| --- | --- | --- | --- |
+| `id` | Existing | Run ID. | Stable handle for show/list/cancel/history. |
+| `definition_id` | Existing field renamed | Optional source `run_definitions.id`. | Rename from `task_id` because the source is a generic definition, not only a task. |
+| `run_type` | Existing, extended values | `agent_run`, `scheduled`, `watch`, `webhook`, or runtime bookkeeping type. | Distinguish direct runs, task runs, watch follow-ups, and webhook invocations. |
+| `status` | Existing, normalized values | `queued`, `running`, `succeeded`, `failed`, `canceled`. | Shared status machine for CLI, Web UI, and agent harness callers. |
+| `source_kind` | New | `cli`, `api`, `scheduler`, `watch`, or `webhook`. | Record who created the run for audit and filtering. |
+| `source_actor` | New | Optional actor/user/system identifier. | Distinguish human, agent, scheduler, and external-system triggers. |
+| `parent_run_id` | New | Parent run ID. | Support harness/sub-agent call chains and recursion guards. |
+| `agent_name` | New | Vibe Agent captured for this run. | Make history auditable even if Agent definitions change later. |
+| `agent_id` | New | Optional Agent ID snapshot. | Preserve relation if display names ever change; nullable if name remains immutable. |
+| `agent_backend` | New | Backend snapshot. | Debug/history without joining the current Agent definition. |
+| `model` | New | Model snapshot. | Explain historical behavior after Agent model changes. |
+| `reasoning_effort` | New | Effort snapshot. | Explain historical behavior after Agent effort changes. |
+| `session_policy` | New | Session resolution policy used for this run. | Explain how `session_id` was obtained. |
+| `session_id` | Existing | Actual Vibe Session ID used by this run. | Continue conversation and query history by session. |
+| `legacy_session_key` | Existing, compatibility | Legacy target for old imported runs. | Migration/display only. |
+| `deliver_key` | Existing, revised semantics | Delivery Scope ID snapshot. | Audit delivery target and query runs by Scope. |
+| `post_to` | Existing | Delivery shortcut snapshot. | Preserve thread/channel shortcut semantics. |
+| `prompt` | Existing, compatibility | Legacy message field. | Read compatibility for old runs; target schema uses `message`. |
+| `message` | New | Actual message sent to the Agent. | Align with `--message` and separate user message from system prompt. |
+| `message_payload_json` | New | Optional structured payload. | Support webhook/API structured input. |
+| `result_text` | New | Final user-visible result when available. | Support sync run output, run show, and Web UI summaries. |
+| `result_payload_json` | New | Optional structured result. | Machine-readable result for API/webhook/harness use. |
+| `message_ids_json` | New | IM message IDs emitted by this run. | Delivery audit, thread association, and UI links. |
+| `cancel_requested` | New | Whether cancellation was requested. | Preserve real execution terminal state after best-effort cancel. |
+| `cancel_requested_at` | New | Cancellation request time. | Audit cancellation requests and worker response latency. |
+| `pid` | Existing | Runtime/watch process ID. | Runtime management and diagnostics. |
+| `exit_code` | Existing | Process exit code. | Diagnose watch/waiter or backend process failures. |
+| `error` | Existing | Error summary. | Surface failure reason in CLI/Web UI. |
+| `stdout` | Existing | Bounded stdout. | Preserve waiter/backend output summary. |
+| `stderr` | Existing | Bounded stderr. | Preserve diagnostic output. |
+| `created_at` | Existing | Run creation time. | Queue and history ordering. |
+| `started_at` | Existing | Execution start time. | Queue wait and duration calculations. |
+| `completed_at` | Existing | Execution completion time. | Duration and terminal-state checks. |
+| `updated_at` | Existing | Latest update time. | Worker polling and stale-running detection. |
+| `metadata_json` | Existing, extension | Non-core extension data. | Store only non-queryable backend-specific or experimental data. |
+
+For scheduled/watch/webhook runs, these columns are populated as a snapshot from
+the definition at run creation time. This keeps historical runs auditable even
+if the task, watch, or Agent definition changes later.
+
+`metadata_json` remains an extension field for non-queryable, backend-specific,
+or experimental data. It is not the storage location for core run semantics.
+
+Run table migration priority:
+
+1. Add `source_kind`, `source_actor`, `parent_run_id`, Agent snapshot fields,
+ `session_policy`, `message`, `message_payload_json`, result fields, and
+ emitted-message fields.
+2. For new runs, snapshot first-class columns from the definition or direct
+ command parameters.
+3. When reading old runs, derive `message` from `prompt` if `message` is empty;
+ if `result_text` is empty, continue deriving summaries from `stdout` /
+ `error`.
+4. Keep reading existing historical extension data from `metadata_json`, but do
+ not write new core semantics there.
+
+### Table Responsibilities
+
+- `run_definitions` owns definition lifecycle and trigger configuration.
+- `agent_runs` owns execution lifecycle, history, output, and errors.
+- One-off agent runs are executions without a saved definition.
+- Webhooks can be added as another definition type plus another run type.
+- Harness/sub-agent usage is represented by `parent_run_id` on runs.
+
+### Indexing Notes
+
+The current indexes already cover the common task/watch queries. The run table
+should also support:
+
+- worker polling: `(status, updated_at)` or `(status, created_at)`;
+- run history by type: `(run_type, status, created_at)`;
+- session history: `(session_id, created_at)`;
+- definition history: `(definition_id, created_at)`.
+
+Migration should rename the old `agent_runs.task_id` column to `definition_id`,
+or add `definition_id` first and backfill it from the old column. The database
+column should consistently be `definition_id`.
+
+## Relationship To Task And Watch
+
+### `vibe task`
+
+`vibe task` manages scheduled trigger definitions.
+
+```bash
+vibe task add --cron "0 9 * * *" --agent release-reviewer --message "Daily review"
+vibe task run <task-id>
+vibe task pause <task-id>
+```
+
+When the schedule fires, it creates a `agent_runs` row by snapshotting the
+task definition columns.
+
+### `vibe watch`
+
+`vibe watch` manages condition trigger definitions.
+
+```bash
+vibe watch add --agent release-reviewer --prefix "CI finished" -- python wait.py
+```
+
+When the waiter succeeds or reaches a terminal failure, it creates a
+`agent_runs` row.
+
+### `vibe agent run`
+
+`vibe agent run` creates a `agent_runs` row immediately. It does not create
+a `run_definitions` definition unless a future command explicitly asks to save
+one.
+
+## Output Contract
+
+JSON output should be the stable contract for agents and scripts.
+
+General rules:
+
+- Top-level output must include `schema_version`, `ok`, and `kind`.
+- `kind` identifies the returned object type, such as `agent_run`,
+ `run_definition`, or `agent_runs`.
+- Human output may be shorter, but `--json` output should be stable.
+
+Synchronous Agent Run success:
+
+```json
+{
+ "schema_version": 1,
+ "ok": true,
+ "kind": "agent_run",
+ "run": {
+ "id": "run123",
+ "status": "succeeded",
+ "session_id": "sesk8m4q2p7x",
+ "result_text": "..."
+ }
+}
+```
+
+Asynchronous Agent Run accepted, or a synchronous run converted to async after
+30 minutes:
+
+```json
+{
+ "schema_version": 1,
+ "ok": true,
+ "accepted": true,
+ "kind": "agent_run",
+ "run": {
+ "id": "run123",
+ "status": "queued",
+ "session_id": "sesnew12345"
+ }
+}
+```
+
+Task/Watch definition creation success:
+
+```json
+{
+ "schema_version": 1,
+ "ok": true,
+ "kind": "run_definition",
+ "definition": {
+ "id": "def123",
+ "definition_type": "scheduled",
+ "enabled": true,
+ "agent_name": "release-reviewer",
+ "session_policy": "create_once",
+ "session_id": "sesnew12345",
+ "deliver_key": "slack::channel::C123",
+ "next_run_at": "2026-06-01T09:00:00+08:00"
+ },
+ "warnings": []
+}
+```
+
+`vibe task run <id>` success:
+
+```json
+{
+ "schema_version": 1,
+ "ok": true,
+ "kind": "agent_run",
+ "definition": {
+ "id": "def123",
+ "definition_type": "scheduled"
+ },
+ "run": {
+ "id": "run123",
+ "status": "queued",
+ "definition_id": "def123",
+ "agent_name": "release-reviewer",
+ "session_id": "sesnew12345"
+ }
+}
+```
+
+`vibe runs show <id>`:
+
+```json
+{
+ "schema_version": 1,
+ "ok": true,
+ "kind": "agent_run",
+ "run": {
+ "id": "run123",
+ "run_type": "agent_run",
+ "status": "running",
+ "source_kind": "cli",
+ "agent_name": "release-reviewer",
+ "session_id": "sesnew12345",
+ "definition_id": null,
+ "created_at": "2026-05-21T17:00:00Z",
+ "started_at": "2026-05-21T17:00:03Z",
+ "completed_at": null,
+ "result_text": null,
+ "error": null
+ }
+}
+```
+
+`vibe runs list`:
+
+```json
+{
+ "schema_version": 1,
+ "ok": true,
+ "kind": "agent_runs",
+ "runs": [
+ {
+ "id": "run123",
+ "run_type": "agent_run",
+ "status": "running",
+ "agent_name": "release-reviewer",
+ "session_id": "sesnew12345",
+ "definition_id": null,
+ "created_at": "2026-05-21T17:00:00Z"
+ }
+ ]
+}
+```
+
+`vibe runs cancel <id>`:
+
+```json
+{
+ "schema_version": 1,
+ "ok": true,
+ "kind": "agent_run",
+ "run": {
+ "id": "run123",
+ "status": "canceled"
+ }
+}
+```
+
+Cancellation rules:
+
+- Runs that have not started should be marked `canceled` directly.
+- Runs already executing in a backend use best-effort cancellation in V1. If the
+ runtime can interrupt them, it should; otherwise it records cancel requested
+ and lets the worker/backend write the final terminal state.
+- If the backend completes normally after cancel was requested, preserve the
+ actual terminal `succeeded` or `failed` status and keep
+ `cancel_requested=true`; do not overwrite real success/failure as `canceled`.
+
+Failure contract:
+
+- CLI/runtime infrastructure failure should exit non-zero with `ok: false`.
+- If the target Agent ran and produced an Agent-level failure, return a run
+ record with `ok: true` only when the command itself completed successfully and
+ the failure is represented in `run.status` / `run.error`.
+- `run.status=failed` should be enough for harness callers to branch without
+ parsing text.
+
+Run inspection and management:
+
+```bash
+vibe runs show run123
+vibe runs list
+vibe runs cancel run123
+vibe runs logs run123
+```
+
+## Runtime And Recursion Policy
+
+`vibe agent run --async` should always enqueue a `agent_runs` row and let
+the Vibe runtime execute it.
+
+Synchronous `vibe agent run` should still create a run record first, then either:
+
+- execute through the local runtime service and wait for completion; or
+- claim/execute the run inline only if the runtime service is unavailable and
+ the backend path is safe to run in the CLI process.
+
+The preferred design is runtime-backed execution because it keeps session
+binding, delivery, logging, cancellation, and backend environment handling in
+one place.
+
+Synchronous runs have no fixed default wait limit. If execution exceeds 30
+minutes, the CLI returns an async accepted response, keeps the `agent_runs` row
+running, and the user can continue through `vibe runs show/list/logs`. The
+30-minute threshold is a system protection threshold, not a user-visible default
+timeout. `--wait-timeout` only changes how long the CLI waits; it does not mean
+the run times out or stops automatically.
+
+Agents may call `vibe agent run` again as a harness/sub-agent mechanism, but the
+run metadata should record `parent_run_id`. A simple recursion guard should be
+added before implementation:
+
+- maximum nesting depth;
+- cycle detection by parent chain;
+- clear failure status when the guard blocks a run.
+
+## Webhook Direction
+
+Future webhook support follows the same run creation path:
+
+```text
+external webhook -> validate source -> build RunSpec/message payload -> create agent_run
+```
+
+Possible CLI:
+
+```bash
+vibe agent webhook create --agent incident-triage --deliver-key slack::channel::C123
+```
+
+This can be designed later, but the schema should already leave room for
+`source.kind=webhook` and structured `payload_json`.
+
+## Specification Summary
+
+1. `vibe hook send` should be deprecated and replaced by `vibe agent run`.
+2. Agent Run message flags should be `--message` and `--message-file`, not `--prompt`.
+3. Agent Run must support existing `--session-id`.
+4. The shared storage model is `run_definitions` definitions plus
+ `agent_runs` executions.
+5. Run inspection and management live under `vibe runs`.
+6. Synchronous `vibe agent run` has no fixed default wait limit; after 30
+ minutes it continues asynchronously as a system protection threshold, and
+ `--wait-timeout` only controls CLI waiting.
+7. `vibe runs cancel` is best-effort; if the run finishes after cancellation was
+ requested, preserve the real `succeeded` / `failed` terminal status and keep
+ `cancel_requested=true`.
diff --git a/docs/plans/agent-run-harness.zh.md b/docs/plans/agent-run-harness.zh.md
new file mode 100644
index 000000000..8b3a766c3
--- /dev/null
+++ b/docs/plans/agent-run-harness.zh.md
@@ -0,0 +1,814 @@
+# Agent Run Harness
+
+## 背景
+
+Vibe Remote 需要三个面向用户的自动化入口:
+
+- 手动或外部触发的 Agent 执行;
+- 定时执行;
+- 监控条件触发执行。
+
+这三者是不同产品入口,但应该复用同一套执行 schema、状态模型、历史记录和
+管理逻辑。
+
+旧的 `vibe hook send` 更准确地说是“排队一次 Agent Run”,不应该作为独立
+产品概念长期存在。这份计划用 Agent Run harness 替代 hook。
+
+## 产品模型
+
+```text
+Agent Run = 执行一次 Agent 工作。
+Task = 时间触发器,触发后创建 Agent Run。
+Watch = 条件触发器,触发后创建 Agent Run。
+```
+
+Web UI 可以是清晰的三个 tab:
+
+- Agent Runs:由 CLI、webhook、手动操作或 API 创建的 run。
+- Scheduled Tasks:基于时间的 trigger definitions。
+- Watches:waiter/monitor trigger definitions。
+
+共享的底层原语是 run record,不是 task。
+
+## 目标
+
+- 用 `vibe agent run` 替代 `vibe hook send`。
+- Agent Run 的用户消息参数使用 `--message` / `--message-file`,不用 `--prompt`。
+- 支持同步和异步 Agent Run。
+- 支持在已有 `session_id` 对话里继续执行。
+- 支持创建新 Session,并返回预留的 Session ID。
+- 让 Agent Run、Task、Watch 都支持 `--agent <name>`,作为命令级 Vibe Agent
+ selector。
+- 让 task 和 watch 复用同一个 run spec 和 run history。
+- 为 webhook-triggered Agent Runs 预留结构。
+
+## CLI 设计
+
+### `vibe agent run`
+
+同步 Agent Run:
+
+```bash
+vibe agent run --agent release-reviewer --message "Review this diff."
+```
+
+异步 Agent Run:
+
+```bash
+vibe agent run --agent release-reviewer --async --message-file request.md
+```
+
+继续已有 Session:
+
+```bash
+vibe agent run --session-id sesk8m4q2p7x --message "Continue the investigation."
+```
+
+创建新 Session 并投递到 Scope:
+
+```bash
+vibe agent run \
+ --create-session \
+ --deliver-key slack::channel::C123 \
+ --message "Start a fresh incident triage."
+```
+
+规则:
+
+- 用户/任务消息使用 `--message` 和 `--message-file`。
+- `--prompt` / `--prompt-file` 是 deprecated compatibility inputs。如果用户
+ 传了它们,应拒绝命令,并明确提示改用 `--message` / `--message-file`。
+- 必须且只能指定一个 message source。
+- `--session-id` 通过公开 Vibe Session ID 继续对话。
+- `--create-session` 会预留一个新的 Vibe Session ID。带 `--deliver-key`
+ 时,这个 Session 同时绑定 delivery Scope;不带 `--deliver-key` 时,direct
+ Agent Run 是 private/no-delivery Session,用于 agent harness/sub-agent
+ 场景,必须显式传 `--agent`,并在输出里返回 `session_id` 供后续继续对话。
+- `--agent <name>` 为这次 run 选择 Vibe Agent。如果不传,则从 session 或
+ delivery Scope 的默认配置解析 Agent。
+- `--deliver-key <scope-id>` 把结果发送到 IM Scope。
+- `--async` 表示排队后立即返回。
+- 不带 `--async` 时,命令等待完成并打印结果。
+
+可选执行控制:
+
+- `--cwd <path>` 可以覆盖本次 run 的工作目录。未指定时,如果存在
+ scope/session,就使用 scope/session workdir;否则使用调用方 shell cwd。
+- `--wait-timeout <seconds>` 控制同步命令最多等待多久;它不终止 run。默认不设置
+ 固定等待上限;如果同步 run 执行超过 30 分钟,CLI 应返回 accepted 结果并把
+ run 转为 async 管理。30 分钟是系统保护阈值,不是用户可见的默认 timeout。
+- `--json` 是稳定的机器可读契约。非 JSON 输出面向人类,可以更简洁。
+
+### 废弃 `vibe hook send`
+
+兼容窗口:
+
+```bash
+vibe hook send ... -> vibe agent run --async ...
+```
+
+规则:
+
+- 暂时继续接受旧命令。
+- 返回 deprecation warning。
+- 新 prompt guidance 和 docs 不再教学 `vibe hook`。
+
+### `vibe task`
+
+`vibe task` 管理保存下来的时间触发器。它本身不直接执行工作,而是创建或管理
+`definition_type=scheduled` 的 `run_definitions` 记录。
+
+创建 recurring task:
+
+```bash
+vibe task add \
+ --cron "0 9 * * *" \
+ --agent release-reviewer \
+ --message "Prepare the daily release review."
+```
+
+创建 one-shot managed task:
+
+```bash
+vibe task add \
+ --at "2026-06-01T09:00:00+08:00" \
+ --create-session \
+ --deliver-key slack::channel::C123 \
+ --message-file request.md
+```
+
+管理 task:
+
+```bash
+vibe task list
+vibe task show <task-id>
+vibe task update <task-id> --cron "*/30 * * * *"
+vibe task run <task-id>
+vibe task pause <task-id>
+vibe task resume <task-id>
+vibe task remove <task-id>
+```
+
+规则:
+
+- 必须且只能指定一个 schedule source:`--cron` 或 `--at`。
+- 必须且只能指定一个 message source:`--message` 或 `--message-file`。
+- `--agent <name>` 选择并保存这个 task definition 使用的 Vibe Agent。
+- 如果不传 `--agent`,创建 task 时从目标 Scope/session 解析 Agent。
+- `task update <id> --agent <name>` 会影响这个 task 的未来 runs;历史
+ `agent_runs` 保留创建时捕获的 run spec。
+- 现有 `--prompt` / `--prompt-file` 只应被识别为 deprecated 参数,然后返回
+ 错误提示,要求改用 `--message` / `--message-file`。
+- `--create-session-per-run` 适用于 recurring tasks;用于 `--at` one-shot task
+ 时应拒绝。
+- `task run <id>` 根据保存的定义立即创建一条 `agent_runs` 记录;它不改变
+ schedule。
+- `pause` 禁用后续 schedule firing,但不删除历史。
+- `remove` soft-delete 这个 definition。
+
+### `vibe watch`
+
+`vibe watch` 管理保存下来的条件触发器。watch 运行一个 waiter command,观察它的
+终态,并在有内容需要报告时创建 Agent Run。
+
+创建 one-shot watch:
+
+```bash
+vibe watch add \
+ --agent release-reviewer \
+ --message "The export finished. Summarize the result." \
+ -- python3 scripts/wait_for_export.py
+```
+
+创建 long-running watch:
+
+```bash
+vibe watch add \
+ --forever \
+ --retry-exit-code 75 \
+ --retry-delay 60 \
+ --create-session-per-run \
+ --deliver-key slack::channel::C123 \
+ --message "A CI event finished. Review the waiter output." \
+ -- python3 scripts/wait_for_ci.py
+```
+
+管理 watch:
+
+```bash
+vibe watch list
+vibe watch show <watch-id>
+vibe watch pause <watch-id>
+vibe watch resume <watch-id>
+vibe watch remove <watch-id>
+```
+
+规则:
+
+- Watch definitions 存在 `run_definitions`,`definition_type=watch`。
+- waiter command 是 trigger configuration 的一部分。
+- `--agent <name>` 选择并保存这个 watch definition 使用的 Vibe Agent。
+- 如果不传 `--agent`,创建 watch 时从目标 Scope/session 解析 Agent。
+- `--message` / `--message-file` 是 waiter 到达可报告状态后创建 Agent Run 的
+ instruction template。
+- 现有 `--prefix` 可以作为兼容 alias 保留,用于在 waiter stdout 前追加指令;
+ 目标 schema 应把它存成 `message.text` 加结构化 waiter output。
+- `--forever` watch 会持续运行,直到 pause、remove、lifetime timeout,或遇到
+ non-retryable terminal failure。
+- Watch runtime process state 可以继续使用 `run_type=watch_runtime`,但用户可见
+ follow-up execution 应使用 `run_type=watch`。
+
+### One-Off Agent Run 和 One-Off Task 的区别
+
+`vibe agent run --async` 和 `vibe task add --at ...` 都可以只执行一次,但它们
+对应不同产品需求:
+
+- Agent Run:现在执行;不保存 definition;通过 run history 管理。
+- One-shot Task:稍后执行;保存 definition;可以 list、show、update、pause、
+ resume、remove,也可以在计划时间前手动 run。
+
+## RunSpec
+
+所有 immediate runs、scheduled tasks、watches 和未来 webhook triggers 应共享
+一个 run spec。
+
+```text
+RunSpec
+ agent_target:
+ mode: named_agent | session
+ agent_name
+ session_id
+ session_target:
+ mode: none | existing | create_once | create_per_run
+ session_id
+ scope_id
+ delivery_target:
+ mode: none | scope | post_to
+ scope_id
+ post_to
+ message:
+ text
+ payload_json
+ execution:
+ mode: sync | async
+```
+
+说明:
+
+- `message.text` 是用户/任务消息,不是 system prompt。
+- Agent system prompt 来自 Vibe Agent catalog。
+- `payload_json` 为 webhook/API structured input 预留。
+- `create_per_run` 属于 trigger definitions,不属于一次性 direct run。
+
+## Session 和 Delivery Targeting
+
+后台命令必须把三种身份分开:
+
+- Agent Session:要继续或创建的 Vibe Session。
+- Delivery Scope:Agent 输出最终投递到的 IM Scope。
+- Agent Definition:提供 backend/model/effort/prompt 的 Vibe Agent。
+
+### Scope ID
+
+`--deliver-key` 应该表示 `scopes.id`。它不是 session key。
+
+格式示例:
+
+```text
+<platform>::<scope_type>::<native_id>
+```
+
+示例:
+
+```text
+slack::channel::C123
+slack::user::U123
+lark::channel::oc_...
+```
+
+不需要单独的 thread anchor 参数。如果未来 thread 成为一等 Scope,同样可以
+通过 `--deliver-key <scope-id>` 覆盖。
+
+### Session Policies
+
+继续已有 Session:
+
+```bash
+--session-id <agent-session-id>
+```
+
+创建一个可复用的新 Session:
+
+```bash
+--create-session --deliver-key <scope-id>
+```
+
+每次 trigger 执行都创建一个新 Session:
+
+```bash
+--create-session-per-run --deliver-key <scope-id>
+```
+
+规则:
+
+- `--session-id`、`--create-session`、`--create-session-per-run` 互斥。
+- `vibe agent run --create-session` 可以不带 `--deliver-key`,表示创建
+ private/no-delivery Session,但必须显式传 `--agent`;managed task/watch
+ definitions 中使用 `--create-session` 或 `--create-session-per-run` 时必须带
+ `--deliver-key`。
+- `--create-session` 立即预留一个 Vibe Session ID。runtime 第一次执行时绑定
+ backend-native 状态。
+- `--create-session-per-run` 在 `run_definitions` 上保存策略;每次执行都创建
+ 一个新的 Vibe Session ID,并记录到对应 `agent_runs` 行里。
+- one-shot `task add --at` 使用 `--create-session-per-run` 时应拒绝,因为它和
+ `--create-session` 生命周期等价,但语义更不清楚。
+- 立即执行的 `vibe agent run` 只需要 `--create-session`;per-run 对单次 direct
+ run 没有独立含义。
+
+### 参数互斥矩阵
+
+| 参数组合 | `vibe agent run` | `vibe task add/update` | `vibe watch add` | 规则 |
+| --- | --- | --- | --- | --- |
+| `--message` + `--message-file` | 拒绝 | 拒绝 | 拒绝 | 每次定义或执行只能有一个 message source。 |
+| `--prompt` / `--prompt-file` + 任意 message 参数 | 拒绝 | 拒绝 | 拒绝 | 旧参数只用于 deprecated 错误提示。 |
+| `--session-id` + `--create-session` | 拒绝 | 拒绝 | 拒绝 | 一个 run 只能有一种 Session policy。 |
+| `--session-id` + `--create-session-per-run` | 拒绝 | 拒绝 | 拒绝 | `existing` 和 `create_per_run` 生命周期冲突。 |
+| `--create-session` + `--create-session-per-run` | 拒绝 | 拒绝 | 拒绝 | `create_once` 和 `create_per_run` 生命周期冲突。 |
+| `--create-session` without `--deliver-key` | 仅允许同时传 `--agent` | 拒绝 | 拒绝 | Direct Agent Run 可创建 private/no-delivery Session,但 Agent 必须显式;managed definitions 创建 Session 需要 Scope。 |
+| `--create-session-per-run` without `--deliver-key` | 不适用 | 拒绝 | 拒绝 | 每次创建新 Session 都需要 Scope。 |
+| `--create-session-per-run` + `task add --at` | 不适用 | 拒绝 | 不适用 | one-shot task 只有一次执行,使用 `--create-session`。 |
+| `--deliver-key` + `--post-to` | 拒绝 | 拒绝 | 拒绝 | 一个是显式 Scope,一个是 shortcut。 |
+| `--agent` + `--session-id` | backend 一致时允许 | backend 一致时允许 | backend 一致时允许 | `--agent` 只覆盖该次 run/definition,不修改 Session;若 Agent backend 和 Session backend 不同则拒绝。 |
+| `--agent` + `--deliver-key` | 允许 | 允许 | 允许 | `--agent` 覆盖 Scope 默认 Agent;`--deliver-key` 决定 delivery。 |
+| `--async` + `--wait-timeout` | 拒绝 | 不适用 | 不适用 | `--wait-timeout` 只控制同步 CLI 等待,不控制 async run 生命周期。 |
+
+### Delivery Policies
+
+创建需要投递到 IM 的新 Session 时,必须提供 `--deliver-key <scope-id>`,因为
+CLI 不能安全推断当前 IM 上下文。Direct `vibe agent run --create-session`
+不带 `--deliver-key` 时不做 IM 投递,只返回 run/session 输出。
+
+对于已有 Session:
+
+- 默认 delivery 来自 Session 自身;
+- `--post-to thread|channel` 继续作为便利快捷方式;
+- `--deliver-key <scope-id>` 是显式 delivery override;
+- `--post-to` 和 `--deliver-key` 互斥。
+
+### Runtime Target Resolution
+
+后台命令不应接受 backend/model/effort override flags。runtime target 解析规则是:
+
+1. 如果传了 `--agent <name>`,加载这个 Vibe Agent。
+2. 否则,如果传了 `--session-id`,使用该 Session 当前的 Agent identity。
+3. 否则,把 `--deliver-key` 解析为 Scope,并读取 Scope 选择的 Vibe Agent。
+4. 如果 Scope 没有选择 Agent,则使用系统默认 Agent。
+5. 如果同时传了 `--agent` 和 `--session-id`,校验 Agent backend 和 Session
+ backend 一致;不一致时拒绝,因为跨 backend 无法保持上下文连续。
+6. 使用解析出的 Agent backend/model/effort/system prompt。
+7. 使用 Scope/session workdir,除非本次 run 通过 `--cwd` 覆盖。
+
+所以 `--agent` 是命令级的 Scope default Agent override,不是
+backend/model/effort override;和 `--session-id` 组合时也只影响本次 run,不修改
+Session 后续默认 Agent。
+
+## 存储模型
+
+由现有两张 background 表迁移并重命名:
+
+- `background_tasks` -> `run_definitions`:reusable managed trigger 的定义表。
+- `background_runs` -> `agent_runs`:每一次实际执行的运行表。
+
+### `run_definitions`:定义
+
+`run_definitions` 保存未来可能创建 runs 的定义,是 task、watch 和未来 webhook
+的统一 definition 表。
+
+建议的 `definition_type`:
+
+- `scheduled`:cron 或 one-shot scheduled task;
+- `watch`:managed waiter,在终态条件达成后产生 follow-up run;
+- `webhook`:未来的外部触发定义。
+
+立即执行的 `vibe agent run` 不创建 `run_definitions` 记录,它直接创建
+`agent_runs` 记录。
+
+核心 definition 语义应作为一等列保存。字段明细:
+
+| Field | Status | Definition | Design intent |
+| --- | --- | --- | --- |
+| `id` | 现有 | Definition ID。 | 作为 task/watch/webhook definition 的稳定管理句柄。 |
+| `definition_type` | 现有字段改名,扩展取值 | Definition 类型:`scheduled`、`watch`、未来 `webhook`。 | 由 `task_type` 改名,避免把 watch/webhook 都称为 task。 |
+| `name` | 现有 | 用户可见名称。 | 让 CLI/Web UI 可以展示可读名称,而不是只展示 ID。 |
+| `agent_name` | 新增 | 这个 definition 创建 runs 时使用的 Vibe Agent 名称。 | 让 task/watch 明确选择 Agent;不传 `--agent` 时写入从 Scope/session 解析出的默认 Agent。 |
+| `session_policy` | 新增 | `existing`、`create_once`、`create_per_run`。 | 把“继续已有 Session / 复用新 Session / 每次新 Session”的生命周期语义落成可查询字段。 |
+| `session_id` | 现有 | `existing` 或 `create_once` policy 下的 Vibe Session ID。 | 保存已有或预留的 Session ID,后续执行能继续同一个 Vibe Session。 |
+| `legacy_session_key` | 现有,兼容 | 旧 `session_key` target。 | 只服务旧记录和旧命令迁移;新写入优先使用 `session_id` / `deliver_key`。 |
+| `deliver_key` | 现有,改义 | Delivery Scope ID。domain/API 层可叫 `delivery_scope_id` 或 `scope_id`。 | 让投递目标和 Session 身份分离;当前保留列名以降低迁移成本。 |
+| `post_to` | 现有 | `thread` / `channel` 这类 delivery shortcut。 | 覆盖最常见的投递调整,不需要用户手写完整 Scope ID。 |
+| `prompt` | 现有,兼容 | 旧消息模板字段。 | 迁移期读写兼容;目标 schema 用 `message` 表达同一语义。 |
+| `message` | 新增 | 保存的 Agent message template。 | 配合 CLI `--message`,避免和 Agent `system_prompt` 混淆。 |
+| `message_payload_json` | 新增 | 可选结构化消息 payload。 | 为 webhook/API 触发保留结构化输入,不把文本 message 和 payload 混在一起。 |
+| `schedule_type` | 现有 | `cron` 或 `at`。 | 区分 recurring task 和 one-shot task。 |
+| `cron` | 现有 | Cron 表达式。 | 存储 recurring schedule。 |
+| `run_at` | 现有 | one-shot scheduled time。 | 存储单次计划执行时间。 |
+| `timezone` | 现有 | schedule timezone。 | 保证 cron/at 的解释可复现,不依赖 runtime 当前时区。 |
+| `command_json` | 现有 | watch waiter argv。 | 存储 structured command,避免 shell quoting 歧义。 |
+| `shell_command` | 现有 | watch waiter shell command。 | 保留 shell 模式,服务复杂脚本和兼容旧命令。 |
+| `prefix` | 现有,兼容 | 旧 watch follow-up instruction prefix。 | 迁移期兼容 `--prefix`;目标语义应合并到 `message`。 |
+| `cwd` | 现有 | watch/runtime working directory。 | 让后台执行不依赖服务进程启动目录。 |
+| `mode` | 现有 | watch mode,例如 `once` 或 `forever`。 | 表达 watch 生命周期。 |
+| `timeout_seconds` | 现有 | per-run 或 per-cycle timeout。 | 防止单次执行无限挂起。 |
+| `lifetime_timeout_seconds` | 现有 | watch overall lifetime timeout。 | 给 long-running watch 设置总生命周期边界。 |
+| `retry_exit_codes_json` | 现有 | 可重试的 waiter exit codes。 | 让 watch 能区分“继续等待”和“终态失败”。 |
+| `retry_delay_seconds` | 现有 | retryable waiter 的重试延迟。 | 控制 forever watch 的重试节奏。 |
+| `enabled` | 现有 | Definition 是否允许创建未来 runs。 | 支持 pause/resume,不删除历史。 |
+| `deleted_at` | 现有 | soft-delete timestamp。 | 支持 remove 后隐藏定义,同时保留历史 runs。 |
+| `created_at` | 现有 | 创建时间。 | 审计和排序。 |
+| `updated_at` | 现有 | 最近更新时间。 | 管理 UI、同步和变更排查。 |
+| `last_started_at` | 现有 | 最近一次执行开始时间。 | 列表页快速展示执行状态。 |
+| `last_finished_at` | 现有 | 最近一次执行结束时间。 | 列表页快速判断是否完成。 |
+| `last_event_at` | 现有 | watch 最近检测到事件的时间。 | watch 列表摘要。 |
+| `last_run_at` | 现有 | scheduled task 最近触发时间。 | task 列表摘要。 |
+| `last_error` | 现有 | 最近错误摘要。 | 列表页直接暴露可处理问题。 |
+| `last_exit_code` | 现有 | 最近 waiter/process exit code。 | watch/debug 摘要。 |
+| `last_run_id` | 新增 | 最近创建的用户可见 run ID。 | 让 definition 和 run history 快速互跳。 |
+| `metadata_json` | 现有,扩展 | 非核心扩展信息。 | 只放暂不需要查询/索引的 backend-specific、UI hint、实验字段。 |
+
+`metadata_json` 只保留给非核心扩展信息:
+
+- backend-specific import metadata;
+- 不影响执行的 UI display hints;
+- 暂时没有查询需求的 webhook auth/source metadata;
+- 实验字段,后续稳定后再提升为列。
+
+实现可以渐进迁移:当前 `prompt` 列先作为 `message` 的兼容 alias 保留,之后通过
+schema migration 改名或复制成 `message` 列。
+
+Definition 表的迁移优先级:
+
+1. 先增加 `agent_name`、`session_policy`、`message`、`message_payload_json`、
+ `last_run_id`。
+2. 写入新 definition 时同时填充新列和必要兼容列,例如 `prompt`。
+3. 读取旧 definition 时,如果 `message` 为空,则从 `prompt` 派生。
+4. 兼容窗口结束后,再考虑是否删除或停止展示 `prompt`、`prefix` 等旧语义字段。
+
+### `agent_runs`:执行
+
+`agent_runs` 保存每一次实际执行:
+
+- 立即执行的 `vibe agent run`;
+- 异步的 `vibe agent run --async`;
+- scheduled task 触发;
+- watch 进入终态后的 follow-up;
+- 未来 webhook invocation。
+
+建议的 `run_type`:
+
+- `agent_run`:直接 agent invocation,通常 `definition_id = null`;
+- `scheduled`:由 scheduled `run_definitions` 记录创建;
+- `watch`:由 watch `run_definitions` 记录创建;
+- `webhook`:由 webhook `run_definitions` 记录创建;
+- `watch_runtime`:如果仍然需要,可以保留给历史/runtime waiter bookkeeping。
+
+目标 domain status:
+
+- `queued`;
+- `running`;
+- `succeeded`;
+- `failed`;
+- `canceled`。
+
+存储层初期可以把这些映射到现有的 `pending`、`processing`、`completed` 等值;
+公开输出 schema 应该使用上面的 domain status。
+
+字段明细:
+
+| Field | Status | Definition | Design intent |
+| --- | --- | --- | --- |
+| `id` | 现有 | Run ID。 | 每次实际执行的稳定句柄,用于 show/list/cancel/history。 |
+| `definition_id` | 现有字段改名 | 可选来源 `run_definitions.id`。 | 由 `task_id` 改名,表达来源是通用 definition,不只是 task。 |
+| `run_type` | 现有,扩展取值 | `agent_run`、`scheduled`、`watch`、`webhook` 或 runtime bookkeeping type。 | 区分 direct run、task run、watch follow-up、webhook invocation。 |
+| `status` | 现有,规范化取值 | `queued`、`running`、`succeeded`、`failed`、`canceled`。 | 给 CLI/Web UI/agent harness 一个统一状态机。 |
+| `source_kind` | 新增 | `cli`、`api`、`scheduler`、`watch` 或 `webhook`。 | 记录谁创建了这次 run,方便审计和筛选。 |
+| `source_actor` | 新增 | 可选 actor/user/system identifier。 | 区分人、agent、scheduler、外部系统触发。 |
+| `parent_run_id` | 新增 | 父 run ID。 | 支持 agent harness/sub-agent 调用链和递归保护。 |
+| `agent_name` | 新增 | 本次 run 捕获的 Vibe Agent 名称。 | 历史 run 可审计;Agent 定义变化后仍知道当时选择的是谁。 |
+| `agent_id` | 新增 | 可选 Agent ID snapshot。 | 避免未来 Agent rename/显示名变化影响历史关联;如果 name 永久不可变,可为空。 |
+| `agent_backend` | 新增 | backend snapshot。 | Debug 和历史审计,不需要 join 当前 Agent 才知道当时跑在哪个 backend。 |
+| `model` | 新增 | model snapshot。 | 记录执行时模型,避免 Agent 后续修改影响历史解释。 |
+| `reasoning_effort` | 新增 | effort snapshot。 | 记录执行时推理强度。 |
+| `session_policy` | 新增 | 本次 run 使用的 session resolution policy。 | 解释 `session_id` 是复用、预留还是 per-run 创建出来的。 |
+| `session_id` | 现有 | 本次 run 实际使用的 Vibe Session ID。 | 支持继续对话、按 session 查历史。 |
+| `legacy_session_key` | 现有,兼容 | 旧导入 runs 的兼容 target。 | 只用于迁移和兼容展示。 |
+| `deliver_key` | 现有,改义 | Delivery Scope ID snapshot。 | 记录结果投递目标,支持按 Scope 查 runs。 |
+| `post_to` | 现有 | Delivery shortcut snapshot。 | 保留 thread/channel 这类快捷投递语义。 |
+| `prompt` | 现有,兼容 | 旧消息字段。 | 迁移期兼容旧 run;目标 schema 用 `message`。 |
+| `message` | 新增 | 发送给 Agent 的实际消息。 | 与 `--message` 对齐,并和 Agent system prompt 分离。 |
+| `message_payload_json` | 新增 | 可选结构化 payload。 | 支持 webhook/API 传结构化输入。 |
+| `result_text` | 新增 | 最终用户可见结果。 | 支持 sync `agent run` 回显、run show、Web UI 摘要。 |
+| `result_payload_json` | 新增 | 可选结构化结果。 | 为 API/webhook/harness 返回机器可读结果。 |
+| `message_ids_json` | 新增 | 本次 run 发送出的 IM message IDs。 | 支持投递审计、后续 thread 关联和 UI 跳转。 |
+| `cancel_requested` | 新增 | 用户是否请求过取消。 | 支持 best-effort cancel 后保留真实执行终态。 |
+| `cancel_requested_at` | 新增 | 取消请求时间。 | 审计取消请求和 worker 响应延迟。 |
+| `pid` | 现有 | runtime/watch process id。 | 支持 watch runtime 管理和诊断。 |
+| `exit_code` | 现有 | process exit code。 | 诊断 watch/waiter 或 backend process 失败。 |
+| `error` | 现有 | 错误摘要。 | CLI/Web UI 快速展示失败原因。 |
+| `stdout` | 现有 | bounded stdout。 | 保留 waiter/backend 输出摘要。 |
+| `stderr` | 现有 | bounded stderr。 | 保留诊断输出。 |
+| `created_at` | 现有 | run 创建时间。 | 队列和历史排序。 |
+| `started_at` | 现有 | run 开始执行时间。 | 计算排队等待和执行耗时。 |
+| `completed_at` | 现有 | run 完成时间。 | 计算执行耗时和判断终态。 |
+| `updated_at` | 现有 | 最近更新时间。 | worker polling、stale running 检测。 |
+| `metadata_json` | 现有,扩展 | 非核心扩展信息。 | 只放非查询、backend-specific 或实验数据。 |
+
+scheduled/watch/webhook 创建 run 时,这些列应从 definition 复制快照。这样即使
+后续 task、watch 或 Agent 定义变化,历史 run 仍然可审计。
+
+`metadata_json` 只作为非查询、backend-specific 或实验数据的扩展字段。核心 run
+语义不能放在 `metadata_json` 里。
+
+Run 表的迁移优先级:
+
+1. 先增加 `source_kind`、`source_actor`、`parent_run_id`、Agent snapshot、
+ `session_policy`、`message`、`message_payload_json`、result 和 message IDs
+ 相关列。
+2. 新创建 run 时,从 definition 或 direct command 参数复制一等列快照。
+3. 读取旧 run 时,如果 `message` 为空,则从 `prompt` 派生;如果 `result_text`
+ 为空,可以继续从旧 `stdout` / `error` 组合展示摘要。
+4. `metadata_json` 中已经存在的历史扩展数据只做兼容读取,不再作为新 run 的
+ core semantics 写入目标。
+
+### 表职责
+
+- `run_definitions` 负责定义生命周期和 trigger 配置。
+- `agent_runs` 负责执行生命周期、历史、输出和错误。
+- 一次性 agent run 是“没有保存定义的执行”。
+- Webhook 可以作为新的 definition type 和 run type 加进来。
+- harness/sub-agent 场景通过 run 上的 `parent_run_id` 表示父子关系。
+
+### 索引建议
+
+现有索引已经覆盖常见 task/watch 查询。run 表还应该支持:
+
+- worker polling:`(status, updated_at)` 或 `(status, created_at)`;
+- 按类型查历史:`(run_type, status, created_at)`;
+- 按 session 查历史:`(session_id, created_at)`;
+- 按定义查历史:`(definition_id, created_at)`。
+
+迁移时应把旧 `agent_runs.task_id` 改名为 `definition_id`,或先新增
+`definition_id` 并从旧列回填;数据库列统一使用 `definition_id`。
+
+## 和 Task / Watch 的关系
+
+### `vibe task`
+
+`vibe task` 管理 scheduled trigger definitions。
+
+```bash
+vibe task add --cron "0 9 * * *" --agent release-reviewer --message "Daily review"
+vibe task run <task-id>
+vibe task pause <task-id>
+```
+
+schedule 触发时,从 task definition 的一等列复制快照,创建一条
+`agent_runs` 记录。
+
+### `vibe watch`
+
+`vibe watch` 管理 condition trigger definitions。
+
+```bash
+vibe watch add --agent release-reviewer --prefix "CI finished" -- python wait.py
+```
+
+waiter 成功或进入 terminal failure 时,创建一条 `agent_runs` 记录。
+
+### `vibe agent run`
+
+`vibe agent run` 立即创建一条 `agent_runs` 记录。除非未来有显式 save
+命令,否则它不创建 `run_definitions` definition。
+
+## 输出契约
+
+JSON 输出应作为 agents 和 scripts 的稳定契约。
+
+通用规则:
+
+- 顶层必须有 `schema_version`、`ok`、`kind`。
+- `kind` 表达返回对象类型,例如 `agent_run`、`run_definition`、`agent_runs`。
+- 人类可读输出可以更短,但 `--json` 输出必须稳定。
+
+同步 Agent Run 成功:
+
+```json
+{
+ "schema_version": 1,
+ "ok": true,
+ "kind": "agent_run",
+ "run": {
+ "id": "run123",
+ "status": "succeeded",
+ "session_id": "sesk8m4q2p7x",
+ "result_text": "..."
+ }
+}
+```
+
+异步 Agent Run accepted,或同步执行超过 30 分钟后转 async:
+
+```json
+{
+ "schema_version": 1,
+ "ok": true,
+ "accepted": true,
+ "kind": "agent_run",
+ "run": {
+ "id": "run123",
+ "status": "queued",
+ "session_id": "sesnew12345"
+ }
+}
+```
+
+Task/Watch definition 创建成功:
+
+```json
+{
+ "schema_version": 1,
+ "ok": true,
+ "kind": "run_definition",
+ "definition": {
+ "id": "def123",
+ "definition_type": "scheduled",
+ "enabled": true,
+ "agent_name": "release-reviewer",
+ "session_policy": "create_once",
+ "session_id": "sesnew12345",
+ "deliver_key": "slack::channel::C123",
+ "next_run_at": "2026-06-01T09:00:00+08:00"
+ },
+ "warnings": []
+}
+```
+
+`vibe task run <id>` 成功:
+
+```json
+{
+ "schema_version": 1,
+ "ok": true,
+ "kind": "agent_run",
+ "definition": {
+ "id": "def123",
+ "definition_type": "scheduled"
+ },
+ "run": {
+ "id": "run123",
+ "status": "queued",
+ "definition_id": "def123",
+ "agent_name": "release-reviewer",
+ "session_id": "sesnew12345"
+ }
+}
+```
+
+`vibe runs show <id>`:
+
+```json
+{
+ "schema_version": 1,
+ "ok": true,
+ "kind": "agent_run",
+ "run": {
+ "id": "run123",
+ "run_type": "agent_run",
+ "status": "running",
+ "source_kind": "cli",
+ "agent_name": "release-reviewer",
+ "session_id": "sesnew12345",
+ "definition_id": null,
+ "created_at": "2026-05-21T17:00:00Z",
+ "started_at": "2026-05-21T17:00:03Z",
+ "completed_at": null,
+ "result_text": null,
+ "error": null
+ }
+}
+```
+
+`vibe runs list`:
+
+```json
+{
+ "schema_version": 1,
+ "ok": true,
+ "kind": "agent_runs",
+ "runs": [
+ {
+ "id": "run123",
+ "run_type": "agent_run",
+ "status": "running",
+ "agent_name": "release-reviewer",
+ "session_id": "sesnew12345",
+ "definition_id": null,
+ "created_at": "2026-05-21T17:00:00Z"
+ }
+ ]
+}
+```
+
+`vibe runs cancel <id>`:
+
+```json
+{
+ "schema_version": 1,
+ "ok": true,
+ "kind": "agent_run",
+ "run": {
+ "id": "run123",
+ "status": "canceled"
+ }
+}
+```
+
+取消规则:
+
+- 对尚未开始的 run,应直接标记为 `canceled`。
+- 对已经进入 backend 执行的 run,第一版使用 best-effort cancel;能中断就中断,
+ 不能中断则记录 cancel requested,并由 worker/backend 最终回写终态。
+- 如果 cancel requested 后 backend 已经正常完成,最终状态保留真实的
+ `succeeded` 或 `failed`,同时保留 `cancel_requested=true`;不要把真实成功或
+ 失败统一覆盖成 `canceled`。
+
+失败契约:
+
+- CLI/runtime 基础设施失败时,命令应非零退出,并返回 `ok: false`。
+- 如果目标 Agent 已经运行,但它产生的是 Agent-level failure,那么只要命令
+ 本身成功完成,可以返回 run 记录;失败信息由 `run.status` / `run.error`
+ 表达。
+- `run.status=failed` 应足够让 harness caller 分支处理,不需要解析文本。
+
+Run 查看和管理:
+
+```bash
+vibe runs show run123
+vibe runs list
+vibe runs cancel run123
+vibe runs logs run123
+```
+
+## Runtime 和递归策略
+
+`vibe agent run --async` 应始终先创建 `agent_runs` 记录,然后交给 Vibe
+runtime 执行。
+
+同步 `vibe agent run` 也应该先创建 run 记录,然后二选一:
+
+- 通过本地 runtime service 执行并等待完成;
+- 只有当 runtime service 不可用且 backend 路径适合在 CLI 进程里安全运行时,
+ 才由 CLI inline claim/execute。
+
+推荐 runtime-backed execution,因为 session binding、delivery、logging、
+cancellation 和 backend environment 都应该由同一条路径处理。
+
+同步 run 默认没有固定等待上限。若执行超过 30 分钟,CLI 返回 async accepted
+响应,保留 `agent_runs` 里的运行状态,后续通过 `vibe runs show/list/logs`
+管理。30 分钟是系统保护阈值,不是用户可见的默认 timeout。`--wait-timeout`
+只改变 CLI 等待多久,不表示 run 执行超时或自动停止。
+
+Agent 可以再次调用 `vibe agent run`,把它作为 harness/sub-agent 机制,但 run
+metadata 应记录 `parent_run_id`。实现前应加一个简单递归保护:
+
+- 最大嵌套深度;
+- 根据 parent chain 做 cycle detection;
+- guard 阻止运行时,写入清晰的 failure status。
+
+## Webhook 方向
+
+未来 webhook 支持也走同一条 run creation 路径:
+
+```text
+external webhook -> validate source -> build RunSpec/message payload -> create agent_run
+```
+
+可能的 CLI:
+
+```bash
+vibe agent webhook create --agent incident-triage --deliver-key slack::channel::C123
+```
+
+这可以之后单独设计,但 schema 应该已经为 `source.kind=webhook` 和结构化
+`payload_json` 留位置。
+
+## 规范摘要
+
+1. `vibe hook send` 应废弃,由 `vibe agent run` 替代。
+2. Agent Run 消息参数应叫 `--message` 和 `--message-file`,不叫 `--prompt`。
+3. Agent Run 必须支持已有 `--session-id`。
+4. 共享存储模型是 `run_definitions` 定义表 + `agent_runs` 执行表。
+5. Run 查看和管理放在 `vibe runs`。
+6. 同步 `vibe agent run` 默认没有固定等待上限;超过 30 分钟自动转为 async
+ 管理,30 分钟是系统保护阈值,`--wait-timeout` 只控制 CLI 等待时长。
+7. `vibe runs cancel` 是 best-effort;如果请求取消后 run 仍正常完成,保留真实
+ `succeeded` / `failed` 终态,并记录 `cancel_requested=true`。
diff --git a/docs/plans/background-session-id-tasks.md b/docs/plans/background-session-id-tasks.md
deleted file mode 100644
index 81878fdf6..000000000
--- a/docs/plans/background-session-id-tasks.md
+++ /dev/null
@@ -1,238 +0,0 @@
-# Background Tasks With Stable Agent Sessions
-
-## Background
-
-Scheduled tasks, hooks, and watches currently target conversations through an
-external `session_key` such as:
-
-```text
-slack::channel::C123::thread::171717.123
-```
-
-That key is useful for bootstrapping a turn from an IM surface, but it is not
-the durable identity of the agent session. Vibe Remote already has an
-`agent_sessions` table whose `id` was explicitly designed as the short handle
-that can be shown to agents, passed to CLI commands, and referenced by future
-Web UI task management.
-
-The intended `agent_sessions.id` format is:
-
-```text
-ses + 10 lowercase base32-like characters
-```
-
-Example:
-
-```text
-sesk8m4q2p7x
-```
-
-It is short, symbol-free, non-numeric, and copyable in chat. The current
-implementation has a critical bug: `SQLiteSessionsService.save_state()` rebuilds
-`agent_sessions` from the legacy in-memory session mappings and generates new
-row IDs on every save. That breaks the original contract. Before any task/watch
-feature references `agent_sessions.id`, the ID must become stable.
-
-## Goals
-
-- Make `agent_sessions.id` stable across saves and service restarts.
-- Inject the current `session_id` into agent prompts as the primary target for
- background commands.
-- Add `--session-id` to `vibe task`, `vibe hook`, and `vibe watch`.
-- Keep `--session-key` as a compatibility path for old scripts and persisted
- tasks, but do not teach it in new agent-facing prompt text.
-- Design the future SQLite background task tables around `session_id`, not
- external `session_key`.
-
-## Non-Goals
-
-- Do not solve the future "create a brand-new session on each run" product
- model in this change. That will get a separate design.
-- Do not remove `--session-key` yet.
-- Do not require the Web UI to manage tasks in this first slice.
-
-## Session Identity Rules
-
-### Stable Agent Session IDs
-
-`agent_sessions.id` is the user-facing Vibe Remote session handle. It must not
-change when:
-
-- a session mapping is saved again;
-- active thread/poll/dedup runtime state changes;
-- the service restarts;
-- task/watch state is updated.
-
-The persistence layer should preserve existing IDs by matching the durable
-business identity of a session:
-
-| Component | Meaning |
-| --- | --- |
-| `scope_id` | IM scope resolved from the legacy session scope key |
-| `agent_variant` | agent or subagent namespace |
-| `session_anchor` | conversation anchor / base session id / composite key |
-| `native_session_id` | backend-native session/thread id |
-
-`workdir` is still stored and indexed, but is not sufficient by itself as a
-unique identity. OpenCode already embeds workdir in the `session_anchor`, while
-Claude/Codex use backend-native session ids to distinguish resumed sessions.
-
-### Prompt Injection
-
-The prompt should use `session_id` as the primary background target:
-
-```text
-Current conversation targeting:
-- Current session id: sesk8m4q2p7x
-```
-
-Rules shown to agents should prefer:
-
-```bash
-vibe task add --session-id sesk8m4q2p7x ...
-vibe hook send --session-id sesk8m4q2p7x ...
-vibe watch add --session-id sesk8m4q2p7x ...
-```
-
-The injected prompt must not mention the legacy session key or show
-`--session-key` examples. Old targeting belongs only in compatibility code and
-low-prominence CLI/help text for existing scripts.
-
-## CLI Compatibility
-
-The new public flag is `--session-id`.
-
-| Command | New primary flag | Legacy flag |
-| --- | --- | --- |
-| `vibe task add` | `--session-id` | `--session-key` |
-| `vibe task update` | `--session-id` | `--session-key` |
-| `vibe hook send` | `--session-id` | `--session-key` |
-| `vibe watch add` | `--session-id` | `--session-key` |
-
-Validation:
-
-- Require exactly one of `--session-id` or `--session-key` for new add/send
- commands.
-- Reject commands that pass both.
-- Keep `--deliver-key` and `--post-to` for explicit delivery overrides.
-- When a stored object has `session_id`, resolve through `agent_sessions`.
-- When a stored object only has `session_key`, use the legacy resolver.
-
-## Resolving `--session-id`
-
-Resolving a session id should load the `agent_sessions` row and its `scope`.
-
-| Target field | Source |
-| --- | --- |
-| platform | `scopes.platform` |
-| scope type | `scopes.scope_type` |
-| scope native id | `scopes.native_id` |
-| session anchor | `agent_sessions.session_anchor` |
-| agent backend | `agent_sessions.agent_backend` |
-| agent variant | `agent_sessions.agent_variant` |
-| native session id | `agent_sessions.native_session_id` |
-| workdir | `agent_sessions.workdir` |
-
-The execution path should reconstruct a scheduled `MessageContext` that routes
-to the same scope and anchor that the session row represents. The agent backend
-then resumes the same native session through the normal session mapping.
-
-## Background Tables
-
-Keep the schema small: two tables cover persisted definitions, queued work,
-runtime snapshots, and execution history.
-
-### `background_tasks`
-
-| Field | Type | Purpose |
-| --- | --- | --- |
-| `id` | TEXT PK | background task id |
-| `task_type` | TEXT | `scheduled` or `watch` |
-| `session_id` | TEXT | primary Agent Session target |
-| `legacy_session_key` | TEXT | compatibility target for old tasks and old CLI |
-| `name` | TEXT | user-visible name |
-| `enabled` | INTEGER | enabled flag |
-| `deleted_at` | TEXT | soft-delete timestamp; hidden from active task/watch lists |
-| `post_to` | TEXT | delivery shortcut |
-| `deliver_key` | TEXT | explicit delivery override |
-| `prompt` | TEXT | scheduled task prompt |
-| `schedule_type` | TEXT | `cron` or `at` |
-| `cron` | TEXT | cron expression |
-| `run_at` | TEXT | one-off run timestamp |
-| `timezone` | TEXT | schedule timezone |
-| `command_json` | TEXT | watch argv array |
-| `shell_command` | TEXT | watch shell command |
-| `prefix` | TEXT | watch follow-up instruction prefix |
-| `cwd` | TEXT | watch working directory |
-| `mode` | TEXT | `once` or `forever` |
-| `timeout_seconds` | REAL | per-cycle timeout |
-| `lifetime_timeout_seconds` | REAL | overall forever-watch timeout |
-| `retry_exit_codes_json` | TEXT | retryable exit codes |
-| `retry_delay_seconds` | REAL | retry delay |
-| `last_started_at` | TEXT | latest start time |
-| `last_finished_at` | TEXT | latest finish time |
-| `last_event_at` | TEXT | latest detected event time |
-| `last_run_at` | TEXT | latest scheduled-task run time |
-| `last_error` | TEXT | latest error |
-| `last_exit_code` | INTEGER | latest exit code |
-| `metadata_json` | TEXT | extension payload |
-| `created_at` | TEXT | create time |
-| `updated_at` | TEXT | update time |
-
-### `background_runs`
-
-| Field | Type | Purpose |
-| --- | --- | --- |
-| `id` | TEXT PK | run id |
-| `task_id` | TEXT | optional `background_tasks.id` |
-| `run_type` | TEXT | `scheduled`, `task_run`, `hook_send`, or `watch_runtime` |
-| `status` | TEXT | `pending`, `processing`, `completed`, `failed`, or `running` |
-| `session_id` | TEXT | actual target session |
-| `legacy_session_key` | TEXT | compatibility target |
-| `post_to` | TEXT | delivery shortcut snapshot |
-| `deliver_key` | TEXT | explicit delivery snapshot |
-| `prompt` | TEXT | actual prompt sent |
-| `pid` | INTEGER | running process id for watch runtime rows |
-| `started_at` | TEXT | start time |
-| `completed_at` | TEXT | finish time |
-| `exit_code` | INTEGER | process exit code |
-| `error` | TEXT | error summary |
-| `stdout` | TEXT | bounded stdout when recorded |
-| `stderr` | TEXT | bounded stderr when recorded |
-| `metadata_json` | TEXT | extension result/runtime payload |
-| `created_at` | TEXT | create time |
-| `updated_at` | TEXT | update time |
-
-## Migration Strategy
-
-1. Fix `agent_sessions.id` stability first.
-2. Add `--session-id` while keeping `--session-key`.
-3. Update prompt injection to prefer `--session-id`.
-4. Add SQLite background tables and import old JSON state once.
-5. Switch task/watch stores to SQLite as the source of truth while preserving
- explicit-path JSON stores for tests and compatibility.
-
-This order keeps old CLI scripts working while making every new task/watch use
-the durable agent session handle.
-
-## Implementation Slices
-
-### Slice 1: Session ID Targeting Bridge
-
-Completed bridge before moving task/watch persistence itself to SQLite:
-
-- preserve `agent_sessions.id` across `save_state()` rebuilds;
-- attach `agent_session_id` to Claude, Codex, and OpenCode prompt contexts when
- the row already exists or is created;
-- inject `Current session id` as the only agent-facing background target;
-- add `--session-id` to task, hook, and watch CLI commands;
-- resolve `session_id` through SQLite `agent_sessions` at runtime, while still
- accepting old `session_key`-only records.
-
-### Slice 2: SQLite Background Store
-
-This slice adds `background_tasks` and `background_runs`, imports existing JSON
-tasks/watches/request state once, and makes SQLite the default source of truth.
-It does not change the public targeting contract again: new rows store
-`session_id` directly and keep `legacy_session_key` only for compatibility
-display/import.
diff --git a/docs/plans/scheduled-tasks.md b/docs/plans/scheduled-tasks.md
deleted file mode 100644
index 20c23f383..000000000
--- a/docs/plans/scheduled-tasks.md
+++ /dev/null
@@ -1,230 +0,0 @@
-# Scheduled Tasks And Turn Pipeline
-
-## Background
-- Vibe Remote already has a mature session mapping model: `session_scope -> agent -> base_session_id -> native_session_id`.
-- The current inbound path mixes two concerns inside `handle_user_message()`:
- - Session semantics: which conversation this input belongs to.
- - IM behavior: whether replies should go to a thread, a newly created Discord thread, or a flat DM channel.
-- Product requirement for scheduled tasks is stricter than a generic background prompt runner:
- - A scheduled task must behave like "the user said this prompt under this session key".
- - The product logic must remain equivalent to manual usage.
- - Thread-capable and flat conversations intentionally behave differently.
-
-## Goal
-Add `vibe task ...` so users or agents can create one-off or cron-based scheduled tasks that inject prompts into existing Vibe Remote conversations without creating a parallel scheduler-only conversation model.
-
-## Status
-- Implemented in this worktree:
- - `vibe task add/list/show/pause/resume/rm`
- - persisted `scheduled_tasks.json` store
- - controller-owned `ScheduledTaskService` with cron and one-off triggers
- - shared `human` / `scheduled` turn pipeline
- - source-aware Discord turn preparation
- - scheduled top-level anchor aliasing into the existing session map
- - Slack/Lark scheduled-thread reply allowance
-- Explicitly not implemented in this slice:
- - `vibe task run <id>`
- - UI management pages for scheduled tasks
-
-## Product Rules
-
-### External Session Key
-The CLI receives one opaque `session_key` parameter. This is an external CLI contract only; it does not replace the current internal `_get_session_key()` implementation.
-
-Recommended wire format:
-
-```text
-<platform>::channel::<channel_id>
-<platform>::channel::<channel_id>::thread::<thread_id>
-<platform>::user::<user_id>
-<platform>::user::<user_id>::thread::<thread_id>
-```
-
-Examples:
-
-```text
-slack::channel::C123
-slack::channel::C123::thread::1712345678.123
-discord::user::123456789012345678
-```
-
-### Equivalent Manual Behavior
-For a scheduled task with prompt `P` and session key `K`, the effect must be equivalent to the user manually sending message `P` under `K`.
-
-That equivalence is defined by product behavior, not by blindly reusing the current webhook code path.
-
-### Session Behavior By Surface Type
-- Thread-capable surfaces without explicit thread:
- - Each scheduled trigger is a new session.
- - The bot sends results directly to the top-level channel/DM surface.
- - Future human replies to those bot messages must continue that session.
-- Flat surfaces without thread support:
- - The same session key keeps using the same session across triggers.
-- Explicit thread:
- - Scheduled triggers always continue that exact thread/session.
-
-## Design
-
-### 1. Split Turn Processing
-Refactor `MessageHandler.handle_user_message()` into a shared turn-processing pipeline with explicit turn source.
-
-Proposed source types:
-- `human`
-- `scheduled`
-
-Proposed stages:
-1. `ingest_human_turn()` / `ingest_scheduled_turn()`
-2. `prepare_turn_context()`
-3. `resolve_turn_session()`
-4. `dispatch_turn_to_agent()`
-5. `finalize_turn_delivery()`
-
-The shared pipeline owns session semantics. IM-specific reply topology decisions move behind IM hooks instead of remaining hard-coded in adapters.
-
-### 2. Move Reply Topology Out Of Discord Inbound Adapter
-Today Discord eagerly creates a thread in the inbound adapter for non-thread guild messages. That is too early because the correct behavior depends on turn source.
-
-New rule:
-- IM adapters only normalize inbound context.
-- IM clients may expose a hook such as `prepare_turn_context(context, source)` for source-aware reply topology.
-- Discord uses that hook to create a thread only for `human` top-level guild messages.
-- Scheduled top-level turns on Discord do not create a thread before agent execution.
-
-Slack and Lark already encode top-level user messages as thread-root contexts; they can continue to do so for real user messages.
-
-### 3. Preserve Existing Session Store, Add Alias Operations
-Do not introduce a separate scheduler conversation namespace.
-
-Instead, extend the existing session mapping facade with alias-oriented operations:
-- detect whether any stored session exists for a given `session_scope + base_session_id`
-- create alias mappings from one `base_session_id` prefix to another
-- remove provisional aliases after final anchoring
-
-Alias behavior must preserve suffixes used by existing backends:
-- Claude subagents: `base:subagent`
-- OpenCode cwd-scoped keys: `base:/abs/path`
-
-Prefix replacement rule:
-- exact match: `old_base -> new_base`
-- prefixed match: `old_base:<suffix> -> new_base:<suffix>`
-
-### 4. Scheduled Turn Anchoring
-Scheduled top-level turns on thread-capable surfaces need a provisional base before the first bot message exists.
-
-Flow:
-1. Build a provisional `base_session_id` for this scheduled run.
-2. Run the agent using that provisional base.
-3. Every top-level bot message emitted by that run is collected as a potential reply anchor.
-4. Once the backend session mapping exists, alias those emitted message IDs to the same native session in the existing store.
-5. After the turn is finalized, clear the provisional aliases and keep only the real anchors.
-
-Why:
-- Slack/Lark replies will later use the bot message ID as thread root directly.
-- Discord top-level replies require an extra bridge:
- - a human may reply to a scheduled bot message in-channel
- - the system creates a new Discord thread for that human turn
- - if the replied-to message ID is already aliased, the new thread ID can inherit that session
-
-### 5. Scheduled Turn Delivery
-Scheduled turns without explicit thread should deliver top-level messages on thread-capable surfaces.
-
-That is intentionally different from real human top-level messages, where some platforms create or use a thread automatically.
-
-To support this, outbound targeting must become source-aware instead of assuming `context.thread_id` alone defines the correct reply location.
-
-### 6. Session-Key Resolution
-Add a resolver that parses the external CLI session key into:
-- platform
-- scope type: `channel` or `user`
-- scope ID
-- optional explicit thread ID
-
-Then resolve it into an execution context:
-- `session_scope`: current internal scope key used by settings/session maps
-- `delivery_channel_id`: actual channel/chat ID used to send messages
-- `context.user_id`: actual DM user ID for user-scoped conversations, synthetic scheduler user for channel-scoped turns
-- `is_dm`
-- `thread_id`
-
-DM resolution requirements:
-- Slack / Discord can open or send to DM by user ID.
-- Lark must resolve the bound user's `dm_chat_id`.
-- WeChat stays flat and uses the chat/user target already persisted by current settings.
-
-### 7. Mention-Gating Compatibility
-Scheduled-created sessions must remain replyable in channels where mention gating is enabled.
-
-Implemented approach:
-- mark scheduled-created Slack/Lark thread roots under synthetic user `scheduled`
-- allow thread replies when either the real user or `scheduled` has an active thread mark
-- for Discord guild channels, treat a reply to a known scheduled anchor as a valid conversation continuation even without a mention
-- once Discord creates or reuses the thread for that reply, alias the scheduled anchor base onto the real thread base
-
-## CLI Scope
-Initial subcommands:
-- `vibe task add`
-- `vibe task list`
-- `vibe task show <id>`
-- `vibe task pause <id>`
-- `vibe task resume <id>`
-- `vibe task rm <id>`
-- `vibe task run <id>`
-
-Initial scheduling modes:
-- `--cron "<expr>"`
-- `--at "<iso8601>"`
-
-Task inputs:
-- `--session-key "<key>"`
-- `--prompt "..."`
-- `--prompt-file path`
-- `--timezone Asia/Shanghai` (default: local timezone)
-
-## Persistence And Runtime
-- Persist scheduled tasks in `~/.vibe_remote/state/scheduled_tasks.json`.
-- Introduce a `ScheduledTaskStore` with atomic writes and `maybe_reload()` support.
-- Introduce a controller-owned `ScheduledTaskService` started after IM readiness.
-- Use a scheduler library for cron support and task reconciliation on store changes.
-
-## Planned Code Changes
-- `core/handlers/message_handler.py`
- - split turn ingestion and shared processing
- - add scheduled turn entrypoint
-- `core/handlers/session_handler.py`
- - source-aware base session resolution
-- `core/controller.py`
- - wire scheduled task service and top-level turn entrypoints
-- `core/message_dispatcher.py`
- - expose sent message IDs to scheduled anchor tracking
-- `modules/im/base.py`
- - add source-aware turn-context preparation hook
-- `modules/im/discord.py`
- - remove eager thread creation from raw inbound adapter
- - move Discord thread creation into the new hook
- - bridge replied-to scheduled bot message -> new thread session alias
-- `modules/im/slack.py`
- - mention-gating fallback for stored session anchors
-- `modules/im/feishu.py`
- - mention-gating fallback if needed for scheduled thread roots
-- `modules/sessions_facade.py`
- - alias helpers and stored-session existence helpers
-- `vibe/cli.py`
- - `task` command group
-- `config/` or `core/`
- - scheduled task store / session key parsing module
-- `tests/`
- - session-key parsing
- - scheduled turn session behavior
- - Discord source-aware thread behavior
- - alias migration and mention-gating fallback
-
-## Implementation Todos
-- [x] Add scheduled-task persistence and session-key parser.
-- [x] Introduce source-aware turn pipeline and scheduled turn entrypoint.
-- [x] Move Discord eager thread creation into handler-driven preprocessing.
-- [x] Add alias operations to existing session facade.
-- [x] Add scheduled anchor tracking and alias finalization.
-- [x] Add `vibe task` CLI.
-- [x] Add scheduled runtime service with cron and one-off triggers.
-- [x] Add focused tests.
-- [x] Run relevant lint/tests/build checks.
diff --git a/docs/plans/task-delivery-key.md b/docs/plans/task-delivery-key.md
deleted file mode 100644
index 8d0ba581c..000000000
--- a/docs/plans/task-delivery-key.md
+++ /dev/null
@@ -1,41 +0,0 @@
-# Task Delivery Target Split
-
-## Background
-
-`vibe task add` and `vibe hook send` currently use one `session_key` for both:
-
-- session continuity
-- outbound delivery target
-
-That breaks cases where the agent should keep a thread-backed session for memory, but publish each result to the parent channel.
-
-## Goal
-
-Keep command usage simple while allowing delivery to be decoupled from session reuse:
-
-- keep `--session-key` as the memory/session target
-- add `--post-to thread|channel` for the common delivery choice
-- add `--deliver-key <session-key>` for advanced delivery overrides
-
-`--deliver-key` should be documented in CLI help and skill docs, but not in injected prompt guidance.
-
-## Solution
-
-1. Extend stored task/request payloads with delivery fields.
-2. Resolve two targets at runtime:
- - session target from `session_key`
- - delivery target from `deliver_key` or `post_to`
-3. Preserve the original thread-backed base session when running the turn.
-4. Apply delivery override only in dispatcher send contexts.
-5. When a scheduled result is delivered as a top-level message, alias that sent message back to the same native session so follow-up replies continue the session.
-
-## Todo
-
-- Add `post_to` / `deliver_key` to task models, queue requests, CLI, and JSON output.
-- Implement delivery override context building in `ScheduledTaskService`.
-- Update dispatcher/session finalization to use delivery override without breaking session reuse.
-- Add focused tests for:
- - CLI parsing and persistence
- - delivery override context building
- - scheduled finalization alias behavior for top-level deliveries
-- Update help text and skill docs.
diff --git a/docs/plans/task-management-polish.md b/docs/plans/task-management-polish.md
deleted file mode 100644
index bbd5cd109..000000000
--- a/docs/plans/task-management-polish.md
+++ /dev/null
@@ -1,26 +0,0 @@
-# Task Management Polish
-
-## Background
-
-Recent task/hook work added session and delivery target separation, but task management is still awkward in three areas:
-
-- stored tasks cannot be updated in place
-- add/send validation only checks syntax, not obvious delivery reachability risks
-- list/show output is still too close to raw storage payloads
-
-## Goal
-
-Improve the existing task CLI without breaking current task execution behavior.
-
-## Solution
-
-1. Add `vibe task update <id>` for partial in-place task edits.
-2. Add non-blocking reachability warnings for obviously risky targets, starting with Lark DM users that lack `dm_chat_id` binding.
-3. Enrich `task list` / `task show` with scheduling-oriented derived fields and add `task list --brief`.
-
-## Notes
-
-- Preserve existing task IDs during update.
-- Keep `task add` / `hook send` successful when a risk is only a warning.
-- Preserve existing raw task fields in default JSON output; only add derived fields on top.
-- Keep prompt injection unchanged for this follow-up.
diff --git a/docs/plans/task-run-hook.md b/docs/plans/task-run-hook.md
deleted file mode 100644
index f59ef7315..000000000
--- a/docs/plans/task-run-hook.md
+++ /dev/null
@@ -1,36 +0,0 @@
-# Task Run And Hook Send
-
-## Background
-
-Vibe Remote already supports persisted scheduled tasks through `vibe task add`, but it lacks:
-
-- an immediate rerun command for an existing task definition
-- a one-shot asynchronous hook command for scripts and long-running workflows
-
-The service runtime and CLI are separate processes, so these new commands need a lightweight IPC path instead of direct controller access from the CLI.
-
-## Goal
-
-Add two user-facing commands:
-
-- `vibe task run <id>`: queue an immediate execution of an existing stored task
-- `vibe hook send --session-key ... --prompt ...`: queue a one-shot asynchronous turn without storing a task
-
-Keep prompt guidance concise and keep session behavior identical to the current scheduled-turn pipeline.
-
-## Solution
-
-Introduce a small request queue under `~/.vibe_remote/state/task_requests/`:
-
-- CLI commands write JSON requests into `pending/`
-- `ScheduledTaskService` polls and claims requests
-- claimed requests move to `processing/`
-- finished requests write receipts to `completed/`
-
-Both new commands reuse the existing scheduled-turn execution path, so they inherit the same session and IM behavior.
-
-## Notes
-
-- `task run` updates `last_run_at` and `last_error` but does not disable one-shot tasks
-- `hook send` does not persist anything into `scheduled_tasks.json`
-- prompt guidance should mention `task add`, `task run`, and `hook send`, but defer full syntax details to `--help`
diff --git a/docs/plans/vibe-agent-catalog.md b/docs/plans/vibe-agent-catalog.md
new file mode 100644
index 000000000..c504dd8f9
--- /dev/null
+++ b/docs/plans/vibe-agent-catalog.md
@@ -0,0 +1,513 @@
+# Vibe Agent Catalog
+
+## Background
+
+Vibe Remote currently treats "agent" mostly as backend-specific routing data:
+
+- `agent_backend`
+- `opencode_agent`
+- `opencode_model`
+- `opencode_reasoning_effort`
+- `claude_agent`
+- `claude_model`
+- `claude_reasoning_effort`
+- `codex_agent`
+- `codex_model`
+- `codex_reasoning_effort`
+
+That was useful while each backend had a different subagent model, but it is not
+the right product abstraction. Scope is becoming the durable project/workspace
+unit in Vibe Remote. Each scope should select one Vibe-owned Agent, and that
+Agent should define how work is handled.
+
+This plan introduces a Vibe Agent catalog as a first-class data model and CLI
+surface.
+
+## Goals
+
+- Add a Vibe-owned Agent data structure.
+- Let scopes select an Agent by name.
+- Move backend, model, effort, description, and system prompt into Agent
+ definitions.
+- Add `vibe agent` commands for CRUD and import.
+- Support importing existing global agents from Claude Code, Codex, and
+ OpenCode.
+- Stop treating backend-native subagents as scope routing fields.
+- Keep the run definition/session design simple: new sessions resolve their
+ runtime target from the scope's configured Vibe Agent.
+
+## Scope
+
+This plan covers the Agent catalog, scope-to-Agent resolution, and import
+workflow. Backend/model/effort are owned by Agent definitions; task, watch, and
+run commands select Agents by name.
+
+Imported agents become Vibe-owned Agent definitions. They keep source metadata
+for traceability, but they are not live-linked to the original backend files in
+V1.
+
+## Core Data Model
+
+### Agent
+
+Minimum persisted shape:
+
+```text
+agents
+ id
+ name
+ description
+ backend
+ model
+ reasoning_effort
+ system_prompt
+ source
+ source_ref
+ metadata_json
+ created_at
+ updated_at
+```
+
+Field semantics:
+
+| Field | Meaning |
+| --- | --- |
+| `id` | Stable internal id. Can be UUID/short id; not the user-facing selector. |
+| `name` | Unique Vibe Agent name used by scopes and CLI. |
+| `description` | Human-readable purpose and selection guidance. |
+| `backend` | `opencode`, `claude`, or `codex`. |
+| `model` | Backend model override for this Agent; nullable means backend default. |
+| `reasoning_effort` | Backend effort/reasoning override; nullable means backend default. |
+| `system_prompt` | Vibe-owned system prompt appended or injected into backend runtime. |
+| `source` | `manual`, `imported_claude`, `imported_codex`, `imported_opencode`, etc. |
+| `source_ref` | Original source path/name/id for imported agents. |
+| `metadata_json` | Extension data such as tools, import details, or backend-specific hints. |
+| `created_at` | Agent creation timestamp. |
+| `updated_at` | Latest Agent update timestamp. |
+
+Name rules:
+
+- Names are case-insensitive for lookup.
+- Store a normalized name for uniqueness.
+- Recommended display names may preserve user casing, but the CLI selector
+ should be stable and shell-friendly.
+- Names should not encode backend. Backend is a field, not part of identity.
+- Names are globally unique. Scope-private Agents are not a Vibe-layer concept;
+ backend-specific private/subagent behavior remains owned by the backend.
+
+### Scope Routing
+
+Scope settings should move toward:
+
+```text
+scope_settings
+ scope_id
+ agent_name
+ workdir
+ enabled
+ require_mention
+ display settings...
+```
+
+The existing `agent_backend` and backend-specific agent/model/effort fields are
+replaced conceptually by one `agent_name` reference.
+
+Resolution rules:
+
+1. If a command explicitly passes `--agent <name>`, load that Vibe Agent.
+2. Otherwise, resolve the incoming or delivery `scope_id`.
+3. Load `scope_settings.agent_name`.
+4. Load the named Vibe Agent.
+5. Use Agent backend/model/effort/system prompt for the turn.
+6. Use scope workdir unless a future Agent model explicitly owns cwd.
+
+If a scope has no selected Agent and no command-level `--agent` was provided,
+fall back to a system default Agent. The system default should be explicit in
+config/state, not inferred from scattered backend defaults forever.
+
+### System Default Agent
+
+Fresh installs and migrations should have an explicit system default Agent:
+
+```text
+default_agent_name -> agents.name
+```
+
+The first version should create an Agent row named `default` and point
+`default_agent_name` to it. Its backend/model/effort can be generated once from
+the currently enabled global backend defaults. Runtime should not keep
+dynamically synthesizing Agents from legacy backend-specific Scope fields.
+
+Because Agent `name` and `backend` are immutable, changing the system default
+backend later should create another Agent and move `default_agent_name` to that
+Agent. This keeps default behavior as first-class Agent configuration instead
+of hidden fallback logic.
+
+### Agent Sessions
+
+`agent_sessions` should store the resolved Vibe Agent identity:
+
+```text
+agent_sessions
+ agent_name
+ agent_id
+ agent_backend
+ model
+ reasoning_effort
+ ...
+```
+
+`agent_backend`, `model`, and `reasoning_effort` remain useful snapshots for
+history/debugging even when the source of truth is the Agent definition.
+
+Existing sessions should use the latest Agent definition on future turns.
+Because `name` and `backend` are immutable, live updates can change prompt,
+model, effort, description, and metadata without changing the backend family of
+an established session.
+
+## CLI Design
+
+### Command Family
+
+```bash
+vibe agent list
+vibe agent show <name>
+vibe agent create ...
+vibe agent update <name> ...
+vibe agent remove <name>
+vibe agent import ...
+```
+
+The command family manages Vibe Agent definitions. Direct/manual execution lives
+under `vibe agent run` and is covered by `agent-run-harness.md`.
+
+### `vibe agent list`
+
+Purpose: list Vibe Agents available for scope routing and session creation.
+
+Suggested flags:
+
+```bash
+vibe agent list
+vibe agent list --backend codex
+vibe agent list --json
+```
+
+Output fields:
+
+- name;
+- description preview;
+- backend;
+- model;
+- reasoning effort;
+- source;
+- updated time.
+
+### `vibe agent show`
+
+Purpose: inspect one full Agent definition.
+
+```bash
+vibe agent show release-reviewer
+```
+
+Output should include full system prompt unless a future `--redact-prompt` flag
+is needed. System prompts are user-authored configuration, not secrets by
+default.
+
+### `vibe agent create`
+
+Purpose: create a Vibe Agent manually.
+
+Candidate shape:
+
+```bash
+vibe agent create release-reviewer \
+ --backend codex \
+ --description "Reviews release diffs and deployment risk." \
+ --model gpt-5.4 \
+ --effort high \
+ --system-prompt-file agents/release-reviewer.md
+```
+
+Notes:
+
+- `--backend` is required.
+- `--description` is recommended.
+- `--model` and `--effort` are optional.
+- System prompt can come from `--system-prompt` or `--system-prompt-file`.
+- If no prompt is provided, the Agent is still valid but uses only backend
+ defaults and Vibe Remote's standard prompt injection.
+
+### `vibe agent update`
+
+Purpose: modify an Agent definition without changing the selected scopes.
+
+Candidate shape:
+
+```bash
+vibe agent update release-reviewer --model gpt-5.5
+vibe agent update release-reviewer --effort xhigh
+vibe agent update release-reviewer --description "..."
+vibe agent update release-reviewer --system-prompt-file agents/release-reviewer.md
+```
+
+Update rules:
+
+- `name` cannot be changed.
+- `backend` cannot be changed.
+- `description`, `model`, `reasoning_effort`, `system_prompt`, and metadata can
+ be changed.
+- Existing sessions resolve the latest Agent definition immediately, so edits
+ affect future turns in already-created sessions.
+
+### `vibe agent remove`
+
+Purpose: remove a Vibe Agent definition.
+
+Rules:
+
+- Refuse removal if any scope references the Agent unless `--force` is passed.
+- With `--force`, affected scopes should be moved to the default Agent or left
+ unset with a warning. The better first implementation is to refuse and require
+ explicit reassignment.
+
+### `vibe agent import`
+
+Purpose: import existing backend-native global agents into the Vibe Agent
+catalog.
+
+Candidate commands:
+
+```bash
+vibe agent import --from claude
+vibe agent import --from codex
+vibe agent import --from opencode
+vibe agent import --from claude --name reviewer
+vibe agent import --from codex --all
+vibe agent import --file reviewer.md --backend codex
+```
+
+Import rules:
+
+- Import should read global agent definitions from the backend's normal global
+ agent location for `--from`.
+- V1 imports global agents only. Project-local agents are out of scope.
+- `--file <path>` imports one explicit file in the common markdown-with-header
+ format. Because that file is backend-neutral at the path level, `--backend`
+ is required with `--file`.
+- Imported Vibe Agent names should be unique. On conflict, skip the import and
+ report the skipped name clearly.
+- Imported definitions become Vibe-owned copies.
+- Source metadata should record backend, original name, and original path/id.
+- Backend-specific tool permissions should be stored in `metadata_json` only.
+ V1 does not enforce them.
+
+Backend mapping:
+
+| Source | Expected fields |
+| --- | --- |
+| Claude Code global agent | name, description, system prompt, optional model/tools metadata |
+| Codex global agent | name, description, developer instructions/system prompt, optional model/effort |
+| OpenCode global agent | name, description, prompt/instructions, optional model metadata |
+
+The exact parsing should reuse existing discovery/parsing helpers where
+available, but the persisted output should be backend-neutral.
+
+## UI And Scope Settings
+
+The UI and IM settings flows should stop exposing separate backend-native
+subagent dropdowns as the main routing model.
+
+New shape:
+
+- Agent selector: one Vibe Agent dropdown.
+- Agent detail preview: description, backend, model, effort.
+- Workdir remains a scope setting.
+- Backend credential/config availability remains global backend configuration.
+
+This makes scope configuration easier to explain:
+
+```text
+Scope = project/workspace.
+Agent = how this scope should think and act.
+Session = one ongoing conversation/run under that scope and Agent.
+```
+
+## Runtime Behavior
+
+### Human Messages
+
+For a human turn:
+
+1. Resolve scope.
+2. Resolve configured Vibe Agent.
+3. Build `AgentRequest` with:
+ - `agent_name` or `vibe_agent_name`;
+ - backend;
+ - model;
+ - reasoning effort;
+ - system prompt.
+4. Route to the backend selected by the Agent.
+
+Prefix-triggered quick switching should target Vibe Agent names if it is added
+later. Routing is based on Vibe Agent resolution, not backend-native subagent
+prefix parsing.
+
+### Background New Sessions
+
+For `--create-session --deliver-key <scope-id>`:
+
+1. Resolve `scope_id`.
+2. Resolve scope's Vibe Agent.
+3. Reserve or create `agent_sessions.id`.
+4. Store the resolved Agent identity on the session.
+5. Execute the first turn through that Agent.
+6. Return the new `session_id` in command output.
+
+For `--create-session-per-run`, repeat that flow for each run.
+
+### Existing Sessions
+
+For `--session-id <id>`:
+
+1. Load the existing session.
+2. Use the session's stored Agent identity to load the current Agent definition.
+3. Apply the latest Agent prompt/model/effort on future turns.
+
+This gives users a simple mental model: editing a Vibe Agent changes how that
+Agent behaves everywhere it is selected, including existing sessions.
+
+### System Prompt Composition
+
+The Agent system prompt replaces backend-native subagent prompt selection at the
+Vibe routing layer. Vibe Remote should inject:
+
+```text
+agent_system_prompt + vibe_remote_instructions
+```
+
+through the same prompt injection point already used for Vibe Remote
+instructions. Backend-native default prompts still exist underneath the backend.
+Vibe Remote uses the selected Vibe Agent's system prompt as its owned prompt
+layer.
+
+## Output Contract
+
+`vibe agent` commands should use the same JSON style as the planned background
+commands.
+
+Create output:
+
+```json
+{
+ "ok": true,
+ "agent": {
+ "name": "release-reviewer",
+ "description": "Reviews release diffs and deployment risk.",
+ "backend": "codex",
+ "model": "gpt-5.4",
+ "reasoning_effort": "high",
+ "source": "manual",
+ "updated_at": "2026-05-19T15:00:00+00:00"
+ },
+ "warnings": []
+}
+```
+
+Import output:
+
+```json
+{
+ "ok": true,
+ "imported": [
+ {
+ "name": "reviewer",
+ "backend": "codex",
+ "source": "imported_codex",
+ "source_ref": "~/.codex/agents/reviewer.md"
+ }
+ ],
+ "skipped": [],
+ "warnings": []
+}
+```
+
+List output:
+
+```json
+{
+ "agents": [
+ {
+ "name": "release-reviewer",
+ "description": "Reviews release diffs and deployment risk.",
+ "backend": "codex",
+ "model": "gpt-5.4",
+ "reasoning_effort": "high",
+ "source": "manual",
+ "updated_at": "2026-05-19T15:00:00+00:00"
+ }
+ ]
+}
+```
+
+## Storage Options
+
+### Preferred
+
+Add SQLite tables:
+
+```text
+agents
+scope_settings.agent_name
+agent_sessions.agent_id / agent_name snapshot fields
+```
+
+This aligns with the direction that scopes and sessions already live in SQLite.
+
+### Compatibility Window
+
+The existing JSON settings shape can keep its old fields during the transition,
+but new code should treat `agent_name` as the source of truth.
+
+No migration is required for old backend-native agent fields per product
+decision. Existing users may need to select/import/create Vibe Agents again.
+
+## Relationship To Existing Plans
+
+- `agent-run-harness.md`: background/direct `--create-session` resolves the
+ runtime target through the scope's Vibe Agent, then records actual execution
+ in `agent_runs`.
+- `agent-run-harness.md`: `vibe agent run` is the direct/manual execution
+ surface. It consumes Vibe Agent definitions from this catalog instead of
+ accepting backend/model/effort overrides.
+- Delivery targeting is owned by `agent-run-harness.md`: `--deliver-key`
+ becomes `scopes.id`, not a legacy session key.
+
+## Implementation Slices
+
+1. Add Agent storage model and CRUD service.
+2. Add `vibe agent list/show/create/update/remove`.
+3. Add import discovery for one backend first, then Claude/Codex/OpenCode.
+4. Add `scope_settings.agent_name` and scope routing resolution.
+5. Update runtime message routing to resolve Vibe Agents.
+6. Update UI/IM settings to select Vibe Agents.
+7. Update background session creation to use scope Agent resolution.
+8. Remove old backend-native agent routing from primary UI/docs.
+
+## Specification Summary
+
+1. Agent names are globally unique.
+2. Agent edits affect existing sessions immediately.
+3. Agent `name` and `backend` are immutable; other fields are editable.
+4. The Agent system prompt is prepended before Vibe Remote instructions at the
+ existing prompt injection point.
+5. Imported backend-specific tool permissions are stored in `metadata_json` only
+ and are not enforced in V1.
+6. `vibe agent import --from ...` imports global agents only in V1.
+7. Import name conflicts are skipped and reported.
+8. `vibe agent import --file <path> --backend <backend>` imports one explicit
+ markdown-with-header file.
+9. Fresh installs and migrations should create an explicit system default Agent
+ and reference it through `default_agent_name`; runtime should not synthesize
+ legacy backend default Agents dynamically.
diff --git a/docs/plans/vibe-agent-catalog.zh.md b/docs/plans/vibe-agent-catalog.zh.md
new file mode 100644
index 000000000..4fef77066
--- /dev/null
+++ b/docs/plans/vibe-agent-catalog.zh.md
@@ -0,0 +1,489 @@
+# Vibe Agent Catalog
+
+## 背景
+
+Vibe Remote 现在基本把 “agent” 当作 backend-specific routing 数据处理:
+
+- `agent_backend`
+- `opencode_agent`
+- `opencode_model`
+- `opencode_reasoning_effort`
+- `claude_agent`
+- `claude_model`
+- `claude_reasoning_effort`
+- `codex_agent`
+- `codex_model`
+- `codex_reasoning_effort`
+
+这在每个 backend 都有不同 subagent 模型时是可用的,但不是正确的产品抽象。
+Scope 正在成为 Vibe Remote 里稳定的 project/workspace 单元。每个 Scope
+应该选择一个 Vibe Remote 自己拥有的 Agent,由这个 Agent 定义工作方式。
+
+这份计划把 Vibe Agent catalog 作为一等数据结构和 CLI 能力引入。
+
+## 目标
+
+- 增加 Vibe-owned Agent 数据结构。
+- 让 Scope 通过名称选择一个 Agent。
+- 将 backend、model、effort、description、system prompt 移入 Agent 定义。
+- 增加 `vibe agent` 命令,用于增删改查和导入。
+- 支持从 Claude Code、Codex、OpenCode 导入已有全局 Agent。
+- 停止把 backend-native subagent 当作 Scope routing 字段。
+- 保持 run definition/session 设计简单:新 Session 从 Scope 配置的 Vibe
+ Agent 解析运行时目标。
+
+## 范围
+
+这份计划覆盖 Agent catalog、Scope-to-Agent resolution 和导入流程。
+backend/model/effort 由 Agent 定义持有;task、watch 和 run 命令通过名称选择
+Agent。
+
+导入的 Agent 会成为 Vibe-owned Agent 定义。它们保留 source metadata 便于追踪,
+但 V1 不和原 backend 文件保持实时链接。
+
+## 核心数据模型
+
+### Agent
+
+最小持久化结构:
+
+```text
+agents
+ id
+ name
+ description
+ backend
+ model
+ reasoning_effort
+ system_prompt
+ source
+ source_ref
+ metadata_json
+ created_at
+ updated_at
+```
+
+字段语义:
+
+| 字段 | 含义 |
+| --- | --- |
+| `id` | 稳定内部 ID。可以是 UUID 或短 ID;不是用户选择时使用的名字。 |
+| `name` | 唯一 Vibe Agent 名称,Scope 和 CLI 通过它引用 Agent。 |
+| `description` | 面向人的用途说明和选择提示。 |
+| `backend` | `opencode`、`claude` 或 `codex`。 |
+| `model` | 这个 Agent 的 backend model override;为空表示 backend 默认值。 |
+| `reasoning_effort` | 这个 Agent 的 reasoning/effort override;为空表示 backend 默认值。 |
+| `system_prompt` | Vibe-owned system prompt,追加或注入到 backend runtime。 |
+| `source` | `manual`、`imported_claude`、`imported_codex`、`imported_opencode` 等。 |
+| `source_ref` | 导入 Agent 的原始路径、名称或 ID。 |
+| `metadata_json` | 扩展数据,例如 tools、导入细节或 backend-specific hints。 |
+| `created_at` | Agent 创建时间。 |
+| `updated_at` | Agent 最近更新时间。 |
+
+名称规则:
+
+- 名称查找大小写不敏感。
+- 存储 normalized name 来保证唯一性。
+- 展示名可以保留用户输入大小写,但 CLI selector 应稳定且适合 shell 使用。
+- 名称不应该编码 backend;backend 是字段,不是身份的一部分。
+- 名称全局唯一。Scope 私有 Agent 不由 Vibe 层实现;backend-specific 私有
+ subagent 行为仍然归 backend 自己管理。
+
+### Scope Routing
+
+Scope settings 目标形态:
+
+```text
+scope_settings
+ scope_id
+ agent_name
+ workdir
+ enabled
+ require_mention
+ display settings...
+```
+
+现有 `agent_backend` 和 backend-specific agent/model/effort 字段,在概念上都由
+一个 `agent_name` 引用替代。
+
+解析规则:
+
+1. 如果命令显式传了 `--agent <name>`,加载这个 Vibe Agent。
+2. 否则解析 inbound 或 delivery `scope_id`。
+3. 读取 `scope_settings.agent_name`。
+4. 加载对应 Vibe Agent。
+5. 使用 Agent 的 backend/model/effort/system prompt 执行这次 turn。
+6. 使用 Scope 的 workdir,除非未来 Agent 模型明确接管 cwd。
+
+如果 Scope 没有选择 Agent,且命令也没有显式传 `--agent`,则回退到系统默认
+Agent。系统默认 Agent 应该是 config/state 里的显式对象,而不是长期从分散的
+backend 默认值里推断出来。
+
+### System Default Agent
+
+Fresh install 和 migration 后应存在一个明确的系统默认 Agent:
+
+```text
+default_agent_name -> agents.name
+```
+
+建议第一版创建一个名为 `default` 的 Agent 行,并把 `default_agent_name` 指向
+它。这个 Agent 的 backend/model/effort 可以从当前启用的全局 backend 默认配置
+生成一次;之后运行时不再从旧 backend-specific scope 字段动态合成 Agent。
+
+因为 Agent 的 `name` 和 `backend` 不可修改,如果用户之后想把系统默认 backend
+从 Codex 换成 Claude/OpenCode,应创建另一个 Agent,然后把
+`default_agent_name` 切到新的 Agent。这样默认行为仍然是一等 Agent 配置,而
+不是隐藏 fallback 逻辑。
+
+### Agent Sessions
+
+`agent_sessions` 应保存已解析的 Vibe Agent 身份:
+
+```text
+agent_sessions
+ agent_name
+ agent_id
+ agent_backend
+ model
+ reasoning_effort
+ ...
+```
+
+即使 Agent 定义是源头,`agent_backend`、`model`、`reasoning_effort` 作为历史
+和调试快照仍然有价值。
+
+已有 Session 后续 turn 应读取 Agent 定义的最新版本。因为 `name` 和 `backend`
+不可变,live update 可以改变 prompt、model、effort、description 和 metadata,
+但不会改变一个已建立 Session 的 backend family。
+
+## CLI 设计
+
+### 命令族
+
+```bash
+vibe agent list
+vibe agent show <name>
+vibe agent create ...
+vibe agent update <name> ...
+vibe agent remove <name>
+vibe agent import ...
+```
+
+这个命令族管理 Vibe Agent 定义。direct/manual execution 放在
+`vibe agent run`,由 `agent-run-harness.md` 覆盖。
+
+### `vibe agent list`
+
+用途:列出可用于 Scope routing 和 Session 创建的 Vibe Agents。
+
+建议参数:
+
+```bash
+vibe agent list
+vibe agent list --backend codex
+vibe agent list --json
+```
+
+输出字段:
+
+- name;
+- description preview;
+- backend;
+- model;
+- reasoning effort;
+- source;
+- updated time。
+
+### `vibe agent show`
+
+用途:查看一个完整 Agent 定义。
+
+```bash
+vibe agent show release-reviewer
+```
+
+输出应包含完整 system prompt,除非未来需要 `--redact-prompt`。System prompt
+是用户配置,不默认当作 secret。
+
+### `vibe agent create`
+
+用途:手动创建一个 Vibe Agent。
+
+候选形态:
+
+```bash
+vibe agent create release-reviewer \
+ --backend codex \
+ --description "Reviews release diffs and deployment risk." \
+ --model gpt-5.4 \
+ --effort high \
+ --system-prompt-file agents/release-reviewer.md
+```
+
+说明:
+
+- `--backend` 必填。
+- `--description` 推荐填写。
+- `--model` 和 `--effort` 可选。
+- System prompt 可以来自 `--system-prompt` 或 `--system-prompt-file`。
+- 如果不提供 prompt,Agent 仍然有效,但只使用 backend 默认值和 Vibe Remote
+ 标准 prompt injection。
+
+### `vibe agent update`
+
+用途:修改 Agent 定义,不改变已选择它的 Scope。
+
+候选形态:
+
+```bash
+vibe agent update release-reviewer --model gpt-5.5
+vibe agent update release-reviewer --effort xhigh
+vibe agent update release-reviewer --description "..."
+vibe agent update release-reviewer --system-prompt-file agents/release-reviewer.md
+```
+
+更新规则:
+
+- `name` 不允许修改。
+- `backend` 不允许修改。
+- `description`、`model`、`reasoning_effort`、`system_prompt` 和 metadata 允许修改。
+- 已有 Session 会立即读取最新 Agent 定义,所以编辑会影响已创建 Session 的后续 turn。
+
+### `vibe agent remove`
+
+用途:删除一个 Vibe Agent 定义。
+
+规则:
+
+- 如果还有 Scope 引用该 Agent,则拒绝删除,除非传 `--force`。
+- 使用 `--force` 时,受影响 Scope 应该迁移到默认 Agent,或置空并给出警告。
+ 更好的第一版实现是拒绝删除,并要求显式重分配。
+
+### `vibe agent import`
+
+用途:把 backend-native 全局 Agent 导入 Vibe Agent catalog。
+
+候选命令:
+
+```bash
+vibe agent import --from claude
+vibe agent import --from codex
+vibe agent import --from opencode
+vibe agent import --from claude --name reviewer
+vibe agent import --from codex --all
+vibe agent import --file reviewer.md --backend codex
+```
+
+导入规则:
+
+- `--from` 从 backend 的正常全局 Agent 位置读取定义。
+- V1 只导入 global agents,不导入 project-local agents。
+- `--file <path>` 导入一个显式文件,格式是通用 markdown-with-header。
+ 因为仅从文件路径无法判断 backend,`--file` 必须同时传 `--backend`。
+- 导入后的 Vibe Agent 名称必须唯一。冲突时跳过并清晰报告被跳过的名称。
+- 导入结果是 Vibe-owned copy。
+- source metadata 记录 backend、原始名称、原始路径或 ID。
+- Backend-specific tool permissions 只保存到 `metadata_json`,V1 不执行这些权限。
+
+Backend 映射:
+
+| 来源 | 预期字段 |
+| --- | --- |
+| Claude Code global agent | name、description、system prompt、可选 model/tools metadata |
+| Codex global agent | name、description、developer instructions/system prompt、可选 model/effort |
+| OpenCode global agent | name、description、prompt/instructions、可选 model metadata |
+
+具体解析应尽量复用现有 discovery/parsing helper,但持久化结果应该是
+backend-neutral 的。
+
+## UI 和 Scope Settings
+
+UI 和 IM settings flow 应该停止把多个 backend-native subagent dropdown 作为
+主要 routing 模型。
+
+新形态:
+
+- Agent selector:一个 Vibe Agent 下拉框。
+- Agent detail preview:description、backend、model、effort。
+- Workdir 仍然是 Scope 设置。
+- Backend credential/config availability 仍然是全局 backend 配置。
+
+这让 Scope 配置更容易解释:
+
+```text
+Scope = project/workspace.
+Agent = how this scope should think and act.
+Session = one ongoing conversation/run under that scope and Agent.
+```
+
+## Runtime 行为
+
+### Human Messages
+
+一次 human turn:
+
+1. 解析 Scope。
+2. 解析该 Scope 配置的 Vibe Agent。
+3. 构造 `AgentRequest`,包含:
+ - `agent_name` 或 `vibe_agent_name`;
+ - backend;
+ - model;
+ - reasoning effort;
+ - system prompt。
+4. 路由到 Agent 选择的 backend。
+
+如果未来需要 prefix-triggered 快速切换,应按 Vibe Agent 名称切换。Routing
+基于 Vibe Agent resolution,而不是 backend-native subagent prefix parsing。
+
+### Background New Sessions
+
+对于 `--create-session --deliver-key <scope-id>`:
+
+1. 解析 `scope_id`。
+2. 解析 Scope 的 Vibe Agent。
+3. 预留或创建 `agent_sessions.id`。
+4. 把 resolved Agent identity 存到 Session。
+5. 用这个 Agent 执行第一轮 turn。
+6. 在命令输出里返回新的 `session_id`。
+
+对 `--create-session-per-run`,每次 run 都重复这个流程。
+
+### Existing Sessions
+
+对于 `--session-id <id>`:
+
+1. 加载已有 Session。
+2. 使用 Session 里存储的 Agent identity 加载当前 Agent 定义。
+3. 后续 turn 应用最新的 Agent prompt/model/effort。
+
+这样用户心智更简单:编辑一个 Vibe Agent,会改变所有选择该 Agent 的地方,
+包括已有 Session 的后续行为。
+
+### System Prompt 组合
+
+Agent system prompt 在 Vibe routing 层替代 backend-native subagent prompt 选择。
+Vibe Remote 应该在现有 prompt injection 点注入:
+
+```text
+agent_system_prompt + vibe_remote_instructions
+```
+
+Backend-native 默认 prompt 仍然存在于 backend 底层。Vibe Remote 使用选中的
+Vibe Agent system prompt 作为自己拥有的 prompt 层。
+
+## 输出契约
+
+`vibe agent` 命令应该使用和后台命令计划一致的 JSON 风格。
+
+Create 输出:
+
+```json
+{
+ "ok": true,
+ "agent": {
+ "name": "release-reviewer",
+ "description": "Reviews release diffs and deployment risk.",
+ "backend": "codex",
+ "model": "gpt-5.4",
+ "reasoning_effort": "high",
+ "source": "manual",
+ "updated_at": "2026-05-19T15:00:00+00:00"
+ },
+ "warnings": []
+}
+```
+
+Import 输出:
+
+```json
+{
+ "ok": true,
+ "imported": [
+ {
+ "name": "reviewer",
+ "backend": "codex",
+ "source": "imported_codex",
+ "source_ref": "~/.codex/agents/reviewer.md"
+ }
+ ],
+ "skipped": [],
+ "warnings": []
+}
+```
+
+List 输出:
+
+```json
+{
+ "agents": [
+ {
+ "name": "release-reviewer",
+ "description": "Reviews release diffs and deployment risk.",
+ "backend": "codex",
+ "model": "gpt-5.4",
+ "reasoning_effort": "high",
+ "source": "manual",
+ "updated_at": "2026-05-19T15:00:00+00:00"
+ }
+ ]
+}
+```
+
+## 存储方案
+
+### 推荐方案
+
+增加 SQLite 表和字段:
+
+```text
+agents
+scope_settings.agent_name
+agent_sessions.agent_id / agent_name snapshot fields
+```
+
+这和 scopes、sessions 已经进入 SQLite 的方向一致。
+
+### 兼容窗口
+
+现有 JSON settings 形态可以在过渡期保留旧字段,但新代码应把 `agent_name`
+作为 source of truth。
+
+根据产品决策,旧 backend-native agent 字段不需要迁移。已有用户可能需要重新
+选择、导入或创建 Vibe Agents。
+
+## 和已有计划的关系
+
+- `agent-run-harness.md`:后台/direct `--create-session` 通过 Scope 的 Vibe
+ Agent 解析 runtime target,然后把实际执行记录到 `agent_runs`。
+- `agent-run-harness.md`:`vibe agent run` 是 direct/manual execution 入口。
+ 它消费本 catalog 里的 Vibe Agent 定义,而不是接受 backend/model/effort
+ override 参数。
+- Delivery targeting 由 `agent-run-harness.md` 负责:`--deliver-key` 变成
+ `scopes.id`,不是 legacy session key。
+
+## 实施切片
+
+1. 增加 Agent storage model 和 CRUD service。
+2. 增加 `vibe agent list/show/create/update/remove`。
+3. 先为一个 backend 增加 import discovery,再扩展 Claude/Codex/OpenCode。
+4. 增加 `scope_settings.agent_name` 和 Scope routing 解析。
+5. 更新 runtime message routing,让它解析 Vibe Agents。
+6. 更新 UI/IM settings,让用户选择 Vibe Agents。
+7. 更新 background session creation,让它使用 Scope Agent resolution。
+8. 从主要 UI/docs 移除旧 backend-native agent routing。
+
+## 规范摘要
+
+1. Agent name 全局唯一。
+2. Agent 编辑立即影响已有 Session。
+3. Agent 的 `name` 和 `backend` 不可修改;其他字段允许修改。
+4. Agent system prompt 在现有 prompt injection 点拼到 Vibe Remote instructions
+ 前面。
+5. 导入的 backend-specific tool permissions 只保存到 `metadata_json`,V1 不执行。
+6. `vibe agent import --from ...` V1 只导入 global agents。
+7. 导入时名称冲突则 skip,并报告出来。
+8. `vibe agent import --file <path> --backend <backend>` 导入一个显式
+ markdown-with-header 文件。
+9. Fresh install/migration 应创建显式系统默认 Agent,并用
+ `default_agent_name` 指针引用;运行时不动态合成旧式 backend 默认 Agent。