Compare commits

..

No commits in common. "579ab635cd1a385c6e47dfb0d919be1341328ced" and "d93dbc053311bc85f3b9c08f4ad4b65866b4525e" have entirely different histories.

252 changed files with 6360 additions and 9013 deletions

View File

@ -2,7 +2,7 @@
title: 'Planning Ticket API and UI without queue operations'
state: 'planning'
created_at: '2026-06-23T19:41:51Z'
updated_at: '2026-06-25T16:38:49Z'
updated_at: '2026-06-23T19:41:51Z'
assignee: null
---

View File

@ -4,46 +4,4 @@
LocalTicketBackend によって作成されました。
---
<!-- event: intake_summary author: hare at: 2026-06-25T16:34:15Z -->
## Intake summary
Marked ready by `yoi ticket state`.
---
<!-- event: state_changed author: "yoi ticket" at: 2026-06-25T16:34:15Z from: planning to: ready reason: cli_state field: state -->
## State changed
Marked ready by `yoi ticket state`.
---
<!-- event: state_changed author: "yoi ticket" at: 2026-06-25T16:38:49Z from: ready to: planning reason: cli_state field: state -->
## State changed
State changed to `planning`.
---
<!-- event: decision author: hare at: 2026-06-25T16:38:49Z -->
## Decision
Returned to planning because the ticket is too broad in the current Runtime direction.
Planning Ticket creation from Web UI should not be a direct form-to-file mutation that bypasses Intake. The intended flow likely needs Backend embedded Runtime + Intake Worker first, then Web Intake/Planning UI on top.
Suggested split:
1. Ticket read API / list-detail UI only.
2. Backend embedded Intake Worker on worker-runtime.
3. Web Intake Console / Planning Ticket creation through Intake.
---

View File

@ -1 +0,0 @@
{"id":"orch-plan-20260625-164513-1","ticket_id":"00001KVZ9JGK0","kind":"blocked_by","related_ticket":"00001KVZSGT0Q","note":"Queue routing checked after Dashboard Queue. Backend internal Companion Runtime/Web Console depends on embedded worker-runtime Backend Registry connection `00001KVZSGT0Q`, which is still queued and itself blocked by earlier worker-runtime/core/Backend foundation dependencies. Do not start MVP implementation until that dependency chain is completed.","author":"yoi-orchestrator","at":"2026-06-25T16:45:13Z"}

View File

@ -4,10 +4,10 @@
{
"ticket_id": "00001KVZ9JGK0",
"kind": "depends_on",
"target": "00001KVZSGT0Q",
"note": "Backend internal Companion Web Console should build on embedded worker-runtime registration in Backend RuntimeRegistry.",
"target": "00001KVZBCQH4",
"note": "Backend internal Companion should run on the embeddable Runtime API.",
"author": "yoi ticket",
"at": "2026-06-25T16:30:00Z"
"at": "2026-06-25T13:25:34Z"
}
]
}

View File

@ -1,11 +1,9 @@
---
title: 'Backend内蔵Companion RuntimeとWeb Console MVP'
state: 'queued'
state: 'planning'
created_at: '2026-06-25T11:45:17Z'
updated_at: '2026-06-25T16:45:24Z'
updated_at: '2026-06-25T13:25:34Z'
assignee: null
queued_by: 'workspace-panel'
queued_at: '2026-06-25T16:44:45Z'
---
## 背景

View File

@ -5,58 +5,3 @@
LocalTicketBackend によって作成されました。
---
<!-- event: intake_summary author: hare at: 2026-06-25T16:34:16Z -->
## Intake summary
Marked ready by `yoi ticket state`.
---
<!-- event: state_changed author: "yoi ticket" at: 2026-06-25T16:34:16Z from: planning to: ready reason: cli_state field: state -->
## State changed
Marked ready by `yoi ticket state`.
---
<!-- event: state_changed author: workspace-panel at: 2026-06-25T16:44:45Z from: ready to: queued reason: queued field: state -->
## State changed
Ticket を `workspace-panel` が queued にしました。
---
<!-- event: decision author: yoi-orchestrator at: 2026-06-25T16:45:24Z -->
## Decision
Routing decision: blocked_by_dependency_or_missing_authority
Reason:
- Dashboard Queue による routing 許可を受けて Ticket / relations / orchestration plan / queue state を確認した。
- 本 Ticket は `00001KVZSGT0Q` (`Backend RuntimeRegistryにembedded worker-runtimeを接続する`) に `depends_on` relation を持つ。
- `00001KVZSGT0Q` は現在 `queued` で、さらに `00001KVZKSV6C` / `00001KVZBCQH4` の依存 chain により blocked と判断済み。
- Backend internal Companion Runtime / Web Console MVP は Backend RuntimeRegistry 上の embedded worker-runtime connection を前提にするため、基盤確定前に開始しない。
Evidence checked:
- Ticket body: Backend internal Companion runtime、conversation/transcript model、Web API、Web Console UI、Runtime/LLM integration、Safety/authority、Non-goals。
- Relations: outgoing `depends_on -> 00001KVZSGT0Q`
- Orchestration plan: blocker record `orch-plan-20260625-164513-1` を追加。
- Queue state: queued は本 Ticket を含む6件。inprogress は worker-runtime core `00001KVZBCQH4` 1件。
- Workspace state: core implementation is under reviewer Worker; dependent Backend Registry work is not accepted yet。
Next action:
- 本 Ticket は queued のまま待機。
- `00001KVZSGT0Q` が accepted/completed して Backend embedded runtime connection が使えるようになった後、再 routing する。
Escalate if:
- Companion MVP を `00001KVZSGT0Q` 完了前に独立 spike する human decision がある。
- Backend internal Runtime foundation の scope が Companion MVP requirements を満たさない。
---

View File

@ -1 +0,0 @@
{"id":"orch-plan-20260625-162107-1","ticket_id":"00001KVZBCQH4","kind":"accepted_plan","note":"Dashboard Queue による human-authorized routing。dependencies `00001KVZD10ED` は closed、`00001KVZG9BMS` は done で relation blockers は解消済み。","accepted_plan":{"summary":"`worker-runtime` core crate を最初の implementation slice として追加する。HTTP/WS/FS/remote は実装せず、memory-backed embedded Runtime API、Runtime/Worker identity、catalog/lifecycle/interaction/projection 型境界、internal store/allocation abstraction を実装する。`worker` crate の socket/session details は Runtime public API に再公開しない。","branch":"work/00001KVZBCQH4-worker-runtime-core","worktree":"/home/hare/Projects/yoi/.worktree/00001KVZBCQH4-worker-runtime-core","role_plan":"Orchestrator が `/home/hare/Projects/yoi/.worktree/orchestration` から child implementation worktree を作成し、coder Worker にその worktree の narrow write scope を委譲する。reviewer Worker は同 worktree read-only を基本とし、IntentPacket / acceptance criteria / runtime authority boundary / public API leakage を確認する。merge/validation/done/cleanup は Orchestrator が行う。"},"author":"yoi-orchestrator","at":"2026-06-25T16:21:07Z"}

View File

@ -1,156 +1,147 @@
---
title: 'worker-runtime core crateと組み込みRuntime APIを作る'
state: 'inprogress'
title: '組み込み/ネットワーク対応Worker Runtime crateを作る'
state: 'planning'
created_at: '2026-06-25T12:17:05Z'
updated_at: '2026-06-25T16:46:17Z'
updated_at: '2026-06-25T13:43:31Z'
assignee: null
queued_by: 'workspace-panel'
queued_at: '2026-06-25T16:20:10Z'
---
## 背景
Yoi は`Pod` 相当の実行単位を今後 `Worker` として扱い、`Runtime` が複数 Worker を保持・操作する構造へ移行する。`llm-worker` は `llm-engine` へ改名し、既存 `pod` crate は `worker` crate へ改名する。次に必要なのは、Backend が持つ `RuntimeRegistry` ではなく、**Worker を実際に動かす環境そのものとしての Runtime** を library として定義することである
Yoi は現在、Worker 的な実行単位を主に `yoi pod` process / Unix socket / pod metadata / session jsonl として扱っている。一方で今後は、Companion や routing-only Orchestrator を Backend process 内に組み込んだ Runtime 上の Worker として動かし、Coder / Reviewer などは local / remote host 上の Runtime process で動かしたい
この Ticket は `worker-runtime` 全体を一括実装する umbrella ではない。最初の実装 slice として、HTTP server、WebSocket/SSE server、FS 永続化、remote client は含めず、Backend などに組み込める `worker-runtime` core crate と memory-backed embedded Runtime API を作る。
このため、Backend が持つ `RuntimeRegistry` や Workspace API の都合ではなく、**Worker を動かす環境そのものとしての Runtime** を独立した crate / library API として定義する必要がある。`RuntimeRegistry` は Backend が embedded Runtime と remote Runtime をまとめて同じようにアクセスするための集約境界であり、Runtime 自体の実装主体ではない。
この Ticket では、まず要件だけを整理する。実装前に、現在の `pod`、`llm-worker`、Panel / Workspace backend における Pod / Worker 扱いを調査し、既存構造から Runtime crate へ移すべき責務と adapter として残すべき責務を把握する。
## 要件
### Crate / feature boundary
### Runtime crate の位置付け
- `crates/worker-runtime` を追加する。
- `worker-runtime/lib.rs` は embeddable Runtime core API を公開する。
- この Ticket では `worker-runtime/main.rs` / standalone Runtime process は実装しない。
- Core crate は HTTP server / WebSocket server / filesystem store dependency を強制しない。
- Cargo feature の土台だけは切ってよい。
- `memory-store` or core default。
- 将来の `fs-store`
- 将来の `http-server`
- 将来の `event-stream` / `ws-server`
- 将来の `http-client`
- `crates/worker-runtime` を Worker を動かす実行環境の正体として設計する。
- `worker-runtime/lib.rs` は Backend などに組み込める embeddable Runtime API を公開する。
- `worker-runtime/main.rs` は同じ Runtime を network API で公開する Runtime process を起動する。
- Runtime process と embedded Runtime は Worker semantics を二重実装しない。
- Worker lifecycle / input / output / event / transcript projection は lib 側を正とする。
- main binary は config / API server / transport / shutdown wrapper に留める。
### Runtime / Worker model
- Runtime は Worker を動かす環境であり、trait object ではなく concrete runtime domain entity として扱う。
- Runtime は Runtime-scoped Worker identity を使う。
- Runtime は Worker を動かす環境であり、trait object ではなく domain entity / concrete runtime implementation として扱う。
- Runtime は複数 Worker を保持・起動・停止・操作できる。
- Worker identity は Runtime scoped とする。
- `runtime_id`
- `worker_id`
- `display_name`
- `display_ref`
- Browser / Backend / API が `pod_name` / socket path / session path を authority にしない model を定義する。
- Runtime / Worker の summary / detail / state / capability / diagnostics 型を定義する。
- UI 表示用 `worker-name@runtime-name` と API authority `runtime_id + worker_id` を分ける。
- UI 用 `display_name` / `display_ref`
- Browser / API / Backend は `runtime_id + worker_id` を authority とし、`pod_name` / socket path / session path を authority にしない。
- Runtime は capability / status / diagnostics を返す。
- backend internal
- local process capable
- future remote host capable
- filesystem / shell / git / worktree capability
- tools availability
### Embedded Runtime API
### Embeddable Runtime API
- Backend などの Rust process に `Runtime` を直接組み込める。
- v0 は memory store でよい。
- Runtime API は transport API ではなく、`worker-runtime/lib.rs` が公開する Rust API として定義する。
- API surface は以下の責務に分ける。
- Backend は `Runtime` を process 内に直接組み込める。
- Embedded Runtime は tools なし Companion のような Worker を local process / socket なしで動かせる。
- API は少なくとも以下の操作を表現できる。
- runtime summary / status
- worker list / detail
- create worker
- send input
- stop / cancel worker
- bounded transcript projection
- event subscription または event cursor
- usage / overview projection
- v0 は single-flight / busy reject でよい。
- raw provider trace / raw session full log を Backend durable authority にしない。
#### Runtime management API
### Networked Runtime process API
Runtime 自体の管理・観測を扱う。Worker 1体の操作とは分ける。
- `worker-runtime/main.rs` は Runtime を network API として公開する。
- 将来、別ホストの Runtime process に Backend が接続し、remote Worker を local / internal Worker と同じ概念で扱えるようにする。
- Network API は command と observation を分ける。
- command: create / input / stop / cancel
- observation: worker status / transcript projection / events
- v0 transport は実装時に選ぶが、HTTP command + SSE/WebSocket event stream を想定可能な shape にする。
- Browser が remote Runtime へ直接 authority-bearing request を送るのではなく、Backend registry / policy 経由にする。
- `runtime_summary` / `runtime_status`
- Runtime capabilities。
- Runtime diagnostics。
- Runtime-local store/allocation status。
- Runtime が保持している Worker 数や busy summary。
- v0 では Runtime config mutation は不要。config bundle sync も別 Ticket とする。
### Backend RuntimeRegistry との関係
#### Worker catalog / lifecycle API
- Workspace backend の `RuntimeRegistry` は、embedded Runtime と remote Runtime client をまとめる集約境界とする。
- Registry は Worker を実行しない。
- Registry は runtime lookup / policy / visibility / API projection / current workspace filtering を担う。
- Backend internal Companion は embedded Runtime に載る Worker として扱う。
- Existing local Pod / process-based Worker は Runtime の adapter または移行対象として扱う。
Runtime 内に存在する Worker の作成・一覧・停止を扱う。これは旧 `Pod` の process lifecycle をそのまま露出するのではなく、Runtime-scoped Worker lifecycle として定義する。
### Existing Worker / LLM engine migration boundary
- `list_workers(query)`
- `get_worker(worker_id)`
- `create_worker(CreateWorkerRequest)`
- `stop_worker(worker_id)`
- `cancel_worker(worker_id)` or active run cancel。
- Unknown worker / duplicate worker / busy worker / unsupported capability を typed error にする。
- `llm-worker` は先に `llm-engine` へ改名し、LLM turn engine と実行単位としての Worker を名前上分離する。
- 既存 `pod` crate は先に `worker` crate へ rename し、single Worker host として扱う。
- 既存 `yoi pod` process は当面 compatibility / process-backed Worker adapter として扱えるようにする。
- 最終的には process boundary を Worker ではなく Runtime に寄せる。
- Runtime process が複数 Worker を保持できる。
- Worker ごとに subprocess を持つかどうかは Runtime implementation detail とする。
- `llm-engine` の provider streaming / tool execution / history integration のうち、Runtime crate に移すべきものと Worker-specific に残すものを調査して整理する。
- `worker` crate の Unix socket protocol / metadata / session persistence / TUI attach semantics は、Runtime API との対応を調査してから移行方針を決める。
`CreateWorkerRequest` は Web/Dashboard intent を直接受けない。Backend resolver 後、Runtime が解決可能な profile-oriented request とする。
### Pod-named store / registry migration boundary
- `display_name` / optional caller-provided worker id。
- `WorkerIntent`
- `ProfileSelector`
- optional `ConfigBundleRef`
- requested capabilities。
- optional workspace / mount references。
- `pod-store` / `pod-registry` は standalone crate として rename せず、`worker-runtime` 作成時に Runtime 内部 module へ直接統合する。
- `pod-store` 相当は Runtime 内部の Worker metadata / transcript projection / config snapshot persistence module とする。
- `pod-registry` 相当は Backend RuntimeRegistry ではなく、Runtime 内部の live Worker allocation / scope conflict / stale reclaim module とする。
- Backend `RuntimeRegistry` は embedded / remote Runtime を束ねる集約境界であり、Worker store / live allocation authority を直接持たない。
- 後方互換 alias / standalone `worker-store` / standalone `worker-registry` / old crate compatibility / old on-disk migration は設けない。
Profile/config bundle sync は別 Ticket とし、この Ticket では `config_bundle` は optional placeholder として型に含める程度でよい。`config_bundle` が無い場合、Runtime-local builtin/default Profile resources の範囲で toolsなし Worker を作れるようにする。
### Safety / authority
#### Worker interaction API
- Runtime API は raw socket path / session path / local metadata path を公開 API authority にしない。
- Worker tool authority は Runtime / Worker config / explicit grant で決める。
- Backend internal Companion v0 は filesystem / shell / git / Ticket mutation tools を持たない。
- Remote Runtime との接続では将来 auth / permission / network safety を挟める境界を残す。
Worker へ入力を送り、run を開始する経路を扱う。これは既存 `worker` crate が持つ single Worker の入力処理を Runtime 経由で呼べるようにする層であり、Worker 内部 API を無制限に継承しない。
## 調査事項
- `send_input(worker_id, WorkerInput)`
- v0 input は user message を最小単位とする。
- v0 は per-worker single-flight / busy reject でよい。
- acceptance result は accepted / rejected / busy / not found / failed を区別する。
- Runtime は `pod_name` / socket path / session path を input authority にしない。
実装前に以下を調査する。
#### Worker observation / projection API
Worker の状態と UI 用 projection を扱う。raw provider trace / raw full session log は Runtime public authority にしない。
- worker status / active run summary。
- bounded transcript projection。
- event cursor or subscription abstraction。
- usage / overview projection placeholder。
- diagnostics / last error。
- v0 は in-memory event log / transcript projection でよい。
#### Existing Worker APIとの関係
- `worker` crate は当面 single Worker host として残る。
- Runtime core は `worker` crate の全 public API を再公開しない。
- Runtime が公開するのは複数 Worker 管理に必要な catalog / lifecycle / interaction / projection API のみ。
- Worker 固有の socket protocol / attach details / session file details は Runtime API に漏らさない。
### Store / allocation core
- Memory-backed store を core に含める。
- Store API は将来 `fs-store` feature や Backend-provided store に差し替えられる境界を持つ。
- `pod-store` 相当の責務は standalone `worker-store` にせず、Runtime internal persistence abstraction として設計する。
- `pod-registry` 相当の責務は standalone `worker-registry` にせず、Runtime internal allocation / scope abstraction として設計する。
- この Ticket では full FS persistence / host-level stale reclaim は実装しない。
### Existing Worker / LLM engine boundary
- `llm-engine` は LLM turn engine として扱い、Runtime / Worker identity は持たせない。
- `worker` crate は当面 single Worker host として残り、Runtime core から直接大規模移植しない。
- Existing process/socket/session compatibility は後続 adapter / integration で扱う。
- `crates/pod` が現在担っている責務。
- process entrypoint
- socket protocol
- session persistence
- metadata / runtime dir
- in-flight snapshot / attach behavior
- tool registry / workflow / profile integration
- `crates/llm-worker` が現在担っている責務。
- provider request / streaming
- history / callback / tool-call loop
- reasoning / usage / continuation / retry
- Worker として再利用できる boundary
- Panel / TUI / Workspace backend が現在 Pod をどう扱っているか。
- Companion send path
- Worker/host list API
- Pod metadata reader
- spawn / stop / attach / event handling
- Existing `client` crate の process spawn / PodClient / socket protocol を Runtime adapter でどう扱うか。
## Non-goals
- `fs-store` implementation。
- REST command server。
- SSE / WebSocket observation server。
- HTTP client / Backend RuntimeRegistry remote integration。
- Backend internal Companion Web Console。
- Existing `pod-store` / `pod-registry` crate の即時削除。
- Existing Worker process/socket/session model の削除。
- Full remote Runtime protocol。
- Profile/config bundle sync implementation。
- Plugin package / grant / prompt resource synchronization。
- Backend internal Companion Web Console の完成。
- Remote Runtime protocol の完成。
- Existing Pod process model の即時削除。
- Full session storage migration。
- Full tool authority redesign。
- Multi-user auth / permission model の完成。
## 受け入れ条件
- `crates/worker-runtime` が追加されている。
- `worker-runtime` core は HTTP / WS / FS store dependency なしで library として使える。
- `Runtime` concrete struct と Runtime/Worker domain types が公開されている。
- Runtime management API、Worker catalog/lifecycle API、Worker interaction API、Worker observation/projection API が型として分離されている。
- Memory-backed embedded Runtime が runtime summary/status、worker list/detail/create、send input、stop/cancel、bounded transcript projection、event cursor/subscription placeholder を持つ。
- Worker create request は Web/Dashboard intent ではなく、`WorkerIntent`、Profile selector、optional `ConfigBundleRef`、requested capabilities を表現できる。
- `ConfigBundleRef` が無い場合、Runtime-local builtin/default resources で toolsなし Worker を作れる。
- `worker` crate の socket / attach / session file details が Runtime public API に再公開されていない。
- Profile/config bundle sync は実装されていないが、後続 Ticket が接続できる型境界がある。
- `runtime_id + worker_id` が authority であり、`pod_name` / socket path / session path を authority にしない。
- Store / allocation abstraction が Runtime internal responsibility として定義されている。
- `worker-store` / `worker-registry` standalone crate は作られていない。
- `cargo test -p worker-runtime` が通る。
- `cargo check -p yoi` が通る。
- `git diff --check` が通る。
- `nix build .#yoi --no-link` が通る。
この Ticket は要件整理と現状把握から開始する。ready に進める前に以下を満たす。
- `worker-runtime/lib.rs``worker-runtime/main.rs` の責務境界が整理されている。
- Runtime / Worker / RuntimeRegistry / Backend service の責務境界が整理されている。
- Runtime は Worker を動かす環境、Registry は Backend の集約境界であることが明確になっている。
- Embedded Runtime と networked Runtime process が同じ Runtime API に基づく方針が整理されている。
- Existing `worker` / `llm-engine` / Panel / Workspace backend の Worker 扱いの調査結果が記録されている。
- `pod-store` / `pod-registry` は standalone rename を挟まず、`worker-runtime` 内部 module へ直接統合する方針が整理されている。
- Backend `RuntimeRegistry` と Runtime internal store / allocation registry の責務境界が整理されている。
- 既存 Worker process model から Runtime model へ移行するための初期 implementation split が提案されている。

View File

@ -244,314 +244,3 @@ The pod -> worker step is a rename, not a rewrite. Runtime creation absorbs the
---
<!-- event: decision author: hare at: 2026-06-25T14:41:12Z -->
## Decision
Decision update: worker-runtime should separate the embeddable Runtime core from optional persistence and network transports.
- `worker-runtime/lib.rs` owns Runtime semantics and can be embedded by Backend.
- `worker-runtime/main.rs` is only a Runtime process wrapper around the same Runtime.
- Use features so embedding the library does not force FS store / HTTP server / WebSocket server dependencies.
- v0 persistence should support memory store for embedded use and fs-store for standalone Runtime process use.
- Backend <-> remote Runtime should be Backend-initiated: Browser -> Backend -> Runtime. Browser must not talk to Runtime directly.
- Commands should be REST/HTTP. Observation should be REST polling, SSE, or WebSocket; REST server and WS/SSE server implementation may be split from core crate creation.
- Runtime-initiated persistent connection back to Backend is not a v0 requirement because it complicates session, auth, reconnect, and delivery semantics.
---
<!-- event: decision author: hare at: 2026-06-25T14:48:23Z -->
## Decision
Decision update: split the former broad worker-runtime ticket into implementation-sized tickets.
Current order:
1. 00001KVZD10ED llm-worker crateをllm-engineへ改名する
2. 00001KVZG9BMS pod crateをworker crateへ改名する
3. 00001KVZBCQH4 worker-runtime core crateと組み込みRuntime APIを作る
4. 00001KVZKST83 worker-runtimeにFS永続化featureを追加する
5. 00001KVZKSTE2 worker-runtimeにREST command serverを追加する
6. 00001KVZKSTJT worker-runtimeにevent stream serverを追加する
7. 00001KVZKSV6C Backend RuntimeRegistryをworker-runtimeへ接続する
8. 00001KVZ9JGK0 Backend内蔵Companion RuntimeとWeb Console MVP
The core ticket must not absorb FS persistence, REST server, event stream server, or Backend remote client integration. Those are separate implementation tickets.
---
<!-- event: decision author: hare at: 2026-06-25T15:51:07Z -->
## Decision
Decision update: Profile/config bundle synchronization is a separate implementation ticket.
The worker-runtime core ticket should only define the create-worker boundary:
- create request accepts a Profile selector.
- create request has an optional ConfigBundleRef placeholder.
- if no bundle is supplied, Runtime may resolve against its local builtin/default resources for v0 testing.
Full bundle sync is tracked by 00001KVZQHPNY and should cover digest/versioned bundle storage, Runtime-side profile resolution, Backend sync orchestration, and host-local secret/mount/plugin policy enforcement.
---
<!-- event: decision author: hare at: 2026-06-25T16:14:53Z -->
## Decision
Decision update: the worker-runtime core API must not be described as a vague list of capabilities.
The API surface is split into:
- Runtime management API: runtime summary/status/capabilities/diagnostics/store-allocation status.
- Worker catalog/lifecycle API: list/detail/create/stop/cancel workers inside one Runtime.
- Worker interaction API: send user input and start a run, with single-flight/busy semantics.
- Worker observation/projection API: status, bounded transcript, event cursor/subscription placeholder, usage/overview diagnostics.
The Runtime API should wrap the single-worker host functionality exposed by the renamed `worker` crate, but must not re-export all Worker internals. Socket protocol, attach details, session file layout, and legacy process details stay out of the Runtime public API.
---
<!-- event: intake_summary author: hare at: 2026-06-25T16:18:21Z -->
## Intake summary
Marked ready by `yoi ticket state`.
---
<!-- event: state_changed author: "yoi ticket" at: 2026-06-25T16:18:21Z from: planning to: ready reason: cli_state field: state -->
## State changed
Marked ready by `yoi ticket state`.
---
<!-- event: state_changed author: workspace-panel at: 2026-06-25T16:20:10Z from: ready to: queued reason: queued field: state -->
## State changed
Ticket を `workspace-panel` が queued にしました。
---
<!-- event: decision author: yoi-orchestrator at: 2026-06-25T16:21:38Z -->
## Decision
Routing decision: implementation_ready
Reason:
- Dashboard Queue により本 Ticket の Orchestrator routing が明示許可された。
- Ticket body / thread には core slice の範囲、Non-goals、API 分割、profile/config bundle sync の境界、`worker` crate との責務境界が十分に記録されている。
- Relation blockers は解消済み。`00001KVZD10ED` は closed、`00001KVZG9BMS` は done。
- `queued` は本 Ticket 1件のみ、`inprogress` は 0 件。追加並列受理候補はない。
- Orchestration worktree は queue commit `30363e5e` 上で clean。既存の旧 worker-rename child worktree/Workers は残っているが、今回の child worktree path / branch / scope は分離できる。
Evidence checked:
- Ticket body: `crates/worker-runtime` core crate、memory-backed embedded Runtime API、Runtime/Worker identity、management/catalog/interaction/projection API、Non-goals、acceptance criteria。
- Ticket thread decisions: implementation order、`pod-store` / `pod-registry` を standalone `worker-store` / `worker-registry` にしない、FS/REST/event-stream/Backend integration/config-bundle sync は別 Ticket。
- Relations: depends_on `00001KVZD10ED` / `00001KVZG9BMS`; incoming dependent Tickets are later FS/REST/event-stream/config-bundle work and do not block this core slice.
- OrchestrationPlan: 新規 accepted plan `orch-plan-20260625-162107-1` を記録。
- Code map: root `Cargo.toml` workspace members/dependencies、既存 `crates/worker` single Worker host、`crates/workspace-server/src/hosts.rs` の現行 `WorkerRuntimeRegistry` / `WorkspaceWorkerRuntime` / local compatibility projection を確認。
- Workspace state: `/home/hare/Projects/yoi/.worktree/orchestration` clean; implementation worktree target `/home/hare/Projects/yoi/.worktree/00001KVZBCQH4-worker-runtime-core` / branch `work/00001KVZBCQH4-worker-runtime-core` を採用。
IntentPacket:
Intent:
- `crates/worker-runtime` を追加し、Backend 等へ組み込める memory-backed embedded Runtime core API を実装する。
Binding decisions / invariants:
- `Runtime` は concrete domain entity。trait object を public authority として設計しない。
- API authority は `runtime_id + worker_id`。`pod_name` / socket path / session path を Runtime public API authority にしない。
- `worker` crate は当面 single Worker host として残し、Runtime core は socket / attach / session file details や全 public Worker internals を再公開しない。
- HTTP server / WebSocket/SSE server / REST command server / HTTP client / FS persistence / Backend RuntimeRegistry integration / Web Console は実装しない。
- `worker-store` / `worker-registry` standalone crate は作らない。store/allocation は Runtime internal abstraction として定義する。
- Profile/config bundle sync は別 Ticket。ここでは `ConfigBundleRef` placeholder と Profile selector 境界まで。
- Existing process/socket/session compatibility の削除・大規模移植はしない。
Requirements / acceptance criteria:
- `crates/worker-runtime` を workspace に追加し、library として HTTP/WS/FS dependency なしで使える。
- Runtime management、Worker catalog/lifecycle、Worker interaction、Worker observation/projection API が型として分離される。
- Memory-backed embedded Runtime が summary/status、worker list/detail/create、send input、stop/cancel、bounded transcript projection、event cursor/subscription placeholder、diagnostics を持つ。
- `CreateWorkerRequest``WorkerIntent`、Profile selector、optional `ConfigBundleRef`、requested capabilities、optional workspace/mount refs を表現する。
- `ConfigBundleRef` なしでも Runtime-local builtin/default resources の範囲で toolsなし Worker を作れる型/挙動にする。
- `cargo test -p worker-runtime`、`cargo check -p yoi`、`git diff --check`、必要に応じて `nix build .#yoi --no-link` が通る。
Implementation latitude:
- Module分割、型名、内部 store/allocation trait/struct の詳細、event cursor/subscription placeholder の最小実装、memory worker の transcript/event 表現は Coder が既存コード規約に合わせて選んでよい。
- v0 は actual LLM/provider integration なし、または toolsなし minimal Worker projection でよい。ただし acceptance criteria の create/send/stop/cancel/projection observable behavior はテストで示す。
Escalate if:
- `worker` crate の public API 大規模変更や socket/session compatibility 変更が必要になる。
- HTTP/WS/FS/Backend integration/config bundle sync を実装しないと acceptance を満たせないと判明する。
- `pod-store` / `pod-registry` の削除または standalone rename が必要になりそうになる。
- Runtime public API authority に socket/session/path identity を混ぜる必要が出る。
Validation:
- `cargo fmt --all`
- `cargo test -p worker-runtime`
- `cargo check -p yoi`
- `git diff --check`
- 依存/packaging変更があるため可能なら `nix build .#yoi --no-link`
Current code map:
- Add: `crates/worker-runtime/**`
- Update: root `Cargo.toml` workspace members/default-members/dependencies, `Cargo.lock` as needed, docs/tests only if needed for public API clarity。
- Reference only as needed: `crates/worker/**` for single Worker host boundary, `crates/workspace-server/src/hosts.rs` for existing Backend registry/projection context。
- Do not implement network/server/fs integration in this Ticket.
Critical risks / reviewer focus:
- Scope creep into REST/WS/FS/Backend integration。
- Runtime API leaking legacy `pod_name` / socket/session authority。
- Re-exporting or duplicating too much of `worker` internals instead of a bounded Runtime API。
- Store/allocation becoming standalone `worker-store` / `worker-registry` crates instead of internal boundaries。
- Config bundle sync accidentally implemented instead of placeholder boundary。
---
<!-- event: state_changed author: yoi-orchestrator at: 2026-06-25T16:21:46Z from: queued to: inprogress reason: routing_accepted_unblocked_worker_runtime_core field: state -->
## State changed
Routing decision: implementation_ready。
Dashboard Queue による human-authorized routing を受け、Ticket body/thread、relations、orchestration plan、workspace state を確認した。`00001KVZD10ED` は closed、`00001KVZG9BMS` は done で relation blockers は解消済み。queued は本 Ticket 1件のみ、inprogress は 0 件。accepted plan と IntentPacket を thread / orchestration plan に記録済み。
これ以降、worktree creation / coder/reviewer Worker routing などの implementation side effect に進める。
---
<!-- event: implementation_report author: yoi-orchestrator at: 2026-06-25T16:23:24Z -->
## Implementation report
Implementation kickoff:
- Worktree created: `/home/hare/Projects/yoi/.worktree/00001KVZBCQH4-worker-runtime-core`
- Branch: `work/00001KVZBCQH4-worker-runtime-core`
- Coder Worker spawned: `yoi-coder-00001KVZBCQH4-worker-runtime`
Scope notes:
- Coder has read access to the implementation worktree and non-recursive workspace root identity path needed by runtime startup.
- Coder write scope is intentionally narrow: `crates/**`, root `Cargo.toml`, and root `Cargo.lock` only.
- Coder is instructed not to modify Ticket records and not to operate in root/orchestration worktrees.
Startup note:
- The first spawn attempt failed before child creation because the runtime workspace root path itself was not readable in the delegated scope. Retried with non-recursive read on `/home/hare/Projects/yoi` plus implementation worktree read/write scope; second spawn succeeded.
---
<!-- event: implementation_report author: yoi-coder-00001KVZBCQH4-worker-runtime at: 2026-06-25T16:32:52Z -->
## Implementation report
Implementation report:
実装完了。マージ・Ticket 更新・cleanup は未実施。
Commit:
- `9b2cae32 feat: add memory worker runtime crate`
変更ファイル / API 概要:
- `Cargo.toml`
- workspace member / default-member に `crates/worker-runtime` を追加。
- workspace dependency に `worker-runtime` を追加。
- `Cargo.lock`
- `worker-runtime` package entry を追加。
- `crates/worker-runtime/Cargo.toml`
- `crates/worker-runtime/src/*`
新規 crate `worker-runtime` の主な API 領域:
- `Runtime`: concrete な memory-backed embedded Runtime domain entity。`Runtime::new_memory()`, `Runtime::with_options(...)`
- `identity`: `RuntimeId`, `WorkerId`, `WorkerRef`。Worker 操作は `runtime_id + worker_id` を持つ `WorkerRef` を authority として扱う。
- `management`: `RuntimeOptions`, `RuntimeSummary`, `RuntimeStatus`, `RuntimeLimits`
- `catalog`: `CreateWorkerRequest`, `WorkerIntent`, `ProfileSelector`, `ConfigBundleRef`, `CapabilityRequest`, `WorkspaceRef`, `MountRef`, `WorkerSummary`, `WorkerDetail`, `WorkerStatus`
- `interaction`: `WorkerInput`, `send_input(...)` による transcript 追記。
- `observation`: bounded transcript projection、`EventCursor`, `RuntimeEventBatch`, poll-only `EventSubscription` placeholder。
- `diagnostics`: `RuntimeDiagnostic`, `DiagnosticSeverity`
実装範囲:
- HTTP / WS / SSE / REST / FS persistence / Backend integration / config bundle sync は未実装。
- provider/tool execution も未統合。
- config bundle なし・requested capabilities なしの tools-less Worker 作成をサポート。
- create/list/detail/send/stop/cancel/projection/events/diagnostics の unit tests を追加。
Validation results:
- `cargo fmt --all`: success
- `cargo test -p worker-runtime`: success (6 tests passed)
- `cargo check -p yoi`: success
- `git diff --check`: success
- `nix build .#yoi --no-link`: failure
- 理由: `Cargo.lock` に新規 workspace crate `worker-runtime` が追加されたため、既存 `package.nix``cargoHash` / vendored lock consistency が古くなっている。
- `package.nix` は今回の delegated write scope 外なので未変更。
Residual risks / review focus:
- `package.nix``cargoHash` 更新が別途必要。今回の delegated write scope が `crates/**`, root `Cargo.toml`, root `Cargo.lock` のみだったため対応していない。
- v0 は in-memory のみで、Runtime/Worker lifecycle semantics は最小実装。特に terminal Worker に対する再 stop/cancel の扱いを review 対象にする。
- Event subscription は意図通り poll-only placeholder。後続 streaming 実装時に cursor semantics が十分か確認する。
---
<!-- event: implementation_report author: yoi-coder-00001KVZBCQH4-runtime-packaging at: 2026-06-25T16:37:25Z -->
## Implementation report
Packaging follow-up implementation report:
対応内容:
- `package.nix``cargoHash` のみ更新。
- New hash: `sha256-RHo2b6dVClqu32wpgES/RQeBMXaqyqXZaooeSH5SveM=`
Commit:
- `593db95175ff8537af2401a5def21fc32dd4846d fix: update nix cargo hash`
Validation:
- `nix build .#yoi --no-link`: success
- `git diff --check`: success
Residual notes:
- 作業ツリーは clean。
- merge / close / cleanup は未実施。
---
<!-- event: review author: yoi-reviewer-00001KVZBCQH4-worker-runtime at: 2026-06-25T16:46:17Z status: request_changes -->
## Review: request changes
Review result: request_changes
主なブロッカー:
- `stop_worker` / `cancel_worker` の terminal lifecycle が不安定です。
`Runtime::transition_worker` は「同じ status への再実行」だけを idempotent 扱いし、既に `Stopped` の Worker に `cancel_worker`、既に `Cancelled` の Worker に `stop_worker` を呼ぶと、terminal state を別の terminal state に上書きできます。
- 該当: `crates/worker-runtime/src/runtime.rs:209-235`, `353-385`
- 現状ロジック: `worker.status == status` の場合のみ早期 return、それ以外は `worker.status = status`
- 影響: stop/cancel が terminal lifecycle として安定せず、summary の `stopped_worker_count` / `cancelled_worker_count` や event history が後続操作で意味を変えられる。
- テストも `stop``cancel` を別 Worker で確認しているだけで、`stop -> cancel` / `cancel -> stop` の不変条件を覆っていません。
- 期待: terminal Worker への反対側 terminal 操作は拒否するか、既存 terminal state を保持する idempotent 応答にし、該当テストを追加してください。
確認した範囲:
- `crates/worker-runtime` は workspace / default-members / workspace.dependencies に追加済み。
- crate 依存は `serde` / `thiserror` のみで、HTTP/WS/FS/provider 依存の追加は見当たりません。
- API は `management`, `catalog`, `interaction`, `observation`, `diagnostics`, `identity` に分離されています。
- `Runtime` は concrete entity として実装され、Worker 操作は `WorkerRef { runtime_id, worker_id }` を要求しています。pod/socket/session path を authority とする API は見当たりません。
- event cursor/subscription placeholder は `runtime_id` 検証、bounded `read_events`、`PollOnly` subscription として概ね意図に合っています。
- `CreateWorkerRequest``WorkerIntent`, `ProfileSelector`, optional `ConfigBundleRef`, requested capabilities, workspace/mount refs を保持しています。
- tools-less 作成と diagnostics のテストは存在します。
- `package.nix``cargoHash` 更新コミットは確認しました。
- `git diff --check f8d3b1cc..HEAD` は成功。
cargo/nix の再実行は、read-only 指示と上記 blocker があるため実施していません。
---

View File

@ -1 +0,0 @@
{"id":"orch-plan-20260625-141406-1","ticket_id":"00001KVZG9BMS","kind":"accepted_plan","accepted_plan":{"summary":"Ticket `00001KVZG9BMS` は prerequisite `00001KVZD10ED` が done になったため implementation_ready。専用 worktree `/home/hare/Projects/yoi/.worktree/00001KVZG9BMS-worker-crate-rename` と branch `work/00001KVZG9BMS-worker-crate-rename` で、`crates/pod` を `crates/worker` へ rename し、public execution-unit API を Worker terminology へ整理する。`pod-store`/`pod-registry` standalone rename、worker-runtime実装、socket/session互換の完全削除は non-goals。","branch":"work/00001KVZG9BMS-worker-crate-rename","worktree":"/home/hare/Projects/yoi/.worktree/00001KVZG9BMS-worker-crate-rename","role_plan":"Orchestrator: accept/routing, worktree creation, final integration/validation/cleanup. Coder: repository-wide crate/API rename in dedicated child worktree. Reviewer: read-only review focusing on mechanical rename completeness, CLI/process launch consistency, no pod-store/registry rename, no responsibility rewrite, and validation evidence."},"author":"yoi-orchestrator","at":"2026-06-25T14:14:06Z"}

View File

@ -1,8 +1,8 @@
---
title: 'pod crateをworker crateへ改名する'
state: 'done'
state: 'queued'
created_at: '2026-06-25T13:42:37Z'
updated_at: '2026-06-25T16:19:23Z'
updated_at: '2026-06-25T14:13:35Z'
assignee: null
queued_by: 'workspace-panel'
queued_at: '2026-06-25T14:13:35Z'

View File

@ -30,718 +30,4 @@ Marked ready by `yoi ticket state`.
Ticket を `workspace-panel` が queued にしました。
---
<!-- event: decision author: yoi-orchestrator at: 2026-06-25T14:14:52Z -->
## Decision
Routing decision: implementation_ready
Reason:
- Dashboard Queue により人間が Orchestrator routing を許可した queued Ticket として確認した。
- outgoing `depends_on``00001KVZD10ED` で、`00001KVZD10ED` は done / merged / reviewed / validated 済み。`TicketShow` derived blockers は空で、implementation acceptance blocker は残っていない。
- incoming dependent `00001KVZBCQH4` は後続 worker-runtime creation であり、この Ticket の acceptance blocker ではない。
- Ticket body は `crates/pod` -> `crates/worker` crate/package/import rename、public execution-unit API rename、CLI/process surface update、non-goals、validation を具体的に列挙している。
- bounded context check で current active references to `crates/pod`, `pod::`, package `pod`, `yoi pod` process entrypoint, tests/docs/Nix を確認した。変更量は大きいが mechanical rename + bounded public surface alignment として進められる。
- CLI/process surface は risk だが、Ticket は backward compatibility alias 不要、dogfooding runtime/spawn path/scripts/tests 影響を明示処理することを要求している。設計未決定というより implementation slice 内の bounded choice と判断する。
Evidence checked:
- Ticket body / thread: `item.md`, `thread.md`。thread は create、planning->ready、ready->queued のみで未解決 blocker は記録されていない。
- Relations / orchestration plan: outgoing depends_on `00001KVZD10ED` is done; incoming dependent `00001KVZBCQH4`; routing 前 plan 0 件。accepted plan `orch-plan-20260625-141406-1` を記録済み。
- Code context: `git grep``crates/pod`, `pod::`, package/dependency `pod`, `yoi pod`, `Pod` public API refs を確認。
- Workspace state: `/home/hare/Projects/yoi/.worktree/orchestration` は clean。queued Ticket はこの 1 件、inprogress Ticket は 0 件。
IntentPacket:
Intent:
- 現在の single execution-unit host crate `pod``worker` に rename し、実行単位としての `worker::Worker` と LLM turn engine `llm_engine::Engine` の命名境界を揃える。
Binding decisions / invariants:
- This is a rename / API terminology alignment Ticket, not a responsibility rewrite.
- `worker` crate remains the current single Worker host: input handling, llm-engine integration, event emission, session/transcript compatibility, tool registry, workflow integration, legacy socket compatibility.
- Do not implement `worker-runtime` crate or multi-worker Runtime API.
- Do not standalone-rename `pod-store` / `pod-registry` to `worker-store` / `worker-registry` in this Ticket.
- Do not change provider request/tool-call/history semantics.
- Do not create `pod` crate/import compatibility alias.
- Existing on-disk/socket/session compatibility may retain legacy `pod` strings only where explicitly legacy/internal and documented.
Requirements / acceptance criteria:
- `crates/worker` exists; `crates/pod` does not remain.
- Cargo package/import path are `worker`.
- Public execution-unit type is `worker::Worker`, not `pod::Pod`.
- Active repository references to `pod` crate / `pod::` import / `crates/pod` are gone except intentional legacy context.
- Dependent crates compile against `worker` crate.
- `llm_engine::Engine` vs `worker::Worker` boundary is clear in code/docs/comments.
- Existing process/socket/session compatibility path still works or is explicitly updated without old-name alias.
- `pod-store` / `pod-registry` are not renamed as standalone crates.
- Validation target includes `cargo test -p worker`, `cargo test -p yoi` or relevant CLI tests, `cargo check -p yoi`, `git diff --check`, `nix build .#yoi --no-link`.
Implementation latitude:
- Exact CLI command spelling may be updated according to Ticket requirement, but no backward alias should be added unless a hard blocker appears. If command migration threatens current runtime dogfooding assumptions, escalate.
- Internal legacy file/socket/session names may remain only when required for compatibility and must be clearly legacy/internal, not active API guidance.
- Type/module rename can be staged mechanically; prioritize compile/test correctness and grep evidence.
Escalate if:
- Rename requires broad runtime architecture rewrite or worker-runtime implementation.
- Current process launch/spawn mechanics cannot work without a compatibility `pod` command/alias.
- `pod-store` / `pod-registry` must be renamed for compile correctness.
- Session/socket/on-disk migration would be required beyond explicit legacy compatibility labels.
- Behavior changes unrelated to naming are needed.
Validation:
- `cargo test -p worker`
- `cargo test -p yoi` or focused process/CLI tests
- `cargo check -p yoi`
- `git diff --check`
- `nix build .#yoi --no-link`
- grep evidence for stale active references.
Current code map:
- Primary: `crates/pod`, workspace `Cargo.toml`, dependent crates (`crates/yoi`, `crates/tui`, workspace-server/client as discovered), tests/docs/resources, `Cargo.lock`, `package.nix`.
- Avoid: `pod-store` / `pod-registry` standalone rename, worker-runtime implementation, root/original workspace operations.
Critical risks / reviewer focus:
- stale active `pod` crate/import/directory references.
- hidden compatibility alias.
- breaking runtime process launch / spawn command path.
- accidentally renaming persistence crates out of scope.
- behavior changes mixed into mechanical rename.
- confusion between `llm_engine::Engine` and `worker::Worker` responsibilities.
Next action:
- `queued -> inprogress` を記録してから worktree-workflow で `/home/hare/Projects/yoi/.worktree/00001KVZG9BMS-worker-crate-rename` を作成し、multi-agent-workflow で Coder/Reviewer sibling loop に進める。
---
<!-- event: state_changed author: yoi-orchestrator at: 2026-06-25T14:15:18Z from: queued to: inprogress reason: orchestrator_acceptance_unblocked field: state -->
## State changed
Orchestrator acceptance: queued -> inprogress
- 直前確認で `TicketShow` は state `queued`、derived blockers は空。
- outgoing dependency `00001KVZD10ED` は done / merged / reviewed / validated 済み。
- accepted plan `orch-plan-20260625-141406-1` を確認した。
- routing decision と IntentPacket は Ticket thread に記録済み。
- これ以降に worktree-workflow で `/home/hare/Projects/yoi/.worktree/00001KVZG9BMS-worker-crate-rename` を作成し、multi-agent-workflow に接続する。
---
<!-- event: implementation_report author: yoi-orchestrator at: 2026-06-25T14:16:23Z -->
## Implementation report
Implementation orchestration update:
- prerequisite `00001KVZD10ED` が done であることを確認し、`00001KVZG9BMS` を受理した。
- worktree-workflow に従い、implementation worktree `/home/hare/Projects/yoi/.worktree/00001KVZG9BMS-worker-crate-rename` と branch `work/00001KVZG9BMS-worker-crate-rename` を作成した。
- child worktree では tracked `.yoi` project records を見える状態にし、`.yoi/memory`、local/runtime/log/lock/secret-like `.yoi` paths を sparse-checkout で除外する方針にした。
- Coder Pod `yoi-coder-00001KVZG9BMS-worker-rename` を sibling として起動した。write scope は child worktree に限定し、runtime workspace root `/home/hare/Projects/yoi` は startup 要件を満たすため non-recursive read のみにした。
- Coder には root/original workspace と orchestration worktree で read/write/validation/git operation を行わないよう明示した。
---
<!-- event: implementation_report author: yoi-coder-00001KVZG9BMS-worker-rename at: 2026-06-25T15:07:12Z -->
## Implementation report
Implementation report:
実装概要:
- `crates/pod``crates/worker` へ改名。
- Cargo package/import path を `pod` から `worker` へ更新。
- `worker::Worker`, `WorkerConfig`, `WorkerState`, `WorkerEvent`, `WorkerClient`, `WorkerRuntimeCommand` など Worker 用語へ更新。
- CLI/process surface を `yoi pod` から `yoi worker` へ変更。
- 後方互換の `yoi pod` alias は追加していません。
- `llm_engine::Engine``worker::Worker` の境界を明確化。
- 既存 manifest の turn-engine 側設定は `engine` 用語へ寄せ、Worker host 側設定と分離しました。
- `pod-store` / `pod-registry` は crate/package としては改名していません。
- ただし Worker API と整合するよう、関連する型・呼び出し側は Worker 用語へ更新。
- 既存互換・内部文脈として、legacy on-disk metadata directory `pods` などは残しています。
- resources/prompts、profiles、docs、Nix、Cargo workspace、Cargo.lock を更新。
- `package.nix``cargoHash` を更新。
主な変更ファイル:
- `crates/pod/**``crates/worker/**`
- `crates/client/src/pod_client.rs``crates/client/src/worker_client.rs`
- `crates/tui/src/pod_list.rs``crates/tui/src/worker_list.rs`
- `crates/yoi/src/pod_cleanup_cli.rs``crates/yoi/src/worker_cleanup_cli.rs`
- `resources/prompts/pod/**``resources/prompts/worker/**`
- `resources/prompts/common/pod-orchestration.md``resources/prompts/common/worker-orchestration.md`
- `docs/design/pod-session-state.md``docs/design/worker-session-state.md`
- `Cargo.toml`, `Cargo.lock`, `package.nix`
- dependent crates: `protocol`, `manifest`, `tui`, `client`, `workspace-server`, `yoi`, docs/resources
Validation:
- `cargo test -p worker`: success
- `cargo test -p yoi`: success
- `cargo check -p yoi`: success
- `git diff --check`: success
- `nix build .#yoi --no-link`: success
Grep evidence:
- `crates/pod` refs: intentional `pod-store` / `pod-registry` path を除きなし
- `pod::` refs: なし
- package/import `pod` refs: intentional `pod-store` / `pod-registry` dependencies を除きなし
- old public `Pod*` execution-unit type refs: intentional exclusions を除きなし
- active CLI refs:
- `yoi pod`: なし
- `"pod" =>`: なし
- `--pod`: なし
- `POD_OPTIONS`: なし
- `parse_pod`: なし
- `pod_name`: intentional exclusions を除きなし
残っている lower-case `pod` は主に以下の intentional legacy/internal context:
- crate/package name として残す指定のある `pod-store`
- crate/package name として残す指定のある `pod-registry`
- legacy on-disk metadata directory `pods`
- related comments/tests describing those legacy/internal boundaries
Commit:
- `6c59fe927b8094f735651ef0e18fad5e8b62ea83 refactor: rename pod crate to worker`
Residual risks / notes:
- `pod-store` / `pod-registry` crate 名は Ticket invariant に従って残しています。そのため grep 上の lower-case `pod` は完全にはゼロになりません。
- legacy on-disk directory `pods` は既存 metadata/session compatibility のため維持しました。
- merge / close / cleanup は実施していません。
---
<!-- event: review author: yoi-reviewer-00001KVZG9BMS-worker-rename at: 2026-06-25T15:15:27Z status: request_changes -->
## Review: request changes
Review result: request_changes
読取専用で Ticket / IntentPacket、`4c677640..HEAD` diff、grep/nl による focused inspection を行いました。`cargo`/`nix` 系の再実行は read-only 指示と書込み副作用回避のため行っていません。
良い点:
- `crates/worker` は存在し、`crates/pod` は削除済み。
- workspace/Cargo.lock 上の package/import は `worker` に移行済みで、`pod-store` / `pod-registry` は standalone rename されていません。
- CLI は `yoi worker` / `--worker` 側へ移行しており、明示的な `yoi pod` alias は見当たりませんでした。
Blockers:
1. 生成済み Web protocol が旧 Pod protocol のまま。
- `web/workspace/src/lib/generated/protocol.ts` が Rust 側の `Worker*` protocol と不整合です。
- 例: `PodStatus`, `Greeting { pod_name: ... }`, `PodEvent`, method `pod_event`, `list_pods`, `restore_pod`, events `pods_listed`, `pod_restored` など。
- `crates/protocol/src/lib.rs``WorkerStatus` / `WorkerEvent` / `worker_name` / `worker_event` 等へ更新済みのため、Web/TS client 側が socket protocol とズレるリスクがあります。
2. public API に旧 Pod 名の enum variant が残存。
- `crates/client/src/spawn.rs``SpawnError::PodLaunchFailed { ... }`
- `crates/client/src/lib.rs``SpawnError` は public re-export されているため、Ticket の “Public execution-unit type/API terminology is Worker, not Pod” に反します。
3. model-facing prompts / workflows / active docs に旧 Pod guidance が残存。
- `resources/prompts/common/worker-orchestration.md`: “Peer Pods ...”
- `resources/workflows/ticket-orchestrator-routing.md`: “Coder/Reviewer は sibling Pods ...”
- `resources/prompts/role/intake.md`, `resources/prompts/role/orchestrator.md`, `resources/prompts/panel/orchestrator_idle_queue_notice.md` にも active orchestration guidance として “Pods” が残っています。
- `docs/design/worker-session-state.md``SendToPeerPod` と記載されていますが、実装側は `SendToPeerWorker`
- これらは legacy/internal compatibility label ではなく current LLM/workflow guidance なので例外扱いできません。
4. active documentation に壊れた旧パス / 旧型名が残存。
- `crates/pod-store/README.md` に削除済み `docs/design/pod-session-state.md` へのリンク。
- `KNOWN_ISSUES.md``crates/worker/src/pod.rs` / `Pod::ensure_segment_head` 等、存在しない path/type。
Required fixes:
- `web/workspace/src/lib/generated/protocol.ts` を Rust protocol と一致させる。
- `client::SpawnError::PodLaunchFailed``WorkerLaunchFailed` に rename し、match/source mapping も更新する。
- `resources/prompts/**` / `resources/workflows/**` の active “Pod(s)” guidance を Worker terminology に更新する。
- `SendToPeerPod` など実装と不一致な docs を `SendToPeerWorker` に更新する。
- 削除済み `docs/design/pod-session-state.md` へのリンク、存在しない `crates/worker/src/pod.rs` / `Pod::ensure_segment_head` 参照を修正する。
- 修正後、報告済み validation に加えて stale grep を再実施する。
---
<!-- event: implementation_report author: yoi-coder-00001KVZG9BMS-worker-rename at: 2026-06-25T15:26:07Z -->
## Implementation report
Follow-up implementation report after review request_changes:
対応内容:
1. Web generated protocol の Worker 用語追従
- `web/workspace/src/lib/generated/protocol.ts` を Rust protocol から再生成。
- 旧 Pod protocol 名を Worker に更新。
- `PodStatus``WorkerStatus`
- `Greeting { pod_name }``Greeting { worker_name }`
- `PodEvent``WorkerEvent`
- `pod_event``worker_event`
- `list_pods``list_workers`
- `restore_pod``restore_worker`
- `pods_listed``workers_listed`
- `pod_restored``worker_restored`
2. public API enum variant の修正
- `crates/client/src/spawn.rs`
- `SpawnError::PodLaunchFailed``SpawnError::WorkerLaunchFailed`
- public re-export される型なので、match / source mapping も更新。
3. active model-facing guidance の Pod 表現修正
- 以下を Worker 用語へ更新。
- `resources/prompts/common/worker-orchestration.md`
- `resources/workflows/ticket-orchestrator-routing.md`
- `resources/prompts/role/intake.md`
- `resources/prompts/role/orchestrator.md`
- `resources/prompts/panel/orchestrator_idle_queue_notice.md`
4. stale docs/path/type の修正
- `docs/design/worker-session-state.md`
- `SendToPeerPod``SendToPeerWorker`
- `crates/pod-store/README.md`
- deleted path `docs/design/pod-session-state.md``docs/design/worker-session-state.md`
- crate 名は invariant に従い `pod-store` のまま、説明は legacy-named crate owning current Worker metadata と明記。
- `KNOWN_ISSUES.md`
- `crates/worker/src/pod.rs``crates/worker/src/worker.rs`
- `Pod::ensure_segment_head``Worker::ensure_segment_head`
- `PodError::WorkflowResolve``WorkerError::WorkflowResolve`
Validation:
- `cargo test -p worker`: success
- `cargo test -p yoi`: success
- `cargo check -p yoi`: success
- `cargo test -p protocol --features typescript`: success
- `cd web/workspace && deno task check`: success
- `git diff --check`: success
- `nix build .#yoi --no-link`: success
Stale grep evidence:
- review blocker terms were checked and found no matches:
- `PodStatus`, `PodEvent`, `pod_name`, `pod_event`, `list_pods`, `restore_pod`, `pods_listed`, `pod_restored`, `PodLaunchFailed`, `SendToPeerPod`, `sibling Pods`, `Peer Pods`, `yoi pod`, `--pod`, `crates/worker/src/pod.rs`, `Pod::ensure_segment_head`, `pod-session-state.md`
- Strict stale grep was rerun; intentional `pod-store` / `pod-registry` crate names aside, active public Pod protocol/prompt/API reference remains absent.
Commit:
- `ebf50baa94f76bb000f70f63e133c7883729de5c fix: align worker rename followups`
Residual risks / notes:
- なし。child worktree は commit 後 clean。
---
<!-- event: review author: yoi-reviewer-00001KVZG9BMS-worker-rename at: 2026-06-25T15:29:25Z status: request_changes -->
## Review: request changes
Review result: request_changes
Follow-up を read-only で確認した。`6c59fe92..HEAD` の差分確認と blocker term grep を実施し、ビルド/テストは副作用回避のため再実行していない。
解消確認:
- `web/workspace/src/lib/generated/protocol.ts``WorkerStatus` / `worker_name` / `WorkerEvent` / `worker_event` / `list_workers` / `restore_worker` / `workers_listed` / `worker_restored` に更新済み。
- `SpawnError::PodLaunchFailed``WorkerLaunchFailed` に更新済み。
- 主要 prompt/workflow の `Peer Pods` / `sibling Pods` は一部修正済み。
Remaining blockers:
1. 削除済み docs path がまだ残存。
- `crates/pod-registry/README.md:29`
- `../../docs/design/pod-session-state.md` への link が残っている。対象 file は `worker-session-state.md` に移行済みなので、壊れた active doc link。
2. 旧 tool 名 `SendToPeerPod` が active code に残存。
- `crates/session-analytics/src/lib.rs:1600`
- 実装側は `SendToPeerWorker` へ移行済みだが、analytics の分類に `SendToPeerWorker` がなく `SendToPeerPod` だけ残っている。stale name であるだけでなく、現行 tool の分類漏れに見える。legacy log 対応で旧名を残すなら、`SendToPeerWorker` を追加した上で legacy comment を付けるのが安全。
3. active docs/comments に旧 Pod guidance がまだ残存。
- `docs/development/work-items.md:250`: `Reviewer Pods should be sibling Pods...`
- `crates/protocol/src/lib.rs:80`: `List Pods visible to this Worker...`
- `AGENTS.md:19`: `Notify / PodEvent / ...`
- いずれも compatibility/internal on-disk `pods` の説明ではなく、現在の active terminology / protocol guidance なので Worker terminology に寄せるべき。
Required verification after fix:
```sh
rg -n -S 'SendToPeerPod|pod-session-state\.md|sibling Pods|List Pods visible|PodEvent' \
AGENTS.md crates resources docs web/workspace/src/lib/generated/protocol.ts \
--glob '!target' --glob '!docs/report/**'
```
This grep should be empty or any remaining hit must be explicitly legacy/internal and justified.
---
<!-- event: implementation_report author: yoi-coder-00001KVZG9BMS-worker-rename at: 2026-06-25T15:44:18Z -->
## Implementation report
Second follow-up implementation report after review request_changes:
対応内容:
1. broken docs path 修正
- `crates/pod-registry/README.md`
- `../../docs/design/pod-session-state.md``../../docs/design/worker-session-state.md`
- `pod-registry` は invariant に従って crate 名を維持しつつ、本文では legacy-named crate と明記して Worker 用語へ更新。
2. old tool name classification 修正
- `crates/session-analytics/src/lib.rs`
- current tool name `SendToPeerWorker` を worker tool classification に追加。
- historical session logs の分類維持のため、`SendToPeerPod` は `LEGACY_SEND_TO_PEER_POD_TOOL` として明示的な legacy analytics-only comment 付きで保持。
3. active docs/comments の Pod guidance 修正
- `docs/development/work-items.md`
- `Reviewer Pods should be sibling Pods...``Reviewer Workers should be sibling Workers...`
- `crates/protocol/src/lib.rs`
- `List Pods visible...``List Workers visible...`
- `AGENTS.md`
- `Podの状態``Workerの状態`
- `Notify / PodEvent / ...``Notify / WorkerEvent / ...`
Validation:
- `cargo test -p session-analytics`: success
- `cargo test -p worker`: success
- `cargo test -p yoi`: success
- `cargo check -p yoi`: success
- `cargo test -p protocol --features typescript`: success
- `cd web/workspace && deno task check`: success
- `git diff --check`: success
- `nix build .#yoi --no-link`: success
Specified grep evidence:
```text
crates/session-analytics/src/lib.rs:1595: const LEGACY_SEND_TO_PEER_POD_TOOL: &str = "SendToPeerPod";
```
- この 1 件のみ残存。
- historical session logs の分類維持のための analytics-only legacy tool name で、直下の classification branch にも legacy comment を付けている。
- active prompt/protocol/docs/API guidance の旧 Pod 参照ではない。
Commit:
- `94c7aa793a179b377108dea841fe9d381affbd9c fix: clean remaining worker rename references`
Residual risks / notes:
- child worktree は commit 後 clean。
---
<!-- event: review author: yoi-reviewer-00001KVZG9BMS-worker-rename at: 2026-06-25T15:46:40Z status: request_changes -->
## Review: request changes
Review result: request_changes
読取専用で `94c7aa79` を確認した。前回指摘分のうち、以下は解消済み。
- `crates/pod-registry/README.md``worker-session-state.md` link 更新。
- `crates/protocol/src/lib.rs``List Workers...` comment 更新。
- `AGENTS.md` / `docs/development/work-items.md:250` の前回 exact blocker 更新。
- `SendToPeerPod``LEGACY_SEND_TO_PEER_POD_TOOL` として analytics-only legacy comment 付きで残り、現行 `SendToPeerWorker` 分類も追加済みなので、この残存は許容可能。
Remaining blockers:
1. active E2E helper に旧 `--pod` CLI が残存。
- `tests/e2e/src/lib.rs:1541`
- `config.command_args` がまだ `"--pod"` を渡している。
- `yoi pod` / `--pod` alias を作らない方針なので、これは現行 CLI に対して壊れた active test/helper。`--worker` へ更新が必要。
2. active user-facing / developer-facing guidance に旧 Pod terminology が残存。
代表例:
- `crates/tui/src/dashboard/mod.rs:96``"no Tickets or Pods found ..."`
- `crates/tui/src/dashboard/mod.rs:2939``"spawning role Pods"`
- `crates/tui/src/dashboard/mod.rs:4951``"sibling coder/reviewer Pods"`
- `crates/tui/src/dashboard/tests.rs:837` — 旧文字列期待
- `crates/client/README.md:5` — “talking to Pods”
- `crates/manifest/src/config.rs:43` — “spawned child Pods”
- `docs/design/overview.md:14` — “between clients and Pods”
- `docs/development/workflows.md` / `docs/development/dogfooding.md` / `docs/development/work-items.md` にも current guidance としての `Pods` が残存。
これらは `pod-store` / `pod-registry` crate 名や on-disk `pods` compatibility の説明ではなく、現在の実行単位・CLI・Dashboard guidance なので Worker terminology に寄せるべき。
Required verification after fixes:
```sh
rg -n -S --glob '!target' --glob '!docs/report/**' -- '--pod|yoi pod' .
rg -n -S --glob '!target' --glob '!docs/report/**' \
'sibling coder/reviewer Pods|role Pods|talking to Pods|between clients and Pods|Spawned Pods|child Pods|Pods found|Pod categories|Pod row' \
crates docs tests resources AGENTS.md README.md KNOWN_ISSUES.md
```
These should be empty or any remaining hit must be explicitly legacy/internal and justified.
---
<!-- event: implementation_report author: yoi-coder-00001KVZG9BMS-worker-rename at: 2026-06-25T15:58:35Z -->
## Implementation report
Third follow-up implementation report after review request_changes:
対応内容:
1. E2E helper の旧 CLI 引数修正
- `tests/e2e/src/lib.rs`
- rewind fixture の起動引数を `--pod` から `--worker` に変更。
- 関連 helper 名・フィールド・説明も `worker_names` / `worker_rows` / Worker row に更新。
- `tests/e2e/tests/panel.rs`
- 期待値・メッセージを Worker terminology に更新。
2. Active user/developer guidance の Pod 表現修正
- `crates/tui/src/dashboard/mod.rs`
- `no Tickets or Pods found ...``no Tickets or Workers found ...`
- `spawning role Pods``spawning role Workers`
- `sibling coder/reviewer Pods``sibling coder/reviewer Workers`
- `crates/tui/src/dashboard/tests.rs`
- 期待文字列を Worker に更新。
- `crates/client/README.md`
- `talking to Pods``talking to Workers`
- `crates/manifest/src/config.rs`
- `spawned child Pods``spawned child Workers`
- `docs/design/overview.md`
- `between clients and Pods``between clients and Workers`
- `docs/design/profiles-manifests-prompts.md`
- `Spawned Pods``Spawned Workers`
- `docs/development/dogfooding.md`
- `child Pods``child Workers`
- `docs/development/workflows.md`
- `Spawned Pods``Spawned Workers`
Validation:
- `cargo test -p worker`: success
- `cargo test -p yoi`: success
- `cargo check -p yoi`: success
- `cargo test -p protocol --features typescript`: success
- `cargo check -p yoi-e2e`: success
- `cd web/workspace && deno task check`: success
- `git diff --check`: success
- `nix build .#yoi --no-link`: success
Notes:
- `cargo check -p e2e` は package 名が存在しなかったため失敗し、正しい package 名 `yoi-e2e``cargo check -p yoi-e2e` を実行して成功。
Specified grep evidence:
- `rg -n -S --glob '!target' --glob '!docs/report/**' -- '--pod|yoi pod' .`: no matches.
- `rg -n -S --glob '!target' --glob '!docs/report/**' 'sibling coder/reviewer Pods|role Pods|talking to Pods|between clients and Pods|Spawned Pods|child Pods|Pods found|Pod categories|Pod row' crates docs tests resources AGENTS.md README.md KNOWN_ISSUES.md`: no matches.
- Additional E2E stale grep for `pod_rows`, `pod_names`, `row.key.kind == "pod"`, `"--pod"`: no matches.
Commit:
- `da96d06f25932ff60fc00a3fc516a276a2847125 fix: remove stale pod guidance references`
Residual risks / notes:
- child worktree は commit 後 clean。
---
<!-- event: review author: yoi-reviewer-00001KVZG9BMS-worker-rename at: 2026-06-25T16:00:39Z status: request_changes -->
## Review: request changes
Review result: request_changes
読取専用で `da96d06f` を確認した。指定 grep は報告通り概ね解消しており、`--pod` / `yoi pod`、`pod_rows` / `pod_names` / `row.key.kind == "pod"` は見当たらなかった。
ただし、前回 blocker の「active user/developer-facing guidance に旧 Pod terminology が残存」に対して、まだ active docs/test diagnostics に旧名が残っている。
Remaining blockers:
- `docs/development/workflows.md`
- `20: ## Child Pods`
- `38: Child Pods may commit ...`
- `docs/development/work-items.md`
- `27: Inside Pods ...`
- `32: Ticket tools inside Pods`
- `34: Pods with the Ticket built-in feature ...`
- `198: spawn coder/reviewer Pods ...`
- `229: coder Pods ...`
- `tests/e2e/tests/panel.rs`
- `77: fixture blocks host Pod launch`
- `626: host/fixture runtime Pod marker ...`
これらは `pod-store` / `pod-registry` crate 名や on-disk `pods` compatibility の説明ではなく、現在の Worker 実行単位・workflow guidance・test diagnostics なので、Ticket の Worker rename intent に合わせて `Worker(s)` へ更新が必要。
`SendToPeerPod` の analytics-only legacy constant は、現行 `SendToPeerWorker` 分類と明示 comment があるため許容。
---
<!-- event: implementation_report author: yoi-coder-00001KVZG9BMS-worker-rename at: 2026-06-25T16:07:26Z -->
## Implementation report
Fourth follow-up implementation report after review request_changes:
対応内容:
1. 指摘箇所の Worker terminology 更新
- `docs/development/workflows.md`
- `## Child Pods``## Child Workers`
- `Child Pods may commit ...``Child Workers may commit ...`
- `docs/development/work-items.md`
- `Inside Pods ...``Inside Workers ...`
- `Ticket tools inside Pods``Ticket tools inside Workers`
- `Pods with the Ticket built-in feature ...``Workers with the Ticket built-in feature ...`
- `spawn coder/reviewer Pods ...``spawn coder/reviewer Workers ...`
- `coder Pods ...``coder Workers ...`
- `tests/e2e/tests/panel.rs`
- `fixture blocks host Pod launch``fixture blocks host Worker launch`
- `host/fixture runtime Pod marker ...``host/fixture runtime Worker marker ...`
2. 追加で見つかった docs/tests の active Pod 表現も更新
- `docs/design/tool-permissions-scope.md`: `Child Pods``Child Workers`
- `docs/design/compaction.md`: `long-running Pods``long-running Workers`
- `docs/design/memory-knowledge.md`: `normal Pods``normal Workers`
- `docs/design/plugin-packages.md`: `Restored Pods``Restored Workers`
- `docs/development/environment.md`: `spawned Pods``spawned Workers`
- `tests/e2e/tests/rewind.rs`: `single-pod rewind fixture``single-worker rewind fixture`
- `tests/e2e/tests/panel.rs`: active test helper/fixture naming and diagnostics updated to Worker terminology.
Validation:
- `cargo test -p worker`: success
- `cargo test -p yoi`: success
- `cargo check -p yoi`: success
- `cargo test -p protocol --features typescript`: success
- `cargo check -p yoi-e2e`: success
- `cd web/workspace && deno task check`: success
- `git diff --check`: success
- `nix build .#yoi --no-link`: success
Grep evidence:
- `rg -n -S --glob '!target' --glob '!docs/report/**' -- '--pod|yoi pod' .`: no matches.
- `rg -n -S --glob '!target' --glob '!docs/report/**' 'sibling coder/reviewer Pods|role Pods|talking to Pods|between clients and Pods|Spawned Pods|child Pods|Pods found|Pod categories|Pod row' crates docs tests resources AGENTS.md README.md KNOWN_ISSUES.md`: no matches.
- `rg -n -S 'Child Pods|Inside Pods|Ticket tools inside Pods|Pods with the Ticket built-in feature|spawn coder/reviewer Pods|coder Pods|host Pod launch|runtime Pod marker' docs/development/workflows.md docs/development/work-items.md tests/e2e/tests/panel.rs`: no matches.
- `rg -n -S '\bPod\b|\bPods\b' docs tests --glob '!target' --glob '!docs/report/**'`: no matches.
Commit:
- `cb0c52e7871849b9482c37ae63cacf4a2898da90 fix: update remaining active worker wording`
Residual risks / notes:
- child worktree は commit 後 clean。
---
<!-- event: review author: yoi-reviewer-00001KVZG9BMS-worker-rename at: 2026-06-25T16:11:36Z status: request_changes -->
## Review: request changes
Review result: request_changes
読取専用で `cb0c52e7` を確認した。前回指摘した `docs/development/workflows.md` / `docs/development/work-items.md` / `tests/e2e/tests/panel.rs` の blocker は解消している。指定 grep も報告通り空だった。
ただし、Ticket の「public type / module / doc comment の Pod terminology を Worker terminology に更新」「active references は legacy context として明示」条件に対して、まだ active な旧 wording が残っている。
Remaining blockers:
- `crates/tui/src/picker.rs:49`
- user-facing error message: `list all host/data-dir Pods`
- 現在の CLI/UX surface では Worker を表示しているため `Workers` へ更新が必要。
- `crates/tools/README.md:5`
- `used by Pods`
- crate README の active architecture doc なので `Workers` へ更新が必要。
- `crates/manifest/README.md:5`
- `used to create or restore Pods`
- `Worker` terminology に更新が必要。
- `crates/pod-store/Cargo.toml:3`
- description: `Durable Pod-name metadata/state persistence`
- `pod-store` crate 名を残すのは Ticket invariant 通りだが、metadata description は current Worker 実行単位に合わせるか、`legacy-named ... Worker metadata/state persistence` のように legacy context を明示する必要がある。
補足:
- `SendToPeerPod` の analytics-only legacy constant は、現行 `SendToPeerWorker` 分類と明示 comment があるため許容。
- `YOI_POD_RUNTIME_COMMAND` や on-disk `pods` compatibility は、別途 legacy/process compatibility context として扱われているため今回の blocker にはしていない。
---
<!-- event: implementation_report author: yoi-coder-00001KVZG9BMS-worker-rename at: 2026-06-25T16:13:43Z -->
## Implementation report
Fifth follow-up implementation report after review request_changes:
対応内容:
- `crates/tui/src/picker.rs`
- user-facing error message: `list all host/data-dir Pods``list all host/data-dir Workers`
- `crates/tools/README.md`
- `used by Pods``used by Workers`
- `crates/manifest/README.md`
- `used to create or restore Pods``used to create or restore Workers`
- `crates/pod-store/Cargo.toml`
- description: `Durable Pod-name metadata/state persistence``Legacy-named durable Worker metadata/state persistence`
- crate 名 `pod-store` は invariant 通り維持。
Validation:
- `cargo fmt --all`: success
- `cargo check -p yoi`: success
- `cargo test -p yoi`: success
- `git diff --check`: success
今回の変更は README / Cargo description / user-facing string の小修正のみのため、重い検証は追加していない。
Grep evidence:
- `rg -n -S 'list all host/data-dir Pods|used by Pods|used to create or restore Pods|Durable Pod-name metadata/state persistence' crates docs tests --glob '!target' --glob '!docs/report/**'`: no matches.
- `rg -n -S '\bPod\b|\bPods\b|\bpod-name\b|\bPod-name\b' crates docs tests --glob '!target' --glob '!docs/report/**'`: no matches.
Commit:
- `60dbd724c5496e80c7fe31a51f1425a7688e50ee fix: clean remaining worker wording`
Residual risks / notes:
- child worktree は commit 後 clean。
---
<!-- event: review author: yoi-reviewer-00001KVZG9BMS-worker-rename at: 2026-06-25T16:15:07Z status: approve -->
## Review: approve
Review result: approve
読取専用で `60dbd724` の follow-up diff と grep を確認した。追加の blocker は見つからなかった。
確認した点:
- `crates/tui/src/picker.rs` の user-facing wording は `Workers` に更新済み。
- `crates/tools/README.md` / `crates/manifest/README.md``Workers` terminology に更新済み。
- `crates/pod-store/Cargo.toml` description は `Legacy-named durable Worker metadata/state persistence` となり、crate 名を残す Ticket invariant と current Worker terminology の両方に整合。
- `crates/worker` は存在し、`crates/pod` は不在。
- workspace/Cargo 上の旧 `pod` package/import は見当たらず、`worker` crate 参照になっている。
- 指定 blocker phrase grep は空。
- repo-wide の高リスク旧語 grep では、`SendToPeerPod` は `crates/session-analytics` の analytics-only legacy constant のみで、現行 `SendToPeerWorker` 分類と明示 comment があるため許容範囲。
- `--pod` / `yoi pod` / `PodEvent` / `PodStatus` / `PodLaunchFailed` / `SpawnPod` / `pod-session-state.md` 等の active stale refs は見当たらなかった。
検証コマンド自体は read-only 方針のため再実行していないが、報告された validation 内容と今回の差分・grep 確認から、これまでの request_changes blockers は解消済みと判断する。
---
<!-- event: decision author: yoi-orchestrator at: 2026-06-25T16:17:59Z -->
## Decision
Routing decision: blocked_by_dependency_or_missing_authority
Reason:
- Dashboard 起点の `/ticket-orchestrator-routing` で target Ticket は未指定だったため、queue 状態を再確認した。
- `TicketList` では `queued` 0 件、`ready` 0 件、`inprogress` 1 件のみ。追加で受理すべき queued Ticket はない。
- 唯一の active Ticket は本 Ticket `00001KVZG9BMS`。実装 branch は reviewer approve 済みで、orchestration worktree には merge commit `2a7e8775 merge: 00001KVZG9BMS worker crate rename` がある。
- ただし Orchestrator 側の最終 validation 実行はユーザー割り込みで中断され、merge 後の Orchestrator validation / done 遷移 / child worktree cleanup の evidence はまだ Ticket に記録されていない。
- 今回の workflow invocation は「Dashboard opened... wait for explicit follow-up before spawning role Pods」という指示付きであり、この routing pass では新規 role Pod は spawn しない。
Evidence checked:
- Ticket body / thread: rename 要件、accepted IntentPacket、Coder implementation reports、Reviewer approve (`60dbd724` follow-up) を確認。
- Relations: outgoing dependency `00001KVZD10ED`、incoming dependent `00001KVZBCQH4`。derived blockers は空。
- Orchestration plan: accepted plan `orch-plan-20260625-141406-1` は implementation worktree `/home/hare/Projects/yoi/.worktree/00001KVZG9BMS-worker-crate-rename` / branch `work/00001KVZG9BMS-worker-crate-rename`
- Repository/worktree: orchestration branch HEAD は `2a7e8775` merge commit、working tree は clean。implementation worktree remains at `60dbd724` and clean per prior checks.
- Visible Workers/Pods: existing coder/reviewer child Workers are idle; no new child Worker was spawned in this routing pass.
Next action:
- 明示 follow-up があれば、orchestration worktree で interrupted final validation を再開する。
- validation が通れば結果を implementation_report として記録し、`inprogress -> done`、必要な cleanupchild Workers stop、implementation worktree/branch cleanupへ進む。
- validation/review evidence に新 blocker が出た場合だけ、追加修正または reviewer loop を検討する。新規 role Worker spawn は明示 follow-up/authority のもとで行う。
Escalate if:
- merge 後 validation が失敗する。
- cleanup が dirty worktree / branch divergence / live Worker scope conflict で blocked になる。
- `develop` など merge target への反映権限・タイミングについて追加判断が必要になる。
---
<!-- event: state_changed author: yoi-orchestrator at: 2026-06-25T16:19:23Z from: inprogress to: done reason: user_confirmed_done_after_merge_and_review field: state -->
## State changed
ユーザー指示「StopPodでハングしてそうだったから再起しただけ / doneにしといて」を受け、完了済みとして記録する。
完了根拠:
- 実装 branch は orchestration worktree に merge 済み: `2a7e8775 merge: 00001KVZG9BMS worker crate rename`
- Reviewer は `60dbd724` follow-up を approve 済みで、残 blocker なし。
- Coder 側 validation は `cargo test -p worker`、`cargo test -p yoi`、`cargo check -p yoi`、`cargo test -p protocol --features typescript`、`cargo check -p yoi-e2e`、`web/workspace deno task check`、`git diff --check`、`nix build .#yoi --no-link` 成功報告あり。
- 最終 Orchestrator validation は operator restart により中断されていたが、ユーザーがその事情を説明し done 記録を明示許可した。
補足:
- この state change は close ではなく `done` 記録。必要なら別途 close / cleanup を扱う。
---

View File

@ -1 +0,0 @@
{"id":"orch-plan-20260625-164354-1","ticket_id":"00001KVZKST83","kind":"blocked_by","related_ticket":"00001KVZBCQH4","note":"Queue routing checked after Dashboard Queue. FS store feature depends on worker-runtime core `00001KVZBCQH4`, which is currently inprogress and under review. Do not start FS persistence implementation until core API is reviewed/merged/done.","author":"yoi-orchestrator","at":"2026-06-25T16:43:54Z"}

View File

@ -1,13 +0,0 @@
{
"version": 1,
"relations": [
{
"ticket_id": "00001KVZKST83",
"kind": "depends_on",
"target": "00001KVZBCQH4",
"note": "FS persistence is an optional feature on top of the worker-runtime core API.",
"author": "yoi ticket",
"at": "2026-06-25T14:47:43Z"
}
]
}

View File

@ -1,55 +0,0 @@
---
title: 'worker-runtimeにFS永続化featureを追加する'
state: 'queued'
created_at: '2026-06-25T14:44:02Z'
updated_at: '2026-06-25T16:44:04Z'
assignee: null
queued_by: 'workspace-panel'
queued_at: '2026-06-25T16:39:26Z'
---
## 背景
`worker-runtime` core は embedded use のため memory store を持つが、独立 Runtime process では process restart に耐える local persistence が必要になる。Backend は SQLite control plane / projection を持つが、remote Runtime process が Backend SQLite を直接 authority とする設計にはしない。Runtime execution store は Runtime 側の local filesystem に置くのが v0 では最も単純で、既存 `pod-store` / session jsonl / runtime dir の知見も活用できる。
この Ticket では `worker-runtime``fs-store` feature と filesystem persistence backend を実装する。HTTP server / event stream server は別 Ticket とする。
## 要件
- `worker-runtime``fs-store` feature を追加する。
- Feature disabled 時、core library は FS store dependency を強制しない。
- `FsRuntimeStore` 相当を追加し、Runtime の store backend として選択できる。
- Filesystem layout は Runtime scoped / Worker scoped にする。
- runtime record / config snapshot。
- worker record。
- worker state。
- event log JSONL。
- transcript projection JSONL。
- overview / usage projection。
- Store は `runtime_id + worker_id` を authority とし、`pod_name` / socket path / legacy session path を authority にしない。
- Atomic write / directory creation / corrupt record diagnostics / bounded read を扱う。
- 旧 `pod-store` の metadata JSON / active segment pointer / atomic write pattern は参考にするが、standalone `worker-store` crate は作らない。
- Memory store tests と FS store tests の両方が通る。
## Non-goals
- REST command server。
- SSE / WebSocket event stream server。
- Backend RuntimeRegistry integration。
- Full legacy Pod session migration。
- SQLite Runtime store。
- Standalone `worker-store` crate。
## 受け入れ条件
- `worker-runtime` に optional `fs-store` feature がある。
- `fs-store` disabled でも `worker-runtime` core が compile できる。
- `FsRuntimeStore` が Runtime の persistence backend として使える。
- Worker create / state update / event append / transcript append / bounded read が FS store で動く。
- FS layout が Runtime/Worker scoped であり、legacy Pod path を public authority にしていない。
- Corrupt/missing files are surfaced as typed diagnostics/errors.
- `cargo test -p worker-runtime --no-default-features` が通る。
- `cargo test -p worker-runtime --features fs-store` が通る。
- `cargo check -p yoi` が通る。
- `git diff --check` が通る。
- `nix build .#yoi --no-link` が通る。

View File

@ -1,61 +0,0 @@
<!-- event: create author: "yoi ticket" at: 2026-06-25T14:44:02Z -->
## 作成
LocalTicketBackend によって作成されました。
---
<!-- event: intake_summary author: hare at: 2026-06-25T16:34:16Z -->
## Intake summary
Marked ready by `yoi ticket state`.
---
<!-- event: state_changed author: "yoi ticket" at: 2026-06-25T16:34:16Z from: planning to: ready reason: cli_state field: state -->
## State changed
Marked ready by `yoi ticket state`.
---
<!-- event: state_changed author: workspace-panel at: 2026-06-25T16:39:26Z from: ready to: queued reason: queued field: state -->
## State changed
Ticket を `workspace-panel` が queued にしました。
---
<!-- event: decision author: yoi-orchestrator at: 2026-06-25T16:44:04Z -->
## Decision
Routing decision: blocked_by_dependency_or_missing_authority
Reason:
- Dashboard Queue による routing 許可を受けて Ticket / relations / orchestration plan / queue state を確認した。
- 本 Ticket は `00001KVZBCQH4` (`worker-runtime core crateと組み込みRuntime APIを作る`) に `depends_on` relation を持つ。
- `00001KVZBCQH4` は現在 `inprogress` で、implementation commits はあるが reviewer review 中。merge / Orchestrator validation / done ではない。
- FS persistence feature は worker-runtime core API / store boundary に依存するため、core API 確定前に開始しない。
Evidence checked:
- Ticket body: `fs-store` feature、atomic write、schema/version metadata、diagnostics、Non-goals。
- Relations: outgoing `depends_on -> 00001KVZBCQH4`
- Orchestration plan: blocker record `orch-plan-20260625-164354-1` を追加。
- Queue state: queued は本 Ticket、REST server、Backend Registry foundation、Backend embedded connection の4件。inprogress は `00001KVZBCQH4` 1件。
Next action:
- 本 Ticket は queued のまま待機。
- `00001KVZBCQH4` が reviewer approve / merge / validation / done になった後、再 routing する。
Escalate if:
- `00001KVZBCQH4` の store/allocation boundary が FS feature の requirements を満たさない。
- FS feature を core Ticket に巻き戻す必要が出る。
---

View File

@ -1 +0,0 @@
{"id":"orch-plan-20260625-164410-1","ticket_id":"00001KVZKSTE2","kind":"blocked_by","related_ticket":"00001KVZBCQH4","note":"Queue routing checked after Dashboard Queue. REST command server depends on worker-runtime core `00001KVZBCQH4`, which is currently inprogress and under review. Do not start HTTP/server implementation until core API is reviewed/merged/done.","author":"yoi-orchestrator","at":"2026-06-25T16:44:10Z"}

View File

@ -1,13 +0,0 @@
{
"version": 1,
"relations": [
{
"ticket_id": "00001KVZKSTE2",
"kind": "depends_on",
"target": "00001KVZBCQH4",
"note": "REST command server wraps the worker-runtime core API.",
"author": "yoi ticket",
"at": "2026-06-25T14:47:43Z"
}
]
}

View File

@ -1,58 +0,0 @@
---
title: 'worker-runtimeにREST command serverを追加する'
state: 'queued'
created_at: '2026-06-25T14:44:02Z'
updated_at: '2026-06-25T16:44:20Z'
assignee: null
queued_by: 'workspace-panel'
queued_at: '2026-06-25T16:39:39Z'
---
## 背景
`worker-runtime` は library として Backend に組み込めるだけでなく、別ホスト上の独立 Runtime process としても動かしたい。独立 process の Runtime は、Backend が client として接続できる command API を公開する必要がある。Browser は Runtime process に直接接続せず、常に Backend を経由する。
この Ticket では observation stream ではなく、Worker 操作 command 用の REST/HTTP server と `worker-runtime/main.rs` の最小 process wrapper を実装する。
## 要件
- `worker-runtime``http-server` feature を追加する。
- `http-server` disabled 時、core library は HTTP server dependency を強制しない。
- `worker-runtime/main.rs` または binary entrypoint が Runtime を起動し、HTTP command API を公開する。
- Command API は少なくとも以下を扱う。
- `GET /v1/runtime`
- `GET /v1/workers`
- `GET /v1/workers/{worker_id}`
- `POST /v1/workers`
- `POST /v1/workers/{worker_id}/input`
- `POST /v1/workers/{worker_id}/stop`
- `POST /v1/workers/{worker_id}/cancel`
- `GET /v1/workers/{worker_id}/transcript`
- API は Runtime lib の methods を呼ぶ wrapper とし、Worker semantics を二重実装しない。
- Command response は typed JSON shape とする。
- Busy / unknown worker / invalid input / unsupported operation / runtime unavailable を typed error にする。
- Runtime process config は v0 で最小限でよいが、runtime id / bind address / store selection を扱えるようにする。
- v0 auth は minimal local token placeholder でもよいが、Browser に Runtime credential を渡さない前提を崩さない。
## Non-goals
- SSE / WebSocket event stream server。
- Backend HTTP client integration。
- Dynamic Runtime registration。
- Browser direct Runtime access。
- Full auth / permission model。
- FS store implementation beyond using existing `fs-store` if available。
## 受け入れ条件
- `worker-runtime` に optional `http-server` feature がある。
- `http-server` disabled でも `worker-runtime` core が compile できる。
- Runtime process binary starts and exposes REST command endpoints.
- REST handlers delegate to `Runtime` lib API rather than duplicating Worker semantics.
- Worker create / input / stop / cancel / detail / transcript endpoints have typed request/response/error shapes.
- Browser-facing docs/comments state that Browser must go through Backend, not Runtime directly.
- Focused HTTP handler tests are added.
- `cargo test -p worker-runtime --features http-server` が通る。
- `cargo check -p yoi` が通る。
- `git diff --check` が通る。
- `nix build .#yoi --no-link` が通る。

View File

@ -1,61 +0,0 @@
<!-- event: create author: "yoi ticket" at: 2026-06-25T14:44:02Z -->
## 作成
LocalTicketBackend によって作成されました。
---
<!-- event: intake_summary author: hare at: 2026-06-25T16:34:16Z -->
## Intake summary
Marked ready by `yoi ticket state`.
---
<!-- event: state_changed author: "yoi ticket" at: 2026-06-25T16:34:16Z from: planning to: ready reason: cli_state field: state -->
## State changed
Marked ready by `yoi ticket state`.
---
<!-- event: state_changed author: workspace-panel at: 2026-06-25T16:39:39Z from: ready to: queued reason: queued field: state -->
## State changed
Ticket を `workspace-panel` が queued にしました。
---
<!-- event: decision author: yoi-orchestrator at: 2026-06-25T16:44:20Z -->
## Decision
Routing decision: blocked_by_dependency_or_missing_authority
Reason:
- Dashboard Queue による routing 許可を受けて Ticket / relations / orchestration plan / queue state を確認した。
- 本 Ticket は `00001KVZBCQH4` (`worker-runtime core crateと組み込みRuntime APIを作る`) に `depends_on` relation を持つ。
- `00001KVZBCQH4` は現在 `inprogress` で、implementation commits はあるが reviewer review 中。merge / Orchestrator validation / done ではない。
- REST command server は worker-runtime command/response/projection semantics に依存するため、core API 確定前に HTTP/server implementation side effect を開始しない。
Evidence checked:
- Ticket body: REST command server、request/response schema、operation timeouts、host/port config、diagnostics、Non-goals。
- Relations: outgoing `depends_on -> 00001KVZBCQH4`。incoming dependent `00001KVZ9JGK0`
- Orchestration plan: blocker record `orch-plan-20260625-164410-1` を追加。
- Queue state: queued は本 Ticket、FS store、Backend Registry foundation、Backend embedded connection の4件。inprogress は `00001KVZBCQH4` 1件。
Next action:
- 本 Ticket は queued のまま待機。
- `00001KVZBCQH4` が reviewer approve / merge / validation / done になった後、再 routing する。
Escalate if:
- worker-runtime core の command/projection API が REST mapping に足りない。
- REST server concerns を core crate に混ぜないと acceptance を満たせないように見える。
---

View File

@ -1,21 +0,0 @@
{
"version": 1,
"relations": [
{
"ticket_id": "00001KVZKSTJT",
"kind": "depends_on",
"target": "00001KVZBCQH4",
"note": "Event stream server exposes the worker-runtime core event bus/log.",
"author": "yoi ticket",
"at": "2026-06-25T14:47:43Z"
},
{
"ticket_id": "00001KVZKSTJT",
"kind": "depends_on",
"target": "00001KVZKSTE2",
"note": "Observation endpoints share the Runtime process server surface with the REST command server.",
"author": "yoi ticket",
"at": "2026-06-25T14:47:43Z"
}
]
}

View File

@ -1,48 +0,0 @@
---
title: 'worker-runtimeにWebSocket event stream serverを追加する'
state: 'planning'
created_at: '2026-06-25T14:44:02Z'
updated_at: '2026-06-25T16:42:14Z'
assignee: null
---
## 背景
Runtime command は REST/HTTP でよいが、Worker output / status / transcript update を Backend が追うには observation transport が必要になる。Runtime から Backend へ能動接続する相互型は v0 では採用せず、Backend が Runtime の event stream に接続する形にする。Browser は Runtime event stream に直接接続せず、Backend が proxy / projection する。
この Ticket では `worker-runtime` process に WebSocket based observation server を追加する。SSE は将来追加してよいが、v0 の実装対象は Backend-owned WebSocket client が接続する Runtime event stream とする。command API とは分離する。
## 要件
- `worker-runtime``ws-server` feature を追加する。
- Feature disabled 時、core library は stream server dependency を強制しない。
- Runtime process が Worker / Runtime events を WebSocket observation endpoint で公開できる。
- Endpoint は少なくとも以下のどちらかを扱う。
- `GET /v1/events/ws?cursor=...`
- `GET /v1/workers/{worker_id}/events/ws?cursor=...`
- Event stream は Runtime lib の event bus / event log を元にする。
- Event cursor / event id は Runtime local opaque id とする。
- Reconnect / cursor resume / bounded backlog / unknown cursor の扱いを typed にする。
- Transcript projection polling endpoint と event stream の責務を分ける。
- Browser direct Runtime access は想定せず、Backend client が購読する。
## Non-goals
- REST command server implementation。
- Backend event proxy UI implementation。
- Runtime-initiated Backend push connection。
- Full exactly-once delivery。
- Browser-facing WebSocket protocol。
## 受け入れ条件
- `worker-runtime` に optional `ws-server` feature がある。
- Feature disabled でも `worker-runtime` core が compile できる。
- Runtime process exposes worker/runtime WebSocket event stream endpoint.
- Backend client can reconnect with cursor / last event id semantics at the protocol level.
- Unknown cursor / expired cursor / worker not found are typed errors or stream diagnostics.
- WebSocket event stream tests cover at least connect, event delivery, cursor resume, and worker-scoped filtering.
- `cargo test -p worker-runtime --features ws-server` が通る。
- `cargo check -p yoi` が通る。
- `git diff --check` が通る。
- `nix build .#yoi --no-link` が通る。

View File

@ -1,52 +0,0 @@
<!-- event: create author: "yoi ticket" at: 2026-06-25T14:44:02Z -->
## 作成
LocalTicketBackend によって作成されました。
---
<!-- event: intake_summary author: hare at: 2026-06-25T16:34:16Z -->
## Intake summary
Marked ready by `yoi ticket state`.
---
<!-- event: state_changed author: "yoi ticket" at: 2026-06-25T16:34:16Z from: planning to: ready reason: cli_state field: state -->
## State changed
Marked ready by `yoi ticket state`.
---
<!-- event: state_changed author: "yoi ticket" at: 2026-06-25T16:42:14Z from: ready to: planning reason: cli_state field: state -->
## State changed
State changed to `planning`.
---
<!-- event: decision author: hare at: 2026-06-25T16:42:14Z -->
## Decision
Returned to planning because the current ticket is not concrete enough.
The purpose is specifically observation: Backend subscribes to a Runtime-owned WebSocket stream to receive Worker output and related runtime/worker events. It is not a command channel, not browser-facing, and not the path for sending user input.
Before this can be ready, define the event model and protocol boundary concretely:
- which Worker output events are streamed (text delta/final, reasoning visibility policy, tool call lifecycle, status, run started/completed/errored, usage, diagnostics);
- whether the stream is runtime-wide, worker-scoped, or both;
- event envelope shape, event id/cursor semantics, ordering, backlog, reconnect behavior, and unknown/expired cursor handling;
- relationship between streamed output and transcript projection/event log persistence;
- Backend client/proxy expectations and how Browser receives the projection without connecting directly to Runtime;
- what is deliberately excluded from the stream, such as raw provider trace or raw full session log.
---

View File

@ -1 +0,0 @@
{"id":"orch-plan-20260625-163206-1","ticket_id":"00001KVZKSV6C","kind":"blocked_by","related_ticket":"00001KVZBCQH4","note":"Queue routing checked after Dashboard Queue. This Backend RuntimeRegistry foundation Ticket depends on `00001KVZBCQH4` worker-runtime core. That dependency is currently inprogress and only at coder implementation report stage, not reviewed/merged/done, so implementation side effects for this Ticket are blocked.","author":"yoi-orchestrator","at":"2026-06-25T16:32:06Z"}

View File

@ -1,13 +0,0 @@
{
"version": 1,
"relations": [
{
"ticket_id": "00001KVZKSV6C",
"kind": "depends_on",
"target": "00001KVZBCQH4",
"note": "Backend RuntimeRegistry foundation should use worker-runtime core domain types.",
"author": "yoi ticket",
"at": "2026-06-25T16:30:00Z"
}
]
}

View File

@ -1,88 +0,0 @@
---
title: 'Backend RuntimeRegistryの基盤をworker-runtime向けに整理する'
state: 'queued'
created_at: '2026-06-25T14:44:03Z'
updated_at: '2026-06-25T16:32:17Z'
assignee: null
queued_by: 'workspace-panel'
queued_at: '2026-06-25T16:31:28Z'
---
## 背景
Workspace Backend は複数 Runtime を束ねる `RuntimeRegistry` を持つ。Registry は Worker を実行する主体ではなく、embedded Runtime と remote Runtime process、既存 local Worker compatibility adapter を同じ Backend-facing API から参照・routing するための集約境界である。
この Ticket は embedded Runtime 実装や remote HTTP client 実装を含めない。先に Backend 側の Registry 構造、runtime identity、capability/status projection、Browser-facing API の authority 境界を `worker-runtime` の domain model に合わせて整理する。
## 要件
### Registry responsibility
- Backend `RuntimeRegistry` は Runtime を実行しない。
- Backend `RuntimeRegistry` は以下を扱う集約境界とする。
- Runtime lookup。
- Runtime summary / capability / status projection。
- Runtime-scoped Worker identity の routing key。
- Browser-facing API への safe projection。
- workspace visibility / policy / audit hook point。
- Runtime internal store / allocation registry と Backend `RuntimeRegistry` を混同しない。
- Worker metadata persistence や live allocation authority は Runtime 側の責務とし、Backend Registry は直接所有しない。
### Runtime identity / handle model
- Backend-facing Runtime identity は `runtime_id` を authority とする。
- Worker authority は `runtime_id + worker_id` とする。
- UI 表示用 `display_ref` は authority にしない。
- Registry は将来以下の runtime source を扱える shape にする。
- embedded `worker_runtime::Runtime`
- remote Runtime process client。
- existing local Worker/Pod compatibility adapter。
- この Ticket では embedded / remote 実 handle の実装は後続に残す。
- Existing local metadata projection は必要なら compatibility source として残すが、正規 Runtime authority として扱わない。
### Backend API boundary
- Browser-facing API は Runtime endpoint / token / socket path / session path / local metadata path を受け取らない。
- Browser-facing API は `runtime_id + worker_id` を authority として扱える shape にする。
- Existing `/api/workers` / `/api/hosts` / runtime list behavior は、新 Registry model へ段階移行できるよう整理する。
- v0 では既存 API の behavior を維持しつつ、内部 model を RuntimeRegistry に寄せてよい。
- New runtime-scoped endpoints を足すか、既存 endpoints を拡張するかは実装時に決めてよいが、ticket内で選んだ方針を記録する。
### Implementation target
- 主な対象は `crates/workspace-server/src/hosts.rs``crates/workspace-server/src/server.rs` とする。
- 既存 `WorkerRuntimeRegistry` / `LocalPodRuntime` / `LocalRuntimeBridge` 相当を、Backend Registry foundation と local compatibility source の境界に整理する。
- `LocalPodRuntime` という名前が正規 Runtime 実装に見える場合は、`LocalPodCompatibilitySource` / `LocalWorkerCompatibilityAdapter` 相当の名前へ寄せる。
- 既存 local metadata reader の behavior は維持してよいが、Runtime authority ではなく compatibility projection として diagnostics / implementation kind に表す。
- 既存 `/api/hosts` / `/api/workers` / `/api/hosts/{host_id}/workers` の outward behavior は原則維持する。
- runtime-scoped endpoint を新設する場合は、既存 endpoint を壊さず追加する。
- この Ticket では Worker create / send input / remote HTTP call / embedded direct call の実処理は実装しない。後続 handle が差し込める型・routing境界までに留める。
### Error / diagnostics
- Unknown runtime、unknown worker、runtime unavailable、operation unsupported、worker not visible を typed に分けられるようにする。
- Compatibility local source 由来の stale metadata / invalid metadata は diagnostic として扱い、Runtime authority を歪めない。
## Non-goals
- Embedded `worker_runtime::Runtime` の登録・routing 実装。
- Remote HTTP Runtime client 実装。
- REST command server / event stream server implementation。
- Backend internal Companion Web Console completion。
- Dynamic Runtime registration。
- Full auth / permission model。
- Removing local compatibility path。
## 受け入れ条件
- Workspace backend に `worker-runtime` domain model と整合した `RuntimeRegistry` 基盤がある。
- Registry は Runtime identity / Worker routing key / capability / status projection を扱える。
- Registry の責務が Runtime internal store/allocation と code/docs/tests 上で分離されている。
- Browser-facing API が Runtime endpoint / token / socket path / session path を authority として受け取らない。
- Existing local Worker/Pod metadata projection は compatibility source として明示されている。
- Embedded/remote runtime 実装は後続 Ticket で追加できる handle boundary がある。
- Focused workspace-server tests cover Registry identity/projection/error mapping and local compatibility source behavior.
- `cargo test -p yoi-workspace-server` が通る。
- `cargo check -p yoi` が通る。
- `git diff --check` が通る。
- `nix build .#yoi --no-link` が通る。

View File

@ -1,82 +0,0 @@
<!-- event: create author: "yoi ticket" at: 2026-06-25T14:44:03Z -->
## 作成
LocalTicketBackend によって作成されました。
---
<!-- event: decision author: hare at: 2026-06-25T16:27:28Z -->
## Decision
Decision update: split Backend Runtime work into three implementation tickets.
1. 00001KVZKSV6C Backend RuntimeRegistryの基盤をworker-runtime向けに整理する
- Registry identity/projection/error boundary only.
- No embedded Runtime handle implementation.
- No remote Runtime client implementation.
2. 00001KVZSGT0Q Backend RuntimeRegistryにembedded worker-runtimeを接続する
- Direct lib-call integration for backend-internal Runtime.
3. 00001KVZSGT14 Backend RuntimeRegistryにremote worker-runtime processを接続する
- HTTP/event-stream client integration for remote Runtime processes.
Companion Web Console depends on embedded integration, not remote integration.
---
<!-- event: intake_summary author: hare at: 2026-06-25T16:30:31Z -->
## Intake summary
Marked ready by `yoi ticket state`.
---
<!-- event: state_changed author: "yoi ticket" at: 2026-06-25T16:30:31Z from: planning to: ready reason: cli_state field: state -->
## State changed
Marked ready by `yoi ticket state`.
---
<!-- event: state_changed author: workspace-panel at: 2026-06-25T16:31:28Z from: ready to: queued reason: queued field: state -->
## State changed
Ticket を `workspace-panel` が queued にしました。
---
<!-- event: decision author: yoi-orchestrator at: 2026-06-25T16:32:17Z -->
## Decision
Routing decision: blocked_by_dependency_or_missing_authority
Reason:
- Dashboard Queue による routing 許可を受けて Ticket / relations / orchestration plan / workspace state を確認した。
- 本 Ticket は `00001KVZBCQH4` (`worker-runtime core crateと組み込みRuntime APIを作る`) に `depends_on` relation を持つ。
- `00001KVZBCQH4` は現在 `inprogress`。Coder implementation report は届いているが、まだ review / merge / validation / done ではない。
- 本 Ticket の要件は worker-runtime core domain types を前提に Backend Registry foundation を整理する内容なので、依存 Ticket が確定する前に別 worktree / Coder Worker を開始すると API churn / conflict risk が高い。
Evidence checked:
- Ticket body: Backend RuntimeRegistry foundation、runtime_id / worker_id authority、existing local compatibility source、workspace-server hosts/server target、Non-goals。
- Relations: outgoing `depends_on -> 00001KVZBCQH4`; incoming dependents `00001KVZSGT0Q`, `00001KVZSGT14`
- Orchestration plan: blocker record `orch-plan-20260625-163206-1` を追加。
- Workspace state: `00001KVZBCQH4` implementation worktree exists and coder has reported commit `9b2cae32`, but no reviewer approval / Orchestrator merge yet。
- Queue state: 本 Ticket と `00001KVZSGT0Q` が queued、`00001KVZBCQH4` が inprogress。
Next action:
- 本 Ticket は queued のまま待機。
- `00001KVZBCQH4` が reviewer approve / merge / validation / done になった後、再 routing して unblocked なら `queued -> inprogress` acceptance に進む。
Escalate if:
- `00001KVZBCQH4` の Runtime API shape が本 Ticket の前提を満たさない。
- Backend Registry foundation 側で worker-runtime core の追加変更が必要になる。
---

View File

@ -1 +0,0 @@
{"id":"orch-plan-20260625-164457-1","ticket_id":"00001KVZQHPNY","kind":"blocked_by","related_ticket":"00001KVZBCQH4","note":"Queue routing checked after Dashboard Queue. Profile/config bundle sync depends on worker-runtime core `00001KVZBCQH4`, which is currently inprogress and under review. Do not start sync implementation until core CreateWorkerRequest/Profile boundary is reviewed/merged/done.","author":"yoi-orchestrator","at":"2026-06-25T16:44:57Z"}

View File

@ -1,13 +0,0 @@
{
"version": 1,
"relations": [
{
"ticket_id": "00001KVZQHPNY",
"kind": "depends_on",
"target": "00001KVZBCQH4",
"note": "Config bundle sync builds on the worker-runtime core CreateWorkerRequest/Profile boundary.",
"author": "yoi ticket",
"at": "2026-06-25T15:51:07Z"
}
]
}

View File

@ -1,95 +0,0 @@
---
title: 'RuntimeへProfile/config bundleを同期する'
state: 'queued'
created_at: '2026-06-25T15:49:30Z'
updated_at: '2026-06-25T16:45:08Z'
assignee: null
queued_by: 'workspace-panel'
queued_at: '2026-06-25T16:44:39Z'
---
## 背景
Runtime は Worker を動かす環境であり、Worker creation 時には Profile / prompt resources / tool policy / plugin declarations / host-local policy を使って最終的な WorkerSpec を作る必要がある。Backend が Profile を完全解決して巨大な WorkerSpec を毎回 Runtime に渡す設計にすると、remote Runtime / Plugin / secret / mount / host-specific policy と相性が悪い。
一方で、Runtime に `profile = "builtin:companion"` の selector だけを送っても、remote Runtime が同じ Profile / prompt / plugin resource を持っている保証はない。したがって、Backend は workspace/project で有効な Profile/config bundle を Runtime に同期し、Worker creation では profile selector + bundle digest + intent を送る形にしたい。
この Ticket は `worker-runtime` core の後続として、Runtime への Profile/config bundle sync と Runtime-side profile resolution を実装する。初期 `worker-runtime` core では `config_bundle = None` による builtin/default fallback で動作確認できるため、この同期機能は別実装粒度とする。
## 要件
### Config bundle model
- Runtime に同期可能な Profile/config bundle model を定義する。
- Bundle は digest / revision / workspace id / created_at / source metadata を持つ。
- Bundle は少なくとも以下を表現できる。
- Profile definitions。
- prompt resources。
- workflow definitions or references。
- tool declarations / tool policy。
- plugin descriptors / package refs / digests。
- non-secret model/provider config refs。
- language settings。
- workspace/project metadata。
- grants / policy declarations。
- Secret values、runtime-local mount actual path、local cache path、raw socket/session path は bundle に含めない。
- Secret は secret ref / grant / policy として表現し、値は Runtime host-local secret store が解決する。
### Runtime sync API
- Runtime は config bundle を受け取り、digest で保存・照合できる。
- Embedded Runtime では direct lib API で bundle sync できる。
- Networked Runtime では REST API で bundle sync できる shape を定義する。
- 例: `PUT /v1/config-bundles/{digest}`
- 例: `GET /v1/config-bundles/{digest}` or status endpoint。
- Runtime は create worker 時に指定された bundle digest を持っているか検証する。
- Bundle digest mismatch / missing bundle / invalid profile selector / unsupported declaration を typed error にする。
### Worker creation integration
- `CreateWorkerRequest` は profile selector + config bundle ref を受ける。
- Runtime は bundle 内の Profile を最終解決する。
- Runtime は host-local policy / capability / secret / mount / plugin grant enforcement を適用して `ResolvedWorkerSpec` を作る。
- Backend は Profile を完全解決した巨大 WorkerSpec を送らず、intent / profile selector / bundle ref / required capabilities を送る。
- Runtime-local builtin/default fallback は残してよいが、remote Runtime / plugin use では bundle が必要になる policy を設定できる。
### Backend responsibility
- Backend は workspace/project の有効 config bundle を作成・選択し、対象 Runtime に同期する。
- Backend はどの Runtime にどの bundle を同期してよいかを policy / workspace visibility で判断する。
- Backend は Browser に Runtime credential / direct endpoint / raw bundle storage path を渡さない。
- Backend RuntimeRegistry は Runtime の bundle availability / digest status を確認できる。
### Plugin / host policy boundary
- Plugin package bytes を bundle に含めるか package ref + digest にするかは実装時に決める。
- Runtime は plugin descriptor / digest / grants を検証してから tool/service/ingress surface を登録する。
- Runtime host が保護したい secret / mount / network egress / shell/git availability は host-local policy として最終判断する。
- Bundle sync は Plugin execution を直接許可するものではなく、Runtime-side grant enforcement が必要である。
## Non-goals
- `worker-runtime` core crate の作成。
- FS store feature の実装。
- REST command server の実装そのもの。ただし API shape は定義してよい。
- Full Plugin package manager / registry / signature policy。
- Secret value synchronization。
- Workspace mount actual path synchronization without host policy。
- Backend internal Companion Web Console completion。
## 受け入れ条件
- Config bundle domain type が定義され、digest / revision / provenance を持つ。
- Runtime は bundle を保存・一覧/確認・digest 検証できる。
- `CreateWorkerRequest` が profile selector + config bundle ref を扱える。
- Runtime は bundle 内 Profile を解決し、host-local policy を適用する境界を持つ。
- Missing bundle / digest mismatch / invalid profile / unsupported declaration が typed error になる。
- Bundle は secret values / raw socket path / raw session path / runtime-local mount actual path を含まない。
- Backend は Runtime へ bundle sync し、Runtime の bundle availability を確認できる。
- Remote Runtime 用 REST sync API shape または実 endpoint がある。
- Builtin/default fallback と synced bundle mode の責務が docs/tests で区別されている。
- `cargo test -p worker-runtime` が通る。
- `cargo test -p yoi-workspace-server` が通る。
- `cargo check -p yoi` が通る。
- `git diff --check` が通る。
- `nix build .#yoi --no-link` が通る。

View File

@ -1,62 +0,0 @@
<!-- event: create author: "yoi ticket" at: 2026-06-25T15:49:30Z -->
## 作成
LocalTicketBackend によって作成されました。
---
<!-- event: intake_summary author: hare at: 2026-06-25T16:34:16Z -->
## Intake summary
Marked ready by `yoi ticket state`.
---
<!-- event: state_changed author: "yoi ticket" at: 2026-06-25T16:34:16Z from: planning to: ready reason: cli_state field: state -->
## State changed
Marked ready by `yoi ticket state`.
---
<!-- event: state_changed author: workspace-panel at: 2026-06-25T16:44:39Z from: ready to: queued reason: queued field: state -->
## State changed
Ticket を `workspace-panel` が queued にしました。
---
<!-- event: decision author: yoi-orchestrator at: 2026-06-25T16:45:08Z -->
## Decision
Routing decision: blocked_by_dependency_or_missing_authority
Reason:
- Dashboard Queue による routing 許可を受けて Ticket / relations / orchestration plan / queue state を確認した。
- 本 Ticket は `00001KVZBCQH4` (`worker-runtime core crateと組み込みRuntime APIを作る`) に `depends_on` relation を持つ。
- `00001KVZBCQH4` は現在 `inprogress` で、implementation/package fix commits はあるが reviewer review 中。merge / Orchestrator validation / done ではない。
- Config bundle sync は worker-runtime core の `CreateWorkerRequest` / Profile selector / `ConfigBundleRef` boundary に依存するため、core API 確定前に implementation side effect を開始しない。
Evidence checked:
- Ticket body: config bundle model、Runtime sync API、Worker creation integration、Backend responsibility、Plugin/host policy boundary、Non-goals。
- Relations: outgoing `depends_on -> 00001KVZBCQH4`; incoming related `00001KVZSGT14`
- Orchestration plan: blocker record `orch-plan-20260625-164457-1` を追加。
- Queue state: queued は本 Ticket を含む6件。inprogress は `00001KVZBCQH4` 1件。
- Workspace state: orchestration worktree is clean at queue commit; core implementation is under reviewer Worker.
Next action:
- 本 Ticket は queued のまま待機。
- `00001KVZBCQH4` が reviewer approve / merge / validation / done になった後、再 routing する。
Escalate if:
- core の `CreateWorkerRequest` / `ConfigBundleRef` placeholder が bundle sync requirements を満たさない。
- bundle sync のために REST server / FS store / Plugin manager 実装を同時に要求する形になりそうな場合。
---

View File

@ -1 +0,0 @@
{"id":"orch-plan-20260625-163225-1","ticket_id":"00001KVZSGT0Q","kind":"blocked_by","related_ticket":"00001KVZKSV6C","note":"Queue routing checked after Dashboard Queue. Embedded Runtime connection depends on Backend RuntimeRegistry foundation `00001KVZKSV6C`, which is still queued and itself blocked by inprogress worker-runtime core `00001KVZBCQH4`. Do not start this Ticket until the foundation dependency is accepted/completed.","author":"yoi-orchestrator","at":"2026-06-25T16:32:25Z"}

View File

@ -1,13 +0,0 @@
{
"version": 1,
"relations": [
{
"ticket_id": "00001KVZSGT0Q",
"kind": "depends_on",
"target": "00001KVZKSV6C",
"note": "Embedded Runtime connection builds on the Backend RuntimeRegistry foundation.",
"author": "yoi ticket",
"at": "2026-06-25T16:30:00Z"
}
]
}

View File

@ -1,67 +0,0 @@
---
title: 'Backend RuntimeRegistryにembedded worker-runtimeを接続する'
state: 'queued'
created_at: '2026-06-25T16:23:58Z'
updated_at: '2026-06-25T16:32:35Z'
assignee: null
queued_by: 'workspace-panel'
queued_at: '2026-06-25T16:31:30Z'
---
## 背景
`worker-runtime` core crate と Backend `RuntimeRegistry` 基盤ができたら、Workspace Backend process 内に embedded `worker_runtime::Runtime` を組み込み、`backend-internal` Runtime として Registry から扱えるようにしたい。これは Backend internal Companion Web Console の前提であり、remote Runtime process / HTTP client / FS store / event stream server を待たずに進められる。
この Ticket では embedded Runtime handle を Backend Registry に接続する。Runtime は memory store / builtin/default Profile fallback / toolsなし Worker でよい。
## 要件
### Embedded Runtime registration
- Workspace Backend が `worker_runtime::Runtime` を process 内に生成・保持できる。
- Embedded Runtime を `backend-internal` 相当の runtime id / display name / capabilities で RuntimeRegistry に登録できる。
- Registry から embedded Runtime の runtime summary / status / capabilities を取得できる。
- Embedded Runtime は HTTP endpoint / token / socket path を持たない。
### Worker operations
- Backend Registry は embedded Runtime に対して direct lib call で以下を route できる。
- worker list / detail。
- create worker。
- send input。
- stop / cancel。
- bounded transcript projection。
- event cursor / subscription placeholder。
- v0 は toolsなし Worker / builtin/default Profile fallback / memory store でよい。
- Busy / unknown worker / runtime unavailable / unsupported operation を typed error に map する。
### Backend API exposure
- Browser-facing API は embedded Runtime を remote Runtime と同じ `runtime_id + worker_id` authority で扱う。
- Browser は embedded Runtime internals / store path / provider credentials を知らない。
- Existing `/api/workers` / runtime list に embedded Runtime Worker を含めるか、新 runtime-scoped endpoint に出すかを実装時に決め、方針を記録する。
- Local compatibility source と embedded Runtime source を diagnostics / implementation kind で区別できる。
## Non-goals
- Remote Runtime process client。
- FS store。
- REST command server。
- Event stream server。
- Full Companion Web Console UI。
- Profile/config bundle sync。
- Local compatibility path の削除。
## 受け入れ条件
- Workspace Backend が embedded `worker_runtime::Runtime` を生成し、RuntimeRegistry に登録できる。
- Backend API から `backend-internal` Runtime の summary/status/capabilities を確認できる。
- Backend Registry が embedded Runtime の worker list/detail/create/send input/transcript projection を direct lib call で扱える。
- v0 toolsなし Worker が create でき、input acceptance まで確認できる。
- Browser-facing API に socket path / session path / runtime internal store path / provider credential が露出しない。
- Local compatibility source と embedded Runtime source が混同されない。
- Focused workspace-server tests cover embedded runtime registration and routing.
- `cargo test -p yoi-workspace-server` が通る。
- `cargo check -p yoi` が通る。
- `git diff --check` が通る。
- `nix build .#yoi --no-link` が通る。

View File

@ -1,61 +0,0 @@
<!-- event: create author: "yoi ticket" at: 2026-06-25T16:23:58Z -->
## 作成
LocalTicketBackend によって作成されました。
---
<!-- event: intake_summary author: hare at: 2026-06-25T16:30:31Z -->
## Intake summary
Marked ready by `yoi ticket state`.
---
<!-- event: state_changed author: "yoi ticket" at: 2026-06-25T16:30:31Z from: planning to: ready reason: cli_state field: state -->
## State changed
Marked ready by `yoi ticket state`.
---
<!-- event: state_changed author: workspace-panel at: 2026-06-25T16:31:30Z from: ready to: queued reason: queued field: state -->
## State changed
Ticket を `workspace-panel` が queued にしました。
---
<!-- event: decision author: yoi-orchestrator at: 2026-06-25T16:32:35Z -->
## Decision
Routing decision: blocked_by_dependency_or_missing_authority
Reason:
- Dashboard Queue による routing 許可を受けて Ticket / relations / orchestration plan / workspace state を確認した。
- 本 Ticket は `00001KVZKSV6C` (`Backend RuntimeRegistryの基盤をworker-runtime向けに整理する`) に `depends_on` relation を持つ。
- `00001KVZKSV6C` は現在 `queued` で、さらに `00001KVZBCQH4` worker-runtime core が `inprogress` のため blocked と判断済み。
- Embedded Runtime connection は Backend RuntimeRegistry foundation の handle boundary に依存するため、foundation 確定前に implementation side effect を開始しない。
Evidence checked:
- Ticket body: embedded `worker_runtime::Runtime` registration、direct lib call routing、Backend API exposure、Non-goals。
- Relations: outgoing `depends_on -> 00001KVZKSV6C`; incoming dependent `00001KVZ9JGK0`
- Orchestration plan: blocker record `orch-plan-20260625-163225-1` を追加。
- Workspace state: `00001KVZBCQH4` は inprogress、`00001KVZKSV6C` は queued/blocked。
Next action:
- 本 Ticket は queued のまま待機。
- `00001KVZKSV6C` が accepted/completed して Backend Registry foundation が確定した後、再 routing する。
Escalate if:
- Embedded Runtime connection のために `00001KVZKSV6C` の scope/acceptance を変更する必要が出る。
- worker-runtime core API が embedded Backend integration に必要な create/send/projection semantics を満たさない。
---

View File

@ -1,45 +0,0 @@
{
"version": 1,
"relations": [
{
"ticket_id": "00001KVZSGT14",
"kind": "depends_on",
"target": "00001KVZKSV6C",
"note": "Remote Runtime connection builds on the Backend RuntimeRegistry foundation.",
"author": "yoi ticket",
"at": "2026-06-25T16:30:00Z"
},
{
"ticket_id": "00001KVZSGT14",
"kind": "depends_on",
"target": "00001KVZKST83",
"note": "Standalone remote Runtime should have FS persistence available before Backend integration.",
"author": "yoi ticket",
"at": "2026-06-25T16:30:00Z"
},
{
"ticket_id": "00001KVZSGT14",
"kind": "depends_on",
"target": "00001KVZKSTE2",
"note": "Remote Runtime routing needs the REST command API.",
"author": "yoi ticket",
"at": "2026-06-25T16:30:00Z"
},
{
"ticket_id": "00001KVZSGT14",
"kind": "depends_on",
"target": "00001KVZKSTJT",
"note": "Remote Runtime observation needs the Runtime event stream API.",
"author": "yoi ticket",
"at": "2026-06-25T16:30:00Z"
},
{
"ticket_id": "00001KVZSGT14",
"kind": "related",
"target": "00001KVZQHPNY",
"note": "Remote Runtime integration will eventually coordinate Profile/config bundle sync, but v0 can use builtin/default fallback where applicable.",
"author": "yoi ticket",
"at": "2026-06-25T16:30:00Z"
}
]
}

View File

@ -1,71 +0,0 @@
---
title: 'Backend RuntimeRegistryにremote worker-runtime processを接続する'
state: 'ready'
created_at: '2026-06-25T16:23:58Z'
updated_at: '2026-06-25T16:30:32Z'
assignee: null
---
## 背景
Standalone `worker-runtime` process が FS store、REST command server、event stream server を持った後、Workspace Backend は remote Runtime process に client として接続できる必要がある。Browser は remote Runtime に直接接続せず、Backend が RuntimeRegistry / policy / visibility / audit / typed error mapping を挟んで proxy / projection する。
この Ticket では Backend RuntimeRegistry に remote Runtime client handle を追加する。Embedded Runtime 接続とは別実装粒度とする。
## 要件
### Remote Runtime client
- Backend は config-like data から remote Runtime client handle を作成できる。
- runtime id / display name。
- base URL。
- token / secret ref placeholder。
- capability cache / last seen status。
- Remote command は `worker-runtime` REST command API に対する Backend-owned client で実行する。
- Remote observation は Runtime event stream API に対する Backend-owned client で購読または proxy できる。
- Backend は Runtime endpoint / credential を Browser に渡さない。
### Registry routing
- Backend RuntimeRegistry は remote Runtime handle へ以下を route できる。
- runtime summary / status / capabilities。
- worker list / detail。
- create worker。
- send input。
- stop / cancel。
- bounded transcript projection。
- event stream/proxy。
- Embedded Runtime handle と remote Runtime handle は Browser-facing API から同じ `runtime_id + worker_id` authority で扱える。
- Network failure / auth failure / timeout / remote unsupported / remote worker not found を typed error に map する。
### Config / policy boundary
- Backend がどの remote Runtime に接続してよいかを config / registry data で管理する。
- Dynamic registration は不要。
- Config bundle sync は関連するが、この Ticket では remote Runtime connection / routing を主目的とする。
- Browser は remote Runtime base URL / token / direct endpoint authority を知らない。
## Non-goals
- `worker-runtime` core crate implementation。
- FS store implementation。
- REST command server implementation。
- Event stream server implementation。
- Embedded Runtime integration。
- Dynamic Runtime registration。
- Full auth / permission model。
- Backend internal Companion Web Console completion。
## 受け入れ条件
- Workspace Backend が remote Runtime client handle を config-like data から登録できる。
- Backend RuntimeRegistry が remote Runtime の list/detail/create/input/transcript/event operations を route できる。
- Remote network/auth/timeout errors が typed Backend errors に map される。
- Browser-facing API に remote Runtime base URL / credential / direct endpoint が露出しない。
- Embedded Runtime handle と remote Runtime handle が同じ `runtime_id + worker_id` authority model で扱われる。
- Event stream client/proxy path が Backend-owned connection として実装されている。
- Focused workspace-server tests cover mocked remote Runtime routing and error mapping.
- `cargo test -p yoi-workspace-server` が通る。
- `cargo check -p yoi` が通る。
- `git diff --check` が通る。
- `nix build .#yoi --no-link` が通る。

View File

@ -1,24 +0,0 @@
<!-- event: create author: "yoi ticket" at: 2026-06-25T16:23:58Z -->
## 作成
LocalTicketBackend によって作成されました。
---
<!-- event: intake_summary author: hare at: 2026-06-25T16:30:32Z -->
## Intake summary
Marked ready by `yoi ticket state`.
---
<!-- event: state_changed author: "yoi ticket" at: 2026-06-25T16:30:32Z from: planning to: ready reason: cli_state field: state -->
## State changed
Marked ready by `yoi ticket state`.
---

View File

@ -11,12 +11,12 @@
LLM に投げる context への割り込みは、大きく2種類に分かれる。**前者は許されるが、後者は禁止**。
Workerの状態から純粋に再現可能で、且つ揮発性の無い操作であることが望ましい。pruning、tool result の content 切り詰め、prompt cache anchor の付与等)。
Podの状態から純粋に再現可能で、且つ揮発性の無い操作であることが望ましい。pruning、tool result の content 切り詰め、prompt cache anchor の付与等)。
原則として、コンテキストは積み重ねるものであり、一時的にメッセージを差し込むことや、過去のメッセージを改ざんすることはKVキャッシュのヒット率を下げる。
**禁止**: ターンを跨ぐことができない情報に基づいて、history に記録せずに context だけにコンテンツを差し込むこと。これをやると LLM はそれに反応して生成を行う一方、次以降のターンでhistoryに残らないため、「自分がなぜその発言/tool call をしたか」の根拠が消えるうえ、prompt cache のヒット率も低下させることになる。
新しい input を context に乗せたいなら、必ず先に `worker.history` に append して commit すること。`history.json` への永続化はそこから自動的についてくる。Notify / WorkerEvent / `<system-reminder>` 系はこの原則で扱う。
新しい input を context に乗せたいなら、必ず先に `worker.history` に append して commit すること。`history.json` への永続化はそこから自動的についてくる。Notify / PodEvent / `<system-reminder>` 系はこの原則で扱う。
また、キャッシュを破壊するタイミングは正確にコントロールされる必要があり、キャッシュ破壊とトークン消費のトレードオフに基づいて慎重に設計されるべきである。
---

94
Cargo.lock generated
View File

@ -2873,6 +2873,52 @@ version = "0.2.3"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "b4596b6d070b27117e987119b4dac604f3c58cfb0b191112e24771b2faeac1a6"
[[package]]
name = "pod"
version = "0.1.0"
dependencies = [
"arc-swap",
"async-trait",
"chrono",
"clap",
"client",
"dotenv",
"fs4",
"futures",
"futures-util",
"include_dir",
"libc",
"llm-engine",
"manifest",
"mcp",
"memory",
"minijinja",
"pod-registry",
"pod-store",
"protocol",
"provider",
"reqwest",
"schemars",
"serde",
"serde_json",
"session-metrics",
"session-store",
"tempfile",
"thiserror 2.0.18",
"ticket",
"tokio",
"tokio-tungstenite",
"toml",
"tools",
"tracing",
"tungstenite",
"uuid",
"wasmtime",
"wat",
"workflow",
"yoi-plugin-pdk",
]
[[package]]
name = "pod-registry"
version = "0.1.0"
@ -5855,52 +5901,6 @@ dependencies = [
"wasmparser 0.248.0",
]
[[package]]
name = "worker"
version = "0.1.0"
dependencies = [
"arc-swap",
"async-trait",
"chrono",
"clap",
"client",
"dotenv",
"fs4",
"futures",
"futures-util",
"include_dir",
"libc",
"llm-engine",
"manifest",
"mcp",
"memory",
"minijinja",
"pod-registry",
"pod-store",
"protocol",
"provider",
"reqwest",
"schemars",
"serde",
"serde_json",
"session-metrics",
"session-store",
"tempfile",
"thiserror 2.0.18",
"ticket",
"tokio",
"tokio-tungstenite",
"toml",
"tools",
"tracing",
"tungstenite",
"uuid",
"wasmtime",
"wat",
"workflow",
"yoi-plugin-pdk",
]
[[package]]
name = "workflow"
version = "0.1.0"
@ -5942,6 +5942,7 @@ dependencies = [
"client",
"manifest",
"memory",
"pod",
"pod-store",
"project-record",
"serde",
@ -5953,7 +5954,6 @@ dependencies = [
"ticket",
"tokio",
"tui",
"worker",
]
[[package]]

View File

@ -8,7 +8,7 @@ members = [
"crates/secrets",
"crates/manifest",
"crates/mcp",
"crates/worker",
"crates/pod",
"crates/plugin-pdk",
"crates/yoi",
"crates/pod-store",
@ -35,7 +35,7 @@ default-members = [
"crates/secrets",
"crates/manifest",
"crates/mcp",
"crates/worker",
"crates/pod",
"crates/plugin-pdk",
"crates/yoi",
"crates/pod-store",
@ -69,7 +69,7 @@ lint-common = { path = "crates/lint-common" }
memory = { path = "crates/memory" }
ticket = { path = "crates/ticket" }
project-record = { path = "crates/project-record" }
worker = { path = "crates/worker" }
pod = { path = "crates/pod" }
yoi-plugin-pdk = { path = "crates/plugin-pdk" }
yoi = { path = "crates/yoi" }
pod-registry = { path = "crates/pod-registry" }

View File

@ -2,7 +2,7 @@
Ticket を切るほどではないが、次に近所を触るときに合わせて拾いたい小粒な所見の置き場。
- `crates/worker/src/controller.rs:1453-1461` — `worker_error_code``WorkerError::WorkflowResolve(_) => InvalidRequest` が post-commit な resolve エラー (`KnowledgeNotFound` 等) にも適用される。意味論的には妥当方向だが、resolve 系のエラー粒度を分けたくなったタイミングで再評価。
- `crates/pod/src/controller.rs:1269-1278` — `worker_error_code``PodError::WorkflowResolve(_) => InvalidRequest` が post-commit な resolve エラー (`KnowledgeNotFound` 等) にも適用される。意味論的には妥当方向だが、resolve 系のエラー粒度を分けたくなったタイミングで再評価。
- `crates/session-store/src/fs_store.rs:200-210``FsStore::read_entry_count``fs::read_to_string` で全文ロードしてから行数カウントするため O(n)。`ensure_head_or_fork` は run-start でしか呼ばれず現状は許容範囲だが、長期セッションが普通になった時点で `\n` バイト数の cheap count か末尾 seek に置き換える。
- `crates/session-store/src/segment.rs:143-172` `ensure_head_or_fork` (free fn, test 専用・本番 caller ゼロ) と `crates/worker/src/worker.rs:2032` `Worker::ensure_segment_head` (本番 inline) に live auto-fork の検知 + forked_from 記録が二重実装されている。entry-hash-abolish 以前からの重複で、両方独立にテスト済みだが drift 必至。session-store 側を本番から呼ぶ形に寄せるか free fn を畳むかは要設計判断。Worker state / fork 周辺を次に触るときに統合を検討。
- `crates/worker/src/worker.rs` / `crates/worker/src/spawn/registry.rs:84-174` — restore 時の spawned child prune/reclaim が Worker restore path と spawned registry load path の両方に残っている。現状は安全側の重複チェックだが、Worker state / spawned registry 周辺を次に触るときに責務境界を再整理。
- `crates/session-store/src/segment.rs:143-172` `ensure_head_or_fork` (free fn, test 専用・本番 caller ゼロ) と `crates/pod/src/pod.rs:1941-2006` `Pod::ensure_segment_head` (本番 inline) に live auto-fork の検知 + forked_from 記録が二重実装されている。entry-hash-abolish 以前からの重複で、両方独立にテスト済みだが drift 必至。session-store 側を本番から呼ぶ形に寄せるか free fn を畳むかは要設計判断。Pod state / fork 周辺を次に触るときに統合を検討。
- `crates/pod/src/pod.rs:4100-4147` / `crates/pod/src/spawn/registry.rs:84-174` — restore 時の spawned child prune/reclaim が Pod restore path と spawned registry load path の両方に残っている。現状は安全側の重複チェックだが、Pod state / spawned registry 周辺を次に触るときに責務境界を再整理。

View File

@ -1,19 +1,19 @@
# 夜居 / Yoi agent
Yoi is an agent runtime for building, running, and orchestrating LLM Workers while preserving explicit history, scoped capabilities, and developer-controlled workflows.
Yoi is an agent runtime for building, running, and orchestrating LLM Pods while preserving explicit history, scoped capabilities, and developer-controlled workflows.
## 1. Yoi agent
Yoi focuses on long-running agent operation rather than one-off prompt execution. A named Worker can keep durable session history, run with explicit tool and filesystem authority, delegate bounded work to child Workers, and be inspected or restored through CLI/TUI surfaces.
Yoi focuses on long-running agent operation rather than one-off prompt execution. A named Pod can keep durable session history, run with explicit tool and filesystem authority, delegate bounded work to child Pods, and be inspected or restored through CLI/TUI surfaces.
Main highlights:
- Named long-running **Workers** with durable session and metadata records.
- Named long-running **Pods** with durable session and metadata records.
- Explicit tool permissions and filesystem scopes.
- Multi-agent orchestration with scoped coder/reviewer Workers.
- Multi-agent orchestration with scoped coder/reviewer Pods.
- Profile, Manifest, and prompt-based runtime configuration.
- Local Tickets and workflow files for auditable project coordination.
- TUI and CLI entry points, including the `yoi panel` workspace Dashboard and single-Worker Console.
- TUI and CLI entry points, including the `yoi panel` workspace Dashboard and single-Pod Console.
Yoi is actively dogfooded in this repository. Public APIs, configuration formats, and workflows may still change.
@ -39,14 +39,14 @@ nix build .#yoi
yoi --help
yoi
yoi panel
yoi --worker <name>
yoi worker --help
yoi --pod <name>
yoi pod --help
```
Typical flow:
1. Configure providers, models, profiles, prompts, and scopes.
2. Start or attach to a named Worker in the Console, or inspect workspace activity in the Dashboard.
2. Start or attach to a named Pod in the Console, or inspect workspace activity in the Dashboard.
3. Use explicit tools and scoped delegation for multi-agent work.
4. Record project work through Tickets, workflow files, and git history.
@ -60,7 +60,7 @@ Key docs:
- [`docs/design/overview.md`](docs/design/overview.md) — architecture and crate ownership map.
- [`docs/design/context-history.md`](docs/design/context-history.md) — history/context invariants.
- [`docs/design/worker-session-state.md`](docs/design/worker-session-state.md) — Worker identity, metadata, and session logs.
- [`docs/design/pod-session-state.md`](docs/design/pod-session-state.md) — Pod identity, metadata, and session logs.
- [`docs/design/profiles-manifests-prompts.md`](docs/design/profiles-manifests-prompts.md) — Profiles, Manifests, and prompt resources.
- [`docs/design/tool-permissions-scope.md`](docs/design/tool-permissions-scope.md) — tool policy and filesystem scope.
- [`docs/development/work-items.md`](docs/development/work-items.md) — Ticket workflow and project records.

View File

@ -2,13 +2,13 @@
## Role
`client` contains reusable socket-client and runtime-command mechanics for talking to Workers from CLI/TUI code.
`client` contains reusable socket-client and runtime-command mechanics for talking to Pods from CLI/TUI code.
## Boundaries
Owns:
- one-shot Worker socket client behavior
- one-shot Pod socket client behavior
- request/reply delivery mechanics
- runtime command construction below the product façade
- shared attach/status probing helpers used by higher layers
@ -16,15 +16,15 @@ Owns:
Does not own:
- product command names (`yoi`)
- Worker state authority (`worker`, `pod-store`, `session-store`)
- Pod state authority (`pod`, `pod-store`, `session-store`)
- UI rendering (`tui`)
- Engine turn semantics (`llm-engine`)
## Design notes
The client boundary lets `tui` and `yoi` share Worker communication without making library crates depend on the product binary. Socket clients should drain connect-time snapshot/alert traffic before sending a method or deciding status.
The client boundary lets `tui` and `yoi` share Pod communication without making library crates depend on the product binary. Socket clients should drain connect-time snapshot/alert traffic before sending a method or deciding status.
## See also
- [`../../docs/design/worker-session-state.md`](../../docs/design/worker-session-state.md)
- [`../../docs/design/pod-session-state.md`](../../docs/design/pod-session-state.md)
- [`../../docs/design/overview.md`](../../docs/design/overview.md)

View File

@ -1,28 +1,28 @@
//! Worker プロトコルを喋るクライアント。
//! Pod プロトコルを喋るクライアント。
//!
//! - [`WorkerClient`]: 既存 worker の Unix ソケットへ接続して `Method` を送り、
//! - [`PodClient`]: 既存 pod の Unix ソケットへ接続して `Method` を送り、
//! `Event` を受け取る低レベル接続。
//! - [`spawn`]: worker バイナリをサブプロセスとして起動し、`YOI-READY`
//! - [`spawn`]: pod バイナリをサブプロセスとして起動し、`YOI-READY`
//! ハンドシェイクが終わるまで待つフロー。subprocess を立ち上げる必要が
//! ない呼び出し側 (=既存 worker に attach する場合) は使わなくてよい。
//! ない呼び出し側 (=既存 pod に attach する場合) は使わなくてよい。
//!
//! TUI / GUI / E2E ハーネスはこの crate に依存して protocol を喋る。
mod pod_client;
pub mod runtime_command;
pub mod spawn;
pub mod ticket_role;
mod worker_client;
pub use runtime_command::WorkerRuntimeCommand;
pub use runtime_command::PodRuntimeCommand;
pub use pod_client::PodClient;
pub use spawn::{
SpawnConfig, SpawnError, SpawnReady, WorkerProcessLaunchConfig, WorkerProcessLaunchOptions,
spawn_worker, spawn_worker_with_options,
PodProcessLaunchConfig, PodProcessLaunchOptions, SpawnConfig, SpawnError, SpawnReady,
spawn_pod, spawn_pod_with_options,
};
pub use ticket_role::{
TicketRef, TicketRoleLaunchContext, TicketRoleLaunchError, TicketRoleLaunchOptions,
TicketRoleLaunchPlan, TicketRoleLaunchResult, TicketRolePreRunWarning,
launch_ticket_role_worker, launch_ticket_role_worker_with_options, plan_ticket_role_launch,
TicketRoleLaunchPlan, TicketRoleLaunchResult, TicketRolePreRunWarning, launch_ticket_role_pod,
launch_ticket_role_pod_with_options, plan_ticket_role_launch,
plan_ticket_role_launch_with_config,
};
pub use worker_client::WorkerClient;

View File

@ -7,13 +7,13 @@ use tokio::net::UnixStream;
use tokio::sync::mpsc;
use tokio::task::JoinHandle;
pub struct WorkerClient {
pub struct PodClient {
writer: JsonLineWriter<tokio::io::WriteHalf<UnixStream>>,
event_rx: mpsc::Receiver<Event>,
reader_task: JoinHandle<()>,
}
impl WorkerClient {
impl PodClient {
pub async fn connect(path: &Path) -> Result<Self, io::Error> {
let stream = UnixStream::connect(path).await?;
let (reader, writer) = tokio::io::split(stream);
@ -50,7 +50,7 @@ impl WorkerClient {
}
}
impl Drop for WorkerClient {
impl Drop for PodClient {
fn drop(&mut self) {
self.reader_task.abort();
}
@ -61,7 +61,7 @@ mod tests {
use std::io::ErrorKind;
use std::time::Duration;
use protocol::{Segment, WorkerStatus};
use protocol::{PodStatus, Segment};
use tempfile::tempdir;
use tokio::io::{AsyncReadExt, AsyncWriteExt};
use tokio::net::UnixListener;
@ -91,13 +91,13 @@ mod tests {
let mut writer = JsonLineWriter::new(stream);
writer
.write(&Event::Status {
status: WorkerStatus::Idle,
status: PodStatus::Idle,
})
.await
.unwrap();
});
let mut client = WorkerClient::connect(&socket_path).await.unwrap();
let mut client = PodClient::connect(&socket_path).await.unwrap();
let event = tokio::time::timeout(Duration::from_secs(1), client.next_event())
.await
@ -105,7 +105,7 @@ mod tests {
assert!(matches!(
event,
Some(Event::Status {
status: WorkerStatus::Idle
status: PodStatus::Idle
})
));
server.await.unwrap();
@ -122,7 +122,7 @@ mod tests {
reader.next::<Method>().await.unwrap()
});
let mut client = WorkerClient::connect(&socket_path).await.unwrap();
let mut client = PodClient::connect(&socket_path).await.unwrap();
let method = Method::Run {
input: vec![Segment::text("hello")],
};
@ -155,7 +155,7 @@ mod tests {
});
for _ in 0..16 {
let client = WorkerClient::connect(&socket_path).await.unwrap();
let client = PodClient::connect(&socket_path).await.unwrap();
drop(client);
}
@ -177,7 +177,7 @@ mod tests {
.await;
});
let client = WorkerClient::connect(&socket_path).await.unwrap();
let client = PodClient::connect(&socket_path).await.unwrap();
tokio::task::yield_now().await;
drop(client);

View File

@ -6,12 +6,12 @@ use std::path::{Path, PathBuf};
const POD_RUNTIME_COMMAND_ENV: &str = "YOI_POD_RUNTIME_COMMAND";
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct WorkerRuntimeCommand {
pub struct PodRuntimeCommand {
pub program: PathBuf,
pub prefix_args: Vec<OsString>,
}
impl WorkerRuntimeCommand {
impl PodRuntimeCommand {
pub fn new(program: impl Into<PathBuf>, prefix_args: Vec<OsString>) -> Self {
Self {
program: program.into(),
@ -24,15 +24,15 @@ impl WorkerRuntimeCommand {
}
pub fn for_executable(program: impl Into<PathBuf>) -> Self {
Self::new(program, vec![OsString::from("worker")])
Self::new(program, vec![OsString::from("pod")])
}
/// Resolve the Worker runtime command used for subprocess launches.
/// Resolve the Pod runtime command used for subprocess launches.
///
/// The default launch path is always the current `yoi` executable plus
/// the unified `worker` prefix argument. During development, a non-empty
/// the unified `pod` prefix argument. During development, a non-empty
/// `YOI_POD_RUNTIME_COMMAND` value replaces only the executable path;
/// the `worker` prefix is still added here and the env value is not parsed as a
/// the `pod` prefix is still added here and the env value is not parsed as a
/// shell command.
pub fn resolve() -> io::Result<Self> {
Self::resolve_from_env_value(
@ -74,7 +74,7 @@ impl WorkerRuntimeCommand {
}
}
impl fmt::Display for WorkerRuntimeCommand {
impl fmt::Display for PodRuntimeCommand {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(f, "{}", self.program.display())?;
for arg in &self.prefix_args {
@ -89,14 +89,14 @@ mod tests {
use super::*;
#[test]
fn yoi_binary_defaults_to_worker_prefix() {
let command = WorkerRuntimeCommand::for_executable("/opt/yoi/bin/yoi");
fn yoi_binary_defaults_to_pod_prefix() {
let command = PodRuntimeCommand::for_executable("/opt/yoi/bin/yoi");
assert_eq!(command.program(), Path::new("/opt/yoi/bin/yoi"));
assert_eq!(command.prefix_args(), [OsString::from("worker")]);
assert_eq!(command.prefix_args(), [OsString::from("pod")]);
assert_eq!(
command.argv_with(["--worker", "agent"]),
vec!["worker", "--worker", "agent"]
command.argv_with(["--pod", "agent"]),
vec!["pod", "--pod", "agent"]
.into_iter()
.map(OsString::from)
.collect::<Vec<_>>()
@ -104,14 +104,14 @@ mod tests {
}
#[test]
fn any_runtime_executable_gets_worker_prefix() {
let command = WorkerRuntimeCommand::for_executable("/opt/yoi/bin/custom-runtime");
fn any_runtime_executable_gets_pod_prefix() {
let command = PodRuntimeCommand::for_executable("/opt/yoi/bin/custom-runtime");
assert_eq!(command.program(), Path::new("/opt/yoi/bin/custom-runtime"));
assert_eq!(command.prefix_args(), [OsString::from("worker")]);
assert_eq!(command.prefix_args(), [OsString::from("pod")]);
assert_eq!(
command.argv_with(["--worker", "agent"]),
vec!["worker", "--worker", "agent"]
command.argv_with(["--pod", "agent"]),
vec!["pod", "--pod", "agent"]
.into_iter()
.map(OsString::from)
.collect::<Vec<_>>()
@ -120,43 +120,43 @@ mod tests {
#[test]
fn resolve_uses_current_exe_when_override_is_unset() {
let command = WorkerRuntimeCommand::resolve_from_env_value(None, || {
let command = PodRuntimeCommand::resolve_from_env_value(None, || {
Ok(PathBuf::from("/opt/yoi/bin/yoi"))
})
.unwrap();
assert_eq!(
command,
WorkerRuntimeCommand::for_executable("/opt/yoi/bin/yoi")
PodRuntimeCommand::for_executable("/opt/yoi/bin/yoi")
);
}
#[test]
fn resolve_uses_current_exe_when_override_is_empty() {
let command = WorkerRuntimeCommand::resolve_from_env_value(Some(OsString::new()), || {
let command = PodRuntimeCommand::resolve_from_env_value(Some(OsString::new()), || {
Ok(PathBuf::from("/opt/yoi/bin/yoi"))
})
.unwrap();
assert_eq!(
command,
WorkerRuntimeCommand::for_executable("/opt/yoi/bin/yoi")
PodRuntimeCommand::for_executable("/opt/yoi/bin/yoi")
);
}
#[test]
fn resolve_override_replaces_only_program_and_keeps_worker_prefix() {
let command = WorkerRuntimeCommand::resolve_from_env_value(
fn resolve_override_replaces_only_program_and_keeps_pod_prefix() {
let command = PodRuntimeCommand::resolve_from_env_value(
Some(OsString::from("/tmp/rebuilt yoi")),
|| panic!("override must not inspect current_exe"),
)
.unwrap();
assert_eq!(command.program(), Path::new("/tmp/rebuilt yoi"));
assert_eq!(command.prefix_args(), [OsString::from("worker")]);
assert_eq!(command.prefix_args(), [OsString::from("pod")]);
assert_eq!(
command.argv_with(["--worker", "agent"]),
vec!["worker", "--worker", "agent"]
command.argv_with(["--pod", "agent"]),
vec!["pod", "--pod", "agent"]
.into_iter()
.map(OsString::from)
.collect::<Vec<_>>()

View File

@ -1,13 +1,13 @@
//! Worker runtime command をサブプロセスとして立ち上げ、`YOI-READY` を待つ
//! Pod runtime command をサブプロセスとして立ち上げ、`YOI-READY` を待つ
//! ハンドシェイク。
//!
//! - 親プロセス (TUI / GUI / E2E) は profile/default/typed restore flags を
//! 指定してこの関数に渡す。worker はそれを受けて socket を bind し、stderr に
//! 指定してこの関数に渡す。pod はそれを受けて socket を bind し、stderr に
//! `YOI-READY\t<name>\t<socket>` を吐く。
//! - 待機中の stderr 行は `progress` コールバック越しに呼び出し側へ流す。
//! UI の進捗表示や E2E のログ収集はここで賄う。
//! - `kill_on_drop = false` + `process_group(0)` により、親プロセス
//! ライフサイクルから切り離した detached worker を作る。ready 後の lifecycle
//! ライフサイクルから切り離した detached pod を作る。ready 後の lifecycle
//! 管理は runtime ディレクトリ / socket を介して行う。
use std::io;
@ -15,7 +15,7 @@ use std::path::{Path, PathBuf};
use std::process::Stdio;
use std::time::Duration;
use crate::WorkerRuntimeCommand;
use crate::PodRuntimeCommand;
use tokio::process::Command;
use uuid::Uuid;
@ -23,14 +23,14 @@ const READY_PREFIX: &str = "YOI-READY\t";
const READY_TIMEOUT: Duration = Duration::from_secs(20);
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct WorkerProcessLaunchConfig {
pub runtime_command: WorkerRuntimeCommand,
/// `worker.name` として使う識別子。runtime ディレクトリ
/// (`manifest::paths::worker_runtime_dir`) の解決と、ready 行に乗る
pub struct PodProcessLaunchConfig {
pub runtime_command: PodRuntimeCommand,
/// `pod.name` として使う識別子。runtime ディレクトリ
/// (`manifest::paths::pod_runtime_dir`) の解決と、ready 行に乗る
/// 名前との突き合わせに使う。
pub worker_name: String,
/// Optional reusable Profile selector. Worker identity is always supplied
/// separately with `--worker`; profile selection must not imply a name.
pub pod_name: String,
/// Optional reusable Profile selector. Pod identity is always supplied
/// separately with `--pod`; profile selection must not imply a name.
pub profile: Option<String>,
/// Explicit runtime workspace root. The child receives it via
/// `--workspace` so startup does not infer workspace identity from the
@ -46,7 +46,7 @@ pub struct WorkerProcessLaunchConfig {
}
#[derive(Debug, Clone, PartialEq, Eq, Default)]
pub struct WorkerProcessLaunchOptions {
pub struct PodProcessLaunchOptions {
/// Extra child CLI arguments supplied by an upper resolver layer. The
/// low-level launch config intentionally does not model Ticket IDs,
/// Ticket roles, orchestration roles, executable authority, or raw
@ -54,7 +54,7 @@ pub struct WorkerProcessLaunchOptions {
pub extra_args: Vec<String>,
}
impl WorkerProcessLaunchOptions {
impl PodProcessLaunchOptions {
pub fn with_hidden_arg(mut self, name: impl Into<String>, value: impl Into<String>) -> Self {
self.extra_args.extend([name.into(), value.into()]);
self
@ -65,11 +65,11 @@ impl WorkerProcessLaunchOptions {
}
}
pub type SpawnConfig = WorkerProcessLaunchConfig;
pub type SpawnConfig = PodProcessLaunchConfig;
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct SpawnReady {
pub worker_name: String,
pub pod_name: String,
pub socket_path: PathBuf,
}
@ -78,11 +78,11 @@ pub enum SpawnError {
Io(io::Error),
/// runtime ディレクトリが解決できなかった (環境変数未設定等)。
RuntimeDirUnavailable,
WorkerLaunchFailed {
command: WorkerRuntimeCommand,
PodLaunchFailed {
command: PodRuntimeCommand,
source: io::Error,
},
WorkerExitedEarly {
PodExitedEarly {
stderr_tail: String,
},
Timeout,
@ -96,20 +96,20 @@ impl std::fmt::Display for SpawnError {
f,
"could not resolve runtime directory (set YOI_HOME, YOI_RUNTIME_DIR, XDG_RUNTIME_DIR, or HOME)"
),
Self::WorkerLaunchFailed { command, source } => write!(
Self::PodLaunchFailed { command, source } => write!(
f,
"failed to launch worker runtime command `{command}`: {source}"
"failed to launch pod runtime command `{command}`: {source}"
),
Self::WorkerExitedEarly { stderr_tail } => {
Self::PodExitedEarly { stderr_tail } => {
if stderr_tail.is_empty() {
write!(f, "worker exited before becoming ready")
write!(f, "pod exited before becoming ready")
} else {
write!(f, "worker exited before becoming ready: {stderr_tail}")
write!(f, "pod exited before becoming ready: {stderr_tail}")
}
}
Self::Timeout => write!(
f,
"worker did not become ready within {}s",
"pod did not become ready within {}s",
READY_TIMEOUT.as_secs()
),
}
@ -119,8 +119,8 @@ impl std::fmt::Display for SpawnError {
impl std::error::Error for SpawnError {
fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
match self {
Self::Io(error) | Self::WorkerLaunchFailed { source: error, .. } => Some(error),
Self::RuntimeDirUnavailable | Self::WorkerExitedEarly { .. } | Self::Timeout => None,
Self::Io(error) | Self::PodLaunchFailed { source: error, .. } => Some(error),
Self::RuntimeDirUnavailable | Self::PodExitedEarly { .. } | Self::Timeout => None,
}
}
}
@ -131,10 +131,7 @@ impl From<io::Error> for SpawnError {
}
}
fn runtime_args(
config: &WorkerProcessLaunchConfig,
options: &WorkerProcessLaunchOptions,
) -> Vec<String> {
fn runtime_args(config: &PodProcessLaunchConfig, options: &PodProcessLaunchOptions) -> Vec<String> {
let mut args = vec![
"--workspace".to_string(),
config.workspace_root.display().to_string(),
@ -143,11 +140,11 @@ fn runtime_args(
args.extend([
"--session".to_string(),
id.to_string(),
"--worker".to_string(),
config.worker_name.clone(),
"--pod".to_string(),
config.pod_name.clone(),
]);
} else {
args.extend(["--worker".to_string(), config.worker_name.clone()]);
args.extend(["--pod".to_string(), config.pod_name.clone()]);
if let Some(profile) = &config.profile {
args.extend(["--profile".to_string(), profile.clone()]);
}
@ -156,32 +153,32 @@ fn runtime_args(
args
}
/// worker を spawn し、`YOI-READY` ハンドシェイクが終わるまで待つ。
/// pod を spawn し、`YOI-READY` ハンドシェイクが終わるまで待つ。
///
/// `progress` は ready 行を見つけるまでに観測した stderr の各行で呼ばれる
/// (ready 行自体は除外される)。UI の表示更新や E2E ログ取得に使う。
pub async fn spawn_worker<F>(
config: WorkerProcessLaunchConfig,
pub async fn spawn_pod<F>(
config: PodProcessLaunchConfig,
progress: F,
) -> Result<SpawnReady, SpawnError>
where
F: FnMut(&str),
{
spawn_worker_with_options(config, WorkerProcessLaunchOptions::default(), progress).await
spawn_pod_with_options(config, PodProcessLaunchOptions::default(), progress).await
}
pub async fn spawn_worker_with_options<F>(
config: WorkerProcessLaunchConfig,
options: WorkerProcessLaunchOptions,
pub async fn spawn_pod_with_options<F>(
config: PodProcessLaunchConfig,
options: PodProcessLaunchOptions,
mut progress: F,
) -> Result<SpawnReady, SpawnError>
where
F: FnMut(&str),
{
let worker_runtime_dir = manifest::paths::worker_runtime_dir(&config.worker_name)
let pod_runtime_dir = manifest::paths::pod_runtime_dir(&config.pod_name)
.ok_or(SpawnError::RuntimeDirUnavailable)?;
std::fs::create_dir_all(&worker_runtime_dir).map_err(SpawnError::Io)?;
let stderr_path = worker_runtime_dir.join("stderr.log");
std::fs::create_dir_all(&pod_runtime_dir).map_err(SpawnError::Io)?;
let stderr_path = pod_runtime_dir.join("stderr.log");
let stderr_file = std::fs::File::create(&stderr_path).map_err(SpawnError::Io)?;
let mut command = Command::new(config.runtime_command.program());
@ -197,15 +194,15 @@ where
}
let mut child = command
.spawn()
.map_err(|source| SpawnError::WorkerLaunchFailed {
.map_err(|source| SpawnError::PodLaunchFailed {
command: config.runtime_command.clone(),
source,
})?;
// Default `kill_on_drop = false` plus `process_group(0)` makes this
// a detached Worker once startup succeeds: dropping the handle does not
// a detached Pod once startup succeeds: dropping the handle does not
// terminate it, and terminal-generated signals for the parent's
// process group do not hit the Worker. Runtime state/socket files are
// process group do not hit the Pod. Runtime state/socket files are
// the source of truth after that point.
let ready = match wait_for_ready_file(&mut progress, &stderr_path, &mut child).await {
Ok(ready) => ready,
@ -243,10 +240,10 @@ where
for line in content[offset..].lines() {
if let Some(rest) = line.strip_prefix(READY_PREFIX) {
let mut parts = rest.splitn(2, '\t');
let worker_name = parts.next().unwrap_or("").to_string();
let pod_name = parts.next().unwrap_or("").to_string();
let socket_str = parts.next().unwrap_or("").to_string();
if worker_name.is_empty() || socket_str.is_empty() {
return Err(SpawnError::WorkerExitedEarly {
if pod_name.is_empty() || socket_str.is_empty() {
return Err(SpawnError::PodExitedEarly {
stderr_tail: format!("malformed ready line: {line}"),
});
}
@ -261,7 +258,7 @@ where
)
.await?;
return Ok(SpawnReady {
worker_name,
pod_name,
socket_path,
});
}
@ -277,11 +274,11 @@ where
tokio::select! {
status = child.wait() => {
let _ = status;
// Worker は exit 直前に最終 stderr 行を flush することがある。
// Pod は exit 直前に最終 stderr 行を flush することがある。
// child.wait() が解決した後に再読みして、原因行を取りこ
// ぼさず WorkerExitedEarly に載せる。
// ぼさず PodExitedEarly に載せる。
drain_stderr_into_tail(stderr_path, &mut tail, &mut offset).await;
return Err(SpawnError::WorkerExitedEarly {
return Err(SpawnError::PodExitedEarly {
stderr_tail: tail.into_string(),
});
}
@ -313,7 +310,7 @@ async fn wait_for_socket(
status = child.wait() => {
let _ = status;
drain_stderr_into_tail(stderr_path, tail, offset).await;
return Err(SpawnError::WorkerExitedEarly {
return Err(SpawnError::PodExitedEarly {
stderr_tail: tail.as_string(),
});
}
@ -366,10 +363,10 @@ mod tests {
use super::*;
use std::ffi::OsString;
fn base_config() -> WorkerProcessLaunchConfig {
WorkerProcessLaunchConfig {
runtime_command: WorkerRuntimeCommand::new("/bin/yoi", vec![OsString::from("worker")]),
worker_name: "explicit-worker".to_string(),
fn base_config() -> PodProcessLaunchConfig {
PodProcessLaunchConfig {
runtime_command: PodRuntimeCommand::new("/bin/yoi", vec![OsString::from("pod")]),
pod_name: "explicit-pod".to_string(),
profile: Some("project:companion".to_string()),
workspace_root: PathBuf::from("/work/other-project"),
cwd: None,
@ -378,14 +375,14 @@ mod tests {
}
#[test]
fn runtime_args_keep_workspace_worker_and_profile_separate() {
fn runtime_args_keep_workspace_pod_and_profile_separate() {
assert_eq!(
runtime_args(&base_config(), &WorkerProcessLaunchOptions::default()),
runtime_args(&base_config(), &PodProcessLaunchOptions::default()),
vec![
"--workspace",
"/work/other-project",
"--worker",
"explicit-worker",
"--pod",
"explicit-pod",
"--profile",
"project:companion",
]
@ -397,14 +394,14 @@ mod tests {
let mut config = base_config();
config.resume_from = Some(Uuid::nil());
assert_eq!(
runtime_args(&config, &WorkerProcessLaunchOptions::default()),
runtime_args(&config, &PodProcessLaunchOptions::default()),
vec![
"--workspace",
"/work/other-project",
"--session",
"00000000-0000-0000-0000-000000000000",
"--worker",
"explicit-worker",
"--pod",
"explicit-pod",
]
);
}
@ -417,14 +414,14 @@ mod tests {
assert_eq!(
runtime_args(
&config,
&WorkerProcessLaunchOptions::default()
&PodProcessLaunchOptions::default()
.with_hidden_arg("--ticket-role", "orchestrator"),
),
vec![
"--workspace",
"/work/other-project",
"--worker",
"explicit-worker",
"--pod",
"explicit-pod",
"--profile",
"project:companion",
"--ticket-role",

View File

@ -1,8 +1,8 @@
//! Ticket-role Worker launch planning and execution.
//! Ticket-role Pod launch planning and execution.
//!
//! This module keeps Ticket role configuration, generated first-run input, and
//! host-side Worker spawning behind the `client` crate so UI callers do not need to
//! depend on `worker` internals.
//! host-side Pod spawning behind the `client` crate so UI callers do not need to
//! depend on `pod` internals.
use std::io;
use std::path::{Path, PathBuf};
@ -15,8 +15,8 @@ pub use ticket::config::TicketRole;
use ticket::config::{TicketConfig, TicketConfigError, TicketRoleLaunchConfigError};
use crate::{
SpawnError, SpawnReady, WorkerClient, WorkerProcessLaunchConfig, WorkerProcessLaunchOptions,
WorkerRuntimeCommand, spawn_worker_with_options,
PodClient, PodProcessLaunchConfig, PodProcessLaunchOptions, PodRuntimeCommand, SpawnError,
SpawnReady, spawn_pod_with_options,
};
const MAX_FIELD_CHARS: usize = 8_000;
@ -37,7 +37,7 @@ impl TicketRef {
}
}
fn worker_name_seed(&self) -> Option<&str> {
fn pod_name_seed(&self) -> Option<&str> {
non_empty(self.id.as_deref())
}
@ -55,17 +55,14 @@ impl TicketRef {
/// Auditable panel handoff target included in a Ticket Intake launch.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct TicketIntakeHandoff {
pub workspace_orchestrator_worker: String,
pub orchestrator_pod: String,
pub workspace_label: String,
}
impl TicketIntakeHandoff {
pub fn new(
workspace_orchestrator_worker: impl Into<String>,
workspace_label: impl Into<String>,
) -> Self {
pub fn new(orchestrator_pod: impl Into<String>, workspace_label: impl Into<String>) -> Self {
Self {
workspace_orchestrator_worker: workspace_orchestrator_worker.into(),
orchestrator_pod: orchestrator_pod.into(),
workspace_label: workspace_label.into(),
}
}
@ -73,11 +70,7 @@ impl TicketIntakeHandoff {
fn append_submit_lines(&self, out: &mut String) {
out.push_str("\nPanel handoff:\n");
push_bounded_bullet(out, "workspace", &self.workspace_label);
push_bounded_bullet(
out,
"workspace_workspace_orchestrator_worker",
&self.workspace_orchestrator_worker,
);
push_bounded_bullet(out, "workspace_orchestrator_pod", &self.orchestrator_pod);
}
}
@ -89,7 +82,7 @@ pub struct TicketRoleLaunchContext {
pub original_workspace_root: Option<PathBuf>,
pub target_workspace_root: Option<PathBuf>,
pub role: TicketRole,
pub worker_name: Option<String>,
pub pod_name: Option<String>,
pub ticket: Option<TicketRef>,
pub user_instruction: Option<String>,
pub intake_handoff: Option<TicketIntakeHandoff>,
@ -109,7 +102,7 @@ impl TicketRoleLaunchContext {
original_workspace_root: None,
target_workspace_root: None,
role,
worker_name: None,
pod_name: None,
ticket: None,
user_instruction: None,
intake_handoff: None,
@ -163,7 +156,7 @@ pub struct TicketRoleLaunchPlan {
pub target_workspace_root: PathBuf,
pub implementation_worktree_root: PathBuf,
pub role: TicketRole,
pub worker_name: String,
pub pod_name: String,
pub profile: String,
pub workflow: String,
pub launch_prompt_ref: Option<String>,
@ -179,14 +172,14 @@ impl TicketRoleLaunchPlan {
pub fn spawn_config(
&self,
runtime_command: WorkerRuntimeCommand,
) -> Result<WorkerProcessLaunchConfig, TicketRoleLaunchError> {
runtime_command: PodRuntimeCommand,
) -> Result<PodProcessLaunchConfig, TicketRoleLaunchError> {
if self.profile == "inherit" {
return Err(TicketRoleLaunchError::UnsupportedInheritProfile);
}
Ok(WorkerProcessLaunchConfig {
Ok(PodProcessLaunchConfig {
runtime_command,
worker_name: self.worker_name.clone(),
pod_name: self.pod_name.clone(),
profile: Some(self.profile.clone()),
workspace_root: self.workspace_root.clone(),
cwd: self.cwd.clone(),
@ -194,8 +187,8 @@ impl TicketRoleLaunchPlan {
})
}
pub fn spawn_options(&self) -> WorkerProcessLaunchOptions {
WorkerProcessLaunchOptions::default()
pub fn spawn_options(&self) -> PodProcessLaunchOptions {
PodProcessLaunchOptions::default()
.with_hidden_arg("--ticket-role", self.role.as_str().to_string())
}
}
@ -215,7 +208,7 @@ pub struct TicketRoleLaunchResult {
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct TicketRoleLaunchAcceptanceEvidence {
pub worker_name: String,
pub pod_name: String,
pub accepted_run_segments: usize,
pub event: TicketRoleLaunchAcceptanceEvent,
}
@ -240,8 +233,8 @@ pub struct TicketRoleLaunchOptions {
}
impl TicketRoleLaunchOptions {
pub fn with_pre_run_peer_registration(mut self, worker_name: impl Into<String>) -> Self {
self.pre_run_peer_registrations.push(worker_name.into());
pub fn with_pre_run_peer_registration(mut self, pod_name: impl Into<String>) -> Self {
self.pre_run_peer_registrations.push(pod_name.into());
self
}
}
@ -260,30 +253,30 @@ pub enum TicketRoleLaunchError {
selector: String,
message: String,
},
#[error("Ticket role Worker name must not be empty")]
EmptyWorkerName,
#[error("Ticket role Pod name must not be empty")]
EmptyPodName,
#[error(
"Ticket role profile 'inherit' cannot be used for top-level launch execution; configure a concrete role profile selector"
)]
UnsupportedInheritProfile,
#[error(transparent)]
Spawn(#[from] SpawnError),
#[error("failed to connect to spawned Ticket role Worker at {}: {source}", .socket_path.display())]
#[error("failed to connect to spawned Ticket role Pod at {}: {source}", .socket_path.display())]
Connect {
socket_path: PathBuf,
#[source]
source: io::Error,
},
#[error("failed to send first run input to spawned Ticket role Worker: {source}")]
#[error("failed to send first run input to spawned Ticket role Pod: {source}")]
SendRun {
#[source]
source: io::Error,
},
#[error("Ticket role Worker rejected first run input with {code:?}: {message}")]
#[error("Ticket role Pod rejected first run input with {code:?}: {message}")]
RunRejected { code: ErrorCode, message: String },
#[error("Ticket role Worker closed before confirming first run acceptance")]
#[error("Ticket role Pod closed before confirming first run acceptance")]
RunAcceptanceClosed,
#[error("timed out waiting for Ticket role Worker to confirm first run acceptance")]
#[error("timed out waiting for Ticket role Pod to confirm first run acceptance")]
RunAcceptanceTimeout,
}
@ -310,17 +303,12 @@ pub fn plan_ticket_role_launch_with_config(
.launch_prompt
.as_ref()
.map(|prompt| prompt.as_str().to_string());
let worker_name = match context.worker_name.as_deref().map(str::trim) {
Some("") => return Err(TicketRoleLaunchError::EmptyWorkerName),
let pod_name = match context.pod_name.as_deref().map(str::trim) {
Some("") => return Err(TicketRoleLaunchError::EmptyPodName),
Some(name) => name.to_string(),
None => default_worker_name(context.role, context.ticket.as_ref()),
None => default_pod_name(context.role, context.ticket.as_ref()),
};
validate_ticket_role_profile(
context.role,
&profile,
&context.workspace_root,
&worker_name,
)?;
validate_ticket_role_profile(context.role, &profile, &context.workspace_root, &pod_name)?;
let prompt = build_launch_prompt(&context);
let original_workspace_root = context.original_workspace_root().to_path_buf();
@ -334,7 +322,7 @@ pub fn plan_ticket_role_launch_with_config(
target_workspace_root,
implementation_worktree_root,
role: context.role,
worker_name,
pod_name,
profile,
workflow: workflow.clone(),
launch_prompt_ref,
@ -351,7 +339,7 @@ fn validate_ticket_role_profile(
role: TicketRole,
profile: &str,
workspace_root: &std::path::Path,
worker_name: &str,
pod_name: &str,
) -> Result<(), TicketRoleLaunchError> {
let selector = ProfileSelector::parse_cli(profile);
let registry = ProfileDiscovery::for_cwd(workspace_root)
@ -366,7 +354,7 @@ fn validate_ticket_role_profile(
.resolve_from_registry(
&selector,
&registry,
ProfileResolveOptions::with_worker_name(worker_name),
ProfileResolveOptions::with_pod_name(pod_name),
)
.map(|_| ())
.map_err(|source| TicketRoleLaunchError::ProfileResolution {
@ -376,17 +364,17 @@ fn validate_ticket_role_profile(
})
}
/// Spawn the Worker, connect to its socket, send the first `Method::Run` input,
/// and wait for bounded acceptance evidence from the Worker event stream.
pub async fn launch_ticket_role_worker<F>(
/// Spawn the Pod, connect to its socket, send the first `Method::Run` input,
/// and wait for bounded acceptance evidence from the Pod event stream.
pub async fn launch_ticket_role_pod<F>(
context: TicketRoleLaunchContext,
runtime_command: WorkerRuntimeCommand,
runtime_command: PodRuntimeCommand,
progress: F,
) -> Result<TicketRoleLaunchResult, TicketRoleLaunchError>
where
F: FnMut(&str),
{
launch_ticket_role_worker_with_options(
launch_ticket_role_pod_with_options(
context,
runtime_command,
progress,
@ -395,11 +383,11 @@ where
.await
}
/// Spawn the Worker, run bounded pre-run launch options while it is still idle,
/// Spawn the Pod, run bounded pre-run launch options while it is still idle,
/// then send the first `Method::Run` input and wait for acceptance evidence.
pub async fn launch_ticket_role_worker_with_options<F>(
pub async fn launch_ticket_role_pod_with_options<F>(
context: TicketRoleLaunchContext,
runtime_command: WorkerRuntimeCommand,
runtime_command: PodRuntimeCommand,
progress: F,
options: TicketRoleLaunchOptions,
) -> Result<TicketRoleLaunchResult, TicketRoleLaunchError>
@ -409,8 +397,8 @@ where
let plan = plan_ticket_role_launch(context)?;
let spawn_config = plan.spawn_config(runtime_command)?;
let spawn_options = plan.spawn_options();
let ready = spawn_worker_with_options(spawn_config, spawn_options, progress).await?;
let mut client = WorkerClient::connect(&ready.socket_path)
let ready = spawn_pod_with_options(spawn_config, spawn_options, progress).await?;
let mut client = PodClient::connect(&ready.socket_path)
.await
.map_err(|source| TicketRoleLaunchError::Connect {
socket_path: ready.socket_path.clone(),
@ -420,7 +408,7 @@ where
let acceptance_event =
wait_for_run_acceptance(&mut client, &plan.run_segments, RUN_ACCEPTANCE_TIMEOUT).await?;
let acceptance_evidence = TicketRoleLaunchAcceptanceEvidence {
worker_name: ready.worker_name.clone(),
pod_name: ready.pod_name.clone(),
accepted_run_segments: plan.run_segments.len(),
event: acceptance_event,
};
@ -433,7 +421,7 @@ where
}
async fn run_pre_run_options_then_send_run(
client: &mut WorkerClient,
client: &mut PodClient,
plan: &TicketRoleLaunchPlan,
options: &TicketRoleLaunchOptions,
) -> Result<Vec<TicketRolePreRunWarning>, TicketRoleLaunchError> {
@ -451,7 +439,7 @@ async fn run_pre_run_options_then_send_run(
}
async fn perform_pre_run_peer_registrations(
client: &mut WorkerClient,
client: &mut PodClient,
peer_names: &[String],
timeout: Duration,
) -> Vec<TicketRolePreRunWarning> {
@ -459,7 +447,7 @@ async fn perform_pre_run_peer_registrations(
for peer_name in peer_names {
if peer_name.trim().is_empty() {
warnings.push(TicketRolePreRunWarning {
message: "pre-run peer registration skipped: peer Worker name is empty".to_string(),
message: "pre-run peer registration skipped: peer Pod name is empty".to_string(),
});
continue;
}
@ -471,7 +459,7 @@ async fn perform_pre_run_peer_registrations(
}
async fn pre_run_register_peer(
client: &mut WorkerClient,
client: &mut PodClient,
peer_name: &str,
timeout: Duration,
) -> Result<(), String> {
@ -515,7 +503,7 @@ async fn pre_run_register_peer(
}
async fn wait_for_run_acceptance(
client: &mut WorkerClient,
client: &mut PodClient,
expected_segments: &[Segment],
timeout: Duration,
) -> Result<TicketRoleLaunchAcceptanceEvent, TicketRoleLaunchError> {
@ -605,10 +593,10 @@ fn append_operation_targets(out: &mut String, context: &TicketRoleLaunchContext)
);
}
fn default_worker_name(role: TicketRole, ticket: Option<&TicketRef>) -> String {
fn default_pod_name(role: TicketRole, ticket: Option<&TicketRef>) -> String {
let mut name = format!("ticket-{}", role.as_str());
if let Some(seed) = ticket.and_then(TicketRef::worker_name_seed) {
let suffix = sanitise_worker_name_component(seed);
if let Some(seed) = ticket.and_then(TicketRef::pod_name_seed) {
let suffix = sanitise_pod_name_component(seed);
if !suffix.is_empty() {
name.push('-');
name.push_str(&suffix);
@ -617,7 +605,7 @@ fn default_worker_name(role: TicketRole, ticket: Option<&TicketRef>) -> String {
name.chars().take(MAX_POD_NAME_CHARS).collect()
}
fn sanitise_worker_name_component(value: &str) -> String {
fn sanitise_pod_name_component(value: &str) -> String {
let mut out = String::new();
let mut last_was_dash = false;
for ch in value.trim().chars() {
@ -692,7 +680,7 @@ fn non_empty(value: Option<&str>) -> Option<&str> {
#[cfg(test)]
mod tests {
use super::*;
use protocol::{Greeting, WorkerStatus};
use protocol::{Greeting, PodStatus};
use tempfile::TempDir;
use tokio::io::{AsyncBufReadExt, AsyncWrite, AsyncWriteExt, BufReader};
use tokio::net::UnixListener;
@ -735,7 +723,7 @@ mod tests {
Event::Snapshot {
entries: vec![],
greeting: Greeting {
worker_name: "ticket-intake".to_string(),
pod_name: "ticket-intake".to_string(),
cwd: "/tmp".to_string(),
provider: "test".to_string(),
model: "test".to_string(),
@ -744,7 +732,7 @@ mod tests {
context_window: 0,
context_tokens: 0,
},
status: WorkerStatus::Idle,
status: PodStatus::Idle,
in_flight: protocol::InFlightSnapshot::default(),
}
}
@ -757,7 +745,7 @@ mod tests {
target_workspace_root: workspace.to_path_buf(),
implementation_worktree_root: workspace.join(".worktree"),
role: TicketRole::Intake,
worker_name: "ticket-intake".to_string(),
pod_name: "ticket-intake".to_string(),
profile: "project:intake".to_string(),
workflow: "ticket-intake-workflow".to_string(),
launch_prompt_ref: None,
@ -770,7 +758,7 @@ mod tests {
#[tokio::test]
async fn pre_run_peer_registration_is_sent_before_first_run_submission() {
let temp = TempDir::new().unwrap();
let socket_path = temp.path().join("worker.sock");
let socket_path = temp.path().join("pod.sock");
let listener = UnixListener::bind(&socket_path).unwrap();
let server = tokio::spawn(async move {
let (stream, _) = listener.accept().await.unwrap();
@ -805,7 +793,7 @@ mod tests {
}
});
let mut client = WorkerClient::connect(&socket_path).await.unwrap();
let mut client = PodClient::connect(&socket_path).await.unwrap();
let options = TicketRoleLaunchOptions::default()
.with_pre_run_peer_registration("workspace-orchestrator");
let warnings = run_pre_run_options_then_send_run(
@ -823,7 +811,7 @@ mod tests {
#[tokio::test]
async fn pre_run_peer_registration_failure_warns_but_still_sends_run() {
let temp = TempDir::new().unwrap();
let socket_path = temp.path().join("worker.sock");
let socket_path = temp.path().join("pod.sock");
let listener = UnixListener::bind(&socket_path).unwrap();
let server = tokio::spawn(async move {
let (stream, _) = listener.accept().await.unwrap();
@ -854,7 +842,7 @@ mod tests {
));
});
let mut client = WorkerClient::connect(&socket_path).await.unwrap();
let mut client = PodClient::connect(&socket_path).await.unwrap();
let options = TicketRoleLaunchOptions::default()
.with_pre_run_peer_registration("workspace-orchestrator");
let warnings = run_pre_run_options_then_send_run(
@ -875,7 +863,7 @@ mod tests {
fn default_config_role_launch_plan_requires_explicit_role_config() {
let temp = TempDir::new().unwrap();
let mut context = TicketRoleLaunchContext::new(temp.path(), TicketRole::Coder);
context.ticket = Some(TicketRef::id("Ticket Role Worker Launcher"));
context.ticket = Some(TicketRef::id("Ticket Role Pod Launcher"));
let err = plan_ticket_role_launch(context).unwrap_err();
@ -1019,7 +1007,7 @@ profile = "builtin:default"
plan.profile = "inherit".to_string();
let err = plan
.spawn_config(WorkerRuntimeCommand::for_executable("/bin/yoi"))
.spawn_config(PodRuntimeCommand::for_executable("/bin/yoi"))
.unwrap_err();
assert!(matches!(
@ -1042,14 +1030,14 @@ workflow = "ticket-review-workflow"
"#,
);
let mut context = TicketRoleLaunchContext::new(temp.path(), TicketRole::Reviewer);
context.worker_name = Some("reviewer-fixed".to_string());
context.ticket = Some(TicketRef::id("20260605-190330-ticket-role-worker-launcher"));
context.pod_name = Some("reviewer-fixed".to_string());
context.ticket = Some(TicketRef::id("20260605-190330-ticket-role-pod-launcher"));
context.user_instruction = Some("Review the submitted implementation.".to_string());
let plan = plan_ticket_role_launch(context).unwrap();
let text = text_segment(&plan);
assert_eq!(plan.worker_name, "reviewer-fixed");
assert_eq!(plan.pod_name, "reviewer-fixed");
assert_eq!(plan.profile, "builtin:default");
assert_eq!(plan.workflow, "ticket-review-workflow");
assert_eq!(
@ -1067,13 +1055,13 @@ workflow = "ticket-review-workflow"
assert!(!text.contains("Role: reviewer"));
assert!(!text.contains("system_instruction"));
assert!(text.contains("Target Ticket:"));
assert!(text.contains("id: 20260605-190330-ticket-role-worker-launcher"));
assert!(text.contains("id: 20260605-190330-ticket-role-pod-launcher"));
assert!(text.contains("Action instruction:"));
assert!(text.contains("Review the submitted implementation."));
let spawn = plan
.spawn_config(WorkerRuntimeCommand::for_executable("/bin/yoi"))
.spawn_config(PodRuntimeCommand::for_executable("/bin/yoi"))
.unwrap();
assert_eq!(spawn.worker_name, "reviewer-fixed");
assert_eq!(spawn.pod_name, "reviewer-fixed");
assert_eq!(spawn.profile.as_deref(), Some("builtin:default"));
assert_eq!(spawn.workspace_root, temp.path());
assert!(spawn.cwd.is_none());
@ -1114,10 +1102,7 @@ workflow = "ticket-review-workflow"
let handoff_plan = plan_ticket_role_launch(handoff_intake).unwrap();
let handoff_text = text_segment(&handoff_plan);
assert!(handoff_text.contains("Panel handoff:"));
assert!(
handoff_text
.contains("workspace_workspace_orchestrator_worker: panel-orchestrator-demo")
);
assert!(handoff_text.contains("workspace_orchestrator_pod: panel-orchestrator-demo"));
assert!(handoff_text.contains("workspace: Demo workspace"));
assert!(!handoff_text.contains("created_or_updated_ticket_id"));
assert!(!handoff_text.contains("Ticket tool surface"));
@ -1140,15 +1125,15 @@ workflow = "ticket-review-workflow"
assert!(!orchestrator_text.contains("role_cwd"));
let mut coder = TicketRoleLaunchContext::new(temp.path(), TicketRole::Coder);
coder.ticket = Some(TicketRef::id("20260605-190330-ticket-role-worker-launcher"));
coder.ticket = Some(TicketRef::id("20260605-190330-ticket-role-pod-launcher"));
coder.worktree_path = Some(PathBuf::from("/tmp/yoi-code"));
coder.branch = Some("work/ticket-role-worker-launcher".into());
coder.branch = Some("work/ticket-role-pod-launcher".into());
coder.validation = vec!["cargo test -p client ticket_role".into()];
coder.report_expectations = vec!["implementation report with validation".into()];
let coder_plan = plan_ticket_role_launch(coder).unwrap();
let coder_text = text_segment(&coder_plan);
assert!(coder_text.contains("path: /tmp/yoi-code"));
assert!(coder_text.contains("branch: work/ticket-role-worker-launcher"));
assert!(coder_text.contains("branch: work/ticket-role-pod-launcher"));
assert!(coder_text.contains("cargo test -p client ticket_role"));
assert!(coder_text.contains("implementation report with validation"));
assert!(!coder_text.contains("provided child worktree/branch"));
@ -1156,14 +1141,14 @@ workflow = "ticket-review-workflow"
assert!(!coder_text.contains("Do not merge, push"));
let mut reviewer = TicketRoleLaunchContext::new(temp.path(), TicketRole::Reviewer);
reviewer.ticket = Some(TicketRef::id("20260605-190330-ticket-role-worker-launcher"));
reviewer.ticket = Some(TicketRef::id("20260605-190330-ticket-role-pod-launcher"));
reviewer.worktree_path = Some(PathBuf::from("/tmp/yoi-review"));
reviewer.branch = Some("work/ticket-role-worker-launcher".into());
reviewer.branch = Some("work/ticket-role-pod-launcher".into());
reviewer.report_expectations = vec!["approve or request changes".into()];
let reviewer_plan = plan_ticket_role_launch(reviewer).unwrap();
let reviewer_text = text_segment(&reviewer_plan);
assert!(reviewer_text.contains("path: /tmp/yoi-review"));
assert!(reviewer_text.contains("branch: work/ticket-role-worker-launcher"));
assert!(reviewer_text.contains("branch: work/ticket-role-pod-launcher"));
assert!(reviewer_text.contains("approve or request changes"));
assert!(!reviewer_text.contains("read-only by default"));
assert!(!reviewer_text.contains("Orchestrator-side integration"));
@ -1192,7 +1177,7 @@ workflow = "ticket-review-workflow"
);
assert_eq!(plan.target_workspace_root, temp.path().join("target"));
let spawn_config = plan
.spawn_config(WorkerRuntimeCommand::for_executable("/bin/yoi"))
.spawn_config(PodRuntimeCommand::for_executable("/bin/yoi"))
.unwrap();
assert_eq!(spawn_config.workspace_root, temp.path());
assert_eq!(spawn_config.cwd, None);
@ -1209,15 +1194,15 @@ workflow = "ticket-review-workflow"
assert!(!text.contains("Orchestrator implementation integration guidance"));
}
#[test]
fn caller_provided_worker_name_is_used_exactly() {
fn caller_provided_pod_name_is_used_exactly() {
let temp = TempDir::new().unwrap();
write_builtin_role_config(temp.path(), &[TicketRole::Intake]);
let mut context = TicketRoleLaunchContext::new(temp.path(), TicketRole::Intake);
context.worker_name = Some("custom-intake-worker".into());
context.pod_name = Some("custom-intake-pod".into());
let plan = plan_ticket_role_launch(context).unwrap();
assert_eq!(plan.worker_name, "custom-intake-worker");
assert_eq!(plan.pod_name, "custom-intake-pod");
}
#[test]

View File

@ -20,7 +20,7 @@ Does not own:
## Design notes
Macros reduce boilerplate, but they must not imply capability. A generated tool definition is still subject to manifest permissions, Worker scope, and runtime policy.
Macros reduce boilerplate, but they must not imply capability. A generated tool definition is still subject to manifest permissions, Pod scope, and runtime policy.
## See also

View File

@ -16,10 +16,10 @@ Owns:
Does not own:
- Worker names, sockets, process lifecycle, or scope delegation (`worker`)
- Pod names, sockets, process lifecycle, or scope delegation (`pod`)
- product CLI shape (`yoi`)
- provider catalog and secret resolution (`provider`, `secrets`)
- durable Worker current state (`pod-store`)
- durable Pod current state (`pod-store`)
## Design notes

View File

@ -213,7 +213,7 @@ pub struct Engine<C: LlmClient, S: EngineState = Mutable> {
/// stream events become visible.
lifecycle_trace_cbs: Vec<Arc<dyn Fn(usize, usize, &str, &Value) + Send + Sync>>,
/// Non-fatal warning callbacks. Invoked when the Engine wants to
/// surface an advisory message to the upper layer (e.g. Worker) so it
/// surface an advisory message to the upper layer (e.g. Pod) so it
/// can be forwarded to the user — distinct from `tracing::warn!`,
/// which is for developer-facing logs.
warning_cbs: Vec<Box<dyn Fn(&str) + Send + Sync>>,
@ -253,7 +253,7 @@ pub struct Engine<C: LlmClient, S: EngineState = Mutable> {
/// Plumbed into [`Request::cache_anchor`] at request build time.
cache_anchor: Option<usize>,
/// Conversation-scoped cache key, set by higher layers. Plumbed into
/// [`Request::cache_key`] at request build time. Worker 側では
/// [`Request::cache_key`] at request build time. Pod 側では
/// `SegmentId` を渡す。
cache_key: Option<String>,
/// State marker
@ -487,7 +487,7 @@ impl<C: LlmClient, S: EngineState> Engine<C, S> {
/// Fired after `post_tool_call` interceptors and any `content`
/// truncation from `tool_output_limits`, so the callback observes
/// exactly what is persisted to history. Intended for upper layers
/// (e.g. Worker) to forward tool results to clients.
/// (e.g. Pod) to forward tool results to clients.
pub fn on_tool_result(&mut self, callback: impl Fn(&ToolResult) + Send + Sync + 'static) {
self.tool_result_cbs.push(Box::new(callback));
}
@ -1121,7 +1121,7 @@ impl<C: LlmClient, S: EngineState> Engine<C, S> {
}
// Drain interceptor-side inputs that are meant to land in
// history (notifications, cross-Worker events, system
// history (notifications, cross-Pod events, system
// reminders). These are committed *before* the per-request
// clone so they participate in the LLM request below and
// get persisted by the upper layer that owns history.json.
@ -1302,7 +1302,7 @@ impl<C: LlmClient, S: EngineState> Engine<C, S> {
// Collect and commit assistant items. Routed through
// `append_history_items` so observers (e.g. the
// Worker-side per-item session-log committer) see each item
// Pod-side per-item session-log committer) see each item
// as it lands.
let reasoning_items = self.thinking_block_collector.take_collected();
let text_blocks = self.text_block_collector.take_collected();
@ -1603,7 +1603,7 @@ impl<C: LlmClient, S: EngineState> Engine<C, S> {
}
Ok(ToolExecutionResult::Completed(results)) => {
// Route per-result pushes through the callback path so
// observers (e.g. the Worker-side per-item session-log
// observers (e.g. the Pod-side per-item session-log
// committer) see each tool result as it lands.
let items = results.into_iter().map(|result| {
Item::tool_result_item(
@ -1708,7 +1708,7 @@ impl<C: LlmClient> Engine<C, Mutable> {
/// Install byte-size caps for tool execution `content`.
///
/// Passing `None` (the default) disables truncation. Higher layers
/// (e.g. Worker) translate manifest configuration into a concrete
/// (e.g. Pod) translate manifest configuration into a concrete
/// [`ToolOutputLimits`] and install it here.
pub fn set_tool_output_limits(&mut self, limits: Option<ToolOutputLimits>) {
self.tool_output_limits = limits;

View File

@ -1,6 +1,6 @@
//! Interceptor - control flow delegation for the Engine execution loop
//!
//! Defines the [`Interceptor`] trait that upper layers (e.g. Worker) implement
//! Defines the [`Interceptor`] trait that upper layers (e.g. Pod) implement
//! to inject orchestration decisions (approval, skip, pause, abort)
//! into the Engine's turn loop without the Engine knowing about
//! higher-level concepts.
@ -132,7 +132,7 @@ pub struct ToolResultInfo {
/// Intercepts the Engine execution loop at key decision points.
///
/// All methods have default implementations that let the Engine
/// proceed without intervention. Upper layers (e.g. Worker) provide
/// proceed without intervention. Upper layers (e.g. Pod) provide
/// richer implementations for approval flows, permission checks, etc.
#[async_trait]
pub trait Interceptor: Send + Sync {
@ -149,7 +149,7 @@ pub trait Interceptor: Send + Sync {
///
/// Use this for inputs that arrive from outside the LLM and need
/// to be reflected in the on-disk history — notifications,
/// cross-Worker events, system reminders. Do **not** use
/// cross-Pod events, system reminders. Do **not** use
/// [`Self::pre_llm_request`] for that purpose: it mutates a
/// per-request clone, so any committed assistant response that
/// reacts to the injection would have no visible trigger on the

View File

@ -51,7 +51,7 @@ pub(crate) struct ResponsesRequest {
#[serde(skip_serializing_if = "Option::is_none")]
pub top_p: Option<f32>,
/// 会話単位の安定キー。ChatGPT backend (codex-oauth) は明示キーが
/// 無いとプロンプトキャッシュがほぼ効かない。worker 側は `SegmentId`
/// 無いとプロンプトキャッシュがほぼ効かない。pod 側は `SegmentId`
/// を渡す。`Request::cache_key` が `None` のときはキー自体を送らない。
#[serde(skip_serializing_if = "Option::is_none")]
pub prompt_cache_key: Option<String>,

View File

@ -523,7 +523,7 @@ pub struct Request {
/// 会話単位の安定キー。`prompt_cache_key` として送られる
/// (OpenAI Responses)。ChatGPT backend (codex-oauth) は明示キーが
/// 無いと org/project ハッシュ衝突でプロンプトキャッシュが
/// ほぼヒットしないため、worker 側で `SegmentId` を渡す運用を想定。
/// ほぼヒットしないため、pod 側で `SegmentId` を渡す運用を想定。
/// `cache_anchor` と違い名前空間キーであり、`prefix anchor` とは
/// 別の概念。`cache_anchor` を読まない provider と同じく、
/// `prompt_cache_key` を持たない provider は無視する。

View File

@ -8,7 +8,7 @@
//!
//! Prune は **コンテキスト射影** であり、history の変換ではない。
//! この crate が提供するのは pure な候補抽出 [`prunable_indices`] のみで、
//! 射影の適用は上位層(`worker::prune_hook` 等)が LLM に送る一時コンテキスト
//! 射影の適用は上位層(`pod::prune_hook` 等)が LLM に送る一時コンテキスト
//! に対してだけ行う。Engine の永続履歴は決して変更されない。
//!
//! 保護境界は末尾 token budget で決めるが、この crate は usage 履歴を
@ -75,7 +75,7 @@ pub enum PruneDecision {
}
/// Optional observer invoked after each prune evaluation, regardless of
/// branch. Worker 等の上位層が install して metrics を発行する。
/// branch. Pod 等の上位層が install して metrics を発行する。
pub type PruneObserver = Box<dyn Fn(&PruneEvaluation) + Send + Sync>;
/// Configuration for the Prune algorithm.

View File

@ -130,13 +130,13 @@ mod tests {
let mut timeline = Timeline::new();
timeline.on_tool_use_block(collector.clone());
timeline.dispatch(&Event::tool_use_start(0, "tool_empty", "ListWorkers"));
timeline.dispatch(&Event::tool_use_start(0, "tool_empty", "ListPods"));
timeline.dispatch(&Event::tool_use_stop(0));
let calls = collector.take_collected();
assert_eq!(calls.len(), 1);
assert_eq!(calls[0].id, "tool_empty");
assert_eq!(calls[0].name, "ListWorkers");
assert_eq!(calls[0].name, "ListPods");
assert!(calls[0].input.is_object());
assert_eq!(
calls[0].input,

View File

@ -75,7 +75,7 @@ impl ToolServerHandle {
/// Execute all pending factories and register the resulting tools.
///
/// Called implicitly by `Engine::lock()` before the first turn.
/// Exposed as `pub` so higher layers (e.g. Worker) can force-materialise
/// Exposed as `pub` so higher layers (e.g. Pod) can force-materialise
/// tools earlier — for example when building a system-prompt template
/// context that needs the list of registered tool names. Redundant
/// calls are no-ops.

View File

@ -2,7 +2,7 @@
//!
//! 1 リクエストの送信時点での「ある history prefix 長で計測した占有量」を
//! 1 件分にまとめたもの。`UsageEvent` (provider stream イベント) を
//! 受けて呼び出し側 (typically Worker) が組み立て、永続化層
//! 受けて呼び出し側 (typically Pod) が組み立て、永続化層
//! (session-store) に流したり、token accounting (`token_counter`) で
//! 履歴として参照したりする。

View File

@ -2,7 +2,7 @@
## Role
`manifest` resolves reusable profile/configuration inputs into the concrete runtime Manifest used to create or restore Workers.
`manifest` resolves reusable profile/configuration inputs into the concrete runtime Manifest used to create or restore Pods.
## Boundaries
@ -17,13 +17,13 @@ Owns:
Does not own:
- provider HTTP clients or secret lookup implementation (`provider`, `secrets`)
- Worker lifecycle (`worker`)
- Pod lifecycle (`pod`)
- product CLI parsing (`yoi`)
- generated memory records (`memory`)
## Design notes
Profiles are reusable recipes; resolved Manifests are runtime contracts. Keep runtime-bound fields such as Worker name, concrete delegated scope, sockets, session pointers, and raw secrets out of reusable Profiles.
Profiles are reusable recipes; resolved Manifests are runtime contracts. Keep runtime-bound fields such as Pod name, concrete delegated scope, sockets, session pointers, and raw secrets out of reusable Profiles.
## See also

View File

@ -1,10 +1,10 @@
//! Partial-form of [`crate::WorkerManifest`] used as cascade layers.
//! Partial-form of [`crate::PodManifest`] used as cascade layers.
//!
//! `WorkerManifestConfig` mirrors `WorkerManifest` but every field is optional
//! `PodManifestConfig` mirrors `PodManifest` but every field is optional
//! so individual layers (builtin defaults, user manifest, project
//! manifest, programmatic overlay) can be partial. Layers are combined
//! via [`WorkerManifestConfig::merge`] and the final config is converted to
//! a validated [`WorkerManifest`] via `TryFrom`.
//! via [`PodManifestConfig::merge`] and the final config is converted to
//! a validated [`PodManifest`] via `TryFrom`.
use std::collections::{BTreeSet, HashMap};
use std::num::NonZeroU32;
@ -17,19 +17,19 @@ use crate::defaults;
use crate::model::{AuthRef, ModelManifest, ReasoningControl};
use crate::plugin::PluginConfig;
use crate::{
CompactionConfig, EngineManifest, FeatureConfig, FeatureFlagConfig, FileUploadLimits,
McpConfig, McpEnvValue, McpStdioCwdPolicy, MemoryConfig, ScopeConfig, SessionConfig,
CompactionConfig, FeatureConfig, FeatureFlagConfig, FileUploadLimits, McpConfig, McpEnvValue,
McpStdioCwdPolicy, MemoryConfig, PodManifest, PodMeta, ScopeConfig, SessionConfig,
SkillsConfig, TicketFeatureAccessConfig, TicketFeatureConfig, ToolOutputLimits,
ToolPermissionConfig, ToolPermissionRule, WebConfig, WorkerManifest, WorkerMeta,
ToolPermissionConfig, ToolPermissionRule, WebConfig, WorkerManifest,
};
/// Partial-form Worker manifest. Every field is optional; one or more
/// instances merge via [`WorkerManifestConfig::merge`] before being
/// converted to a validated [`WorkerManifest`] via `TryFrom`.
/// Partial-form Pod manifest. Every field is optional; one or more
/// instances merge via [`PodManifestConfig::merge`] before being
/// converted to a validated [`PodManifest`] via `TryFrom`.
#[derive(Debug, Clone, Default, Serialize, Deserialize)]
pub struct WorkerManifestConfig {
pub struct PodManifestConfig {
#[serde(default)]
pub worker: WorkerMetaConfig,
pub pod: PodMetaConfig,
/// `[model]` セクションは partial でも完成形でも同じ
/// [`ModelManifest`] を使う。ref / inline の両形を受け入れるための
/// 全 Optional 構造なので、カスケード層と最終マニフェストで型を
@ -37,10 +37,10 @@ pub struct WorkerManifestConfig {
#[serde(default)]
pub model: ModelManifest,
#[serde(default)]
pub engine: EngineManifestConfig,
pub worker: WorkerManifestConfig,
#[serde(default)]
pub scope: ScopeConfig,
/// Scope that may be subdelegated to spawned child Workers. Defaults empty.
/// Scope that may be subdelegated to spawned child Pods. Defaults empty.
#[serde(default)]
pub delegation_scope: ScopeConfig,
#[serde(default)]
@ -83,7 +83,7 @@ pub struct FeatureConfigPartial {
#[serde(default)]
pub web: Option<FeatureFlagConfigPartial>,
#[serde(default)]
pub workers: Option<FeatureFlagConfigPartial>,
pub pods: Option<FeatureFlagConfigPartial>,
#[serde(default)]
pub ticket: Option<TicketFeatureConfigPartial>,
#[serde(default)]
@ -98,7 +98,7 @@ impl FeatureConfigPartial {
task: merge_option(self.task, other.task, FeatureFlagConfigPartial::merge),
memory: merge_option(self.memory, other.memory, FeatureFlagConfigPartial::merge),
web: merge_option(self.web, other.web, FeatureFlagConfigPartial::merge),
workers: merge_option(self.workers, other.workers, FeatureFlagConfigPartial::merge),
pods: merge_option(self.pods, other.pods, FeatureFlagConfigPartial::merge),
ticket: merge_option(self.ticket, other.ticket, TicketFeatureConfigPartial::merge),
ticket_orchestration: merge_option(
self.ticket_orchestration,
@ -150,10 +150,7 @@ impl From<FeatureConfigPartial> for FeatureConfig {
.map(FeatureFlagConfig::from)
.unwrap_or_default(),
web: value.web.map(FeatureFlagConfig::from).unwrap_or_default(),
workers: value
.workers
.map(FeatureFlagConfig::from)
.unwrap_or_default(),
pods: value.pods.map(FeatureFlagConfig::from).unwrap_or_default(),
ticket: value
.ticket
.map(TicketFeatureConfig::from)
@ -210,7 +207,7 @@ impl From<FeatureConfig> for FeatureConfigPartial {
task: Some(value.task.into()),
memory: Some(value.memory.into()),
web: Some(value.web.into()),
workers: Some(value.workers.into()),
pods: Some(value.pods.into()),
ticket: Some(value.ticket.into()),
ticket_orchestration: Some(value.ticket_orchestration.into()),
plugins: Some(value.plugins.into()),
@ -219,18 +216,18 @@ impl From<FeatureConfig> for FeatureConfigPartial {
}
#[derive(Debug, Clone, Default, Serialize, Deserialize)]
pub struct WorkerMetaConfig {
pub struct PodMetaConfig {
#[serde(default)]
pub name: Option<String>,
/// Optional `PromptCatalog` manifest pack override. See
/// [`crate::WorkerMeta::prompt_pack`] for semantics. Relative paths
/// are resolved through [`WorkerManifestConfig::resolve_paths`].
/// [`crate::PodMeta::prompt_pack`] for semantics. Relative paths
/// are resolved through [`PodManifestConfig::resolve_paths`].
#[serde(default)]
pub prompt_pack: Option<PathBuf>,
}
#[derive(Debug, Clone, Default, Serialize, Deserialize)]
pub struct EngineManifestConfig {
pub struct WorkerManifestConfig {
#[serde(default)]
pub instruction: Option<String>,
#[serde(default)]
@ -321,8 +318,8 @@ pub struct CompactionConfigPartial {
pub model: Option<ModelManifest>,
}
/// Errors raised when converting a [`WorkerManifestConfig`] to a validated
/// [`WorkerManifest`] via `TryFrom`.
/// Errors raised when converting a [`PodManifestConfig`] to a validated
/// [`PodManifest`] via `TryFrom`.
#[derive(Debug, thiserror::Error)]
pub enum ResolveError {
#[error("missing required field: {0}")]
@ -362,7 +359,7 @@ pub(crate) fn reject_removed_manifest_fields(s: &str) -> Result<(), toml::de::Er
Ok(())
}
impl WorkerManifestConfig {
impl PodManifestConfig {
/// Parse a partial manifest from a TOML string. Unknown top-level or
/// nested fields emit a `tracing::warn!` and are ignored; use
/// `tracing_subscriber` with `WARN` enabled to surface them to the
@ -381,12 +378,12 @@ impl WorkerManifestConfig {
/// from this layer so every per-field default lives at exactly one
/// call site (the `defaults` module).
///
/// `TryFrom<WorkerManifestConfig>` also reads the same constants as a
/// `TryFrom<PodManifestConfig>` also reads the same constants as a
/// belt-and-suspenders fallback, so a manually-constructed config
/// that skips this layer still resolves to the same values.
pub fn builtin_defaults() -> Self {
Self {
engine: EngineManifestConfig {
worker: WorkerManifestConfig {
tool_output: ToolOutputLimitsPartial {
default_max_bytes: Some(defaults::TOOL_OUTPUT_MAX_BYTES),
per_tool: HashMap::new(),
@ -418,7 +415,7 @@ impl WorkerManifestConfig {
base.display()
);
resolve_auth_file(&mut self.model.auth, base);
if let Some(ref mut pack) = self.worker.prompt_pack {
if let Some(ref mut pack) = self.pod.prompt_pack {
*pack = join_if_relative(base, pack);
}
for rule in &mut self.scope.allow {
@ -460,11 +457,11 @@ impl WorkerManifestConfig {
/// fields from `self`. Map entries merge key-wise with `upper`
/// winning on conflict. Scope rules from both layers accumulate
/// (see [`ScopeConfig`] semantics).
pub fn merge(self, upper: WorkerManifestConfig) -> Self {
pub fn merge(self, upper: PodManifestConfig) -> Self {
Self {
worker: self.worker.merge(upper.worker),
pod: self.pod.merge(upper.pod),
model: self.model.merge(upper.model),
engine: self.engine.merge(upper.engine),
worker: self.worker.merge(upper.worker),
scope: merge_scope(self.scope, upper.scope),
delegation_scope: merge_scope(self.delegation_scope, upper.delegation_scope),
session: merge_option(self.session, upper.session, SessionConfigPartial::merge),
@ -578,7 +575,7 @@ impl MemoryConfig {
}
}
impl WorkerMetaConfig {
impl PodMetaConfig {
fn merge(self, upper: Self) -> Self {
Self {
name: upper.name.or(self.name),
@ -587,7 +584,7 @@ impl WorkerMetaConfig {
}
}
impl EngineManifestConfig {
impl WorkerManifestConfig {
fn merge(self, upper: Self) -> Self {
Self {
instruction: upper.instruction.or(self.instruction),
@ -699,9 +696,9 @@ fn join_if_relative(base: &Path, p: &Path) -> PathBuf {
}
}
/// Invariant check: every path in a fully-resolved [`WorkerManifestConfig`]
/// Invariant check: every path in a fully-resolved [`PodManifestConfig`]
/// must be absolute. Relative paths are resolved per-layer via
/// [`WorkerManifestConfig::resolve_paths`]; if one reaches `TryFrom` it
/// [`PodManifestConfig::resolve_paths`]; if one reaches `TryFrom` it
/// indicates a caller skipped the per-layer resolve step.
fn ensure_absolute(field: &'static str, path: &Path) -> Result<(), ResolveError> {
if path.is_absolute() {
@ -874,48 +871,45 @@ fn bounded_label(value: &str) -> String {
out
}
impl TryFrom<WorkerManifestConfig> for WorkerManifest {
impl TryFrom<PodManifestConfig> for PodManifest {
type Error = ResolveError;
fn try_from(cfg: WorkerManifestConfig) -> Result<Self, Self::Error> {
let name = cfg
.worker
.name
.ok_or(ResolveError::MissingField("worker.name"))?;
let prompt_pack = cfg.worker.prompt_pack;
fn try_from(cfg: PodManifestConfig) -> Result<Self, Self::Error> {
let name = cfg.pod.name.ok_or(ResolveError::MissingField("pod.name"))?;
let prompt_pack = cfg.pod.prompt_pack;
if let Some(ref p) = prompt_pack {
ensure_absolute("worker.prompt_pack", p)?;
ensure_absolute("pod.prompt_pack", p)?;
}
validate_model_paths(&cfg.model, "model.auth.file")?;
let engine = EngineManifest {
let worker = WorkerManifest {
instruction: cfg
.engine
.worker
.instruction
.unwrap_or_else(|| defaults::DEFAULT_INSTRUCTION.to_string()),
language: cfg
.engine
.worker
.language
.unwrap_or_else(|| defaults::WORKER_LANGUAGE.to_string()),
max_tokens: cfg.engine.max_tokens,
max_turns: cfg.engine.max_turns,
temperature: cfg.engine.temperature,
top_p: cfg.engine.top_p,
top_k: cfg.engine.top_k,
stop_sequences: cfg.engine.stop_sequences.unwrap_or_default(),
reasoning: cfg.engine.reasoning,
max_tokens: cfg.worker.max_tokens,
max_turns: cfg.worker.max_turns,
temperature: cfg.worker.temperature,
top_p: cfg.worker.top_p,
top_k: cfg.worker.top_k,
stop_sequences: cfg.worker.stop_sequences.unwrap_or_default(),
reasoning: cfg.worker.reasoning,
tool_output: ToolOutputLimits {
default_max_bytes: cfg
.engine
.worker
.tool_output
.default_max_bytes
.unwrap_or(defaults::TOOL_OUTPUT_MAX_BYTES),
per_tool: cfg.engine.tool_output.per_tool,
per_tool: cfg.worker.tool_output.per_tool,
},
file_upload: FileUploadLimits {
max_bytes: cfg
.engine
.worker
.file_upload
.max_bytes
.unwrap_or(defaults::FILE_UPLOAD_MAX_BYTES),
@ -1013,10 +1007,10 @@ impl TryFrom<WorkerManifestConfig> for WorkerManifest {
validate_mcp_config(&cfg.mcp)?;
Ok(WorkerManifest {
worker: WorkerMeta { name, prompt_pack },
Ok(PodManifest {
pod: PodMeta { name, prompt_pack },
model: cfg.model,
engine,
worker,
scope: cfg.scope,
delegation_scope: cfg.delegation_scope,
session,
@ -1047,9 +1041,9 @@ mod tests {
AuthRef::ApiKey { file: Some(path) }
}
fn minimal_valid() -> WorkerManifestConfig {
WorkerManifestConfig {
worker: WorkerMetaConfig {
fn minimal_valid() -> PodManifestConfig {
PodManifestConfig {
pod: PodMetaConfig {
name: Some("test".into()),
prompt_pack: None,
},
@ -1058,10 +1052,10 @@ mod tests {
model_id: Some("claude-sonnet-4-20250514".into()),
..Default::default()
},
engine: EngineManifestConfig::default(),
worker: WorkerManifestConfig::default(),
scope: ScopeConfig {
allow: vec![ScopeRule {
target: abs("/worker"),
target: abs("/pod"),
permission: Permission::Write,
recursive: true,
}],
@ -1082,8 +1076,8 @@ mod tests {
#[test]
fn resolve_minimal_succeeds() {
let manifest: WorkerManifest = minimal_valid().try_into().unwrap();
assert_eq!(manifest.worker.name, "test");
let manifest: PodManifest = minimal_valid().try_into().unwrap();
assert_eq!(manifest.pod.name, "test");
assert_eq!(manifest.model.scheme, Some(SchemeKind::Anthropic));
assert!(manifest.permissions.is_none());
}
@ -1119,7 +1113,7 @@ mod tests {
},
});
let manifest: WorkerManifest = cfg.try_into().unwrap();
let manifest: PodManifest = cfg.try_into().unwrap();
assert_eq!(manifest.mcp.stdio_servers.len(), 1);
let server = &manifest.mcp.stdio_servers[0];
@ -1143,7 +1137,7 @@ mod tests {
env: crate::McpEnvConfig::default(),
});
let err = WorkerManifest::try_from(cfg).unwrap_err();
let err = PodManifest::try_from(cfg).unwrap_err();
assert!(matches!(
err,
ResolveError::InvalidMcpConfig {
@ -1163,7 +1157,7 @@ mod tests {
});
}
let err = WorkerManifest::try_from(cfg).unwrap_err();
let err = PodManifest::try_from(cfg).unwrap_err();
assert!(matches!(
err,
ResolveError::InvalidMcpConfig {
@ -1192,7 +1186,7 @@ mod tests {
},
});
let err = WorkerManifest::try_from(cfg).unwrap_err();
let err = PodManifest::try_from(cfg).unwrap_err();
let rendered = err.to_string();
assert!(rendered.contains("secret_ref"));
assert!(!rendered.contains("bad secret id with spaces"));
@ -1214,7 +1208,7 @@ mod tests {
env: crate::McpEnvConfig::default(),
});
let manifest: WorkerManifest = cfg.try_into().unwrap();
let manifest: PodManifest = cfg.try_into().unwrap();
assert_eq!(
manifest.mcp.stdio_servers[0].command,
"definitely-not-a-command-yoi-must-spawn"
@ -1228,7 +1222,7 @@ mod tests {
record_event_trace: Some(true),
});
let manifest: WorkerManifest = cfg.try_into().unwrap();
let manifest: PodManifest = cfg.try_into().unwrap();
assert!(manifest.session.record_event_trace);
}
@ -1240,7 +1234,7 @@ mod tests {
rules: Vec::new(),
});
let err = WorkerManifest::try_from(cfg).unwrap_err();
let err = PodManifest::try_from(cfg).unwrap_err();
assert!(matches!(
err,
@ -1267,7 +1261,7 @@ mod tests {
],
});
let manifest: WorkerManifest = cfg.try_into().unwrap();
let manifest: PodManifest = cfg.try_into().unwrap();
let permissions = manifest.permissions.unwrap();
assert_eq!(permissions.default_action, crate::ToolPermissionAction::Ask);
@ -1324,7 +1318,7 @@ mod tests {
fn try_from_invariant_rejects_lingering_relative_auth_file() {
let mut cfg = minimal_valid();
cfg.model.auth = Some(api_key_file_auth(PathBuf::from("keys/relative")));
let err = WorkerManifest::try_from(cfg).unwrap_err();
let err = PodManifest::try_from(cfg).unwrap_err();
assert!(matches!(
err,
ResolveError::RelativePath {
@ -1338,7 +1332,7 @@ mod tests {
fn try_from_invariant_rejects_lingering_relative_scope_target() {
let mut cfg = minimal_valid();
cfg.scope.allow[0].target = PathBuf::from("docs");
let err = WorkerManifest::try_from(cfg).unwrap_err();
let err = PodManifest::try_from(cfg).unwrap_err();
assert!(matches!(
err,
ResolveError::RelativePath {
@ -1349,25 +1343,25 @@ mod tests {
}
#[test]
fn resolve_rejects_missing_worker_name() {
fn resolve_rejects_missing_pod_name() {
let mut cfg = minimal_valid();
cfg.worker.name = None;
let err = WorkerManifest::try_from(cfg).unwrap_err();
assert!(matches!(err, ResolveError::MissingField("worker.name")));
cfg.pod.name = None;
let err = PodManifest::try_from(cfg).unwrap_err();
assert!(matches!(err, ResolveError::MissingField("pod.name")));
}
#[test]
fn resolve_accepts_empty_scope_for_profile_launch_policy() {
let mut cfg = minimal_valid();
cfg.scope.allow.clear();
let manifest = WorkerManifest::try_from(cfg).unwrap();
let manifest = PodManifest::try_from(cfg).unwrap();
assert!(manifest.scope.allow.is_empty());
}
#[test]
fn merge_scalar_upper_wins() {
let lower = WorkerManifestConfig {
worker: WorkerMetaConfig {
let lower = PodManifestConfig {
pod: PodMetaConfig {
name: Some("lower".into()),
prompt_pack: None,
},
@ -1377,30 +1371,30 @@ mod tests {
},
..Default::default()
};
let upper = WorkerManifestConfig {
worker: WorkerMetaConfig {
let upper = PodManifestConfig {
pod: PodMetaConfig {
name: Some("upper".into()),
prompt_pack: None,
},
..Default::default()
};
let merged = lower.merge(upper);
assert_eq!(merged.worker.name.as_deref(), Some("upper"));
assert_eq!(merged.pod.name.as_deref(), Some("upper"));
// model_id not present in upper — retain lower
assert_eq!(merged.model.model_id.as_deref(), Some("lower-model"));
}
#[test]
fn merge_worker_reasoning_upper_wins() {
let lower = WorkerManifestConfig {
engine: EngineManifestConfig {
let lower = PodManifestConfig {
worker: WorkerManifestConfig {
reasoning: Some(ReasoningControl::Effort(ReasoningEffort::Low)),
..Default::default()
},
..Default::default()
};
let upper = WorkerManifestConfig {
engine: EngineManifestConfig {
let upper = PodManifestConfig {
worker: WorkerManifestConfig {
reasoning: Some(ReasoningControl::BudgetTokens(4096)),
..Default::default()
},
@ -1410,15 +1404,15 @@ mod tests {
let merged = lower.merge(upper);
assert_eq!(
merged.engine.reasoning,
merged.worker.reasoning,
Some(ReasoningControl::BudgetTokens(4096))
);
}
#[test]
fn merge_worker_generation_settings_upper_wins() {
let lower = WorkerManifestConfig {
engine: EngineManifestConfig {
let lower = PodManifestConfig {
worker: WorkerManifestConfig {
top_p: Some(0.8),
top_k: Some(20),
stop_sequences: Some(vec!["lower".into()]),
@ -1426,8 +1420,8 @@ mod tests {
},
..Default::default()
};
let upper = WorkerManifestConfig {
engine: EngineManifestConfig {
let upper = PodManifestConfig {
worker: WorkerManifestConfig {
top_p: Some(0.9),
stop_sequences: Some(vec!["upper".into()]),
..Default::default()
@ -1437,14 +1431,14 @@ mod tests {
let merged = lower.merge(upper);
assert_eq!(merged.engine.top_p, Some(0.9));
assert_eq!(merged.engine.top_k, Some(20));
assert_eq!(merged.engine.stop_sequences, Some(vec!["upper".into()]));
assert_eq!(merged.worker.top_p, Some(0.9));
assert_eq!(merged.worker.top_k, Some(20));
assert_eq!(merged.worker.stop_sequences, Some(vec!["upper".into()]));
}
#[test]
fn merge_scope_accumulates_allow_and_deny() {
let lower = WorkerManifestConfig {
let lower = PodManifestConfig {
scope: ScopeConfig {
allow: vec![ScopeRule {
target: abs("/a"),
@ -1455,7 +1449,7 @@ mod tests {
},
..Default::default()
};
let upper = WorkerManifestConfig {
let upper = PodManifestConfig {
scope: ScopeConfig {
allow: vec![ScopeRule {
target: abs("/b"),
@ -1477,7 +1471,7 @@ mod tests {
#[test]
fn merge_permissions_accumulates_rules_and_upper_default_wins() {
let lower = WorkerManifestConfig {
let lower = PodManifestConfig {
permissions: Some(PermissionConfigPartial {
default_action: Some(crate::ToolPermissionAction::Allow),
rules: vec![ToolPermissionRule {
@ -1488,7 +1482,7 @@ mod tests {
}),
..Default::default()
};
let upper = WorkerManifestConfig {
let upper = PodManifestConfig {
permissions: Some(PermissionConfigPartial {
default_action: Some(crate::ToolPermissionAction::Deny),
rules: vec![ToolPermissionRule {
@ -1513,8 +1507,8 @@ mod tests {
#[test]
fn merge_tool_output_per_tool_keywise() {
let lower = WorkerManifestConfig {
engine: EngineManifestConfig {
let lower = PodManifestConfig {
worker: WorkerManifestConfig {
tool_output: ToolOutputLimitsPartial {
default_max_bytes: Some(8192),
per_tool: [("Read".to_string(), 1024)].into_iter().collect(),
@ -1523,8 +1517,8 @@ mod tests {
},
..Default::default()
};
let upper = WorkerManifestConfig {
engine: EngineManifestConfig {
let upper = PodManifestConfig {
worker: WorkerManifestConfig {
tool_output: ToolOutputLimitsPartial {
default_max_bytes: None,
per_tool: [("Read".to_string(), 2048), ("Grep".to_string(), 512)]
@ -1536,7 +1530,7 @@ mod tests {
..Default::default()
};
let merged = lower.merge(upper);
let to = &merged.engine.tool_output;
let to = &merged.worker.tool_output;
assert_eq!(to.default_max_bytes, Some(8192));
assert_eq!(to.per_tool.get("Read"), Some(&2048));
assert_eq!(to.per_tool.get("Grep"), Some(&512));
@ -1544,8 +1538,8 @@ mod tests {
#[test]
fn merge_file_upload_max_bytes_upper_wins() {
let lower = WorkerManifestConfig {
engine: EngineManifestConfig {
let lower = PodManifestConfig {
worker: WorkerManifestConfig {
file_upload: FileUploadLimitsPartial {
max_bytes: Some(8192),
},
@ -1553,8 +1547,8 @@ mod tests {
},
..Default::default()
};
let upper = WorkerManifestConfig {
engine: EngineManifestConfig {
let upper = PodManifestConfig {
worker: WorkerManifestConfig {
file_upload: FileUploadLimitsPartial {
max_bytes: Some(54_321),
},
@ -1563,11 +1557,11 @@ mod tests {
..Default::default()
};
let merged = lower.merge(upper);
assert_eq!(merged.engine.file_upload.max_bytes, Some(54_321));
assert_eq!(merged.worker.file_upload.max_bytes, Some(54_321));
}
#[test]
fn merge_option_struct_field_wise() {
let lower = WorkerManifestConfig {
let lower = PodManifestConfig {
compaction: Some(CompactionConfigPartial {
threshold: Some(50_000),
prune_protected_tokens: Some(5_000),
@ -1583,7 +1577,7 @@ mod tests {
}),
..Default::default()
};
let upper = WorkerManifestConfig {
let upper = PodManifestConfig {
compaction: Some(CompactionConfigPartial {
threshold: Some(80_000),
..Default::default()
@ -1610,32 +1604,32 @@ mod tests {
#[test]
fn from_toml_type_mismatch_is_hard_error() {
let bad = r#"
[worker]
[pod]
name = "x"
[engine]
[worker]
max_tokens = "not-a-number"
"#;
assert!(WorkerManifestConfig::from_toml(bad).is_err());
assert!(PodManifestConfig::from_toml(bad).is_err());
}
#[test]
fn from_toml_accepts_unknown_field() {
// Unknown keys are warn-and-ignored, not hard errors.
// `worker.pwd` specifically is silently dropped after the
// `pod.pwd` specifically is silently dropped after the
// path-resolution ticket — keep it in the fixture to exercise
// that code path.
let ok = r#"
[worker]
[pod]
name = "x"
pwd = "/obsolete"
[engine]
[worker]
max_tokens = 1000
unknown_future_field = "tolerated"
"#;
let cfg = WorkerManifestConfig::from_toml(ok).unwrap();
assert_eq!(cfg.engine.max_tokens, Some(1000));
let cfg = PodManifestConfig::from_toml(ok).unwrap();
assert_eq!(cfg.worker.max_tokens, Some(1000));
}
#[test]
@ -1644,7 +1638,7 @@ unknown_future_field = "tolerated"
[compaction]
prune_protected_turns = 3
"#;
let err = WorkerManifestConfig::from_toml(bad).unwrap_err();
let err = PodManifestConfig::from_toml(bad).unwrap_err();
assert!(
err.to_string().contains("compaction.prune_protected_turns"),
"unexpected error: {err}"
@ -1657,7 +1651,7 @@ prune_protected_turns = 3
[memory]
extract_worker_max_input_tokens = 30000
"#;
let err = WorkerManifestConfig::from_toml(bad).unwrap_err();
let err = PodManifestConfig::from_toml(bad).unwrap_err();
assert!(
err.to_string()
.contains("memory.extract_worker_max_input_tokens"),
@ -1667,7 +1661,7 @@ extract_worker_max_input_tokens = 30000
#[test]
fn from_toml_accepts_extract_worker_max_turns() {
let cfg = WorkerManifestConfig::from_toml(
let cfg = PodManifestConfig::from_toml(
r#"
[memory]
extract_worker_max_turns = 2
@ -1679,36 +1673,36 @@ extract_worker_max_turns = 2
#[test]
fn from_toml_accepts_worker_reasoning_string_or_integer() {
let effort = WorkerManifestConfig::from_toml(
let effort = PodManifestConfig::from_toml(
r#"
[engine]
[worker]
reasoning = "xhigh"
"#,
)
.unwrap();
assert_eq!(
effort.engine.reasoning,
effort.worker.reasoning,
Some(ReasoningControl::Effort(ReasoningEffort::XHigh))
);
let budget = WorkerManifestConfig::from_toml(
let budget = PodManifestConfig::from_toml(
r#"
[engine]
[worker]
reasoning = -1
"#,
)
.unwrap();
assert_eq!(
budget.engine.reasoning,
budget.worker.reasoning,
Some(ReasoningControl::BudgetTokens(-1))
);
}
#[test]
fn from_toml_accepts_worker_generation_settings() {
let cfg = WorkerManifestConfig::from_toml(
let cfg = PodManifestConfig::from_toml(
r#"
[engine]
[worker]
top_p = 0.9
top_k = 40
stop_sequences = ["\n\n", "</stop>"]
@ -1716,17 +1710,17 @@ stop_sequences = ["\n\n", "</stop>"]
)
.unwrap();
assert_eq!(cfg.engine.top_p, Some(0.9));
assert_eq!(cfg.engine.top_k, Some(40));
assert_eq!(cfg.worker.top_p, Some(0.9));
assert_eq!(cfg.worker.top_k, Some(40));
assert_eq!(
cfg.engine.stop_sequences,
cfg.worker.stop_sequences,
Some(vec!["\n\n".into(), "</stop>".into()])
);
}
#[test]
fn from_toml_accepts_worker_max_turns() {
let cfg = WorkerManifestConfig::from_toml(
let cfg = PodManifestConfig::from_toml(
r#"
[compaction]
worker_max_turns = 7
@ -1742,7 +1736,7 @@ worker_max_turns = 7
let mut cfg = minimal_valid();
cfg.compaction = Some(CompactionConfigPartial::default());
let manifest = WorkerManifest::try_from(cfg).unwrap();
let manifest = PodManifest::try_from(cfg).unwrap();
assert_eq!(
manifest.compaction.unwrap().worker_max_turns,
@ -1752,18 +1746,18 @@ worker_max_turns = 7
#[test]
fn feature_flags_default_disabled_in_resolved_manifest() {
let manifest: WorkerManifest = minimal_valid().try_into().unwrap();
let manifest: PodManifest = minimal_valid().try_into().unwrap();
assert!(!manifest.feature.task.enabled);
assert!(!manifest.feature.memory.enabled);
assert!(!manifest.feature.web.enabled);
assert!(!manifest.feature.workers.enabled);
assert!(!manifest.feature.pods.enabled);
assert!(!manifest.feature.ticket.enabled);
assert!(!manifest.feature.ticket_orchestration.enabled);
}
#[test]
fn from_toml_parses_explicit_feature_flags() {
let cfg = WorkerManifestConfig::from_toml(
let cfg = PodManifestConfig::from_toml(
r#"
[feature.task]
enabled = true
@ -1777,10 +1771,10 @@ enabled = true
"#,
)
.unwrap();
let manifest: WorkerManifest = WorkerManifestConfig::builtin_defaults()
let manifest: PodManifest = PodManifestConfig::builtin_defaults()
.merge(cfg)
.merge(WorkerManifestConfig {
worker: WorkerMetaConfig {
.merge(PodManifestConfig {
pod: PodMetaConfig {
name: Some("feature-test".into()),
prompt_pack: None,
},
@ -1791,7 +1785,7 @@ enabled = true
},
scope: ScopeConfig {
allow: vec![ScopeRule {
target: abs("/worker"),
target: abs("/pod"),
permission: Permission::Read,
recursive: true,
}],
@ -1813,7 +1807,7 @@ enabled = true
#[test]
fn feature_flags_merge_as_partial_profile_layers() {
let base = WorkerManifestConfig::from_toml(
let base = PodManifestConfig::from_toml(
r#"
[feature.memory]
enabled = true
@ -1824,7 +1818,7 @@ access = "read_only"
"#,
)
.unwrap();
let upper = WorkerManifestConfig::from_toml(
let upper = PodManifestConfig::from_toml(
r#"
[feature.ticket]
access = "lifecycle"
@ -1834,11 +1828,11 @@ enabled = true
"#,
)
.unwrap();
let manifest: WorkerManifest = WorkerManifestConfig::builtin_defaults()
let manifest: PodManifest = PodManifestConfig::builtin_defaults()
.merge(base)
.merge(upper)
.merge(WorkerManifestConfig {
worker: WorkerMetaConfig {
.merge(PodManifestConfig {
pod: PodMetaConfig {
name: Some("feature-merge-test".into()),
prompt_pack: None,
},
@ -1849,7 +1843,7 @@ enabled = true
},
scope: ScopeConfig {
allow: vec![ScopeRule {
target: abs("/worker"),
target: abs("/pod"),
permission: Permission::Read,
recursive: true,
}],
@ -1866,7 +1860,7 @@ enabled = true
TicketFeatureAccessConfig::Lifecycle
);
assert!(manifest.feature.web.enabled);
assert!(!manifest.feature.workers.enabled);
assert!(!manifest.feature.pods.enabled);
}
#[test]
@ -1877,20 +1871,20 @@ enabled = true
target = "/abs/project"
permission = "write"
"#;
let cfg = WorkerManifestConfig::from_toml(toml).unwrap();
assert!(cfg.worker.name.is_none());
let cfg = PodManifestConfig::from_toml(toml).unwrap();
assert!(cfg.pod.name.is_none());
assert_eq!(cfg.scope.allow.len(), 1);
}
#[test]
fn builtin_defaults_populates_worker_limit_defaults() {
let cfg = WorkerManifestConfig::builtin_defaults();
let cfg = PodManifestConfig::builtin_defaults();
assert_eq!(
cfg.engine.tool_output.default_max_bytes,
cfg.worker.tool_output.default_max_bytes,
Some(defaults::TOOL_OUTPUT_MAX_BYTES)
);
assert_eq!(
cfg.engine.file_upload.max_bytes,
cfg.worker.file_upload.max_bytes,
Some(defaults::FILE_UPLOAD_MAX_BYTES)
);
}
@ -1898,10 +1892,10 @@ permission = "write"
#[test]
fn builtin_defaults_merged_into_minimal_resolves_with_defaults() {
// Starting from builtin_defaults and overlaying only the
// required fields must resolve to a WorkerManifest carrying the
// required fields must resolve to a PodManifest carrying the
// centralised default values.
let overlay = WorkerManifestConfig {
worker: WorkerMetaConfig {
let overlay = PodManifestConfig {
pod: PodMetaConfig {
name: Some("x".into()),
prompt_pack: None,
},
@ -1912,7 +1906,7 @@ permission = "write"
},
scope: ScopeConfig {
allow: vec![ScopeRule {
target: abs("/worker"),
target: abs("/pod"),
permission: Permission::Write,
recursive: true,
}],
@ -1920,22 +1914,22 @@ permission = "write"
},
..Default::default()
};
let merged = WorkerManifestConfig::builtin_defaults().merge(overlay);
let manifest: WorkerManifest = merged.try_into().unwrap();
let merged = PodManifestConfig::builtin_defaults().merge(overlay);
let manifest: PodManifest = merged.try_into().unwrap();
assert_eq!(
manifest.engine.tool_output.default_max_bytes,
manifest.worker.tool_output.default_max_bytes,
defaults::TOOL_OUTPUT_MAX_BYTES
);
assert_eq!(
manifest.engine.file_upload.max_bytes,
manifest.worker.file_upload.max_bytes,
defaults::FILE_UPLOAD_MAX_BYTES
);
}
#[test]
fn end_to_end_cascade() {
let builtin = WorkerManifestConfig::default();
let user = WorkerManifestConfig::from_toml(
let builtin = PodManifestConfig::default();
let user = PodManifestConfig::from_toml(
r#"
[model]
scheme = "anthropic"
@ -1943,7 +1937,7 @@ model_id = "claude-sonnet-4-20250514"
"#,
)
.unwrap();
let project = WorkerManifestConfig::from_toml(
let project = PodManifestConfig::from_toml(
r#"
[[scope.allow]]
target = "/abs/project"
@ -1951,17 +1945,17 @@ permission = "write"
"#,
)
.unwrap();
let overlay = WorkerManifestConfig::from_toml(
let overlay = PodManifestConfig::from_toml(
r#"
[worker]
[pod]
name = "dbg"
"#,
)
.unwrap();
let merged = builtin.merge(user).merge(project).merge(overlay);
let manifest: WorkerManifest = merged.try_into().unwrap();
assert_eq!(manifest.worker.name, "dbg");
let manifest: PodManifest = merged.try_into().unwrap();
assert_eq!(manifest.pod.name, "dbg");
assert_eq!(manifest.model.scheme, Some(SchemeKind::Anthropic));
assert_eq!(manifest.scope.allow.len(), 1);
}
@ -1987,7 +1981,7 @@ name = "dbg"
cfg.skills = Some(SkillsConfig {
directories: vec![PathBuf::from("relative/skills")],
});
let err = WorkerManifest::try_from(cfg).unwrap_err();
let err = PodManifest::try_from(cfg).unwrap_err();
assert!(matches!(
err,
ResolveError::RelativePath {
@ -1999,13 +1993,13 @@ name = "dbg"
#[test]
fn skills_merge_extends_directories() {
let lower = WorkerManifestConfig {
let lower = PodManifestConfig {
skills: Some(SkillsConfig {
directories: vec![PathBuf::from("/a")],
}),
..Default::default()
};
let upper = WorkerManifestConfig {
let upper = PodManifestConfig {
skills: Some(SkillsConfig {
directories: vec![PathBuf::from("/b")],
}),
@ -2019,13 +2013,13 @@ name = "dbg"
#[test]
fn from_toml_parses_skills_section() {
let toml = r#"
[worker]
[pod]
name = "x"
[skills]
directories = [".claude/skills", ".cursor/skills"]
"#;
let cfg = WorkerManifestConfig::from_toml(toml).unwrap();
let cfg = PodManifestConfig::from_toml(toml).unwrap();
let dirs = cfg.skills.unwrap().directories;
assert_eq!(
dirs,
@ -2038,14 +2032,14 @@ directories = [".claude/skills", ".cursor/skills"]
#[test]
fn merge_preserves_ref() {
let lower = WorkerManifestConfig {
let lower = PodManifestConfig {
model: ModelManifest {
ref_: Some("anthropic/claude-sonnet-4-6".into()),
..Default::default()
},
..Default::default()
};
let upper = WorkerManifestConfig {
let upper = PodManifestConfig {
model: ModelManifest {
// only override auth
auth: Some(AuthRef::None),

View File

@ -1,7 +1,7 @@
//! Single source of truth for manifest default values.
//!
//! Every default that would otherwise be duplicated between serde
//! `#[serde(default = "...")]` attributes (on [`crate::WorkerManifest`])
//! `#[serde(default = "...")]` attributes (on [`crate::PodManifest`])
//! and the cascade resolution in [`crate::config`] lives here as a
//! `pub const`. Both paths read from this module, so changing a
//! default requires editing exactly one line.
@ -48,7 +48,7 @@ pub const COMPACT_OVERVIEW_DEADLINE_TOKENS: u64 = 40_000;
pub const DEFAULT_INSTRUCTION: &str = "$yoi/default";
/// Default language policy used by the main worker for normal prose
/// responses. See [`crate::EngineManifest::language`].
/// responses. See [`crate::WorkerManifest::language`].
pub const WORKER_LANGUAGE: &str =
"match the user's language unless they explicitly request another language";

View File

@ -7,9 +7,9 @@ mod profile;
mod scope;
pub use config::{
CompactionConfigPartial, EngineManifestConfig, FileUploadLimitsPartial,
PermissionConfigPartial, ResolveError, SessionConfigPartial, ToolOutputLimitsPartial,
WorkerManifestConfig, WorkerMetaConfig,
CompactionConfigPartial, FileUploadLimitsPartial, PermissionConfigPartial, PodManifestConfig,
PodMetaConfig, ResolveError, SessionConfigPartial, ToolOutputLimitsPartial,
WorkerManifestConfig,
};
pub use model::{
AuthRef, ModelCapability, ModelManifest, ReasoningControl, ReasoningEffort, SchemeKind,
@ -32,20 +32,20 @@ use std::path::PathBuf;
use serde::de::Error as _;
use serde::{Deserialize, Serialize};
/// Declarative configuration for a Worker.
/// Declarative configuration for a Pod.
///
/// Parsed from a TOML manifest file. Describes the model, system prompt,
/// and directory scope (required). The Worker's working directory is **not**
/// and directory scope (required). The Pod's working directory is **not**
/// part of the manifest — it is the process's `std::env::current_dir()`
/// at construction time.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct WorkerManifest {
pub worker: WorkerMeta,
pub struct PodManifest {
pub pod: PodMeta,
pub model: ModelManifest,
pub engine: EngineManifest,
/// Direct filesystem authority for this Worker's own tools.
pub worker: WorkerManifest,
/// Direct filesystem authority for this Pod's own tools.
pub scope: ScopeConfig,
/// Filesystem authority this Worker may pass to spawned children. Missing
/// Filesystem authority this Pod may pass to spawned children. Missing
/// metadata/config defaults to no delegation authority.
#[serde(default)]
pub delegation_scope: ScopeConfig,
@ -91,14 +91,14 @@ pub struct WorkerManifest {
#[serde(default)]
pub skills: Option<SkillsConfig>,
/// Optional profile provenance for manifests produced by profile resolution.
/// Stored only after profile resolution so Worker restore can prefer the
/// Stored only after profile resolution so Pod restore can prefer the
/// validated snapshot over current profile files or one-file Manifest input.
#[serde(default, skip_serializing_if = "Option::is_none")]
pub profile: Option<profile::ProfileManifestSnapshot>,
}
/// Explicit built-in feature/tool-surface enablement. These flags are
/// profile/config data only: they do not carry runtime Worker names, sockets,
/// profile/config data only: they do not carry runtime Pod names, sockets,
/// sessions, secrets, or resolved host state. Tool registration still applies
/// the normal scope, host-authority, backend, memory, and network checks.
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
@ -110,7 +110,7 @@ pub struct FeatureConfig {
#[serde(default)]
pub web: FeatureFlagConfig,
#[serde(default)]
pub workers: FeatureFlagConfig,
pub pods: FeatureFlagConfig,
#[serde(default)]
pub ticket: TicketFeatureConfig,
#[serde(default)]
@ -125,7 +125,7 @@ impl Default for FeatureConfig {
task: FeatureFlagConfig::disabled(),
memory: FeatureFlagConfig::disabled(),
web: FeatureFlagConfig::disabled(),
workers: FeatureFlagConfig::disabled(),
pods: FeatureFlagConfig::disabled(),
ticket: TicketFeatureConfig::default(),
ticket_orchestration: FeatureFlagConfig::disabled(),
plugins: FeatureFlagConfig::disabled(),
@ -197,7 +197,7 @@ pub struct SkillsConfig {
/// Skills *roots*. Children of each root must be individual
/// `<name>/SKILL.md` bundles; the directory itself is not a skill.
/// Resolved against the manifest base directory before
/// [`WorkerManifest`] is materialised.
/// [`PodManifest`] is materialised.
#[serde(default)]
pub directories: Vec<PathBuf>,
}
@ -206,7 +206,7 @@ pub struct SkillsConfig {
///
/// The manifest layer records local stdio MCP server declarations but never
/// starts them. Future lifecycle code must opt in to spawning and must keep MCP
/// process authority separate from Plugin permissions and `worker::feature` flags.
/// process authority separate from Plugin permissions and `pod::feature` flags.
#[derive(Debug, Clone, Default, Serialize, Deserialize, PartialEq, Eq)]
#[serde(deny_unknown_fields)]
pub struct McpConfig {
@ -363,7 +363,7 @@ pub struct WebFetchConfig {
/// Memory subsystem configuration. Presence in the manifest enables
/// memory; `workspace_root` pins the memory workspace explicitly. When it
/// is absent, memory resolution searches upward from the Worker's pwd for a
/// is absent, memory resolution searches upward from the Pod's pwd for a
/// `.yoi/memory` marker rather than treating `.yoi` project records alone
/// as a memory root.
///
@ -396,7 +396,7 @@ pub struct MemoryConfig {
#[serde(default)]
pub language: Option<String>,
/// Optional model for the extract worker. When `None`,
/// the main engine model is cloned via `clone_boxed()`. Lightweight
/// the main pod model is cloned via `clone_boxed()`. Lightweight
/// reasoning-capable models (Haiku / 4o-mini / Flash class) are
/// recommended.
#[serde(default)]
@ -414,7 +414,7 @@ pub struct MemoryConfig {
#[serde(default)]
pub extract_worker_max_turns: Option<u32>,
/// Optional model for the consolidation worker. When
/// `None`, the main engine model is cloned via `clone_boxed()`.
/// `None`, the main pod model is cloned via `clone_boxed()`.
/// Reasoning-class models are recommended.
#[serde(default)]
pub consolidation_model: Option<ModelManifest>,
@ -432,12 +432,12 @@ pub struct MemoryConfig {
pub consolidation_threshold_bytes: Option<u64>,
}
/// Worker metadata.
/// Pod metadata.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct WorkerMeta {
pub struct PodMeta {
pub name: String,
/// Optional path to a TOML override file read as the top layer of
/// `worker::PromptCatalog`. Subject to the same relative-path
/// `pod::PromptCatalog`. Subject to the same relative-path
/// resolution as other manifest paths (joined against the
/// manifest's base directory). `None` leaves the 4th overlay layer
/// empty; auto-discovered user and workspace packs still apply.
@ -453,7 +453,7 @@ pub struct WorkerMeta {
/// Worker-level configuration embedded in the manifest.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct EngineManifest {
pub struct WorkerManifest {
/// Reference to the instruction prompt asset used as the body of
/// the worker's system prompt. Uses the `PromptLoader` prefix
/// addressing scheme (`$yoi/...`, `$user/...`,
@ -572,7 +572,7 @@ impl ToolOutputLimits {
/// Declarative scope configuration.
///
/// A Worker may only touch paths whose effective permission (computed from
/// A Pod may only touch paths whose effective permission (computed from
/// allow/deny rules below) is at least `Read` / `Write`. See
/// [`Scope`] for the resolved runtime form.
#[derive(Debug, Clone, Default, Serialize, Deserialize)]
@ -653,7 +653,7 @@ pub struct CompactionConfig {
/// Safety-net (between-requests) compaction threshold.
///
/// Checked by `WorkerInterceptor::pre_llm_request` inside a turn. When
/// Checked by `PodInterceptor::pre_llm_request` inside a turn. When
/// current occupancy exceeds this value, the run yields so that the
/// Controller can compact before the next LLM request. `None`
/// disables the between-requests check.
@ -802,7 +802,7 @@ impl Default for CompactionConfig {
}
}
impl WorkerManifest {
impl PodManifest {
/// Parse a manifest from a TOML string.
pub fn from_toml(s: &str) -> Result<Self, toml::de::Error> {
config::reject_removed_manifest_fields(s)?;
@ -818,14 +818,14 @@ mod tests {
use super::*;
const MINIMAL_REQUIRED: &str = r#"
[worker]
[pod]
name = "test-agent"
[model]
scheme = "anthropic"
model_id = "claude-sonnet-4-20250514"
[engine]
[worker]
[[scope.allow]]
target = "/abs/scope"
@ -834,8 +834,8 @@ permission = "write"
#[test]
fn parse_minimal_manifest() {
let manifest = WorkerManifest::from_toml(MINIMAL_REQUIRED).unwrap();
assert_eq!(manifest.worker.name, "test-agent");
let manifest = PodManifest::from_toml(MINIMAL_REQUIRED).unwrap();
assert_eq!(manifest.pod.name, "test-agent");
assert_eq!(manifest.model.scheme, Some(SchemeKind::Anthropic));
assert_eq!(
manifest.model.model_id.as_deref(),
@ -846,19 +846,19 @@ permission = "write"
assert!(manifest.scope.deny.is_empty());
assert!(manifest.delegation_scope.allow.is_empty());
assert!(manifest.delegation_scope.deny.is_empty());
assert_eq!(manifest.engine.instruction, defaults::DEFAULT_INSTRUCTION);
assert!(manifest.engine.top_p.is_none());
assert!(manifest.engine.top_k.is_none());
assert!(manifest.engine.stop_sequences.is_empty());
assert_eq!(manifest.worker.instruction, defaults::DEFAULT_INSTRUCTION);
assert!(manifest.worker.top_p.is_none());
assert!(manifest.worker.top_k.is_none());
assert!(manifest.worker.stop_sequences.is_empty());
assert!(manifest.web.is_none());
}
#[test]
fn deserialize_old_manifest_snapshot_defaults_to_no_delegation() {
let manifest = WorkerManifest::from_toml(MINIMAL_REQUIRED).unwrap();
let manifest = PodManifest::from_toml(MINIMAL_REQUIRED).unwrap();
let mut snapshot = serde_json::to_value(&manifest).unwrap();
snapshot.as_object_mut().unwrap().remove("delegation_scope");
let restored: WorkerManifest = serde_json::from_value(snapshot).unwrap();
let restored: PodManifest = serde_json::from_value(snapshot).unwrap();
assert_eq!(restored.scope.allow.len(), 1);
assert!(restored.delegation_scope.allow.is_empty());
assert!(restored.delegation_scope.deny.is_empty());
@ -870,7 +870,7 @@ permission = "write"
"{}\n[web]\nenabled = true\n\n[web.search]\nprovider = \"brave\"\napi_key_secret = \"web/brave/default\"\ntimeout_secs = 12\n\n[web.fetch]\ntimeout_secs = 7\nredirect_limit = 3\nmax_response_bytes = 12345\nmax_output_bytes = 2048\n",
MINIMAL_REQUIRED
);
let manifest = WorkerManifest::from_toml(&toml).unwrap();
let manifest = PodManifest::from_toml(&toml).unwrap();
let web = manifest.web.unwrap();
assert_eq!(web.enabled, Some(true));
let search = web.search.unwrap();
@ -886,7 +886,7 @@ permission = "write"
#[test]
fn parse_full_manifest() {
let toml = r#"
[worker]
[pod]
name = "code-reviewer"
[model]
@ -894,7 +894,7 @@ scheme = "anthropic"
model_id = "claude-sonnet-4-20250514"
auth = { kind = "api_key", file = "/abs/keys/anthropic" }
[engine]
[worker]
instruction = "$user/reviewer"
max_tokens = 4096
temperature = 0.3
@ -924,21 +924,21 @@ permission = "write"
target = "/abs/project/tasks/private"
permission = "write"
"#;
let manifest = WorkerManifest::from_toml(toml).unwrap();
assert_eq!(manifest.worker.name, "code-reviewer");
let manifest = PodManifest::from_toml(toml).unwrap();
assert_eq!(manifest.pod.name, "code-reviewer");
let file = match manifest.model.auth.as_ref() {
Some(AuthRef::ApiKey { file, .. }) => file.as_deref(),
_ => panic!("expected ApiKey"),
};
assert_eq!(file, Some(std::path::Path::new("/abs/keys/anthropic")));
assert_eq!(manifest.engine.instruction, "$user/reviewer");
assert_eq!(manifest.engine.max_tokens, Some(4096));
assert_eq!(manifest.engine.temperature, Some(0.3));
assert_eq!(manifest.engine.top_p, Some(0.9));
assert_eq!(manifest.engine.top_k, Some(40));
assert_eq!(manifest.engine.stop_sequences, vec!["\n\n", "</stop>"]);
assert_eq!(manifest.worker.instruction, "$user/reviewer");
assert_eq!(manifest.worker.max_tokens, Some(4096));
assert_eq!(manifest.worker.temperature, Some(0.3));
assert_eq!(manifest.worker.top_p, Some(0.9));
assert_eq!(manifest.worker.top_k, Some(40));
assert_eq!(manifest.worker.stop_sequences, vec!["\n\n", "</stop>"]);
assert_eq!(
manifest.engine.reasoning,
manifest.worker.reasoning,
Some(ReasoningControl::Effort(ReasoningEffort::Medium))
);
let allow = &manifest.scope.allow;
@ -960,16 +960,16 @@ permission = "write"
#[test]
fn reject_missing_scope() {
let toml = r#"
[worker]
[pod]
name = "missing-scope"
[model]
scheme = "anthropic"
model_id = "claude-sonnet-4-20250514"
[engine]
[worker]
"#;
assert!(WorkerManifest::from_toml(toml).is_err());
assert!(PodManifest::from_toml(toml).is_err());
}
#[test]
@ -984,7 +984,7 @@ model_id = "claude-sonnet-4-20250514"
[plugins.enabled.config]\n\
greeting = \"hello\"\n"
);
let manifest = WorkerManifest::from_toml(&toml).unwrap();
let manifest = PodManifest::from_toml(&toml).unwrap();
assert_eq!(manifest.plugins.enabled.len(), 1);
let enabled = &manifest.plugins.enabled[0];
assert_eq!(enabled.id, "project:example");
@ -1005,37 +1005,37 @@ model_id = "claude-sonnet-4-20250514"
#[test]
fn parse_max_turns() {
let toml = MINIMAL_REQUIRED.replace("[engine]\n", "[engine]\nmax_turns = 50\n");
let manifest = WorkerManifest::from_toml(&toml).unwrap();
assert_eq!(manifest.engine.max_turns.unwrap().get(), 50);
let toml = MINIMAL_REQUIRED.replace("[worker]\n", "[worker]\nmax_turns = 50\n");
let manifest = PodManifest::from_toml(&toml).unwrap();
assert_eq!(manifest.worker.max_turns.unwrap().get(), 50);
}
#[test]
fn parse_reasoning_budget() {
let toml = MINIMAL_REQUIRED.replace("[engine]\n", "[engine]\nreasoning = -1\n");
let manifest = WorkerManifest::from_toml(&toml).unwrap();
let toml = MINIMAL_REQUIRED.replace("[worker]\n", "[worker]\nreasoning = -1\n");
let manifest = PodManifest::from_toml(&toml).unwrap();
assert_eq!(
manifest.engine.reasoning,
manifest.worker.reasoning,
Some(ReasoningControl::BudgetTokens(-1))
);
}
#[test]
fn omitted_max_turns_is_none() {
let manifest = WorkerManifest::from_toml(MINIMAL_REQUIRED).unwrap();
assert!(manifest.engine.max_turns.is_none());
let manifest = PodManifest::from_toml(MINIMAL_REQUIRED).unwrap();
assert!(manifest.worker.max_turns.is_none());
}
#[test]
fn reject_max_turns_zero() {
let toml = MINIMAL_REQUIRED.replace("[engine]\n", "[engine]\nmax_turns = 0\n");
assert!(WorkerManifest::from_toml(&toml).is_err());
let toml = MINIMAL_REQUIRED.replace("[worker]\n", "[worker]\nmax_turns = 0\n");
assert!(PodManifest::from_toml(&toml).is_err());
}
#[test]
fn parse_compaction_config() {
let toml = format!("{MINIMAL_REQUIRED}\n[compaction]\nthreshold = 80000\n");
let manifest = WorkerManifest::from_toml(&toml).unwrap();
let manifest = PodManifest::from_toml(&toml).unwrap();
let c = manifest.compaction.unwrap();
assert_eq!(c.prune_protected_tokens, 8000);
assert_eq!(c.prune_min_savings, 4096);
@ -1048,7 +1048,7 @@ model_id = "claude-sonnet-4-20250514"
#[test]
fn reject_removed_prune_protected_turns_field() {
let toml = format!("{MINIMAL_REQUIRED}\n[compaction]\nprune_protected_turns = 3\n");
let err = WorkerManifest::from_toml(&toml).unwrap_err();
let err = PodManifest::from_toml(&toml).unwrap_err();
assert!(
err.to_string().contains("compaction.prune_protected_turns"),
"unexpected error: {err}"
@ -1062,7 +1062,7 @@ model_id = "claude-sonnet-4-20250514"
[compaction]\n\
worker_max_turns = 7\n"
);
let manifest = WorkerManifest::from_toml(&toml).unwrap();
let manifest = PodManifest::from_toml(&toml).unwrap();
let c = manifest.compaction.unwrap();
assert_eq!(c.worker_max_turns, Some(7));
}
@ -1075,7 +1075,7 @@ model_id = "claude-sonnet-4-20250514"
threshold = 80000\n\
request_threshold = 90000\n"
);
let manifest = WorkerManifest::from_toml(&toml).unwrap();
let manifest = PodManifest::from_toml(&toml).unwrap();
let c = manifest.compaction.unwrap();
assert_eq!(c.threshold, Some(80000));
assert_eq!(c.request_threshold, Some(90000));
@ -1088,7 +1088,7 @@ model_id = "claude-sonnet-4-20250514"
[compaction]\n\
request_threshold = 90000\n"
);
let manifest = WorkerManifest::from_toml(&toml).unwrap();
let manifest = PodManifest::from_toml(&toml).unwrap();
let c = manifest.compaction.unwrap();
assert_eq!(c.threshold, None);
assert_eq!(c.request_threshold, Some(90000));
@ -1104,7 +1104,7 @@ model_id = "claude-sonnet-4-20250514"
scheme = \"gemini\"\n\
model_id = \"gemini-2.0-flash\"\n"
);
let manifest = WorkerManifest::from_toml(&toml).unwrap();
let manifest = PodManifest::from_toml(&toml).unwrap();
let c = manifest.compaction.unwrap();
let p = c.model.unwrap();
assert_eq!(p.scheme, Some(SchemeKind::Gemini));
@ -1113,20 +1113,20 @@ model_id = "claude-sonnet-4-20250514"
#[test]
fn omitted_compaction_is_none() {
let manifest = WorkerManifest::from_toml(MINIMAL_REQUIRED).unwrap();
let manifest = PodManifest::from_toml(MINIMAL_REQUIRED).unwrap();
assert!(manifest.compaction.is_none());
}
#[test]
fn omitted_memory_is_none() {
let manifest = WorkerManifest::from_toml(MINIMAL_REQUIRED).unwrap();
let manifest = PodManifest::from_toml(MINIMAL_REQUIRED).unwrap();
assert!(manifest.memory.is_none());
}
#[test]
fn empty_memory_section_enables_with_default_root() {
let toml = format!("{MINIMAL_REQUIRED}\n[memory]\n");
let manifest = WorkerManifest::from_toml(&toml).unwrap();
let manifest = PodManifest::from_toml(&toml).unwrap();
let mem = manifest.memory.expect("memory section parsed");
assert!(mem.workspace_root.is_none());
assert_eq!(mem.inject_summary, None);
@ -1135,7 +1135,7 @@ model_id = "claude-sonnet-4-20250514"
#[test]
fn memory_section_with_inject_summary_false() {
let toml = format!("{MINIMAL_REQUIRED}\n[memory]\ninject_summary = false\n");
let manifest = WorkerManifest::from_toml(&toml).unwrap();
let manifest = PodManifest::from_toml(&toml).unwrap();
let mem = manifest.memory.unwrap();
assert_eq!(mem.inject_summary, Some(false));
}
@ -1143,7 +1143,7 @@ model_id = "claude-sonnet-4-20250514"
#[test]
fn memory_section_with_explicit_root() {
let toml = format!("{MINIMAL_REQUIRED}\n[memory]\nworkspace_root = \"/some/where\"\n");
let manifest = WorkerManifest::from_toml(&toml).unwrap();
let manifest = PodManifest::from_toml(&toml).unwrap();
let mem = manifest.memory.unwrap();
assert_eq!(
mem.workspace_root.unwrap(),
@ -1154,7 +1154,7 @@ model_id = "claude-sonnet-4-20250514"
#[test]
fn memory_section_with_language() {
let toml = format!("{MINIMAL_REQUIRED}\n[memory]\nlanguage = \"Japanese\"\n");
let manifest = WorkerManifest::from_toml(&toml).unwrap();
let manifest = PodManifest::from_toml(&toml).unwrap();
let mem = manifest.memory.unwrap();
assert_eq!(mem.language.as_deref(), Some("Japanese"));
}
@ -1163,62 +1163,62 @@ model_id = "claude-sonnet-4-20250514"
fn reject_unknown_scheme() {
let toml =
MINIMAL_REQUIRED.replace("scheme = \"anthropic\"", "scheme = \"unknown_scheme\"");
assert!(WorkerManifest::from_toml(&toml).is_err());
assert!(PodManifest::from_toml(&toml).is_err());
}
#[test]
fn omitted_limits_fall_back_to_defaults() {
let manifest = WorkerManifest::from_toml(MINIMAL_REQUIRED).unwrap();
let limits = &manifest.engine.tool_output;
let manifest = PodManifest::from_toml(MINIMAL_REQUIRED).unwrap();
let limits = &manifest.worker.tool_output;
assert_eq!(limits.default_max_bytes, defaults::TOOL_OUTPUT_MAX_BYTES);
assert!(limits.per_tool.is_empty());
assert_eq!(
manifest.engine.file_upload.max_bytes,
manifest.worker.file_upload.max_bytes,
defaults::FILE_UPLOAD_MAX_BYTES
);
}
#[test]
fn worker_language_defaults_and_parses() {
let manifest = WorkerManifest::from_toml(MINIMAL_REQUIRED).unwrap();
assert_eq!(manifest.engine.language, defaults::WORKER_LANGUAGE);
let manifest = PodManifest::from_toml(MINIMAL_REQUIRED).unwrap();
assert_eq!(manifest.worker.language, defaults::WORKER_LANGUAGE);
let toml = MINIMAL_REQUIRED.replace("[engine]\n", "[engine]\nlanguage = \"Japanese\"\n");
let manifest = WorkerManifest::from_toml(&toml).unwrap();
assert_eq!(manifest.engine.language, "Japanese");
let toml = MINIMAL_REQUIRED.replace("[worker]\n", "[worker]\nlanguage = \"Japanese\"\n");
let manifest = PodManifest::from_toml(&toml).unwrap();
assert_eq!(manifest.worker.language, "Japanese");
}
#[test]
fn parse_worker_output_limits() {
let toml = MINIMAL_REQUIRED.replace(
"[engine]\n",
"[engine]\n\
"[worker]\n",
"[worker]\n\
[worker.tool_output]\n\
default_max_bytes = 8192\n\n\
[worker.tool_output.per_tool]\n\
Read = 32768\n\
Grep = 4096\n\n\
[engine.file_upload]\n\
[worker.file_upload]\n\
max_bytes = 12345\n",
);
let manifest = WorkerManifest::from_toml(&toml).unwrap();
let limits = &manifest.engine.tool_output;
let manifest = PodManifest::from_toml(&toml).unwrap();
let limits = &manifest.worker.tool_output;
assert_eq!(limits.default_max_bytes, 8192);
assert_eq!(limits.limit_for("Read"), 32768);
assert_eq!(limits.limit_for("Grep"), 4096);
assert_eq!(limits.limit_for("Unknown"), 8192);
assert_eq!(manifest.engine.file_upload.max_bytes, 12345);
assert_eq!(manifest.worker.file_upload.max_bytes, 12345);
}
#[test]
fn empty_tool_output_section_uses_default_max_bytes() {
let toml = MINIMAL_REQUIRED.replace(
"[engine]\n",
"[engine]\n\
"[worker]\n",
"[worker]\n\
[worker.tool_output]\n",
);
let manifest = WorkerManifest::from_toml(&toml).unwrap();
let limits = &manifest.engine.tool_output;
let manifest = PodManifest::from_toml(&toml).unwrap();
let limits = &manifest.worker.tool_output;
assert_eq!(limits.default_max_bytes, defaults::TOOL_OUTPUT_MAX_BYTES);
assert!(limits.per_tool.is_empty());
}

View File

@ -1,6 +1,6 @@
//! LLM モデル宣言型
//!
//! Worker マニフェストの `[model]` セクションで記述する型。`ref`(プロバイダ
//! Pod マニフェストの `[model]` セクションで記述する型。`ref`(プロバイダ
//! とモデルを両方指し示す短縮形)と inline 指定(`scheme` / `model_id`
//! 直書き)の両方を受け入れるため、すべてのフィールドを `Option` として
//! 持つ 1 つの型 [`ModelManifest`] に統合している。実解決ref をプロバイダ
@ -18,7 +18,7 @@ use serde::{Deserialize, Serialize};
// マニフェストで任意に override できるよう型だけ再エクスポートする。
pub use llm_engine::llm_client::capability::{ModelCapability, ReasoningControl, ReasoningEffort};
/// Worker マニフェストの `[model]` セクション。
/// Pod マニフェストの `[model]` セクション。
///
/// - ref だけ書く: `[model] ref = "anthropic/claude-sonnet-4-6"`
/// - ref + 一部 override: ref で基底を引き、`auth` 等だけ書き換え

View File

@ -6,7 +6,7 @@
//! `providers.toml`, `models.toml`, `prompts/`, `prompts.toml` 等
//! - **`data_dir`** — プログラムが書く永続データ。`sessions/` 等
//! - **`runtime_dir`** — 再起動で消えてよいランタイム状態。socket,
//! `workers.json`, `pid` ファイル等
//! `pods.json`, `pid` ファイル等
//!
//! ## 解決順 (優先順位高 → 低)
//!
@ -46,7 +46,7 @@ pub fn data_dir() -> Option<PathBuf> {
)
}
/// ランタイムディレクトリ。socket, `workers.json`, Worker ごとの `pid` /
/// ランタイムディレクトリ。socket, `pods.json`, Pod ごとの `pid` /
/// `status.json` 等が置かれる。再起動で消えて構わない。
pub fn runtime_dir() -> Option<PathBuf> {
resolve_runtime_dir_from_parts(
@ -61,7 +61,7 @@ pub fn runtime_dir() -> Option<PathBuf> {
/// `<config_dir>/profiles.toml` — user profile registry/default configuration.
///
/// This is application/profile selection configuration, not a Worker manifest
/// This is application/profile selection configuration, not a Pod manifest
/// layer.
pub fn user_profiles_path() -> Option<PathBuf> {
user_profiles_path_from_config_dir(config_dir())
@ -88,24 +88,24 @@ pub fn sessions_dir() -> Option<PathBuf> {
sessions_dir_from_data_dir(data_dir())
}
/// `<runtime_dir>/workers.json` — machine-wide Worker allocation registry。
/// `<runtime_dir>/pods.json` — machine-wide Pod allocation registry。
pub fn pod_registry_path() -> Option<PathBuf> {
pod_registry_path_from_runtime_dir(runtime_dir())
}
/// `<runtime_dir>/<worker_name>/` — Worker ごとのランタイムディレクトリ。
pub fn worker_runtime_dir(worker_name: &str) -> Option<PathBuf> {
worker_runtime_dir_from_runtime_dir(runtime_dir(), worker_name)
/// `<runtime_dir>/<pod_name>/` — Pod ごとのランタイムディレクトリ。
pub fn pod_runtime_dir(pod_name: &str) -> Option<PathBuf> {
pod_runtime_dir_from_runtime_dir(runtime_dir(), pod_name)
}
/// `<runtime_dir>/<worker_name>/sock` — Worker の Unix socket パス。
/// `<runtime_dir>/<pod_name>/sock` — Pod の Unix socket パス。
///
/// Worker プロセス内で実際に socket を作成するのは `worker` crate の
/// `RuntimeDir::socket_path()` で、Worker 名が分かっている外部 (TUI の
/// Pod プロセス内で実際に socket を作成するのは `pod` crate の
/// `RuntimeDir::socket_path()` で、Pod 名が分かっている外部 (TUI の
/// attach フロー等) からの**予測**はこの関数で行う。両者は同じパス
/// を返すことが期待される。
pub fn pod_socket_path(worker_name: &str) -> Option<PathBuf> {
pod_socket_path_from_runtime_dir(runtime_dir(), worker_name)
pub fn pod_socket_path(pod_name: &str) -> Option<PathBuf> {
pod_socket_path_from_runtime_dir(runtime_dir(), pod_name)
}
// ---- internals --------------------------------------------------------------
@ -184,21 +184,21 @@ fn sessions_dir_from_data_dir(data_dir: Option<PathBuf>) -> Option<PathBuf> {
}
fn pod_registry_path_from_runtime_dir(runtime_dir: Option<PathBuf>) -> Option<PathBuf> {
Some(runtime_dir?.join("workers.json"))
Some(runtime_dir?.join("pods.json"))
}
fn worker_runtime_dir_from_runtime_dir(
fn pod_runtime_dir_from_runtime_dir(
runtime_dir: Option<PathBuf>,
worker_name: &str,
pod_name: &str,
) -> Option<PathBuf> {
Some(runtime_dir?.join(worker_name))
Some(runtime_dir?.join(pod_name))
}
fn pod_socket_path_from_runtime_dir(
runtime_dir: Option<PathBuf>,
worker_name: &str,
pod_name: &str,
) -> Option<PathBuf> {
Some(worker_runtime_dir_from_runtime_dir(runtime_dir, worker_name)?.join("sock"))
Some(pod_runtime_dir_from_runtime_dir(runtime_dir, pod_name)?.join("sock"))
}
/// 空文字列の env は未設定として扱う。`std::env::var` は `Ok("")` と
@ -397,10 +397,10 @@ mod tests {
);
assert_eq!(
pod_registry_path_from_runtime_dir(runtime_dir.clone()).unwrap(),
PathBuf::from("/sand/run/workers.json")
PathBuf::from("/sand/run/pods.json")
);
assert_eq!(
worker_runtime_dir_from_runtime_dir(runtime_dir.clone(), "foo").unwrap(),
pod_runtime_dir_from_runtime_dir(runtime_dir.clone(), "foo").unwrap(),
PathBuf::from("/sand/run/foo")
);
assert_eq!(

View File

@ -2,7 +2,7 @@
//!
//! Profiles are reusable, human-authored recipes. They are intentionally not
//! complete runtime manifests: runtime-bound and authority-bearing fields such
//! as `worker.name` and concrete `scope.allow` rules are supplied by the resolver
//! as `pod.name` and concrete `scope.allow` rules are supplied by the resolver
//! from launch context.
use std::cell::RefCell;
@ -19,9 +19,9 @@ use crate::config::{
use crate::model::{AuthRef, ModelManifest};
use crate::plugin::PluginConfig;
use crate::{
EngineManifestConfig, McpConfig, McpStdioCwdPolicy, MemoryConfig, Permission, ResolveError,
ScopeConfig, ScopeRule, SkillsConfig, WebConfig, WorkerManifest, WorkerManifestConfig,
WorkerMetaConfig, paths,
McpConfig, McpStdioCwdPolicy, MemoryConfig, Permission, PodManifest, PodManifestConfig,
PodMetaConfig, ResolveError, ScopeConfig, ScopeRule, SkillsConfig, WebConfig,
WorkerManifestConfig, paths,
};
const PROFILE_FORMAT_V1: &str = "yoi.lua-profile.v1";
@ -408,26 +408,26 @@ pub struct WorkspaceOverrideSnapshot {
#[derive(Debug)]
struct WorkspaceOverrideLayer {
path: PathBuf,
config: WorkerManifestConfig,
config: PodManifestConfig,
}
#[derive(Debug, Clone)]
pub struct ResolvedProfile {
pub source: ProfileSource,
pub profile: Option<ProfileMetadata>,
pub manifest: WorkerManifest,
pub manifest: PodManifest,
pub manifest_snapshot: serde_json::Value,
pub raw_artifact: serde_json::Value,
}
#[derive(Debug, Clone, Default)]
pub struct ProfileResolveOptions {
pub worker_name: Option<String>,
pub pod_name: Option<String>,
}
impl ProfileResolveOptions {
pub fn with_worker_name(name: impl Into<String>) -> Self {
pub fn with_pod_name(name: impl Into<String>) -> Self {
Self {
worker_name: Some(name.into()),
pod_name: Some(name.into()),
}
}
}
@ -469,8 +469,8 @@ impl ProfileResolver {
}
}
/// Resolve a registry/default selector against an already-discovered
/// registry. Callers such as SpawnWorker use this to bind discovery to the
/// Worker's cwd instead of the process current directory.
/// registry. Callers such as SpawnPod use this to bind discovery to the
/// Pod's cwd instead of the process current directory.
pub fn resolve_from_registry(
&self,
selector: &ProfileSelector,
@ -604,22 +604,22 @@ fn resolve_lua_profile_value(
let profile: ProfileConfig = serde_json::from_value(value.clone())
.map_err(|source| ProfileError::ProfileDeserialize { source })?;
validate_profile_paths(&profile)?;
let worker_name = options
.worker_name
.ok_or(ProfileError::MissingRuntimeWorkerName)?;
let pod_name = options
.pod_name
.ok_or(ProfileError::MissingRuntimePodName)?;
let profile_meta = Some(ProfileMetadata {
name: profile.slug.clone().or_else(|| source_name(&source)),
description: profile.description.clone(),
format: Some(PROFILE_FORMAT_V1.to_string()),
});
let compaction = profile_compaction_to_partial(profile.compaction, &profile.model)?;
let config = WorkerManifestConfig {
worker: WorkerMetaConfig {
name: Some(worker_name),
let config = PodManifestConfig {
pod: PodMetaConfig {
name: Some(pod_name),
prompt_pack: None,
},
model: profile.model.unwrap_or_default(),
engine: profile.engine.unwrap_or_default(),
worker: profile.worker.unwrap_or_default(),
scope: profile_scope_to_config(profile.scope, workspace_base)?,
delegation_scope: profile_delegation_scope_to_config(
profile.delegation_scope,
@ -635,8 +635,7 @@ fn resolve_lua_profile_value(
memory: profile.memory,
skills: profile.skills,
};
let mut config =
WorkerManifestConfig::builtin_defaults().merge(config.resolve_paths(profile_dir));
let mut config = PodManifestConfig::builtin_defaults().merge(config.resolve_paths(profile_dir));
let workspace_override_snapshot = if let Some(override_layer) = workspace_override {
let override_base =
override_layer
@ -653,7 +652,7 @@ fn resolve_lua_profile_value(
} else {
None
};
let mut manifest = WorkerManifest::try_from(config).map_err(ProfileError::ManifestResolve)?;
let mut manifest = PodManifest::try_from(config).map_err(ProfileError::ManifestResolve)?;
manifest.profile = Some(ProfileManifestSnapshot {
source: source.clone(),
profile: profile_meta.clone(),
@ -680,7 +679,7 @@ struct ProfileConfig {
#[serde(default)]
model: Option<ModelManifest>,
#[serde(default)]
engine: Option<EngineManifestConfig>,
worker: Option<WorkerManifestConfig>,
#[serde(default)]
scope: Option<ProfileScopeConfig>,
#[serde(default)]
@ -815,16 +814,16 @@ fn load_workspace_override_file(path: &Path) -> Result<WorkspaceOverrideLayer, P
path: path.to_path_buf(),
source,
})?;
let config = WorkerManifestConfig::from_toml(&content).map_err(|source| {
let config = PodManifestConfig::from_toml(&content).map_err(|source| {
ProfileError::WorkspaceOverrideParse {
path: path.to_path_buf(),
source,
}
})?;
if config.worker.name.is_some() {
if config.pod.name.is_some() {
return Err(ProfileError::InvalidWorkspaceOverride {
path: path.to_path_buf(),
message: "workspace-local manifest overrides cannot set worker.name; Worker identity is a runtime input".into(),
message: "workspace-local manifest overrides cannot set pod.name; Pod identity is a runtime input".into(),
});
}
Ok(WorkspaceOverrideLayer {
@ -1210,8 +1209,8 @@ fn reject_manifest_shaped_profile(value: &serde_json::Value) -> Result<(), Profi
)));
}
}
if map.contains_key("worker") {
return Err(ProfileError::InvalidProfile("field `worker` is runtime-bound and is not allowed in reusable Profiles; pass the Worker name via CLI/TUI runtime inputs".into()));
if map.contains_key("pod") {
return Err(ProfileError::InvalidProfile("field `pod` is runtime-bound and is not allowed in reusable Profiles; pass the Pod name via CLI/TUI runtime inputs".into()));
}
if let Some(scope) = map.get("scope").and_then(|v| v.as_object()) {
for key in ["allow", "deny"] {
@ -1443,7 +1442,7 @@ pub fn resolve_profile_artifact(
source,
base_dir,
base_dir,
ProfileResolveOptions::with_worker_name("artifact-worker"),
ProfileResolveOptions::with_pod_name("artifact-pod"),
raw_artifact.clone(),
raw_artifact,
None,
@ -1490,8 +1489,8 @@ pub enum ProfileError {
InvalidWorkspaceOverride { path: PathBuf, message: String },
#[error("no default profile is configured")]
NoDefaultProfile,
#[error("profile resolution requires an explicit runtime Worker name")]
MissingRuntimeWorkerName,
#[error("profile resolution requires an explicit runtime Pod name")]
MissingRuntimePodName,
#[error("profile not found: {selector}")]
ProfileNotFound { selector: String },
#[error("ambiguous profile name `{name}`; use a source-qualified selector such as {matches:?}")]
@ -1575,17 +1574,17 @@ mod tests {
.with_workspace_base(tmp.path())
.resolve(
&ProfileSelector::source_named(ProfileRegistrySource::Builtin, expected),
ProfileResolveOptions::with_worker_name("role-worker"),
ProfileResolveOptions::with_pod_name("role-pod"),
)
.unwrap();
assert_eq!(
resolved.profile.as_ref().unwrap().name.as_deref(),
Some(expected)
);
assert_eq!(resolved.manifest.worker.name, "role-worker");
assert_eq!(resolved.manifest.pod.name, "role-pod");
if matches!(expected, "intake" | "orchestrator" | "coder" | "reviewer") {
let expected_instruction = format!("$yoi/role/{expected}");
assert_eq!(resolved.manifest.engine.instruction, expected_instruction);
assert_eq!(resolved.manifest.worker.instruction, expected_instruction);
}
}
}
@ -1598,7 +1597,7 @@ mod tests {
.with_workspace_base(tmp.path())
.resolve(
&ProfileSelector::source_named(ProfileRegistrySource::Builtin, role),
ProfileResolveOptions::with_worker_name("role-worker"),
ProfileResolveOptions::with_pod_name("role-pod"),
)
.unwrap()
.manifest
@ -1606,7 +1605,7 @@ mod tests {
let companion = resolve("companion");
assert!(companion.feature.task.enabled);
assert!(companion.feature.workers.enabled);
assert!(companion.feature.pods.enabled);
assert!(companion.feature.ticket.enabled);
assert!(companion.scope.allow.is_empty());
assert!(companion.scope.deny.is_empty());
@ -1616,7 +1615,7 @@ mod tests {
let intake = resolve("intake");
assert!(!intake.feature.task.enabled);
assert!(!intake.feature.workers.enabled);
assert!(!intake.feature.pods.enabled);
assert!(intake.feature.ticket.enabled);
assert!(intake.scope.allow.is_empty());
assert!(intake.delegation_scope.allow.is_empty());
@ -1626,7 +1625,7 @@ mod tests {
let orchestrator = resolve("orchestrator");
assert!(!orchestrator.feature.task.enabled);
assert!(orchestrator.feature.workers.enabled);
assert!(orchestrator.feature.pods.enabled);
assert!(orchestrator.feature.ticket.enabled);
assert!(orchestrator.feature.ticket_orchestration.enabled);
assert!(orchestrator.scope.allow.is_empty());
@ -1639,7 +1638,7 @@ mod tests {
let coder = resolve("coder");
assert!(coder.feature.task.enabled);
assert!(!coder.feature.workers.enabled);
assert!(!coder.feature.pods.enabled);
assert!(coder.scope.allow.is_empty());
assert!(coder.delegation_scope.allow.is_empty());
assert_eq!(coder.model.ref_.as_deref(), Some("codex-oauth/gpt-5.5"));
@ -1647,7 +1646,7 @@ mod tests {
let reviewer = resolve("reviewer");
assert!(!reviewer.feature.task.enabled);
assert!(!reviewer.feature.workers.enabled);
assert!(!reviewer.feature.pods.enabled);
assert!(!reviewer.feature.ticket.enabled);
assert!(reviewer.scope.allow.is_empty());
assert!(reviewer.delegation_scope.allow.is_empty());
@ -1656,17 +1655,17 @@ mod tests {
}
#[test]
fn profile_resolution_requires_runtime_worker_name() {
fn profile_resolution_requires_runtime_pod_name() {
let tmp = TempDir::new().unwrap();
let err = ProfileResolver::new()
.with_workspace_base(tmp.path())
.resolve(&ProfileSelector::Default, ProfileResolveOptions::default())
.unwrap_err();
assert!(matches!(err, ProfileError::MissingRuntimeWorkerName));
assert!(matches!(err, ProfileError::MissingRuntimePodName));
}
#[test]
fn resolves_plain_lua_profile_with_runtime_worker_name_and_scope_intent() {
fn resolves_plain_lua_profile_with_runtime_pod_name_and_scope_intent() {
let tmp = TempDir::new().unwrap();
let profile = write_profile(
tmp.path(),
@ -1677,7 +1676,7 @@ local scope = require("yoi.scope")
return profile {
slug = "coder",
model = { scheme = "anthropic", model_id = "claude-sonnet-4-20250514" },
engine = { reasoning = "high" },
worker = { reasoning = "high" },
scope = scope.workspace_read(),
}
"#,
@ -1688,13 +1687,13 @@ return profile {
.with_workspace_base(&workspace)
.resolve(
&ProfileSelector::path(&profile),
ProfileResolveOptions::with_worker_name("runtime-worker"),
ProfileResolveOptions::with_pod_name("runtime-pod"),
)
.unwrap();
assert_eq!(resolved.manifest.worker.name, "runtime-worker");
assert_eq!(resolved.manifest.pod.name, "runtime-pod");
assert_eq!(resolved.manifest.model.scheme, Some(SchemeKind::Anthropic));
assert_eq!(
resolved.manifest.engine.reasoning,
resolved.manifest.worker.reasoning,
Some(ReasoningControl::Effort(ReasoningEffort::High))
);
assert_eq!(resolved.manifest.scope.allow[0].target, workspace);
@ -1749,7 +1748,7 @@ return profile {
.with_workspace_base(&workspace)
.resolve(
&ProfileSelector::path(&profile),
ProfileResolveOptions::with_worker_name("runtime-worker"),
ProfileResolveOptions::with_pod_name("runtime-pod"),
)
.unwrap();
@ -1786,7 +1785,7 @@ return profile {
task = { enabled = true },
memory = { enabled = false },
web = { enabled = true },
workers = { enabled = true },
pods = { enabled = true },
ticket = { enabled = true, access = "read_only" },
ticket_orchestration = { enabled = false },
},
@ -1799,14 +1798,14 @@ return profile {
.with_workspace_base(&workspace)
.resolve(
&ProfileSelector::path(&profile),
ProfileResolveOptions::with_worker_name("runtime-worker"),
ProfileResolveOptions::with_pod_name("runtime-pod"),
)
.unwrap();
assert_eq!(resolved.manifest.worker.name, "runtime-worker");
assert_eq!(resolved.manifest.pod.name, "runtime-pod");
assert!(resolved.manifest.feature.task.enabled);
assert!(!resolved.manifest.feature.memory.enabled);
assert!(resolved.manifest.feature.web.enabled);
assert!(resolved.manifest.feature.workers.enabled);
assert!(resolved.manifest.feature.pods.enabled);
assert!(resolved.manifest.feature.ticket.enabled);
assert_eq!(
resolved.manifest.feature.ticket.access,
@ -1845,7 +1844,7 @@ return yoi.profile {
.with_workspace_base(tmp.path())
.resolve(
&ProfileSelector::path(profile),
ProfileResolveOptions::with_worker_name("p"),
ProfileResolveOptions::with_pod_name("p"),
)
.unwrap();
assert_eq!(
@ -1878,7 +1877,7 @@ p.slug = "assigned"
p.model = yoi.models.catalog("anthropic/claude-sonnet-4-6")
p.feature = {
task = { enabled = false },
workers = { enabled = true },
pods = { enabled = true },
}
p.web = { enabled = false }
p.compaction = yoi.compact.tokens { threshold = 123, request_threshold = 456 }
@ -1889,7 +1888,7 @@ return p
.with_workspace_base(tmp.path())
.resolve(
&ProfileSelector::path(profile),
ProfileResolveOptions::with_worker_name("p"),
ProfileResolveOptions::with_pod_name("p"),
)
.unwrap();
assert_eq!(
@ -1897,7 +1896,7 @@ return p
Some("anthropic/claude-sonnet-4-6")
);
assert!(!resolved.manifest.feature.task.enabled);
assert!(resolved.manifest.feature.workers.enabled);
assert!(resolved.manifest.feature.pods.enabled);
assert_eq!(resolved.manifest.web.as_ref().unwrap().enabled, Some(false));
assert!(resolved.manifest.web.as_ref().unwrap().search.is_none());
assert_eq!(
@ -1926,7 +1925,7 @@ return yoi.profile.extend("builtin:default", {
.with_workspace_base(tmp.path())
.resolve(
&ProfileSelector::path(profile),
ProfileResolveOptions::with_worker_name("p"),
ProfileResolveOptions::with_pod_name("p"),
)
.unwrap_err();
let message = err.to_string();
@ -1949,7 +1948,7 @@ return yoi.profile.extend("builtin:default", {
.with_workspace_base(tmp.path())
.resolve(
&ProfileSelector::path(path),
ProfileResolveOptions::with_worker_name("p"),
ProfileResolveOptions::with_pod_name("p"),
)
.unwrap_err();
assert!(matches!(
@ -1963,7 +1962,7 @@ return yoi.profile.extend("builtin:default", {
for (value, needle) in [
(serde_json::json!({"manifest": {}}), "manifest"),
(serde_json::json!({"config": {}}), "config"),
(serde_json::json!({"worker": {"name": "bad"}}), "worker"),
(serde_json::json!({"pod": {"name": "bad"}}), "pod"),
(
serde_json::json!({"model": {"ref": "codex-oauth/gpt-5.5"}, "scope": {"allow": []}}),
"scope.allow",
@ -2009,7 +2008,7 @@ return profile {
.with_workspace_base(tmp.path())
.resolve(
&ProfileSelector::path(profile),
ProfileResolveOptions::with_worker_name("p"),
ProfileResolveOptions::with_pod_name("p"),
)
.unwrap();
let c = resolved.manifest.compaction.unwrap();
@ -2024,10 +2023,10 @@ return profile {
.with_workspace_base(tmp.path())
.resolve(
&ProfileSelector::source_named(ProfileRegistrySource::Builtin, "default"),
ProfileResolveOptions::with_worker_name("runtime-workspace"),
ProfileResolveOptions::with_pod_name("runtime-workspace"),
)
.unwrap();
assert_eq!(resolved.manifest.worker.name, "runtime-workspace");
assert_eq!(resolved.manifest.pod.name, "runtime-workspace");
assert_eq!(
resolved.manifest.model.ref_.as_deref(),
Some("codex-oauth/gpt-5.5")
@ -2061,9 +2060,9 @@ return profile {
std::fs::write(
&override_path,
r#"
[worker]
[pod]
prompt_pack = "prompts.toml"
[engine]
[worker]
language = "ja"
[session]
record_event_trace = false
@ -2075,15 +2074,15 @@ record_event_trace = false
.with_workspace_base(&nested)
.resolve(
&ProfileSelector::Default,
ProfileResolveOptions::with_worker_name("runtime-worker"),
ProfileResolveOptions::with_pod_name("runtime-pod"),
)
.unwrap();
assert_eq!(resolved.manifest.worker.name, "runtime-worker");
assert_eq!(resolved.manifest.engine.language, "ja");
assert_eq!(resolved.manifest.pod.name, "runtime-pod");
assert_eq!(resolved.manifest.worker.language, "ja");
assert!(!resolved.manifest.session.record_event_trace);
assert_eq!(
resolved.manifest.worker.prompt_pack.as_deref(),
resolved.manifest.pod.prompt_pack.as_deref(),
Some(yoi_dir.join("prompts.toml").as_path())
);
assert!(resolved.manifest.scope.allow.is_empty());
@ -2112,9 +2111,9 @@ record_event_trace = false
std::fs::write(
parent_yoi.join(WORKSPACE_OVERRIDE_LOCAL_FILENAME),
r#"
[worker]
[pod]
prompt_pack = "parent-prompts.toml"
[engine]
[worker]
language = "parent"
"#,
)
@ -2123,9 +2122,9 @@ language = "parent"
std::fs::write(
&nested_override_path,
r#"
[worker]
[pod]
prompt_pack = "nested-prompts.toml"
[engine]
[worker]
language = "nested"
"#,
)
@ -2135,13 +2134,13 @@ language = "nested"
.with_workspace_base(&child)
.resolve(
&ProfileSelector::Default,
ProfileResolveOptions::with_worker_name("runtime-worker"),
ProfileResolveOptions::with_pod_name("runtime-pod"),
)
.unwrap();
assert_eq!(resolved.manifest.engine.language, "nested");
assert_eq!(resolved.manifest.worker.language, "nested");
assert_eq!(
resolved.manifest.worker.prompt_pack.as_deref(),
resolved.manifest.pod.prompt_pack.as_deref(),
Some(nested_yoi.join("nested-prompts.toml").as_path())
);
assert_eq!(
@ -2156,13 +2155,13 @@ language = "nested"
}
#[test]
fn workspace_local_override_rejects_runtime_worker_name() {
fn workspace_local_override_rejects_runtime_pod_name() {
let tmp = TempDir::new().unwrap();
let yoi_dir = tmp.path().join(".yoi");
std::fs::create_dir_all(&yoi_dir).unwrap();
std::fs::write(
yoi_dir.join(WORKSPACE_OVERRIDE_LOCAL_FILENAME),
"[worker]\nname = \"not-local\"\n",
"[pod]\nname = \"not-local\"\n",
)
.unwrap();
@ -2170,11 +2169,11 @@ language = "nested"
.with_workspace_base(tmp.path())
.resolve(
&ProfileSelector::Default,
ProfileResolveOptions::with_worker_name("runtime-worker"),
ProfileResolveOptions::with_pod_name("runtime-pod"),
)
.unwrap_err();
assert!(matches!(err, ProfileError::InvalidWorkspaceOverride { .. }));
assert!(err.to_string().contains("worker.name"));
assert!(err.to_string().contains("pod.name"));
}
#[test]

View File

@ -1,8 +1,8 @@
//! Runtime representation of a Worker's access scope.
//! Runtime representation of a Pod's access scope.
//!
//! Built from [`crate::ScopeConfig`] via [`Scope::from_config`]. Every
//! rule `target` must already be an absolute path — per-layer path
//! resolution runs earlier, inside [`crate::WorkerManifestConfig::resolve_paths`].
//! resolution runs earlier, inside [`crate::PodManifestConfig::resolve_paths`].
//! All rule `target` paths inside the [`Scope`] are canonicalised (where
//! possible) so access checks are pure path comparisons.
@ -14,7 +14,7 @@ use arc_swap::{ArcSwap, Guard};
use crate::{Permission, ScopeConfig, ScopeRule};
/// Parsed, pwd-resolved set of allow/deny rules for a Worker.
/// Parsed, pwd-resolved set of allow/deny rules for a Pod.
///
/// Read/write access decisions are pure functions of the path being
/// queried and these rules — see [`Scope::permission_at`].
@ -32,7 +32,7 @@ struct ResolvedRule {
recursive: bool,
}
/// Parsed filesystem authority this Worker may pass to spawned children.
/// Parsed filesystem authority this Pod may pass to spawned children.
///
/// Unlike [`Scope`], an empty allow list is valid and means no delegation
/// authority. Direct tools never consult this type.
@ -173,7 +173,7 @@ impl Scope {
///
/// Every `target` in `config` must already be absolute — per-layer
/// resolution happens upstream in
/// [`crate::WorkerManifestConfig::resolve_paths`] so that cascade merge
/// [`crate::PodManifestConfig::resolve_paths`] so that cascade merge
/// operates on fully-qualified paths. A lingering relative target
/// here signals an upstream bug and is rejected.
pub fn from_config(config: &ScopeConfig) -> Result<Self, ScopeError> {
@ -266,7 +266,7 @@ impl Scope {
/// Allow rules with their targets resolved to absolute paths.
///
/// Used by the pod-registry, where every Worker's allocation
/// Used by the pod-registry, where every Pod's allocation
/// must be expressed in absolute terms so prefix comparisons are
/// meaningful across processes.
pub fn allow_rules(&self) -> Vec<ScopeRule> {
@ -324,7 +324,7 @@ impl Scope {
/// Build a new [`Scope`] equal to `self` with `extra_deny` appended
/// to the deny set. Used by dynamic-scope shrink paths
/// (e.g. SpawnWorker-style delegation that strips Write from the
/// (e.g. SpawnPod-style delegation that strips Write from the
/// spawner without touching its allow rules).
pub fn with_added_deny_rules(
&self,
@ -420,7 +420,7 @@ impl Scope {
/// not lose each other's contributions.
///
/// All clones share the same underlying state — a `SharedScope` cloned
/// out to multiple consumers (Worker, ScopedFs, future grant/revoke
/// out to multiple consumers (Pod, ScopedFs, future grant/revoke
/// callers) sees every update.
#[derive(Debug, Clone)]
pub struct SharedScope {

View File

@ -17,7 +17,7 @@ Owns:
Does not own:
- authoritative project records (`.yoi/tickets/`, git history)
- normal Worker turn orchestration (`llm-engine`)
- normal Pod turn orchestration (`llm-engine`)
- product CLI command shape (`yoi`)
- curated workflow definitions (`workflow`)

View File

@ -31,7 +31,7 @@ pub fn build_consolidate_input(
"consolidation input. Run the integration step first \
(fold the staging activity logs into memory and knowledge), then the \
tidy step (clean up existing records). Use the memory tools for \
every write direct file writes are denied by the worker scope.\n\n",
every write direct file writes are denied by the pod scope.\n\n",
);
out.push_str("## Staging entries (consumed by this run)\n\n");

View File

@ -2,7 +2,7 @@
//!
//! `docs/plan/memory.md` §並走防止 に従い:
//!
//! - ファイルが存在し、記録された Worker が動作している間、その Worker が排他占有
//! - ファイルが存在し、記録された Pod が動作している間、その Pod が排他占有
//! - クラッシュで残った stale lock は、所有者 PID が死んでいれば次回 spawn
//! 時に上書き取得できる
//! - cleanup は consumed ID の staging エントリのみ削除し、実行中に extract
@ -22,12 +22,12 @@ use crate::workspace::WorkspaceLayout;
const LOCK_FILE: &str = ".consolidation.lock";
/// 占有ファイルの中身。`pid` で stale 判定し、`worker_name` / `started_at` /
/// 占有ファイルの中身。`pid` で stale 判定し、`pod_name` / `started_at` /
/// `consumed_ids` は診断とクラッシュ復旧時の参照に使う。
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct LockRecord {
pub pid: u32,
pub worker_name: String,
pub pod_name: String,
pub started_at: DateTime<Utc>,
/// この consolidation run が起動時スナップショットで確定した consumed staging
/// entry の UUIDv7 列。完了時はこの列のみ削除し、追加分は残す。
@ -38,8 +38,8 @@ pub struct LockRecord {
#[derive(Debug, thiserror::Error)]
pub enum LockError {
/// 占有ファイルが既にあり、所有者 PID が生きているのでスキップ。
#[error("consolidation lock held by live pid {pid} (worker {worker_name:?})")]
InUse { pid: u32, worker_name: String },
#[error("consolidation lock held by live pid {pid} (pod {pod_name:?})")]
InUse { pid: u32, pod_name: String },
#[error("io error at {}: {source}", .path.display())]
Io {
path: PathBuf,
@ -85,7 +85,7 @@ impl StagingLock {
pub fn acquire(
layout: &WorkspaceLayout,
pid: u32,
worker_name: impl Into<String>,
pod_name: impl Into<String>,
consumed_ids: Vec<Uuid>,
) -> Result<Self, LockError> {
let staging_dir = layout.staging_dir();
@ -99,12 +99,12 @@ impl StagingLock {
if pid_is_alive(existing.pid) {
return Err(LockError::InUse {
pid: existing.pid,
worker_name: existing.worker_name,
pod_name: existing.pod_name,
});
}
tracing::warn!(
stale_pid = existing.pid,
stale_pod = %existing.worker_name,
stale_pod = %existing.pod_name,
"consolidation stale lock detected, taking over"
);
} else {
@ -114,7 +114,7 @@ impl StagingLock {
let record = LockRecord {
pid,
worker_name: worker_name.into(),
pod_name: pod_name.into(),
started_at: Utc::now(),
consumed_ids,
};
@ -213,11 +213,11 @@ mod tests {
#[test]
fn acquire_writes_lock_file() {
let (_dir, layout) = make_layout();
let lock = StagingLock::acquire(&layout, std::process::id(), "worker", Vec::new()).unwrap();
let lock = StagingLock::acquire(&layout, std::process::id(), "pod", Vec::new()).unwrap();
let path = layout.staging_dir().join(LOCK_FILE);
assert!(path.exists());
assert_eq!(lock.record().pid, std::process::id());
assert_eq!(lock.record().worker_name, "worker");
assert_eq!(lock.record().pod_name, "pod");
}
#[test]
@ -225,8 +225,8 @@ mod tests {
let (_dir, layout) = make_layout();
// Use this test process's pid — it's definitely alive.
let _first =
StagingLock::acquire(&layout, std::process::id(), "worker-a", Vec::new()).unwrap();
let err = StagingLock::acquire(&layout, std::process::id(), "worker-b", Vec::new())
StagingLock::acquire(&layout, std::process::id(), "pod-a", Vec::new()).unwrap();
let err = StagingLock::acquire(&layout, std::process::id(), "pod-b", Vec::new())
.expect_err("expected InUse");
assert!(matches!(err, LockError::InUse { .. }));
}
@ -239,7 +239,7 @@ mod tests {
// dead on every platform we target.
let stale = LockRecord {
pid: u32::MAX,
worker_name: "ghost".into(),
pod_name: "ghost".into(),
started_at: Utc::now(),
consumed_ids: Vec::new(),
};
@ -249,7 +249,7 @@ mod tests {
)
.unwrap();
let lock = StagingLock::acquire(&layout, std::process::id(), "worker", Vec::new())
let lock = StagingLock::acquire(&layout, std::process::id(), "pod", Vec::new())
.expect("stale lock must be overwritable");
assert_eq!(lock.record().pid, std::process::id());
}
@ -276,7 +276,7 @@ mod tests {
)
.unwrap();
let lock = StagingLock::acquire(&layout, std::process::id(), "worker", vec![id_a]).unwrap();
let lock = StagingLock::acquire(&layout, std::process::id(), "pod", vec![id_a]).unwrap();
let lock_path = lock.path().to_path_buf();
lock.release_with_cleanup(&layout);
@ -295,8 +295,7 @@ mod tests {
fn release_is_resilient_to_missing_consumed_entries() {
let (_dir, layout) = make_layout();
let phantom = uuid::Uuid::now_v7();
let lock =
StagingLock::acquire(&layout, std::process::id(), "worker", vec![phantom]).unwrap();
let lock = StagingLock::acquire(&layout, std::process::id(), "pod", vec![phantom]).unwrap();
let lock_path = lock.path().to_path_buf();
// No file at <staging>/<phantom>.json — release must not panic.
lock.release_with_cleanup(&layout);

View File

@ -2,8 +2,8 @@
//!
//! extract が staging に残した活動ログを `memory/*` / `knowledge/*` に
//! 統合し、続けて既存 record を `outdated | superseded | unused | noisy`
//! の観点で整理する disposable Engine を、Worker 側が組み立てるための
//! ヘルパー群を提供する。Worker は次の手順で sub-Engine を構築する:
//! の観点で整理する disposable Engine を、Pod 側が組み立てるための
//! ヘルパー群を提供する。Pod は次の手順で sub-Engine を構築する:
//!
//! - [`build_consolidate_input`] を sub-Engine の最初の user 入力に
//! - memory 専用 Tool (read / write / edit) と Knowledge / memory 検索ツールを登録
@ -11,8 +11,8 @@
//! - sub-Engine run 完了後、[`StagingLock::release_with_cleanup`] で
//! consumed ID 分の staging のみ削除し、占有ファイルを解放
//!
//! system prompt は Worker の `PromptCatalog`
//! (`WorkerPrompt::MemoryConsolidationSystem`) で管理される。Usage report は
//! system prompt は Pod の `PromptCatalog`
//! (`PodPrompt::MemoryConsolidationSystem`) で管理される。Usage report は
//! 判断材料として渡すだけで、ここでは Knowledge 化や protection の hard decision はしない
//! `docs/plan/memory.md` §Consolidation / 整理材料)。

View File

@ -1,6 +1,6 @@
//! extract sub-Engine への入力テキスト組み立て。
//!
//! `crates/worker/src/worker.rs::build_summary_prompt` と同じ方針で
//! `crates/pod/src/pod.rs::build_summary_prompt` と同じ方針で
//! Item 列を flat な行に落とすreasoning は省く、tool call は名前のみ、
//! tool result は summary のみ。conversation 全体を Markdown の単一
//! セクションとして渡し、抽出指示は system prompt 側に寄せる。

View File

@ -1,17 +1,17 @@
//! extract: 活動抽出。
//!
//! 通常 Worker の post-run hook で発火する disposable Engine と、その
//! 通常 Pod の post-run hook で発火する disposable Engine と、その
//! 出力を `<workspace>/.yoi/memory/_staging/<id>.json` に書き出す
//! ヘルパーを提供する。Worker 側はこのモジュールから:
//! ヘルパーを提供する。Pod 側はこのモジュールから:
//!
//! - [`build_extract_input`] を sub-Engine の最初の user 入力に
//! - [`write_extracted_tool`] を唯一のツールとして
//! - [`write_staging`] で受け取った JSON を staging に書き出し
//!
//! の順で組み立てる。system prompt は Worker の `PromptCatalog`
//! (`WorkerPrompt::MemoryExtractSystem`) で管理される。pointer 永続化
//! の順で組み立てる。system prompt は Pod の `PromptCatalog`
//! (`PodPrompt::MemoryExtractSystem`) で管理される。pointer 永続化
//! session-store の `LogEntry::Extension`、domain `"memory.extract"`)は
//! Worker 側が責務を持つ。
//! Pod 側が責務を持つ。
//!
//! 出力 JSON の wrap は [`write_staging`] が `source: { segment_id, range }`
//! を機械付与する形で担当し、LLM には source を推論させない。

View File

@ -1,6 +1,6 @@
//! extract 抽出の出力 schema。
//!
//! LLM は [`ExtractedPayload`] そのものsource 抜き)を返し、Worker
//! LLM は [`ExtractedPayload`] そのものsource 抜き)を返し、Pod
//! ラッパーが [`StagingRecord`] に組み立てて staging へ書き出す。
//! source は機械付与する契約 (`docs/plan/memory.md` §Extract)。
@ -78,7 +78,7 @@ pub struct RequestEntry {
/// staging に書き出される 1 ファイル分のレコード。
///
/// `source` は Worker 側ラッパーが segment_id と log entry range を
/// `source` は Pod 側ラッパーが segment_id と log entry range を
/// 機械付与する。LLM はこのフィールドを見ない / 推論しない。
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct StagingRecord {

View File

@ -1,6 +1,6 @@
//! `LogEntry::Extension { domain: "memory.extract", payload }` の payload 形式と
//! restore 時の fold ヘルパー。memory crate がドメインを所有するので、
//! session-store / Worker は payload 構造を知らない。
//! session-store / Pod は payload 構造を知らない。
use serde::{Deserialize, Serialize};

View File

@ -2,7 +2,7 @@
//!
//! sub-Engine からは extract worker が出した [`ExtractedPayload`] を
//! 受け取って `Mutex` 越しに [`ExtractWorkerContext`] に置くだけ。
//! Worker 側はランループ完了後に `take_payload()` で取り出して
//! Pod 側はランループ完了後に `take_payload()` で取り出して
//! [`super::staging::write_staging`] に渡す。
use std::sync::{Arc, Mutex};
@ -22,7 +22,7 @@ the wrapper attaches provenance mechanically.";
pub struct ExtractWorkerContext {
payload: Mutex<Option<ExtractedPayload>>,
/// `write_extracted` が複数回呼ばれた回数debug 用)。
/// 後勝ちで上書きするが、Worker 側で warn を出したい場合に参照する。
/// 後勝ちで上書きするが、Pod 側で warn を出したい場合に参照する。
call_count: Mutex<usize>,
}
@ -31,7 +31,7 @@ impl ExtractWorkerContext {
Self::default()
}
/// sub-Engine 終了後に Worker が呼んで payload を取り出す。
/// sub-Engine 終了後に Pod が呼んで payload を取り出す。
/// 一度も `write_extracted` が呼ばれなければ `None`。
pub fn take_payload(&self) -> Option<ExtractedPayload> {
self.payload

View File

@ -3,7 +3,7 @@
//! Self-contained: provides its own Tool implementations (read/write/edit)
//! that target `<workspace>/memory/` and `<workspace>/knowledge/` only,
//! with a pre-write Linter built in. Generic CRUD tools (in the `tools`
//! crate) must not touch these directories — Worker is responsible for
//! crate) must not touch these directories — Pod is responsible for
//! denying them at the Scope level when memory is enabled.
pub mod audit;

View File

@ -1,6 +1,6 @@
//! Workspace memory resident-enumeration helpers.
//!
//! Surfaces used by the Worker system-prompt assembler:
//! Surfaces used by the Pod system-prompt assembler:
//!
//! - [`collect_resident_knowledge`] — resident-injection candidates
//! (`model_invokation: true`) returned as `(slug, description)` pairs.
@ -8,7 +8,7 @@
//! `<workspace>/.yoi/memory/summary.md` when it parses as a summary
//! record and has non-empty body.
//! - [`list_knowledge_slugs`] — every slug whose file parses, regardless
//! of `model_invokation`. Used by the Worker IPC layer to answer TUI `#`
//! of `model_invokation`. Used by the Pod IPC layer to answer TUI `#`
//! completion (`model_invokation` is a resident-injection flag, not a
//! user-visibility flag).
//!

View File

@ -1,7 +1,7 @@
//! Helpers for constructing `ScopeRule` entries that exclude the
//! memory tree from the generic CRUD tools' write surface.
//!
//! Worker is expected to call [`deny_write_rules`] when memory is enabled
//! Pod is expected to call [`deny_write_rules`] when memory is enabled
//! and append the result to the manifest's `scope.deny` list before
//! constructing the [`Scope`] passed to `tools::ScopedFs`. The memory
//! tools themselves bypass `ScopedFs` and write directly under the

View File

@ -18,7 +18,7 @@
//! `.yoi/workflow/`.
//!
//! `memory.workspace_root` pins this root explicitly. Without an explicit
//! root, resolution searches upward from the Worker pwd for a `.yoi/memory`
//! root, resolution searches upward from the Pod pwd for a `.yoi/memory`
//! marker; `.yoi` project records alone are not a memory marker.
use std::path::{Path, PathBuf};

View File

@ -177,8 +177,8 @@ fn pdk_runtime_dependencies_are_guest_side_only() {
.as_table()
.expect("dependencies table");
let forbidden = [
"worker",
"yoi-worker",
"pod",
"yoi-pod",
"llm-engine",
"tui",
"yoi-tui",

View File

@ -2,29 +2,29 @@
## Role
`pod-registry` is the legacy-named crate that tracks live Worker process ownership and delegated scope locks at runtime.
`pod-registry` tracks live Pod process ownership and delegated scope locks at runtime.
## Boundaries
Owns:
- machine-local live Worker registration
- collision detection for running Worker names
- machine-local live Pod registration
- collision detection for running Pod names
- delegated scope lock bookkeeping
- registry cleanup hooks for stopped or unreachable children
Does not own:
- durable Worker metadata (`pod-store`)
- durable Pod metadata (`pod-store`)
- replayable session logs (`session-store`)
- socket protocol definitions (`protocol`)
- project work item state
## Design notes
The registry is a runtime coordination mechanism. It can help decide whether a Worker is live or colliding, but durable visibility/restoration should be backed by Worker metadata when possible.
The registry is a runtime coordination mechanism. It can help decide whether a Pod is live or colliding, but durable visibility/restoration should be backed by Pod metadata when possible.
## See also
- [`../../docs/design/worker-session-state.md`](../../docs/design/worker-session-state.md)
- [`../../docs/design/pod-session-state.md`](../../docs/design/pod-session-state.md)
- [`../../docs/design/tool-permissions-scope.md`](../../docs/design/tool-permissions-scope.md)

View File

@ -80,18 +80,18 @@ pub fn is_within_effective_write(lock: &LockFile, parent: &str, rule: &ScopeRule
!child_conflict
}
/// The Worker and rule that actually own a conflicting write scope.
/// The Pod and rule that actually own a conflicting write scope.
#[derive(Debug, Clone)]
pub struct ConflictOwner {
pub worker_name: String,
pub pod_name: String,
pub rule: ScopeRule,
}
/// Find the Worker/rule that actually owns a write scope overlapping `rule`.
/// Find the Pod/rule that actually owns a write scope overlapping `rule`.
///
/// Walks the delegation tree: if an allocation overlaps `rule`, we
/// descend into its children and return the deepest overlapping node
/// as the true owner. `exempt` names a Worker whose ownership is
/// as the true owner. `exempt` names a Pod whose ownership is
/// permitted (used during delegation: the spawner itself is allowed
/// to still own the rule's region because it is handing it down).
pub fn find_conflict_owner(
@ -115,7 +115,7 @@ pub fn find_conflict_owners(
.iter()
.filter(|a| a.delegated_from.is_none())
.filter_map(|alloc| find_conflict_in_subtree(lock, alloc, rule))
.filter(|owner| Some(owner.worker_name.as_str()) != exempt)
.filter(|owner| Some(owner.pod_name.as_str()) != exempt)
.collect()
}
@ -142,14 +142,14 @@ fn find_conflict_in_subtree(
for child in lock
.allocations
.iter()
.filter(|a| a.delegated_from.as_deref() == Some(alloc.worker_name.as_str()))
.filter(|a| a.delegated_from.as_deref() == Some(alloc.pod_name.as_str()))
{
if let Some(owner) = find_conflict_in_subtree(lock, child, rule) {
return Some(owner);
}
}
Some(ConflictOwner {
worker_name: alloc.worker_name.clone(),
pod_name: alloc.pod_name.clone(),
rule: overlapping_rule.clone(),
})
}
@ -158,7 +158,7 @@ fn find_conflict_in_subtree(
mod tests {
use super::*;
use crate::test_util::*;
use crate::{ScopeLockError, delegate_scope, register_pod, register_worker_with_deny};
use crate::{ScopeLockError, delegate_scope, register_pod, register_pod_with_deny};
use tempfile::TempDir;
#[test]
@ -192,9 +192,9 @@ mod tests {
#[test]
fn conflict_detection_descends_to_real_owner() {
let dir = TempDir::new().unwrap();
let path = dir.path().join("workers.json");
let path = dir.path().join("pods.json");
let mut g = open_empty(&path);
register_worker(
register_pod(
&mut g,
"a".into(),
std::process::id(),
@ -213,9 +213,9 @@ mod tests {
&delegation_scope(vec![write_rule("/src", true)]),
)
.unwrap();
// A different top-level Worker trying to register /src/core/x
// A different top-level Pod trying to register /src/core/x
// should be blamed on B (deepest owner), not A.
let err = register_worker(
let err = register_pod(
&mut g,
"x".into(),
std::process::id(),
@ -233,9 +233,9 @@ mod tests {
#[test]
fn denied_write_region_is_not_claimed_by_restored_parent() {
let dir = TempDir::new().unwrap();
let path = dir.path().join("workers.json");
let path = dir.path().join("pods.json");
let mut g = open_empty(&path);
register_worker_with_deny(
register_pod_with_deny(
&mut g,
"parent".into(),
std::process::id(),
@ -245,7 +245,7 @@ mod tests {
sid(),
)
.unwrap();
register_worker(
register_pod(
&mut g,
"child".into(),
std::process::id(),
@ -259,9 +259,9 @@ mod tests {
#[test]
fn partial_deny_does_not_hide_parent_conflict() {
let dir = TempDir::new().unwrap();
let path = dir.path().join("workers.json");
let path = dir.path().join("pods.json");
let mut g = open_empty(&path);
register_worker_with_deny(
register_pod_with_deny(
&mut g,
"parent".into(),
std::process::id(),
@ -272,7 +272,7 @@ mod tests {
)
.unwrap();
let err = register_worker(
let err = register_pod(
&mut g,
"other".into(),
std::process::id(),

View File

@ -9,10 +9,10 @@ use session_store::SegmentId;
/// Errors raised by the mutating pod-registry operations.
#[derive(Debug, thiserror::Error)]
pub enum ScopeLockError {
#[error("I/O error on workers.json: {0}")]
#[error("I/O error on pods.json: {0}")]
Io(#[from] io::Error),
#[error("pod name `{0}` is already registered")]
DuplicateWorkerName(String),
DuplicatePodName(String),
#[error("requested scope `{}` conflicts with pod `{competitor}` rule `{}`", .rule.target.display(), .competitor_rule.target.display())]
WriteConflict {
competitor: String,
@ -27,14 +27,14 @@ pub enum ScopeLockError {
#[error("invalid delegation scope: {source}")]
InvalidScope { source: ScopeError },
#[error("pod `{0}` is not registered")]
UnknownWorker(String),
UnknownPod(String),
#[error(
"session {segment_id} is already held by pod `{worker_name}` at {}",
"session {segment_id} is already held by pod `{pod_name}` at {}",
.socket.display()
)]
SegmentConflict {
segment_id: SegmentId,
worker_name: String,
pod_name: String,
socket: PathBuf,
},
}

View File

@ -1,16 +1,16 @@
//! Machine-wide Worker allocation registry.
//! Machine-wide Pod allocation registry.
//!
//! A single JSON file at `<runtime_dir>/workers.json` records every live
//! Worker's allocation (see [`manifest::paths::pod_registry_path`] for
//! A single JSON file at `<runtime_dir>/pods.json` records every live
//! Pod's allocation (see [`manifest::paths::pod_registry_path`] for
//! how the path is resolved). File-level `flock(2)` serialises access
//! across processes so spawn sequences from unrelated Workers can't race.
//! across processes so spawn sequences from unrelated Pods can't race.
//!
//! Each Worker, when starting, acquires the lock, reclaims stale entries
//! (Workers whose PID has died), checks that its requested write scope
//! Each Pod, when starting, acquires the lock, reclaims stale entries
//! (Pods whose PID has died), checks that its requested write scope
//! does not overlap any other allocation's effective write scope, and
//! registers itself. When it exits normally, it removes its entry and
//! returns delegated scope to its `delegated_from` parent. Crash
//! recovery rides on the next Worker that opens the file — no background
//! recovery rides on the next Pod that opens the file — no background
//! reaper.
mod conflict;
@ -31,7 +31,7 @@ pub use lifecycle::{
install_top_level_with_deny, lookup_segment, update_segment,
};
pub use mutate::{
delegate_scope, reclaim_delegated_scope, reclaim_stale, reclaim_stale_with, register_worker,
register_worker_with_deny, release_worker,
delegate_scope, reclaim_delegated_scope, reclaim_stale, reclaim_stale_with, register_pod,
register_pod_with_deny, release_pod,
};
pub use table::{Allocation, LockFile, LockFileGuard, default_registry_path};

View File

@ -8,21 +8,21 @@ use manifest::ScopeRule;
use session_store::SegmentId;
use crate::error::ScopeLockError;
use crate::mutate::release_worker;
use crate::mutate::release_pod;
use crate::table::{LockFileGuard, default_registry_path};
/// Owned allocation: on drop, opens the lock file and releases this
/// Worker's entry. The guard keeps only the name + lock-file path; it
/// does not hold the `flock` for the Worker's lifetime.
/// Pod's entry. The guard keeps only the name + lock-file path; it
/// does not hold the `flock` for the Pod's lifetime.
#[derive(Debug)]
pub struct ScopeAllocationGuard {
worker_name: String,
pod_name: String,
lock_path: PathBuf,
}
impl ScopeAllocationGuard {
pub fn worker_name(&self) -> &str {
&self.worker_name
pub fn pod_name(&self) -> &str {
&self.pod_name
}
pub fn lock_path(&self) -> &Path {
@ -33,35 +33,28 @@ impl ScopeAllocationGuard {
impl Drop for ScopeAllocationGuard {
fn drop(&mut self) {
if let Ok(mut guard) = LockFileGuard::open(&self.lock_path) {
let _ = release_worker(&mut guard, &self.worker_name);
let _ = release_pod(&mut guard, &self.pod_name);
}
}
}
/// Open the default lock file, register a top-level Worker, and return a
/// Open the default lock file, register a top-level Pod, and return a
/// guard that will release the allocation on drop.
pub fn install_top_level(
worker_name: String,
pod_name: String,
pid: u32,
socket: PathBuf,
scope_allow: Vec<ScopeRule>,
segment_id: SegmentId,
) -> Result<ScopeAllocationGuard, ScopeLockError> {
install_top_level_with_deny(
worker_name,
pid,
socket,
scope_allow,
Vec::new(),
segment_id,
)
install_top_level_with_deny(pod_name, pid, socket, scope_allow, Vec::new(), segment_id)
}
/// Open the default lock file, register a top-level Worker with explicit
/// Open the default lock file, register a top-level Pod with explicit
/// deny rules, and return a guard that will release the allocation on
/// drop.
pub fn install_top_level_with_deny(
worker_name: String,
pod_name: String,
pid: u32,
socket: PathBuf,
scope_allow: Vec<ScopeRule>,
@ -70,9 +63,9 @@ pub fn install_top_level_with_deny(
) -> Result<ScopeAllocationGuard, ScopeLockError> {
let lock_path = default_registry_path()?;
let mut guard = LockFileGuard::open(&lock_path)?;
crate::mutate::register_worker_with_deny(
crate::mutate::register_pod_with_deny(
&mut guard,
worker_name.clone(),
pod_name.clone(),
pid,
socket,
scope_allow,
@ -80,13 +73,13 @@ pub fn install_top_level_with_deny(
segment_id,
)?;
Ok(ScopeAllocationGuard {
worker_name,
pod_name,
lock_path,
})
}
/// Take ownership of an existing allocation that was pre-registered by
/// a spawning Worker.
/// a spawning Pod.
///
/// The spawning flow is two-stage: the spawner calls
/// [`crate::delegate_scope`] (with its own pid as a live placeholder,
@ -95,7 +88,7 @@ pub fn install_top_level_with_deny(
/// segment_id to its own and claim the [`ScopeAllocationGuard`] so
/// the entry is released when the child exits.
pub fn adopt_allocation(
worker_name: String,
pod_name: String,
new_pid: u32,
segment_id: SegmentId,
) -> Result<ScopeAllocationGuard, ScopeLockError> {
@ -103,24 +96,24 @@ pub fn adopt_allocation(
let mut guard = LockFileGuard::open(&lock_path)?;
let alloc = guard
.data_mut()
.find_mut(&worker_name)
.ok_or_else(|| ScopeLockError::UnknownWorker(worker_name.clone()))?;
.find_mut(&pod_name)
.ok_or_else(|| ScopeLockError::UnknownPod(pod_name.clone()))?;
alloc.pid = new_pid;
alloc.segment_id = Some(segment_id);
guard.save()?;
Ok(ScopeAllocationGuard {
worker_name,
pod_name,
lock_path,
})
}
/// Rewrite the `segment_id` recorded for `worker_name` to
/// Rewrite the `segment_id` recorded for `pod_name` to
/// `new_segment_id`.
///
/// The Worker's in-memory `segment_id` can change underneath the
/// The Pod's in-memory `segment_id` can change underneath the
/// allocation in two normal places:
///
/// - `Worker::compact` mints a fresh session and swaps it in.
/// - `Pod::compact` mints a fresh session and swaps it in.
/// - `session_store::ensure_head_or_fork` auto-forks when another
/// writer has advanced the store head behind our back.
///
@ -128,37 +121,37 @@ pub fn adopt_allocation(
/// find the live session id, not the old one. Without this update a
/// concurrent `restore_from_manifest(new_id)` would see "no live
/// writer" and proceed to register a competing allocation on the
/// session this Worker just moved into.
/// session this Pod just moved into.
///
/// The lock is opened once and the allocation is rewritten inside the
/// guard, so the segment_id collision check is atomic with the
/// rewrite.
pub fn update_segment(worker_name: &str, new_segment_id: SegmentId) -> Result<(), ScopeLockError> {
pub fn update_segment(pod_name: &str, new_segment_id: SegmentId) -> Result<(), ScopeLockError> {
let lock_path = default_registry_path()?;
let mut guard = LockFileGuard::open(&lock_path)?;
if let Some(other) = guard.data().find_by_segment(new_segment_id) {
if other.worker_name != worker_name {
if other.pod_name != pod_name {
return Err(ScopeLockError::SegmentConflict {
segment_id: new_segment_id,
worker_name: other.worker_name.clone(),
pod_name: other.pod_name.clone(),
socket: other.socket.clone(),
});
}
}
let alloc = guard
.data_mut()
.find_mut(worker_name)
.ok_or_else(|| ScopeLockError::UnknownWorker(worker_name.into()))?;
.find_mut(pod_name)
.ok_or_else(|| ScopeLockError::UnknownPod(pod_name.into()))?;
alloc.segment_id = Some(new_segment_id);
guard.save()?;
Ok(())
}
/// Information about a Worker that currently holds an allocation for a
/// Information about a Pod that currently holds an allocation for a
/// given session.
#[derive(Debug, Clone)]
pub struct SegmentLockInfo {
pub worker_name: String,
pub pod_name: String,
pub socket: PathBuf,
pub pid: u32,
}
@ -166,7 +159,7 @@ pub struct SegmentLockInfo {
/// Open the default lock file, reclaim stale entries, and return the
/// allocation currently writing to `segment_id`, if any.
///
/// Used by `Worker::restore_from_manifest` to refuse a resume that would
/// Used by `Pod::restore_from_manifest` to refuse a resume that would
/// race a live writer on the same source session.
pub fn lookup_segment(segment_id: SegmentId) -> Result<Option<SegmentLockInfo>, ScopeLockError> {
let lock_path = default_registry_path()?;
@ -176,7 +169,7 @@ pub fn lookup_segment(segment_id: SegmentId) -> Result<Option<SegmentLockInfo>,
.data()
.find_by_segment(segment_id)
.map(|a| SegmentLockInfo {
worker_name: a.worker_name.clone(),
pod_name: a.pod_name.clone(),
socket: a.socket.clone(),
pid: a.pid,
}))
@ -192,11 +185,11 @@ mod tests {
/// Mimic what the spawner does before the child comes up: push an
/// allocation for the child carrying the spawner's (live) pid as a
/// placeholder. Exists only in tests.
fn delegate_placeholder(g: &mut LockFileGuard, worker_name: &str, placeholder_pid: u32) {
fn delegate_placeholder(g: &mut LockFileGuard, pod_name: &str, placeholder_pid: u32) {
g.data_mut().allocations.push(Allocation {
worker_name: worker_name.to_string(),
pod_name: pod_name.to_string(),
pid: placeholder_pid,
socket: sock(worker_name),
socket: sock(pod_name),
scope_allow: vec![write_rule("/tmp/child", true)],
scope_deny: Vec::new(),
delegated_from: None,
@ -209,7 +202,7 @@ mod tests {
fn scope_allocation_guard_releases_on_drop() {
let dir = TempDir::new().unwrap();
let _sandbox = RuntimeDirSandbox::new(dir.path());
let lock_path = dir.path().join("workers.json");
let lock_path = dir.path().join("pods.json");
let guard = install_top_level(
"a".into(),
std::process::id(),
@ -233,7 +226,7 @@ mod tests {
fn adopt_allocation_rewrites_pid_and_releases_on_drop() {
let dir = TempDir::new().unwrap();
let _sandbox = RuntimeDirSandbox::new(dir.path());
let lock_path = dir.path().join("workers.json");
let lock_path = dir.path().join("pods.json");
// Pre-register an allocation under spawner's pid, as delegate_scope would.
{
let mut g = LockFileGuard::open(&lock_path).unwrap();
@ -258,7 +251,7 @@ mod tests {
let dir = TempDir::new().unwrap();
let _sandbox = RuntimeDirSandbox::new(dir.path());
let err = adopt_allocation("ghost".into(), 42, sid()).unwrap_err();
assert!(matches!(err, ScopeLockError::UnknownWorker(ref n) if n == "ghost"));
assert!(matches!(err, ScopeLockError::UnknownPod(ref n) if n == "ghost"));
}
#[test]
@ -275,7 +268,7 @@ mod tests {
)
.unwrap();
let info = lookup_segment(s).unwrap().expect("expected live writer");
assert_eq!(info.worker_name, "live");
assert_eq!(info.pod_name, "live");
assert_eq!(info.socket, sock("live"));
drop(guard);
// After the guard's release, the lookup goes back to None.
@ -299,7 +292,7 @@ mod tests {
update_segment("p", updated).unwrap();
// lookup against the original is now empty, the updated id wins.
assert!(lookup_segment(original).unwrap().is_none());
assert_eq!(lookup_segment(updated).unwrap().unwrap().worker_name, "p");
assert_eq!(lookup_segment(updated).unwrap().unwrap().pod_name, "p");
}
#[test]
@ -328,11 +321,11 @@ mod tests {
let err = update_segment("a", s_b).unwrap_err();
match err {
ScopeLockError::SegmentConflict {
worker_name,
pod_name,
segment_id,
..
} => {
assert_eq!(worker_name, "b");
assert_eq!(pod_name, "b");
assert_eq!(segment_id, s_b);
}
other => panic!("expected SegmentConflict, got {other:?}"),

View File

@ -11,24 +11,24 @@ use crate::conflict::{find_conflict_owner, find_conflict_owners};
use crate::error::ScopeLockError;
use crate::table::{Allocation, LockFileGuard};
/// Register a top-level Worker (started directly by a human, no
/// Register a top-level Pod (started directly by a human, no
/// delegation parent). Reclaims stale entries before checking
/// conflicts so a crashed Worker's allocation doesn't block the new one.
/// conflicts so a crashed Pod's allocation doesn't block the new one.
///
/// Rejects when another live allocation is already writing to
/// `segment_id`, so two `restore_from_manifest` calls under different
/// `worker_name`s cannot both grab the same session log.
pub fn register_worker(
/// `pod_name`s cannot both grab the same session log.
pub fn register_pod(
guard: &mut LockFileGuard,
worker_name: String,
pod_name: String,
pid: u32,
socket: PathBuf,
scope_allow: Vec<ScopeRule>,
segment_id: SegmentId,
) -> Result<(), ScopeLockError> {
register_worker_with_deny(
register_pod_with_deny(
guard,
worker_name,
pod_name,
pid,
socket,
scope_allow,
@ -37,21 +37,21 @@ pub fn register_worker(
)
}
/// Register a top-level Worker with explicit deny rules that reduce the
/// Register a top-level Pod with explicit deny rules that reduce the
/// claimed effective write scope.
///
/// Conflict semantics: if every Worker overlapping a requested allow rule
/// Conflict semantics: if every Pod overlapping a requested allow rule
/// is fully covered by one of `scope_deny`, the conflict is suppressed
/// and the registration proceeds. The check is structural (deny ⊇
/// competitor.rule), not relational — it does not verify that the
/// competitor actually descends from this Worker's prior delegations.
/// competitor actually descends from this Pod's prior delegations.
/// In practice this is safe because the canonical restore caller derives
/// `scope_deny` from outstanding `pod-store` child delegations, so any
/// covered competitor is expected to be a descendant of the original
/// allocation. Direct callers must uphold the same invariant.
pub fn register_worker_with_deny(
pub fn register_pod_with_deny(
guard: &mut LockFileGuard,
worker_name: String,
pod_name: String,
pid: u32,
socket: PathBuf,
scope_allow: Vec<ScopeRule>,
@ -59,13 +59,13 @@ pub fn register_worker_with_deny(
segment_id: SegmentId,
) -> Result<(), ScopeLockError> {
reclaim_stale(guard);
if guard.data().find(&worker_name).is_some() {
return Err(ScopeLockError::DuplicateWorkerName(worker_name));
if guard.data().find(&pod_name).is_some() {
return Err(ScopeLockError::DuplicatePodName(pod_name));
}
if let Some(existing) = guard.data().find_by_segment(segment_id) {
return Err(ScopeLockError::SegmentConflict {
segment_id,
worker_name: existing.worker_name.clone(),
pod_name: existing.pod_name.clone(),
socket: existing.socket.clone(),
});
}
@ -86,14 +86,14 @@ pub fn register_worker_with_deny(
}
if let Some(competitor) = conflicts.into_iter().next() {
return Err(ScopeLockError::WriteConflict {
competitor: competitor.worker_name,
competitor: competitor.pod_name,
rule: rule.clone(),
competitor_rule: competitor.rule,
});
}
}
guard.data_mut().allocations.push(Allocation {
worker_name,
pod_name,
pid,
socket,
scope_allow,
@ -105,9 +105,9 @@ pub fn register_worker_with_deny(
Ok(())
}
/// Register a spawned Worker whose scope is delegated from `spawner`.
/// Register a spawned Pod whose scope is delegated from `spawner`.
/// The requested scope must be within the spawner's delegation authority;
/// overlap with any Worker other than `spawner` is a conflict.
/// overlap with any Pod other than `spawner` is a conflict.
pub fn delegate_scope(
guard: &mut LockFileGuard,
spawner: &str,
@ -119,10 +119,10 @@ pub fn delegate_scope(
) -> Result<(), ScopeLockError> {
reclaim_stale(guard);
if guard.data().find(&spawned).is_some() {
return Err(ScopeLockError::DuplicateWorkerName(spawned));
return Err(ScopeLockError::DuplicatePodName(spawned));
}
if guard.data().find(spawner).is_none() {
return Err(ScopeLockError::UnknownWorker(spawner.into()));
return Err(ScopeLockError::UnknownPod(spawner.into()));
}
for rule in &scope_allow {
let allowed = delegation_scope
@ -137,7 +137,7 @@ pub fn delegate_scope(
if rule.permission == Permission::Write {
if let Some(competitor) = find_conflict_owner(guard.data(), rule, Some(spawner)) {
return Err(ScopeLockError::WriteConflict {
competitor: competitor.worker_name,
competitor: competitor.pod_name,
rule: rule.clone(),
competitor_rule: competitor.rule,
});
@ -145,7 +145,7 @@ pub fn delegate_scope(
}
}
guard.data_mut().allocations.push(Allocation {
worker_name: spawned,
pod_name: spawned,
pid,
socket,
scope_allow,
@ -159,21 +159,21 @@ pub fn delegate_scope(
Ok(())
}
/// Remove a Worker's allocation. Surviving children are reparented to
/// the removed Worker's own `delegated_from`, so the delegation tree
/// Remove a Pod's allocation. Surviving children are reparented to
/// the removed Pod's own `delegated_from`, so the delegation tree
/// stays connected.
pub fn release_worker(guard: &mut LockFileGuard, worker_name: &str) -> Result<(), ScopeLockError> {
pub fn release_pod(guard: &mut LockFileGuard, pod_name: &str) -> Result<(), ScopeLockError> {
let idx = guard
.data()
.allocations
.iter()
.position(|a| a.worker_name == worker_name);
.position(|a| a.pod_name == pod_name);
let Some(idx) = idx else {
return Err(ScopeLockError::UnknownWorker(worker_name.into()));
return Err(ScopeLockError::UnknownPod(pod_name.into()));
};
let removed = guard.data().allocations[idx].clone();
for alloc in guard.data_mut().allocations.iter_mut() {
if alloc.delegated_from.as_deref() == Some(worker_name) {
if alloc.delegated_from.as_deref() == Some(pod_name) {
alloc.delegated_from.clone_from(&removed.delegated_from);
}
}
@ -187,7 +187,7 @@ pub fn release_worker(guard: &mut LockFileGuard, worker_name: &str) -> Result<()
/// This is idempotent for missing deny entries. For each delegated Write rule,
/// at most one exact matching deny rule is removed from the parent's `scope_deny`
/// even when the child allocation is already absent; restore reconciliation uses
/// that case when durable Worker-state still records an outstanding delegation but
/// that case when durable Pod-state still records an outstanding delegation but
/// the live lock file no longer has a child allocation.
pub fn reclaim_delegated_scope(
guard: &mut LockFileGuard,
@ -199,7 +199,7 @@ pub fn reclaim_delegated_scope(
.data()
.allocations
.iter()
.position(|a| a.worker_name == child);
.position(|a| a.pod_name == child);
let removed_child_parent = child_idx
.map(|idx| guard.data().allocations[idx].delegated_from.clone())
.unwrap_or(None);
@ -229,8 +229,8 @@ pub fn reclaim_delegated_scope(
}
/// Remove allocations whose PID is dead, reparenting children to the
/// dead Worker's `delegated_from`. Idempotent and best-effort — I/O
/// errors on save are swallowed so a crashed Worker's entry never blocks
/// dead Pod's `delegated_from`. Idempotent and best-effort — I/O
/// errors on save are swallowed so a crashed Pod's entry never blocks
/// forward progress.
pub fn reclaim_stale(guard: &mut LockFileGuard) {
reclaim_stale_with(guard, pid_alive);
@ -243,7 +243,7 @@ pub fn reclaim_stale_with(guard: &mut LockFileGuard, mut is_alive: impl FnMut(u3
.allocations
.iter()
.filter(|a| !is_alive(a.pid))
.map(|a| a.worker_name.clone())
.map(|a| a.pod_name.clone())
.collect();
if dead.is_empty() {
return;
@ -253,7 +253,7 @@ pub fn reclaim_stale_with(guard: &mut LockFileGuard, mut is_alive: impl FnMut(u3
.data()
.allocations
.iter()
.position(|a| a.worker_name == *name)
.position(|a| a.pod_name == *name)
else {
continue;
};
@ -294,9 +294,9 @@ mod tests {
#[test]
fn register_detects_write_conflict() {
let dir = TempDir::new().unwrap();
let path = dir.path().join("workers.json");
let path = dir.path().join("pods.json");
let mut g = open_empty(&path);
register_worker(
register_pod(
&mut g,
"a".into(),
std::process::id(),
@ -305,7 +305,7 @@ mod tests {
sid(),
)
.unwrap();
let err = register_worker(
let err = register_pod(
&mut g,
"b".into(),
std::process::id(),
@ -321,11 +321,11 @@ mod tests {
}
#[test]
fn duplicate_worker_name_rejected() {
fn duplicate_pod_name_rejected() {
let dir = TempDir::new().unwrap();
let path = dir.path().join("workers.json");
let path = dir.path().join("pods.json");
let mut g = open_empty(&path);
register_worker(
register_pod(
&mut g,
"a".into(),
std::process::id(),
@ -334,7 +334,7 @@ mod tests {
sid(),
)
.unwrap();
let err = register_worker(
let err = register_pod(
&mut g,
"a".into(),
std::process::id(),
@ -343,15 +343,15 @@ mod tests {
sid(),
)
.unwrap_err();
assert!(matches!(err, ScopeLockError::DuplicateWorkerName(ref n) if n == "a"));
assert!(matches!(err, ScopeLockError::DuplicatePodName(ref n) if n == "a"));
}
#[test]
fn delegate_must_be_subset() {
let dir = TempDir::new().unwrap();
let path = dir.path().join("workers.json");
let path = dir.path().join("pods.json");
let mut g = open_empty(&path);
register_worker(
register_pod(
&mut g,
"a".into(),
std::process::id(),
@ -376,9 +376,9 @@ mod tests {
#[test]
fn delegate_uses_delegation_scope_not_direct_effective_write() {
let dir = TempDir::new().unwrap();
let path = dir.path().join("workers.json");
let path = dir.path().join("pods.json");
let mut g = open_empty(&path);
register_worker(
register_pod(
&mut g,
"orchestrator".into(),
std::process::id(),
@ -406,9 +406,9 @@ mod tests {
#[test]
fn delegate_succeeds_within_parent_scope() {
let dir = TempDir::new().unwrap();
let path = dir.path().join("workers.json");
let path = dir.path().join("pods.json");
let mut g = open_empty(&path);
register_worker(
register_pod(
&mut g,
"a".into(),
std::process::id(),
@ -445,9 +445,9 @@ mod tests {
#[test]
fn delegate_rejects_sibling_overlap() {
let dir = TempDir::new().unwrap();
let path = dir.path().join("workers.json");
let path = dir.path().join("pods.json");
let mut g = open_empty(&path);
register_worker(
register_pod(
&mut g,
"a".into(),
std::process::id(),
@ -486,9 +486,9 @@ mod tests {
#[test]
fn release_reparents_children() {
let dir = TempDir::new().unwrap();
let path = dir.path().join("workers.json");
let path = dir.path().join("pods.json");
let mut g = open_empty(&path);
register_worker(
register_pod(
&mut g,
"a".into(),
std::process::id(),
@ -517,7 +517,7 @@ mod tests {
&delegation_scope(vec![write_rule("/src/core", true)]),
)
.unwrap();
release_worker(&mut g, "b").unwrap();
release_pod(&mut g, "b").unwrap();
// D should now list A as its delegated_from.
let d = g.data().find("d").unwrap();
assert_eq!(d.delegated_from.as_deref(), Some("a"));
@ -527,10 +527,10 @@ mod tests {
#[test]
fn reclaim_delegated_scope_removes_child_and_one_parent_deny_layer() {
let dir = TempDir::new().unwrap();
let path = dir.path().join("workers.json");
let path = dir.path().join("pods.json");
let mut g = open_empty(&path);
let delegated_rule = write_rule("/src/core", true);
register_worker_with_deny(
register_pod_with_deny(
&mut g,
"a".into(),
std::process::id(),
@ -540,7 +540,7 @@ mod tests {
sid(),
)
.unwrap();
register_worker(
register_pod(
&mut g,
"b".into(),
std::process::id(),
@ -566,10 +566,10 @@ mod tests {
#[test]
fn reclaim_delegated_scope_removes_parent_deny_when_child_allocation_missing() {
let dir = TempDir::new().unwrap();
let path = dir.path().join("workers.json");
let path = dir.path().join("pods.json");
let mut g = open_empty(&path);
let delegated_rule = write_rule("/src/core", true);
register_worker_with_deny(
register_pod_with_deny(
&mut g,
"a".into(),
std::process::id(),
@ -595,9 +595,9 @@ mod tests {
#[test]
fn reclaim_stale_reparents_and_removes_dead_entries() {
let dir = TempDir::new().unwrap();
let path = dir.path().join("workers.json");
let path = dir.path().join("pods.json");
let mut g = open_empty(&path);
register_worker(
register_pod(
&mut g,
"a".into(),
std::process::id(),
@ -630,7 +630,7 @@ mod tests {
// will treat as dead.
let fake_dead_pid: u32 = 0xffff_fff0;
for alloc in g.data_mut().allocations.iter_mut() {
if alloc.worker_name == "b" {
if alloc.pod_name == "b" {
alloc.pid = fake_dead_pid;
}
}
@ -643,9 +643,9 @@ mod tests {
#[test]
fn read_rules_do_not_conflict_with_write() {
let dir = TempDir::new().unwrap();
let path = dir.path().join("workers.json");
let path = dir.path().join("pods.json");
let mut g = open_empty(&path);
register_worker(
register_pod(
&mut g,
"a".into(),
std::process::id(),
@ -655,7 +655,7 @@ mod tests {
)
.unwrap();
// B only reads under the same tree — allowed.
register_worker(
register_pod(
&mut g,
"b".into(),
std::process::id(),
@ -670,9 +670,9 @@ mod tests {
#[test]
fn releasing_pod_reopens_scope_for_fresh_registration() {
let dir = TempDir::new().unwrap();
let path = dir.path().join("workers.json");
let path = dir.path().join("pods.json");
let mut g = open_empty(&path);
register_worker(
register_pod(
&mut g,
"a".into(),
std::process::id(),
@ -681,8 +681,8 @@ mod tests {
sid(),
)
.unwrap();
release_worker(&mut g, "a").unwrap();
register_worker(
release_pod(&mut g, "a").unwrap();
register_pod(
&mut g,
"b".into(),
std::process::id(),
@ -696,9 +696,9 @@ mod tests {
#[test]
fn delegated_scope_returns_to_parent_on_release() {
let dir = TempDir::new().unwrap();
let path = dir.path().join("workers.json");
let path = dir.path().join("pods.json");
let mut g = open_empty(&path);
register_worker(
register_pod(
&mut g,
"a".into(),
std::process::id(),
@ -722,7 +722,7 @@ mod tests {
"a",
&write_rule("/src/core", true)
));
release_worker(&mut g, "b").unwrap();
release_pod(&mut g, "b").unwrap();
// /src/core is back in A's effective write scope.
assert!(is_within_effective_write(
g.data(),
@ -734,10 +734,10 @@ mod tests {
#[test]
fn register_pod_rejects_session_id_collision() {
let dir = TempDir::new().unwrap();
let path = dir.path().join("workers.json");
let path = dir.path().join("pods.json");
let mut g = open_empty(&path);
let shared_session = sid();
register_worker(
register_pod(
&mut g,
"first".into(),
std::process::id(),
@ -747,9 +747,9 @@ mod tests {
)
.unwrap();
// Second registration tries to grab the same segment_id under
// a different worker_name. Without the SegmentConflict check both
// a different pod_name. Without the SegmentConflict check both
// would succeed and race on the same jsonl.
let err = register_worker(
let err = register_pod(
&mut g,
"second".into(),
std::process::id(),
@ -761,11 +761,11 @@ mod tests {
match err {
ScopeLockError::SegmentConflict {
segment_id,
worker_name,
pod_name,
..
} => {
assert_eq!(segment_id, shared_session);
assert_eq!(worker_name, "first");
assert_eq!(pod_name, "first");
}
other => panic!("expected SegmentConflict, got {other:?}"),
}

View File

@ -22,33 +22,33 @@ pub struct LockFile {
pub allocations: Vec<Allocation>,
}
/// One Worker's scope allocation.
/// One Pod's scope allocation.
///
/// `scope_allow` is the full set of allow rules the Worker was granted.
/// Portions delegated out to child Workers are **not** subtracted in
/// `scope_allow` is the full set of allow rules the Pod was granted.
/// Portions delegated out to child Pods are **not** subtracted in
/// storage — the effective write scope is derived on the fly by
/// removing rules owned by any Worker whose `delegated_from` points to
/// removing rules owned by any Pod whose `delegated_from` points to
/// this one. Keeping the raw allow set makes reparenting (stale
/// reclaim) trivial.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct Allocation {
/// Worker name — also the identity used throughout orchestration.
pub worker_name: String,
/// Pod name — also the identity used throughout orchestration.
pub pod_name: String,
/// Owning process. Checked with `kill(pid, 0)` for stale detection.
pub pid: u32,
/// Worker's Unix socket path.
/// Pod's Unix socket path.
pub socket: PathBuf,
/// Allow rules granted to this Worker (write + read).
/// Allow rules granted to this Pod (write + read).
pub scope_allow: Vec<ScopeRule>,
/// Deny rules that cap this Worker's effective scope. Normally empty for
/// fresh allocations; restored Workers use this to avoid reclaiming
/// Deny rules that cap this Pod's effective scope. Normally empty for
/// fresh allocations; restored Pods use this to avoid reclaiming
/// previously delegated write regions.
#[serde(default)]
pub scope_deny: Vec<ScopeRule>,
/// Name of the Worker that delegated scope to this one, or `None` for
/// a top-level Worker started directly by a human.
/// Name of the Pod that delegated scope to this one, or `None` for
/// a top-level Pod started directly by a human.
pub delegated_from: Option<String>,
/// Segment ID this Worker is currently writing to. `None` means this
/// Segment ID this Pod is currently writing to. `None` means this
/// is a pre-reservation made by a spawner via [`crate::delegate_scope`]
/// before the child has come up; the child fills it in at
/// [`crate::adopt_allocation`] time.
@ -57,16 +57,12 @@ pub struct Allocation {
}
impl LockFile {
pub fn find(&self, worker_name: &str) -> Option<&Allocation> {
self.allocations
.iter()
.find(|a| a.worker_name == worker_name)
pub fn find(&self, pod_name: &str) -> Option<&Allocation> {
self.allocations.iter().find(|a| a.pod_name == pod_name)
}
pub fn find_mut(&mut self, worker_name: &str) -> Option<&mut Allocation> {
self.allocations
.iter_mut()
.find(|a| a.worker_name == worker_name)
pub fn find_mut(&mut self, pod_name: &str) -> Option<&mut Allocation> {
self.allocations.iter_mut().find(|a| a.pod_name == pod_name)
}
/// Find the allocation currently writing to `segment_id`. Skips
@ -78,7 +74,7 @@ impl LockFile {
}
}
/// Default on-disk path: `<runtime_dir>/workers.json` resolved via
/// Default on-disk path: `<runtime_dir>/pods.json` resolved via
/// [`manifest::paths::pod_registry_path`]. Tests should point this
/// elsewhere by setting `YOI_HOME` or `YOI_RUNTIME_DIR` to a
/// tempdir.
@ -86,7 +82,7 @@ pub fn default_registry_path() -> io::Result<PathBuf> {
paths::pod_registry_path().ok_or_else(|| {
io::Error::new(
io::ErrorKind::NotFound,
"could not resolve workers.json path (no YOI_HOME / \
"could not resolve pods.json path (no YOI_HOME / \
YOI_RUNTIME_DIR / XDG_RUNTIME_DIR / HOME)",
)
})
@ -177,7 +173,7 @@ impl LockFileGuard {
serde_json::from_str(&buf).map_err(|e| {
io::Error::new(
io::ErrorKind::InvalidData,
format!("workers.json parse error: {e}"),
format!("pods.json parse error: {e}"),
)
})?
};
@ -219,7 +215,7 @@ mod tests {
#[test]
fn open_creates_empty_lock_file() {
let dir = TempDir::new().unwrap();
let path = dir.path().join("workers.json");
let path = dir.path().join("pods.json");
let guard = LockFileGuard::open(&path).unwrap();
assert!(guard.data().allocations.is_empty());
assert!(path.exists());
@ -230,7 +226,7 @@ mod tests {
use std::os::unix::fs::PermissionsExt;
let dir = TempDir::new().unwrap();
let parent = dir.path().join("yoi");
let path = parent.join("workers.json");
let path = parent.join("pods.json");
let _guard = LockFileGuard::open(&path).unwrap();
let file_mode = std::fs::metadata(&path).unwrap().permissions().mode() & 0o777;
assert_eq!(file_mode, 0o600, "file mode = {file_mode:o}");
@ -241,10 +237,10 @@ mod tests {
#[test]
fn save_and_reopen_roundtrip() {
let dir = TempDir::new().unwrap();
let path = dir.path().join("workers.json");
let path = dir.path().join("pods.json");
{
let mut g = open_empty(&path);
register_worker(
register_pod(
&mut g,
"a".into(),
std::process::id(),
@ -256,19 +252,19 @@ mod tests {
}
let guard = LockFileGuard::open(&path).unwrap();
assert_eq!(guard.data().allocations.len(), 1);
assert_eq!(guard.data().allocations[0].worker_name, "a");
assert_eq!(guard.data().allocations[0].pod_name, "a");
}
#[test]
fn find_by_session_skips_none_placeholders() {
let dir = TempDir::new().unwrap();
let path = dir.path().join("workers.json");
let path = dir.path().join("pods.json");
let mut g = open_empty(&path);
// Pre-reservation: delegate_scope leaves segment_id = None
// until adopt_allocation rewrites it. find_by_segment must not
// match those placeholders, otherwise a freshly-spawning child
// would shadow itself before it has even chosen a session.
register_worker(
register_pod(
&mut g,
"parent".into(),
std::process::id(),
@ -296,6 +292,6 @@ mod tests {
// After adopt-style rewrite, the same allocation is now found.
g.data_mut().find_mut("child").unwrap().segment_id = Some(target_session);
let found = g.data().find_by_segment(target_session).unwrap();
assert_eq!(found.worker_name, "child");
assert_eq!(found.pod_name, "child");
}
}

View File

@ -1,6 +1,6 @@
[package]
name = "pod-store"
description = "Legacy-named durable Worker metadata/state persistence"
description = "Durable Pod-name metadata/state persistence"
version = "0.1.0"
edition.workspace = true
license.workspace = true

View File

@ -2,13 +2,13 @@
## Role
`pod-store` is the legacy-named crate that owns current Worker metadata keyed by Worker name.
`pod-store` owns current Pod metadata keyed by Pod name.
## Boundaries
Owns:
- persisted Worker metadata files
- persisted Pod metadata files
- current active/pending session pointers
- resolved manifest snapshots for restoration
- parent-visible spawned-child metadata
@ -23,8 +23,8 @@ Does not own:
## Design notes
Worker metadata is intentionally thin. It should answer current-state questions without duplicating transcripts or becoming a second session log.
Pod metadata is intentionally thin. It should answer current-state questions without duplicating transcripts or becoming a second session log.
## See also
- [`../../docs/design/worker-session-state.md`](../../docs/design/worker-session-state.md)
- [`../../docs/design/pod-session-state.md`](../../docs/design/pod-session-state.md)

View File

@ -1,14 +1,14 @@
//! Durable Worker-name metadata/state persistence.
//! Durable Pod-name metadata/state persistence.
//!
//! This crate owns the name-keyed Worker state surface under a Worker-state root,
//! e.g. `{data_dir}/workers/{worker_name}/metadata.json`. Session JSONL replay stays
//! in `session-store`; Worker metadata may point at a `(SessionId, SegmentId)` but
//! This crate owns the name-keyed Pod state surface under a Pod-state root,
//! e.g. `{data_dir}/pods/{pod_name}/metadata.json`. Session JSONL replay stays
//! in `session-store`; Pod metadata may point at a `(SessionId, SegmentId)` but
//! does not own or replay session logs.
//!
//! `resolved_manifest_snapshot` is authority only for Worker-name restore before
//! `resolved_manifest_snapshot` is authority only for Pod-name restore before
//! loading the session log. Existing segment replay still uses `SegmentStart`
//! entries from `session-store`. `spawned_children` is durable current parent
//! Worker state for child registry/reclaim; child lifecycle messages shown to the
//! Pod state for child registry/reclaim; child lifecycle messages shown to the
//! model remain session JSONL history. Socket and callback paths are last-known
//! runtime hints, not proof of liveness.
@ -17,9 +17,9 @@ use session_store::{SegmentId, SessionId};
use std::fs;
use std::path::PathBuf;
/// Errors from Worker metadata persistence.
/// Errors from Pod metadata persistence.
#[derive(Debug, thiserror::Error)]
pub enum WorkerStoreError {
pub enum PodStoreError {
#[error("I/O error: {0}")]
Io(#[from] std::io::Error),
@ -30,15 +30,15 @@ pub enum WorkerStoreError {
InvalidPodName(String),
}
/// Active Session/Segment pointer for a Worker.
/// Active Session/Segment pointer for a Pod.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct WorkerActiveSegmentRef {
pub struct PodActiveSegmentRef {
pub session_id: SessionId,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub segment_id: Option<SegmentId>,
}
impl WorkerActiveSegmentRef {
impl PodActiveSegmentRef {
/// Create a reference whose active Segment is not known yet.
pub fn pending_segment(session_id: SessionId) -> Self {
Self {
@ -57,21 +57,21 @@ impl WorkerActiveSegmentRef {
}
/// One delegated scope rule for a spawned child, kept local to avoid depending
/// on manifest scope types in durable Worker state.
/// on manifest scope types in durable Pod state.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct WorkerSpawnedScopeRule {
pub struct PodSpawnedScopeRule {
pub target: PathBuf,
pub permission: String,
pub recursive: bool,
}
/// One child Worker spawned by this Worker and persisted with the spawner's
/// name-keyed Worker state. Runtime paths are last-known hints only.
/// One child Pod spawned by this Pod and persisted with the spawner's
/// name-keyed Pod state. Runtime paths are last-known hints only.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct WorkerSpawnedChild {
pub worker_name: String,
pub struct PodSpawnedChild {
pub pod_name: String,
pub socket_path: PathBuf,
pub scope_delegated: Vec<WorkerSpawnedScopeRule>,
pub scope_delegated: Vec<PodSpawnedScopeRule>,
pub callback_address: PathBuf,
}
@ -79,44 +79,44 @@ pub struct WorkerSpawnedChild {
/// restore can distinguish outstanding delegated scope from already-reclaimed
/// child state without consulting session logs.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct WorkerReclaimedChild {
pub worker_name: String,
pub scope_delegated: Vec<WorkerSpawnedScopeRule>,
pub struct PodReclaimedChild {
pub pod_name: String,
pub scope_delegated: Vec<PodSpawnedScopeRule>,
}
/// One peer Worker made visible by an explicit peer handshake.
/// One peer Pod made visible by an explicit peer handshake.
///
/// Peer visibility is intentionally separate from spawned-child delegation: it
/// does not carry filesystem scope, callback ownership, output cursors, or
/// lifecycle-notification authority.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct WorkerPeer {
pub worker_name: String,
pub struct PodPeer {
pub pod_name: String,
}
/// Persistent metadata for a Worker name.
/// Persistent metadata for a Pod name.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct WorkerMetadata {
pub worker_name: String,
pub struct PodMetadata {
pub pod_name: String,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub active: Option<WorkerActiveSegmentRef>,
pub active: Option<PodActiveSegmentRef>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub workspace_root: Option<PathBuf>,
#[serde(default, skip_serializing_if = "Vec::is_empty")]
pub spawned_children: Vec<WorkerSpawnedChild>,
pub spawned_children: Vec<PodSpawnedChild>,
#[serde(default, skip_serializing_if = "Vec::is_empty")]
pub reclaimed_children: Vec<WorkerReclaimedChild>,
pub reclaimed_children: Vec<PodReclaimedChild>,
#[serde(default, skip_serializing_if = "Vec::is_empty")]
pub peers: Vec<WorkerPeer>,
pub peers: Vec<PodPeer>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub resolved_manifest_snapshot: Option<serde_json::Value>,
}
impl WorkerMetadata {
/// Create Worker metadata for `worker_name`.
pub fn new(worker_name: impl Into<String>, active: Option<WorkerActiveSegmentRef>) -> Self {
impl PodMetadata {
/// Create Pod metadata for `pod_name`.
pub fn new(pod_name: impl Into<String>, active: Option<PodActiveSegmentRef>) -> Self {
Self {
worker_name: worker_name.into(),
pod_name: pod_name.into(),
active,
workspace_root: None,
spawned_children: Vec::new(),
@ -132,39 +132,35 @@ impl WorkerMetadata {
}
}
/// Sync persistence backend for Worker metadata.
pub trait WorkerMetadataStore: Send + Sync {
/// Create or replace metadata for its `worker_name` key.
fn write(&self, metadata: &WorkerMetadata) -> Result<(), WorkerStoreError>;
/// Sync persistence backend for Pod metadata.
pub trait PodMetadataStore: Send + Sync {
/// Create or replace metadata for its `pod_name` key.
fn write(&self, metadata: &PodMetadata) -> Result<(), PodStoreError>;
/// Read metadata by Worker name. Returns `None` when no metadata exists.
fn read_by_name(&self, worker_name: &str) -> Result<Option<WorkerMetadata>, WorkerStoreError>;
/// Read metadata by Pod name. Returns `None` when no metadata exists.
fn read_by_name(&self, pod_name: &str) -> Result<Option<PodMetadata>, PodStoreError>;
/// List persisted Worker metadata keys.
fn list_names(&self) -> Result<Vec<String>, WorkerStoreError>;
/// List persisted Pod metadata keys.
fn list_names(&self) -> Result<Vec<String>, PodStoreError>;
/// Return the metadata root directory when this backend is path-backed.
fn root_dir(&self) -> Option<PathBuf> {
None
}
/// Delete metadata by Worker name. Missing metadata is a successful no-op.
fn delete_by_name(&self, worker_name: &str) -> Result<(), WorkerStoreError>;
/// Delete metadata by Pod name. Missing metadata is a successful no-op.
fn delete_by_name(&self, pod_name: &str) -> Result<(), PodStoreError>;
/// Merge an update into one Worker's metadata, preserving unrelated fields.
fn update_by_name<F>(
&self,
worker_name: &str,
update: F,
) -> Result<WorkerMetadata, WorkerStoreError>
/// Merge an update into one Pod's metadata, preserving unrelated fields.
fn update_by_name<F>(&self, pod_name: &str, update: F) -> Result<PodMetadata, PodStoreError>
where
F: FnOnce(&mut WorkerMetadata),
F: FnOnce(&mut PodMetadata),
{
let mut metadata = self
.read_by_name(worker_name)?
.unwrap_or_else(|| WorkerMetadata::new(worker_name, None));
.read_by_name(pod_name)?
.unwrap_or_else(|| PodMetadata::new(pod_name, None));
update(&mut metadata);
metadata.worker_name = worker_name.to_string();
metadata.pod_name = pod_name.to_string();
self.write(&metadata)?;
Ok(metadata)
}
@ -172,22 +168,22 @@ pub trait WorkerMetadataStore: Send + Sync {
/// Set the active pointer while preserving spawned children, workspace ownership, and manifest snapshot.
fn set_active(
&self,
worker_name: &str,
active: Option<WorkerActiveSegmentRef>,
pod_name: &str,
active: Option<PodActiveSegmentRef>,
resolved_manifest_snapshot: Option<serde_json::Value>,
) -> Result<WorkerMetadata, WorkerStoreError> {
self.set_active_with_workspace_root(worker_name, active, resolved_manifest_snapshot, None)
) -> Result<PodMetadata, PodStoreError> {
self.set_active_with_workspace_root(pod_name, active, resolved_manifest_snapshot, None)
}
/// Set the active pointer and workspace ownership while preserving unrelated fields.
fn set_active_with_workspace_root(
&self,
worker_name: &str,
active: Option<WorkerActiveSegmentRef>,
pod_name: &str,
active: Option<PodActiveSegmentRef>,
resolved_manifest_snapshot: Option<serde_json::Value>,
workspace_root: Option<PathBuf>,
) -> Result<WorkerMetadata, WorkerStoreError> {
self.update_by_name(worker_name, |metadata| {
) -> Result<PodMetadata, PodStoreError> {
self.update_by_name(pod_name, |metadata| {
metadata.active = active;
metadata.resolved_manifest_snapshot = resolved_manifest_snapshot;
if let Some(workspace_root) = workspace_root {
@ -199,56 +195,38 @@ pub trait WorkerMetadataStore: Send + Sync {
/// Set spawned-child registry state while preserving active pointer and manifest snapshot.
fn set_spawned_children(
&self,
worker_name: &str,
children: Vec<WorkerSpawnedChild>,
) -> Result<WorkerMetadata, WorkerStoreError> {
self.update_by_name(worker_name, |metadata| {
pod_name: &str,
children: Vec<PodSpawnedChild>,
) -> Result<PodMetadata, PodStoreError> {
self.update_by_name(pod_name, |metadata| {
metadata.spawned_children = children;
})
}
/// Set peer visibility state while preserving active pointer, child state,
/// and manifest snapshot.
fn set_peers(
&self,
worker_name: &str,
peers: Vec<WorkerPeer>,
) -> Result<WorkerMetadata, WorkerStoreError> {
self.update_by_name(worker_name, |metadata| {
fn set_peers(&self, pod_name: &str, peers: Vec<PodPeer>) -> Result<PodMetadata, PodStoreError> {
self.update_by_name(pod_name, |metadata| {
metadata.peers = peers;
})
}
/// Add one peer if absent while preserving every other metadata field.
fn add_peer(
&self,
worker_name: &str,
peer_name: &str,
) -> Result<WorkerMetadata, WorkerStoreError> {
self.update_by_name(worker_name, |metadata| {
if !metadata
.peers
.iter()
.any(|peer| peer.worker_name == peer_name)
{
metadata.peers.push(WorkerPeer {
worker_name: peer_name.to_string(),
fn add_peer(&self, pod_name: &str, peer_name: &str) -> Result<PodMetadata, PodStoreError> {
self.update_by_name(pod_name, |metadata| {
if !metadata.peers.iter().any(|peer| peer.pod_name == peer_name) {
metadata.peers.push(PodPeer {
pod_name: peer_name.to_string(),
});
metadata
.peers
.sort_by(|a, b| a.worker_name.cmp(&b.worker_name));
metadata.peers.sort_by(|a, b| a.pod_name.cmp(&b.pod_name));
}
})
}
/// Remove one peer while preserving every other metadata field.
fn remove_peer(
&self,
worker_name: &str,
peer_name: &str,
) -> Result<WorkerMetadata, WorkerStoreError> {
self.update_by_name(worker_name, |metadata| {
metadata.peers.retain(|peer| peer.worker_name != peer_name);
fn remove_peer(&self, pod_name: &str, peer_name: &str) -> Result<PodMetadata, PodStoreError> {
self.update_by_name(pod_name, |metadata| {
metadata.peers.retain(|peer| peer.pod_name != peer_name);
})
}
@ -256,47 +234,47 @@ pub trait WorkerMetadataStore: Send + Sync {
/// them in durable reclaim history.
fn reclaim_spawned_children(
&self,
worker_name: &str,
reclaimed: Vec<WorkerReclaimedChild>,
) -> Result<WorkerMetadata, WorkerStoreError> {
self.update_by_name(worker_name, |metadata| {
pod_name: &str,
reclaimed: Vec<PodReclaimedChild>,
) -> Result<PodMetadata, PodStoreError> {
self.update_by_name(pod_name, |metadata| {
for reclaimed_child in &reclaimed {
metadata
.spawned_children
.retain(|child| child.worker_name != reclaimed_child.worker_name);
.retain(|child| child.pod_name != reclaimed_child.pod_name);
}
metadata.reclaimed_children.extend(reclaimed);
})
}
}
/// Filesystem-backed Worker metadata store.
/// Filesystem-backed Pod metadata store.
#[derive(Clone)]
pub struct FsWorkerStore {
pub struct FsPodStore {
root: PathBuf,
}
impl FsWorkerStore {
/// Create a store rooted at the Worker-state directory, usually `{data_dir}/workers`.
pub fn new(root: impl Into<PathBuf>) -> Result<Self, WorkerStoreError> {
impl FsPodStore {
/// Create a store rooted at the Pod-state directory, usually `{data_dir}/pods`.
pub fn new(root: impl Into<PathBuf>) -> Result<Self, PodStoreError> {
let root = root.into();
fs::create_dir_all(&root)?;
Ok(Self { root })
}
fn pod_dir(&self, worker_name: &str) -> Result<PathBuf, WorkerStoreError> {
validate_worker_name(worker_name)?;
Ok(self.root.join(worker_name))
fn pod_dir(&self, pod_name: &str) -> Result<PathBuf, PodStoreError> {
validate_pod_name(pod_name)?;
Ok(self.root.join(pod_name))
}
fn metadata_path(&self, worker_name: &str) -> Result<PathBuf, WorkerStoreError> {
Ok(self.pod_dir(worker_name)?.join("metadata.json"))
fn metadata_path(&self, pod_name: &str) -> Result<PathBuf, PodStoreError> {
Ok(self.pod_dir(pod_name)?.join("metadata.json"))
}
}
impl WorkerMetadataStore for FsWorkerStore {
fn write(&self, metadata: &WorkerMetadata) -> Result<(), WorkerStoreError> {
let path = self.metadata_path(&metadata.worker_name)?;
impl PodMetadataStore for FsPodStore {
fn write(&self, metadata: &PodMetadata) -> Result<(), PodStoreError> {
let path = self.metadata_path(&metadata.pod_name)?;
if let Some(parent) = path.parent() {
fs::create_dir_all(parent)?;
}
@ -305,17 +283,17 @@ impl WorkerMetadataStore for FsWorkerStore {
Ok(())
}
fn read_by_name(&self, worker_name: &str) -> Result<Option<WorkerMetadata>, WorkerStoreError> {
let path = self.metadata_path(worker_name)?;
fn read_by_name(&self, pod_name: &str) -> Result<Option<PodMetadata>, PodStoreError> {
let path = self.metadata_path(pod_name)?;
let content = match fs::read_to_string(path) {
Ok(content) => content,
Err(err) if err.kind() == std::io::ErrorKind::NotFound => return Ok(None),
Err(err) => return Err(WorkerStoreError::Io(err)),
Err(err) => return Err(PodStoreError::Io(err)),
};
Ok(Some(serde_json::from_str(&content)?))
}
fn list_names(&self) -> Result<Vec<String>, WorkerStoreError> {
fn list_names(&self) -> Result<Vec<String>, PodStoreError> {
let mut names = Vec::new();
if !self.root.exists() {
return Ok(names);
@ -331,7 +309,7 @@ impl WorkerMetadataStore for FsWorkerStore {
let Some(name) = entry.file_name().to_str().map(ToOwned::to_owned) else {
continue;
};
if validate_worker_name(&name).is_ok() {
if validate_pod_name(&name).is_ok() {
names.push(name);
}
}
@ -343,12 +321,12 @@ impl WorkerMetadataStore for FsWorkerStore {
Some(self.root.clone())
}
fn delete_by_name(&self, worker_name: &str) -> Result<(), WorkerStoreError> {
let path = self.metadata_path(worker_name)?;
fn delete_by_name(&self, pod_name: &str) -> Result<(), PodStoreError> {
let path = self.metadata_path(pod_name)?;
match fs::remove_file(&path) {
Ok(()) => {}
Err(err) if err.kind() == std::io::ErrorKind::NotFound => return Ok(()),
Err(err) => return Err(WorkerStoreError::Io(err)),
Err(err) => return Err(PodStoreError::Io(err)),
}
if let Some(parent) = path.parent() {
let _ = fs::remove_dir(parent);
@ -357,20 +335,20 @@ impl WorkerMetadataStore for FsWorkerStore {
}
}
pub fn validate_worker_name(worker_name: &str) -> Result<(), WorkerStoreError> {
if worker_name.is_empty()
|| worker_name == "."
|| worker_name == ".."
|| worker_name.contains('/')
|| worker_name.contains('\0')
pub fn validate_pod_name(pod_name: &str) -> Result<(), PodStoreError> {
if pod_name.is_empty()
|| pod_name == "."
|| pod_name == ".."
|| pod_name.contains('/')
|| pod_name.contains('\0')
{
return Err(WorkerStoreError::InvalidPodName(worker_name.to_string()));
return Err(PodStoreError::InvalidPodName(pod_name.to_string()));
}
Ok(())
}
/// Convenience composition for callers that want one handle carrying separate
/// session-log and Worker-state roots.
/// session-log and Pod-state roots.
#[derive(Clone)]
pub struct CombinedStore<S, P> {
pub session_store: S,
@ -464,25 +442,25 @@ where
}
}
impl<S, P> WorkerMetadataStore for CombinedStore<S, P>
impl<S, P> PodMetadataStore for CombinedStore<S, P>
where
S: Send + Sync,
P: WorkerMetadataStore,
P: PodMetadataStore,
{
fn write(&self, metadata: &WorkerMetadata) -> Result<(), WorkerStoreError> {
fn write(&self, metadata: &PodMetadata) -> Result<(), PodStoreError> {
self.pod_store.write(metadata)
}
fn read_by_name(&self, worker_name: &str) -> Result<Option<WorkerMetadata>, WorkerStoreError> {
self.pod_store.read_by_name(worker_name)
fn read_by_name(&self, pod_name: &str) -> Result<Option<PodMetadata>, PodStoreError> {
self.pod_store.read_by_name(pod_name)
}
fn list_names(&self) -> Result<Vec<String>, WorkerStoreError> {
fn list_names(&self) -> Result<Vec<String>, PodStoreError> {
self.pod_store.list_names()
}
fn root_dir(&self) -> Option<PathBuf> {
self.pod_store.root_dir()
}
fn delete_by_name(&self, worker_name: &str) -> Result<(), WorkerStoreError> {
self.pod_store.delete_by_name(worker_name)
fn delete_by_name(&self, pod_name: &str) -> Result<(), PodStoreError> {
self.pod_store.delete_by_name(pod_name)
}
}
@ -492,9 +470,9 @@ mod tests {
#[test]
fn pod_metadata_manifest_snapshot_roundtrips() {
let mut metadata = WorkerMetadata::new(
let mut metadata = PodMetadata::new(
"profile-pod",
Some(WorkerActiveSegmentRef::pending_segment(
Some(PodActiveSegmentRef::pending_segment(
session_store::new_session_id(),
)),
);
@ -504,7 +482,7 @@ mod tests {
}));
let json = serde_json::to_string(&metadata).unwrap();
let restored: WorkerMetadata = serde_json::from_str(&json).unwrap();
let restored: PodMetadata = serde_json::from_str(&json).unwrap();
assert_eq!(restored, metadata);
}
@ -513,29 +491,29 @@ mod tests {
fn fs_store_writes_under_pod_state_root_only() {
let tmp = tempfile::TempDir::new().unwrap();
let session_root = tmp.path().join("sessions");
let pod_root = tmp.path().join("workers");
let pod_root = tmp.path().join("pods");
fs::create_dir_all(&session_root).unwrap();
let store = FsWorkerStore::new(&pod_root).unwrap();
let store = FsPodStore::new(&pod_root).unwrap();
store
.write(&WorkerMetadata::new(
.write(&PodMetadata::new(
"agent",
Some(WorkerActiveSegmentRef::pending_segment(
Some(PodActiveSegmentRef::pending_segment(
session_store::new_session_id(),
)),
))
.unwrap();
assert!(pod_root.join("agent/metadata.json").exists());
assert!(!session_root.join("workers/agent/metadata.json").exists());
assert!(!session_root.join("pods/agent/metadata.json").exists());
}
#[test]
fn active_updates_preserve_children_and_manifest_snapshot() {
let tmp = tempfile::TempDir::new().unwrap();
let store = FsWorkerStore::new(tmp.path()).unwrap();
let mut metadata = WorkerMetadata::new("agent", None);
metadata.spawned_children.push(WorkerSpawnedChild {
worker_name: "child".into(),
let store = FsPodStore::new(tmp.path()).unwrap();
let mut metadata = PodMetadata::new("agent", None);
metadata.spawned_children.push(PodSpawnedChild {
pod_name: "child".into(),
socket_path: std::path::Path::new("/tmp/child.sock").into(),
scope_delegated: vec![],
callback_address: std::path::Path::new("/tmp/parent.sock").into(),
@ -547,7 +525,7 @@ mod tests {
store
.set_active(
"agent",
Some(WorkerActiveSegmentRef::active_segment(
Some(PodActiveSegmentRef::active_segment(
session_store::new_session_id(),
session_store::new_segment_id(),
)),
@ -562,8 +540,8 @@ mod tests {
#[test]
fn child_updates_preserve_active_and_manifest_snapshot() {
let tmp = tempfile::TempDir::new().unwrap();
let store = FsWorkerStore::new(tmp.path()).unwrap();
let active = WorkerActiveSegmentRef::active_segment(
let store = FsPodStore::new(tmp.path()).unwrap();
let active = PodActiveSegmentRef::active_segment(
session_store::new_session_id(),
session_store::new_segment_id(),
);
@ -574,8 +552,8 @@ mod tests {
store
.set_spawned_children(
"agent",
vec![WorkerSpawnedChild {
worker_name: "child".into(),
vec![PodSpawnedChild {
pod_name: "child".into(),
socket_path: std::path::Path::new("/tmp/child.sock").into(),
scope_delegated: vec![],
callback_address: std::path::Path::new("/tmp/parent.sock").into(),
@ -590,8 +568,8 @@ mod tests {
#[test]
fn peer_updates_preserve_active_children_and_manifest_snapshot() {
let tmp = tempfile::TempDir::new().unwrap();
let store = FsWorkerStore::new(tmp.path()).unwrap();
let active = WorkerActiveSegmentRef::active_segment(
let store = FsPodStore::new(tmp.path()).unwrap();
let active = PodActiveSegmentRef::active_segment(
session_store::new_session_id(),
session_store::new_segment_id(),
);
@ -602,8 +580,8 @@ mod tests {
store
.set_spawned_children(
"agent",
vec![WorkerSpawnedChild {
worker_name: "child".into(),
vec![PodSpawnedChild {
pod_name: "child".into(),
socket_path: std::path::Path::new("/tmp/child.sock").into(),
scope_delegated: vec![],
callback_address: std::path::Path::new("/tmp/parent.sock").into(),
@ -622,7 +600,7 @@ mod tests {
restored
.peers
.iter()
.map(|peer| peer.worker_name.as_str())
.map(|peer| peer.pod_name.as_str())
.collect::<Vec<_>>(),
vec!["peer-a", "peer-b"]
);
@ -630,14 +608,14 @@ mod tests {
store.remove_peer("agent", "peer-a").unwrap();
let restored = store.read_by_name("agent").unwrap().unwrap();
assert_eq!(restored.peers.len(), 1);
assert_eq!(restored.peers[0].worker_name, "peer-b");
assert_eq!(restored.peers[0].pod_name, "peer-b");
}
#[test]
fn reclaim_children_removes_outstanding_and_records_history() {
let tmp = tempfile::TempDir::new().unwrap();
let store = FsWorkerStore::new(tmp.path()).unwrap();
let scope = WorkerSpawnedScopeRule {
let store = FsPodStore::new(tmp.path()).unwrap();
let scope = PodSpawnedScopeRule {
target: std::path::Path::new("/tmp/delegated").into(),
permission: "write".into(),
recursive: true,
@ -645,8 +623,8 @@ mod tests {
store
.set_spawned_children(
"agent",
vec![WorkerSpawnedChild {
worker_name: "child".into(),
vec![PodSpawnedChild {
pod_name: "child".into(),
socket_path: std::path::Path::new("/tmp/child.sock").into(),
scope_delegated: vec![scope.clone()],
callback_address: std::path::Path::new("/tmp/parent.sock").into(),
@ -657,8 +635,8 @@ mod tests {
store
.reclaim_spawned_children(
"agent",
vec![WorkerReclaimedChild {
worker_name: "child".into(),
vec![PodReclaimedChild {
pod_name: "child".into(),
scope_delegated: vec![scope.clone()],
}],
)

View File

@ -1,5 +1,5 @@
[package]
name = "worker"
name = "pod"
version = "0.1.0"
edition.workspace = true
license.workspace = true

32
crates/pod/README.md Normal file
View File

@ -0,0 +1,32 @@
# pod
## Role
`pod` turns an `llm-engine` Engine into a named runtime entity with manifest configuration, scoped tools, session persistence, protocol handling, and Pod metadata integration.
## Boundaries
Owns:
- Pod lifecycle and socket protocol serving
- Engine construction around a resolved Manifest
- session-store and pod-store coordination
- built-in tool registration under scope/policy
- spawned-child orchestration hooks
Does not own:
- provider-specific wire formats (`provider` / `llm-engine` clients)
- product CLI parsing (`yoi`)
- TUI display authority (`tui`)
- current-state storage schema outside Pod metadata (`pod-store`)
## Design notes
A Pod is runtime authority, not UI state. It should commit model-visible events through history/session paths and keep current Pod-name state in Pod metadata rather than in transient runtime files.
## See also
- [`../../docs/design/pod-session-state.md`](../../docs/design/pod-session-state.md)
- [`../../docs/design/context-history.md`](../../docs/design/context-history.md)
- [`../../docs/design/tool-permissions-scope.md`](../../docs/design/tool-permissions-scope.md)

Some files were not shown because too many files have changed in this diff Show More