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.

feat(harness): give a command task an addressable working directory, and an honest escalation pane (#1159)

Qi Qi0bfc78b99ec7
diff --git a/docs/CLI.md b/docs/CLI.md
index ae6413a64..9a6a7bb1c 100644
--- a/docs/CLI.md
+++ b/docs/CLI.md
@@ -241,8 +241,8 @@ Use `vibe task add --help` and `vibe task update --help` for the full command su
- `--cron` and `--at` scheduling
- `--name`, `--timezone`, and message file support
- `--shell` / trailing `-- <argv>` for a scheduled command with no Agent turn,
- with `--on-failure {none,agent}` and a per-run `--timeout` (default 21600
- seconds, 0 = none)
+ with `--on-failure {none,agent}`, a per-run `--timeout` (default 21600
+ seconds, 0 = none), and `--cwd` for the directory the command runs in
When `vibe task add` runs inside an Avibe-injected Agent shell, `--session-id`
may be omitted. Avibe defaults the task target to the caller Session from
@@ -255,8 +255,27 @@ a failed run records a durable failure notice naming the command and its exit
code. With `--on-failure agent --message '<instructions>'` the failure instead
starts one Agent turn carrying the failure report, and that turn replaces the
notice for the run. `vibe task update` can change a command task's `--shell`,
-argv, or `--timeout`, but switching a task between message and command form, or
-changing `--on-failure`, is rejected — remove the task and recreate it.
+argv, `--timeout`, or `--cwd`, but switching a task between message and command
+form, or changing `--on-failure`, is rejected — remove the task and recreate it.
+
+`--cwd` is where the command runs. What else it touches depends on whether the
+definition also *creates* a Session:
+
+- Bound to an existing Session (`--session-id`, or the caller-session default),
+ or to a reusable one already reserved: the flag is the command's alone. The
+ escalation Session keeps its own working directory, which is the case the flag
+ was added for — a command task binds to a Session so `--on-failure agent` has
+ somewhere to land, not to say where it runs.
+- Creating one (`--create-session`, `--create-session-per-run`): the flag places
+ that Session too, so the escalation turn runs where the command does. Pass a
+ scope instead (`--same-scope` / `--scope-id`) and omit `--cwd` if you want the
+ Session to inherit its directory.
+
+Without the flag, a Session-bound command follows that Session's directory —
+read live at fire time, so `/setcwd` on that conversation relocates the job —
+and every other command records the directory you ran `vibe task add` from. For
+a message task `--cwd` still places the Session it creates, and is still refused
+for one that already exists.
`--session-key` remains accepted for older scripts, but new tasks should use
the Agent Session ID shown in the active Avibe prompt.
diff --git a/docs/CLI_ZH.md b/docs/CLI_ZH.md
index 799f0a0e1..b4c317929 100644
--- a/docs/CLI_ZH.md
+++ b/docs/CLI_ZH.md
@@ -222,8 +222,8 @@ vibe task remove <task-id>
- 用 `--cron` / `--at` 控制定时方式
- 以及 `--name`、`--timezone`、`--message-file` 等参数
- 用 `--shell` 或写在 `--` 之后的 argv 创建不触发 Agent turn 的定时命令任务,
- 可搭配 `--on-failure {none,agent}` 和按次执行的 `--timeout`
- (默认 21600 秒,`0` 表示不限制)
+ 可搭配 `--on-failure {none,agent}`、按次执行的 `--timeout`
+ (默认 21600 秒,`0` 表示不限制),以及指定命令执行目录的 `--cwd`
当 `vibe task add` 运行在 Avibe 已注入 caller context 的 Agent shell 内时,
可以省略 `--session-id`。Avibe 会把任务目标默认到 `AVIBE_SESSION_ID`
@@ -235,8 +235,24 @@ session creation 参数和 delivery 参数仍然优先。
持久化的失败通知,并在通知中写明命令与退出码。若使用
`--on-failure agent --message '<处理说明>'`,失败会改为触发一次携带失败报告的 Agent
turn,并由该 turn 取代这次执行的失败通知。`vibe task update` 可以修改命令任务的
-`--shell`、argv 或 `--timeout`,但在 message 形态与 command 形态之间切换、或修改
-`--on-failure`,都会被拒绝——请删除任务后重新创建。
+`--shell`、argv、`--timeout` 或 `--cwd`,但在 message 形态与 command 形态之间切换、
+或修改 `--on-failure`,都会被拒绝——请删除任务后重新创建。
+
+`--cwd` 指定命令的执行目录。它是否还会影响 Session,取决于该定义是否要「创建」
+Session:
+
+- 绑定到已存在的 Session(`--session-id`,或调用方 Session 默认值),或已经预留过
+ 可复用 Session 时:该参数只作用于命令。升级 Session 保留自己的工作目录——这正是
+ 引入该参数要解决的场景:命令任务绑定 Session 是为了让 `--on-failure agent`
+ 有地方落地,而不是为了指定命令在哪里执行。
+- 需要创建 Session 时(`--create-session`、`--create-session-per-run`):该参数
+ 同时决定这个 Session 的目录,也就是升级 turn 会和命令跑在同一个目录。如果希望
+ Session 继承目录,请改用 `--same-scope` / `--scope-id` 指定 scope 并省略 `--cwd`。
+
+不传该参数时,绑定了 Session 的命令会跟随那个 Session 的目录(该目录在触发时实时
+读取,因此在那个会话里执行 `/setcwd` 会让任务换个地方运行),其他命令则记录你执行
+`vibe task add` 时所在的目录。对 message 任务,`--cwd` 仍然用于放置它创建的
+Session,且在目标 Session 已存在时仍然会被拒绝。
`--session-key` 仍兼容旧脚本,但新任务应使用当前 Avibe prompt
里展示的 Agent Session ID。
diff --git a/docs/COMMANDS.md b/docs/COMMANDS.md
index 53eaf5add..2c7415ce6 100644
--- a/docs/COMMANDS.md
+++ b/docs/COMMANDS.md
@@ -743,11 +743,18 @@ Important options:
- `--shell`
- `--on-failure {none,agent}`
- `--timeout <seconds>`
+- `--cwd <dir>`
- `--timezone`
A command task (`--shell` or a trailing `-- <argv>`) runs with no Agent turn and
takes no session, scope, or agent flags unless `--on-failure agent` is set.
`--timeout` bounds each command run (default 21600 seconds, `0` = no timeout).
+`--cwd` is where the command runs; with `--on-failure agent` bound to an existing
+Session it means only that, and the escalation Session keeps its own working
+directory. With `--create-session` / `--create-session-per-run` it places that
+Session too. Without it, a Session-bound command follows that Session's directory
+— read live at fire time — and every other command records the directory you ran
+`vibe task add` from. See `docs/CLI.md` for the full rules.
### `vibe task update`
@@ -772,10 +779,14 @@ Important options:
- `--message-file`
- `--shell`
- `--timeout <seconds>`
+- `--cwd <dir>`
- `--timezone`
Switching a task between message and command form, or changing `--on-failure`,
-is rejected with `task_mode_immutable` — remove the task and recreate it.
+is rejected with `task_mode_immutable` — remove the task and recreate it. `--cwd`
+repoints a command task's working directory without touching the Session it
+escalates to; on a message task it is still refused once the target Session
+exists.
### `vibe task list`
diff --git a/docs/COMMANDS_ZH.md b/docs/COMMANDS_ZH.md
index 8f70d9f45..47e635651 100644
--- a/docs/COMMANDS_ZH.md
+++ b/docs/COMMANDS_ZH.md
@@ -722,11 +722,17 @@ vibe task add (--cron <表达式> | --at <时间戳>) (--shell <命令> | -- <ar
- `--shell`
- `--on-failure {none,agent}`
- `--timeout <秒>`
+- `--cwd <目录>`
- `--timezone`
命令任务(`--shell` 或写在 `--` 之后的 argv)执行时不会触发任何 Agent turn,
除非设置了 `--on-failure agent`,否则不接受 session、scope 或 agent 相关参数。
`--timeout` 限制每次命令执行的时长(默认 21600 秒,`0` 表示不限制)。
+`--cwd` 指定命令的执行目录;当 `--on-failure agent` 绑定到已存在的 Session 时,
+它只作用于命令,升级 Session 保留自己的工作目录;配合 `--create-session` /
+`--create-session-per-run` 时,它同时决定新建 Session 的目录。不传该参数时,
+绑定了 Session 的命令会跟随那个 Session 的目录(触发时实时读取),其他命令则记录
+你执行 `vibe task add` 时所在的目录。完整规则见 `docs/CLI.md`。
### `vibe task update`
@@ -751,10 +757,13 @@ vibe task update <task_id> [options]
- `--message-file`
- `--shell`
- `--timeout <秒>`
+- `--cwd <目录>`
- `--timezone`
在 message 形态与 command 形态之间切换,或修改 `--on-failure`,都会被
-`task_mode_immutable` 拒绝——请删除任务后重新创建。
+`task_mode_immutable` 拒绝——请删除任务后重新创建。`--cwd` 可以修改命令任务的执行
+目录,而不影响它升级时使用的 Session;对 message 任务,在目标 Session 已存在时
+仍然会被拒绝。
### `vibe task list`
diff --git a/docs/plans/command-task-cwd-and-escalation-pane.md b/docs/plans/command-task-cwd-and-escalation-pane.md
new file mode 100644
index 000000000..06c36549b
--- /dev/null
+++ b/docs/plans/command-task-cwd-and-escalation-pane.md
@@ -0,0 +1,378 @@
+# Command Tasks: an Addressable Working Directory, and an Honest Escalation Pane
+
+Follow-up to `scheduled-command-task.md` (shipped in cde33c9d). Two defects found
+while converting a real daily job — a `sub2api` re-auth reminder — from an Agent
+message task to a command task. Both are small, both are independent, and both
+come from the same root: a command task reuses a data model whose fields were
+written to answer *Agent* questions, and two of those fields are now being asked
+a *command* question they were never labelled for.
+
+---
+
+## Issue 1 — `--cwd` is refused for exactly the command tasks that most need it
+
+### What happens
+
+```
+$ vibe task add --name sub2api-reauth-remind \
+ --cron '0 11 * * *' --timezone Asia/Shanghai \
+ --cwd /essd/qiqi/code/fish/f2debug \
+ --shell '...' --on-failure agent --message '...'
+
+{"ok": false, "code": "cwd_with_existing_session",
+ "error": "--cwd only applies when this definition creates new Sessions",
+ "hint": "An existing target Session keeps its own working directory."}
+```
+
+Drop `--cwd` and the task is created. At fire time the command runs from
+`/home/qiqi/code/cc/slack` — the bound Session's workdir, an unrelated chat
+router directory — with no field anywhere on the definition recording that.
+
+### Why
+
+`_resolve_definition_session_cwd` (`vibe/cli.py:5081-5109`) answers **one**
+question — where a Session this definition creates should run — and it is the
+only thing consulted for `--cwd`. Its `existing` branch refuses (`cli.py:5060-5068`),
+on a rule that is correct on its own terms: an existing Session owns its
+directory, and a definition pointing at one has no business rewriting it.
+
+The rule predates command tasks. A command task binds to an existing Session
+for a reason unrelated to where it runs: `--on-failure agent` needs somewhere to
+escalate. `_resolve_session_policy` returns `existing`, the branch fires, and the
+command's cwd is refused as collateral.
+
+`_command_definition_spawn_cwd` (`cli.py:5111-5137`) is the function that
+converts the Session answer into the command answer. It already documents the
+split — *"`_resolve_definition_session_cwd` answers a Session question… A command
+cannot wait for that"* — and already special-cases `create_per_run` by falling
+back to the invocation directory. `existing` is the one policy it deliberately
+passes through untouched, because a bound definition is supposed to read its
+directory live from the Session.
+
+That live read is `_bound_session_workdir` (`core/scheduled_tasks.py:6609-6650`),
+and its docstring states this issue as a known consequence:
+
+> `--cwd` is REFUSED for a definition bound to an existing Session
+> (`cwd_with_existing_session`), on the rule that the Session owns its working
+> directory — so an escalating command task legitimately stores `cwd=None`. A
+> message task loses nothing to that: the Agent turn starts in the Session's
+> workdir. A command has no turn to inherit it from, so `None` fell through to
+> the `~/.avibe` fallback and `--shell './scripts/sync.sh'` — the form the docs
+> use — ran from the product state directory, with **the one flag that could
+> have said otherwise rejected by the Session rule**.
+
+That function is the mitigation, not the design. It stopped commands landing in
+`~/.avibe`; it did not give the user a way to say where the command runs.
+
+### Why the inherited directory is the wrong answer
+
+Not merely unstated — unstable. `_bound_session_workdir` reads the Session row
+**live at fire time**, by design, so a command follows a Session whose workdir
+later changed. For a message task that is right: the turn belongs to that
+conversation. For a command it means `vibe session update --cwd` on an unrelated
+conversation silently relocates a cron job, with no edit to the task and nothing
+in its history showing a change.
+
+The failure mode is quiet. Every path in the fallback chain is validated with
+`isdir`, so a relocated command does not error — it runs, from somewhere else.
+A script robust to its cwd (ours resolves everything off
+`Path(__file__).resolve().parent`) never notices. A script using a relative path
+breaks, or writes into the wrong tree.
+
+### Proposal
+
+Teach the refusal the difference between the two questions.
+
+1. `_resolve_definition_session_cwd` grows a `has_command: bool = False`
+ parameter. In the `existing` branch, refuse only when `not has_command`.
+ The message stays exactly as it is for message tasks.
+2. When `has_command` and the policy is `existing`, resolve `--cwd` through the
+ existing `_resolve_existing_cwd` (giving the same `cwd_not_found` check every
+ other policy gets), and return it as the **command's** cwd:
+ `session_workdir` stays `None`, `task.cwd` gets the resolved path.
+3. `_command_definition_spawn_cwd` needs no change. `task.cwd` is already first
+ in the fire-time chain (`core/scheduled_tasks.py:6696-6699`), so a stored
+ value wins over the bound Session automatically, and omitting `--cwd` keeps
+ today's inherit-from-Session behaviour unchanged.
+
+Call sites: `vibe task add` (`cli.py:3297`) and `vibe task update`
+(`cli.py:3944`) pass `has_command`. `vibe task update` already threads
+`task.has_command` into `_command_definition_spawn_cwd` at `cli.py:3968`, so the
+value is in hand at both.
+
+**Not** `_resolve_run_cwd` (`cli.py:4970-4979`). `vibe agent run` has no command
+lane; its identical refusal remains correct.
+
+### Also: the pane never shows where a command runs
+
+`WatchDetail` renders `harness.detail.cwd` ("Working directory",
+`ui/src/components/workbench/HarnessPage.tsx:1474`). `TaskDetail` renders no cwd
+field at all, so the directory a command runs in is invisible in the UI even
+when explicitly stored. Add the same field to `TaskDetail`, gated on
+`isCommand`. Where `task.cwd` is null, showing the em-dash placeholder is
+honest — the answer genuinely is not on the definition — but the better display
+names the inherited source ("Session workdir") rather than implying none exists.
+
+### Docs
+
+`--cwd`'s help text reads as Session-only ("Working directory for Sessions
+created by this task"). It becomes two sentences: the Session meaning for
+message tasks, the spawn-directory meaning for command tasks. The "Command
+tasks" help section gains a line saying the command runs from `--cwd`, else the
+bound Session's directory, else the runtime default.
+
+### Tests
+
+| Test | Change |
+| --- | --- |
+| `tests/test_cli_task_command.py:1702` | Asserts today's refusal. Re-point at a **message** task (still refused); add a command-task case that now succeeds and stores `cwd`. |
+| `tests/test_scheduled_tasks.py:14796` | Same split. |
+| `tests/test_cli_agent_run_schema.py:1801` | Unchanged — `vibe agent run` keeps the refusal. |
+| new | `--cwd` on an escalating command task stores it on the definition and beats the bound Session's workdir at fire time. |
+| new | No `--cwd` still inherits live from the bound Session (guards `_bound_session_workdir`). |
+| new | `--cwd /nonexistent` on a command task raises `cwd_not_found`, not `cwd_with_existing_session`. |
+| new (ui) | `TaskDetail` shows the working directory for a command task. |
+
+### Risk
+
+Low, and one-directional: this accepts input that is currently an error. No
+stored definition changes meaning — `cwd=None` still resolves through the same
+chain. The only behaviour change is for a task created *after* the fix *with*
+`--cwd`, which stops following its Session. That is the point, and it is opt-in
+per task.
+
+Scenario catalogue: this needs an SCT entry of its own. `scheduled-command-task.md:157`
+records the refusal as settled design ("the Session owns its directory"); that
+line should be amended to point here rather than left contradicting the new
+behaviour.
+
+---
+
+## Issue 2 — the escalation lane is rendered as if it were the job
+
+### What happens
+
+A command task with `--on-failure agent` shows, top to bottom:
+
+```
+COMMAND vibe vault run --env … -- …/remind.py
+SCHEDULE every day at 11:00
+NEXT RUN today 11:00
+AGENT claude · claude-opus-5 · effort high ← failure-only
+SESSION DevBot TELEGRAM ↗ ← failure-only
+SESSION MODE Reuse the same session DELIVERY Default ← failure-only
+MESSAGE The sub2api re-auth reminder command failed…← failure-only
+ON FAILURE Escalate to an Agent TIMEOUT 300s ← the qualifier
+LAST RUN 2026-08-04 10:37:04 GMT+8
+```
+
+Five consecutive fields describing a path that runs on no healthy day are
+rendered at the same visual weight as `COMMAND` and `SCHEDULE`, and the field
+that explains them arrives *after* all five. A reader scanning top-down
+concludes an Agent runs daily on Opus with high effort — the exact cost the task
+was rewritten to avoid. `MESSAGE` is the sharpest case: on a message task that
+label means the payload sent every run; here the identical label means a triage
+prompt sent almost never.
+
+### Why the fields are shown at all — and why that part is right
+
+`routesSomewhere` (`ui/src/components/workbench/HarnessPage.tsx:1223-1230`) gates
+the block on real bindings: `on_failure === 'agent'`, or a pinned agent, session,
+or delivery target. That gate is SCT-043, which fixed the inverse bug — three
+label helpers resolve a stored `null` to a confident answer ("Inherits default
+agent", "Reuse the same session", "Default · session location"), so a pure
+`--on-failure none` command used to advertise routing it deliberately had none
+of. Its rule, *"gated on the BINDINGS, not on the kind"*, is correct and stays:
+an escalation turn really is routed by exactly these fields.
+
+SCT-043 settled **whether** to show them. It never addressed **what they mean
+once shown**, and for a command task the answer is different from a message
+task's.
+
+### Proposal
+
+No change to `routesSomewhere`. Change order and labelling only.
+
+1. **Move `ON FAILURE` above the routing block** when `isCommand`. The
+ conditional should read before the fields it governs. `TIMEOUT` leaves that
+ grid and pairs with the new working-directory field instead — both are
+ process mechanics belonging with `COMMAND`, and pairing it with `ON FAILURE`
+ is what currently drags the qualifier down below the routing.
+2. **Group the five under a heading** — "On failure → escalation" — for command
+ tasks with `on_failure === 'agent'`. Message tasks render exactly as today.
+3. **Relabel `MESSAGE` to "Triage prompt"** (new key `harness.detail.triagePrompt`)
+ when the message exists only as escalation instructions. The distinction is
+ already load-bearing in the CLI, where `--message` means the payload for a
+ message task and the failure prompt for a command task.
+4. Consider a muted note on `AGENT` for this case — the pane states model and
+ effort with no indication of how rarely they apply.
+
+### Tests
+
+`ui/src/components/workbench/HarnessPage.test.tsx:470-540` — `TaskDetail command
+task` already covers this area, including SCT-043 ("drops the Agent routing a
+pure command task deliberately has none of") and its counterpart ("keeps the
+routing fields wherever there is something to route"). Both assert presence and
+absence, not order, so both survive unchanged. Add:
+
+- an escalating command task renders `ON FAILURE` before `AGENT` in document order;
+- its message renders under the triage-prompt label, and a message task's under
+ the plain `MESSAGE` label.
+
+New scenario entry, sibling to SCT-043: *the task pane presents the escalation
+lane as the job it only runs instead of*.
+
+### Risk
+
+Presentation only; no gating, storage, or dispatch change. The one judgement
+call is heading wording, which is i18n-visible and needs the same key added to
+every locale in `ui/src/i18n/`.
+
+---
+
+## Sequencing
+
+Independent — either can land alone. Issue 1 touches CLI + core + docs + tests;
+Issue 2 touches UI + i18n + tests. Suggested order is Issue 1 first, so
+`TaskDetail`'s new working-directory field arrives with something real to
+display and both panes get their layout reviewed once.
+
+---
+
+## Status
+
+Both implemented on this branch. Shipped shape differs from the sketch above in
+two places, neither material:
+
+- `TIMEOUT` moved *up* beside the new working-directory field rather than staying
+ at the bottom — both are command mechanics, and the pane reads better with the
+ process facts together.
+- `_command_definition_spawn_cwd` also grew `stored_cwd`. Without it, letting a
+ command task store a `cwd` created a new bug rather than fixing one: the update
+ path writes the Session answer with `update_cwd=True` on every edit, so
+ `vibe task update --name` would have erased the pin. Covered by SCT-051.
+
+Scenario catalogue: SCT-050, SCT-051, SCT-052.
+
+### Review pass
+
+Three P2 findings, all taken. Each is the same shape as the bugs above — a field
+whose second meaning was not carried all the way through.
+
+- **A policy change promoted the command's directory onto a new Session.**
+ Retargeting at `--create-session*` without `--cwd` carries the stored directory
+ forward from `task.cwd`, which is correct while `cwd` has one meaning and wrong
+ the moment Issue 1 let it have two. The Session half now reads
+ `metadata["session_workdir"]` for a command task (`_stored_session_workdir`),
+ which a bound definition never had and a per-run definition leaves unset on
+ purpose (SCT-047), while the command half survives on `stored_cwd`. That also
+ stops a policy change re-stamping the directory the *update* ran from —
+ SCT-051's rule in the lane the explicit flag does not cover. **SCT-053.**
+- **The escalation heading was keyed on the kind.** A command task with
+ `on_failure: none` and a real delivery target keeps the routing fields
+ legitimately (that is SCT-043's whole rule), so the heading made the pane say
+ "Notice only (no Agent)" and "escalation" about one task, one field apart.
+ Keyed on `taskOnFailure(task) === 'agent'` — the same value the field above it
+ prints. **SCT-054.**
+- **"Session working directory" named an outcome the pane cannot verify.**
+ `_bound_session_workdir` answers `None` for a deleted row, a NULL workdir or a
+ failed read, and every fallback is `isdir`-validated, so the command can land on
+ the runtime default while the pane points at a Session — beside the "Session
+ deleted" the Session field prints two rows up. The field names the *chain* the
+ fire walks and drops the Session term where the binding is visibly gone.
+ Resolving it exactly would need the backend to publish the source; the pane
+ stops making a claim it cannot support instead. **SCT-055.**
+
+### Second review pass
+
+Four findings, all taken. Two of them are the first pass's own fix landing one
+line short.
+
+- **The Session reservation still read the command's answer.**
+ `_stored_session_workdir` split the two halves on the read side, and then
+ `_reserve_definition_session(..., workdir=cwd, ...)` was handed `cwd` — the
+ variable `_command_definition_spawn_cwd` had just overwritten with the
+ command's. So `--create-session` on a pinned command task reserved its
+ replacement escalation Session in the build directory, which is exactly the
+ defect SCT-053 closed, reintroduced through the same field one line later. Both
+ call sites (add and update) now pass `session_workdir`. **SCT-056.**
+- **`--cwd` was refused on the very tasks Issue 1 was for.**
+ `_reject_inert_create_once_cwd_update` is a Session rule — a reserved reusable
+ Session owns its workdir, so the flag is inert — but it ran before the
+ command-aware resolution, so it reached a command task first. Repointing a
+ nightly build meant `--create-session`, discarding an escalation Session that
+ had nothing to do with the request. Softened for commands exactly as Issue 1
+ softened the `existing` refusal. The same branch (`command_only_cwd`) also stops
+ the `else: cwd = task.cwd` fall-through writing a command directory into
+ `metadata["session_workdir"]` on an unrelated edit. **SCT-057.**
+- **The `--help` epilog described a chain the code does not walk.** It promised
+ "else the runtime default", but `cmd_task_add`'s pure-command branch stores
+ `os.getcwd()` and `_command_definition_spawn_cwd` returns it for an unpinned
+ `create_per_run` — SCT-047's rule, which the epilog was written before. Reworded
+ to say what is stored.
+- **Scenario IDs were missing from the tests and the PR body.** AGENTS.md:250
+ asks for them in both. Added for SCT-050 – SCT-057.
+
+### Third review pass
+
+Three findings, all taken. The first is the same conflation again, in the last
+lane that still read `task.cwd` for the Session's answer.
+
+- **An edit that asks nothing about directories still placed a Session.**
+ `command_only_cwd` covers the lanes where the *flag* arrives; the plain
+ `else: cwd = task.cwd` fall-through was left, and for a command task that value
+ is the command's half. So `vibe task update --name` on a `create_per_run`
+ definition wrote it into `metadata["session_workdir"]` and pinned every future
+ per-run Session to the directory `task add` was typed in — undoing SCT-047's
+ deliberate blank — and a `create_once` definition that had not reserved yet
+ reserved there. Each half now carries forward from where that half is stored.
+ **SCT-058.**
+- **The runtime half of SCT-050 carried no scenario ID.**
+ `test_a_stored_cwd_beats_the_bound_sessions_workdir` is the assertion that the
+ stored `cwd` actually wins at fire time; ID added, and the catalogue entry now
+ names it alongside the CLI test.
+- **`--cwd` was undocumented in the user references.** `docs/CLI.md` and
+ `docs/CLI_ZH.md` list the command-task flags and explain what `vibe task update`
+ may change; both now include `--cwd`, with a paragraph on what it means on a
+ command task versus a message task. (`docs/COMMANDS*.md` covers IM slash
+ commands, not the `vibe` CLI, so nothing there applies.)
+
+### Fourth review pass
+
+Two findings, both taken, both about a claim rather than the code.
+
+- **The new `docs/CLI.md` paragraph overstated the split.** "On a command task
+ `--cwd` means only where the command runs" is true for a binding — existing, or
+ a reusable Session already reserved — and false for `--create-session*`, where
+ `_resolve_definition_session_cwd` folds the flag into `session_workdir` on
+ purpose: a Session created by this edit and its command run in the same place.
+ Documented as the two cases it is, EN and ZH, with the way to opt out (pass a
+ scope, omit `--cwd`).
+- **"Runtime default" named a config key the run may never reach.** Past
+ `_runtime_default_workdir()` — unset on a fresh install, and `isdir`-revalidated
+ on every fire — `_execute_command_task` falls through to the Avibe state
+ directory. Same overclaim SCT-055 fixed, one link further down. Both strings now
+ name the terminal fallback, asserted on the `en` and `zh` copy directly, since
+ the copy is where the claim lives. Folded into **SCT-055** rather than given its
+ own ID: same invariant, same field.
+
+### Fifth review pass
+
+Two findings, both taken.
+
+- **A policy change pulled the command back to its Session's directory.** The
+ mirror image of SCT-053, in the last lane where one half was read as the other.
+ `--cwd` on a bound command moves it to B and leaves the Session on A — that
+ separation is the point of Issue 1 — and a later `--create-session*` carries A
+ forward as the *Session's* answer correctly, but `_command_definition_spawn_cwd`
+ read `session_cwd` before `stored_cwd` and so moved the command back. The two
+ are equal wherever `--cwd` set both and differ exactly where the user separated
+ them, so the stored command half now outranks the Session's, under the explicit
+ flag. **SCT-059.**
+- **`--cwd` still missing from `docs/COMMANDS*.md`.** My previous reply said that
+ file covers IM slash commands only. It also carries a `vibe task add` /
+ `vibe task update` option reference, so the flag belongs in both lists and in
+ both command-task explanations. Added, EN and ZH, pointing at `docs/CLI.md` for
+ the full rules.
+
+Scenario catalogue: SCT-050 – SCT-059.
diff --git a/docs/plans/scheduled-command-task.md b/docs/plans/scheduled-command-task.md
index 740f40985..d5e421939 100644
--- a/docs/plans/scheduled-command-task.md
+++ b/docs/plans/scheduled-command-task.md
@@ -152,15 +152,22 @@ is where most of step 4's real work lives.
`--cwd` keeps its current meaning and default (caller directory) and becomes
the command's working directory for command tasks.
-One consequence needs naming, because it has no `--cwd` to fix it: a definition
-bound to an *existing* Session must not pass `--cwd` at all
-(`cwd_with_existing_session` — the Session owns its directory), so an escalating
-command task legitimately stores `cwd=None`. A message task loses nothing there,
-since the Agent turn starts in the Session's workdir; a command has no turn to
-inherit from. So the command reads that workdir itself at fire time
-(`_bound_session_workdir`) rather than falling through to `~/.avibe`. Read live,
-not copied at creation, so it follows a Session whose workdir later changes and
-reads as "no answer" for a per-run binding that does not exist yet.
+One consequence needs naming: a definition bound to an *existing* Session stores
+`cwd=None` unless its command names one, so the command reads the Session's
+workdir itself at fire time (`_bound_session_workdir`) rather than falling
+through to `~/.avibe`. Read live, not copied at creation, so it follows a
+Session whose workdir later changes and reads as "no answer" for a per-run
+binding that does not exist yet.
+
+> **Superseded in part.** This section originally said a bound definition "must
+> not pass `--cwd` at all" (`cwd_with_existing_session`), leaving an escalating
+> command task with no way to state where it runs. That refusal is a *Session*
+> rule, and a command task binds to a Session only so `--on-failure agent` has
+> somewhere to escalate — so it was refusing a question nobody asked it, and the
+> live inheritance above became the only answer available. It is now softened for
+> command tasks: see `command-task-cwd-and-escalation-pane.md`. A message task is
+> still refused, and a command task that omits the flag still inherits exactly as
+> described here.
`vibe task update` accepts the same new fields. Switching a definition between
message and command mode via update is rejected (`task_mode_immutable`) —
diff --git a/tests/scenarios/harness_command_task/catalog.yaml b/tests/scenarios/harness_command_task/catalog.yaml
index 2aec703ff..79f1d5e5d 100644
--- a/tests/scenarios/harness_command_task/catalog.yaml
+++ b/tests/scenarios/harness_command_task/catalog.yaml
@@ -510,3 +510,165 @@ scenarios:
# updates the row the metadata already lives on, which is why the gap was invisible
# from there; the recovery writer already composed from the file, so the same backend's
# two terminal writers disagreed about what a settled row remembers.
+ - id: SCT-050
+ name: an escalating command task can name the directory its command runs in
+ status: covered
+ kind: routing
+ layer: unit
+ backend: shared
+ test: tests/test_cli_task_command.py::test_task_add_escalating_command_task_accepts_an_explicit_cwd
+ # SCT-008 made a bound definition supply the directory ``--cwd`` was refused, which
+ # stopped commands landing in ``~/.avibe`` without giving the user a way to say where
+ # they run. The refusal is a SESSION rule -- an existing Session owns its workdir --
+ # and a command task binds to one only so ``--on-failure agent`` has somewhere to
+ # escalate, so the rule was answering a question nobody asked it. Softened for
+ # commands only: the flag becomes the definition's ``cwd``, ``session_workdir`` stays
+ # unset so the Session still owns its own, and a message task is refused exactly as
+ # before. Omitting it keeps SCT-008 intact, which matters because the inherited
+ # directory is read live -- ``vibe session update --cwd`` on an unrelated conversation
+ # silently relocates every unpinned command, and nothing errors, because every
+ # fallback in the chain is ``isdir``-validated. The runtime half -- that a stored
+ # ``cwd`` actually beats the live Session read at fire time, or accepting the flag
+ # means nothing -- is
+ # tests/test_scheduled_tasks.py::test_a_stored_cwd_beats_the_bound_sessions_workdir.
+ - id: SCT-051
+ name: an unrelated edit does not un-pin a command task's working directory
+ status: covered
+ kind: routing
+ layer: unit
+ backend: shared
+ test: tests/test_cli_task_command.py::test_task_update_keeps_a_command_tasks_cwd_through_an_unrelated_edit
+ # A bound definition resolves its Session question to ``None`` on every edit, and the
+ # update path persists that with ``update_cwd=True``. Harmless while no command task
+ # could store a ``cwd``; the moment SCT-050 let one, ``vibe task update --name`` erased
+ # it and the next fire went back to following the escalation Session. Only the explicit
+ # flag replaces a stored directory.
+ - id: SCT-052
+ name: the task pane presents the escalation lane as the job it only runs instead of
+ status: covered
+ kind: observability
+ layer: unit
+ backend: shared
+ test: ui/src/components/workbench/HarnessPage.test.tsx::TaskDetail command task states the failure policy before the routing it governs, not after it
+ # SCT-043 settled WHETHER to show Agent/Session/mode/delivery/message on a command
+ # task -- gated on the bindings, because an escalation turn is routed by exactly those
+ # fields. It did not settle what they mean once shown. Five fields describing a path
+ # that runs on no healthy day rendered at the same weight as the command and the
+ # schedule, with the ``On failure`` that qualifies them BELOW all five, so the pane
+ # read top-down as a daily Opus turn -- the cost an agent-free task is chosen to
+ # avoid. The qualifier moves above the block, the block gets a name, and the message
+ # is called a triage prompt rather than sharing a label with a message task's payload.
+ # The working directory is shown for the first time on this pane in the same pass: it
+ # was unanswerable from the UI even once SCT-050 could store one.
+ - id: SCT-053
+ name: a command task's directory and its Session's survive a policy change separately
+ status: covered
+ kind: routing
+ layer: unit
+ backend: shared
+ test: tests/test_cli_task_command.py::test_task_update_retarget_does_not_promote_a_command_cwd_onto_a_new_session
+ # Retargeting at ``--create-session``/``--create-session-per-run`` without naming a
+ # directory carries forward the stored one, reading it off ``task.cwd``. That is the
+ # right source while ``cwd`` has one meaning -- for a message task it IS the Session's
+ # directory -- and the wrong one the moment SCT-050 let the two differ: the command's
+ # directory was promoted into the new Session's placement, so an escalation Session
+ # stopped inheriting from its Scope with nothing in the edit saying so. The Session
+ # half now comes from ``metadata["session_workdir"]``, which a bound definition never
+ # had and a per-run definition leaves unset on purpose (SCT-047). The command half
+ # comes from its own stored value, which also stops a policy change from re-stamping
+ # the directory the UPDATE happened to run from -- SCT-051's rule in the lane the
+ # explicit flag does not cover.
+ - id: SCT-054
+ name: nothing is called an escalation on a command task that escalates to no one
+ status: covered
+ kind: observability
+ layer: unit
+ backend: shared
+ test: ui/src/components/workbench/HarnessPage.test.tsx::TaskDetail command task calls nothing an escalation on a command task that escalates to no one
+ # SCT-052's heading was keyed on the KIND, which is the same mistake SCT-043 rejected
+ # one level down: a command task with ``--on-failure none`` delivered to a real
+ # conversation keeps the routing fields legitimately, and heading them "On failure ->
+ # escalation" made the pane say "Notice only (no Agent)" and "escalation" about one
+ # task, one field apart. Keyed on ``on_failure`` instead -- the same value the field
+ # above it prints -- so the two cannot contradict each other.
+ - id: SCT-055
+ name: the pane does not name a Session the command cannot inherit a directory from
+ status: covered
+ kind: observability
+ layer: unit
+ backend: shared
+ test: ui/src/components/workbench/HarnessPage.test.tsx::TaskDetail command task does not name a session the command cannot inherit a directory from
+ # "Session working directory" named an OUTCOME the pane cannot verify.
+ # ``_bound_session_workdir`` answers ``None`` for a deleted row, a NULL workdir or a
+ # failed read, and every fallback is ``isdir``-validated besides, so the command lands
+ # on the runtime default while the pane points at a Session -- next to the "Session
+ # deleted" the Session field prints two rows up, in the case the UI can already see.
+ # The field names the CHAIN the fire walks instead, and drops the Session term where
+ # the binding is visibly gone or absent. The chain does not stop at
+ # ``runtime.default_cwd`` either: it is unset on a fresh install and revalidated on
+ # every fire, and ``_execute_command_task`` then falls through to the Avibe state
+ # directory -- so "Runtime default" alone named a specific config key the run may
+ # never reach, which is the same overclaim one link further down. Both strings name
+ # the terminal fallback, asserted on the copy in ``en`` and ``zh`` because that is
+ # where the claim lives.
+ - id: SCT-056
+ name: a replacement reusable Session is reserved where the Session belongs, not where the command runs
+ status: covered
+ kind: routing
+ layer: unit
+ backend: shared
+ test: tests/test_cli_task_command.py::test_task_update_reserves_a_replacement_session_without_the_commands_directory
+ # SCT-053 split the two halves of ``cwd`` on the read side, then handed the reservation
+ # ``cwd`` -- the variable ``_command_definition_spawn_cwd`` had just overwritten with
+ # the COMMAND's answer. So ``--create-session`` on a command task pinned to a build
+ # directory reserved its replacement escalation Session in that build directory instead
+ # of letting it inherit from its Scope: the defect SCT-053 closed, reintroduced one
+ # line later and through the same field. The reservation reads the Session half it was
+ # always meant to. The add path carried the identical line and is fixed with it.
+ - id: SCT-057
+ name: repointing a reserved command task's directory does not replace the Session it escalates to
+ status: covered
+ kind: routing
+ layer: unit
+ backend: shared
+ test: tests/test_cli_task_command.py::test_task_update_repoints_a_reserved_command_task_without_replacing_its_session
+ # ``_reject_inert_create_once_cwd_update`` refuses ``--cwd`` once a reusable Session
+ # exists, and for a message task that is right -- the Session owns its workdir and the
+ # flag would change nothing. It runs before the command-aware resolution, so it reached
+ # a command task first and left ``--create-session`` as the only way to move a nightly
+ # build: discarding an escalation Session that had nothing to do with the request.
+ # Softened exactly as SCT-050 softened the ``existing`` refusal, and for the same
+ # reason. The same branch stops an unrelated edit on a reserved definition from
+ # falling through and stamping the command's directory into
+ # ``metadata["session_workdir"]`` -- SCT-053's rule in the lane SCT-051 does not cover.
+ - id: SCT-058
+ name: an edit that asks nothing about directories places no Session
+ status: covered
+ kind: routing
+ layer: unit
+ backend: shared
+ test: tests/test_cli_task_command.py::test_task_update_unrelated_edit_leaves_a_per_run_definitions_sessions_unplaced
+ # SCT-053 fixed the retarget; this is the same conflation in the lane where the edit
+ # asks nothing at all. With no ``--cwd`` and no creation flag the update carries the
+ # stored directory forward from ``task.cwd`` -- the COMMAND's half -- and then writes
+ # it as the Session's, so ``vibe task update --name`` pinned every future per-run
+ # Session to the directory ``task add`` was typed in and undid SCT-047's deliberate
+ # blank. A ``create_once`` definition that had not reserved yet reserved there for the
+ # same reason. Each half now carries forward from where that half is stored, which is
+ # the rule SCT-053, SCT-056 and SCT-057 each enforce in one other lane.
+ - id: SCT-059
+ name: a policy change does not pull a command back to its Session's directory
+ status: covered
+ kind: routing
+ layer: unit
+ backend: shared
+ test: tests/test_cli_task_command.py::test_task_update_retarget_does_not_pull_the_command_back_to_its_sessions_directory
+ # The mirror image of SCT-053, and the last lane where one half was read as the other.
+ # ``--cwd`` on a bound escalating command moves the command to B and leaves its
+ # Session on A -- that separation is what SCT-050 exists for. A later
+ # ``--create-session*`` carries A forward as the SESSION's answer, correctly, and
+ # ``_command_definition_spawn_cwd`` read it before the stored command half, so the
+ # command was pulled back to A with nothing in the edit asking. The two are equal
+ # wherever ``--cwd`` set both and differ exactly where the user separated them, so
+ # the stored command half now outranks the Session's: SCT-051's rule -- only the
+ # explicit flag replaces a stored directory -- in the retarget lane.
diff --git a/tests/test_cli_task_command.py b/tests/test_cli_task_command.py
index 36982bb18..a837dd0a4 100644
--- a/tests/test_cli_task_command.py
+++ b/tests/test_cli_task_command.py
@@ -1675,6 +1675,396 @@ def test_task_update_rejects_scope_without_session_creation(tmp_path: Path) -> N
assert payload["code"] == "scope_without_session_creation"
+def test_task_update_repoints_an_escalating_command_tasks_cwd(
+ tmp_path: Path, capsys, monkeypatch
+) -> None:
+ """SCT-050 -- the same flag the add path now accepts, on a task that already exists."""
+
+ _bare_terminal_caller(monkeypatch)
+ db_path, agent_store = _caller_session_state(tmp_path)
+ store = _command_task_store(tmp_path)
+ old = tmp_path / "old"
+ old.mkdir()
+ new_dir = tmp_path / "new"
+ new_dir.mkdir()
+ task = _stored_command_task(
+ store,
+ session_id="sesCaller",
+ session_policy="existing",
+ cwd=str(old),
+ metadata={"on_failure": "agent"},
+ )
+ args = _parse_task_update(task.id, ["--cwd", str(new_dir)])
+
+ with (
+ patch("vibe.cli.paths.get_state_dir", return_value=db_path.parent),
+ patch("vibe.cli.paths.get_sqlite_state_path", return_value=db_path),
+ patch("vibe.cli._agent_store", return_value=agent_store),
+ patch("vibe.cli._task_store", return_value=store),
+ ):
+ result = cli.cmd_task_update(args)
+
+ assert result == 0
+ definition = json.loads(capsys.readouterr().out)["definition"]
+ assert definition["cwd"] == str(new_dir)
+ assert "session_workdir" not in (definition["metadata"] or {})
+
+
+def test_task_update_keeps_a_command_tasks_cwd_through_an_unrelated_edit(
+ tmp_path: Path, capsys, monkeypatch
+) -> None:
+ """SCT-051 -- a rename must not silently un-pin the directory the command was given.
+
+ A bound definition resolves its SESSION question to ``None`` on every edit, and the
+ update path persists that with ``update_cwd=True``. Once a command task can store a
+ ``cwd`` of its own, that same write erases it -- and nothing about a ``--name`` edit
+ tells the user their job just went back to following its escalation Session.
+ """
+
+ _bare_terminal_caller(monkeypatch)
+ db_path, agent_store = _caller_session_state(tmp_path)
+ store = _command_task_store(tmp_path)
+ pinned = tmp_path / "pinned"
+ pinned.mkdir()
+ task = _stored_command_task(
+ store,
+ session_id="sesCaller",
+ session_policy="existing",
+ cwd=str(pinned),
+ metadata={"on_failure": "agent"},
+ )
+ args = _parse_task_update(task.id, ["--name", "renamed"])
+
+ with (
+ patch("vibe.cli.paths.get_state_dir", return_value=db_path.parent),
+ patch("vibe.cli.paths.get_sqlite_state_path", return_value=db_path),
+ patch("vibe.cli._agent_store", return_value=agent_store),
+ patch("vibe.cli._task_store", return_value=store),
+ ):
+ result = cli.cmd_task_update(args)
+
+ assert result == 0
+ definition = json.loads(capsys.readouterr().out)["definition"]
+ assert definition["name"] == "renamed"
+ assert definition["cwd"] == str(pinned), (
+ "an unrelated edit dropped the command's working directory, so the next fire "
+ f"silently moved to the bound Session's: {definition['cwd']!r}"
+ )
+
+
+def test_task_update_retarget_does_not_pull_the_command_back_to_its_sessions_directory(
+ tmp_path: Path, capsys, monkeypatch
+) -> None:
+ """SCT-059 -- once the two halves differ, neither may be read as the other.
+
+ ``--cwd`` on a bound escalating command moves the command to B and leaves its
+ Session on A, which is the whole point of SCT-050. A later ``--create-session*``
+ carries A forward as the Session's answer -- correct -- and
+ ``_command_definition_spawn_cwd`` read that before the stored command half, so the
+ command was pulled back to A with nothing in the edit asking to. SCT-051's rule in
+ the retarget lane: only the explicit flag replaces a stored directory.
+ """
+
+ _bare_terminal_caller(monkeypatch)
+ db_path, agent_store = _caller_session_state(tmp_path)
+ store = _command_task_store(tmp_path)
+ session_dir = tmp_path / "session-dir"
+ session_dir.mkdir()
+ command_dir = tmp_path / "command-dir"
+ command_dir.mkdir()
+ task = _stored_command_task(
+ store,
+ session_id="sesCaller",
+ session_policy="create_once",
+ agent_name="codex",
+ # What ``task update --cwd <command_dir>`` leaves behind on a definition whose
+ # reusable Session was reserved in ``session_dir``: the halves now differ.
+ cwd=str(command_dir),
+ metadata={
+ "session_scope_id": "avibe::project::proj-command-task",
+ "session_workdir": str(session_dir),
+ "on_failure": "agent",
+ },
+ )
+ args = _parse_task_update(task.id, ["--create-session-per-run"])
+
+ with (
+ patch("vibe.cli.paths.get_state_dir", return_value=db_path.parent),
+ patch("vibe.cli.paths.get_sqlite_state_path", return_value=db_path),
+ patch("vibe.cli._agent_store", return_value=agent_store),
+ patch("vibe.cli._task_store", return_value=store),
+ patch("os.getcwd", return_value=str(tmp_path)),
+ ):
+ result = cli.cmd_task_update(args)
+
+ assert result == 0
+ definition = json.loads(capsys.readouterr().out)["definition"]
+ assert definition["session_policy"] == "create_per_run"
+ assert definition["cwd"] == str(command_dir), (
+ "the policy change pulled the command back to its Session's directory: "
+ f"{definition['cwd']!r}"
+ )
+ assert definition["metadata"]["session_workdir"] == str(session_dir), (
+ "the Session half did not survive the retarget: "
+ f"{definition['metadata'].get('session_workdir')!r}"
+ )
+
+
+def test_task_update_unrelated_edit_leaves_a_per_run_definitions_sessions_unplaced(
+ tmp_path: Path, capsys, monkeypatch
+) -> None:
+ """SCT-058 -- an edit that asks nothing about directories must place no Session.
+
+ SCT-053 covers the retarget; this is the same conflation in the lane where nothing
+ is asked at all. With no ``--cwd`` and no creation flag the update carries the
+ stored directory forward from ``task.cwd``, which for a command task is the
+ COMMAND's -- so a plain ``--name`` wrote it into ``metadata["session_workdir"]``
+ and every future per-run Session was pinned to the directory ``task add`` happened
+ to be typed in, undoing SCT-047's deliberate blank. Each half now carries forward
+ from where that half is stored.
+ """
+
+ _bare_terminal_caller(monkeypatch)
+ db_path, agent_store = _caller_session_state(tmp_path)
+ store = _command_task_store(tmp_path)
+ described_in = tmp_path / "described-in"
+ described_in.mkdir()
+ task = _stored_command_task(
+ store,
+ session_id="",
+ session_policy="create_per_run",
+ agent_name="codex",
+ # What SCT-047 stores for a per-run command created without ``--cwd``: the
+ # command has a directory, the Sessions deliberately do not.
+ cwd=str(described_in),
+ metadata={"on_failure": "agent"},
+ )
+ args = _parse_task_update(task.id, ["--name", "renamed"])
+
+ with (
+ patch("vibe.cli.paths.get_state_dir", return_value=db_path.parent),
+ patch("vibe.cli.paths.get_sqlite_state_path", return_value=db_path),
+ patch("vibe.cli._agent_store", return_value=agent_store),
+ patch("vibe.cli._task_store", return_value=store),
+ ):
+ result = cli.cmd_task_update(args)
+
+ assert result == 0
+ definition = json.loads(capsys.readouterr().out)["definition"]
+ assert definition["name"] == "renamed"
+ assert definition["cwd"] == str(described_in), (
+ "the rename moved the command: " f"{definition['cwd']!r}"
+ )
+ assert "session_workdir" not in (definition["metadata"] or {}), (
+ "a rename pinned every future per-run Session to the command's directory, so "
+ "the escalation turn stopped inheriting from its Scope"
+ )
+
+
+def test_task_update_retarget_does_not_promote_a_command_cwd_onto_a_new_session(
+ tmp_path: Path, capsys, monkeypatch
+) -> None:
+ """SCT-053 -- the two halves of ``cwd`` survive a policy change separately.
+
+ Retargeting at ``--create-session-per-run`` without naming a directory carries
+ forward the one the definition already has. For a message task that is right --
+ ``cwd`` IS its Session's directory. For an escalating command task it is where the
+ COMMAND runs, and carrying it across pins the newly created escalation Session to a
+ directory the user chose for a subprocess, instead of letting it inherit from its
+ Scope. The command must keep it; the Session must not receive it.
+ """
+
+ _bare_terminal_caller(monkeypatch)
+ db_path, agent_store = _caller_session_state(tmp_path)
+ store = _command_task_store(tmp_path)
+ pinned = tmp_path / "pinned"
+ pinned.mkdir()
+ task = _stored_command_task(
+ store,
+ session_id="sesCaller",
+ session_policy="existing",
+ cwd=str(pinned),
+ metadata={"on_failure": "agent"},
+ )
+ args = _parse_task_update(task.id, ["--create-session-per-run"])
+
+ with (
+ patch("vibe.cli.paths.get_state_dir", return_value=db_path.parent),
+ patch("vibe.cli.paths.get_sqlite_state_path", return_value=db_path),
+ patch("vibe.cli._agent_store", return_value=agent_store),
+ patch("vibe.cli._task_store", return_value=store),
+ patch("os.getcwd", return_value=str(tmp_path)),
+ ):
+ result = cli.cmd_task_update(args)
+
+ assert result == 0
+ definition = json.loads(capsys.readouterr().out)["definition"]
+ assert definition["session_policy"] == "create_per_run"
+ assert definition["cwd"] == str(pinned), (
+ "the policy change moved the command, which nothing in the edit asked for: "
+ f"{definition['cwd']!r}"
+ )
+ assert "session_workdir" not in (definition["metadata"] or {}), (
+ "the command's directory was promoted into the created Session's placement, so "
+ "the escalation Session stopped following its Scope"
+ )
+
+
+def test_task_update_reserves_a_replacement_session_without_the_commands_directory(
+ tmp_path: Path, capsys
+) -> None:
+ """SCT-056 -- the reservation reads the Session's half, not the command's.
+
+ ``--create-session`` on a ``create_once`` definition reserves a replacement Session
+ there and then, and it was handed ``cwd`` -- the variable
+ ``_command_definition_spawn_cwd`` had already overwritten with the COMMAND's answer.
+ So an escalating command task pinned to a build directory reserved its replacement
+ escalation Session *in that build directory*, instead of letting it take the Scope's
+ workdir. ``_stored_session_workdir`` closes the branch one step earlier; this is the
+ line that could put it straight back.
+ """
+
+ from sqlalchemy import select
+ from storage.db import create_sqlite_engine
+ from storage.importer import ensure_sqlite_state
+ from storage.models import agent_sessions, scope_settings
+ from storage.settings_service import upsert_scope
+
+ state_home = tmp_path / "home"
+ scope_cwd = tmp_path / "scope"
+ scope_cwd.mkdir()
+ pinned = tmp_path / "pinned"
+ pinned.mkdir()
+ with patch.dict("os.environ", {"AVIBE_HOME": str(state_home)}):
+ ensure_sqlite_state()
+ db_path = state_home / "state" / "vibe.sqlite"
+ engine = create_sqlite_engine(db_path)
+ with engine.begin() as conn:
+ scope_id = upsert_scope(conn, "avibe", "project", "proj-command-cwd", now="2026-06-16T00:00:00Z")
+ conn.execute(
+ scope_settings.insert().values(
+ scope_id=scope_id,
+ enabled=1,
+ role=None,
+ workdir=str(scope_cwd),
+ agent_name="worker",
+ agent_backend="codex",
+ agent_variant="codex",
+ model=None,
+ reasoning_effort=None,
+ require_mention=None,
+ settings_version=1,
+ settings_json="{}",
+ created_at="2026-06-16T00:00:00Z",
+ updated_at="2026-06-16T00:00:00Z",
+ )
+ )
+ conn.execute(
+ agent_sessions.insert().values(
+ id="sesOld",
+ scope_id=scope_id,
+ agent_backend="codex",
+ agent_name="worker",
+ agent_variant="codex",
+ session_anchor="avibe_proj-command-cwd:definition_old",
+ native_session_id="native-old",
+ status="active",
+ metadata_json="{}",
+ created_at="2026-06-16T00:00:00Z",
+ updated_at="2026-06-16T00:00:00Z",
+ last_active_at="2026-06-16T00:00:00Z",
+ workdir=str(scope_cwd),
+ )
+ )
+ agent_store = cli.VibeAgentStore(db_path)
+ agent_store.create(name="worker", backend="codex")
+ store = _command_task_store(tmp_path)
+ task = _stored_command_task(
+ store,
+ session_id="sesOld",
+ session_policy="create_once",
+ agent_name="worker",
+ cwd=str(pinned),
+ metadata={"session_scope_id": scope_id, "on_failure": "agent"},
+ )
+ parser = cli.build_parser()
+ args = parser.parse_args(["task", "update", task.id, "--create-session"])
+
+ with (
+ patch("vibe.cli._ensure_config", return_value=_configured_v2(set())),
+ patch("vibe.cli._agent_store", return_value=agent_store),
+ patch("vibe.cli._task_store", return_value=store),
+ patch("vibe.cli.paths.get_sqlite_state_path", return_value=db_path),
+ ):
+ result = cli.cmd_task_update(args)
+
+ definition = json.loads(capsys.readouterr().out)["definition"]
+ with engine.connect() as conn:
+ reserved = conn.execute(
+ select(agent_sessions.c.workdir).where(agent_sessions.c.id == definition["session_id"]).limit(1)
+ ).mappings().one()
+
+ assert result == 0
+ assert definition["session_id"] != "sesOld"
+ assert definition["cwd"] == str(pinned), "the command lost the directory it was pinned to"
+ assert reserved["workdir"] != str(pinned), (
+ "the replacement escalation Session was reserved in the command's working "
+ f"directory: {reserved['workdir']!r}"
+ )
+
+
+def test_task_update_repoints_a_reserved_command_task_without_replacing_its_session(
+ tmp_path: Path, capsys
+) -> None:
+ """SCT-057 -- repointing the command must not mean replacing the escalation Session.
+
+ ``_reject_inert_create_once_cwd_update`` refuses ``--cwd`` once a reusable Session
+ exists, which is right for a message task -- that Session owns its workdir and the
+ flag would do nothing. It ran before the command-aware resolution, so the only way
+ to move a nightly command was ``--create-session``, discarding an escalation Session
+ that had nothing to do with the request. Same rule as the ``existing`` refusal, and
+ softened the same way: the command's half moves, the Session's half is untouched.
+ """
+
+ db_path, agent_store = _caller_session_state(tmp_path, session_id="sesReserved")
+ store = _command_task_store(tmp_path)
+ saved = tmp_path / "saved"
+ saved.mkdir()
+ moved = tmp_path / "moved"
+ moved.mkdir()
+ task = _stored_command_task(
+ store,
+ session_id="sesReserved",
+ session_policy="create_once",
+ agent_name="codex",
+ cwd=str(saved),
+ metadata={
+ "session_scope_id": "avibe::project::proj-command-task",
+ "session_workdir": str(saved),
+ "on_failure": "agent",
+ },
+ )
+ parser = cli.build_parser()
+ args = parser.parse_args(["task", "update", task.id, "--cwd", str(moved)])
+
+ with (
+ patch("vibe.cli.paths.get_state_dir", return_value=db_path.parent),
+ patch("vibe.cli.paths.get_sqlite_state_path", return_value=db_path),
+ patch("vibe.cli._agent_store", return_value=agent_store),
+ patch("vibe.cli._task_store", return_value=store),
+ ):
+ result = cli.cmd_task_update(args)
+
+ assert result == 0
+ definition = json.loads(capsys.readouterr().out)["definition"]
+ assert definition["cwd"] == str(moved)
+ assert definition["session_id"] == "sesReserved", "the escalation Session was replaced"
+ assert definition["metadata"]["session_workdir"] == str(saved), (
+ "moving the command moved the Session it escalates to as well: "
+ f"{definition['metadata'].get('session_workdir')!r}"
+ )
+
+
def test_task_update_rejects_cwd_for_already_reserved_create_once_task(tmp_path: Path) -> None:
store_path = tmp_path / "scheduled_tasks.json"
store = cli.ScheduledTaskStore(store_path)
@@ -4346,6 +4736,132 @@ def test_task_add_escalating_command_task_binds_caller_session(
assert payload["session_default_notice"]["code"] == "session_defaulted_to_caller"
+def test_task_add_escalating_command_task_accepts_an_explicit_cwd(
+ tmp_path: Path, capsys, monkeypatch
+) -> None:
+ """SCT-050 -- the command's directory is not the bound Session's question.
+
+ An escalating command task binds to an existing Session for one reason -- a failed
+ run needs somewhere to report -- and that binding made ``session_policy`` read
+ ``existing``, where ``--cwd`` was refused on the rule that a bound Session owns its
+ working directory. The rule is right about the SESSION and wrong about the command:
+ the flag was the only way to say where a subprocess with no Agent turn spawns, and
+ it came back ``cwd_with_existing_session``.
+
+ Stored on the definition, and NOT as the Session's workdir: the Session still owns
+ that, so ``session_workdir`` must stay out of the metadata.
+ """
+
+ _agent_shell_caller(monkeypatch)
+ db_path, agent_store = _caller_session_state(tmp_path)
+ store = _command_task_store(tmp_path)
+ project = tmp_path / "project"
+ project.mkdir()
+ args = _parse_task_add(
+ [
+ "--cron",
+ "0 3 * * *",
+ "--shell",
+ "./scripts/sync.sh",
+ "--on-failure",
+ "agent",
+ "--message",
+ "The nightly sync failed. Diagnose it.",
+ "--cwd",
+ str(project),
+ ]
+ )
+
+ with (
+ patch("vibe.cli.paths.get_state_dir", return_value=db_path.parent),
+ patch("vibe.cli.paths.get_sqlite_state_path", return_value=db_path),
+ patch("vibe.cli._agent_store", return_value=agent_store),
+ patch("vibe.cli._task_store", return_value=store),
+ ):
+ result = cli.cmd_task_add(args)
+
+ assert result == 0
+ definition = json.loads(capsys.readouterr().out)["definition"]
+ assert definition["session_policy"] == "existing"
+ assert definition["cwd"] == str(project), (
+ "the command has no way to say where it runs, so it falls back to whatever "
+ f"directory its escalation Session happens to have: {definition['cwd']!r}"
+ )
+ assert "session_workdir" not in (definition["metadata"] or {}), (
+ "the bound Session owns its own working directory; pinning it here is the "
+ "rule the refusal was protecting"
+ )
+
+
+def test_task_add_escalating_command_task_rejects_a_missing_cwd(
+ tmp_path: Path, monkeypatch
+) -> None:
+ """SCT-050 -- accepted does not mean unchecked, and the error must name the real problem.
+
+ Every other policy resolves ``--cwd`` through the same existence check. Reporting a
+ typo'd directory as ``cwd_with_existing_session`` would send the user to look at
+ their Session binding.
+ """
+
+ _agent_shell_caller(monkeypatch)
+ db_path, agent_store = _caller_session_state(tmp_path)
+ store = _command_task_store(tmp_path)
+ args = _parse_task_add(
+ [
+ "--cron",
+ "0 3 * * *",
+ "--shell",
+ "./scripts/sync.sh",
+ "--on-failure",
+ "agent",
+ "--cwd",
+ str(tmp_path / "does-not-exist"),
+ ]
+ )
+
+ with (
+ patch("vibe.cli.paths.get_state_dir", return_value=db_path.parent),
+ patch("vibe.cli.paths.get_sqlite_state_path", return_value=db_path),
+ patch("vibe.cli._agent_store", return_value=agent_store),
+ patch("vibe.cli._task_store", return_value=store),
+ ):
+ result, payload = _capture_stderr_json(cli.cmd_task_add, args)
+
+ assert result == 1
+ assert payload["code"] == "cwd_not_found"
+
+
+def test_task_add_message_task_still_refuses_cwd_for_a_bound_session(
+ tmp_path: Path, monkeypatch
+) -> None:
+ """SCT-050 -- the softened refusal is softened for commands only.
+
+ A message task's Agent turn starts in its Session's workdir. There is no second
+ directory to name, so ``--cwd`` there is still a request to rewrite a Session's own
+ setting from a task definition.
+ """
+
+ _agent_shell_caller(monkeypatch)
+ db_path, agent_store = _caller_session_state(tmp_path)
+ store = _command_task_store(tmp_path)
+ project = tmp_path / "project"
+ project.mkdir()
+ args = _parse_task_add(
+ ["--cron", "0 3 * * *", "--message", "Share the summary.", "--cwd", str(project)]
+ )
+
+ with (
+ patch("vibe.cli.paths.get_state_dir", return_value=db_path.parent),
+ patch("vibe.cli.paths.get_sqlite_state_path", return_value=db_path),
+ patch("vibe.cli._agent_store", return_value=agent_store),
+ patch("vibe.cli._task_store", return_value=store),
+ ):
+ result, payload = _capture_stderr_json(cli.cmd_task_add, args)
+
+ assert result == 1
+ assert payload["code"] == "cwd_with_existing_session"
+
+
def test_task_add_per_run_command_records_the_directory_it_was_described_in(
tmp_path: Path, capsys, monkeypatch
) -> None:
diff --git a/tests/test_scheduled_tasks.py b/tests/test_scheduled_tasks.py
index b3973b758..b55f74f3c 100644
--- a/tests/test_scheduled_tasks.py
+++ b/tests/test_scheduled_tasks.py
@@ -16125,21 +16125,68 @@ def test_the_escalation_prompt_prepends_the_stored_message_and_names_the_run(
)
+def test_a_stored_cwd_beats_the_bound_sessions_workdir(tmp_path: Path, monkeypatch) -> None:
+ """SCT-050 -- an explicit ``--cwd`` has to actually win, or accepting the flag means nothing.
+
+ The bound Session's workdir is read LIVE at fire time, by design, so a command with
+ no directory of its own follows a Session that moves. That is the behaviour the
+ flag exists to opt out of: a scheduled job should not relocate because someone ran
+ ``vibe session update --cwd`` on an unrelated conversation. Both directories exist
+ here and hold different files, so the assertion cannot pass by falling back.
+ """
+
+ _command_task_env(tmp_path, monkeypatch)
+ session_dir = tmp_path / "session"
+ session_dir.mkdir()
+ (session_dir / "marker").write_text("session-workdir\n", encoding="utf-8")
+ pinned = tmp_path / "pinned"
+ pinned.mkdir()
+ (pinned / "marker").write_text("pinned-workdir\n", encoding="utf-8")
+
+ store = ScheduledTaskStore()
+ session_id = _bare_session_row(workdir=session_dir, anchor="avibe_task_pinned_cwd")
+ task = store.add_task(
+ session_key="",
+ session_id=session_id,
+ session_policy="existing",
+ prompt="",
+ schedule_type="cron",
+ cron="0 * * * *",
+ timezone_name="UTC",
+ cwd=str(pinned),
+ deliver_key="slack::channel::C123",
+ shell_command="cat marker",
+ metadata={"origin": "cli", "on_failure": "agent"},
+ )
+ service = _scheduled_service_with_ledger(tmp_path, store, [])
+
+ run = _fire_command_task(service, task)
+
+ assert run["status"] == "succeeded", run["error"]
+ assert "pinned-workdir" in (run["stdout"] or ""), (
+ "the definition's own cwd lost to the Session it only escalates into, so "
+ f"--cwd cannot pin a scheduled command at all: {run['stdout']!r}"
+ )
+
+
def test_an_escalating_command_runs_in_its_bound_sessions_workdir(
tmp_path: Path, monkeypatch
) -> None:
"""SCT-008 -- the relative commands the docs promise have to resolve somewhere.
- ``--cwd`` is REFUSED for a definition bound to an existing Session, on the rule
- that the Session owns its working directory (`cwd_with_existing_session`), so the
- CLI stores ``cwd=None``. For a message task that is complete: the Agent turn starts
- in the Session's workdir. A command task has no Agent turn to inherit it from, so
- the stored ``None`` fell through to the ``~/.avibe`` fallback -- meaning
- ``--shell './scripts/sync.sh'``, the form the docs use, ran from the product state
- directory with no way to override it: the flag that would fix it is the one the
- Session rule rejects.
-
- So the binding has to supply what it refused to let the user state.
+ A definition bound to an existing Session stores ``cwd=None`` unless its command
+ was given one: ``--cwd`` is still refused for a MESSAGE task, on the rule that the
+ Session owns its working directory (`cwd_with_existing_session`), and for a message
+ task that is complete -- the Agent turn starts in the Session's workdir. A command
+ task has no Agent turn to inherit it from, so the stored ``None`` fell through to
+ the ``~/.avibe`` fallback, meaning ``--shell './scripts/sync.sh'``, the form the
+ docs use, ran from the product state directory.
+
+ A command task can now name its own directory
+ (``test_task_add_escalating_command_task_accepts_an_explicit_cwd``). This is the
+ other half: what happens when it does not. The binding supplies the answer, and
+ goes on supplying it, so omitting the flag keeps the behaviour every task created
+ before it relies on.
The lookup opens a store per FIRE, and each one carries an engine and an
invalidation probe, so the second assertion is that it does not outlive the read:
diff --git a/ui/src/components/workbench/HarnessPage.test.tsx b/ui/src/components/workbench/HarnessPage.test.tsx
index 655c0dc97..1b761575f 100644
--- a/ui/src/components/workbench/HarnessPage.test.tsx
+++ b/ui/src/components/workbench/HarnessPage.test.tsx
@@ -6,6 +6,7 @@ import { MemoryRouter } from 'react-router-dom';
import { describe, expect, it } from 'vitest';
import en from '../../i18n/en.json';
+import zh from '../../i18n/zh.json';
import type {
ApiContextType,
HarnessRun,
@@ -549,6 +550,109 @@ describe('TaskDetail command task', () => {
expect(message).toContain(`>${i18n.t('harness.detail.sessionPolicy')}<`);
});
+ it('shows where the command runs, and names the source when it follows a session', () => {
+ // SCT-052. ``WatchDetail`` has shown the working directory since it shipped; the task pane
+ // never did, so a scheduled command's directory was unanswerable from the UI even
+ // once ``--cwd`` could store one.
+ const pinned = detail(task({ shell_command: 'make test', cwd: '/srv/app' }));
+ expect(pinned).toContain(`>${i18n.t('harness.detail.cwd')}<`);
+ expect(pinned).toContain('/srv/app');
+
+ // A null is not "nowhere": the fire walks a chain, which is a different answer
+ // from the bare em-dash a missing field would print. Stated as the chain rather
+ // than as an outcome — ``_bound_session_workdir`` answers None for a NULL workdir
+ // or a failed read too, so "Session working directory" was a promise the pane
+ // cannot keep.
+ const inherited = detail(
+ task({ shell_command: 'make test', session_id: 'ses1', session_platform: 'slack', cwd: null }),
+ );
+ expect(inherited).toContain(i18n.t('harness.detail.cwdFromSession'));
+ });
+
+ it('does not name a session the command cannot inherit a directory from', () => {
+ // SCT-055. A binding whose Session row is gone resolves to None at fire time and falls
+ // through to the runtime default — so naming the Session here would contradict the
+ // "Session deleted" the Session field prints two rows up, and misstate where the
+ // command runs.
+ const deleted = detail(task({ shell_command: 'make test', session_id: 'ses-gone', cwd: null }));
+ expect(deleted).toContain(i18n.t('harness.detail.cwdRuntimeDefault'));
+ expect(deleted).not.toContain(i18n.t('harness.detail.cwdFromSession'));
+
+ const unbound = detail(task({ shell_command: 'make test', session_id: null, cwd: null }));
+ expect(unbound).toContain(i18n.t('harness.detail.cwdRuntimeDefault'));
+
+ // Asserted on the copy itself because that is where the claim lives. The chain does
+ // not end at ``runtime.default_cwd`` — it is unset on a fresh install and
+ // revalidated on every fire, and ``_execute_command_task`` then falls through to the
+ // Avibe state directory. Naming only the config key is the same overclaim as naming
+ // the Session, one link further down.
+ expect(en.harness.detail.cwdRuntimeDefault).toMatch(/Avibe/);
+ expect(en.harness.detail.cwdFromSession).toMatch(/Avibe/);
+ expect(zh.harness.detail.cwdRuntimeDefault).toMatch(/Avibe/);
+ expect(zh.harness.detail.cwdFromSession).toMatch(/Avibe/);
+ });
+
+ it('states the failure policy before the routing it governs, not after it', () => {
+ // SCT-052. The five routing fields describe a path that runs on no healthy day. Rendered
+ // above the ``On failure`` that qualifies them, the pane read top-down as "this
+ // job spends an Agent turn every morning" — the exact cost an agent-free command
+ // task is chosen to avoid.
+ const html = detail(task({ shell_command: 'make test', metadata: { on_failure: 'agent' } }));
+
+ const onFailure = html.indexOf(`>${i18n.t('harness.detail.onFailure')}<`);
+ const agent = html.indexOf(`>${i18n.t('harness.detail.agent')}<`);
+ expect(onFailure).toBeGreaterThan(-1);
+ expect(agent).toBeGreaterThan(-1);
+ expect(onFailure).toBeLessThan(agent);
+ expect(html).toContain(`>${i18n.t('harness.detail.escalation')}<`);
+ });
+
+ it('calls an escalating command task\'s message a triage prompt, not the job', () => {
+ // SCT-052. Same label as a message task's payload, entirely different meaning: this text is
+ // sent only when the command fails.
+ const html = detail(
+ task({ shell_command: 'make test', message: 'Diagnose it.', metadata: { on_failure: 'agent' } }),
+ );
+
+ expect(html).toContain(`>${i18n.t('harness.detail.triagePrompt')}<`);
+ expect(html).not.toContain(`>${i18n.t('harness.detail.message')}<`);
+ expect(html).toContain('Diagnose it.');
+ });
+
+ it('calls nothing an escalation on a command task that escalates to no one', () => {
+ // SCT-054. The routing gate is SCT-043's: bindings, not kind. A command task with
+ // ``--on-failure none`` delivered to a real conversation keeps these fields
+ // legitimately — and heading them "On failure → escalation" would have the pane
+ // say "Notice only (no Agent)" and "escalation" about the same task, one field
+ // apart.
+ const html = detail(
+ task({
+ shell_command: 'make test',
+ session_key: 'slack::channel::C123',
+ post_to: 'thread',
+ message: 'Left over from an older edit.',
+ metadata: { on_failure: 'none' },
+ }),
+ );
+
+ expect(html).toContain(`>${i18n.t('harness.onFailure.none')}<`);
+ expect(html).toContain(`>${i18n.t('harness.detail.delivery')}<`);
+ expect(html).not.toContain(`>${i18n.t('harness.detail.escalation')}<`);
+ expect(html).not.toContain(`>${i18n.t('harness.detail.triagePrompt')}<`);
+ expect(html).toContain(`>${i18n.t('harness.detail.message')}<`);
+ });
+
+ it('leaves a message task reading as the job it is', () => {
+ // SCT-054. A message task routes EVERY run through those fields, so grouping them under a
+ // failure heading would be a lie in the other direction.
+ const html = detail(task({ prompt: 'Summarize #ops', message: 'Summarize #ops' }));
+
+ expect(html).toContain(`>${i18n.t('harness.detail.message')}<`);
+ expect(html).not.toContain(`>${i18n.t('harness.detail.escalation')}<`);
+ expect(html).not.toContain(`>${i18n.t('harness.detail.triagePrompt')}<`);
+ expect(html).not.toContain(`>${i18n.t('harness.detail.onFailure')}<`);
+ });
+
it('drops the Message field a command task has nothing to put in', () => {
const html = detail(commandTask);
diff --git a/ui/src/components/workbench/HarnessPage.tsx b/ui/src/components/workbench/HarnessPage.tsx
index ff026def3..3f8f918bc 100644
--- a/ui/src/components/workbench/HarnessPage.tsx
+++ b/ui/src/components/workbench/HarnessPage.tsx
@@ -1209,6 +1209,29 @@ const RowActions: React.FC<RowActionsProps> = ({ enabled, pending, onToggle, onD
);
};
+/** What to print for a command task that stores no working directory of its own.
+ *
+ * Names the CHAIN the fire actually walks (``_execute_command_task``) -- the bound
+ * Session's workdir read live, then ``runtime.default_cwd``, then the Avibe state
+ * directory -- rather than an outcome the pane cannot verify. "Session working
+ * directory" was the wrong promise: ``_bound_session_workdir`` answers ``None`` for a
+ * deleted row, a NULL workdir or a failed read, and every fallback is
+ * ``isdir``-validated besides, so the command can land further down the chain while the
+ * pane names a Session. The last term is not decoration either -- ``default_cwd`` is
+ * unset on a fresh install and revalidated on every fire, so "Runtime default" alone
+ * named a specific config key that the run may never reach.
+ *
+ * Where the pane can already see the first term is impossible -- no binding at all, or
+ * one whose Session row is gone (the same ``deleted`` state the Session field prints
+ * two rows up) -- it drops that term instead of contradicting itself.
+ */
+function commandCwdFallbackKey(task: HarnessTask): string {
+ const state = harnessSessionState(task, task.session_id);
+ return state === 'none' || state === 'deleted'
+ ? 'harness.detail.cwdRuntimeDefault'
+ : 'harness.detail.cwdFromSession';
+}
+
interface TaskDetailProps {
task: HarnessTask;
agent?: VibeAgentBrief;
@@ -1216,10 +1239,55 @@ interface TaskDetailProps {
pending: boolean;
}
+/** Agent, Session, session mode, delivery and the message they carry.
+ *
+ * One component because they are one answer -- who runs this, where it lands -- and
+ * because a command task needs that answer said differently: it routes only a FAILURE,
+ * and its message is triage guidance rather than the payload of every run. Both
+ * differences are wording and framing, so they are props here instead of a second copy
+ * of the fields.
+ */
+const RoutingFields: React.FC<{
+ task: HarnessTask;
+ agent?: VibeAgentBrief;
+ group?: string;
+ messageLabel: string;
+ showMessage: boolean;
+}> = ({ task, agent, group, messageLabel, showMessage }) => {
+ const { t } = useTranslation();
+ const fields = (
+ <>
+ <DetailField label={t('harness.detail.agent')}>
+ <DetailAgent agentName={task.agent_name} agent={agent} />
+ </DetailField>
+ <DetailField label={t('harness.detail.session')}>
+ <DetailSession summary={task} sessionId={task.session_id} />
+ </DetailField>
+ <div className="grid grid-cols-2 gap-4">
+ <DetailField label={t('harness.detail.sessionPolicy')}>
+ <span className="text-[12px] text-foreground">{sessionPolicyLabel(task.session_policy, t)}</span>
+ </DetailField>
+ <DetailField label={t('harness.detail.delivery')}>
+ <span className="text-[12px] text-foreground">{deliveryLabel(task.post_to, t)}</span>
+ </DetailField>
+ </div>
+ {showMessage && (
+ <DetailField label={messageLabel}>
+ <pre className="max-h-44 overflow-auto whitespace-pre-wrap rounded-md border border-border bg-surface-3 p-2 font-mono text-[11px] text-foreground">
+ {task.message || task.prompt || '—'}
+ </pre>
+ </DetailField>
+ )}
+ </>
+ );
+ return group ? <DetailGroup label={group}>{fields}</DetailGroup> : fields;
+};
+
export const TaskDetail: React.FC<TaskDetailProps> = ({ task, agent, onToggleEnabled, pending }) => {
const { t } = useTranslation();
const isCommand = taskIsCommand(task);
const commandPreview = isCommand ? taskCommandPreview(task) : '';
+ const escalates = isCommand && taskOnFailure(task) === 'agent';
const routesSomewhere =
!isCommand ||
taskOnFailure(task) === 'agent' ||
@@ -1254,6 +1322,32 @@ export const TaskDetail: React.FC<TaskDetailProps> = ({ task, agent, onToggleEna
</pre>
</DetailField>
)}
+ {/* Where the command runs and how long it may take -- process mechanics, so they
+ sit with the command rather than with the failure lane below. ``WatchDetail``
+ has shown the working directory since it shipped; the task pane never did, so
+ a scheduled command's directory was unanswerable from the UI even once
+ ``--cwd`` stored one. A null is not "nowhere": the fire walks a chain, so the
+ field names the chain rather than printing the em-dash a missing field would.
+ */}
+ {isCommand && (
+ <div className="grid grid-cols-2 gap-4">
+ <DetailField label={t('harness.detail.cwd')}>
+ <code className="font-mono text-[11px] text-muted">
+ {task.cwd || t(commandCwdFallbackKey(task))}
+ </code>
+ </DetailField>
+ <DetailField label={t('harness.detail.timeout')}>
+ {/* Always rendered, because a limit is always in force: a row with no
+ stored timeout is run under the six-hour default, and hiding the
+ field read as "no limit". A stored 0 IS "no limit" server-side, and
+ printing "0s" would read as an instant kill — the opposite. The
+ default is shown in duration words ("6h") because it is a policy
+ constant nobody typed; a stored value is echoed in the seconds the
+ user actually set. */}
+ <span className="font-mono text-[11px] text-muted">{formatTimeout(task, t)}</span>
+ </DetailField>
+ </div>
+ )}
{/* The row humanizes the schedule; this is where the literal lives, so
an operator can still read and copy the exact expression. */}
<DetailField label={t('harness.detail.schedule')}>
@@ -1280,56 +1374,46 @@ export const TaskDetail: React.FC<TaskDetailProps> = ({ task, agent, onToggleEna
not have. Shown as soon as anything here is real: an escalation turn
(``--on-failure agent``), a pinned Agent, or a conversation a failure
notice is delivered to. */}
+ {/* BEFORE the routing it governs, not after it. "no Agent" is a deliberate
+ configuration rather than an omission, so it is stated rather than left
+ blank — and when it says the opposite, it is the sentence that makes the
+ block below mean "only when this fails". */}
+ {isCommand && (
+ <DetailField label={t('harness.detail.onFailure')}>
+ <span className="text-[12px] text-foreground">{t(`harness.onFailure.${taskOnFailure(task)}`)}</span>
+ </DetailField>
+ )}
{routesSomewhere && (
- <>
- <DetailField label={t('harness.detail.agent')}>
- <DetailAgent agentName={task.agent_name} agent={agent} />
- </DetailField>
- <DetailField label={t('harness.detail.session')}>
- <DetailSession summary={task} sessionId={task.session_id} />
- </DetailField>
- <div className="grid grid-cols-2 gap-4">
- <DetailField label={t('harness.detail.sessionPolicy')}>
- <span className="text-[12px] text-foreground">{sessionPolicyLabel(task.session_policy, t)}</span>
- </DetailField>
- <DetailField label={t('harness.detail.delivery')}>
- <span className="text-[12px] text-foreground">{deliveryLabel(task.post_to, t)}</span>
- </DetailField>
- </div>
- </>
+ <RoutingFields
+ task={task}
+ agent={agent}
+ // Only an ESCALATING command task is describing a path it does not take on a
+ // healthy day. A message task routes every run through these same fields, so
+ // grouping them under a failure heading there would be a lie in the other
+ // direction -- and so would grouping them for a command task whose
+ // ``on_failure`` is ``none``. That row is exactly what SCT-043's gate keeps:
+ // no Agent turn, but a real Session or delivery target carrying the failure
+ // notice. Keyed on the same value the field above prints, so the pane cannot
+ // say "Notice only (no Agent)" and "escalation" about one task.
+ group={escalates ? t('harness.detail.escalation') : undefined}
+ messageLabel={escalates ? t('harness.detail.triagePrompt') : t('harness.detail.message')}
+ showMessage={Boolean(!isCommand || task.message || task.prompt)}
+ />
)}
{/* A command task's ``prompt`` is empty by construction, so this field
would render a bare em-dash under the heading "Message" — a promise of
a message the task does not have. A command task that *also* carries
- one (``--on-failure agent``) still shows it. */}
- {(!isCommand || task.message || task.prompt) && (
+ one (``--on-failure agent``) shows it above, inside the escalation
+ group, because that is the only thing it is. This is the leftover case:
+ a stored message with nothing to route it, which no current CLI path
+ creates and old rows still can. Shown rather than dropped. */}
+ {!routesSomewhere && (task.message || task.prompt) && (
<DetailField label={t('harness.detail.message')}>
<pre className="max-h-44 overflow-auto whitespace-pre-wrap rounded-md border border-border bg-surface-3 p-2 font-mono text-[11px] text-foreground">
{task.message || task.prompt || '—'}
</pre>
</DetailField>
)}
- {/* What a failed run does, and how long it is allowed to take. Both are
- command-task-only policy, and both are unanswerable from anything else
- on this pane — "no Agent" is a deliberate configuration, not an
- omission, so it is stated rather than left blank. */}
- {isCommand && (
- <div className="grid grid-cols-2 gap-4">
- <DetailField label={t('harness.detail.onFailure')}>
- <span className="text-[12px] text-foreground">{t(`harness.onFailure.${taskOnFailure(task)}`)}</span>
- </DetailField>
- <DetailField label={t('harness.detail.timeout')}>
- {/* Always rendered, because a limit is always in force: a row with no
- stored timeout is run under the six-hour default, and hiding the
- field read as "no limit". A stored 0 IS "no limit" server-side, and
- printing "0s" would read as an instant kill — the opposite. The
- default is shown in duration words ("6h") because it is a policy
- constant nobody typed; a stored value is echoed in the seconds the
- user actually set. */}
- <span className="font-mono text-[11px] text-muted">{formatTimeout(task, t)}</span>
- </DetailField>
- </div>
- )}
{task.last_run_at && (
<DetailField label={t('harness.detail.lastRun')}>
<span className="font-mono text-[11px] text-muted">{formatLocalDateTime(task.last_run_at)}</span>
@@ -2008,6 +2092,21 @@ const DetailField: React.FC<DetailFieldProps> = ({ label, children }) => (
</div>
);
+/** A named group of fields that answer one question, indented under that question.
+ *
+ * Written for the escalation lane: five fields describing a path that runs on no
+ * healthy day, rendered at the same weight as the command and the schedule, said the
+ * task's daily work was an Agent turn on Opus. The fields are right (see
+ * ``routesSomewhere``) and the fix is not to hide them -- it is to say what they
+ * belong to, above them rather than below.
+ */
+const DetailGroup: React.FC<{ label: string; children: React.ReactNode }> = ({ label, children }) => (
+ <div className="flex flex-col gap-4 border-l-2 border-border pl-3">
+ <div className="font-mono text-[10px] font-bold uppercase tracking-[0.12em] text-muted">{label}</div>
+ {children}
+ </div>
+);
+
const EmptyState: React.FC<{ i18nKey: string }> = ({ i18nKey }) => {
const { t } = useTranslation();
return (
diff --git a/ui/src/context/ApiContext.tsx b/ui/src/context/ApiContext.tsx
index 017e375dd..abb37bc2c 100644
--- a/ui/src/context/ApiContext.tsx
+++ b/ui/src/context/ApiContext.tsx
@@ -1338,6 +1338,11 @@ export type HarnessTask = HarnessSessionSummary & HarnessDefinitionState & {
timeout_seconds?: number | null;
last_exit_code?: number | null;
metadata?: Record<string, unknown> | null;
+ // Where a command task's subprocess runs. Null is not "nowhere": a definition
+ // bound to a Session follows that Session's workdir, read live at fire time
+ // (``_bound_session_workdir``), so the pane names the source rather than
+ // printing a blank.
+ cwd?: string | null;
};
export type HarnessWatchRuntime = {
diff --git a/ui/src/i18n/en.json b/ui/src/i18n/en.json
index 52414b4d7..470b833e2 100644
--- a/ui/src/i18n/en.json
+++ b/ui/src/i18n/en.json
@@ -2902,7 +2902,11 @@
"timeoutSeconds": "{{seconds}}s",
"timeoutNone": "No timeout",
"timeoutDefault": "{{duration}} (default)",
- "lastExitCode": "Last exit code"
+ "lastExitCode": "Last exit code",
+ "escalation": "On failure → escalation",
+ "triagePrompt": "Triage prompt",
+ "cwdFromSession": "Bound session, else runtime default or Avibe state dir",
+ "cwdRuntimeDefault": "Runtime default, else Avibe state dir"
},
"taskKind": {
"command": "Command"
diff --git a/ui/src/i18n/zh.json b/ui/src/i18n/zh.json
index ba29beb16..11eceafbe 100644
--- a/ui/src/i18n/zh.json
+++ b/ui/src/i18n/zh.json
@@ -2902,7 +2902,11 @@
"timeoutSeconds": "{{seconds}} 秒",
"timeoutNone": "不限时",
"timeoutDefault": "{{duration}}(默认)",
- "lastExitCode": "最近退出码"
+ "lastExitCode": "最近退出码",
+ "escalation": "失败后 → 交给 Agent",
+ "triagePrompt": "排查提示词",
+ "cwdFromSession": "跟随绑定会话,否则运行时默认目录或 Avibe 状态目录",
+ "cwdRuntimeDefault": "运行时默认目录,否则 Avibe 状态目录"
},
"taskKind": {
"command": "命令"
diff --git a/vibe/cli.py b/vibe/cli.py
index f03cdc23b..ab08f9dac 100644
--- a/vibe/cli.py
+++ b/vibe/cli.py
@@ -501,6 +501,8 @@ def _task_add_examples_text() -> str:
Failure handling is silent-success by default: a successful run stays quiet, and a failed run records a failure notice.
Add --on-failure agent with --message to spend an Agent turn triaging a failed run instead.
--timeout bounds one run; use 0 for no timeout.
+ --cwd is where the command runs; without it, a Session-bound command follows that Session's directory
+ and every other command records the directory you ran this from.
Examples:
vibe task add --session-id sesk8m4q2p7x --cron '0 * * * *' --message 'Share the hourly summary.'
@@ -3299,11 +3301,16 @@ def cmd_task_add(args):
existing_cwd=None,
session_policy=session_policy,
scoped_session=_has_modern_scope_target(args),
+ has_command=has_command,
help_command="vibe task add --help",
)
session_workdir = cwd
cwd = _command_definition_spawn_cwd(
- cwd, has_command=has_command, session_policy=session_policy
+ cwd,
+ has_command=has_command,
+ session_policy=session_policy,
+ explicit_cwd=getattr(args, "cwd", None),
+ help_command="vibe task add --help",
)
agent_resolution = _resolve_agent_target(
agent_name=getattr(args, "agent", None),
@@ -3321,7 +3328,11 @@ def cmd_task_add(args):
agent_name=agent_name,
agent_id=agent.id if agent else None,
deliver_key=scope_key or "",
- workdir=cwd,
+ # The SESSION half, captured before the command's overwrote it. The
+ # two agree here today, but reading the command's answer is what
+ # made the update path place a Session in a subprocess directory,
+ # and the same line is the one that would do it here.
+ workdir=session_workdir,
help_command="vibe task add --help",
require_enabled_agent=expected_enabled_agent_id is not None,
expected_reference_agent_id=expected_reference_agent_id,
@@ -3937,13 +3948,40 @@ def cmd_task_update(args):
current_policy=task.session_policy,
current_session_id=task.session_id,
create_session=bool(getattr(args, "create_session", False)),
+ has_command=task.has_command,
help_command="vibe task update --help",
)
- if session_policy == "existing":
+ # This edit is not placing a Session: the definition is bound to one that owns
+ # its own directory, or has already reserved its reusable one and passed no
+ # --create-session to replace it. For a message task that leaves ``--cwd``
+ # nothing to do, and the two refusals above say so. For a command task it
+ # leaves exactly one question -- where the subprocess runs -- so the flag is
+ # resolved as the command's alone and the Session's half is read back from
+ # storage untouched. Without the branch, every path below writes SOME answer
+ # into ``session_workdir``, and for a command task that answer is the command's
+ # directory: an unrelated ``--name`` edit on a reserved definition wrote the
+ # subprocess directory into ``metadata["session_workdir"]``.
+ command_only_cwd = task.has_command and (
+ session_policy == "existing"
+ or (
+ session_policy == "create_once"
+ and bool(task.session_id)
+ and not getattr(args, "create_session", False)
+ )
+ )
+ if command_only_cwd:
+ session_workdir = _stored_session_workdir(task, metadata)
+ cwd = _resolve_command_only_cwd(
+ explicit_cwd,
+ stored_cwd=task.cwd,
+ help_command="vibe task update --help",
+ )
+ elif session_policy == "existing":
cwd = _resolve_definition_session_cwd(
explicit_cwd=explicit_cwd,
existing_cwd=None,
session_policy=session_policy,
+ has_command=task.has_command,
help_command="vibe task update --help",
)
elif explicit_cwd is not None:
@@ -3957,17 +3995,32 @@ def cmd_task_update(args):
elif getattr(args, "create_session", False) or getattr(args, "create_session_per_run", False):
cwd = _resolve_definition_session_cwd(
explicit_cwd=None,
- existing_cwd=task.cwd,
+ existing_cwd=_stored_session_workdir(task, metadata),
session_policy=session_policy,
scoped_session=_has_modern_scope_target(args) or bool(str(metadata.get("session_scope_id") or "").strip()),
help_command="vibe task update --help",
)
else:
- cwd = task.cwd
- session_workdir = cwd
- cwd = _command_definition_spawn_cwd(
- cwd, has_command=task.has_command, session_policy=session_policy
- )
+ # Nothing in this edit asks about directories, so each half carries forward
+ # from where that half is stored. For a message task ``task.cwd`` IS the
+ # Session's answer; for a command task it is the command's alone, and
+ # reading it here promoted it into ``metadata["session_workdir"]`` -- so a
+ # plain ``--name`` on a per-run definition that deliberately left its
+ # Sessions unplaced (SCT-047) pinned every future one to the directory
+ # ``task add`` happened to be typed in, and a ``create_once`` definition
+ # that had not reserved yet reserved there. The command half is untouched:
+ # ``_command_definition_spawn_cwd`` falls back to ``stored_cwd`` below.
+ cwd = _stored_session_workdir(task, metadata) if task.has_command else task.cwd
+ if not command_only_cwd:
+ session_workdir = cwd
+ cwd = _command_definition_spawn_cwd(
+ cwd,
+ has_command=task.has_command,
+ session_policy=session_policy,
+ explicit_cwd=explicit_cwd,
+ stored_cwd=task.cwd,
+ help_command="vibe task update --help",
+ )
scope_key = requested_scope_key or str(metadata.get("session_scope_id") or "").strip() or _legacy_scope_key_from_target(deliver_key)
if session_policy == "create_once" and not scope_key:
raise TaskCliError(
@@ -4013,7 +4066,13 @@ def cmd_task_update(args):
agent_name=agent_name,
agent_id=agent.id if agent else None,
deliver_key=scope_key,
- workdir=cwd,
+ # The SESSION half, captured before ``_command_definition_spawn_cwd``
+ # overwrote ``cwd`` with the command's. Reading ``cwd`` here handed the
+ # replacement Session the directory the user picked for a subprocess,
+ # so it stopped inheriting from its Scope -- the same defect
+ # ``_stored_session_workdir`` closes one branch earlier, through the
+ # one line that could reintroduce it.
+ workdir=session_workdir,
help_command="vibe task update --help",
require_enabled_agent=expected_enabled_agent_id is not None,
expected_reference_agent_id=expected_reference_agent_id,
@@ -4968,9 +5027,21 @@ def _reject_inert_create_once_cwd_update(
current_policy: Optional[str],
current_session_id: Optional[str],
create_session: bool,
+ has_command: bool = False,
help_command: str,
) -> None:
- if explicit_cwd is None or create_session:
+ """Refuse a ``--cwd`` that would change nothing, for the tasks where it changes nothing.
+
+ A reusable Session that has already been reserved owns its workdir, so for a
+ message task the flag is inert and saying so beats accepting it silently. A command
+ task in the same position still has the other question to answer -- where its
+ subprocess runs -- and this refusal reached it first, so the only way to repoint a
+ nightly command was to replace an escalation Session that had nothing to do with
+ the request. Same rule as ``_resolve_definition_session_cwd``'s, softened the same
+ way and for the same reason.
+ """
+
+ if explicit_cwd is None or create_session or has_command:
return
if current_policy == "create_once" and current_session_id:
raise TaskCliError(
@@ -5085,11 +5156,27 @@ def _resolve_definition_session_cwd(
existing_cwd: Optional[str],
session_policy: str,
scoped_session: bool = False,
+ has_command: bool = False,
help_command: str,
) -> Optional[str]:
+ """Where a Session this definition CREATES should run. Never the command's answer.
+
+ The ``existing`` refusal states a rule that is still true -- a Session bound here
+ owns its own directory, and a definition pointing at one must not rewrite it. What
+ it must not also do is refuse the OTHER question. A command task binds to an
+ existing Session for a reason unrelated to where it runs (``--on-failure agent``
+ needs somewhere to escalate), so the refusal landed on ``--cwd`` as collateral and
+ left the command with no way to say where it spawns.
+
+ ``has_command`` therefore softens the refusal rather than widening the return: this
+ still answers only the Session question, and answers it ``None``, so nothing writes
+ a workdir onto a Session that owns one. ``_command_definition_spawn_cwd`` picks the
+ flag up as the command's half.
+ """
+
raw = (explicit_cwd or "").strip()
if session_policy == "existing":
- if raw:
+ if raw and not has_command:
raise TaskCliError(
"--cwd only applies when this definition creates new Sessions",
code="cwd_with_existing_session",
@@ -5113,6 +5200,9 @@ def _command_definition_spawn_cwd(
*,
has_command: bool,
session_policy: str,
+ explicit_cwd: Optional[str] = None,
+ stored_cwd: Optional[str] = None,
+ help_command: str = "vibe task add --help",
) -> Optional[str]:
"""Where this definition's COMMAND runs, given where its Session would run.
@@ -5130,11 +5220,101 @@ def _command_definition_spawn_cwd(
-- an ``existing`` binding is read live from its Session at fire time, and
``create_once`` reserves its Session immediately -- and never over an explicit
``--cwd``.
+
+ ``explicit_cwd`` is that flag arriving for the one policy whose Session question
+ answers ``None`` on purpose. Every other policy has already folded it into
+ ``session_cwd``, where it is BOTH answers at once: a created Session and its
+ command run in the same place. An ``existing`` binding is the case where the two
+ genuinely differ -- the Session keeps its directory, the command gets the one the
+ user named -- so the flag is resolved here, under the same ``cwd_not_found`` check
+ every other policy gives it, and stored as the definition's ``cwd``. Fire time
+ already prefers that over the bound Session's live workdir
+ (``_bound_session_workdir``), so omitting the flag keeps today's
+ inherit-from-Session behaviour untouched.
+
+ ``stored_cwd`` is what an UPDATE must not drop. A bound definition resolves its
+ Session question to ``None`` on every edit, and the update path persists that with
+ ``update_cwd=True`` -- so without this, renaming an escalating command task would
+ silently un-pin the directory it was created with, and the next fire would go back
+ to following the Session. Only the explicit flag replaces it, and it outranks the
+ invocation directory for every policy rather than only for ``existing``: a policy
+ change is not a request to move the command, and re-stamping the directory the
+ UPDATE happened to run from is the same silent relocation in a different lane.
+ It outranks ``session_cwd`` for the same reason. The two are equal wherever
+ ``--cwd`` set both, and differ exactly where the user separated them -- a bound
+ command moved to B while its Session keeps A -- so reading the Session half first
+ let a later ``--create-session*`` carry A forward onto the command and move it
+ back. ``stored_cwd`` defaults to ``None``, so ``task add`` -- which has nothing
+ stored yet -- resolves exactly as it did before.
"""
- if not has_command or session_cwd or session_policy != "create_per_run":
+ if not has_command:
return session_cwd
- return os.getcwd()
+ raw = (explicit_cwd or "").strip()
+ if raw:
+ # The flag is the command's answer wherever it arrives. A creating policy has
+ # already folded it into ``session_cwd`` -- same directory, both halves -- so
+ # resolving it again here returns the same path; an ``existing`` binding answers
+ # its Session question ``None`` on purpose, and this is the only place the flag
+ # can be picked up at all.
+ return _resolve_existing_cwd(raw, help_command=help_command, code="cwd_not_found", label="task")
+ if stored_cwd:
+ # Before ``session_cwd``, because the two can legitimately differ and only one of
+ # them is an answer to this question. Once ``--cwd`` moves a bound command to B
+ # while its Session keeps A, a later ``--create-session*`` carrying A forward
+ # resolved the command to A as well -- moving it back, with nothing in the edit
+ # asking to. Same rule as ``_resolve_command_only_cwd``'s and SCT-051's: only the
+ # explicit flag replaces a stored directory.
+ return stored_cwd
+ if session_cwd:
+ return session_cwd
+ if session_policy == "create_per_run":
+ return os.getcwd()
+ return None
+
+
+def _resolve_command_only_cwd(
+ explicit_cwd: Optional[str],
+ *,
+ stored_cwd: Optional[str],
+ help_command: str,
+) -> Optional[str]:
+ """``--cwd`` for an edit that answers the command question and nothing else.
+
+ Under the same ``cwd_not_found`` check every other policy gives the flag. Omitting
+ it keeps the stored directory rather than re-deriving one, because a definition
+ whose Session is already settled has no other source to fall back to and the
+ invocation directory of an unrelated edit is not an answer anybody asked for.
+ """
+
+ raw = (explicit_cwd or "").strip()
+ if raw:
+ return _resolve_existing_cwd(raw, help_command=help_command, code="cwd_not_found", label="task")
+ return stored_cwd
+
+
+def _stored_session_workdir(task, metadata: Optional[dict]) -> Optional[str]:
+ """The SESSION half of what a definition already stores, for a policy change.
+
+ Retargeting at ``--create-session``/``--create-session-per-run`` without naming a
+ directory carries forward the one the definition already had. For a message task
+ ``task.cwd`` IS that directory: the Session question and the run question are the
+ same question, answered once at ``task add``.
+
+ For a command task they can differ, and since the ``existing`` refusal was softened
+ they routinely do -- ``task.cwd`` is where the COMMAND runs. The Session half lives
+ in ``metadata["session_workdir"]``, or is deliberately absent: a bound definition
+ never had one, and a per-run definition leaves it unset on purpose so an
+ escalation's Session follows its Scope (SCT-047). Reading ``task.cwd`` for it
+ promotes a directory the user picked for a subprocess into a Session placement they
+ never asked for, and the newly created Session stops inheriting from its Scope with
+ nothing in the edit saying so. ``_command_definition_spawn_cwd`` keeps the command
+ half from its own ``stored_cwd``, so the two survive the retarget separately.
+ """
+
+ if not task.has_command:
+ return task.cwd
+ return str((metadata or {}).get("session_workdir") or "").strip() or None
def _has_modern_scope_target(args) -> bool:
@@ -14537,7 +14717,13 @@ def build_parser():
task_add_parser.add_argument("--same-scope", action="store_true", help="Place a created Session in the caller Session scope")
task_add_parser.add_argument("--scope-id", help="Existing scopes.id that should own created Sessions")
task_add_parser.add_argument("--agent", help="Avibe Agent name to use when the task runs")
- task_add_parser.add_argument("--cwd", help="Working directory for Sessions created by this task. Defaults to the caller's current directory.")
+ task_add_parser.add_argument(
+ "--cwd",
+ help=(
+ "Working directory for Sessions created by this task, and for a command task, "
+ "the directory its command runs in. Defaults to the caller's current directory."
+ ),
+ )
delivery_group = task_add_parser.add_mutually_exclusive_group()
delivery_group.add_argument(
"--post-to",
@@ -14606,7 +14792,10 @@ def build_parser():
task_update_parser.add_argument("--scope-id", help="Existing scopes.id that should own created Sessions")
task_update_parser.add_argument("--agent", help="Replace the Avibe Agent used by this task")
task_update_parser.add_argument("--clear-agent", action="store_true", help="Clear the stored Avibe Agent override")
- task_update_parser.add_argument("--cwd", help="Set working directory for Sessions created by this task")
+ task_update_parser.add_argument(
+ "--cwd",
+ help="Set working directory for Sessions created by this task, or for a command task, where its command runs",
+ )
update_delivery_group = task_update_parser.add_mutually_exclusive_group()
update_delivery_group.add_argument(
"--post-to",