diff --git a/docs/architecture/rust-agent/capability-event-inventory.md b/docs/architecture/rust-agent/capability-event-inventory.md index 922d1f8fd0..b613d8c5ff 100644 --- a/docs/architecture/rust-agent/capability-event-inventory.md +++ b/docs/architecture/rust-agent/capability-event-inventory.md @@ -17,7 +17,7 @@ | --- | --- | --- | --- | --- | | Approval | 审批请求、响应与未完成请求结算 | approval/*;读取权限状态 | 产品生成目录 | [实现](../../../crates/dim-agent-capabilities/src/approval.rs) / [说明](plugins/Permission.md) | | BackgroundExec | 后台执行任务及完成通知 | exec/*、input/message;中断与回合边界 | 产品生成目录 | [实现](../../../crates/dim-agent-capabilities/src/workspace_tools/background.rs) / [说明](plugins/WorkspaceTools.md) | -| BranchLine | 父子分支工作的跟踪、输入交接与结果通知 | branch/*、input/*、turn/*、step/tool-* | 产品生成目录 | [实现](../../../crates/dim-agent-capabilities/src/timeline_tree.rs) / [说明](plugins/BranchTool.md) | +| BranchLine | 父子分支工作的跟踪、输入交接与结果通知 | branch/*、input/*、turn/*、step/tool-* | 产品生成目录 | [实现](../../../crates/dim-agent-capabilities/src/timeline_tree.rs) / [说明](plugins/BranchLine.md) | | CollaborationTimeline | 跨 Session 协作交接与结算 | collaboration/*、input/*、turn/*、step/* | 产品生成目录 | [实现](../../../crates/dim-app-server/src/collaboration.rs) | | ContextPreparation | 准备模型请求与上下文压缩工作 | context/prepare、compaction-*、model/call;失败输出终态 | 产品生成目录 | [实现](../../../crates/dim-agent-capabilities/src/context_preparation.rs) / [说明](plugins/ContextPreparation.md) | | ContextUsage | 上下文使用量计算与派生结果恢复 | context/*、model/*、input/consumed、step/*、context-usage/* | 产品生成目录 | [实现](../../../crates/dim-agent-capabilities/src/context_usage.rs) / [说明](plugins/ContextUsage.md) | @@ -108,7 +108,7 @@ | exec | [WorkspaceTools](plugins/WorkspaceTools.md)、[ShellSession](../../../crates/dim-agent-capabilities/src/shell_session.rs) | | prompt、context | [Prompt](plugins/Prompt.md)、[ContextPreparation](plugins/ContextPreparation.md)、[ContextUsage](plugins/ContextUsage.md)、[上下文策略](../../../crates/dim-agent-capabilities/src/context_policy.rs) | | model、step | [ModelProvider](plugins/ModelProvider.md)、[输出提交](../../../crates/dim-agent-capabilities/src/output.rs)、[ToolExecution](plugins/ToolExecution.md)、[Loop](plugins/Loop.md) | -| branch | [TimelineTree](plugins/TimelineTree.md)、[BranchLine](plugins/BranchTool.md) | +| branch | [TimelineTree](plugins/TimelineTree.md)、[BranchLine](plugins/BranchLine.md) | | collaboration | [协作实现](../../../crates/dim-app-server/src/collaboration.rs) | | session/forked | [Timeline 存储](../../../crates/dim-app-server/src/storage/timeline.rs) | diff --git a/docs/architecture/rust-agent/plugins/BranchLine.md b/docs/architecture/rust-agent/plugins/BranchLine.md new file mode 100644 index 0000000000..bbf754286c --- /dev/null +++ b/docs/architecture/rust-agent/plugins/BranchLine.md @@ -0,0 +1,324 @@ +# BranchLine + +Owner: [timeline_tree.rs](../../../../crates/dim-agent-capabilities/src/timeline_tree.rs). +Scope: branch. Issue: [#2024](https://github.com/arcships/dim/issues/2024). + +This page is the owner contract for one line's view of itself and its lines. +[Current implementation](#current-implementation) describes the code as it is today. + +BranchLine is one line's view of itself and of the lines it opened. It folds the line's own committed facts into its role, the tool lines it opened, the state of its current turn and its read cursors, and it writes the blocks a line's neighbourhood reads: the roster, the parent block, the idle notice, the ended notice and the status note a default-line move leaves. TimelineTree owns the directory and the lifecycle; BranchLine owns what one line says about its neighbourhood and keeps it current. A line that opened nothing and is the root writes no block. + +## Use and scope: responsibility split + +BranchLine owns: + +- **Its role and parent.** `main`, `tool`, `host` or `user`, and the line it was cut from, both read from the parent's `branch/create` at the line's `createdAt` (the create fact's own position), never at the inherited `cut` and never parsed from rendered history. A line cut at an older point than its creation would otherwise read the wrong fact. +- **The tool lines it opened and their states.** The roster of open tool lines with the first line of each purpose, in opening order, retired when none is open. +- **Its read cursors.** The `nextCursor` of its latest successful read of each target it may read. +- **The parent block.** The head and cursor the line has reported to itself about the line it was cut from, and whether a block is currently held and undelivered. +- **Its turn and notices.** The state of its current turn, and the idle notice it steers into its opener. The roster and the ended notice are written when this line is the opener of a line that ended: the opener's own BranchLine writes them on the opener's own line. +- **The status note.** One keyed block when the line becomes, or stops being, the conversation line, with the text this owner writes after TimelineTree records the transition. +- **The model-facing markers.** ``, `` and ``, and the guide entries of all four markers, until this part unloads. ``'s text shape and guide entry are this owner's; the block itself is written by BranchTool for a message and by TimelineTree for an end's final message. + +Callers keep: which lines they message or read (BranchTool's kin rules), what a message says, how a page is rendered, and every decision about the caller's own work. + +| Requirement (callers) | Compose from the operations below without breaking the owner's invariants? | Handling | +| --- | --- | --- | +| BranchTool asks this line's role before deciding what it may message, read or end | No: the role and parent are folded from the line's own facts and cached; re-deriving them in a Session part means folding another owner's state | `view` | +| BranchTool learns whether this line has committed its own end | No: same fold | `view` | +| BranchTool continues a read of a target where the line's last read stopped | Yes: the view answers that target's cursor in the same call | `view` | +| Write the roster, the parent block, the idle notice, the ended notice, the status note | No, but not public: these are this owner's own writes, driven by the line's facts | Internal | +| Tell the opener the line moved: a parent turn end past the cursor | No: it is this owner's fold of its own facts and its own write queue | Internal | +| Tell the opener a line it opened ended | No: only the opener's own BranchLine can write its line, and the ended line's writer is closing | `branch/ended` fold, internal | +| Answer what the line is holding back | Yes: `view` reports the held parent block | `view` | + +## Caller example + +BranchTool decides what the calling line may do; the view is one read on the line's own BranchLine, and no `Branch` object is involved. + +```rust +// The tool execution carries the calling line id as a value. +let line = line_owner::(&execution.branch_id)?.view().await?; +match line.role { + LineRole::Tool => { /* may end itself, message its parent, read its children */ } + LineRole::Host => { /* follows its creator's protocol; message refused */ } + LineRole::Main | LineRole::User => { /* opens and reads lines, ends none of them */ } +} +if line.ending { + return refused("branch_ended", &execution.branch_id); +} +let after = line.cursor.unwrap_or(if opened_by_caller { 0 } else { cut }); +``` + +## Own contract + +### Contract dependencies + +| Service | Purpose | +| --- | --- | +| `B:Dispatcher` | The line's own facts, in commit order after the rebuild. | +| `B:Timeline` / `B:TimelineIdentity` | Its own facts and its own id. | +| `B:BranchLifecycle` | Wait for the branch to be active before writing. | +| `B:InputQueue` | Its own line's input entry. The opener's entry is called by line id (`line_owner::`), not injected (ADR 027 D4). | +| `S:SessionScope` | `activated` and `closing`: wait for the Session's publication before roster repair. | +| `S:GuideEntries` | The four markers above, until this part unloads. | +| owner-internal `TreeHandle` | The owner's weak handle to TimelineTree: the line's record, the default line, the move transitions and the parent's turn-end signal. Weak because the tree holds this line's scope and the scope holds this part; a strong handle would be a cycle close could not break. | + +### Operations + +| Operation | Intent | Request | Reply | Cancellation | Errors (codes) | +| --- | --- | --- | --- | --- | --- | +| `view` | One line's role, parent, end state and the read cursor for the target the caller asks about | `{target?}` (the operation runs on the line's own BranchLine) | `{role, parent?, ending, cursor?, blocked?}` | None: a read of the owner's folded state, or one bounded read of its own history for that target | `unknown_branch` (the line has no directory record yet), `storage` (the read of its own history failed; retryable), `closed` | + +`cursor` is the `nextCursor` of this line's latest successful read of the named target: retained from live results, and rebuilt on load from this line's own `step/tool-use` and `step/tool-result` for that target when the line has read it. It is absent when the target is omitted or this line never read it. `blocked` reports the held parent block: its target and the head it reported. The reply is a value, not a subscription: BranchTool reads it once per call, and the owner keeps it current from its own facts. + +### Errors + +| Kind (wire code) | What the caller does next | +| --- | --- | +| `unknown_branch` | The line has no directory record yet; retry after it is published, or treat the line as unopened | +| `storage` | Retryable: the line's own history could not be read, so no cursor is known; retry the view, or read with no `after` | +| `closed` | The Session is closing; the caller's own refusal follows | + +### Flows + +| Operation | Normal path | Caller cancels | Caller unloads | Owner closes or reloads | Settled by | +| --- | --- | --- | --- | --- | --- | +| `view` | Read the cached role and the target's cursor; a target with no cursor reads that target's facts once | Nothing to release | Nothing to release | Refused `closed` for a closing Session; a reloaded line rebuilds from its own facts | BranchLine | +| internal writes | A fact of the line's own arrives, the fold decides, one keyed block is written into its own line through its input entry. The ended notice is one **Steer** input carrying the roster's keyed block when the roster retires, so an idle opener wakes once; only the idle notice steers the opener through `line_owner::(opener)` | The write belongs to the line, not to a caller; a cancelled turn writes nothing more | The line's writes stop with the line | The branch scope closes after its last write; a restored line rebuilds its blocks and writes only what is owed | BranchLine writes; the line's input owner admits; TimelineTree settles the scope | + +## Exceptions with reasons + +- The status note restates the line's birth identity byte for byte: a compaction replays the note, so it must be self-contained; the identity is written by TimelineTree and repeated here only as text. TimelineTree records the move; this owner writes the note. +- A restored line writes a missing note once and, on the conversation line, replaces a note an older rule set wrote: the note's text is this owner's, and the tree only knows the transition. +- The parent block is decided from the line's own state rather than from the parent's signal: a signal that arrives while a block is held must not lose the move, so the queue and the block's consumption decide the write. +- The idle notice is steered into the opener's line through the opener's input owner (`line_owner::`), not by TimelineTree: the notice is this line's statement about itself, and the opener's queue decides its order. The ended notice and the roster retirement are written by the opener's own BranchLine on its own line when it folds `branch/ended`, because the ended line's scope is closing and its writer must not be the one to tell the opener. + +## Verification + +Flow tests on the owner: + +- A line cut from the root knows `main`, `tool` or `host` from its opening facts and reports no cursor before its first read. +- The roster lists the open tool lines in opening order, retires when none is open, and a child cut after its parent wrote a roster gets one retirement block. +- An idle tool line steers its opener once per turn end that said nothing, and never while it is the conversation line. +- A line ended from outside wakes its opener once: the opener's BranchLine writes the roster retirement and `` on its own line, and the ended line's closing scope writes nothing to it. +- A move writes one status note per participant in commit order; a reload of the conversation line replaces an outdated note once and writes nothing on a second restart. +- A parent turn end past the cursor writes one parent block; a block held while a move arrives is written after consumption, deletion or interruption. + +## Supersedes + +- [Timeline branches](../../../design/timeline-branches.md): §5's BranchLine row and its "BranchLine injects …" sentence, and §7.1.1's parent-block write paragraph, each now points here. + +## Client-visible changes + +The `branchLine` face keeps its wire name and its scope but replaces its three operations (`resolved`, `ending`, `cursor`) with one `view` that takes `{target?}` and answers `{role, parent?, ending, cursor?, blocked?}`. The generated `npm/branch-services.d.ts` loses the three and gains `view`, and the runtime fixture `runtime/fixtures/branch-part.ts`, which calls them today, moves to `view` in the same change. No RPC client calls this face; a foreign part that bound one of the three must move to `view`, and its caller gets the same facts in one reply. + +## Rule check + +| Rule | Application | +| --- | --- | +| §1 parts and Capabilities | BranchLine is one branch part and a Capability: it folds its own committed facts, writes its own keyed blocks, and TimelineTree records the move it writes the note for. | +| §2 scopes | Branch scope: role, roster, cursors and notes belong to one line and end with it. | +| §3 orthogonality | It reads its own facts and the directory record; it writes only its own line and steers its opener through the opener's input owner. | +| §4 rule 1 | Its writes are inputs of its own line, admitted once. | +| §4 rule 2 | The ended notice travels as `branch/ended`; the opener's own BranchLine writes its line. The idle notice is steered into the opener's queue. | +| §4 rule 3 | Handlers register tasks; no handler awaits I/O of another owner. | +| §4 rule 4 | Its state is rebuildable from its own facts; the read cursors are re-derived from its own tool results. | +| §4 rule 5 | No batch crosses. | +| §4 rule 6 | The blocks reach the model as inputs of their own line; no other path is added. | +| §4 rule 7 | It uses the tree's handle and its own line's input entry; it reads no node, queue or scope. | +| §4 rule 8 | No infrastructure change. | +| §4 rule 9 | Notes are published after their batch commits. | +| §7 | Every argument and reply is data and a line is an id; no object or handle crosses, except the owner's internal weak handle. Deleting the old surface and migrating every caller is one change. The owner answers its own state and facts, never another owner's record. | +| ADR 002 D1 | Branch scope: the line's own view dies with the line. | +| ADR 002 D2 | No wiring plugin: the service is on `BranchLine`; the weak tree handle is an internal reference. | +| ADR 002 D3 | Depends only on the branch services, its own input owner and the tree's handle. | +| ADR 002 D4 | The idle-notice policy is the line's opening data, not a setting of this part. | +| ADR 002 D5 | The contract is ids and values; the Rust binding is the appendix. | +| ADR 027 | BranchTool reaches this owner with `line_owner::(line)`, a data face of the branch group (D1–D3); a Session part sees `SessionClosing` and `NoLine`, never `NoSession`. | + +## Requirements raised to mechanism owners + +None beyond TimelineTree's: BranchTool is a Session part and reaches this owner with `line_owner::(line)`, which is the runtime's id routing stated there; a Session part sees `SessionClosing` and `NoLine`, never `NoSession` ([#2127](https://github.com/arcships/dim/issues/2127); [SessionScope](https://github.com/arcships/dim/pull/2093) states the Session side). + +## Binding appendix + +The service is marked on `BranchLine`; the wire name is `branchLine`. + +```rust +#[derive(Debug, Clone, Copy, PartialEq, Eq, serde::Serialize, serde::Deserialize)] +#[serde(rename_all = "camelCase")] +pub enum LineRole { + Main, + Tool, + Host, + User, +} + +#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)] +#[serde(rename_all = "camelCase")] +pub struct HeldBlock { + pub target: String, + pub head: u64, +} + +/// One line's published view. Named apart from TimelineTree's `LineState`. +#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)] +#[serde(rename_all = "camelCase")] +pub struct LineView { + pub role: LineRole, + #[serde(skip_serializing_if = "Option::is_none")] + pub parent: Option, + pub ending: bool, + #[serde(skip_serializing_if = "Option::is_none")] + pub cursor: Option, + #[serde(skip_serializing_if = "Option::is_none")] + pub blocked: Option, +} + +#[derive(Debug, Clone, serde::Serialize, serde::Deserialize, thiserror::Error)] +#[serde(tag = "code", rename_all = "snake_case")] +pub enum LineViewError { + #[error("line {line} has no directory record yet")] + UnknownBranch { line: String }, + #[error("the line's history could not be read")] + Storage, + #[error("the Session is closing")] + Closed, +} + +#[rutis::service(name = "branchLine")] +impl BranchLine { + pub async fn view(&self, target: Option) -> Result { + // ... + } +} +``` + +## Current implementation + +The code here still uses the pre-contract names (`TreeCommands`, `treeCommands`); the contract above is the target. + +Owner: [timeline_tree.rs](../../../../crates/dim-agent-capabilities/src/timeline_tree.rs). +Folds the line's own committed facts into its role, the tool lines it opened, +the state of its current turn and the line's read cursors, and writes its roster, +the parent block, the idle notice, the ended notice and the one status note a +move of the default branch writes on a participant, through the tree's handle. + +Its role and its parent come from +`TreeCommands.info`, which is filled from the parent's `branch/create` at +creation and at restore. + +### Data face + +The branch-scoped `branchLine` face exposes the owner's existing read operations: +`resolved()` returns `[role, parent]` or `null`, where role is `main` (the root), `tool`, `host` (a plugin line) or +`user` (a line a client opened); `ending()` reports whether the line committed its own `branch/end`; +`cursor(target)` returns its latest successful read cursor for that target or +`null`. Cursor read failures use the standard `AgentError` name, variant code +and display message on the wire; native error source identity is not serialized. +The native binding and foreign dispatcher call these same operations. Reads retain the current cached +role/cursor behavior and load only the requested target's cursor when needed; +they do not read or rebuild all history. Writer lifecycle and event settlement +are unchanged. See [service faces](../../../design/service-faces.md). + +### Dependencies + +| Service | Purpose | +| --- | --- | +| `B:Dispatcher` | Consume the line's own facts in order after the rebuild. | +| `B:Timeline` | Fix the committed mount cutoff. | +| `B:TimelineIdentity` | The line's own id. | +| `B:BranchLifecycle` | Wait for the branch to be Active before writing. | +| `S:SessionLifecycle` | Wait for the restored child directory to be published before roster repair. | +| `S:TreeCommands` | `info` for the role and its lines; `head`, the crate-internal `turn_ends` and the parent's new-activity check for the parent block; `default_branch`, the crate-internal move signal and the line's own queue of owed moves for the status note; `input` for every write. | +| `S:GuideEntries` | Register the roster and message entries on every line, until this part unloads. | + +### Events and lifetime + +Consumes `branch/create`, `branch/create-failed`, `branch/ended`, `branch/end`, +`input/message`, `input/applied`, `input/consumed`, `input/deleted`, `turn/start`, +`turn/end`, `stop/interrupt`, `step/tool-use` and `step/tool-result`. It writes only +`input/message`, through the tree's input path. + +- **Status note.** On a line that is not the root, one keyed Append under `branch:line` when the + line becomes the default branch or stops being it, read in commit order from the queue the tree + filled when the move committed, woken by its move signal. It + restates the line's birth identity byte for byte and then the sentences the move changes; the + root never receives one, and a load whose latest block disagrees with the tree writes the + missing note once; on the tree's current default branch the load also compares that block's text + with the note this code writes, and replaces a note an older rule set left once (design [§5](../../../design/timeline-branches.md#5-parts), [§12.1](../../../design/timeline-branches.md#121-context-mapping)). +- **Roster.** On a line that has opened tool lines, a keyed Append under `branch:roster` of `` lists the lines it opened with the tool that are still open, in the order it opened them, with the + first line of each purpose; when none is open the key is retired. A plugin line is never on a roster, and neither is a line the user opened: it stays in the Session's directory and coordinates its own tool lines. A child whose inherited prefix holds a live roster gets one block in its opening input that retires that key, so a line that opened no tool line of its own keeps no list; TimelineTree writes it with the identity block (design [§7.1](../../../design/timeline-branches.md#71-keyed-state-branchline-branchroster-and-branchparent)). +- **Parent block.** On a line that is not the root, one keyed Append of + `` on the line itself when its opener ends a turn past + the line's read cursor for it, the head the latest block reported, and the + line's opening, the sequence of its `branch/create` on the parent. It names + the parent, that head and the cursor, and never carries the parent's + content. The fold keeps the cursor of each successful read from the line's + own `step/tool-use` and `step/tool-result`, so a replay rebuilds it. The block is + decided from the line's state rather than the parent's signal: the parent's + turn-end, published by TimelineTree, and the line's own write queue wake the + writer, and consuming, deleting or interrupting a held block queues the same + decision. An idle line is not woken, and the root gets none. A child whose + inherited prefix holds a live parent block, meaning a nested line, gets one + more block in its opening input, naming its own parent at the cut; + TimelineTree writes it with the identity block + (design [§7.1.1](../../../design/timeline-branches.md#711-the-parent-block-branchparent)). +- **Idle notice.** On a line opened by the tool, one Steer to its opener at a `turn/end` that + neither steered the opener in that turn, called `end`, nor left a driving + input pending, and only while the line is not the current default branch. A steer counts only once its tool result says the call was + accepted: a refused or denied call wrote nothing to the parent, which would + otherwise wait on silence. +- **Ended notice.** On the opener, the roster update and `` in one + Steer, for any end of a tool line it opened other than that line's own `end`. +- **Status note.** On the new default branch and on the former one, one keyed Append of + `` under `branch:line`, carrying `default`, restating the identity it replaces + and then the rules that hold while the line is, or is no longer, the default branch. The key is + the identity's, so a compaction replays the note and the line still knows which line it is. The + note states no rule another line could contradict: the protection of the default branch's chain + is decided when `end` is called, from the tree. The root gets no note, because neither of its + rules changes with the role, so a note to it would say nothing. + +BranchLine mounts at the committed Dispatcher cutoff without reading historical events. It starts its writer after both branch and Session publication so all current child directory entries are available. Roster repair reads known current creation positions and the last roster block. A root whose stored history was written before the key split also holds its old roster under `branch:line`; its load reads that block once and retires the key with the roster write, alone when none is owed, so the root keeps no identity, as a root has none. Parent notices read the last parent block and the requested parent's read cursor. Old turn progress is not restored; a recovery turn end does not emit an idle notice. Read cursors are loaded for one target when used, and neither ordinary input history nor all tool results are retained. No recovery event is written. + +### Tests + +[branch_flow.rs](../../../../crates/dim-agent-capabilities/tests/branch_flow.rs): +`the_root_lists_its_open_tool_lines_under_the_roster_key`, +`a_configured_roster_closing_reaches_the_roster`, +`an_idle_line_tells_main_once_when_its_turn_ends_without_a_word`, +`a_tool_line_ends_itself_and_main_learns_it_from_the_roster`, +`an_end_from_outside_a_tool_line_wakes_main_with_a_notice`, +`a_roster_and_an_identity_replay_separately_after_a_compaction`, +`a_child_cut_after_a_roster_retires_it_and_one_cut_before_gets_nothing`, +`the_roots_roster_from_before_the_key_split_is_retired_at_load`, +`an_opener_that_is_not_the_root_keeps_its_identity_and_its_roster`, +`a_status_note_and_a_live_roster_do_not_retire_each_other`, +`a_user_opened_default_branch_coordinates_the_line_it_opens`, +`a_line_messages_and_reads_its_parent_and_the_lines_it_opened`, +`a_sibling_or_grandparent_is_refused_with_nothing_written`, +`an_idle_line_is_told_its_parent_moved_without_being_woken`, +`a_running_line_gets_the_block_with_its_next_request_once`, +`two_parent_turns_while_the_line_is_idle_write_one_block`, +`a_move_while_a_block_is_held_is_written_after_the_block_is_consumed`, +`a_move_while_a_block_is_held_is_written_after_the_block_is_deleted`, +`a_move_while_a_block_is_held_is_written_after_the_block_is_interrupted`, +`a_restore_writes_a_due_parent_block_once_and_none_without_movement`, +`an_ending_line_and_main_get_no_parent_block`, +`the_parent_block_replays_after_a_compaction`, +`the_creating_call_is_written_before_the_line_was_opened`, +`a_host_line_cut_at_the_start_is_not_told_what_happened_before_it`, +`a_host_line_cut_at_the_start_is_told_when_main_acts_after_it`, +`a_host_line_cut_before_it_was_opened_is_not_told_about_the_gap`, +`a_nested_line_is_told_its_own_parent_at_open`, +`a_childs_first_system_is_its_parents_at_the_cut`. + + +| 项 | 值 | +| --- | --- | +| 作用域 | 分支 | +| 注入 | `B:BranchLifecycle`、`B:Dispatcher`、`B:Timeline`、`B:TimelineIdentity`、`S:GuideEntries`、`S:SessionLifecycle`、`S:TreeCommands` | +| 提供 | `B:BranchLine`、`B:dyn HostDispatch#branchLine` | +| 被注入于 | — | + diff --git a/docs/architecture/rust-agent/plugins/BranchTool.md b/docs/architecture/rust-agent/plugins/BranchTool.md index 747360675d..4026d4570b 100644 --- a/docs/architecture/rust-agent/plugins/BranchTool.md +++ b/docs/architecture/rust-agent/plugins/BranchTool.md @@ -1,41 +1,206 @@ # BranchTool Owner: [timeline_tree.rs](../../../../crates/dim-agent-capabilities/src/timeline_tree.rs). -Registers the Session's `branch` tool, through which one line opens, messages, -reads and ends its lines ([timeline branches §11](../../../design/timeline-branches.md#11-the-branch-tool)). -It is installed with the default execution loop; the minimal execution profile -leaves it out. The facts it emits and consumes are BranchLine's, the branch -part below. - -`create` passes the optional idle notice policy and the Session's cap to TimelineTree. -The child restores the idle notice from its opening identity before BranchLine handles -turn ends. `create` admits two callers and refuses every other line: the root, in every -state, and the current default branch. The root's right never changes, which is what -lets a user ask it for a line while another line holds the role. The cap is a total -over the Session and counts the open tool lines that are not on the protected path, so -a line the user keeps continuing on costs no slot. TimelineTree charges the caller's -eligibility and the cap in the lock that reserves the new line, so a switch or a second -create cannot slip between a check and the reservation; publication charges nothing a -second time, and a creation that fails releases its slot. - -`end` ends the calling line and every line below it, so it guards the caller as well as -the target: only a tool line ends itself, a plugin line follows its own protocol, and a line -the user opened is ended by the user. A line that is the default branch, or that has a -descendant which is, is refused, because ending a line ends every line below it. - -## Dependencies +Scope: Session. Issue: [#2024](https://github.com/arcships/dim/issues/2024). + +The sections through [Binding appendix](#binding-appendix) are the owner contract for the model's +`branch` tool. [Current implementation](#current-implementation) describes the code as it is today. +BranchLine is its own owner with [its own contract](BranchLine.md). + +BranchTool is the model's `branch` tool: the only way a line opens, messages, reads or ends another line. It owns the tool's action menu, its kin rules and the shape of its answer. TimelineTree owns the directory and the lifecycle; BranchLine owns the calling line's view; the lines' input owners accept writes. BranchTool decides, per call, what the calling line may do and how the answer reads. + +## Use and scope: responsibility split + +BranchTool owns: + +- **The action menu.** `create`, `message`, `read`, `end`, the fields each takes, and the refusal when a field belongs to another action. +- **The kin rule.** A line messages and reads the line it was cut from and the tool lines it opened; a plugin line follows its creator's protocol and opens nothing; a line the user opened is not on a roster and is ended by the user. +- **The read page.** Which ranges a read covers, where it continues from the line's cursor, the item shapes and the effects a tool result declares. +- **The model-facing text** of every refusal and every page. + +Callers keep: nothing — the tool is the model's entrance. The Session owns the tool registry and the assembly decides whether the tool is installed. + +| Requirement (model intent) | Compose from the operations below without breaking the owner's invariants? | Handling | +| --- | --- | --- | +| Open a line to work on a part of the task | No: the cut is the calling request's own start, which the tool reads from its execution context | `timelineTree.create` | +| Send a line a message or a last word | No: the write belongs to the target line's input owner; the tool decides the kin rule | Target line's input owner by id, with the mode the tool chose | +| Read what a line did, continuing where the last read stopped | No: the continuation is the calling line's cursor, owned by BranchLine; the page boundaries and the rendering are the tool's | `branchLine.view`, `timelineTree.read` | +| End the calling tool line with its last word | No: the end and the last word are one settled operation | `timelineTree.end` | +| Learn what the calling line may do | No: role and parent are BranchLine's fold | `branchLine.view` | +| Check that a target belongs to the pair before messaging or reading it | No: the record's parent and source decide it | `timelineTree.line` with `{line}` | + +## Caller example + +The model calls `branch`; the tool maps one action onto the owner operations and answers one page or one refusal. + +```rust +// create: the cut is this request's own start, read from the execution context. +let cut = self.request_start(execution).await?; // business: the calling request's start +let line = tree.create(CreateLine { + parent: execution.branch_id.clone(), + cut, + prompt, + source: BranchSource::Tool { turn_id, request_id, call_id }, + idle_notice: input.idle_notice, +}, cancelled).await + .map_err(refusal_from_line_error)?; + +// message: the kin rule is the tool's; the write is the target line's owner. +if !kin(&own, &target) { + return refused("branch_not_kin"); +} +line_owner::(target.line.clone())? + .submit(InputMessageData::message(&own.line, &target.line, content, mode)) + .await?; + +// read: the cursor is the calling line's, the page is the tool's rendering. +let own = line_owner::(&execution.branch_id)?.view(Some(target.clone())).await?; +// Without `after` and without a cursor: a line the caller opened starts at 0, + // the line it was cut from at its own opening cut. + let start = if target.opened_by_caller { 0 } else { cut }; + let after = input.after.unwrap_or_else(|| own.cursor.unwrap_or(start)); +let page = tree.read(ReadLines { + line: target.line.clone(), + from: Some(after + 1), + through: Some(target.head), + fields: Some(READ_FIELDS.to_vec()), + limit: Some(input.limit.unwrap_or(READ_PAGE_LIMIT)), +}).await + .map_err(refusal_from_line_error)?; +``` + +## Own contract + +### Contract dependencies + +| Service | Purpose | +| --- | --- | +| `S:ToolRegistry` | Register the `branch` tool, until this part unloads. | +| `S:TimelineTree` | `create`, `end`, `read` and `line`. | +| `line_owner::` | The calling line's role, end state, its cursor for a target and the held parent block (`view`). | +| `line_owner::` | `submit`, for the message action. This is a call by line id, not an injection. | + +### Operations + +One tool, one request object, no service: + +| Field | Meaning | +| --- | --- | +| `action` | `create`, `message`, `read` or `end`; required, no other property allowed | +| `prompt` | `create`: what the new line is for | +| `at` | `create`: the cut; absent means this request's own start | +| `idleNotice` | `create`: `steer` (default) or `none` | +| `to`, `content`, `mode` | `message`: the target, the text and the mode (`append` or `steer`) | +| `branch`, `after`, `limit` | `read`: the target, the continuation and the page size | +| `content` | `end`: the line's last word | + +Every reply is text; `read` carries a structured `{items, nextCursor, done}`. A refusal is an error result whose `structuredContent` carries `{error, message}`, where `error` is the code below and `message` the text; no write happens. An argument error is a failed result with no code, as today (`Invalid branch arguments: …`). + +### Errors + +The tool's coded refusals are the accepted set ([timeline branches §11](../../../design/timeline-branches.md#11-the-branch-tool)); an argument error and every other ending are failed results without a code, so the model-visible result shape does not change. The pair check reads `line(id)` first: `unknown_branch` there becomes `branch_not_kin`, never a separate code. A `NoLine` after the pair check succeeded means the target's instance closed in between, which each action reports as `branch_ended`. `SessionClosing` is a failed result without a code, and a Session part never receives `NoSession` ([#2127](https://github.com/arcships/dim/issues/2127); [TimelineTree](TimelineTree.md#session-parts-reaching-a-lines-owners)). + +Refusals, with the code in `structuredContent.error`: + +| Code | Actions | What the model does next | +| --- | --- | --- | +| `branch_not_opener` | `create` | Only the root and the conversation line open lines; move the conversation or ask one of those | +| `branch_limit_reached` | `create` | End an open tool line first | +| `branch_not_kin` | `message`, `read` | Address the line it was cut from, or a line it opened | +| `branch_not_tool_line` | `message`, `read` | A plugin line follows its creator's protocol; a plugin line reads only the line it was cut from | +| `branch_ended` | `create`, `message`, `read`, `end` | The target's own end is recorded, or the calling line's own end is: read the line instead. Not retryable; an owed last word is delivered by restore | +| `branch_cannot_end` | `end` | Not retryable as is: only a tool line ends itself, and not while its chain holds the conversation line | + +Endings without a code, reported as a failed result: + +| Ending | Actions | What the model does next | +| --- | --- | --- | +| The read's `after` is past the target's head | `read` | Re-read `line` and start at or below its head; retry once | +| The page's cutoff is inside an atomic batch | `read` | Start at the record's head, which ends a batch | +| A continuation arrived without its `after` | `read` | Resend `after` with the current record | +| The tool's own start is not a usable cut | `create` | Report it; do not retry | +| `SessionClosing` or a closing Session | all | Stop; nothing more happens in this generation | +| An admitted creation cancelled by its caller | `create` | The line publishes without a waiter and the call has no result | + +### Flows + +| Action | Normal path | Caller cancels | Session closes | Settled by | +| --- | --- | --- | --- | --- | +| `create` | Read this request's start as the cut, admit and build through the tree, answer the line id | A cancel before admission writes nothing; after admission the line publishes and the call has no result, because the call itself was cancelled | `branch_ended` when the parent ended; a failed result without a code when the Session is closing | TimelineTree | +| `message` | Check the pair, write into the target's queue — the target's input owner refuses with `branch_ended` once its record is `ending` or `ended` — answer the target id | The write is one commit; a cancelled call writes nothing | A failed result without a code | The target line's input owner | +| `read` | Resolve the target record, the cursor and the head, read one page, render items | Nothing to release | A failed result without a code | TimelineTree, BranchLine | +| `end` | Check that the caller is a tool line and that its own end is not yet recorded, then call the tree's `end` with the last word; a line that already recorded its own end answers `branch_ended` and an owed last word is delivered by restore | The end settles even if the call stops watching | A failed result without a code | TimelineTree | + +## Supersedes + +- [Timeline branches §6](../../../design/timeline-branches.md#6-messages-between-lines)'s **Read** paragraph, whose read path now points at this page's contract. + +## Client-visible changes + +None: the tool's action menu, fields, result shape and refusal codes are unchanged. + +## Exceptions with reasons + +- The tool reads the calling request's own start to cut the new line: the request identity is the tool execution's context, not a line fact, so no owner can supply it. +- The rendered page repeats a tool result's declared effects and cuts a command at its 200th character: the rendering is model-facing text and belongs to the tool that reads it. + +## Verification + +Flow tests on the tool: + +- A root and the conversation line open a line; a tool line and a plugin line answer `branch_not_opener` with no write. +- The Session's cap counts open tool lines outside the conversation line's chain; a creation failure releases the slot. +- A message reaches its receiver in the requested mode; a sibling or a grandparent answers `branch_not_kin` with nothing written. +- A read of the line the caller was cut from starts at the cut; a read without `after` continues from the line's cursor; an `after` past the head answers an error and leaves the cursor unchanged. +- `end` on a line that is not the default line withholds no final word; a line whose chain holds the conversation line answers `branch_cannot_end`. + +## Rule check + +| Rule | Application | +| --- | --- | +| §1 parts and Capabilities | BranchTool is one Session part and not a Capability: it registers a tool and folds nothing. | +| §2 scopes | Session scope for the registration; each call acts on the calling line's id. | +| §3 orthogonality | It reads the directory and the calling line's state and writes through owners. | +| §4 rule 1 | A refused call writes nothing; an accepted one lands in the target owner's operation. | +| §4 rule 2 | It writes no fact of its own; the owners it calls do. | +| §4 rule 3 | The tool returns after its work; waits belong to the owners it calls. | +| §4 rule 4 | It keeps no state between calls except what BranchLine publishes. | +| §4 rule 5 | It reads whole batches through the tree's read. | +| §4 rule 6 | The page is the tool result, the only text the model reads. | +| §4 rule 7 | It uses the owners' operations; it holds no scope, node or queue. | +| §4 rule 8 | One requirement is raised with TimelineTree's: resolving a line id to a branch-scope service ([#2127](https://github.com/arcships/dim/issues/2127)). | +| §4 rule 9 | It writes no fact. | +| §7 | Every argument and reply is data and a line is an id; no object or handle crosses, except the owner's internal weak handle. Deleting the old surface and migrating every caller is one change. The owner answers its own state and facts, never another owner's record. | +| ADR 002 D1 | Session scope: one registration for every line. | +| ADR 002 D2 | No wiring plugin: the tool belongs to the TimelineTree plugin's feature. | +| ADR 002 D3 | Depends only on the registry, the tree and BranchLine. | +| ADR 002 D4 | The profile decides whether the tool is installed. | +| ADR 002 D5 | The tool's request and reply are data; the Rust binding is the appendix. | +| ADR 027 | The tool reaches BranchLine and a target's input owner with `line_owner::(line)`. | + +## Requirements raised to mechanism owners + +The same one as TimelineTree's: the tool reaches a line's input owner and BranchLine with `line_owner::(line)`, which needs the runtime's id routing ([#2127](https://github.com/arcships/dim/issues/2127); [SessionScope](https://github.com/arcships/dim/pull/2093) states the Session side). + +## Binding appendix + +No service and no wire name. The request is the tool's input object; the refusal codes are its data. The Rust side is the tool handler registered with `ToolRegistry`. + +## Current implementation + +### Dependencies | Service | Purpose | | --- | --- | -| `S:TreeCommands` | Create a child, write and read a line, and end a line, per call. | | `S:ToolRegistry` | Register `branch`, until this part unloads. | +| `S:TreeCommands` | Create a child, write and read a line, and end a line, per call. | -## Events and lifetime +### Events and lifetime No events of its own: the tree writes `branch/create`, `branch/start` and `branch/end`; a call writes its result, and `message` and `end` write their -inputs through `TreeCommands.input` (`end` the final message before the -command it writes). The input is one +inputs through `TreeCommands.input` today; an end's final message rides on +`branch/end` and the tree delivers it ([the contract](#own-contract)). The input is one action-based object, `{action, prompt?, at?, to?, content?, mode?, branch?, after?, limit?}`, with `action` required and no other properties; risk stays `session`, and Approval admits each call like any tool @@ -60,7 +225,7 @@ shares the rule). The target is the line the caller was cut from or a line the c line, which BranchLine retains from live results and otherwise reads for that specific target from its own `step/tool-use` and `step/tool-result` (design [§6](../../../design/timeline-branches.md#6-messages-between-lines)). -## Tests +### Tests [flows.rs](../../../../crates/dim-agent-capabilities/tests/flows.rs): `branch_tool_reuses_capabilities_without_replaying_ancestor_inputs`; @@ -93,128 +258,3 @@ specific target from its own `step/tool-use` and `step/tool-result` (design [§6 | 提供 | — | | 被注入于 | — | - -## BranchLine - -Owner: [timeline_tree.rs](../../../../crates/dim-agent-capabilities/src/timeline_tree.rs). -Folds the line's own committed facts into its role, the tool lines it opened, -the state of its current turn and the line's read cursors, and writes its roster, -the parent block, the idle notice, the ended notice and the one status note a -move of the default branch writes on a participant, through `S:TreeCommands`. - -Its role and its parent come from -`TreeCommands.info`, which is filled from the parent's `branch/create` at -creation and at restore. - -### Data face - -The branch-scoped `branchLine` face exposes the owner's existing read operations: -`resolved()` returns `[role, parent]` or `null`, where role is `main` (the root), `tool`, `host` (a plugin line) or -`user` (a line a client opened); `ending()` reports whether the line committed its own `branch/end`; -`cursor(target)` returns its latest successful read cursor for that target or -`null`. Cursor read failures use the standard `AgentError` name, variant code -and display message on the wire; native error source identity is not serialized. -The native binding and foreign dispatcher call these same operations. Reads retain the current cached -role/cursor behavior and load only the requested target's cursor when needed; -they do not read or rebuild all history. Writer lifecycle and event settlement -are unchanged. See [service faces](../../../design/service-faces.md). - -### Dependencies - -| Service | Purpose | -| --- | --- | -| `B:Dispatcher` | Consume the line's own facts in order after the rebuild. | -| `B:Timeline` | Fix the committed mount cutoff. | -| `B:TimelineIdentity` | The line's own id. | -| `B:BranchLifecycle` | Wait for the branch to be Active before writing. | -| `S:SessionLifecycle` | Wait for the restored child directory to be published before roster repair. | -| `S:TreeCommands` | `info` for the role and its lines; `head`, the crate-internal `turn_ends` and the parent's new-activity check for the parent block; `default_branch`, the crate-internal move signal and the line's own queue of owed moves for the status note; `input` for every write. | -| `S:GuideEntries` | Register the roster and message entries on every line, until this part unloads. | - -### Events and lifetime - -Consumes `branch/create`, `branch/create-failed`, `branch/ended`, `branch/end`, -`input/message`, `input/consumed`, `input/deleted`, `turn/end`, `step/tool-use` and -`step/tool-result`. It writes only `input/message`, through the tree's input path. - -- **Status note.** On a line that is not the root, one keyed Append under `branch:line` when the - line becomes the default branch or stops being it, read in commit order from the queue the tree - filled when the move committed, woken by its move signal. It - restates the line's birth identity byte for byte and then the sentences the move changes; the - root never receives one, and a load whose latest block disagrees with the tree writes the - missing note once; on the tree's current default branch the load also compares that block's text - with the note this code writes, and replaces a note an older rule set left once (design [§5](../../../design/timeline-branches.md#5-parts), [§12.1](../../../design/timeline-branches.md#121-context-mapping)). -- **Roster.** On a line that has opened tool lines, a keyed Append under `branch:roster` of `` lists the lines it opened with the tool that are still open, in the order it opened them, with the - first line of each purpose; when none is open the key is retired. A plugin line is never on a roster, and neither is a line the user opened: it stays in the Session's directory and coordinates its own tool lines. A child whose inherited prefix holds a live roster gets one block in its opening input that retires that key, so a line that opened no tool line of its own keeps no list; TimelineTree writes it with the identity block (design [§7.1](../../../design/timeline-branches.md#71-keyed-state-branchline-branchroster-and-branchparent)). -- **Parent block.** On a line that is not the root, one keyed Append of - `` on the line itself when its opener ends a turn past - the line's read cursor for it, the head the latest block reported, and the - line's opening, the sequence of its `branch/create` on the parent. It names - the parent, that head and the cursor, and never carries the parent's - content. The fold keeps the cursor of each successful read from the line's - own `step/tool-use` and `step/tool-result`, so a replay rebuilds it. The block is - decided from the line's state rather than the parent's signal: the parent's - turn-end, published by TimelineTree, and the line's own write queue wake the - writer, and consuming, deleting or interrupting a held block queues the same - decision. An idle line is not woken, and the root gets none. A child whose - inherited prefix holds a live parent block, meaning a nested line, gets one - more block in its opening input, naming its own parent at the cut; - TimelineTree writes it with the identity block - (design [§7.1.1](../../../design/timeline-branches.md#711-the-parent-block-branchparent)). -- **Idle notice.** On a line opened by the tool, one Steer to its opener at a `turn/end` that - neither steered the opener in that turn, called `end`, nor left a driving - input pending, and only while the line is not the current default branch. A steer counts only once its tool result says the call was - accepted: a refused or denied call wrote nothing to the parent, which would - otherwise wait on silence. -- **Ended notice.** On the opener, the roster update and `` in one - Steer, for any end of a tool line it opened other than that line's own `end`. -- **Status note.** On the new default branch and on the former one, one keyed Append of - `` under `branch:line`, carrying `default`, restating the identity it replaces - and then the rules that hold while the line is, or is no longer, the default branch. The key is - the identity's, so a compaction replays the note and the line still knows which line it is. The - note states no rule another line could contradict: the protection of the default branch's chain - is decided when `end` is called, from the tree. The root gets no note, because neither of its - rules changes with the role, so a note to it would say nothing. - -BranchLine mounts at the committed Dispatcher cutoff without reading historical events. It starts its writer after both branch and Session publication so all current child directory entries are available. Roster repair reads known current creation positions and the last roster block. A root whose stored history was written before the key split also holds its old roster under `branch:line`; its load reads that block once and retires the key with the roster write, alone when none is owed, so the root keeps no identity, as a root has none. Parent notices read the last parent block and the requested parent's read cursor. Old turn progress is not restored; a recovery turn end does not emit an idle notice. Read cursors are loaded for one target when used, and neither ordinary input history nor all tool results are retained. No recovery event is written. - -### Tests - -[branch_flow.rs](../../../../crates/dim-agent-capabilities/tests/branch_flow.rs): -`the_root_lists_its_open_tool_lines_under_the_roster_key`, -`a_configured_roster_closing_reaches_the_roster`, -`an_idle_line_tells_main_once_when_its_turn_ends_without_a_word`, -`a_tool_line_ends_itself_and_main_learns_it_from_the_roster`, -`an_end_from_outside_a_tool_line_wakes_main_with_a_notice`, -`a_roster_and_an_identity_replay_separately_after_a_compaction`, -`a_child_cut_after_a_roster_retires_it_and_one_cut_before_gets_nothing`, -`the_roots_roster_from_before_the_key_split_is_retired_at_load`, -`an_opener_that_is_not_the_root_keeps_its_identity_and_its_roster`, -`a_status_note_and_a_live_roster_do_not_retire_each_other`, -`a_user_opened_default_branch_coordinates_the_line_it_opens`, -`a_line_messages_and_reads_its_parent_and_the_lines_it_opened`, -`a_sibling_or_grandparent_is_refused_with_nothing_written`, -`an_idle_line_is_told_its_parent_moved_without_being_woken`, -`a_running_line_gets_the_block_with_its_next_request_once`, -`two_parent_turns_while_the_line_is_idle_write_one_block`, -`a_move_while_a_block_is_held_is_written_after_the_block_is_consumed`, -`a_move_while_a_block_is_held_is_written_after_the_block_is_deleted`, -`a_move_while_a_block_is_held_is_written_after_the_block_is_interrupted`, -`a_restore_writes_a_due_parent_block_once_and_none_without_movement`, -`an_ending_line_and_main_get_no_parent_block`, -`the_parent_block_replays_after_a_compaction`, -`the_creating_call_is_written_before_the_line_was_opened`, -`a_host_line_cut_at_the_start_is_not_told_what_happened_before_it`, -`a_host_line_cut_at_the_start_is_told_when_main_acts_after_it`, -`a_host_line_cut_before_it_was_opened_is_not_told_about_the_gap`, -`a_nested_line_is_told_its_own_parent_at_open`, -`a_childs_first_system_is_its_parents_at_the_cut`. - - -| 项 | 值 | -| --- | --- | -| 作用域 | 分支 | -| 注入 | `B:BranchLifecycle`、`B:Dispatcher`、`B:Timeline`、`B:TimelineIdentity`、`S:GuideEntries`、`S:SessionLifecycle`、`S:TreeCommands` | -| 提供 | `B:BranchLine`、`B:dyn HostDispatch#branchLine` | -| 被注入于 | — | - diff --git a/docs/architecture/rust-agent/plugins/README.md b/docs/architecture/rust-agent/plugins/README.md index 1fd80891c6..ea6e9e9580 100644 --- a/docs/architecture/rust-agent/plugins/README.md +++ b/docs/architecture/rust-agent/plugins/README.md @@ -29,7 +29,7 @@ dependency is not necessarily a plugin with the same name. | [WorkspaceTools](WorkspaceTools.md) | WorkspaceToolsOwner | WorkspaceTools | FileReads, BackgroundExec | | [Wait](Wait.md) | — | Wait | WaitBranch | | [Recall](Recall.md) | — | Recall | — | -| [TimelineTree](TimelineTree.md) | — | TimelineTree | TreeTimeline | +| [TimelineTree](TimelineTree.md) | — | TimelineTree | [TreeTimeline](TreeTimeline.md) | | [InputQueue](InputQueue.md) | — | InputMethods | InputQueue | | [Permission](Permission.md) | — | — | Permission, Approval | | [ToolExecution](ToolExecution.md) | — | [ToolMethods](ToolMethods.md) | ToolBinding, ToolExecutor | @@ -39,7 +39,7 @@ dependency is not necessarily a plugin with the same name. | [PromptSuggestion](PromptSuggestion.md) | — | PromptSuggestion | — | | [Attachments](Attachments.md) | — | Attachments | — | | [Questions](Questions.md) | — | Questions | — | -| [BranchTool](BranchTool.md) | — | BranchTool, BranchLine | — | +| [BranchTool](BranchTool.md) | — | BranchTool | [BranchLine](BranchLine.md) | | [ContextPreparation](ContextPreparation.md) | — | — | ContextPreparation, [ContextUsage](ContextUsage.md) | | [Prompt](Prompt.md) | — | — | Prompt | | [Loop](Loop.md) | — | [LoopMethods](LoopMethods.md) | Loop | diff --git a/docs/architecture/rust-agent/plugins/TimelineTree.md b/docs/architecture/rust-agent/plugins/TimelineTree.md index c1ec933721..7f27f0d34a 100644 --- a/docs/architecture/rust-agent/plugins/TimelineTree.md +++ b/docs/architecture/rust-agent/plugins/TimelineTree.md @@ -1,6 +1,436 @@ # TimelineTree -The TimelineTree plugin registers TimelineTree in every Session and TreeTimeline in every branch. +The TimelineTree plugin registers TimelineTree in every Session and TreeTimeline in every branch. Scope: Session. Issue: #2024. + +The sections through [Binding appendix](#binding-appendix) are the owner contract for [#2024](https://github.com/arcships/dim/issues/2024). [Current implementation](#current-implementation) describes the code as it is today. + +TimelineTree owns a Session's lines: the directory of what lines exist, each line's beginning and end, and the facts a line's neighbours learn. A line is one branch scope with an id; the RPC field naming a line stays `branchId`. The code this contract replaces is described under [Current implementation](#current-implementation). + +TreeTimeline, BranchLine and BranchTool are separate owners in this group with their own documents ([TreeTimeline](TreeTimeline.md), [BranchLine](BranchLine.md), [BranchTool](BranchTool.md)). A line's own owners — its input queue, its capabilities, its Prompt — are other owners; a Session part reaches them through `line_owner` (see below), and this contract provides no entry into them. + +## Use and scope: responsibility split + +TimelineTree owns: + +- **The line directory.** Every line's id, parent, cut, source, state (open, ending, ended), head and end event, and the line the Session's conversation is on. One read answers the default together with the whole directory, so a client never pairs a default from before a move with a directory from after one. +- **A line's beginning.** The cut's validity, the caller's eligibility, building the branch scope, publishing it, and the opening blocks the child starts with — identity, the retired roster, the parent block — written where the child has no owner yet. +- **The line cap's enforcement, for tool opens only.** The cap is BranchTool's configuration ([timeline branches §6.1](../../../design/timeline-branches.md#61-resources-and-limits)); it counts the open tool lines outside the conversation line's chain and the admitted tool reservations, and it is charged — with the tool opener's eligibility — in the one lock that reserves the line. A user line and a plugin line are never refused by it and never count ([timeline branches §6.1](../../../design/timeline-branches.md#61-resources-and-limits)). +- **A line's end.** The target checks, ending descendants before their parent, committing `branch/end` with a tool end's final message, delivering that message to the parent, closing the scope, and writing `branch/ended` on the parent — in that order, so a stop after any step leaves one state restore can finish. +- **Ended lines' history.** A line's scope is gone once ended; its facts stay readable at the line's fixed head for as long as the Session lives. +- **Each live line's scope and the weak handle to this owner.** A line's scope is created, held and closed here; the owner's branch parts receive a weak handle to this owner, never a strong one, so a line's scope cannot keep the tree alive. + +Callers keep: + +- What a line is for: a goal, a collaboration member, a tool line, a plugin line, a terminal line, a client's line. +- The texts the model reads and their guide entries, except the opening blocks this owner writes. +- Which facts they fold, and every decision about their own line. +- Which line a request names when a client or a method may name none: they read `default` first. + +| Requirement (callers) | Compose from the operations below without breaking the owner's invariants? | Handling | +| --- | --- | --- | +| A client opens a conversation line at a position it names | No: the cut, the parent's state and the opening blocks are this owner's; the client's open has no opener check and no cap | `create` with a `user` source | +| The model opens a tool line cut before its own request | No: the tool's eligibility and the cap must be charged in the same lock that reserves the line, and the opening blocks are this owner's | `create` with a `tool` source | +| A plugin opens a line it will drive | No: the opening blocks and the parent's state are this owner's; a plugin open has no opener check and no cap, and its source keeps it off the default | `create` with a `host` source | +| End a line: a tool line ending itself with a last word, a user ending a line, a plugin ending what it opened | No: the target's guards, ending descendants first, the final message, closing the scope and the end facts are one settled operation | `end` | +| Move the conversation to another line and tell every participant | No: the pointer and the `branch/default` fact commit here, and the transitions are queued for each participant's own writer | `set_default` | +| Read the lines and the current default | No: `default` and the directory come from one read; states, heads and end events are this owner's | `directory` | +| Read one line's record: is it open, where is its head, when did it end | No: the record is the directory's own entry | `line` | +| Read a line's facts at a cutoff: a client's history, a method's turn, a tool's recall, an index build, a report's evidence | No: the cutoff's validity, the atomic-batch boundary, the fixed head of an ended line and the continuation rule are this owner's knowledge | `read` | +| Read a line and its ancestors as one cut: a search over the chain, an index over the chain | No: each ancestor is bounded by the cut the line inherited from it, and the chain is the directory's knowledge | `read` with the chain scope | +| Read a line's purpose and source for its detail view | Yes: `line` carries the cut and source; the purpose is the parent's `branch/create` facts at that cut | Business composes with `line` and `read` | +| Learn whether a line is still open before writing to it | Yes: the record's state answers open, ending or ended | Business composes with `line` | +| Learn the configuration a line adopted at a cutoff | Yes for a live line: Prompt answers it through `line_owner`; for an ended line the facts are read at the fixed head | Business composes with `read`; Prompt keeps its own operation | +| Write an input to a line | Not this owner: the line's input owner decides order, idempotency and rejection | `line_owner::` | +| Act on a line's own owner: compact it, read its usage, withdraw from it, approve in it, adopt a language or a profile in it | Not this owner: each is that owner's own operation | `line_owner::` | +| Create the root line, restore the stored directory, settle on close | No, but not public: the Session assembly drives these; a client or plugin must not | Assembly-internal | + +## Caller example + +A client opens a line, reads the directory and ends a line; a Session method answers a turn read with one page. No call has a version to compare, a wait to bound, or an id the caller must release. + +```rust +// session.branch_create: the client names the parent, the cut and the purpose. +let line = tree.create(CreateLine { + parent: parent.clone(), + cut, + prompt, + source: BranchSource::User { operation_id }, + idle_notice: None, +}, cancelled).await?; + +// session.branches: the default and every line from one read. +let Directory { default, lines } = tree.directory()?; +let current = lines.iter().find(|record| record.line == default).expect("the default is a line"); + +// A Session method answering a turn read on the conversation line, at its head. +let page = tree.read(ReadLines { + line: current.line.clone(), + scope: None, + from: Some(after + 1), + through: Some(current.head), + fields: None, + limit: None, +}).await?; + +// A method that names a line reads its record first, then the same page. +let record = tree.line(requested.clone())?; +let page = tree.read(ReadLines { + line: requested, + scope: None, + from: None, + through: Some(record.head), + fields: None, + limit: None, +}).await?; + +// session.branch_end: the client ends the line it opened. +tree.end(EndLine { line, source, final_message: None }).await?; + +// Nothing is released here: the line id is a value and the record's head is a number. +``` + +A caller that needs the line's own owners — the input queue it writes into, the capability it compacts — calls no operation of this owner for that; the next section says how a Session part reaches those owners. The Session assembly drives the root line, the restore and the close through the owner's crate-private lifecycle, not through these operations, and no client or plugin may reach them. + +## Session parts reaching a line's owners + +A Session part acts on one line by line id, never through a `Branch` object. `line_owner::(line)` resolves the branch-group service `T` of the instance the runtime holds for that line, and the caller calls that owner's own operation or reads its published value ([ADR 027](../../../adr/027-cross-scope-access-by-id.md) D1). Any data face of the branch group may be reached this way, except the registration points (`sessionMethods`, `toolRegistry`, `promptRegistry`) and the lifecycle services (`timeline`, `dispatcher`, `branchLifecycle`, `timelineIdentity`); those stay inside the scope (ADR 027 D3). + +`line_owner` answers with the service. A Session part sees two of the route's answers: `SessionClosing` — this Session is closing, so the part ends its work; and `NoLine` — the branch instance is closing or gone, or the id is not this Session's, which is final for that line: no hold and no retry. The route still reaches the owner between the line's own `branch/end` and the instance's close, so an ending line is not `NoLine`. `NoSession` — no live Session instance — belongs to process callers, which take an Agents hold before calling again; a Session part is inside a live Session and never receives it ([#2127](https://github.com/arcships/dim/issues/2127)). No operation name is a string, no request is a `json!` value, and no forwarding facade sits between the caller and the owner. The runtime keeps the `(session, line)` index it builds when it constructs a line's context, routes the call itself, and hands no instance key to the caller ([ADR 027](../../../adr/027-cross-scope-access-by-id.md)); TimelineTree is not in this path. + +Caller code after the change: a Session method steering a member line, a method reading a line owner's published value, and one using another data face of the line. + +```rust +// Write the line's state: the member's input owner decides order and outcome. +line_owner::(&member)?.submit(steer_input).await?; + +// Read a line's published value: the owner answers, not its timeline. +let usage = line_owner::(&line)?.read(None, cancelled).await?; + +// Use any other data face of that line the same way. +let pending = line_owner::(&line)?.pending().await?; +``` + +A write to a line is not this owner's operation: the target's own input owner accepts it and refuses it once the line's record is `ending` or `ended`, answering `branch_ended` (the same refusal it answers today when the target's context has ended). TimelineTree states the record's state; it adds no input entry. + +A Session part that cannot resolve a line keeps its business blocked; it does not fall back to holding a `Branch`, and TimelineTree adds no forwarding operation for it. [SessionScope](https://github.com/arcships/dim/pull/2093) documents the mechanism side with this contract. + +## Own contract + +### Contract dependencies + +| Service | Purpose | +| --- | --- | +| `S:SessionScope` | `identity` for the Session id the store is keyed by, and the branch-construction entry (`openBranch`; its only caller is this owner, target, pending [#2093](https://github.com/arcships/dim/pull/2093)) that builds a line's context; the tree holds and settles what that entry returns. | +| `S:dyn TimelineStore` | The line directory and a line's facts in storage at a fixed head; a chain read goes through `readSegments` ([SessionStore](https://github.com/arcships/dim/pull/2091), target, pending its head). | +| `S:GuideEntries` | The `` and `` entries, until this part unloads ([Prompt](Prompt.md)). | + +### Operations + +| Operation | Intent | Request | Reply | Cancellation | Errors (codes) | +| --- | --- | --- | --- | --- | --- | +| `create` | Open a line at a cut of its parent; the source decides the admission | `{parent, cut, prompt, source, idleNotice?}`, `cancelled`. `cut` is a position; a `before` producer that records `at: {kind: "create"}` keeps that variant in the fact, and the tree records the create fact's own sequence as `createdAt` | the new line's id | The caller's cancel stops only the wait for admission: a creation that was admitted builds and publishes, keeps its slot, and answers nothing to a caller that left; before admission nothing is reserved and the reply is `cancelled` | `invalid_parent`, `branch_ended` (the parent ended), `invalid_cut` (over the parent's head, or not an atomic-batch boundary), `branch_not_opener` and `branch_limit_reached` (tool source only), `cancelled`, `closed` | +| `end` | End a line and settle it | `{line, source, finalMessage?}` | `{}` | None: an admitted end settles even if the caller goes away | `unknown_branch`, `branch_ended` (the target's own end is already recorded), `invalid_target` (the root never ends: the operation's own input error), `branch_cannot_end` (the target is the conversation line or an ancestor of it, so it needs a move first), `closed` | +| `set_default` | Move the conversation to a line | `{line, source}` | the line the conversation is on, an id | None: the move is one commit | `unknown_branch`, `branch_ended` (the target ended), `branch_already_default`, `branch_not_selectable` (a plugin line), `branch_target_protected` (the target or an ancestor is ending), `closed` | +| `directory` | The lines and the current default, from one read | `{}` | `{default, lines}` | None | `closed` | +| `line` | One line's record | `{line}` | `record` | None | `unknown_branch` (an id this Session never had), `closed` | +| `read` | A line's facts at a cutoff, or the line and its ancestors at one cut | `{line, scope?, from?, through?, fields?, limit?}` | `{through, events}` or `{through, rows}` | None: one bounded read | `unknown_branch`, `beyond_head` (a cutoff past the line's head), `not_batch_boundary` (a cutoff inside an atomic batch), `continuation_without_cutoff`, `closed` | + +A record is `{line, parent, cut, createdAt, source, state, head, endEvent?}`; `state` is `open`, `ending` or `ended`. `cut` is the point of the parent's history the line starts from; `createdAt` is the sequence of the line's `branch/create` on the parent, which is where the line came into being and what its opener and its own BranchLine read the line's opening by. The two differ: a line cut at an old point is created later than its cut, and a `before` producer's anchor can be either. A record exists from the reservation on. What a read answers while the build is still running, after `create` released its lock and before the scope published: | Read during the reservation | Answer | +| --- | --- | +| `line` | The record: `state: open`, `parent`, `cut`, `createdAt`, `source`, `head: 0` | +| `read` | `unknown_branch`: there is no scope and no committed fact of the line yet | +| `directory` | The line is absent; the directory lists published lines only | +| `branch.get` (App Server) | `branch_missing`, because it reads the directory | +| `end` | `unknown_branch`, for the same reason as `read` | +| `line_owner::(line)` | `NoLine`: the runtime builds the line's instance with its scope | +| The building line's own parts, in `apply` | `line` answers as above; this is the read the line's own parts make while they reconcile | + +A line whose own `branch/end` is recorded is `ending` until its scope closed and the parent holds its `branch/ended`; a repeated `end` answers `branch_ended` from that point on. An owed final message is delivered by restore, never by a repeated `end`. + +**A build that fails.** The parent gets `branch/create-failed`; the reservation is dropped and its slot released; the caller's `create` answers the build error. The `branch/create` fact stays in the parent's history as the fact of a line that was created and never published, and `branch/create-failed` carries the reason. From then on `line`, `read` and `end` answer `unknown_branch` for that id, `line_owner` answers `NoLine`, and `directory` never listed it. A caller that stopped waiting learns the outcome from `branch/create-failed` on the parent. `read` answers a live line from its scope and an ended line from the store at its fixed head, with the same shape and the same visibility. The chain scope reads only published facts, bounds every ancestor at the cut the line inherited, and keeps the original cutoff across a continuation page. `fields` absent selects the whole event data; ids and sizes cross as strings and numbers; no handle, cursor or channel crosses. + +**The default line's restore.** A `branch/default` fact names the line the conversation is on. On restore the tree reads the latest one and keeps it only when that line is live and selectable: an ended line, a plugin line, or a line created before the upgrade with a `host` source it cannot select leaves the conversation on the root, and no new fact is written. A `session/forked` written on the root after a copied `branch/default` wins: its target answers the root, so a Session forked while a line was the default comes back on the root ([timeline branches §5](../../../design/timeline-branches.md#5-parts)). A move that stopped between its fact and its notes is reconciled by the line's BranchLine, not here. + +### Errors + +| Kind (wire code) | Operations | What the caller does next | +| --- | --- | +| `invalid_parent` | `create` | Retry with an existing line, after reading `directory` | +| `invalid_cut` | `create` | Retry with the parent's head from `line`, or a cutoff that ends an atomic batch | +| `branch_not_opener` | `create` with a `tool` source | Not retryable from this line: only the root and the conversation line open lines; move the conversation first with `set_default` | +| `branch_limit_reached` | `create` with a `tool` source | Retry after ending an open tool line | +| `branch_cannot_end` | `end` | Not retryable as is: the target is the conversation line or an ancestor of it; move the conversation first and call again | +| `invalid_target` | `end` | Not retryable: the root never ends and the operation answers its own input error, as today | +| `branch_target_protected` | `set_default` | Stop and do not retry the same call: an end already on its way to the target or an ancestor wins; read `line` and act on the state found | +| `branch_already_default` | `set_default` | Not retryable and nothing happened | +| `branch_not_selectable` | `set_default` | Not retryable: a plugin line cannot be the conversation line | +| `branch_ended` | `end`, `set_default` | Not retryable: the target's own end is recorded. An owed final message is delivered by restore, and the message never delivers twice; read the line if the last word matters. `create` answers it about the **parent** instead: see the row below | +| `branch_ended` | `create` | The parent line has ended; pick a live parent. Not retryable with the same parent | +| `beyond_head` | `read` | Retry with the record's head as the cutoff | +| `not_batch_boundary` | `read` | Retry with a reply's `through`, or the head of a record | +| `continuation_without_cutoff` | `read` | Retry with the original `through` on the continuation page | +| `unknown_branch` | `line`, `read`, `end`, `set_default` | A reservation: retry after the line publishes (`directory` shows it). An id this Session never had: not retryable, read `directory` | +| `cancelled` | `create` | Retryable. Before admission nothing happened; after admission the line is being built and publishes without a waiter, so read `line` before opening again | +| `closed` | all | Not retryable in this generation: the Session is closing or unloading; a follow-up decision waits for the Session's replacement | + +### Flows + +| Operation | Normal path | Caller cancels | Caller unloads | Owner closes or reloads | Settled by | +| --- | --- | --- | --- | --- | --- | +| `create` | Validate the parent and cut; for a tool source also the opener and the cap under the same lock that reserves the line; reserve the line, build the scope, write the opening blocks and the first input, publish; a caller that stopped waiting leaves the build running and the slot spent (a user or plugin open spends nothing) | Before admission: nothing reserved, `cancelled`. After admission: the build continues, the line publishes and charges nothing again; a definitively failed creation writes `branch/create-failed` and releases the slot | The admitted build continues; the line is the Session's, not the caller's | A build in flight finishes or is rolled back before the generation closes; new calls answer `closed` | TimelineTree: the scope, the reservation, the slot and a failed creation's fact | +| `end` | Check the target, end descendants deepest first, commit `branch/end` (a tool end carries its final message), deliver that message to the parent, close the scope, write `branch/ended` on the parent; a delivery that fails is completed by restore, and a repeated `end` answers `branch_ended` | None; the call answers when the end settles | The end continues; the caller's absence changes nothing | An end in flight finishes before the generation closes; the close waits for it and for the store's answer | TimelineTree: the delivery, the scope's close and the end facts | +| `set_default` | Validate the target and its chain, write `branch/default` on the root, queue one transition per participant, wake the writers | None | Nothing to release | Refused with `closed` once closing starts | TimelineTree records the transitions; each participant's BranchLine writes its own note | +| `directory` | Read the default and every record under one lock, resolve each head | None | Nothing to release | Pending reads answer at the state they observed | TimelineTree | +| `line` | Read one record under the tree lock | None | Nothing to release | An ended line answers until its record leaves; an id the Session never had answers `unknown_branch` | TimelineTree | +| `read` | Resolve the line and the cutoff, check the batch boundary, read the facts, answer with the cutoff | None | Nothing to release | An ended line's read answers from the store; a live line's read answers `closed` once its scope is gone | TimelineTree | + +## Exceptions with reasons + +- A child's opening blocks are written before the child's scope is published: until publication the line has no other owner, so no other owner's timeline is written. +- `end` delivers a tool end's final message into the parent's timeline: the message is part of the end's settlement, `branch/end` carries it, and the accepted design keeps the delivery with the end so restore can finish exactly once ([timeline branches §10](../../../design/timeline-branches.md#10-ending-a-line)). Delivery happens before the scope close and before `branch/ended`, so a parent that holds `branch/ended` is never owed a message; a delivery that fails is completed by restore, not by a repeated `end`. +- `read` resolves a live line through the directory and returns its facts unchanged: facts are shared state under design rules §4, not another owner's folded state. +- An ended line's facts are answered here because the line's own owners are gone with its scope; the tree keeps the fixed head and the directory record. +- `set_default` queues one transition per participant: the note's key and text are BranchLine's, and only the transition is recorded here, in commit order, because a restart must not lose it. +- The owner's branch parts hold an owner-internal weak reference to this owner (`TreeHandle`, holding `Weak`), passed by the tree when it constructs the part; it is not a catalog name and has no wire name: the tree holds each line's scope and the scope holds the part, so a strong handle would be a cycle and close could not settle the scope. The handle is built when the tree is created, answers `closed` once the tree is gone, and is not a public face. + +## Verification + +Flow tests on the owner: + +- `create` charges opener, cap and reservations under the same lock: a second create and a `set_default` interleaved with it cannot both pass a check; a caller that cancels after admission leaves a line that publishes, and a definitively failed creation releases its slot and writes `branch/create-failed`. +- `end` ends descendants before their parent, records one `branch/ended` each, writes `branch/ended` only after the final message is delivered, and refuses the root and the conversation line's chain with their own kinds. +- A tool end whose final message cannot be delivered at the time still ends the line; restore delivers the message exactly once, and a repeated `end` answers `branch_ended`. +- `directory` answers `default` and the lines from one read under a concurrent move or end; `line` answers an open, an ending and an ended line, and `unknown_branch` for an id the Session never had. +- `read` answers an ended line at its fixed head with the same field selection as the live line, refuses a cutoff inside an atomic batch, and keeps the original cutoff across a continuation page. +- Close cancels reservations, joins builds, closes every live scope and answers after the store's last batch; a late `TreeHandle` use answers `closed`. + +## Supersedes + +- [Runtime owner operations](../../../design/contracts/runtime-owner-operations.md): the `timelineTree` row of the retained table; the InputQueue row of the new-API table; and the whole "Calls from a Session to a selected branch" section. Each now points here. Five rows of the new-API table are deleted here because this contract replaces them: Branch directory readers (`timelineTree.directory`), Goal → `timelineTree.inputs`, Branch-detail RPC (`display`), History RPC and line-read tools (`batchEnd`/`pageEnd`/`page`), and Goal and Shell admission (`directory({id})`). Their replacements are this contract's `directory`, `read` and `line`, and `line_owner` for writes. +- [Service faces §3.3](../../../design/service-faces.md) row for `treeCommands` and `timelineTreeControl`, which now points here. +- [Plugin contract](../../../design/plugin-contract.md) rows for `timelineTree` and for the Session-to-branch direction, which now point here or state `line_owner`. +- [Timeline branches](../../../design/timeline-branches.md): the migration note at the top, §4's source paragraph, §6's message paragraph and §10's general operation, each now a pointer to this contract. + +## Client-visible changes + +None to names, fields or error codes: `session.branches`, `session.branch_create`, `session.branch_end`, `session.branch_set_default`, `session.branch.get`, `session.history` and `session.model.get` keep their method names, request and reply fields, and the `branch_*` codes. The App Server maps the kinds above onto the codes it answers today. + +An end of the root keeps today's input error: the App Server answers the same client error it answers now, not a `branch_*` code (`invalid_target` is the owner's kind for it). + +`session.branch_create` is the user's own entry: it keeps accepting any valid parent, is never refused as a non-opener and is never refused by the cap, because a user line neither counts nor is counted ([timeline branches §6.1](../../../design/timeline-branches.md#61-resources-and-limits)). Only a tool open is checked against the opener rule and the cap. The admission the contract states by source is what the App Server does today. + +A foreign-facing page that still names the pre-contract binding, `docs/typescript-plugin-authoring.md`, moves to `timelineTree` and `line_owner` in the same change as the implementation. + +A reservation is not visible to a client today either: `session.branches` and `session.branch.get` answer only lines that published, and this contract keeps that. A client observes a line after `session.branch_create` answers, which is after publication. + +## Rule check + +| Rule | Application | +| --- | --- | +| §1 parts and Capabilities | TimelineTree is one Session part; TreeTimeline and BranchLine are its two branch parts; BranchTool is a separate Session part (its own document). TimelineTree writes Timeline facts and folds no state from them: not a Capability. TreeTimeline and BranchLine are Capabilities: they consume a line's committed facts, and the tree writes the facts that follow. | +| §2 scopes | Session scope for the directory, the lifecycle and the weak handle; branch scope for TreeTimeline and BranchLine. The Session owns the child scope's lifecycle under ADR 002 D1. | +| §3 orthogonality | No other owner's state is read or changed. The final message is delivered by the end, as the accepted design assigns it; the default line's notes are written by each participant's BranchLine. | +| §4 rule 1 | No command event from a client: `create`, `end` and `set_default` write facts only after their admission commits. | +| §4 rule 2 | The end and the move hand off through facts (`branch/end`, `branch/ended`, `branch/default`); each participant's BranchLine drains its transition and writes its note. | +| §4 rule 3 | No handler waits for I/O: creation and settlement run in the owner's tasks, and close joins them. | +| §4 rule 4 | The directory and the facts are the Session's own state; no other owner's record is copied into them. | +| §4 rule 5 | Batch boundaries are enforced by `read` and by `create`'s cut. | +| §4 rule 6 | No event reaches the model from here; the opening blocks are inputs the tree writes, and the model reads them as inputs. | +| §4 rule 7 | Callers use these six operations; no caller reads a node, a queue or a scope. | +| §4 rule 8 | One requirement is raised below: resolving a line id to a branch-scope service. | +| §4 rule 9 | Facts are published after their atomic batch commits; the end and its message are one fact. | +| §7 | Every argument and reply is data and a line is an id; no object or handle crosses, except the owner's internal weak handle. Deleting the old surface and migrating every caller is one change. The owner answers its own state and facts, never another owner's record. | +| ADR 002 D1 | Session scope: the directory outlives every line and every branch scope is created and settled here. | +| ADR 002 D2 | No wiring plugin: the service is on `TimelineTree`; the weak handle is an internal reference, not a public face. | +| ADR 002 D3 | Dependencies point from extensions to the core; TimelineTree depends on the Session scope, the store and the guide entries only. | +| ADR 002 D4 | No setting selects a behaviour here; the cap BranchTool configures is charged by this owner. | +| ADR 002 D5 | The contract is language-neutral: ids, records and facts; the Rust binding is the appendix. | +| ADR 027 | Applies: D1–D3. The mechanism is [#2127](https://github.com/arcships/dim/issues/2127). | + +## Requirements raised to mechanism owners + +1. **Resolve a line id to a branch-scope service.** `line_owner::(line)` is the runtime's id routing ([ADR 027](../../../adr/027-cross-scope-access-by-id.md) D1–D3), owned and tracked in [#2127](https://github.com/arcships/dim/issues/2127): resolve the line to the live instance, run the target owner's own operation there, and answer `SessionClosing` when the Session is closing, `NoLine` when the line is not live, or `NoSession` when no live Session instance exists (the last only to a process caller). `NoLine` is final for that line; a caller takes no hold and does not retry it. The mechanism keeps the index and hands no instance key to the caller; TimelineTree stays out of the path and adds no forwarding operation. Session-side use is stated in [SessionScope](https://github.com/arcships/dim/pull/2093) ([#2025](https://github.com/arcships/dim/issues/2025)). + +2. **Batch submission stays atomic, on the line's input owner.** Goal writes a record and its trigger as one atomic batch and reads the trigger's sequence from the batch's second event ([Goal](../../../design/plugins/Goal.md)). `line_owner::(line)?.submitMany({inputs}) → {sequences}` must submit that batch as one commit on the line and answer the committed sequences in order, so a restore never sees a record without its trigger. This is a delivery gate: the implementation task does not land until the input owner's contract carries the operation, and the InputQueue and Goal drafts align on it rather than on two independent writes. The requirement is raised to the input owner's contract ([#2027](https://github.com/arcships/dim/issues/2027)); this contract's `create` is the only write the tree performs itself, and its first input is written before the line publishes. + +3. **The Session access surface stops carrying line operations.** `Session::end_branch`, `set_default_branch`, `branch`, `branches`, `directory`, `default_and_directory`, `ended_head`, `sequence`, `batch_end` and `query` forward here today; after this contract the tree is the only face and the Session surface must not restate it. [SessionScope](https://github.com/arcships/dim/pull/2093) owns that surface. + +## Binding appendix + +The service is marked on `TimelineTree`; the wire name is `timelineTree`. `TreeCommands`, `TimelineTreeControl` and the `Branch` facade no longer cross this owner's boundary. `CancelledFn` is the crate's existing cancellation argument and is not a request field. Requests carry serde data only. + +```rust +use crate::host::CancelledFn; +use dim_agent_types::BranchSource; +use rutis::service; + +#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)] +#[serde(rename_all = "camelCase")] +pub struct LineRecord { + pub line: String, + #[serde(skip_serializing_if = "Option::is_none")] + pub parent: Option, + #[serde(skip_serializing_if = "Option::is_none")] + pub cut: Option, + #[serde(skip_serializing_if = "Option::is_none")] + pub created_at: Option, + #[serde(skip_serializing_if = "Option::is_none")] + pub source: Option, + pub state: LineState, + pub head: u64, + #[serde(skip_serializing_if = "Option::is_none")] + pub end_event: Option, +} + +/// The record's state. Replaces the crate's `BranchDirectoryState`, which names the same three states. +#[derive(Debug, Clone, Copy, PartialEq, Eq, serde::Serialize, serde::Deserialize)] +#[serde(rename_all = "camelCase")] +pub enum LineState { + Open, + Ending, + Ended, +} + +/// The idle-notice policy a new line's opener chooses; the wire value is `steer` or `none`. +#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, serde::Serialize, serde::Deserialize)] +#[serde(rename_all = "camelCase")] +pub enum IdleNotice { + #[default] + Steer, + None, +} + +#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)] +#[serde(rename_all = "camelCase")] +pub struct CreateLine { + pub parent: String, + pub cut: u64, + pub prompt: String, + pub source: BranchSource, + #[serde(skip_serializing_if = "Option::is_none")] + pub idle_notice: Option, +} + +#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)] +#[serde(rename_all = "camelCase")] +pub struct EndLine { + pub line: String, + pub source: BranchSource, + #[serde(skip_serializing_if = "Option::is_none")] + pub final_message: Option, +} + +#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)] +#[serde(rename_all = "camelCase")] +pub struct Directory { + pub default: String, + pub lines: Vec, +} + +#[derive(Debug, Clone, Copy, PartialEq, Eq, serde::Serialize, serde::Deserialize)] +#[serde(rename_all = "camelCase")] +pub enum LineScope { + Line, + Chain, +} + +#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)] +#[serde(rename_all = "camelCase")] +pub struct ReadLines { + pub line: String, + #[serde(skip_serializing_if = "Option::is_none")] + pub scope: Option, + #[serde(skip_serializing_if = "Option::is_none")] + pub from: Option, + #[serde(skip_serializing_if = "Option::is_none")] + pub through: Option, + #[serde(skip_serializing_if = "Option::is_none")] + pub fields: Option>, + #[serde(skip_serializing_if = "Option::is_none")] + pub limit: Option, +} + +/// One or the other: an event page, or field rows. +#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)] +#[serde(untagged)] +pub enum ReadReply { + Events { through: u64, events: Vec }, + Rows { through: u64, rows: Vec }, +} + +/// Every kind the owner answers, tagged by the wire code. +#[derive(Debug, Clone, serde::Serialize, serde::Deserialize, thiserror::Error)] +#[serde(tag = "code", rename_all = "snake_case")] +pub enum LineError { + #[error("no such line: {line}")] + InvalidParent { line: String }, + #[error("line {line} ended")] + BranchEnded { line: String }, + #[error("cut {cut} is not usable on line {line}")] + InvalidCut { line: String, cut: u64 }, + #[error("line {line} may not open a line")] + BranchNotOpener { line: String }, + #[error("the Session holds its limit of open lines")] + BranchLimitReached, + #[error("line {line} cannot end")] + BranchCannotEnd { line: String }, + #[error("line {line} cannot end: the root never ends")] + InvalidTarget { line: String }, + #[error("line {line} or its chain is ending")] + BranchTargetProtected { line: String }, + #[error("line {line} is the conversation line")] + BranchAlreadyDefault { line: String }, + #[error("line {line} cannot be the conversation line")] + BranchNotSelectable { line: String }, + #[error("cutoff {cutoff} is past line {line}'s head {head}")] + BeyondHead { line: String, head: u64, cutoff: u64 }, + #[error("cutoff {cutoff} is inside an atomic batch")] + NotBatchBoundary { cutoff: u64 }, + #[error("a continuation needs the original cutoff")] + ContinuationWithoutCutoff, + #[error("unknown line: {line}")] + UnknownBranch { line: String }, + #[error("the call was cancelled before admission")] + Cancelled, + #[error("the Session is closing")] + Closed, +} + +impl dim_agent_runtime::PublicService for TimelineTree {} + +#[service(name = "timelineTree")] +impl TimelineTree { + pub async fn create(&self, request: CreateLine, cancelled: CancelledFn) -> Result { + // ... + } + + pub async fn end(&self, request: EndLine) -> Result<(), LineError> { + // ... + } + + pub async fn set_default(&self, line: String, source: BranchSource) -> Result { + // ... + } + + pub fn directory(&self) -> Result { + // ... + } + + pub fn line(&self, line: String) -> Result { + // ... + } + + pub async fn read(&self, request: ReadLines) -> Result { + // ... + } +} +``` + +`LineError`'s serde tag is the wire `code`; the variant names match the errors table one for one (`BranchTargetProtected` answers `branch_target_protected`, and so on). Records, requests and replies are camelCase on the wire; `cut`, `through` and `head` are unsigned integers; a line id is a string. `TreeHandle` is the owner's internal weak reference to `TimelineTree`; it is not a service and has no wire name. + +## Current implementation + +The code here still uses the pre-contract names (`TreeCommands`, `treeCommands`); the contract above is the target. The single-line display read also belongs to TimelineTree. The directory itself is read without history I/O; display details are requested separately. It reads the @@ -14,7 +444,7 @@ newest `branch/default` or `session/forked` through the kind index to find the d The App Server only maps these owner-produced properties into its wire fields. `TreeCommands.page_end` resolves a raw-event page endpoint using atomic-batch metadata through the live Timeline or the ended line’s store. It decodes no event body and has no wire binding. The default branch's answer and its write are `TreeCommands` methods too: `default_branch()` answers the line the Session's conversation is on, restored from the root's newest `branch/default` or `session/forked`, and `set_default_branch(id, source)` admits an open conversation line whose chain is not ending, then writes `branch/default` on the root. Its refusals are `branch_already_default`, `branch_not_selectable` and `branch_target_protected`, and it writes nothing for any of them. A move queues its transition on every participant that is not the root, so a line owes its note from the moment it can take part, and signals every line; each line's own BranchLine drains its queue and writes the one status note its role earns; a load whose latest `branch:line` block disagrees with the tree writes the missing note once, and on the tree's current default branch a block whose text differs from the note this code writes is replaced once. -## TimelineTree +### TimelineTree Owner: [timeline_tree.rs](../../../../crates/dim-agent-capabilities/src/timeline_tree.rs). Owns Session branches, reservations and asynchronous creation/restore/close, @@ -28,7 +458,7 @@ Provides the TreeCommands/TimelineTreeControl ports. The `branch` tool is block and the branch markers — with their classes are listed on [timeline branches §12.4](../../../design/timeline-branches.md#124-texts-and-their-classes). -### Dependencies +#### Dependencies | Service | Purpose | | --- | --- | @@ -37,7 +467,7 @@ block and the branch markers — with their classes are listed on | `S:dyn TimelineStore` | Native binding of the Session [`timelineStore` data face](../../../design/resource-faces.md#5-store-and-timelinestore); persist/load branch directories and Timeline facts through the same backend operations. | | `S:GuideEntries` | Register the `` and `` entries for the Session, until this part unloads. | -### Events and lifetime +#### Events and lifetime Produces `branch/create`, `branch/create-failed`, `branch/start`, `branch/resume`, `branch/end`, `branch/ended` and `branch/default`, and initial child input, through tree-owned @@ -73,7 +503,7 @@ the tree, cancels reservations, joins builds and closes branch contexts. Restore ancestry cuts cannot split required result relationships. Client detach is not Session close, and closing is not deletion of persisted history. -### Tests +#### Tests [branch_flow.rs](../../../../crates/dim-agent-capabilities/tests/branch_flow.rs): `delayed_create_uses_its_anchor_and_survives_an_abandoned_waiter`, @@ -107,44 +537,3 @@ Session close, and closing is not deletion of persisted history. | 提供 | `S:TimelineTree`、`S:TreeCommands`、`S:dyn HostDispatch#treeCommands`、`S:dyn TimelineTreeControl` | | 被注入于 | `BranchLine`、`BranchTool`、`InputMethods`、`InputQueue`、`LoopMethods`、`PromptSuggestion`、`Questions`、`Recall`、`ShellInput`、`ToolMethods`、`TreeTimeline`、`Wait`、`WorkspaceTools` | - -## TreeTimeline - -Owner: [timeline_tree.rs](../../../../crates/dim-agent-capabilities/src/timeline_tree.rs). -Routes branch-local creation facts to the Session tree using the actual parent -identity, and releases pending child reservations when the parent unloads. - -### Dependencies - -| Service | Purpose | -| --- | --- | -| `S:TreeCommands` | Reach the owning Session tree through its command port. | -| `B:TimelineIdentity` | Identify the parent branch. | -| `B:Dispatcher` | Consume creation events. | -| `B:Timeline` | Parent history, creation and end settlement location. | - -### Events and lifetime - -Consumes `branch/create` and `branch/end` (with the next turn end of a line -that ended through a tool call), and reports every `turn/end` to the tree, -which publishes it for the line's children; tree-owned work produces the -opening, failure and end facts (see TimelineTree). The handler registers creation, not a long-running build future. -Cleanup cancels pending reservations for this parent and settles their waiters. -No independent worker or persistent tree is owned here. Reload does not by -itself replay arbitrary old create events; recovery belongs to TimelineTree. -An accepted creation need not survive parent or Session close. - -### Tests - -[branch_flow.rs](../../../../crates/dim-agent-capabilities/tests/branch_flow.rs): -`parent_close_waits_for_dispatch_before_releasing_branch_reservations`, -`close_releases_an_unconsumed_create_without_waiting_for_dispatch`. - - -| 项 | 值 | -| --- | --- | -| 作用域 | 分支 | -| 注入 | `B:Dispatcher`、`B:Timeline`、`B:TimelineIdentity`、`S:TreeCommands` | -| 提供 | — | -| 被注入于 | — | - diff --git a/docs/architecture/rust-agent/plugins/TreeTimeline.md b/docs/architecture/rust-agent/plugins/TreeTimeline.md new file mode 100644 index 0000000000..6cae778016 --- /dev/null +++ b/docs/architecture/rust-agent/plugins/TreeTimeline.md @@ -0,0 +1,152 @@ +# TreeTimeline + +Owner: [timeline_tree.rs](../../../../crates/dim-agent-capabilities/src/timeline_tree.rs). +Scope: branch. Issue: [#2024](https://github.com/arcships/dim/issues/2024). + +This page is the owner contract for the branch-scope route from a line's facts to the line +directory. [Current implementation](#current-implementation) describes the code as it is today. + +TreeTimeline is the branch-scope half of the line directory: it watches the facts of the line it runs in and hands the ones the tree must act on to TimelineTree. It holds no state of its own and answers no caller. + +## Use and scope: responsibility split + +TreeTimeline owns: + +- **The route from a line's own committed facts to the tree.** TimelineTree reserves a child inside `create`'s lock, before it appends `branch/create`; this part hands the committed `branch/create` to the tree, which starts that child's build and records the create position. A `branch/end` commits this line's end; a `turn/end` is the point after which a tool end settles. +- **The release of the reservations this line's children hold.** When this line unloads, a child reservation the tree made and has not dispatched is cancelled and its waiter settled, so a parent that goes away leaves no half-open line. + +Callers keep: every decision about the parent's own facts; TreeTimeline decides nothing, it routes and releases. + +| Requirement (callers) | Compose from the operations below without breaking the owner's invariants? | Handling | +| --- | --- | --- | +| The tree learns a child was created on this line, with the cut it inherits | No: the fact is dispatched in this line's scope, and the tree cannot subscribe to every line's facts from the Session scope | Internal handover | +| The tree learns this line committed its end, and settles it at the turn end a tool end belongs to | No: same reason; the fact and its settlement order are the tree's | Internal handover | +| The tree learns this line ended a turn, so its children see it moved | No: the sequence is published by the tree for this line's children | Internal handover | +| Reservations this line opened and never received are cancelled when the line unloads | No: the reservation table is the tree's and the unload is this scope's event | Internal handover | + +No operation is public: the handover is inside one owner, across two scopes, and adding a public face would give callers a second path to the tree. + +## Caller example + +None: no caller holds TreeTimeline. The tree's own directory is the only reader of what this part reports, and it reads it through the owner's internal handover. + +## Own contract + +### Contract dependencies + +| Service | Purpose | +| --- | --- | +| `B:Dispatcher` | The line's committed facts, in order. | +| `B:Timeline` / `B:TimelineIdentity` | Creation and end settlement location and this line's id. | +| `S:TreeHandle` | The owner's weak handle to TimelineTree: the internal handover for creation, end and turn end. Weak because the tree holds this line's scope and the scope holds this part. | + +### Operations + +None public. The handover is three tree-internal calls — a child was created, this line ended, this line ended a turn — plus one release on unload. They are not on the data face and no other owner may call them. + +### Errors + +None reach a caller. A routing failure is recorded on the tree's cleanup list and surfaces in the Session's diagnostics; a child that fails to build answers its own creator through the tree's `create` reply. + +### Flows + +| Case | Normal path | Line unloads | Owner closes or reloads | Settled by | +| --- | --- | --- | --- | --- | +| A child was created on this line | TimelineTree already reserved the child inside `create`'s lock and appended `branch/create`; the subscription hands that committed fact to the tree, which starts the build and records the create position | A reservation the tree made and never dispatched is cancelled; its waiter is settled | The tree's close cancels every reservation before the scopes close | TreeTimeline releases reservations; TimelineTree settles the children | +| This line committed its end | A tool end waits for the turn end; any other end settles at once | The end is already the tree's; the scope closes after its last write | An end in flight finishes before the generation's close | TimelineTree | +| This line ended a turn | The tree publishes the sequence for this line's children | Nothing held | Nothing held | TimelineTree | + +## Supersedes + +- The `TreeTimeline` dependency on `S:TreeCommands` in [timeline branches §5](../../../design/timeline-branches.md#5-parts): the service is the owner's weak `S:TreeHandle`. + +## Client-visible changes + +None: the part has no public face. + +## Exceptions with reasons + +- The routing crosses two scopes inside one owner: the subscription must live in the branch scope, while the reservation table and the directory are the Session's. `Weak` access to the tree keeps the branch scope from owning the tree, which the tree already holds through this line's scope. +- A reservation this line opened and never dispatched is cancelled on unload and its waiters settle; a build already in flight is awaited and publishes, and the line is then the tree's. + +## Verification + +Flow tests on the owner: + +- `create` reserves the child under its own lock; the committed `branch/create` starts the build through this part; a parent that unloads before the reservation is dispatched cancels it and settles the waiter. +- A tool end waits for the line's turn end and settles after it; a client end settles without waiting. +- A turn end publishes the sequence this line's children read; an ended line publishes nothing further. + +## Rule check + +| Rule | Application | +| --- | --- | +| §1 parts and Capabilities | TreeTimeline is one branch part and a Capability: it consumes the line's committed facts and drives the tree's writes; it holds no state of its own and writes no fact. | +| §2 scopes | Branch scope for the subscription and the unload; the reservation table and the cap lock are TimelineTree's, in `create`. | +| §3 orthogonality | It routes facts and touches no other owner's state. | +| §4 rule 1 | No command; it reacts to committed facts. | +| §4 rule 2 | The handover is a fact route; the tree writes every resulting fact. | +| §4 rule 3 | The handler registers the tree's work and returns; no I/O waits in the handler. | +| §4 rule 4 | No state is kept here. | +| §4 rule 5 | No batch. | +| §4 rule 6 | No context input is produced. | +| §4 rule 7 | It uses the owner's internal handover, not a public service. | +| §4 rule 8 | No infrastructure change. | +| §4 rule 9 | It acts after the fact's batch commits, as the dispatcher delivers it. | +| §7 | Every argument and reply is data and a line is an id; no object or handle crosses, except the owner's internal weak handle. Deleting the old surface and migrating every caller is one change. The owner answers its own state and facts, never another owner's record. | +| ADR 002 D1 | Branch scope: the subscription lives with the line. | +| ADR 002 D2 | No wiring plugin: the part belongs to the TimelineTree plugin. | +| ADR 002 D3 | Depends only on branch services and the tree. | +| ADR 002 D4 | No configuration. | +| ADR 002 D5 | No public contract, so no language binding; the handover is Rust-internal. | + +## Requirements raised to mechanism owners + +None. + +## Binding appendix + +None: no service and no wire name. The part provides no name in the catalog. + +## Current implementation + +The code here still uses the pre-contract names (`TreeCommands`, `treeCommands`); the contract above is the target. + +Owner: [timeline_tree.rs](../../../../crates/dim-agent-capabilities/src/timeline_tree.rs). +Routes branch-local creation facts to the Session tree using the actual parent +identity, and releases pending child reservations when the parent unloads. + +#### Dependencies + +| Service | Purpose | +| --- | --- | +| `S:TreeCommands` | Reach the owning Session tree through its command port. | +| `B:TimelineIdentity` | Identify the parent branch. | +| `B:Dispatcher` | Consume creation events. | +| `B:Timeline` | Parent history, creation and end settlement location. | + +#### Events and lifetime + +Consumes `branch/create` and `branch/end` (with the next turn end of a line +that ended through a tool call), and reports every `turn/end` to the tree, +which publishes it for the line's children; tree-owned work produces the +opening, failure and end facts (see TimelineTree). The handler registers creation, not a long-running build future. +Cleanup cancels pending reservations for this parent and settles their waiters. +No independent worker or persistent tree is owned here. Reload does not by +itself replay arbitrary old create events; recovery belongs to TimelineTree. +An accepted creation need not survive parent or Session close. + +#### Tests + +[branch_flow.rs](../../../../crates/dim-agent-capabilities/tests/branch_flow.rs): +`parent_close_waits_for_dispatch_before_releasing_branch_reservations`, +`close_releases_an_unconsumed_create_without_waiting_for_dispatch`. + + +| 项 | 值 | +| --- | --- | +| 作用域 | 分支 | +| 注入 | `B:Dispatcher`、`B:Timeline`、`B:TimelineIdentity`、`S:TreeCommands` | +| 提供 | — | +| 被注入于 | — | + diff --git a/docs/design/branch-typescript.md b/docs/design/branch-typescript.md index 8f4b714a78..3dfe75998a 100644 --- a/docs/design/branch-typescript.md +++ b/docs/design/branch-typescript.md @@ -1,6 +1,6 @@ # Branch TypeScript binding -The [target Session tree binding](contracts/runtime-owner-operations.md) moves calls from `treeCommands` to `timelineTree` with the same arguments and replies. The catalog entry and consumer injections change together. References to `treeCommands` below describe the pre-migration binding. +The Session tree's binding is superseded by the [TimelineTree contract](../architecture/rust-agent/plugins/TimelineTree.md); references below to `treeCommands` describe the pre-redesign binding. A Session part cannot inject a single branch's service, but can read that branch-group data face by line id with `line_owner` ([ADR 027](../adr/027-cross-scope-access-by-id.md)). Status: implemented for [C5 / #64](https://github.com/arcships/dim/issues/64), the branch portion of [#4](https://github.com/arcships/dim/issues/4), on rutis 0.16.0 `build::Exports` @@ -32,9 +32,9 @@ ordered consumption. | --- | --- | | Branch instance and typed keys | The `branch` group instance, nested in its Session's; the catalog keys each name for it (`Names`) | | Ordered consumption, handler failures, committed reads | Branch `Dispatcher` (over its `Timeline`) | -| Input validation and commitment | `Branch::input`, reached by branch id through Session `TreeCommands` | +| Input validation and commitment | 见 [TimelineTree 契约](../architecture/rust-agent/plugins/TimelineTree.md#session-parts-reaching-a-lines-owners) | | Event writes, including extension events | Branch `Timeline` | -| Branch directory and creation | Session `TreeCommands` / `TimelineTree` | +| Line directory, creation and end | 见 [TimelineTree 契约](../architecture/rust-agent/plugins/TimelineTree.md#own-contract) | | Activation and closing | `BranchLifecycle` | | Branch identity | `TimelineIdentity` | @@ -48,7 +48,7 @@ every instance of that group; a row gets the nearest enclosing instance. Its met | Name | Group | Rust type | Methods used by parts | | --- | --- | --- | --- | -| `treeCommands` | `session` | `TreeCommands` | `list()`, `info(id)`, `input(id, input)`, `create(parent, at, options, cancelled)`, `end(id, source)`, `page(id, after, limit)` | +| `timelineTree` | `session` | `TimelineTree` | 见 [TimelineTree 契约](../architecture/rust-agent/plugins/TimelineTree.md#binding-appendix) | | `dispatcher` | `branch` | `Dispatcher` | `consume(name, keys, rebuild, handler)`, `listen(name, keys, handler)`, `committed()`, `notify()`, `sequence()`, `changed()` | | `branchLifecycle` | `branch` | `BranchLifecycle` | `activated()`, `closing()`. `registerOpening` registers work that branch opening waits for. | | `timeline` | `branch` | `Timeline` | `append({type, name, data, tags?})` → the committed event; `query(query)` (the one bounded read, `include_publishing` for the branch's not-yet-published facts), `ancestors()`, `sequence()`, `committed()`, `hasPending()` | @@ -57,11 +57,8 @@ every instance of that group; a row gets the nearest enclosing instance. Its met The data methods were added for this purpose; the existing ones that return handles or take Rust closures stay as they are for Rust callers: -- `TreeCommands::info`, `input`, `create`, `end` and `page` address branches by id and return - data: `TimelineInfo` (with `source`, and answered for an ended line as well), the committed - `AgentEvent`, the new branch's id, and one page of an open or ended line's committed batches. - `create` takes the caller's cancellation explicitly (§Cancellation); `end` is - [timeline branches](timeline-branches.md#10-ending-a-line). +- The tree's operations are the [TimelineTree contract](../architecture/rust-agent/plugins/TimelineTree.md#own-contract): + a record per line, the new line's id, and one bounded read of a line's facts at a cutoff. - `Dispatcher::listen` is `subscribe` in data form. Its `&Ctx` parameter is the calling row's context, so the subscription belongs to that row and ends when it unloads or restarts. The handler receives the committed event by value; its throw or rejection is the subscriber's handler @@ -81,7 +78,7 @@ closures stay as they are for Rust callers: and a core domain decodes only through its typed contract, so a malformed core event is rejected before anything is appended. Which owner writes which event is the event's contract, followed by review as for native capabilities, not a check of the export (time bus §2, AGENTS.md rule 11): - a part asks another owner through its command, such as input through `treeCommands.input`. + a part asks another owner through its own operation, such as input through `line_owner::(line)?.submit`. C5 first left `Timeline` unexported because the generator cannot filter a type's methods and no part needed to write then (#196); the reads moved to `Dispatcher`. Extension events are the first @@ -148,14 +145,13 @@ same-module snapshots, online metadata, disablement and Pending apply unchanged. 5. Input written from a handler is committed to the Timeline tail and consumed later; its reply proves commitment, not dispatch or adoption. 6. One branch never receives another branch's Dispatcher. Cross-branch communication is input by - id through `treeCommands`, asynchronous. + line id through `line_owner::(line)`, asynchronous. ## Open -- ~~**A Session part reading a branch-owned service.**~~ Settled with Goal: a Session part reads - no branch state. It writes input by branch id and the branch owner decides; clients read the - owner's results as Timeline facts (Goal A.3, A8). A Session part cannot depend on a per-branch - service (ADR 002 D3), and none is needed. +- ~~**A Session part reading a branch-owned service.**~~ Settled: a Session part cannot inject a + single branch's service (ADR 002 D3), but it reads that branch-group data face by line id with + `line_owner` ([TimelineTree contract](../architecture/rust-agent/plugins/TimelineTree.md#session-parts-reaching-a-lines-owners); [ADR 027](../adr/027-cross-scope-access-by-id.md)). - **Generator limitations worked around.** rutis' generator resolves a generic alias's item type where the alias is defined, so the exported methods spell out `std::result::Result<_, AgentError>` instead of the runtime's `Result<_>` ([arcships/rutis#463](https://github.com/arcships/rutis/issues/463)); and, as documented, it @@ -168,7 +164,7 @@ same-module snapshots, online metadata, disablement and Pending apply unchanged. - In two Sessions sharing the runtime, each `main` part reads its own identity, follows `input/message`, `turn/start` and `turn/end` in commit order, and writes one marked input to its - branch through `treeCommands.input`. Later turn ends do not write again. + branch through `line_owner::(line)?.submit`. Later turn ends do not write again. - A child in the first Session uses its own Dispatcher, identity and local fold. It writes its own marker despite inheriting its parent's prefix, without writing another marker to the parent. - After a restart, each restored Session's part rebuilds from committed history through a nonzero diff --git a/docs/design/contracts/runtime-owner-operations.md b/docs/design/contracts/runtime-owner-operations.md index 3d36fd9d6d..04f4aba1c3 100644 --- a/docs/design/contracts/runtime-owner-operations.md +++ b/docs/design/contracts/runtime-owner-operations.md @@ -4,7 +4,7 @@ | Caller → owner | Final API | | --- | --- | -| Branch management, input and history callers → `timelineTree` | `create/end/info/input/list/page/query` retain their existing signatures on the single Session tree face. Creation returns the branch ID. | +| Line directory, lifecycle and history callers → `timelineTree` | 本节由 [TimelineTree 契约](../../architecture/rust-agent/plugins/TimelineTree.md#own-contract) 取代。 | | Language readers → PromptSources | `sessionLanguage.get`. | | Language updates → App Server | [`session.language.update`](session-access.md) accepts the existing language code or clear action. The owner serializes persistence, live-state replacement and Prompt adoption on main and loaded branches before replying. | | Prompt → PromptRegistry; guide and tool contributors → their registries | `initialPromptConfiguration.get`, `promptHost.load`, `guideEntries.register`, `toolRegistry.register`, `toolSourcesView.get/observe`. | @@ -16,15 +16,12 @@ | Caller → owner | New API | | --- | --- | -| Branch directory readers → `timelineTree` | `timelineTree.directory({}) → [{info, head, state, endEvent?}]`, including ending and ended branches. | | Skills content and MCP publication → Session loader | `sessionLoader.create({group, definitionId, instanceData}) → {instanceId}`; `remove({instanceId}) → void`. The Session loader admits groups whose configured parent is the Session group. Registered Session extension definitions must activate their instance rows. Host-added optional groups retain their optional rows. Skills supplies its content definition; MCP supplies its connection definition ID and retains the resolved transport configuration. | -| Goal → timelineTree | `inputs(id, inputs) → committed events`. One validated atomic batch for the Goal record and trigger. | -| Branch-detail RPC → timelineTree | `display(id) → {entry,purpose?,cutMessages?,end?}`. | -| History RPC and line-read tools → timelineTree | `batchEnd(id, sequence) → void`, `pageEnd(id, after, limit, through) → sequence`, and `page` at the same cutoff. Preserve complete batches and the fixed head of ended lines. | | Context RPC → target branch | `agentLoop.compact` and `contextUsage.read`. | -| Goal and Shell admission → timelineTree | `directory({id})` returns the matching directory entry or the unknown-branch error using a single-branch lookup. Goal reads ended history through `query`; writes retain the ended/unknown errors. | -| InputQueue and Collaboration approvals → target branch | `timelineTree.input`, `inputQueue.withdraw` after submission checks, and `approval.pending/decide` on the selected branch. | -| PromptSuggestion → ContextUsage; Report and Agent configuration → Prompt | `contextUsage.read`, `prompt.adoptedConfiguration({}) → adopted configuration or null`. Report also uses `timelineTree.query` at the selected head for evidence. | +| InputQueue → target line | 本节由 [TimelineTree 契约](../../architecture/rust-agent/plugins/TimelineTree.md#session-parts-reaching-a-lines-owners) 取代。 | +| Collaboration approvals → target line | `approval.pending` returns the target's pending requests; `approval.decide` settles one. Both are that owner's own operations, reached by line id. Collaboration keeps its ended answer on closed, ended or unknown detail lookup. | +| PromptSuggestion → ContextUsage | `contextUsage.read`, on the target line's own face. | +| Report and Agent configuration → Prompt | `prompt.adoptedConfiguration`; Report reads its evidence through the tree's `read`, whose contract is [TimelineTree](../../architecture/rust-agent/plugins/TimelineTree.md#own-contract). | | Prompt and ToolBinding → `branchLifecycle` | `registerOpening(completion) → void`. Opening waits for admitted completions under its existing deadline and propagates their errors. | | Fault producers and Session observers → `sessionLifecycle` | `reportFault(error) → void`, `failure({}) → SessionFault or null`, `observeFault(listener) → id`, `release(id) → boolean`. The listener receives the current failure (initially null) and subsequent reports. Caller unload releases the observation. The first fault wins until a storage failure supersedes it; the first storage failure wins. | | Check providers and input admission → SubmitChecks | `register(name, check) → void`; `check({entry, branchId, user?, mode}, cancelled) → proceed{blocks, warnings} or block{message}`. Run in name order through the first block. Interrupted checks write nothing. | @@ -32,27 +29,7 @@ ### Calls from a Session to a selected branch -Within a branch, inject its owner face directly. For Session callers the existing -`timelineTree` face gains `call({branchId,operation}, cancelled) → operation reply`. -TimelineTree resolves the admitted live branch once using its existing branch lookup and -dispatches on that branch instance. The operation is a tagged union of the calls below; -Direct variants use the owner method's arguments, reply and error. The compact RPC variant below returns the existing settled client result. The Session caller gets data. -Ended and unknown branches retain their original errors. Calls admitted before close stay -with that generation. Tree history, directory and batch input continue to use the tree's -own methods. - -| Session caller | Target operation | -| --- | --- | -| Context RPC / PromptSuggestion | `contextUsage.read`. The `compactAndWait` variant runs the existing compact RPC handler: it calls `agentLoop.compact` and waits for the compaction fact matching that command sequence and returns the existing completed/skipped/failed reply. The committed sequence watch and bounded query run inside the selected branch for that wait. | -| Session language / Agent configuration / Report | `prompt.configure` or `prompt.adoptedConfiguration` with the existing source, model and outcome records. | -| InputQueue management / Collaboration | `inputQueue.withdraw` with the existing command; the caller runs the existing submit checks for steer before writing. `approval.pending` returns the branch's existing pending requests, and `approval.decide` settles the selected request. Collaboration retains its ended response on closed/ended/unknown detail lookup. | - -For a live main branch, Report captures its published head once at draft capture (`directory({id:"main"}).head`) -and stores it as `conversationThrough` on that draft. Activity evidence and later opt-in -conversation extraction call `timelineTree.query` with the same explicit `through`, -existing bounded window and `include_publishing: false`. Zero yields an empty window. -A draft without a captured cutoff does not fetch a conversation. Plan generation never -substitutes a newer head. +本节由 [TimelineTree 契约](../../architecture/rust-agent/plugins/TimelineTree.md#session-parts-reaching-a-lines-owners) 取代。 ### Prompt, configuration and files diff --git a/docs/design/examples/capability-models/coverage-audit.md b/docs/design/examples/capability-models/coverage-audit.md index 7bba118c18..ea5259498c 100644 --- a/docs/design/examples/capability-models/coverage-audit.md +++ b/docs/design/examples/capability-models/coverage-audit.md @@ -42,7 +42,7 @@ | ShellSession / [源码](../../../../crates/dim-agent-capabilities/src/shell_session.rs) | 借 ExecLifecycle 检查 start/end/wake 边界及 crash 缺口 | 前台命令转后台只有一个 task 身份;stop/自然完成/shell 退出竞争哪个终态;旧 generation 完成信号不结算新命令;命令排队取消是否发生 started、是否欠终态 | PTY marker 解析可留插件内部,不因此排除其输出所决定的 Timeline 身份与终态;crash 缺口仍单独跟踪 #1633 | | [FileReads](../../../architecture/rust-agent/plugins/WorkspaceTools.md#filereads) | 单文件绑定被压缩切出、reload 清绑定 | 分文件/分支绑定隔离;read/write/edit 都可建立绑定;edit 与 write 对压缩的要求不同;同一 published cut 的查询判断。原模型只有 WriteCheck,不能解释 edit 合法而 write 被拒绝的场景 | 编码/hash/外部文件竞争归文件操作契约;不强行增加持久状态 | | [TreeTimeline / TimelineTree](../../../architecture/rust-agent/plugins/TimelineTree.md) | reservation、父关闭、两层子树结束 | 固定 ancestry cut 不随等待者消失改变;candidate 在 opening receipt 和初始 input 接纳前不可见;tool end 等 turn/end;中断 create/close 的已接纳义务如何结算;不同 parent/source 身份不混淆 | 目录恢复及资源归 Session tree,不让 branch 重做;TreeLifecycle 的 Build(ok) 把 opening 的核心条件压成了外部布尔值 | -| [BranchLine](../../../architecture/rust-agent/plugins/BranchTool.md#branchline) | 两个 cursor、held block、成功 steer、恢复不发 idle | main/tool/host 角色;opening cut 与最后已通知 head;idle notice 排除 own-end 和 pending driving input;外部结束合并 roster 与 ended notice;显式重新读取可回退 cursor。现有 Read 只能推进到 held block,未覆盖真实读页 | 不复制父正文、不接管树。资格判断属于 BranchLine,不能全部排除在模型输入前提中 | +| [BranchLine](../../../architecture/rust-agent/plugins/BranchLine.md) | 两个 cursor、held block、成功 steer、恢复不发 idle | main/tool/host 角色;opening cut 与最后已通知 head;idle notice 排除 own-end 和 pending driving input;外部结束合并 roster 与 ended notice;显式重新读取可回退 cursor。现有 Read 只能推进到 held block,未覆盖真实读页 | 不复制父正文、不接管树。资格判断属于 BranchLine,不能全部排除在模型输入前提中 | | [CollaborationTimeline](../../../../crates/dim-app-server/src/collaboration.rs) | input/delivered 分开、未交付恢复、成员缺失结算 | operation/request/member 是不同身份:同一 member 的多次请求、message/cancel/close 不等价;当前请求被取消而已结束请求保持;多个审批转发分别清理;交付失败的结果与对方已采用输入分开 | Team 目录/Agent 删除由对应 owner 管;[owner-independent 提案](../../collaboration-timeline.md)不当现行实现。现有 Ids 同时代表成员和请求,无法检查多请求共用成员 | | [GoalBranch](../../plugins/Goal.md) / [状态合同](../../plugins/Goal-state-read.md) | 显式启动、active 重载内存暂停 | edit 保留状态;pending input/后台工作抑制续行;正常输入重置本轮计数;旧 evaluator 报告不能结束新执行;model/evaluator judge 分别处理 completed;子分支/fork 不继承目标。GoalLifecycle 的 Signal 不具备这些判定状态 | Goal.md 是 Draft,逐项与 branch/fold 实现及既有 flow 对照,不将提案自动认作实现保证;不证明 evaluator 的判断质量 | | [HooksBranch](../../../architecture/rust-agent/plugins/Hooks.md#hooksbranch) | consumed/interrupt 使输出失效、普通点与审批并行 | 按 event kind/outcome 选择 hook point;handler catalog 顺序合并及 onFailure;每条 follow-up chain 的上限和新正常回合 reset;SessionStart 输出提交前重新检查 turn/start;不同 approval_id 的独立取消 | shell 命令实现/输出文本解析可外置;会产生何种输入、是否启动后续 turn 属于 Hooks 的业务语义 | diff --git a/docs/design/examples/owner-handoff-verification.md b/docs/design/examples/owner-handoff-verification.md index 845eef8a24..05443a3cac 100644 --- a/docs/design/examples/owner-handoff-verification.md +++ b/docs/design/examples/owner-handoff-verification.md @@ -47,7 +47,7 @@ | [Goal](../../../crates/dim-goal/src/branch.rs) `rebuild` | committed、publication(h)、load 固定 h;返回 h | [read](../../../crates/dim-goal/src/read.rs) 读取最后 goal/state;[query](../../../crates/dim-goal/src/branch/recovery.rs) 不含 publishing;pause_reloaded,不恢复旧任务 | | [CollaborationTimeline](../../../crates/dim-app-server/src/collaboration.rs) `restore` | 回调内 committed、固定 through、include_publishing;返回原 through | 整理旧操作;部分撤回工作另等 activated;这不等于所有协作副作用已经结束 | | [HooksBranch](../../../crates/dim-agent-capabilities/src/hooks/runner.rs) apply 回调 | 回调内 committed,设置 view.last,返回 h;不读历史 | [Hooks 合同](../../architecture/rust-agent/plugins/Hooks.md) 明确不重跑旧 hook;不是遗漏了通用恢复扫描 | -| [BranchLine](../../../crates/dim-agent-capabilities/src/timeline_tree.rs) apply 回调 | 回调内 committed,返回 h;随后 want Roster/Parent | [BranchTool 合同](../../architecture/rust-agent/plugins/BranchTool.md) 从当前目录和按需历史重建;跳过旧触发不等于恢复整个业务视图 | +| [BranchLine](../../../crates/dim-agent-capabilities/src/timeline_tree.rs) apply 回调 | 回调内 committed,返回 h;随后 want Roster/Parent | [BranchLine 合同](../../architecture/rust-agent/plugins/BranchLine.md) 从当前目录和按需历史重建;跳过旧触发不等于恢复整个业务视图 | [TS branch](../../../runtime/fixtures/branch-part.ts)、[TS extension](../../../runtime/fixtures/extension-events.ts)、 [Python branch](../../../runtime/fixtures/python/python_branch_part.py) 均在 rebuild 回调里调用 @@ -183,7 +183,7 @@ ModelOutputEnd 数量断言以确认终态身份:未创建 request 时为零 | Goal | 固定 cut 读取业务状态,pause_reloaded,不重启旧 continuation/evaluator;依赖 input/turn 和子分支目录 | [Goal 合同](../../design/plugins/Goal.md);GoalLifecycle/GoalProgress;[goal_cases_flow](../../../crates/dim-goal/tests/goal_cases_flow.rs) 的 `d5_a_restored_line_repeats_no_decision` 断言已读:恢复暂停、旧 continuation 不重启、显式 resume 才继续 | 复用已有恢复语义;evaluator 子分支清理/输入撤回组合仍是业务范围,不因 cut 核对判定全覆盖 | | CollaborationTimeline | 未投递操作写关闭错误,已投递 delegation 恢复关联,后续撤回等待 publication;依赖 Session collaboration owner 和 input/tree | [Collaboration 合同](../../design/plugins/Collaboration.md);CollaborationHandoff/Identity;restore 选择及 transport_flow 的 restart/private 与 orphan 清理断言已读:重启保留 delegation 与隔离、移除 orphan/incomplete 目录且保留合法 leader | 目录/投递/撤回并非一个 terminal;保留逐项核对,不用“delegation 可恢复”代表全部副作用已结算 | | HooksBranch | 从当前 cut 开始接收新触发,不重跑旧 hook;旧运行 handler 由自己卸载结算 | [Hooks 合同](../../architecture/rust-agent/plugins/Hooks.md);HookScheduling/HookFollowups 等;`a_live_reload_resolves_the_tool_that_started_before_hooks_mounted` 断言已读:工具阻塞时重启 Hooks,释放后仍得到正确工具名/参数 | 真实跨 owner 热重载已有流程,直接复用;不要求补全量历史回放,不把旧请求身份查询误作重执行 | -| BranchLine | 不回放旧触发;从当前目录、last roster/parent block 和目标 cursor 按需构造视图;依赖 TimelineTree/目录及 publication | [BranchTool 合同](../../architecture/rust-agent/plugins/BranchTool.md);BranchLine;branch_flow 的 `a_restore_writes_a_due_parent_block_once_and_none_without_movement`、`a_read_cursor_survives_a_restore` 断言已读:只补应有 parent block、无新进展不补、cursor 后续读严格前进 | 归按需视图恢复,不能强加“所有历史事件消费一次”;目录重建/通知组合仍按对应 flow 进一步核对 | +| BranchLine | 不回放旧触发;从当前目录、last roster/parent block 和目标 cursor 按需构造视图;依赖 TimelineTree/目录及 publication | [BranchLine 合同](../../architecture/rust-agent/plugins/BranchLine.md);branch_flow 的 `a_restore_writes_a_due_parent_block_once_and_none_without_movement`、`a_read_cursor_survives_a_restore` 断言已读:只补应有 parent block、无新进展不补、cursor 后续读严格前进 | 归按需视图恢复,不能强加“所有历史事件消费一次”;目录重建/通知组合仍按对应 flow 进一步核对 | ### 7.1 生命周期不是全局停机屏障 diff --git a/docs/design/examples/timeline-capability-analysis.md b/docs/design/examples/timeline-capability-analysis.md index 061ca3288e..167c1101d2 100644 --- a/docs/design/examples/timeline-capability-analysis.md +++ b/docs/design/examples/timeline-capability-analysis.md @@ -162,7 +162,7 @@ - **转换**:子线变化更新 keyed roster;父亲 turn/end 后基于 read cursor 发布 parent block;tool line 结束按原因/当前驾驶输入决定 idle/ended notice。失败或拒绝的 steer 不算已通知父线。 - **恢复**:从 Dispatcher committed cut 挂载;按当前子线创建位置、最后 roster/parent block 和目标 read cursor 精准查询。旧 turn 进度不恢复,恢复补写 turn/end 不触发新的 idle notice。 - **性质/论证**:parent block 只报告身份与位置而不复制父正文;通知依据 line 消费态而非一个原始父信号,消费/删除 held block 后可重算。不同目标 cursor 不混用。 -- **对应**:[timeline_tree.rs](../../../crates/dim-agent-capabilities/src/timeline_tree.rs) 的 BranchLine 与 writer/read-cursor 查询;[BranchTool](../../architecture/rust-agent/plugins/BranchTool.md#branchline);branch_flow 和 local_execution 的分支交接流程。文档 `tool/use`/`tool/result` 拼写应与实际 `step/tool-use`/`step/tool-result` 区分。 +- **对应**:[timeline_tree.rs](../../../crates/dim-agent-capabilities/src/timeline_tree.rs) 的 BranchLine 与 writer/read-cursor 查询;[BranchLine](../../architecture/rust-agent/plugins/BranchLine.md);branch_flow 和 local_execution 的分支交接流程。文档 `tool/use`/`tool/result` 拼写应与实际 `step/tool-use`/`step/tool-result` 区分。 ## 17. CollaborationTimeline diff --git a/docs/design/plugin-contract.md b/docs/design/plugin-contract.md index 1d34d18338..3f35269327 100644 --- a/docs/design/plugin-contract.md +++ b/docs/design/plugin-contract.md @@ -59,7 +59,7 @@ process (root) process parts: storage, catalogs, connections, Ag | --- | --- | --- | --- | | Process (root) | Host start | Host shutdown | — (process parts provide their own) | | Agent (`agent`) | Agents creates an Agent | Agent close, host shutdown | Host-internal | -| Session (`session`) | An Agent creates or restores a Session | Session close, idle unload | `sessionIdentity`, `sessionLifecycle`, `treeCommands` | +| Session (`session`) | An Agent creates or restores a Session | Session close, idle unload | `sessionScope`; a Session's line directory is the [TimelineTree](../architecture/rust-agent/plugins/TimelineTree.md) part | | Branch (`branch`) | TimelineTree creates a branch | The branch ends, or its Session closes | `timeline`, `dispatcher`, `branchLifecycle`, `timelineIdentity` | Visibility follows the tree, as in [principles §2](../architecture/rust-agent/principles.md): @@ -67,7 +67,7 @@ Visibility follows the tree, as in [principles §2](../architecture/rust-agent/p | Direction | How | | --- | --- | | Up (an enclosing instance, the process) | Inject the service by name | -| Down (Session to branch) | `treeCommands`: input by branch id, branch creation. Never by injecting a branch service | +| Down (Session to branch) | `line_owner::(line)`: resolve the line to the branch scope's service and call that owner's own operation ([ADR 027](../adr/027-cross-scope-access-by-id.md)); registration points and the lifecycle services stay out ([TimelineTree](../architecture/rust-agent/plugins/TimelineTree.md)) | | Sideways (sibling branches, other Sessions) | Not visible. Go through a common ancestor's business service, such as `sessions` | The scope roots, the facades and their publication rules are mechanisms. Each Session and branch is @@ -114,9 +114,9 @@ R4). This table says what each name Dim defines is for. | `workflowFiles` | process | App Server | yes | Marked `#[rutis::service]` | | `eventHub` | process | EventHub | designed, not implemented | A producer declares a source and publishes an event; EventHub delivers it to the Sessions subscribed, through Agents' `sessions` ([EventHub](plugins/EventHub.md)) | | `collaborationMembers:` | process | the member provider | designed, not implemented | [ExternalAgent](plugins/ExternalAgent.md); registers with Collaboration when built (rutis usage R6) | -| `treeCommands` | `session` | TimelineTree | yes | `input` by branch id, `create`, `list`, `info` | -| `sessionIdentity` | `session` | SessionScope | yes | `get()`: `{sessionId, restored}` | -| `sessionLifecycle` | `session` | SessionScope | yes | `activated`, `closing`, `hold`, `release`: a hold is an id the calling row owns, ended by `release(id)` or that row's unload. `reportFault` reports a fault, `failure` reads it and `observeFault` subscribes. The calling row releases its subscription with `release(id)` or on unload. | +| `timelineTree` | `session` | TimelineTree | designed, not implemented (today: `treeCommands`) | 见 [TimelineTree 契约](../architecture/rust-agent/plugins/TimelineTree.md#own-contract) | + +| `sessionScope` | `session` | SessionScope | designed, not implemented (today: `sessionIdentity`, `sessionLifecycle`) | the Session's identity, phase, faults and holds ([SessionScope](https://github.com/arcships/dim/pull/2093)) | | `sessionConfig` | `session` | SessionScope | yes | `get()`: the creation-time configuration, the snapshot a tool call carries | | `agentConfig` | `session` | SessionScope | yes | `get()`: the Agent's identity and default model | | `timeline` | `branch` | BranchScope | yes, except `before` | `append`, the published sequence and the event query (§5.4); the query reaches other languages with its declaration | @@ -138,8 +138,10 @@ ToolRegistry or PromptRegistry, or on the method table of its scope, `sessionMet `managementMethods` (process, served to protected-local v3 only), which Rpc reads per call. Each contribution follows its owner's data-face contract and registration lifetime. Two mechanism contracts tie the facades to core parts: a branch is published only with a `LoopState` -provider, and a Session only with a `TimelineTreeControl` provider. Loop and TimelineTree are therefore -core parts, written in Rust. This design does not change that. +provider, and a Session only with the line directory's owner. Loop and TimelineTree are therefore +core parts, written in Rust; the Session assembly reaches the latter through a crate-private +lifecycle entry, not through a catalog name. Today that gate is the catalog name `TimelineTreeControl`; +the target contract states the tree's lifecycle entry ([TimelineTree](../architecture/rust-agent/plugins/TimelineTree.md#own-contract)). ## 5. Events diff --git a/docs/design/plugins/ImageUnderstanding.md b/docs/design/plugins/ImageUnderstanding.md index 5cf9a328be..0e5dfe8bad 100644 --- a/docs/design/plugins/ImageUnderstanding.md +++ b/docs/design/plugins/ImageUnderstanding.md @@ -197,8 +197,8 @@ owner changes its own document. **M4 TimelineTree: published branch-chain queries for Session parts.** - **Problem.** A Session tool needs the calling branch's inherited, published history, not just its own line (§3). -- **Existing mechanisms, and why they fail.** `treeCommands.query` reads only one line; `Branch::query` supports inheritance but obtaining a branch through the Rust-only `get` method bypasses the data face. Reassembling ancestry in the consumer would duplicate the owner's range and continuation rules. -- **Needed capability.** Extend the existing `treeCommands.query` operation with published chain scope, using the shared property-query shape. TimelineTree owns the range, ancestor cuts, ended-line reads and continuation, as specified on its [owner page](../../architecture/rust-agent/plugins/TimelineTree.md). The tool consumes this operation, not a branch handle or storage internals. +- **Existing mechanisms, and why they fail.** Today's `treeCommands.query` reads only one line; `Branch::query` supports inheritance but obtaining a branch through the Rust-only `get` method bypasses the data face. Reassembling ancestry in the consumer would duplicate the owner's range and continuation rules. +- **Needed capability.** The tree's `read` with the chain scope (`scope: Chain`) and a `fields` selection, which gives a line and its ancestors as one cut. TimelineTree owns the range, ancestor cuts, ended-line reads and continuation, as specified on its [owner page](../../architecture/rust-agent/plugins/TimelineTree.md). The tool consumes this operation, not a branch handle or storage internals. - **Ordering impact.** Read-only, fixed published cutoff; no change to sequences, batches, interruption, reload or event formats. Own-line queries retain their existing behavior. - **Owner and issue.** TimelineTree, [#1624](https://github.com/arcships/dim/issues/1624). @@ -241,7 +241,7 @@ Rules: [principles §1 and §4](../../architecture/rust-agent/principles.md), [A | §4.4 No business meaning in core | No core change: the tool is registered through `toolRegistry`, and the image routing rule — pixels, a reference or a placeholder — stays in ModelProvider as Attachments already owns it. | | §4.5 Atomic batches | The design writes no event itself; Loop's ordinary tool-call batch covers the call and its result. | | §4.6 Context only from handed-off events | The answer reaches the model only as a tool result; no injection during request preparation. | -| §4.7 Public events and services only | The part uses `toolRegistry`, `treeCommands.query` with published chain scope (§5 M4) to resolve a reference, the declared `auxiliaryModel` host, `sessionFiles` to read stored image bytes, `guideEntries` for its input-guide entry, Provider's `modelSelectionHost` read for the serving route's protocol, and Modality's M1 read. | +| §4.7 Public events and services only | The part uses `toolRegistry`, the tree's `read` with the chain scope (§5 M4) to resolve a reference, the declared `auxiliaryModel` host, `sessionFiles` to read stored image bytes, `guideEntries` for its input-guide entry, Provider's `modelSelectionHost` read for the serving route's protocol, and Modality's M1 read. | | §4.8 Requirements to mechanism owners | §5, M1–M4. The existing TimelineTree query gains published chain scope; no new runtime or rutis mechanism. | | §4.9 Only facts later decisions use enter the Timeline | Only the ordinary tool facts enter; the digest index is derived and discarded. | | §1 Capability and App Server boundary | A Session Capability in its own crate; the App Server only installs it. | diff --git a/docs/design/service-faces.md b/docs/design/service-faces.md index 0cf6cd6437..3cdf4e47da 100644 --- a/docs/design/service-faces.md +++ b/docs/design/service-faces.md @@ -114,7 +114,7 @@ Rust 产品装配的现状以 [生成的 catalog](../architecture/rust-agent/gen | `modelHost` | `modelHost` | 完整模型请求直接调用所选配置的执行入口;辅助请求使用 `providerService.complete`。 | | `loader` | `rutis/loader` | 插件管理走数据面 | | `sessionStore` | `store`、`sessionFiles`、`timelineStore` | 标题与 worktree 关联直接调 store | -| `treeCommands`、`timelineTreeControl` | `timelineTree` | 分支操作直接调用 Session 的树;不保留别名 | +| `treeCommands`、`timelineTreeControl` | `timelineTree` | 已按 [TimelineTree](../architecture/rust-agent/plugins/TimelineTree.md) 收敛:两个名字删除,`timelineTree` 是树唯一的数据面 | ### 3.4 对象/句柄:拆成操作加 id diff --git a/docs/design/timeline-branches.md b/docs/design/timeline-branches.md index b26f8e0ff0..47566679e0 100644 --- a/docs/design/timeline-branches.md +++ b/docs/design/timeline-branches.md @@ -1,6 +1,6 @@ # Timeline branches -The [target Session tree binding](contracts/runtime-owner-operations.md) moves calls from `treeCommands` to `timelineTree` with the same arguments and replies. The catalog entry and consumer injections change together. References to `treeCommands` below describe the pre-migration binding. +The Session tree's target contract is [TimelineTree](../architecture/rust-agent/plugins/TimelineTree.md): `timelineTree` with `create`, `end`, `set_default`, `directory`, `line` and `read`, and no `treeCommands`, `TreeCommands` or `TimelineTreeControl`. References to `TreeCommands` and `treeCommands` below describe the pre-redesign binding; the behavior this document requires of the tree is unchanged. Status: Accepted ([#427](https://github.com/arcships/dim/issues/427)). This document holds both the requirements and the design: §1–§3 answer #427's questions, and §4 onward is the design. Scope: the TimelineTree plugin (TimelineTree, TreeTimeline, BranchTool, plus a new branch part for BranchLine), one App Server built-in method, one core event, one `BranchSource` kind, the CLI TUI, the Web workspace, and a rewrite of [design rules §2](../architecture/rust-agent/principles.md#2-作用域的含义). Language: Rust. Chinese: [中文](../zh/design/timeline-branches.md). @@ -83,9 +83,9 @@ These needs are not branches: - **Sources.** Every line has a source, recorded in its parent's `branch/create`. The source records where the line was created from; it is not a role marker, and this design reads nothing from it beyond what is stated here: - A **tool line** was opened by the `branch` tool. It is a conversation line: it can be the default branch, and it ends itself with `end` while it is not the default branch. - A **user line** was opened by a client through `session.branch_create`. Its opener is the user, and it is a conversation line too: it can be the default branch. The user ends it; it cannot end itself. - - A **plugin line** was opened by a plugin (`TreeCommands.create`). Its creator owns its protocol, and it can never be the default branch. It opens no lines either. + - A **plugin line** was opened by a plugin. Its creator owns its protocol, and it can never be the default branch. It opens no lines either. - The source can be read as `TimelineInfo.source`, returned for active lines by `TreeCommands.list` and `info` and absent on `main` (§5). Ended directory entries may omit it; opening their display detail reads the creation source at its known position. A plugin line's source is `{kind: "host", operation_id}`: the opener's opaque tag, which the core never interprets. A user line's source is `{kind: "user", operation_id}`, its own kind, so a reader that must tell a conversation line from a plugin line does not parse an `operation_id`. An opener finds its own lines by its own operation-id convention, for example Goal's `goal:evaluate:` prefix. The kind says where the line was created from, and nothing about a role. + The source is the record's `source`, answered by the [TimelineTree contract](../architecture/rust-agent/plugins/TimelineTree.md#own-contract). Ended directory entries may omit it; opening their display detail reads the creation source at its known position. A plugin line's source is `{kind: "host", operation_id}`: the opener's opaque tag, which the core never interprets. A user line's source is `{kind: "user", operation_id}`, its own kind, so a reader that must tell a conversation line from a plugin line does not parse an `operation_id`. An opener finds its own lines by its own operation-id convention, for example Goal's `goal:evaluate:` prefix. The kind says where the line was created from, and nothing about a role. - **Lines created before the upgrade.** `session.branch_create` persists `{kind: "host", operation_id}` today ([connection/tree.rs](../../crates/dim-app-server/src/connection/tree.rs)), and this design rewrites no stored row. A line the user opened through a client before the upgrade, Web `/branch` under `FORMAT` 52 included, therefore stays `host` and is not a valid switch target afterwards, while the same action on a line opened after the upgrade works. This change accepts that limit instead of migrating the fact: `FORMAT` 53 is a marker-only bump that adds no data (§15, §16), and an upgrade case states it (§20). - **Reach of the tool.** A line messages and reads the line it was cut from and each open tool line it opened. A line the user opened stands on both sides of that rule: it messages the line it was cut from and reads it from its cut, and it coordinates the tool lines it opens; the line it was cut from neither messages nor reads it, because the user opened it (§6). `end {content}` takes no target, so it ends the calling line and no other (§6, §10, §11). A plugin line is not on any roster, and the tool neither messages it nor ends it. - **The parent block.** A line's BranchLine writes one keyed `` block on the line itself when the line it was cut from ends a turn and has new activity past the line's last read, the last head the line was told and the line's opening (§7.1.1, §12.1). The block reports positions and is state, not a request; the content stays in the pages a read returns. @@ -102,36 +102,26 @@ Who ends which line is a convention among callers, apart from the lines the tool ## 5. Parts -Every part belongs to the TimelineTree plugin ([timeline_tree.rs](../../crates/dim-agent-capabilities/src/timeline_tree.rs)), and each sits in the scope that owns its state ([ADR 002](../adr/002-plugin-scope.md) D1). +Two features carry these parts ([timeline_tree.rs](../../crates/dim-agent-capabilities/src/timeline_tree.rs)): the TimelineTree feature holds TimelineTree and TreeTimeline, and the BranchTool feature holds BranchTool and BranchLine, each installed with the default profile. Each part sits in the scope that owns its state ([ADR 002](../adr/002-plugin-scope.md) D1). | Part | Scope | Capability | Owns in this design | | --- | --- | --- | --- | | TimelineTree | Session | No | The line lifecycle: the identity block in every child's opening input, `TimelineInfo.source`, the end of a line (`branch/end` → `branch/ended`), refusing input once a line is ending, the restore rule, reads of an ended line's history, the default branch and its `branch/default` fact, and the branch directory (§14) | | TreeTimeline | Branch | Yes | Routes `branch/end` to TimelineTree, as it routes `branch/create` today. For an end issued by a tool call, it also routes the turn end that the close waits for | | BranchTool | Session | No | The action-based `branch` tool (§11). It finds the calling line's BranchLine per call, the way WorkspaceTools finds FileReads | -| **BranchLine** (new) | Branch | Yes | One line's view of its lines. Its role (root, tool line, user line or plugin line) and its parent come from `TreeCommands.info(own id)`. From its own facts it folds its open tool lines and the state of its current turn. It writes the roster, the idle notice and the ended notice, and the one status note a line receives when it becomes the default branch or stops being it. With two openers the roster is its own key, `branch:roster`, which holds the open tool lines it opened (§7.1) | +| **BranchLine** (new) | Branch | Yes | 见 [BranchLine 契约](../architecture/rust-agent/plugins/BranchLine.md#own-contract)。 | -BranchLine injects `B:Dispatcher`, `B:TimelineIdentity`, `B:BranchLifecycle` and `S:TreeCommands`, and provides `B:BranchLine`. +BranchLine's dependencies and its `B:BranchLine` face are stated in the [BranchLine contract](../architecture/rust-agent/plugins/BranchLine.md#own-contract). -It decides the way Goal does: from consumed state, through an owned write task that rechecks before writing, and only on live events after its load cutoff. A reload therefore writes nothing twice, with one exception: a load whose own history ends with a live roster key the fold does not match writes the roster once, because a restart that completed an ended line (§20.7) recorded `branch/ended` before `main`'s replay, so no live event follows it (§6.2). +The line lifecycle, the identity block and the roster belong to [TimelineTree's contract](../architecture/rust-agent/plugins/TimelineTree.md#own-contract) and [BranchLine's](../architecture/rust-agent/plugins/BranchLine.md#own-contract). -The same exception reconciles a move that stopped between its fact and its notes. `branch/default` and each status note are separate batches (§4.5), so a daemon that stops after the fact commits leaves the fact in force and a note unwritten. On load, BranchLine compares two things for its own line: the `default` attribute of the latest live `branch:line` block on it, where a missing attribute means not default, and whether `TreeCommands` reports this line as the default branch now. When they differ it writes the note that matches the tree once, before the line's next model request, and a root never writes one. The new-default note names the line the move started from, so a reconciling load has to know that line: `branch/default` carries it, under the `from` field the note already needs (§16), which is what §4.9 admits a fact for, since the reconciled note decides with it. A load that finds its line's block and the tree in agreement writes nothing, so a second restart writes nothing. On the line the tree reports as the default branch alone, the comparison also reads the text of that block, so a note an older rule set wrote is replaced once at load. +**Restoring the default branch.** The `branch/default` fact is read back on restore and kept only when the line it names is live and selectable (§14): an ended line, a plugin line, or a line created before the upgrade with a `host` source leaves the conversation on the root, and no new fact is written. A move that stopped between its fact and its notes is reconciled by the line's BranchLine (§5, §6.2). -**Restoring the default branch.** A Session whose directory holds one line is on its root and reads nothing for it. A Session with more lines reads one fact: the newest `branch/default` or `session/forked` among the root's own events, through the existing `timeline_events_by_kind` index. A `branch/default` whose target is still open and can be selected names the default branch; a `session/forked` means the default branch is the root, because every `branch/default` the fork copied was written before its `session/forked` and is void; nothing recorded means the root. A target that is no longer open, one naming a plugin line and one naming a line created through a client before the upgrade all fall back to the root (§4). - -That one answer serves every request that omits a branch. A pending approval and an already created scheduled job carry the line they were bound to, so neither is resolved again (§9, §13). - -An explicit creation API `at` is a fixed sequence, including when it equals the -parent's current head. Its fact records `at={kind: "sequence", sequence: at}`; -parent activity while validation awaits cannot widen the inherited prefix. -A `before` producer may still explicitly choose `at={kind: "create"}`, whose -existing meaning is the creation fact's own position. - -Ended display details read purpose/source and end data at their recorded positions. The optional historical cut message count is omitted; displaying a branch does not count all preceding user inputs. +**An explicit creation API `at`.** `session.branch_create` takes an `at` position for the cut. `branch/create` records `{kind: "sequence", sequence}` or, for a producer that names a `before` point, `{kind: "create"}`; the latter stays a fact value the tree keeps, and the line's own creation position is recorded beside it. ## 6. Messages between lines -A message is an `input/message` on the receiver's Timeline, written through `TreeCommands.input`. No new input path is added. A message carries one raw block, marked by its producer and without a key, and the mode of [InputQueue](../architecture/rust-agent/plugins/InputQueue.md): +A message is one `input/message` on the receiver's Timeline, written by the tool and by the tree; its shape and writer are the [TimelineTree contract](../architecture/rust-agent/plugins/TimelineTree.md#session-parts-reaching-a-lines-owners)'s and the [BranchLine contract](../architecture/rust-agent/plugins/BranchLine.md#own-contract)'s. It carries one raw block, marked by its producer and without a key, and the mode of [InputQueue](../architecture/rust-agent/plugins/InputQueue.md): | Mode | Effect on the receiver | When to use it | | --- | --- | --- | @@ -154,7 +144,7 @@ These are Collaboration's message modes and words (`append`, `steer`), with the | Any other pair: siblings, a line and its grandparent | No | No | `branch_not_kin` | A line the user opened is a conversation line like a tool line, and the row it falls under is decided by the edge it stands on: as a line that was opened it has the second row, whose opener is the user and not the line it was cut from, and as an opener of tool lines it has the first row like any other opener. An ended tool line keeps its row, with its message refused: its opener still reads it, which is how the opener gets a result the line never sent. An ended plugin line stays under the plugin row, where no line reads it through the tool. `end` is not part of any pair: `end {content}` has no target, so it always ends the calling line (§10, §11). Coordination follows the parent-child relation, so it stays with the line that opened a line and never moves when the default branch moves, and a former default branch keeps the tool lines it opened and still messages and reads them. -- **Read.** `read {branch, after?, limit?}` returns one page of the target's committed history, open or ended, read from the store through `TreeCommands.page` and rendered the way Collaboration's `read` renders a member's page: inputs, text, tool calls and results, and turn ends, with `nextCursor`; a tool result item carries the effects its tool declared on that result (session boundary A.6), present only when the result declared at least one, a path verbatim and a command cut at its 200th character with the cut marked. The target is the line the caller was cut from, or a line the caller opened. One cursor rule covers both directions: +- **Read.** The page is read through the [TimelineTree contract](../architecture/rust-agent/plugins/TimelineTree.md#own-contract) and rendered the way Collaboration's `read` renders a member's page: inputs, text, tool calls and results, and turn ends, with `nextCursor`; a tool result item carries the effects its tool declared on that result (session boundary A.6), present only when the result declared at least one, a path verbatim and a command cut at its 200th character with the cut marked. The target is the line the caller was cut from, or a line the caller opened. One cursor rule covers both directions: - With no `after`, a read continues after the caller's last successful read of that line: the `nextCursor` of the latest read that returned a page. With no earlier read, a read of the line the caller was cut from starts at the caller's cut, and a read of a line the caller opened starts at that line's first event. - An explicit `after` reads from that point. A read of the line the caller was cut from raises a value below the cut to the cut, because the events up to the cut are already the caller's own history. A read of a line the caller opened uses the value as given, so `after: 0` re-reads that line from its start. - Every successful read moves the cursor to its `nextCursor`, an explicit-after read included; the latest read wins. The cursor is a fact of the caller's own line: BranchLine retains live read results in memory; after a reload it locates the latest successful read for the requested target only when a cursor is used, then reads that request's result fields. Resume does not replay tool history. @@ -264,7 +254,7 @@ A read is on demand, so a line must also know that the line it was cut from move 3. the parent has new activity past `from = max(A, told, opened)`, where `A` is the line's read cursor for the parent (its cut when it has not read yet), `told` is the head the latest `branch:parent` block on the line reports (0 when there is none), and `opened` is the sequence of the line's `branch/create` event on the parent, at or above every cut. Activity from before the line existed is not news, and the line reads it when it needs it. - **What counts as new activity.** Two kinds of event count: an operator input, an `input/message` that carries `user` content, and a tool call. The creating call's `step/tool-use` is written before `opened`, so it is never counted. Nothing else counts on its own: the parent's text, its turn ends, block-only inputs such as the roster and messages from lines, and the creating call's result. The rule is that a line is told when the parent acts or when the operator tells the parent something, and never for the turn that only opened it (its creating call's result, its text and its turn end), which would make every line read its parent for nothing and train it to ignore the block. - **The check.** The parent's facts are read through the one event query ([ADR 019](../adr/019-event-query.md)): the branch's `input/message` and `step/tool-use` events, newest first, paged until one qualifies or the read reaches `from`. No other line's events are folded. -- **The write.** One keyed Append, `branch:parent`, written on the line itself through `TreeCommands.input`, with the parent's id, `head` and `after` as attributes. A later block of the same key replaces the earlier one in the keyed baseline. After the write the fold records the new head and the new input, so a second decision in the queue does not write again. +- **The write.** One keyed Append, the parent block, whose shape, writer and key are stated in the [BranchLine contract](../architecture/rust-agent/plugins/BranchLine.md#own-contract). A later block of the same key replaces the earlier one in the keyed baseline. After the write the fold records the new head and the new input, so a second decision in the queue does not write again. - **At open.** When a child's inherited prefix holds a live `branch:parent` block, the child's opening input carries one more raw block, after the identity block: keyed `branch:parent`, live and not retired, naming the line that opened it P with `head` and `after` both the cut H. It supersedes the inherited block the way the identity supersedes the inherited roster (§7.1), so the line's latest `branch:parent` always names its own parent and its `told` starts at H, which equals `opened`; a compaction replays this block and never the one above it, and the usual block supersedes it when P moves. Only a nested line gets it: a line cut from `main` inherits no `branch:parent` block, so its opening input is byte for byte what it was. TimelineTree composes it where it writes the identity block, and reads whether the key is live from the keyed state of the prefix the child inherits, never from the rendered history. It reads that state while it opens the child, as it reads a resumed line's facts; a failed read fails the create like any other opening failure (branch/create-failed). - **What follows.** A running line gets the block with its next model request. An idle line is not woken: the block is consumed with the first request of its next turn, ahead of the input that starts that turn, which is the documented Append rule ([session access](contracts/session-access.md), [Loop](../architecture/rust-agent/plugins/Loop.md)). A reload writes nothing; a restart writes at most the one block that was due. `main` gets no block: nothing is above it. - **The record.** The line sends the System its configuration holds. The guide is the same on every line (§7.3), so a line whose System did not move from the one it inherited references the configuration that recorded it, on whichever line of its chain recorded it, and a line publishes its own `context/configured` when its System moves, as any branch does. @@ -378,7 +368,7 @@ This pair mirrors `branch/create` and `branch/create-failed`: a command on one T `ancestor` names the line whose own end started the cascade: the end that carries no `ancestor` of its own. Every descendant the cascade ends carries that line, `source` is copied from that same end, and the pair therefore names one end operation: who asked, and on which line. A line ended at its own request has a `source` and no `ancestor`, and a descendant whose own end was already committed keeps that pair when the cascade reaches it. `branch/ended` copies `source` and `ancestor` from the line's `branch/end`, and is always written on the ending line's own parent, taken from the directory. -**A general operation.** `TreeCommands.end(id, source)` and `Session::end_branch(id, source)` check only the target: it exists, it is open, it is not the root, it is not the default branch, and it is not an ancestor of the default branch. Ending the root would close the Session, and ending a line ends every line below it, so the default branch's whole chain is protected. These checks are about the target, not the caller. They never check who calls: the user, an opener and a plugin meet the same guards, and ending the default branch always takes a move of the default branch first. +**A general operation.** `timelineTree.end` checks only the target, and the guards are the [TimelineTree contract](../architecture/rust-agent/plugins/TimelineTree.md#own-contract)'s: it exists, it is open, it is not the root, it is not the default branch, and it is not an ancestor of the default branch. Ending the root would close the Session, and ending a line ends every line below it, so the default branch's whole chain is protected. `Session::end_branch` forwards to the tree today and is removed with the Session face ([#2093](https://github.com/arcships/dim/pull/2093)). These checks are about the target, not the caller. They never check who calls: the user, an opener and a plugin meet the same guards, and ending the default branch always takes a move of the default branch first. The check reads the chain from the directory at the moment of the call and under the tree lock that a move also takes, so a move and an end cannot interleave into a state the rule forbids. Two orderings are therefore admitted, and nothing else: either the end is admitted and the move is refused, because the target or one of its ancestors is ending or ended, or the move is admitted and a later end of a line on the new default branch's chain is refused. A move is refused with `branch_target_protected` when the target or any ancestor of it is still `ending`, so a target cannot become the default branch while an ancestor's cascade is already writing its descendants' ends. A refusal writes nothing. @@ -737,7 +727,7 @@ refusal is shown where the action was raised. The commands the composer offers a | TimelineTree | The identity block in `first_input` for every source. `TreeCommands.end(id, source)` and `TreeCommands.page(id, after, limit)`. `TimelineInfo.source`, filled from the parent's `branch/create` (§5). The end flow and its guards, refusing input once a line is ending, `branch/ended`, the restore rule, reads of ended lines, and the default branch: `branch/default` on the root, its restore read, and the fact the write makes. Its `directory()` reports an open line, an ending line (its own `branch/end` committed, from a tool, a user or a cascade, until its ended row is written) and an ended line, with the ending line's live head, and the current `defaultBranchId`. Its node publishes the sequence of the line's latest turn end to the line's children (§7.1.1). It also delivers the final message a tool end recorded: a tool end's `branch/end` carries it (§10, §16), so restore writes it on the parent under the id derived from that command when the parent holds no input with it, and writes nothing when it does | It owns the line lifecycle, the opening input and the default branch's one authoritative fact | | TreeTimeline | Consumes `branch/end`, plus the line's next turn end for an end issued by a tool call, and routes them to TimelineTree. It reports every `turn/end` to TimelineTree, which publishes it for the line's children | It routes `branch/create` the same way | | BranchTool | The action-based tool, plus the new BranchLine branch part. `read` and `message` reach the line the caller was cut from and the tool lines it opened, with one cursor rule. `create` admits the root and the current default branch and refuses every other line with `branch_not_opener`, then checks the Session's cap and refuses with `branch_limit_reached` | The tool's actions and one line's view of its lines | -| Session facade | `Session::end_branch(id, source)`, `Session::default_branch(id)` and `Session::set_default_branch(id, source)`. An ended line's head is `Session::sequence`; its history is read at that fixed head through `TreeCommands.page` | §17 | +| Session facade | `Session::end_branch(id, source)`, `Session::default_branch(id)` and `Session::set_default_branch(id, source)`, forwarded to the tree and removed with the Session face ([#2093](https://github.com/arcships/dim/pull/2093)). An ended line's head is `Session::sequence`; its history is read at that fixed head through `TreeCommands.page` | §17 | | App Server | `session.branch_end` (v3, a user source with a minted `operation_id`, listed in `hello.features` with the other Session methods when `session_execution` is on and the connection's entry is not bare or the daemon profile is not protected). `session.branch_set_default` (v3, the same admission). `session.history` on an ended line returns immediately, at its stored head. `session.branches` reads the tree's directory and carries `defaultBranchId` (§14). Every Session-level default target that today names `main` reads the default branch instead: `session.submit`, `session.stop`, `session.idle`, `session.goal.*` and `shell.run`, and a newly created scheduled job. `session.model.update`, `session.agent.update` and `session.prompt.refresh` act on the default branch rather than refusing every line but the root. `approval.respond` keeps the `branchId` its notice carried, so a pending request stays on the line that asked for it. On a connection whose projection carries the root alone (v1) an omitted `branchId` keeps reaching the root; v2 and later may name a line, and a v3 connection's unnamed calls follow the default branch. `session.attach` keeps `sequence` as the root's and adds `defaultBranch {branchId, sequence}`; a catalog row's `sequence` stays the root's in both projections while `running` and the activity follow the default branch, and a persisted move refreshes that activity in its own transaction. `session.branches` reads the default and the directory under one tree snapshot. Collaboration stores the member branch a request's input was delivered on and reads it for the idle wait, settlement and every stop; a read page reports its branch, and a continuation carries it or is refused. PromptSuggestion binds its cached turn, offer and generation to a line and withdraws them on a move. EventHub answers admission, source ownership and the type before it resolves an omitted target branch. `ProductEvent::new` carries the new kind in v3 and leaves it out of v1 and v2 | An entry and three reads, no business logic | | dim-agent-types | `branch/end` and `branch/ended` in `EventKind` and the v1 exclusion list, then `branch/default`, registered in the contract tests. `BranchSource` gains a kind for a line the user opened, distinct from a plugin's. The frozen fixtures are unchanged | Core facts (§16) | | Storage | `FORMAT` 52 → 53 as a marker-only upgrade `(52, &[])`: no table scan and no data migration, so an older daemon refuses the store instead of failing on its first decode. `SqliteTimelineStore`'s writer thread caches each Session's default branch for the catalog's recent activity, initialised by the same indexed point query that restore uses | A new event kind and a new `BranchSource` variant are rows a 52 daemon cannot decode |