From 0c327cd395db83d561ad26341e2936d9cc570919 Mon Sep 17 00:00:00 2001 From: huihui Date: Sun, 22 Nov 2026 14:28:47 +0800 Subject: [PATCH 01/35] fix(branch): name a line's parent in the guide entries The ``, `` and `` entries named `main` as the parent, as the roster's line and as the receiver. Any line may open a line, so the examples carry the design's placeholders: `P` for the line a block came from or goes to, and `O` for the line whose roster it is. No sentence changes. The copies the flow tests pin follow. --- crates/dim-agent-capabilities/src/timeline_tree.rs | 6 +++--- crates/dim-agent-capabilities/tests/branch_flow.rs | 6 +++--- tests/integration/tests/minimal_execution.rs | 2 +- tests/integration/tests/prompt_guide.rs | 4 ++-- 4 files changed, 9 insertions(+), 9 deletions(-) diff --git a/crates/dim-agent-capabilities/src/timeline_tree.rs b/crates/dim-agent-capabilities/src/timeline_tree.rs index deb7ef1ff7..94f2f4a458 100644 --- a/crates/dim-agent-capabilities/src/timeline_tree.rs +++ b/crates/dim-agent-capabilities/src/timeline_tree.rs @@ -3467,11 +3467,11 @@ impl LineView { } } /// ``, written by TimelineTree at the start of every child. -const IDENTITY_ENTRY: &str = r#": which line of this session you are, placed by the runtime at the start of a line's own history. A later block of this name replaces the earlier one; a block carrying `default` is the note a move writes. Both are state about the line, not requests."#; +const IDENTITY_ENTRY: &str = r#": which line of this session you are, placed by the runtime at the start of a line's own history. A later block of this name replaces the earlier one; a block carrying `default` is the note a move writes. Both are state about the line, not requests."#; /// ``, the roster BranchLine writes under [`roster_key`] on /// a line that opened lines. -const ROSTER_ENTRY: &str = r#": the lines you opened, under the key `branch:roster` and apart from your own identity under `branch:line`: the runtime lists the tool lines you opened that are still open, each with the first line of its purpose. A later block of this name replaces the earlier one; it is state about the lines, not a request."#; +const ROSTER_ENTRY: &str = r#": the lines you opened, under the key `branch:roster` and apart from your own identity under `branch:line`: the runtime lists the tool lines you opened that are still open, each with the first line of its purpose. A later block of this name replaces the earlier one; it is state about the lines, not a request."#; /// The roster's closing sentence, coordination text for `main` /// ([timeline branches §12.4](../../../docs/design/timeline-branches.md#124-texts-and-their-classes)), @@ -3479,7 +3479,7 @@ const ROSTER_ENTRY: &str = r#": the lines you op const ROSTER_CLOSING: &str = "They message you when they find something, need you, or end. Use the branch tool to message or read them, and the `wait` tool to wait for them; end the wait when your lines have nothing left to tell you."; /// ``, `` and ``. -const BRANCH_MESSAGE_ENTRY: &str = r#": a message from another line of this session, in that line's own words and not the operator's. dim-branch-idle and dim-branch-ended are the runtime's reports about a line you opened: information, not requests."#; +const BRANCH_MESSAGE_ENTRY: &str = r#": a message from another line of this session, in that line's own words and not the operator's. dim-branch-idle and dim-branch-ended are the runtime's reports about a line you opened: information, not requests."#; /// ``, written by BranchLine on a line whose parent moved. const PARENT_ENTRY: &str = r#": on a line, the runtime reports that the line it was cut from has moved past where this line last read it, and where the next read starts. A later block of this name replaces the earlier one; it is state about that line, not a request."#; diff --git a/crates/dim-agent-capabilities/tests/branch_flow.rs b/crates/dim-agent-capabilities/tests/branch_flow.rs index 88f294ae74..a11477a391 100644 --- a/crates/dim-agent-capabilities/tests/branch_flow.rs +++ b/crates/dim-agent-capabilities/tests/branch_flow.rs @@ -4568,12 +4568,12 @@ async fn a_configured_description_reaches_the_request_declaration() { /// its guide entry is registered there, at the Session, and a line carries it /// even where no branch part is loaded. `` stays with /// BranchLine, which writes the roster. -const IDENTITY_ENTRY: &str = r#": which line of this session you are, placed by the runtime at the start of a line's own history. A later block of this name replaces the earlier one; a block carrying `default` is the note a move writes. Both are state about the line, not requests."#; -const ROSTER_ENTRY: &str = r#": the lines you opened, under the key `branch:roster` and apart from your own identity under `branch:line`: the runtime lists the tool lines you opened that are still open, each with the first line of its purpose. A later block of this name replaces the earlier one; it is state about the lines, not a request."#; +const IDENTITY_ENTRY: &str = r#": which line of this session you are, placed by the runtime at the start of a line's own history. A later block of this name replaces the earlier one; a block carrying `default` is the note a move writes. Both are state about the line, not requests."#; +const ROSTER_ENTRY: &str = r#": the lines you opened, under the key `branch:roster` and apart from your own identity under `branch:line`: the runtime lists the tool lines you opened that are still open, each with the first line of its purpose. A later block of this name replaces the earlier one; it is state about the lines, not a request."#; /// #987: the parent block can arrive only on a line with a parent, so main's /// guide carries no entry for it. const PARENT_ENTRY: &str = r#": on a line, the runtime reports that the line it was cut from has moved past where this line last read it, and where the next read starts. A later block of this name replaces the earlier one; it is state about that line, not a request."#; -const MESSAGE_ENTRY: &str = r#": a message from another line of this session, in that line's own words and not the operator's. dim-branch-idle and dim-branch-ended are the runtime's reports about a line you opened: information, not requests."#; +const MESSAGE_ENTRY: &str = r#": a message from another line of this session, in that line's own words and not the operator's. dim-branch-idle and dim-branch-ended are the runtime's reports about a line you opened: information, not requests."#; fn system_text(prompt: &SystemPrompt) -> String { match prompt { diff --git a/tests/integration/tests/minimal_execution.rs b/tests/integration/tests/minimal_execution.rs index 810e16c3fd..b9972d8348 100644 --- a/tests/integration/tests/minimal_execution.rs +++ b/tests/integration/tests/minimal_execution.rs @@ -546,7 +546,7 @@ fn tool_results(events: &[Arc]) -> usize { } /// #552: the entry TimelineTree registers for ``. -const IDENTITY_ENTRY: &str = r#": which line of this session you are, placed by the runtime at the start of a line's own history. A later block of this name replaces the earlier one; a block carrying `default` is the note a move writes. Both are state about the line, not requests."#; +const IDENTITY_ENTRY: &str = r#": which line of this session you are, placed by the runtime at the start of a line's own history. A later block of this name replaces the earlier one; a block carrying `default` is the note a move writes. Both are state about the line, not requests."#; fn system_text(prompt: &SystemPrompt) -> String { match prompt { diff --git a/tests/integration/tests/prompt_guide.rs b/tests/integration/tests/prompt_guide.rs index 92d2087299..333b77d698 100644 --- a/tests/integration/tests/prompt_guide.rs +++ b/tests/integration/tests/prompt_guide.rs @@ -50,9 +50,9 @@ const CHANNEL_RULE: &str = "The operator is the person running this session. The const PROBE_ENTRY: &str = r#": an entry a contributor registered for this flow; the composition places it between the state and the rule entries."#; /// #552: TimelineTree writes `` and registers its entry. -const IDENTITY_ENTRY: &str = r#": which line of this session you are, placed by the runtime at the start of a line's own history. A later block of this name replaces the earlier one; a block carrying `default` is the note a move writes. Both are state about the line, not requests."#; +const IDENTITY_ENTRY: &str = r#": which line of this session you are, placed by the runtime at the start of a line's own history. A later block of this name replaces the earlier one; a block carrying `default` is the note a move writes. Both are state about the line, not requests."#; /// #552: BranchLine writes `` and registers its entry. -const ROSTER_ENTRY: &str = r#": the lines you opened, under the key `branch:roster` and apart from your own identity under `branch:line`: the runtime lists the tool lines you opened that are still open, each with the first line of its purpose. A later block of this name replaces the earlier one; it is state about the lines, not a request."#; +const ROSTER_ENTRY: &str = r#": the lines you opened, under the key `branch:roster` and apart from your own identity under `branch:line`: the runtime lists the tool lines you opened that are still open, each with the first line of its purpose. A later block of this name replaces the earlier one; it is state about the lines, not a request."#; fn configuration(model: &str) -> ModelSelection { ModelSelection { From 5397bf587d390f2751220f0320dff1616258cfc7 Mon Sep 17 00:00:00 2001 From: huihui Date: Sun, 22 Nov 2026 18:25:59 +0800 Subject: [PATCH 02/35] docs(branch): state the opening policy and the status-note texts MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit §12.1 now holds the coordination paragraph of the branch tool, the four conditions for opening a line with their exception and boundaries, the brief a line receives, and the "How you work here" blocks of the status notes: four bullets on a tool line that became the default branch, two on a line the user opened, and two in the note to the former default branch. §12.4 names the three factory members that replace those blocks and keeps the protocol sentences byte-identical. §20.32 states that an end ends every line below it with `ancestor` set, as §10 describes. The Chinese text mirrors the English one. --- docs/design/timeline-branches.md | 29 ++++++++++++------------ docs/zh/design/timeline-branches.md | 35 +++++++++++++++-------------- 2 files changed, 33 insertions(+), 31 deletions(-) diff --git a/docs/design/timeline-branches.md b/docs/design/timeline-branches.md index f636b2df77..ba698ea805 100644 --- a/docs/design/timeline-branches.md +++ b/docs/design/timeline-branches.md @@ -6,7 +6,7 @@ Status: Accepted ([#427](https://github.com/arcships/dim/issues/427)). This docu This design delivers two capabilities: the Session's **default branch**, the line its conversation is on and choosing another open line as that line; and **who may open a line**, which is now the root always, plus whichever line is the current default branch. Every other line is refused, so at most two lines can open at any moment, and the root keeps the ability it has today. -One decision it does not take is the guidance for *when* a model should open a line: the four conditions and their boundaries with neighbouring mechanisms are stated in §12.4 as policy, and the change that first puts a candidate for them in place judges it with the scenarios in §12.3. A Session-wide cap on open tool lines sits beside the right to open (§6.1). +One decision it does not take is the guidance for *when* a model should open a line: the four conditions and their boundaries with neighbouring mechanisms are stated in §12.1 as policy, and the change that first puts a candidate for them in place judges it with the scenarios in §12.3. A Session-wide cap on open tool lines sits beside the right to open (§6.1). The English words are **default branch** for the role and **root** for the line with no parent, whose id is always `main`. The UI keeps 主线 for the default branch and 起点 for the root. @@ -488,14 +488,15 @@ still break adjacent-text merging. No event cache or additional storage format i | Final message | `P`, no key | Steer | `` / `` / blank / `Line C ends with this message.` / `` | | Idle notice | `P`, no key, for a tool line `C` that `P` opened | Steer | `` / `Line C's turn ended () without a message to you, and C is waiting. Read it if you need its state; message it with mode "steer" to give it more work, or leave it.` / `` | | Ended notice | `P`, no key, in the roster's input, for any end of a tool line `P` opened other than its own `end` | Steer | `` / `Line C was ended from outside its own line, by the user or a host operation. It no longer receives messages; read it if you need what it did.` / `` | -| Status note, new default branch, a tool line | `C`, `branch:line` | Append | `` / the birth identity's sentences byte for byte, purpose label and purpose included, then blank / `This line is now the session's default branch, switched from line O. While this block is your latest one: answer the user here; you can open lines with create; you send no automatic idle notice to P; you cannot call end on yourself. Line O stays open and keeps the lines it opened.` / blank / `How you work here:` / `- The user switched here to continue directly from this line's context and approach, so the user's request takes precedence over the purpose above, which still says what this line is for.` / `- When your purpose is done, or cannot be done, message P with what you found, did, changed and left undone and keep working: while this line is the default branch you cannot call end on yourself.` / `- You share the workspace with P and its other lines. If edit or write fails because the file was modified after it was last read, another line may have changed that file: read it again before editing.` / `` | -| Status note, new default branch, a line the user opened | `C`, `branch:line` | Append | `` / its birth identity's sentence byte for byte, then blank / `The user has now made this line the session's default branch, switched from line O. While this block is your latest one: answer the user here; you can open lines with create; you cannot call end on yourself; the user ends this line. Line O stays open and keeps the lines it opened.` / blank / `How you work here:` / `- Carry this line's work forward yourself; the user's request takes precedence over the prompt this line was opened with.` / `` | -| Status note, former default branch | `C`, `branch:line` | Append | `` or the same with `source="user"` / its birth identity's sentences byte for byte, then blank / `Line O is now the session's default branch. This line stays open, reports to P as before and keeps coordinating the lines it opened; it can no longer open lines with create, and the rest of the rules above hold again.` / `` | -| Tool description | Every line | — | `Work with the other lines of this session. A line is you: it starts from your history at the point it is opened, then works in parallel on its own line. It is not a helper with its own memory, and it owes you no result; you and it keep each other informed by reading each other's work and messaging what the other must act on. On a line that opens lines you coordinate: answer a line's steer and act on what it asks for; leave a line's part to that line instead of redoing it; read a line's work instead of waiting for a report.` / `- create (the root and the current default branch only): open a line to work on prompt in parallel. Open one line per part that can go on at the same time as the rest — separate files, a separate question, or a second approach — instead of doing those parts one after another yourself; not for a single quick edit, nor when your next step needs its result. Write prompt as a brief to yourself: the purpose, what you already know that it needs, which files or area are its own, and when it should tell you or end. Returns the line's id.` / `- message: send content to a line you opened, or to the line that opened you. Send a decision, a blocker, or a conflict, not a progress report the receiver can read. Mode "append" (default) reaches the receiver at its next step without interrupting it and does not wake an idle line. Use "steer" when the receiver must act now or is idle.` / `- read: show a page of the activity of the line you were cut from, or of a line you opened, also after it ended. With no after, a read continues after your last read of that line: from your cut for the line you were cut from, and from its first event for a line you opened. Pass after to read from another point. Do not page through a whole line.` / `- end: on a line opened with create, end your own line. content is your final message to the line that opened you: what you found, did, changed and left undone. It is your last action.` / `A line messages and reads the line it was cut from and the lines it opened. The end action ends the calling line only.` | +| Status note, new default branch, a tool line | `C`, `branch:line` | Append | `` / the birth identity's sentences byte for byte, purpose label and purpose included, then blank / `This line is now the session's default branch, switched from line O. While this block is your latest one: answer the user here; you can open lines with create; you send no automatic idle notice to P; you cannot call end on yourself. Line O stays open and keeps the lines it opened.` / blank / `How you work here:` / `- The user switched here to continue directly from this line's context and approach, so the user's request takes precedence over the purpose above, which still says what this line is for.` / `- Carry this line's main work forward yourself; open a new line only when the four conditions for opening one hold again, not to hand off your current task.` / `- When your purpose is done, or cannot be done, message P with what you found, did, changed and left undone and keep working: while this line is the default branch you cannot call end on yourself.` / `- You share the workspace with P and its other lines. Avoid redoing work assigned to lines opened before your cut. If edit or write fails because the file was modified after it was last read, another line may have changed that file: read it again before editing.` / `` | +| Status note, new default branch, a line the user opened | `C`, `branch:line` | Append | `` / its birth identity's sentence byte for byte, then blank / `The user has now made this line the session's default branch, switched from line O. While this block is your latest one: answer the user here; you can open lines with create; you cannot call end on yourself; the user ends this line. Line O stays open and keeps the lines it opened.` / blank / `How you work here:` / `- Carry this line's work forward yourself; open a new line only when the four conditions for opening one hold again. The user's request takes precedence over the prompt this line was opened with.` / `- Line O stays open in the shared workspace and keeps coordinating any lines it already opened. If edit or write fails because the file was modified after it was last read, another line may have changed that file: read it again before editing.` / `` | +| Status note, former default branch, a tool line | `C`, `branch:line` | Append | `` / its birth identity's sentences byte for byte, then blank / `The session's default branch moved from this line to line O. This line stays open, reports to P as before and keeps coordinating the lines it opened; it can no longer open lines with create, and the rest of the rules above hold again. Only a line opened with create can end itself, and not while it or a line below it is the default branch. If end is refused when your purpose is done, message P with what you found, did, changed and left undone and keep working.` / blank / `How you work here:` / `- Keep coordinating any open lines you already opened, and answer messages or user inputs addressed to this line.` / `- You share the workspace with the other open lines; do not edit files outside your remaining scope unless asked, and if edit or write fails because the file was modified after it was last read, read the file again before continuing.` / `` | +| Status note, former default branch, a line the user opened | `C`, `branch:line` | Append | `` / its birth identity's sentences byte for byte, then blank / `The session's default branch moved from this line to line O. This line stays open and keeps coordinating the lines it opened; it can no longer open lines with create, and the rest of the rules above hold again. Only a line opened with create can end itself, and not while it or a line below it is the default branch.` / blank / `How you work here:` / `- Keep coordinating any open lines you already opened, and answer messages or user inputs addressed to this line.` / `- You share the workspace with the other open lines; do not edit files outside your remaining scope unless asked, and if edit or write fails because the file was modified after it was last read, read the file again before continuing.` / `` | +| Tool description | Every line | — | `Work with the other lines of this session. A line is you: it starts from your history at the point it is opened, then works in parallel on its own line. It is not a helper with its own memory, and it owes you no result; you and it keep each other informed by reading each other's work and messaging what the other must act on. On a line that opens lines you coordinate: answer a line's steer and act on what it asks for; leave a line's part to that line instead of redoing it; read a line's work instead of waiting for a report.` / `- create (the root and the current default branch only): open a line to work on prompt in parallel. Open a line only when all four of these hold: the work needs this conversation's context, or its approach is worth the user seeing and taking over; after opening it you have other work to do here right away rather than waiting for it; the part you hand over is multi-step work, not two or three quick actions; and the two lines will not write the same files at the same time. When the user asks for a line, open it. These are not line-shaped: a long command runs in the background instead of taking a line; work that needs none of this conversation's context, or needs different instructions, belongs to another member; one task pursued to completion stays here, or uses a goal; waiting for something outside the session uses an event subscription. Write prompt as a brief to yourself: the purpose in one line, what you decided in this response that the line needs, which files or area are its own (or that it is read-only), and when it should tell you or end. Returns the line's id.` / `- message: send content to a line you opened, or to the line that opened you. Send a decision, a blocker, or a conflict, not a progress report the receiver can read. Mode "append" (default) reaches the receiver at its next step without interrupting it and does not wake an idle line. Use "steer" when the receiver must act now or is idle.` / `- read: show a page of the activity of the line you were cut from, or of a line you opened, also after it ended. With no after, a read continues after your last read of that line: from your cut for the line you were cut from, and from its first event for a line you opened. Pass after to read from another point. Do not page through a whole line.` / `- end: on a line opened with create, end your own line. content is your final message to the line that opened you: what you found, did, changed and left undone. It is your last action.` / `A line messages and reads the line it was cut from and the lines it opened. The end action ends the calling line and every line below it.` | These texts replace the delegation wording in the code today: the `dim-branch-task` block in `first_input` ("That branch delegated this task to you") and the tool description ("works on prompt as a task you delegate"). Their classes are in [§12.4](#124-texts-and-their-classes). -**Why a status note restates the identity.** A note is a later block of the `branch:line` key, so it replaces the birth identity of the line that receives it, and a compaction replays the note alone: a line that could not name its parent, its source and its purpose from its own current block would lose them for the rest of its life. A note therefore repeats the birth block's sentences byte for byte and changes only the sentences the move changes. No note says whether some other line is the default branch, because a later move writes nothing to this line; what a note states are the rules for this line, and the protection of the default branch's chain is checked when `end` is called (§10). +**Why a status note restates the identity.** A note is a later block of the `branch:line` key, so it replaces the birth identity of the line that receives it, and a compaction replays the note alone: a line that could not name its parent, its source and its purpose from its own current block would lose them for the rest of its life. A note therefore repeats the birth block's sentences byte for byte and changes only the sentences the move changes. No note says whether some other line is the default branch, because a later move writes nothing to this line; what a note states are the rules for this line, and the rule it states about `end` is the tree's own, applied when `end` is called (§10). **Which lines get a note.** The rule is per participant: each participant of a move that is not the root receives one note, and the root receives none. A move has two participants, the line the user moved to and the line the user moved from, so it writes two notes when neither is the root, one when one of them is, and none only when both are, which no move has. `main → B` writes one note, to B with `default="true"`; `B → main` writes one note, to B with `default="false"`; `B → C` writes two. The root never receives one in either direction, because neither of its rules changes: it opens lines and it never ends, whichever line holds the default branch. Every other line receives nothing, so no other line's cached prefix moves (§7.3). That is also why no fork-retire rule is needed: a fork copies the root's `branch:line` block, and the only such block the root can hold is its roster. @@ -545,27 +546,27 @@ Every model-facing text of the branch mechanism, with its class ([model-facing p **Protocol.** -- **Marker names and attributes.** `dim-branch-line` with `branch`, `parent`, `source` and, on a status note, `default` (`true` or `false`), keyed `branch:line`; `dim-branch-lines` with `branch`, keyed `branch:roster`; `dim-branch-lines` with `branch`; `dim-branch-parent` with `branch`, `head` and `after`, keyed `branch:parent`; `dim-branch-message` with `from`, `to` and, on a final message, `final`; `dim-branch-idle` with `branch` and `status` (`completed`, `failed` or `cancelled`); `dim-branch-ended` with `branch`. The modes are the InputQueue's: Queue for the identity, Append for the roster, the parent block and the status note, Steer for the notices and for a final message. +- **Marker names and attributes.** `dim-branch-line` with `branch`, `parent`, `source` and, on a status note, `default` (`true` or `false`), keyed `branch:line`; `dim-branch-lines` with `branch`, keyed `branch:roster`; `dim-branch-parent` with `branch`, `head` and `after`, keyed `branch:parent`; `dim-branch-message` with `from`, `to` and, on a final message, `final`; `dim-branch-idle` with `branch` and `status` (`completed`, `failed` or `cancelled`); `dim-branch-ended` with `branch`. The modes are the InputQueue's: Queue for the identity, Append for the roster, the parent block and the status note, Steer for the notices and for a final message. - **The identity blocks' factual sentences.** In a tool line, "You are line C of this session" through "are P's, not yours.", and the label "Your purpose, as P wrote it:"; in a line the user opened and in a plugin line, the block's whole sentence, whose `source` attribute names which of the two it is. A purpose after the label is the creator's own words, carried as content. - **The roster's factual sentences.** "Lines you opened that are still open. Each is you …" and "All lines you opened have ended."; each listed line carries its id and the first line of its purpose. - **The parent block's factual sentences.** "Line P has new activity: it was at H when this was written, and you have read it to A.", the action and field names in "Read what is new with the branch tool (action read, branch \"P\")", and the rule "with no after, the read continues from A." - **The notices' factual sentences.** "Line C's turn ended () without a message to you, and C is waiting." and "Line C was ended from outside its own line, by the user or a host operation. It no longer receives messages". -- **The branch tool's actions and modes.** The actions `create`, `message`, `read` and `end` and what each one does; `mode` `append` or `steer` and what it does to the receiver; the fields each action takes, with `action` required and nothing else accepted; the `read` target rule and its cursor rule ("With no after, a read continues after your last read of that line"); and the sentences that state a guarantee: "Returns the line's id", "Pass after to read from another point", "It is your last action" and "A line messages and reads the line it was cut from and the lines it opened. The end action ends the calling line only." +- **The branch tool's actions and modes.** The actions `create`, `message`, `read` and `end` and what each one does; `mode` `append` or `steer` and what it does to the receiver; the fields each action takes, with `action` required and nothing else accepted; the `read` target rule and its cursor rule ("With no after, a read continues after your last read of that line"); and the sentences that state a guarantee: "Returns the line's id", "Pass after to read from another point", "It is your last action" and "A line messages and reads the line it was cut from and the lines it opened. The end action ends the calling line and every line below it." - **The results and refusals.** `Line created: C`, `Sent to C.`, the page `{items, nextCursor, done}`, `Line C is ending; your final message was sent to P.` and `Line C ends with this message.`; the codes `branch_not_opener`, `branch_limit_reached`, `branch_not_kin`, `branch_not_tool_line`, `branch_ended` and `branch_cannot_end`, with the text each one returns, and `branch_already_default`, `branch_target_protected` and `branch_not_selectable`, which the switch method answers at `session.branch_set_default`; `after A is past line T's head H; a read starts at or below H`, the error result a read returns for an `after` past the target's head, with no code; and `Invalid branch arguments: …`. -- **The status notes' factual sentences.** A note to the new default branch states its id, its parent, its source and its purpose (from the birth block it repeats), the line it was switched from, and the rules that hold while the block is the line's latest one: it answers the user here, it may open lines with `create`, it sends no automatic idle notice to the line that opened it, and it cannot `end` itself. A note to the former default branch states the line now holding the role, that this line stays open and keeps coordinating the lines it opened, that it can no longer open lines, and that the rest of its birth identity's rules hold again. Neither says whether any other line is the default branch (§6.2), the root gets no note, and no note writes an end rule that the tree would contradict: `end` applies the ancestor guard from the tree whenever it is called (§10). +- **The status notes' factual sentences.** A note to the new default branch states its id, its parent, its source and its purpose (from the birth block it repeats), the line it was switched from, and the rules that hold while the block is the line's latest one: it answers the user here, it may open lines with `create`, it sends no automatic idle notice to the line that opened it, and it cannot `end` itself. A note to the former default branch states the move that took the role from this line, naming the line it moved to, that this line stays open and keeps coordinating the lines it opened, that it can no longer open lines, that only a line opened with `create` can end itself and not while it or a line below it is the default branch, that a tool line is told to message the line that opened it and keep working when `end` is refused with its purpose done, and that the rest of its birth identity's rules hold again. Neither says whether any other line is the default branch now (§6.2), the root gets no note, and the rule a note states about whether `end` applies is the tree's own, applied whenever `end` is called (§10). - **The guide entries.** An entry states what its marker is, whose words or which facts it carries, and that it is state or information and never a request. The `` entry states that a later block of that name replaces it, that a block carrying `default` is the note a move writes, and that it belongs to TimelineTree, which writes every identity block, so it is in force in every execution profile. The `` entry belongs to TimelineTree with it and registers at `session` scope, as Goal's does ([Goal §A.5.1](plugins/Goal.md#a51-protocol-and-policy)), because a line's System has to equal its parent's (§7.3): it is in force on `main` too, which never receives the block. The entries of ``, `` and `` belong to BranchLine, which writes the roster and both notices; the `` entry registers with them, and BranchLine is loaded exactly where BranchTool, which writes a message, is. The roster and message entries stay on every line. **Policy.** -- **The coordination text for an opener.** The `branch` tool description's guidance, the same text on every line and therefore for both openers: the opening paragraph on what a line is and what coordinating means for a line that may open lines, the `create` rule for when to open a line and what the brief carries, the `message` rule for choosing a mode and for sending a decision instead of a progress report, and the `read` rule for reading a line's work instead of waiting for a report. [`BranchToolConfig.description`](../../crates/dim-agent-capabilities/src/timeline_tree.rs) replaces the description and nothing else. It covers [§12.2](#122-items-for-the-prompt-layer-429)'s first item: how `main` briefs a line and assigns its files or area, in the `create` rule; answering steers, "answer a line's steer and act on what it asks for"; and not redoing a line's work, "leave a line's part to that line instead of redoing it". The roster's closing sentence, "They message you when they find something, need you, or end. Use the branch tool to message or read them, and the `wait` tool to wait for them; end the wait when your lines have nothing left to tell you.", is coordination text for `main` too, and its "end the wait when your lines have nothing left to tell you" covers ending `main`'s own wait; [`BranchToolConfig.roster_closing`](../../crates/dim-agent-capabilities/src/timeline_tree.rs) replaces it and nothing else. -- **The line's working rules.** The five bullets of "How you work with P:", on the purpose, the reads and messages — including "Do not send P a progress report it can read" and "do not page through P's whole stream" — the workspace, the user and the end, including "Read P once more before you end if the parent block says P has moved", apart from the clauses that name a mechanism: "You cannot open lines", the action and mode names, and "the file was modified after it was last read", the failure `edit` and `write` report, are protocol, as above. It has no factory member yet, and gets one in the change that first evaluates a candidate for it. +- **The coordination text for an opener.** The `branch` tool description's guidance, the same text on every line and therefore for both openers: the opening paragraph on what a line is and what coordinating means for a line that may open lines, the `create` rule for when to open a line and what the brief carries, the `message` rule for choosing a mode and for sending a decision instead of a progress report, and the `read` rule for reading a line's work instead of waiting for a report. The `create` rule's four conditions, its exception for a line the user asks for, and its boundaries by need are policy, and §12.1 holds their text. [`BranchToolConfig.description`](../../crates/dim-agent-capabilities/src/timeline_tree.rs) replaces the description and nothing else. It covers [§12.2](#122-items-for-the-prompt-layer-429)'s first item, how an opener briefs a line and assigns its files or area, in the `create` rule, and how it answers steers and does not redo a line's work, in the opening paragraph's coordination sentence. The roster's closing sentence, "They message you when they find something, need you, or end. Use the branch tool to message or read them, and the `wait` tool to wait for them; end the wait when your lines have nothing left to tell you.", is coordination text for an opener too, and its "end the wait when your lines have nothing left to tell you" covers ending the opener's own wait; [`BranchToolConfig.roster_closing`](../../crates/dim-agent-capabilities/src/timeline_tree.rs) replaces it and nothing else. +- **The line's working rules.** The five bullets of "How you work with P:", on the purpose, the reads and messages — including "Do not send P a progress report it can read" and "do not page through P's whole stream" — the workspace, the user and the end, including "Read P once more before you end if the parent block says P has moved", apart from the clauses that name a mechanism: the opening rule, the action and mode names, and "the file was modified after it was last read", the failure `edit` and `write` report, are protocol, as above. It has no factory member yet, and gets one in the change that first evaluates a candidate for it. - **The parent block's guidance.** "Read it when what P did changes what you do, and before your final message; do not page through all of P's work." It has no factory member yet, and gets one in the change that first evaluates a candidate for it. The rest of the block is protocol, above. - **The notices' guidance.** "Read it if you need its state; message it with mode \"steer\" to give it more work, or leave it." and "read it if you need what it did." It has no factory member yet, and gets one in the change that first evaluates a candidate for it. -- **The status notes' guidance.** Six sentences are policy, each behind its factory member: on the new default branch, "The user switched here to continue directly from this line's context and approach, so the user's request takes precedence over the purpose above, which still says what this line is for.", "Carry this line's main work forward yourself; open a new line only when the four conditions for opening one hold again, not to hand off your current task." and "Avoid redoing work assigned to lines opened before your cut."; on a new default branch the user opened, "Carry this line's work forward yourself; open a new line only when the four conditions for opening one hold again."; on the former default branch, "Keep coordinating any open lines you already opened, and answer messages or user inputs addressed to this line." and "You share the workspace with line N; do not edit files outside your remaining scope unless asked." `BranchToolConfig.primary_note` and `BranchToolConfig.former_primary_note` replace them and nothing else. Everything else in the notes is protocol: the restated identity, whether the line may open a line, that it sends no idle notice, whether it may `end` and why, the line it was switched from, and that a former default branch stays open and keeps its lines. The opening rule is protocol rather than policy because it is the tree's own answer to whether `create` would succeed, and a note that hedged it would tell a line less than the tool call tells it. +- **The status notes' guidance.** Each note's `How you work here:` block is its guidance, and §12.1 holds its exact text: the four bullets after the change sentences on the new default branch of a tool line, the two bullets on the new default branch of a line the user opened, and the two bullets at the end of the note to the former default branch. [`BranchToolConfig.default_note`](../../crates/dim-agent-capabilities/src/timeline_tree.rs), [`BranchToolConfig.user_default_note`](../../crates/dim-agent-capabilities/src/timeline_tree.rs) and [`BranchToolConfig.former_default_note`](../../crates/dim-agent-capabilities/src/timeline_tree.rs) replace those blocks and nothing else, and BranchLine writes each with the note's protocol sentences. A candidate keeps the block's protocol sentences byte-identical: the sentence on what to do when the purpose is done on a tool line, and, in every block, the clause that names the `edit` or `write` failure. Everything else in the notes is protocol too: the restated identity, whether the line may open a line, that it sends no idle notice, whether it may `end` and why, the line it was switched from or the line the role moved to, that a former default branch stays open and keeps its lines, and that only a line opened with `create` can end itself and not while it or a line below it is the default branch. The opening rule is protocol rather than policy because it is the tree's own answer to whether `create` would succeed, and a note that hedged it would tell a line less than the tool call tells it. A candidate for a policy text is put in place at that text's factory member ([model-facing prompts §8.1](model-prompts.md#81-the-rule)) and keeps the protocol sentences of the text it replaces byte-identical. -The coordination text and the status notes are judged together, as one family, in the change that first puts a candidate for either in place ([model-facing prompts §8](model-prompts.md#8-judging-a-change)): the tool description at `BranchToolConfig.description`, the status notes at `BranchToolConfig.primary_note` and `former_primary_note`, and the roster's closing at `BranchToolConfig.roster_closing`. A later change to one of them re-runs the family, because a text that reads well alone can still lose a comparison another one wins. The opening text is judged on the should-open scenarios of §12.3 and, for this design, on `root-opens-after-switch`: a guard that let only the default branch open a line would make the root answer the request instead of opening one, and that scenario is where the difference shows. +The coordination text and the status notes are judged together, as one family, in the change that first puts a candidate for either in place ([model-facing prompts §8](model-prompts.md#8-judging-a-change)): the tool description at `BranchToolConfig.description`, the status notes at `BranchToolConfig.default_note`, `BranchToolConfig.user_default_note` and `BranchToolConfig.former_default_note`, and the roster's closing at `BranchToolConfig.roster_closing`. A later change to one of them re-runs the family, because a text that reads well alone can still lose a comparison another one wins. The opening text is judged on the should-open scenarios of §12.3 and, for this design, on `root-opens-after-switch`: a guard that let only the default branch open a line would make the root answer the request instead of opening one, and that scenario is where the difference shows. ## 13. Interactions @@ -882,7 +883,7 @@ Who may open a line, and the cap: 31. A switch that leaves the Session over the cap refuses new opens and closes nothing. The cap is two and `main → A → B` are the only open tool lines. Selecting `B` protects both, so the counted total is zero; switching back to `main` makes `A` and `B` count together, which is two, and the next `create` answers `branch_limit_reached` with a text that says it is the cap. A single line on the counted side of that subtree leaves the Session over its cap, and nothing is closed either way: every line that was open before the switch is open after it, which the directory reports. A switch never counts only its two participants, and the recorded runs state both halves. `BranchCapSwitch-BackToRoot` starts below both nested lines and admits the switch that spends every slot; `BranchCapSwitch-OverCap` adds one line opened meanwhile and leaves the Session over its cap; `BranchEligibility-AtCapBelow` states the same rule for one line in the single-line model. -32. Every line but the two openers is refused `create`, writes nothing, and keeps the tool lines it opened. A former default branch still messages and reads the tool lines it opened, and its own `create` answers `branch_not_opener`. Its coordination ends no other line either: `end {content}` has no target, so B ends itself and nothing below it. When the user wants C ended, they end it through `session.branch_end`, or B asks C with a steer message to end itself, which is the convention §10 states. A line below one that ends through the cascade is ended by that cascade, not by the tool call. +32. Every line but the two openers is refused `create`, writes nothing, and keeps the tool lines it opened. A former default branch still messages and reads the tool lines it opened, and its own `create` answers `branch_not_opener`. Its coordination cannot end a child on its own either: `end {content}` has no target, so calling it on B ends B itself and every line below it (§10), not C alone. When the user wants C ended, they end it through `session.branch_end`, or B asks C with a steer message to end itself, which is the convention §10 states. A line below an ending ancestor is ended by that cascade (with `ancestor` set, §10), not by a tool call targeting the child. 33. The last slot and a child of the default branch. The cap is two, one open tool line is already off the protected path, and the root is the default branch, so exactly one slot is left. The root opens a line: the new child is a descendant of the default branch, not an ancestor of it, so it counts, and the slot is spent. A second `create` from the root, from the same state of the tree, answers `branch_limit_reached` and writes nothing. Neither open is exempt for being opened from the default branch, and no line is closed to make room. The recorded model run `BranchEligibility-CapBoundary` covers exactly this: `RootInit` with `peers=1`, one open admitted, and no state where a second is. diff --git a/docs/zh/design/timeline-branches.md b/docs/zh/design/timeline-branches.md index 07d0c2711f..7eeeac2931 100644 --- a/docs/zh/design/timeline-branches.md +++ b/docs/zh/design/timeline-branches.md @@ -4,7 +4,7 @@ 本次交付两件事:Session 的**默认分支**(英文 default branch,界面上仍叫“主线”),也就是它的对话所在的那条线,以及由用户把另一条未结束的线选为这条线;以及**谁能开线**,现在是根永远可以,加上当前默认分支。其余每条线都被拒绝,所以任何时刻最多两条线能开线,而根保留它今天的权利。 -它不做的一个决定是什么时候该开线的说明:四个条件以及它们与相邻机制的边界写在 §12.4,作为策略,由第一次把它们放进去的改动用 §12.3 的场景判定。开着的工具线的 Session 级上限与开线权放在一起(§6.1)。 +它不做的一个决定是什么时候该开线的说明:四个条件以及它们与相邻机制的边界写在 §12.1,作为策略,由第一次把它们放进去的改动用 §12.3 的场景判定。开着的工具线的 Session 级上限与开线权放在一起(§6.1)。 ## 1. 分支用来做什么 @@ -443,7 +443,7 @@ WorkspaceTools 不变。 | 写入 | 位置、key | 模式 | 文本 | | --- | --- | --- | --- | | 身份,工具线 | `C`,开启输入的第一个块,`branch:line` | Queue | `` / `You are line C of this session. Line P opened you at this point of its history to work in parallel with it. You are the same agent as P: everything above is your own history, and you continue from here on your own line. P keeps working on its line; you can read its work after this point, and it can read yours. Messages above that were addressed to P, such as its list of open lines, are P's, not yours.` / 空行 / `Your purpose, as P wrote it:` / `` / 空行 / `How you work with P:` / `- Work on this purpose only. You cannot open lines unless this line is the default branch of the session, and this block does not make it one: a status note would. If more parallel work is needed and you cannot open a line, tell P.` / `- Read P with the branch tool (action read, branch "P") when what P did or decided since your cut changes your work; the parent block reports when P has moved. Message P only for what it must act on: a decision that changes its work, a blocker only the user can settle, a conflict with another line, or a change to your purpose. Use mode "steer" for what P must act on now, "append" for what P should see at its next step. Do not send P a progress report it can read, and do not page through P's whole stream: read the page that answers your question, then act.` / `- You share the workspace with P and its other lines. Change only the files P gave you; before changing any other file, tell P which. If edit or write fails because the file was modified after it was last read, another line may have changed the file: read it again and tell P before you continue.` / `- The user can talk to you directly. Answer the user, and ask with ask_user when only the user can decide.` / `- When your purpose is done, or cannot be done, call the branch tool with action "end" and content saying what you found, did, changed and left undone. If you already told P that in a message, your end content carries only what is new. Read P once more before you end if the parent block says P has moved, so your last word still holds. That is your last action; P receives it.` / `` | -| 身份,用户线 | `C`,开启输入的第一个块,`branch:line`。用户的 prompt 是这条输入的 `user` | Queue | `` / `You are line C of this session, opened from line P at this point of its history. You are the same agent as P: everything above is your own history, and you continue from here on your own line, in parallel with P. You can read P's work after this point. Messages above that were addressed to P are P's, not yours. The message after this one says what this line is for.` / `` | +| 身份,用户线 | `C`,开启输入的第一个块,`branch:line`。用户的 prompt 是这条输入的 `user` | Queue | `` / `You are line C of this session, opened by the user from line P at this point of its history. You are the same agent as P: everything above is your own history, and you continue from here on your own line, in parallel with P. You can read P's work after this point. Unless the user makes this line the default branch, you cannot call end on yourself. Messages above that were addressed to P are P's, not yours. The message after this one is from the user for this line.` / `` | | 身份,插件线 | `C`,开启输入的第一个块,`branch:line`。创建者的 prompt 是这条输入的 `user` | Queue | `` / `You are line C of this session, opened from line P at this point of its history. You are the same agent as P: everything above is your own history, and you continue from here on your own line, in parallel with P. You can read P's work after this point. Messages above that were addressed to P are P's, not yours. The message after this one says what this line is for.` / `` | | 名册 | `O`,`branch:roster` | Append | `` / `Lines you opened that are still open. Each is you, working in parallel from the point you opened it; it can read your work after that point, and you can read its.` / `- C1: <目的的第一行,最多 120 个字符>` / … / ``They message you when they find something, need you, or end. Use the branch tool to message or read them, and the `wait` tool to wait for them; end the wait when your lines have nothing left to tell you.`` / `` | | 名册,没有未结束的线 | `O`,`branch:roster` 退役 | Append | `` / `All lines you opened have ended.` / `` | @@ -454,14 +454,15 @@ WorkspaceTools 不变。 | 最终消息 | `P`,无 key | Steer | `` / `` / 空行 / `Line C ends with this message.` / `` | | 空闲通知 | `P`,无 key,针对 `P` 开出的工具线 `C` | Steer | `` / `Line C's turn ended () without a message to you, and C is waiting. Read it if you need its state; message it with mode "steer" to give it more work, or leave it.` / `` | | 结束通知 | `P`,无 key,与名册在同一条输入里;`P` 开出的工具线除自己的 `end` 之外的任何结束 | Steer | `` / `Line C was ended from outside its own line, by the user or a host operation. It no longer receives messages; read it if you need what it did.` / `` | -| 状态说明,新的默认分支,工具线 | `C`,`branch:line` | Append | `` / 逐字重述出生身份的句子,包括目的标签和目的本身,然后空行 / `This line is now the session's default branch, switched from line O. While this block is your latest one: answer the user here; you can open lines with create; you send no automatic idle notice to P; you cannot call end on yourself. Line O stays open and keeps the lines it opened.` / 空行 / `How you work here:` / `- The user switched here to continue directly from this line's context and approach, so the user's request takes precedence over the purpose above, which still says what this line is for.` / `- When your purpose is done, or cannot be done, message P with what you found, did, changed and left undone and keep working: while this line is the default branch you cannot call end on yourself.` / `- You share the workspace with P and its other lines. If edit or write fails because the file was modified after it was last read, another line may have changed that file: read it again before editing.` / `` | -| 状态说明,新的默认分支,用户开的线 | `C`,`branch:line` | Append | `` / 逐字重述出生身份的句子,然后空行 / `The user has now made this line the session's default branch, switched from line O. While this block is your latest one: answer the user here; you can open lines with create; you cannot call end on yourself; the user ends this line. Line O stays open and keeps the lines it opened.` / 空行 / `How you work here:` / `- Carry this line's work forward yourself; the user's request takes precedence over the prompt this line was opened with.` / `` | -| 状态说明,原来的默认分支 | `C`,`branch:line` | Append | ``,或 `source="user"` 的同一条 / 逐字重述出生身份的句子,然后空行 / `Line O is now the session's default branch. This line stays open, reports to P as before and keeps coordinating the lines it opened; it can no longer open lines with create, and the rest of the rules above hold again.` / `` | -| 工具描述 | 每条线 | — | `Work with the other lines of this session. A line is you: it starts from your history at the point it is opened, then works in parallel on its own line. It is not a helper with its own memory, and it owes you no result; you and it keep each other informed by reading each other's work and messaging what the other must act on. On a line that opens lines you coordinate: answer a line's steer and act on what it asks for; leave a line's part to that line instead of redoing it; read a line's work instead of waiting for a report.` / `- create (the root and the current default branch only): open a line to work on prompt in parallel. Open one line per part that can go on at the same time as the rest — separate files, a separate question, or a second approach — instead of doing those parts one after another yourself; not for a single quick edit, nor when your next step needs its result. Write prompt as a brief to yourself: the purpose, what you already know that it needs, which files or area are its own, and when it should tell you or end. Returns the line's id.` / `- message: send content to a line you opened, or to the line that opened you. Send a decision, a blocker, or a conflict, not a progress report the receiver can read. Mode "append" (default) reaches the receiver at its next step without interrupting it and does not wake an idle line. Use "steer" when the receiver must act now or is idle.` / `- read: show a page of the activity of the line you were cut from, or of a line you opened, also after it ended. With no after, a read continues after your last read of that line: from your cut for the line you were cut from, and from its first event for a line you opened. Pass after to read from another point. Do not page through a whole line.` / `- end: on a line opened with create, end your own line. content is your final message to the line that opened you: what you found, did, changed and left undone. It is your last action.` / `A line messages and reads the line it was cut from and the lines it opened. The end action ends the calling line only.` | +| 状态说明,新的默认分支,工具线 | `C`,`branch:line` | Append | `` / 逐字重述出生身份的句子,包括目的标签和目的本身,然后空行 / `This line is now the session's default branch, switched from line O. While this block is your latest one: answer the user here; you can open lines with create; you send no automatic idle notice to P; you cannot call end on yourself. Line O stays open and keeps the lines it opened.` / 空行 / `How you work here:` / `- The user switched here to continue directly from this line's context and approach, so the user's request takes precedence over the purpose above, which still says what this line is for.` / `- Carry this line's main work forward yourself; open a new line only when the four conditions for opening one hold again, not to hand off your current task.` / `- When your purpose is done, or cannot be done, message P with what you found, did, changed and left undone and keep working: while this line is the default branch you cannot call end on yourself.` / `- You share the workspace with P and its other lines. Avoid redoing work assigned to lines opened before your cut. If edit or write fails because the file was modified after it was last read, another line may have changed that file: read it again before editing.` / `` | +| 状态说明,新的默认分支,用户开的线 | `C`,`branch:line` | Append | `` / 逐字重述出生身份的句子,然后空行 / `The user has now made this line the session's default branch, switched from line O. While this block is your latest one: answer the user here; you can open lines with create; you cannot call end on yourself; the user ends this line. Line O stays open and keeps the lines it opened.` / 空行 / `How you work here:` / `- Carry this line's work forward yourself; open a new line only when the four conditions for opening one hold again. The user's request takes precedence over the prompt this line was opened with.` / `- Line O stays open in the shared workspace and keeps coordinating any lines it already opened. If edit or write fails because the file was modified after it was last read, another line may have changed that file: read it again before editing.` / `` | +| 状态说明,原来的默认分支,工具线 | `C`,`branch:line` | Append | `` / 逐字重述出生身份的句子,然后空行 / `The session's default branch moved from this line to line O. This line stays open, reports to P as before and keeps coordinating the lines it opened; it can no longer open lines with create, and the rest of the rules above hold again. Only a line opened with create can end itself, and not while it or a line below it is the default branch. If end is refused when your purpose is done, message P with what you found, did, changed and left undone and keep working.` / 空行 / `How you work here:` / `- Keep coordinating any open lines you already opened, and answer messages or user inputs addressed to this line.` / `- You share the workspace with the other open lines; do not edit files outside your remaining scope unless asked, and if edit or write fails because the file was modified after it was last read, read the file again before continuing.` / `` | +| 状态说明,原来的默认分支,用户开的线 | `C`,`branch:line` | Append | `` / 逐字重述出生身份的句子,然后空行 / `The session's default branch moved from this line to line O. This line stays open and keeps coordinating the lines it opened; it can no longer open lines with create, and the rest of the rules above hold again. Only a line opened with create can end itself, and not while it or a line below it is the default branch.` / 空行 / `How you work here:` / `- Keep coordinating any open lines you already opened, and answer messages or user inputs addressed to this line.` / `- You share the workspace with the other open lines; do not edit files outside your remaining scope unless asked, and if edit or write fails because the file was modified after it was last read, read the file again before continuing.` / `` | +| 工具描述 | 每条线 | — | `Work with the other lines of this session. A line is you: it starts from your history at the point it is opened, then works in parallel on its own line. It is not a helper with its own memory, and it owes you no result; you and it keep each other informed by reading each other's work and messaging what the other must act on. On a line that opens lines you coordinate: answer a line's steer and act on what it asks for; leave a line's part to that line instead of redoing it; read a line's work instead of waiting for a report.` / `- create (the root and the current default branch only): open a line to work on prompt in parallel. Open a line only when all four of these hold: the work needs this conversation's context, or its approach is worth the user seeing and taking over; after opening it you have other work to do here right away rather than waiting for it; the part you hand over is multi-step work, not two or three quick actions; and the two lines will not write the same files at the same time. When the user asks for a line, open it. These are not line-shaped: a long command runs in the background instead of taking a line; work that needs none of this conversation's context, or needs different instructions, belongs to another member; one task pursued to completion stays here, or uses a goal; waiting for something outside the session uses an event subscription. Write prompt as a brief to yourself: the purpose in one line, what you decided in this response that the line needs, which files or area are its own (or that it is read-only), and when it should tell you or end. Returns the line's id.` / `- message: send content to a line you opened, or to the line that opened you. Send a decision, a blocker, or a conflict, not a progress report the receiver can read. Mode "append" (default) reaches the receiver at its next step without interrupting it and does not wake an idle line. Use "steer" when the receiver must act now or is idle.` / `- read: show a page of the activity of the line you were cut from, or of a line you opened, also after it ended. With no after, a read continues after your last read of that line: from your cut for the line you were cut from, and from its first event for a line you opened. Pass after to read from another point. Do not page through a whole line.` / `- end: on a line opened with create, end your own line. content is your final message to the line that opened you: what you found, did, changed and left undone. It is your last action.` / `A line messages and reads the line it was cut from and the lines it opened. The end action ends the calling line and every line below it.` | 这些文本取代代码里现有的委派措辞:`first_input` 里的 `dim-branch-task` 块("That branch delegated this task to you")和工具描述("works on prompt as a task you delegate")。那条状态说明的类别见 [§12.4](#124-文本及其类别)。 -**状态说明为什么重述身份。** 说明是 `branch:line` key 的后续块,所以它取代收到它的那条线的出生身份,而压缩也只重放这条说明:一条无法从自己当前块里说出父分支、来源和目的的线,会在余生里一直缺这几项。所以说明逐字重复出生块的句子,只改移动所改变的那几句。说明里不写别的线现在是不是默认分支,因为再移一次并不会给这条线写任何东西;说明写的是这条线自己的规则,而默认分支祖宗链的保护在 `end` 被调用时判定(§10)。 +**状态说明为什么重述身份。** 说明是 `branch:line` key 的后续块,所以它取代收到它的那条线的出生身份,而压缩也只重放这条说明:一条无法从自己当前块里说出父分支、来源和目的的线,会在余生里一直缺这几项。所以说明逐字重复出生块的句子,只改移动所改变的那几句。说明里不写别的线现在是不是默认分支,因为再移一次并不会给这条线写任何东西;说明写的是这条线自己的规则,而它写的那条 `end` 规则是树自己的规则,在 `end` 被调用时适用(§10)。 **哪些线会收到说明。** 规则按参与者算:一次移动的每个参与者,只要不是根,就收到恰好一条说明;根一条也不收。一次移动有两个参与者,用户移去的那条线和移开的那条线,所以两者都不是根时写两条,其中之一是根时写一条,只有两者都是根时才是零条,而没有这样的移动。`main → B` 写一条,给 B,`default="true"`;`B → main` 写一条,给 B,`default="false"`;`B → C` 写两条。根在两个方向上都不收,因为它的规则一条都没变:它开线、它永不结束,不论默认分支是哪条线。其他每条线都收不到任何东西,所以其他任何线的缓存前缀都不会移动(§7.3)。这也是为什么不需要 fork 清理规则:fork 复制根上的 `branch:line` 块,而根能持有的这种块只有它的名册。各段文本的类别见 [§12.4](#124-文本及其类别)。 @@ -511,28 +512,28 @@ WorkspaceTools 不变。 **协议。** -- **标记名与属性。** `dim-branch-line` 带 `branch`、`parent`、`source`,状态说明上还带 `default`(`true` 或 `false`),key 为 `branch:line`;`dim-branch-lines` 带 `branch`,key 为 `branch:roster`;`dim-branch-parent` 带 `branch`、`head` 和 `after`,key 为 `branch:parent`;`dim-branch-message` 带 `from`、`to`,最终消息再带 `final`;`dim-branch-idle` 带 `branch` 和 `status`(`completed`、`failed` 或 `cancelled`);`dim-branch-ended` 带 `branch`。模式用的是 InputQueue 的:身份是 Queue,名册和父线块是 Append,通知和最终消息是 Steer。 +- **标记名与属性。** `dim-branch-line` 带 `branch`、`parent`、`source`,状态说明上还带 `default`(`true` 或 `false`),key 为 `branch:line`;`dim-branch-lines` 带 `branch`,key 为 `branch:roster`;`dim-branch-parent` 带 `branch`、`head` 和 `after`,key 为 `branch:parent`;`dim-branch-message` 带 `from`、`to`,最终消息再带 `final`;`dim-branch-idle` 带 `branch` 和 `status`(`completed`、`failed` 或 `cancelled`);`dim-branch-ended` 带 `branch`。模式用的是 InputQueue 的:身份是 Queue,名册、父线块和状态说明是 Append,通知和最终消息是 Steer。 - **身份块的事实句。** 工具线里,"You are line C of this session" 到 "are P's, not yours.",以及标签 "Your purpose, as P wrote it:";用户线和插件线里,整句,`source` 属性说明是哪一种。标签后的 purpose 是创建者自己的话,按内容承载。 - **名册的事实句。** "Lines you opened that are still open. Each is you …" 与 "All lines you opened have ended.";列出的每一条带线的 id 和目的的第一行。 - **父线块的事实句。** "Line P has new activity: it was at H when this was written, and you have read it to A."、"Read what is new with the branch tool (action read, branch \"P\")" 中的动作与字段名,以及规则 "with no after, the read continues from A."。 - **通知的事实句。** "Line C's turn ended () without a message to you, and C is waiting." 与 "Line C was ended from outside its own line, by the user or a host operation. It no longer receives messages"。 -- **branch 工具的动作与模式。** 动作 `create`、`message`、`read`、`end` 及各自做什么;`mode` 为 `append` 或 `steer` 及它对接收方的作用;每个动作接收的字段,`action` 必填且不接受别的字段;`read` 的目标规则及其游标规则("With no after, a read continues after your last read of that line");以及陈述保证的句子:"Returns the line's id"、"Pass after to read from another point"、"It is your last action"、"A line messages and reads the line it was cut from and the lines it opened. The end action ends the calling line only."。 -- **结果与拒绝。** `Line created: C`、`Sent to C.`、页 `{items, nextCursor, done}`、`Line C is ending; your final message was sent to P.` 与 `Line C ends with this message.`;拒绝码 `branch_not_opener`、`branch_limit_reached`、`branch_not_kin`、`branch_not_tool_line`、`branch_ended`、`branch_cannot_end` 及各自的文本;`after A is past line T's head H; a read starts at or below H`,即读取在 `after` 超过目标头部时返回的错误结果,不带代码;以及 `Invalid branch arguments: …`。 -- **状态说明的事实句。** 给新默认分支的说明写出它的 id、父分支、来源和目的(逐字重述出生块)、它从哪条线切过来,以及这块是它最新块时成立的规则:它在这里回答用户、可以用 `create` 开线、不向开它的那条线发自动空闲通知、不能对自己 `end`。给原默认分支的说明写出现在持有这个角色的线、这条线照旧开着并继续协调它开过的线、它不能再开线,以及它出生身份里其余规则重新成立。 -- **指南条目。** 每个条目标明它的标记是什么、承载谁的话或哪些事实,以及它是状态或信息、绝不是请求。`` 的条目说明后出现的同名块会取代它,并说明带 `default` 的块是移动默认分支时写的说明,它归 TimelineTree——每段身份块都由它写——所以在任何执行配置下都在位。`` 的条目写明 key 是 `branch:roster`,`` 和 `` 的条目归 BranchLine,名册和两条通知都由它写;`` 的条目与它们一起注册,因为 BranchLine 恰好在写消息的 BranchTool 所在之处加载。`` 的条目与它一起归 TimelineTree,按 `session` 作用域注册,和 Goal 的一样([Goal §A.5.1](plugins/Goal.md#a51-协议与策略)),因为一条线的 System 必须等于它父线的 System(§7.3):它在根上同样在位,尽管根从不收到这个块。`` 的条目写明它的 key 是 `branch:roster`,所以读者不会把它当成 `branch:line` 下的身份。`` 的条目还说明带 `default` 的块是移动默认分支时写的说明。名册条目和消息条目在每条线上都在。 +- **branch 工具的动作与模式。** 动作 `create`、`message`、`read`、`end` 及各自做什么;`mode` 为 `append` 或 `steer` 及它对接收方的作用;每个动作接收的字段,`action` 必填且不接受别的字段;`read` 的目标规则及其游标规则("With no after, a read continues after your last read of that line");以及陈述保证的句子:"Returns the line's id"、"Pass after to read from another point"、"It is your last action"、"A line messages and reads the line it was cut from and the lines it opened. The end action ends the calling line and every line below it."。 +- **结果与拒绝。** `Line created: C`、`Sent to C.`、页 `{items, nextCursor, done}`、`Line C is ending; your final message was sent to P.` 与 `Line C ends with this message.`;拒绝码 `branch_not_opener`、`branch_limit_reached`、`branch_not_kin`、`branch_not_tool_line`、`branch_ended`、`branch_cannot_end` 及各自的文本,以及切换方法在 `session.branch_set_default` 处返回的 `branch_already_default`、`branch_target_protected` 和 `branch_not_selectable`;`after A is past line T's head H; a read starts at or below H`,即读取在 `after` 超过目标头部时返回的错误结果,不带代码;以及 `Invalid branch arguments: …`。 +- **状态说明的事实句。** 给新默认分支的说明写出它的 id、父分支、来源和目的(逐字重述出生块)、它从哪条线切过来,以及这块是它最新块时成立的规则:它在这里回答用户、可以用 `create` 开线、不向开它的那条线发自动空闲通知、不能对自己 `end`。给原默认分支的说明写出这次把角色从这条线移走的移动、并点明移到了哪条线;这条线照旧开着并继续协调它开过的线;它不能再开线;只有用 `create` 开出的线才能结束自己,而且当它自己或它下面的一条线是默认分支时不能结束;工具线还被告知在目的完成而 `end` 被拒时给开它的那条线发消息并继续工作;以及它出生身份里其余规则重新成立。两条说明都不说别的线现在是不是默认分支(§6.2),根不写说明,而说明里关于 `end` 是否适用的规则是树自己的规则,在每次调用 `end` 时适用(§10)。 +- **指南条目。** 每个条目标明它的标记是什么、承载谁的话或哪些事实,以及它是状态或信息、绝不是请求。`` 的条目说明后出现的同名块会取代它,并说明带 `default` 的块是移动默认分支时写的说明,它归 TimelineTree——每段身份块都由它写——所以在任何执行配置下都在位。`` 的条目与它一起归 TimelineTree,按 `session` 作用域注册,和 Goal 的一样([Goal §A.5.1](plugins/Goal.md#a51-协议与策略)),因为一条线的 System 必须等于它父线的 System(§7.3):它在根上同样在位,尽管根从不收到这个块。``、`` 和 `` 的条目归 BranchLine,名册和两条通知都由它写;`` 的条目与它们一起注册,因为 BranchLine 恰好在写消息的 BranchTool 所在之处加载。名册条目和消息条目在每条线上都在。 **策略。** -- **开线方的协调文字。** `branch` 工具描述的指引,每条线上都是同一份,所以两个开线方都适用:说明一条线是什么、以及对于一条能开线的线而言协调意味着什么的开头段、`create` 关于何时开线与 brief 带什么的规则、`message` 关于选模式和发决定而不是进度报告的规则,以及 `read` 关于读线上的工作而不是等报告的规则。[`BranchToolConfig.description`](../../../crates/dim-agent-capabilities/src/timeline_tree.rs) 只替换这段描述,不替换别的。它覆盖 [§12.2](#122-交给提示词层的事项429) 的第一项:`main` 怎样给一条线写说明、分配它的文件或区域(`create` 规则);回应 steer("answer a line's steer and act on what it asks for");不重做线上的工作("leave a line's part to that line instead of redoing it")。名册的收尾句 "They message you when they find something, need you, or end. Use the branch tool to message or read them, and the `wait` tool to wait for them; end the wait when your lines have nothing left to tell you." 也是 `main` 的协调文字,其中 "end the wait when your lines have nothing left to tell you" 覆盖结束 `main` 自己的等待;[`BranchToolConfig.roster_closing`](../../../crates/dim-agent-capabilities/src/timeline_tree.rs) 只替换这句,不替换别的。 -- **线的工作规则。** "How you work with P:" 的五条要点——目的、读取与消息(含 "Do not send P a progress report it can read" 和 "do not page through P's whole stream")、工作区、用户和结束(含 "Read P once more before you end if the parent block says P has moved")——除了点明机制的从句:"You cannot open lines"、动作名与模式名,以及 "the file was modified after it was last read"(`edit` 与 `write` 报告的那次失败)是协议,见上。它还没有工厂配置成员,在第一次为它评估候选的改动里获得成员。 +- **开线方的协调文字。** `branch` 工具描述的指引,每条线上都是同一份,所以两个开线方都适用:说明一条线是什么、以及对于一条能开线的线而言协调意味着什么的开头段、`create` 关于何时开线与 brief 带什么的规则、`message` 关于选模式和发决定而不是进度报告的规则,以及 `read` 关于读线上的工作而不是等报告的规则。`create` 规则里的四个条件、用户要求开线时的例外,以及按需要划的边界是策略,它们的文本在 §12.1。[`BranchToolConfig.description`](../../../crates/dim-agent-capabilities/src/timeline_tree.rs) 只替换这段描述,不替换别的。它覆盖 [§12.2](#122-交给提示词层的事项429) 的第一项:开线方怎样给一条线写说明、分配它的文件或区域,在 `create` 规则里;以及它怎样回应 steer、不重做线上的工作,在开头段的协调句里。名册的收尾句 "They message you when they find something, need you, or end. Use the branch tool to message or read them, and the `wait` tool to wait for them; end the wait when your lines have nothing left to tell you." 也是开线方的协调文字,其中 "end the wait when your lines have nothing left to tell you" 覆盖结束开线方自己的等待;[`BranchToolConfig.roster_closing`](../../../crates/dim-agent-capabilities/src/timeline_tree.rs) 只替换这句,不替换别的。 +- **线的工作规则。** "How you work with P:" 的五条要点——目的、读取与消息(含 "Do not send P a progress report it can read" 和 "do not page through P's whole stream")、工作区、用户和结束(含 "Read P once more before you end if the parent block says P has moved")——除了点明机制的从句:开线那条规则、动作名与模式名,以及 "the file was modified after it was last read"(`edit` 与 `write` 报告的那次失败)是协议,见上。它还没有工厂配置成员,在第一次为它评估候选的改动里获得成员。 - **父线块的指引。** "Read it when what P did changes what you do, and before your final message; do not page through all of P's work."。它还没有工厂配置成员,在第一次为它评估候选的改动里获得成员。块的其余部分是协议,见上。 - **通知的指引。** "Read it if you need its state; message it with mode \"steer\" to give it more work, or leave it." 与 "read it if you need what it did."。它还没有工厂配置成员,在第一次为它评估候选的改动里获得成员。 -- **状态说明的指引。** 有六句是策略,各自在工厂配置成员后面:给新默认分支的“用户移到这里,是为了直接从这条线的上下文和做法继续,所以用户的请求优先于上面那个目的,那个目的仍然说明这条线是做什么的。”“自己把这条线的主要工作接着做下去;只有在开线的四个条件再次全部成立时才开新线,而不是把当前任务交出去。”和“避免重做切点之前开出的线已经分到的工作。”;给用户新开的默认分支的“自己把这条线的工作接着做下去;只有在开线的四个条件再次全部成立时才开新线。”;给原默认分支的“继续协调你已经开过的线,并回答发给这条线的消息或用户输入。”和“你与线 N 共用工作区;除非被要求,不要改你剩余范围之外的文件。”。`BranchToolConfig.primary_note` 与 `BranchToolConfig.former_primary_note` 替换它们,别的都不动。说明里其余的都是协议:重述的身份、这条线能不能开线、不发空闲通知、能不能 `end` 及原因、它从哪条线切过来,以及原默认分支照旧开着并保留自己的线。开线那条规则属于协议而不是策略,因为它是树对 `create` 会不会成功的直接答案,一条含糊的说明反而会让线知道得比工具调用更少。 +- **状态说明的指引。** 每条说明的 `How you work here:` 块就是它的指引,确切文本在 §12.1:工具线的新默认分支是更改句之后的四条要点,用户开的那条线是两条要点,原默认分支是说明末尾的两条要点。[`BranchToolConfig.default_note`](../../../crates/dim-agent-capabilities/src/timeline_tree.rs)、[`BranchToolConfig.user_default_note`](../../../crates/dim-agent-capabilities/src/timeline_tree.rs) 与 [`BranchToolConfig.former_default_note`](../../../crates/dim-agent-capabilities/src/timeline_tree.rs) 只替换这些块,不替换别的,由 BranchLine 连同说明里的协议句一起写出。候选要逐字节保留块里的协议句:工具线上目的完成时该做什么的那一句,以及每个块里点明 `edit` 或 `write` 失败的那一句。说明里其余的都是协议:重述的身份、这条线能不能开线、不发空闲通知、能不能 `end` 及原因、它从哪条线切过来或角色移到了哪条线、原默认分支照旧开着并保留自己的线,以及只有用 `create` 开出的线才能结束自己、当它自己或它下面的一条线是默认分支时不能结束。开线那条规则属于协议而不是策略,因为它是树对 `create` 会不会成功的直接答案,一条含糊的说明反而会让线知道得比工具调用更少。 策略文本的候选放在该文本的工厂配置成员上([面向模型的提示词 §8.1](model-prompts.md#81-规则)),并让它替换的文本里的协议句逐字节不变。 -协调文字和状态说明合在一起判定,作为同一个族,由第一次为其中任何一段放入候选的改动来做([面向模型的提示词 §8](model-prompts.md#8-一次改动怎样判定)):工具描述在 `BranchToolConfig.description`、状态说明在 `BranchToolConfig.primary_note` 与 `former_primary_note`、名册的收尾句在 `BranchToolConfig.roster_closing`。以后改动其中一段就要重跑整个族,因为单独读着顺的文本,仍可能输给另一段文本赢下的对照。开线那段文字在 §12.3 的 should-open 场景上判定,对本设计还要加上 `root-opens-after-switch`:只让默认分支开线的守卫会让根去回答请求而不是开一条线,那个场景正是这个差别的落点。 +协调文字和状态说明合在一起判定,作为同一个族,由第一次为其中任何一段放入候选的改动来做([面向模型的提示词 §8](model-prompts.md#8-一次改动怎样判定)):工具描述在 `BranchToolConfig.description`、状态说明在 `BranchToolConfig.default_note`、`BranchToolConfig.user_default_note` 与 `BranchToolConfig.former_default_note`、名册的收尾句在 `BranchToolConfig.roster_closing`。以后改动其中一段就要重跑整个族,因为单独读着顺的文本,仍可能输给另一段文本赢下的对照。开线那段文字在 §12.3 的 should-open 场景上判定,对本设计还要加上 `root-opens-after-switch`:只让默认分支开线的守卫会让根去回答请求而不是开一条线,那个场景正是这个差别的落点。 ## 13. 相互影响 @@ -769,7 +770,7 @@ Goal 流程,放在 `crates/dim-goal/tests` 的流程测试中(§7.4): 31. 一次移动让 Session 越过上限时,拒绝新的开线、不关闭任何东西。上限为二,`main → A → B` 是仅有的未结束工具线。选中 `B` 时两条都受保护,计数为零;移回 `main` 时 `A` 和 `B` 同时计数,也就是二,之后 `create` 回答 `branch_limit_reached`,其文本说明这是上限。这样一条线落在计数一侧时,Session 就停在上限之上,两个方向都没有关闭任何线:移动前开着的线在移动后仍开着,目录也会这样报告。移动从不只算它的两个参与者,记录的运行把两半都写出来:`BranchCapSwitch-BackToRoot` 从两条嵌套线之下开始,接受这次用满全部名额的切换;`BranchCapSwitch-OverCap` 期间多开一条线,把 Session 留在上限之上;`BranchEligibility-AtCapBelow` 在单线模型里陈述同一条规则。 -32. 除两个开线方之外的每条线都被拒绝 `create`,什么也不写,并保留它开出的工具线:曾经的默认分支仍能给开出的工具线发消息、读它们,只是它自己的 `create` 回答 `branch_not_opener`。它的协调也不会结束任何别的线:`end {content}` 不接受目标,所以 B 结束的是自己,不连带它下面的线。用户要结束 C 时,要么经 `session.branch_end` 结束它,要么由 B 用一条 steer 消息请 C 自己结束,这就是 §10 写的约定;因祖先结束而结束的线是被那次连锁结束的,不是被这次工具调用结束的。 +32. 除两个开线方之外的每条线都被拒绝 `create`,什么也不写,并保留它开出的工具线:曾经的默认分支仍能给开出的工具线发消息、读它们,只是它自己的 `create` 回答 `branch_not_opener`。它的协调也不能单独结束某条子线:`end {content}` 不接受目标,所以在 B 上调用它结束的是 B 自己以及它下面的每一条线(§10),而不是单独结束 C。用户要结束 C 时,要么经 `session.branch_end` 结束它,要么由 B 用一条 steer 消息请 C 自己结束,这就是 §10 写的约定;处在结束中的祖先之下的线是由那次连锁一并结束的(带 `ancestor`,§10),而不是由指定子线的工具调用结束的。 33. 最后一个名额和默认分支的子线。上限为二,已经有一条不在受保护路径上的工具线,根是默认分支,所以正好还剩一个名额。根开一条线:新子线是默认分支的后代而不是祖先,所以它计数,名额被花掉。同一树状态下根再 `create` 一次回答 `branch_limit_reached`,什么也不写。两次开线都不因由默认分支发出而获免,也没有任何线被关闭来腾位置。记录的模型运行 `BranchEligibility-CapBoundary` 正是这个场景:`RootInit` 取 `peers=1`,一次开线被接受,没有任何状态接受第二次。 From aecad5c5d05e42146f8a2851e3f37843a8c36505 Mon Sep 17 00:00:00 2001 From: huihui Date: Sun, 22 Nov 2026 18:50:46 +0800 Subject: [PATCH 03/35] feat(branch): state the opening policy and the status notes The branch tool's description now says what coordinating means on a line that opens lines, when all four conditions for opening one hold, the exception when the user asks for a line, the work these conditions do not cover, and that an end ends every line below it. A status note's "How you work here" block is written by BranchLine from three factory members: `default_note` for a tool line a move makes the default branch, `user_default_note` for a line the user opened, and `former_default_note` for the former default branch. The note's protocol sentences stay the code's, the former note names the line the role moved to and restates the end rule, and the line ids the note names replace the members' `{parent}` and `{other}` placeholders. The evaluation can replace each block with `timeline-tree/default-note`, `timeline-tree/user-default-note` and `timeline-tree/former-default-note`. The compaction identity test now covers a tool line a move makes the default branch, a tool line it displaced, a line the user opened and the root. The description grows by 586 characters, about 147 tokens per request. A status note is written only when a move writes it. --- .../src/timeline_tree.rs | 97 ++++++++-- .../tests/branch_flow.rs | 175 ++++++++++++++++-- .../rust-agent/plugins/BranchTool.md | 4 +- xtask/src/app_server.rs | 13 ++ xtask/src/scenario_eval.rs | 76 ++++++++ 5 files changed, 328 insertions(+), 37 deletions(-) diff --git a/crates/dim-agent-capabilities/src/timeline_tree.rs b/crates/dim-agent-capabilities/src/timeline_tree.rs index 94f2f4a458..fa1fcd9e95 100644 --- a/crates/dim-agent-capabilities/src/timeline_tree.rs +++ b/crates/dim-agent-capabilities/src/timeline_tree.rs @@ -3562,7 +3562,7 @@ impl DynPlugin for BranchLinePlugin { own: identity.branch_id.clone(), tree, timeline: timeline.clone(), - roster_closing: self.config.roster_closing.clone(), + config: self.config.clone(), view: Mutex::new(LineView::default()), wanted: Mutex::new(std::collections::VecDeque::new()), changed: tokio::sync::Notify::new(), @@ -3640,8 +3640,9 @@ pub struct BranchLine { /// The line's own Timeline, which a load writes through before the tree /// has registered the line. timeline: Arc, - /// The roster's closing sentence in place of [`ROSTER_CLOSING`]. - roster_closing: Option>, + /// The factory configuration of the texts this part writes: the roster's + /// closing sentence and the status notes' guidance blocks. + config: BranchToolConfig, view: Mutex, wanted: Mutex>, changed: tokio::sync::Notify, @@ -4616,7 +4617,10 @@ impl BranchLine { &[("branch", &self.own)], &format!( "Lines you opened that are still open. Each is you, working in parallel from the point you opened it; it can read your work after that point, and you can read its.\n{listed}\n{}", - self.roster_closing.as_deref().unwrap_or(ROSTER_CLOSING) + self.config + .roster_closing + .as_deref() + .unwrap_or(ROSTER_CLOSING) ), ), false, @@ -4857,6 +4861,7 @@ impl BranchLine { idle_notice, is_default, other, + &self.config, ))) } /// Records `block` as this line's latest `branch:line` block and answers @@ -5930,8 +5935,8 @@ fn user_line_body(line: &str, parent: &str) -> String { /// The status note a move writes on a conversation line: the line's birth /// identity under the same key, restated byte for byte, then the sentences the -/// move changes (design §5, §12.1). A line the user opened and a tool line get -/// their own rule. The policy sentences come later; these are the protocol's. +/// move changes and the guidance block a candidate replaces (design §5, +/// §12.1). A line the user opened and a tool line get their own rule. fn status_note( line: &str, parent: &str, @@ -5940,26 +5945,55 @@ fn status_note( idle_notice: IdleNotice, default: bool, other: &str, + config: &BranchToolConfig, ) -> String { let (kind, birth) = match source { BranchSource::Tool { .. } => ("tool", tool_line_body(line, parent, purpose)), _ => ("user", user_line_body(line, parent)), }; - let change = if default { + let (change, block) = if default { match kind { - "tool" => format!( - "This line is now the session's default branch, switched from line {other}. While this block is your latest one: answer the user here; you can open lines with create; you send no automatic idle notice to {parent}; you cannot call end on yourself. Line {other} stays open and keeps the lines it opened." + "tool" => ( + format!( + "This line is now the session's default branch, switched from line {other}. While this block is your latest one: answer the user here; you can open lines with create; you send no automatic idle notice to {parent}; you cannot call end on yourself. Line {other} stays open and keeps the lines it opened." + ), + config.default_note.as_deref().unwrap_or(DEFAULT_NOTE), ), - _ => format!( - "The user has now made this line the session's default branch, switched from line {other}. While this block is your latest one: answer the user here; you can open lines with create; you cannot call end on yourself; the user ends this line. Line {other} stays open and keeps the lines it opened." + _ => ( + format!( + "The user has now made this line the session's default branch, switched from line {other}. While this block is your latest one: answer the user here; you can open lines with create; you cannot call end on yourself; the user ends this line. Line {other} stays open and keeps the lines it opened." + ), + config + .user_default_note + .as_deref() + .unwrap_or(USER_DEFAULT_NOTE), ), } + } else if kind == "tool" { + ( + format!( + "The session's default branch moved from this line to line {other}. This line stays open, reports to {parent} as before and keeps coordinating the lines it opened; it can no longer open lines with create, and the rest of the rules above hold again. {CANNOT_END_TEXT} If end is refused when your purpose is done, message {parent} with what you found, did, changed and left undone and keep working." + ), + config + .former_default_note + .as_deref() + .unwrap_or(FORMER_DEFAULT_NOTE), + ) } else { - format!( - "Line {other} is now the session's default branch. This line stays open, reports to {parent} as before and keeps coordinating the lines it opened; it can no longer open lines with create, and the rest of the rules above hold again." + ( + format!( + "The session's default branch moved from this line to line {other}. This line stays open and keeps coordinating the lines it opened; it can no longer open lines with create, and the rest of the rules above hold again. {CANNOT_END_TEXT}" + ), + config + .former_default_note + .as_deref() + .unwrap_or(FORMER_DEFAULT_NOTE), ) }; - let body = format!("{birth}\n\n{change}"); + let body = format!( + "{birth}\n\n{change}\n\nHow you work here:\n{}", + block.replace("{parent}", parent).replace("{other}", other) + ); let mut attrs = vec![ ("branch", line), ("parent", parent), @@ -5984,9 +6018,26 @@ const CANNOT_END_TEXT: &str = "Only a line opened with create can end itself, an const LIMIT_REACHED_TEXT: &str = "This Session holds its limit of open lines. Continue on this line, or end one of its open lines first."; /// The `branch` tool's description: its policy sentences are the coordination -/// text for `main` ([timeline branches §12.4](../../../docs/design/timeline-branches.md#124-texts-and-their-classes)), -/// replaceable at [`BranchToolConfig`]. -const BRANCH_TOOL_DESCRIPTION: &str = "Work with the other lines of this session. A line is you: it starts from your history at the point it is opened, then works in parallel on its own line. It is not a helper with its own memory, and it owes you no result; you and it keep each other informed by reading each other's work and messaging what the other must act on. On main you coordinate: answer a line's steer and act on what it asks for; leave a line's part to that line instead of redoing it; read a line's work instead of waiting for a report.\n- create (the root and the current default branch only): open a line to work on prompt in parallel. Open one line per part that can go on at the same time as the rest — separate files, a separate question, or a second approach — instead of doing those parts one after another yourself; not for a single quick edit, nor when your next step needs its result. Write prompt as a brief to yourself: the purpose, what you already know that it needs, which files or area are its own, and when it should tell you or end. Returns the line's id.\n- message: send content to a line you opened, or to the line that opened you. Send a decision, a blocker, or a conflict, not a progress report the receiver can read. Mode \"append\" (default) reaches the receiver at its next step without interrupting it and does not wake an idle line. Use \"steer\" when the receiver must act now or is idle.\n- read: show a page of the activity of the line you were cut from, or of a line you opened, also after it ended. With no after, a read continues after your last read of that line: from your cut for the line you were cut from, and from its first event for a line you opened. Pass after to read from another point. Do not page through a whole line.\n- end: on a line opened with create, end your own line. content is your final message to the line that opened you: what you found, did, changed and left undone. It is your last action.\nA line messages and reads the line it was cut from and the lines it opened. The end action ends the calling line only."; +/// text for a line that opens lines ([timeline branches §12.4](../../../docs/design/timeline-branches.md#124-texts-and-their-classes)), +/// replaceable at [`BranchToolConfig::description`]. +const BRANCH_TOOL_DESCRIPTION: &str = "Work with the other lines of this session. A line is you: it starts from your history at the point it is opened, then works in parallel on its own line. It is not a helper with its own memory, and it owes you no result; you and it keep each other informed by reading each other's work and messaging what the other must act on. On a line that opens lines you coordinate: answer a line's steer and act on what it asks for; leave a line's part to that line instead of redoing it; read a line's work instead of waiting for a report.\n- create (the root and the current default branch only): open a line to work on prompt in parallel. Open a line only when all four of these hold: the work needs this conversation's context, or its approach is worth the user seeing and taking over; after opening it you have other work to do here right away rather than waiting for it; the part you hand over is multi-step work, not two or three quick actions; and the two lines will not write the same files at the same time. When the user asks for a line, open it. These are not line-shaped: a long command runs in the background instead of taking a line; work that needs none of this conversation's context, or needs different instructions, belongs to another member; one task pursued to completion stays here, or uses a goal; waiting for something outside the session uses an event subscription. Write prompt as a brief to yourself: the purpose in one line, what you decided in this response that the line needs, which files or area are its own (or that it is read-only), and when it should tell you or end. Returns the line's id.\n- message: send content to a line you opened, or to the line that opened you. Send a decision, a blocker, or a conflict, not a progress report the receiver can read. Mode \"append\" (default) reaches the receiver at its next step without interrupting it and does not wake an idle line. Use \"steer\" when the receiver must act now or is idle.\n- read: show a page of the activity of the line you were cut from, or of a line you opened, also after it ended. With no after, a read continues after your last read of that line: from your cut for the line you were cut from, and from its first event for a line you opened. Pass after to read from another point. Do not page through a whole line.\n- end: on a line opened with create, end your own line. content is your final message to the line that opened you: what you found, did, changed and left undone. It is your last action.\nA line messages and reads the line it was cut from and the lines it opened. The end action ends the calling line and every line below it."; + +/// The `How you work here:` bullets of the note a move writes on a tool line +/// that becomes the default branch, after the note's protocol sentences +/// ([timeline branches §12.1](../../../docs/design/timeline-branches.md#121-context-mapping)), +/// replaceable at [`BranchToolConfig::default_note`]. `{parent}` and `{other}` +/// stand for the line ids the note names. +const DEFAULT_NOTE: &str = "- The user switched here to continue directly from this line's context and approach, so the user's request takes precedence over the purpose above, which still says what this line is for.\n- Carry this line's main work forward yourself; open a new line only when the four conditions for opening one hold again, not to hand off your current task.\n- When your purpose is done, or cannot be done, message {parent} with what you found, did, changed and left undone and keep working: while this line is the default branch you cannot call end on yourself.\n- You share the workspace with {parent} and its other lines. Avoid redoing work assigned to lines opened before your cut. If edit or write fails because the file was modified after it was last read, another line may have changed that file: read it again before editing."; + +/// The `How you work here:` bullets of the note a move writes on a line the +/// user opened that becomes the default branch (design §12.1), replaceable at +/// [`BranchToolConfig::user_default_note`]. +const USER_DEFAULT_NOTE: &str = "- Carry this line's work forward yourself; open a new line only when the four conditions for opening one hold again. The user's request takes precedence over the prompt this line was opened with.\n- Line {other} stays open in the shared workspace and keeps coordinating any lines it already opened. If edit or write fails because the file was modified after it was last read, another line may have changed that file: read it again before editing."; + +/// The `How you work here:` bullets of the note a move writes on the former +/// default branch, either source (design §12.1), replaceable at +/// [`BranchToolConfig::former_default_note`]. +const FORMER_DEFAULT_NOTE: &str = "- Keep coordinating any open lines you already opened, and answer messages or user inputs addressed to this line.\n- You share the workspace with the other open lines; do not edit files outside your remaining scope unless asked, and if edit or write fails because the file was modified after it was last read, read the file again before continuing."; /// Factory configuration of the branch tool ([timeline branches §12.4](../../../docs/design/timeline-branches.md#124-texts-and-their-classes)). /// The product sets none of it, so the built-in text is in force. @@ -6000,6 +6051,18 @@ pub struct BranchToolConfig { /// BranchLine, the part that writes the roster /// ([timeline branches §12.4](../../../docs/design/timeline-branches.md#124-texts-and-their-classes)). pub roster_closing: Option>, + /// The `How you work here:` bullets in place of [`DEFAULT_NOTE`], the + /// guidance of the note a move writes on a tool line it makes the default + /// branch ([timeline branches §12.4](../../../docs/design/timeline-branches.md#124-texts-and-their-classes)). + pub default_note: Option>, + /// The `How you work here:` bullets in place of [`USER_DEFAULT_NOTE`], the + /// guidance of the note a move writes on a line the user opened that it + /// makes the default branch (design §12.4). + pub user_default_note: Option>, + /// The `How you work here:` bullets in place of [`FORMER_DEFAULT_NOTE`], + /// the guidance of the note a move writes on the former default branch of + /// either source (design §12.4). + pub former_default_note: Option>, /// The Session's cap on open tool lines in place of the built-in four /// ([timeline branches §6.1](../../../docs/design/timeline-branches.md#61-resources-and-limits)). pub max_open_lines: Option, diff --git a/crates/dim-agent-capabilities/tests/branch_flow.rs b/crates/dim-agent-capabilities/tests/branch_flow.rs index a11477a391..87d1fd1150 100644 --- a/crates/dim-agent-capabilities/tests/branch_flow.rs +++ b/crates/dim-agent-capabilities/tests/branch_flow.rs @@ -4523,6 +4523,46 @@ async fn a_configured_roster_closing_reaches_the_roster() { soon(agent.close()).await.unwrap(); } +/// A note's `How you work here:` block is the factory member +/// `BranchToolConfig::default_note`: a configured value reaches the note byte +/// for byte in place of the built-in bullets, with the line ids its `{parent}` +/// and `{other}` placeholders name, while the note's protocol sentences stay +/// the code's (design §12.1, §12.4). +#[tokio::test(flavor = "multi_thread", worker_threads = 2)] +async fn a_configured_note_block_reaches_the_note() { + let block = "- Configured guidance for {parent}, switched from {other}."; + let probe = Arc::new(Probe::default()); + let agent = MinimalHost::start(&builder_with_branch_config( + &probe, + BranchToolConfig { + default_note: Some(block.into()), + ..Default::default() + }, + )) + .await + .unwrap(); + let session = soon(agent.create_session(SessionConfig::default())) + .await + .unwrap(); + let line = open_line(&session, "the configured line").await; + switch(&session, &line).await; + let notes = owed_notes(&session, &line, 1).await; + let note = notes.last().expect("the line holds its note"); + assert!( + note.contains("How you work here:\n- Configured guidance for main, switched from main."), + "{note}" + ); + assert!( + !note.contains("- The user switched here to continue directly"), + "the built-in bullets are replaced: {note}" + ); + assert!( + note.contains("you send no automatic idle notice to main"), + "the note's protocol sentences stay: {note}" + ); + soon(agent.close()).await.unwrap(); +} + /// #549: a description set at the declaring owner's factory configuration /// reaches the model request byte for byte, carried through ToolRegistry and /// ToolBinding by the shipped assembly. @@ -4834,7 +4874,7 @@ async fn the_branch_tool_declares_its_actions_and_modes() { "- end: on a line opened with create, end your own line.", "Returns the line's id.", "It is your last action.", - "A line messages and reads the line it was cut from and the lines it opened. The end action ends the calling line only.", + "A line messages and reads the line it was cut from and the lines it opened. The end action ends the calling line and every line below it.", ] { assert!( branch.description.contains(sentence), @@ -9551,6 +9591,10 @@ async fn a_default_branch_that_was_a_tool_line_stops_sending_its_idle_notice() { soon(agent.close()).await.unwrap(); } +/// A note a move writes survives the line's next compaction: the tool line the +/// move makes the default branch, the tool line it displaced, a line the user +/// opened, and the root, which gets no note and so keeps no block with a +/// parent (design §5, §12.1). #[tokio::test(flavor = "multi_thread", worker_threads = 2)] async fn a_switched_line_keeps_its_identity_after_a_compaction() { let mut builder = AgentBuilder::new(AgentConfig::default()); @@ -9574,19 +9618,13 @@ async fn a_switched_line_keeps_its_identity_after_a_compaction() { let session = soon(agent.create_session(SessionConfig::default())) .await .unwrap(); + + // The tool line the first move makes the default branch, and the tool line + // the next move displaces it with. let line = open_line(&session, "the parser race").await; - soon(session.set_default_branch( - &line, - BranchSource::User { - operation_id: "switch".into(), - }, - )) - .await - .unwrap(); - for text in ["x".repeat(1500), "y".repeat(1500)] { - session.submit(text, InputMode::Queue, &line).await.unwrap(); - patient(session.idle(&line)).await.unwrap(); - } + let other = open_line(&session, "the renderer race").await; + switch(&session, &line).await; + compact_line(&session, &line).await; let note = line_block(&chain_events(&session, &line, ..).await.unwrap()) .expect("the note is the latest block of the key"); assert!( @@ -9608,6 +9646,99 @@ async fn a_switched_line_keeps_its_identity_after_a_compaction() { note.0 ); assert!(!note.1, "the note is live"); + + // The tool line the next move displaces. + switch(&session, &other).await; + owed_notes(&session, &line, 2).await; + compact_line(&session, &line).await; + let note = line_block(&chain_events(&session, &line, ..).await.unwrap()) + .expect("the former default branch keeps the note"); + assert!( + note.0.starts_with(&format!( + "" + )), + "{}", + note.0 + ); + assert!( + note.0.contains("Your purpose, as main wrote it:"), + "{}", + note.0 + ); + assert!(note.0.contains("the parser race"), "{}", note.0); + assert!( + note.0 + .contains(&format!("moved from this line to line {other}")), + "the note names the line that holds the role: {}", + note.0 + ); + assert!( + note.0.contains( + "Only a line opened with create can end itself, and not while it or a line below it is the default branch." + ), + "the note's own end rule: {}", + note.0 + ); + assert!(!note.1, "the note is live"); + + // A line the user opened, which the move makes the default branch. + let cut = session.sequence("main").unwrap(); + let opened = soon(session.branch( + "main".into(), + cut, + BranchOptions { + prompt: "the user line".into(), + source: BranchSource::User { + operation_id: "client".into(), + }, + }, + )) + .await + .unwrap(); + soon(session.idle(&opened)).await.unwrap(); + switch(&session, &opened).await; + owed_notes(&session, &opened, 1).await; + compact_line(&session, &opened).await; + let note = line_block(&chain_events(&session, &opened, ..).await.unwrap()) + .expect("the user line keeps the note"); + assert!( + note.0.starts_with(&format!( + "" + )), + "{}", + note.0 + ); + assert!( + note.0.contains("opened by the user from line main"), + "{}", + note.0 + ); + assert!( + note.0.contains("the user ends this line"), + "the note's own end rule: {}", + note.0 + ); + assert!(!note.0.contains("Your purpose, as"), "{}", note.0); + assert!(!note.1, "the note is live"); + + // The root: a move back to it writes no note, so its compaction replays no + // identity block and the note it would carry names no parent. + switch(&session, "main").await; + compact_line(&session, "main").await; + let events = chain_events(&session, "main", ..).await.unwrap(); + assert!( + baseline_message(&events, "branch:roster").is_some(), + "the root compacted and replayed its roster" + ); + assert!( + baseline_message(&events, "branch:line").is_none(), + "the root gets no note: its identity key stays empty" + ); + assert!( + line_block(&events).is_none(), + "the root holds no `branch:line` block" + ); + assert_eq!(session.default_branch().unwrap(), "main"); soon(agent.close()).await.unwrap(); } @@ -11058,7 +11189,9 @@ async fn a_clean_restart_writes_no_status_note() { .pop() .expect("B holds its notes"); assert!( - latest.contains(&format!("Line {c} is now the session's default branch")), + latest.contains(&format!( + "The session's default branch moved from this line to line {c}" + )), "B's latest note names C before the restart: {latest}" ); let id = session.id().to_owned(); @@ -11082,7 +11215,9 @@ async fn a_clean_restart_writes_no_status_note() { .pop() .expect("B holds its notes"); assert!( - latest.contains(&format!("Line {c} is now the session's default branch")), + latest.contains(&format!( + "The session's default branch moved from this line to line {c}" + )), "B's latest note still names C: {latest}" ); assert_eq!( @@ -11533,7 +11668,7 @@ async fn a_move_that_stopped_between_its_fact_and_its_notes_is_completed_at_load ( b.clone(), r#"default="false""#.to_owned(), - format!("Line {c} is now the session's default branch"), + format!("The session's default branch moved from this line to line {c}"), ), ( c.clone(), @@ -11829,7 +11964,9 @@ async fn a_move_committed_before_its_writer_starts_still_owes_its_note() { assert!(notes[0].contains("switched from line main"), "{}", notes[0]); assert!(notes[1].contains(r#"default="false""#), "{}", notes[1]); assert!( - notes[1].contains(&format!("Line {c} is now the session's default branch")), + notes[1].contains(&format!( + "The session's default branch moved from this line to line {c}" + )), "{}", notes[1] ); @@ -11848,7 +11985,9 @@ async fn a_move_committed_before_its_writer_starts_still_owes_its_note() { ); assert!(at_c[1].contains(r#"default="false""#), "{}", at_c[1]); assert!( - at_c[1].contains(&format!("Line {b} is now the session's default branch")), + at_c[1].contains(&format!( + "The session's default branch moved from this line to line {b}" + )), "{}", at_c[1] ); diff --git a/docs/architecture/rust-agent/plugins/BranchTool.md b/docs/architecture/rust-agent/plugins/BranchTool.md index 2dcb10a676..747360675d 100644 --- a/docs/architecture/rust-agent/plugins/BranchTool.md +++ b/docs/architecture/rust-agent/plugins/BranchTool.md @@ -18,8 +18,8 @@ eligibility and the cap in the lock that reserves the new line, so a switch or a 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 nothing else, 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 +`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. diff --git a/xtask/src/app_server.rs b/xtask/src/app_server.rs index 9f86787b54..d306d15376 100644 --- a/xtask/src/app_server.rs +++ b/xtask/src/app_server.rs @@ -48,6 +48,16 @@ pub struct Overrides { /// The roster's closing sentence in place of its built-in text /// (timeline branches §12.4). pub roster_closing: Option>, + /// The `How you work here:` bullets of the note a move writes on a tool + /// line it makes the default branch, in place of its built-in text + /// (timeline branches §12.4). + pub default_note: Option>, + /// The same bullets on a line the user opened that becomes the default + /// branch (timeline branches §12.4). + pub user_default_note: Option>, + /// The same bullets on the former default branch of either source + /// (timeline branches §12.4). + pub former_default_note: Option>, /// Goal's objective policy sentence in place of the shipped one /// (model-prompts §8.1). pub goal_objective: Option>, @@ -234,6 +244,9 @@ pub async fn serve_home( dim_agent_capabilities::timeline_tree::BranchToolConfig { description: run.overrides.branch_description.clone(), roster_closing: run.overrides.roster_closing.clone(), + default_note: run.overrides.default_note.clone(), + user_default_note: run.overrides.user_default_note.clone(), + former_default_note: run.overrides.former_default_note.clone(), max_open_lines: None, }, PromptSourcesConfig { diff --git a/xtask/src/scenario_eval.rs b/xtask/src/scenario_eval.rs index 5d7c494fd9..308edc8a9a 100644 --- a/xtask/src/scenario_eval.rs +++ b/xtask/src/scenario_eval.rs @@ -604,10 +604,22 @@ const TEXTS: &[(&str, TextMember)] = &[ "timeline-tree/branch-description", TextMember::Rust(|overrides, text| overrides.branch_description = Some(text)), ), + ( + "timeline-tree/default-note", + TextMember::Rust(|overrides, text| overrides.default_note = Some(text)), + ), + ( + "timeline-tree/former-default-note", + TextMember::Rust(|overrides, text| overrides.former_default_note = Some(text)), + ), ( "timeline-tree/roster-closing", TextMember::Rust(|overrides, text| overrides.roster_closing = Some(text)), ), + ( + "timeline-tree/user-default-note", + TextMember::Rust(|overrides, text| overrides.user_default_note = Some(text)), + ), ( "goal/objective", TextMember::Rust(|overrides, text| overrides.goal_objective = Some(text)), @@ -2880,6 +2892,9 @@ fn overrides_value(overrides: &Overrides) -> Value { plugin_configs, branch_description, roster_closing, + default_note, + user_default_note, + former_default_note, goal_objective, goal_continuation, eventhub_entry, @@ -2894,6 +2909,9 @@ fn overrides_value(overrides: &Overrides) -> Value { "pluginConfigs": plugin_configs, "branchDescription": branch_description.as_ref().map(ToString::to_string), "rosterClosing": roster_closing.as_ref().map(ToString::to_string), + "defaultNote": default_note.as_ref().map(ToString::to_string), + "userDefaultNote": user_default_note.as_ref().map(ToString::to_string), + "formerDefaultNote": former_default_note.as_ref().map(ToString::to_string), "goalObjective": goal_objective.as_ref().map(ToString::to_string), "goalContinuation": goal_continuation.as_ref().map(ToString::to_string), "schedulerDescription": scheduler_description.as_ref().map(ToString::to_string), @@ -2918,6 +2936,9 @@ fn child_overrides(value: &Value) -> Overrides { .unwrap_or_default(), branch_description: text("branchDescription"), roster_closing: text("rosterClosing"), + default_note: text("defaultNote"), + user_default_note: text("userDefaultNote"), + former_default_note: text("formerDefaultNote"), goal_objective: text("goalObjective"), goal_continuation: text("goalContinuation"), scheduler_description: text("schedulerDescription"), @@ -8084,6 +8105,61 @@ mod tests { assert!(overrides.branch_description.is_none()); } + /// Each status note's `How you work here:` block is injected through its + /// own factory member (timeline branches §12.4, model-prompts §8.1): + /// `--text timeline-tree/default-note`, `user-default-note` and + /// `former-default-note` land on the `Overrides` fields + /// [`app_server::serve_home`] hands `BranchToolConfig`, never on a product + /// string patched for the evaluation, and the serve child carries them. + #[test] + fn the_status_note_blocks_are_factory_members() { + let overrides = overrides_in( + TEXTS, + &[ + ( + "timeline-tree/default-note".to_owned(), + Arc::from("candidate default note"), + ), + ( + "timeline-tree/user-default-note".to_owned(), + Arc::from("candidate user note"), + ), + ( + "timeline-tree/former-default-note".to_owned(), + Arc::from("candidate former note"), + ), + ], + ) + .unwrap(); + assert_eq!( + overrides.default_note.as_deref(), + Some("candidate default note") + ); + assert_eq!( + overrides.user_default_note.as_deref(), + Some("candidate user note") + ); + assert_eq!( + overrides.former_default_note.as_deref(), + Some("candidate former note") + ); + assert!(overrides.branch_description.is_none()); + assert!(overrides.roster_closing.is_none()); + let carried = child_overrides(&overrides_value(&overrides)); + assert_eq!( + carried.default_note.as_deref(), + Some("candidate default note") + ); + assert_eq!( + carried.user_default_note.as_deref(), + Some("candidate user note") + ); + assert_eq!( + carried.former_default_note.as_deref(), + Some("candidate former note") + ); + } + /// The base prompt is injected through PromptSources' own factory member /// (model-prompts §8.2, PromptSources §2): `--text prompt-sources/base` /// lands on the `Overrides` field [`app_server::serve_home`] hands From e515a895e07bd36138db8f8004d80d2a3a3a6a3b Mon Sep 17 00:00:00 2001 From: huihui Date: Sun, 22 Nov 2026 18:55:31 +0800 Subject: [PATCH 04/35] test(branch): cut the user line from an idle root The compaction identity test opens a line the user makes the default branch at the root's head. That head can sit inside a model output the root is still writing, and the open is refused for it; the cut now waits for the root to be idle, as the other user-opened flows do. --- crates/dim-agent-capabilities/tests/branch_flow.rs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/crates/dim-agent-capabilities/tests/branch_flow.rs b/crates/dim-agent-capabilities/tests/branch_flow.rs index 87d1fd1150..d3b8f40ae0 100644 --- a/crates/dim-agent-capabilities/tests/branch_flow.rs +++ b/crates/dim-agent-capabilities/tests/branch_flow.rs @@ -9682,7 +9682,7 @@ async fn a_switched_line_keeps_its_identity_after_a_compaction() { assert!(!note.1, "the note is live"); // A line the user opened, which the move makes the default branch. - let cut = session.sequence("main").unwrap(); + let cut = idle_cut(&session, "main").await; let opened = soon(session.branch( "main".into(), cut, From c6bbe55cf81e54abf9dc53b2fd75c64ae3930740 Mon Sep 17 00:00:00 2001 From: huihui Date: Sun, 22 Nov 2026 19:12:00 +0800 Subject: [PATCH 05/35] test(app-server): widen the export fixture's window The timeline export flow compacts a Session whose model declares 4,400 tokens. The branch tool's longer description raises the request frame, and the compaction's resident parts no longer fit half of that budget, so the manual compact answers `nothing_to_compact` instead of `completed`. The window moves to 6,000, which keeps the flow's small model and its completed compaction. --- crates/dim-app-server/tests/transport_flow/timeline_export.rs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/crates/dim-app-server/tests/transport_flow/timeline_export.rs b/crates/dim-app-server/tests/transport_flow/timeline_export.rs index 798be8abbd..6a87a9e124 100644 --- a/crates/dim-app-server/tests/transport_flow/timeline_export.rs +++ b/crates/dim-app-server/tests/transport_flow/timeline_export.rs @@ -359,7 +359,7 @@ async fn timeline_export_reads_a_live_product_home_and_its_copies() { let (mut daemon, socket) = launch_product(&directory).await; let mut client = connect(&socket).await; - let capabilities = dim_agent_types::CatalogCapabilities::with_limits(4_400, 200); + let capabilities = dim_agent_types::CatalogCapabilities::with_limits(6_000, 200); assert_ok(&client.rpc("provider.create", json!({"providerId":"018ec73f-0000-7000-8000-000000000004","displayName":"Window","connection":{"driverKind":"openai-compatible","baseUrl":format!("http://{endpoint}/v1"),"auth":{"type":"bearer"},"credential":{"action":"set","value":CREDENTIAL}},"models":[{"modelId":"small","displayName":"small","status":"active","capabilities":capabilities}],"enabled":true})).await); assert_ok( &client From cad5cf99af80a0df24104b59326f86900c97815c Mon Sep 17 00:00:00 2001 From: huihui Date: Sun, 22 Nov 2026 19:33:17 +0800 Subject: [PATCH 06/35] refactor(branch): write a status note from its line The note builder took the line id and the factory configuration as two more arguments than clippy allows. It is now a method on BranchLine, which holds both, so the call names only what the move decides. --- .../src/timeline_tree.rs | 149 +++++++++--------- 1 file changed, 73 insertions(+), 76 deletions(-) diff --git a/crates/dim-agent-capabilities/src/timeline_tree.rs b/crates/dim-agent-capabilities/src/timeline_tree.rs index fa1fcd9e95..9d9e624108 100644 --- a/crates/dim-agent-capabilities/src/timeline_tree.rs +++ b/crates/dim-agent-capabilities/src/timeline_tree.rs @@ -4853,17 +4853,87 @@ impl BranchLine { _ => String::new(), }; let idle_notice = self.view.lock().unwrap().idle_notice; - Ok(Some(status_note( - &self.own, + Ok(Some(self.status_note( parent, &source, &purpose, idle_notice, is_default, other, - &self.config, ))) } + /// The status note a move writes on this line: the line's birth identity + /// under the same key, restated byte for byte, then the sentences the move + /// changes and the guidance block a candidate replaces (design §5, + /// §12.1). A line the user opened and a tool line get their own rule. + fn status_note( + &self, + parent: &str, + source: &BranchSource, + purpose: &str, + idle_notice: IdleNotice, + default: bool, + other: &str, + ) -> String { + let line = self.own.as_str(); + let (kind, birth) = match source { + BranchSource::Tool { .. } => ("tool", tool_line_body(line, parent, purpose)), + _ => ("user", user_line_body(line, parent)), + }; + let (change, block) = if default { + match kind { + "tool" => ( + format!( + "This line is now the session's default branch, switched from line {other}. While this block is your latest one: answer the user here; you can open lines with create; you send no automatic idle notice to {parent}; you cannot call end on yourself. Line {other} stays open and keeps the lines it opened." + ), + self.config.default_note.as_deref().unwrap_or(DEFAULT_NOTE), + ), + _ => ( + format!( + "The user has now made this line the session's default branch, switched from line {other}. While this block is your latest one: answer the user here; you can open lines with create; you cannot call end on yourself; the user ends this line. Line {other} stays open and keeps the lines it opened." + ), + self.config + .user_default_note + .as_deref() + .unwrap_or(USER_DEFAULT_NOTE), + ), + } + } else if kind == "tool" { + ( + format!( + "The session's default branch moved from this line to line {other}. This line stays open, reports to {parent} as before and keeps coordinating the lines it opened; it can no longer open lines with create, and the rest of the rules above hold again. {CANNOT_END_TEXT} If end is refused when your purpose is done, message {parent} with what you found, did, changed and left undone and keep working." + ), + self.config + .former_default_note + .as_deref() + .unwrap_or(FORMER_DEFAULT_NOTE), + ) + } else { + ( + format!( + "The session's default branch moved from this line to line {other}. This line stays open and keeps coordinating the lines it opened; it can no longer open lines with create, and the rest of the rules above hold again. {CANNOT_END_TEXT}" + ), + self.config + .former_default_note + .as_deref() + .unwrap_or(FORMER_DEFAULT_NOTE), + ) + }; + let body = format!( + "{birth}\n\n{change}\n\nHow you work here:\n{}", + block.replace("{parent}", parent).replace("{other}", other) + ); + let mut attrs = vec![ + ("branch", line), + ("parent", parent), + ("source", kind), + ("default", if default { "true" } else { "false" }), + ]; + if idle_notice == IdleNotice::None { + attrs.push((QUIET_IDLE_ATTRIBUTE, "none")); + } + crate::context_block::element("dim-branch-line", &attrs, &body) + } /// Records `block` as this line's latest `branch:line` block and answers /// the role it states, where a missing `default` attribute means not /// default (design §5). @@ -5933,79 +6003,6 @@ fn user_line_body(line: &str, parent: &str) -> String { ) } -/// The status note a move writes on a conversation line: the line's birth -/// identity under the same key, restated byte for byte, then the sentences the -/// move changes and the guidance block a candidate replaces (design §5, -/// §12.1). A line the user opened and a tool line get their own rule. -fn status_note( - line: &str, - parent: &str, - source: &BranchSource, - purpose: &str, - idle_notice: IdleNotice, - default: bool, - other: &str, - config: &BranchToolConfig, -) -> String { - let (kind, birth) = match source { - BranchSource::Tool { .. } => ("tool", tool_line_body(line, parent, purpose)), - _ => ("user", user_line_body(line, parent)), - }; - let (change, block) = if default { - match kind { - "tool" => ( - format!( - "This line is now the session's default branch, switched from line {other}. While this block is your latest one: answer the user here; you can open lines with create; you send no automatic idle notice to {parent}; you cannot call end on yourself. Line {other} stays open and keeps the lines it opened." - ), - config.default_note.as_deref().unwrap_or(DEFAULT_NOTE), - ), - _ => ( - format!( - "The user has now made this line the session's default branch, switched from line {other}. While this block is your latest one: answer the user here; you can open lines with create; you cannot call end on yourself; the user ends this line. Line {other} stays open and keeps the lines it opened." - ), - config - .user_default_note - .as_deref() - .unwrap_or(USER_DEFAULT_NOTE), - ), - } - } else if kind == "tool" { - ( - format!( - "The session's default branch moved from this line to line {other}. This line stays open, reports to {parent} as before and keeps coordinating the lines it opened; it can no longer open lines with create, and the rest of the rules above hold again. {CANNOT_END_TEXT} If end is refused when your purpose is done, message {parent} with what you found, did, changed and left undone and keep working." - ), - config - .former_default_note - .as_deref() - .unwrap_or(FORMER_DEFAULT_NOTE), - ) - } else { - ( - format!( - "The session's default branch moved from this line to line {other}. This line stays open and keeps coordinating the lines it opened; it can no longer open lines with create, and the rest of the rules above hold again. {CANNOT_END_TEXT}" - ), - config - .former_default_note - .as_deref() - .unwrap_or(FORMER_DEFAULT_NOTE), - ) - }; - let body = format!( - "{birth}\n\n{change}\n\nHow you work here:\n{}", - block.replace("{parent}", parent).replace("{other}", other) - ); - let mut attrs = vec![ - ("branch", line), - ("parent", parent), - ("source", kind), - ("default", if default { "true" } else { "false" }), - ]; - if idle_notice == IdleNotice::None { - attrs.push((QUIET_IDLE_ATTRIBUTE, "none")); - } - crate::context_block::element("dim-branch-line", &attrs, &body) -} - /// The `branch` tool's refusal of `create` on a line that is neither the root /// nor the default branch (design §4, §11). const NOT_OPENER_TEXT: &str = "Only the root and the default branch open lines. Tell one of them if more parallel work is needed."; From 1cca0a6f8d59cae6ccb69a102de14d882701bce7 Mon Sep 17 00:00:00 2001 From: huihui Date: Sun, 22 Nov 2026 20:46:46 +0800 Subject: [PATCH 07/35] docs(branch): name an opener as the roster closing's reader MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit BranchLine writes the closing sentence on any line that opened lines, not only on the default branch, and §12.4 classes it as the opener's coordination text. --- crates/dim-agent-capabilities/src/timeline_tree.rs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/crates/dim-agent-capabilities/src/timeline_tree.rs b/crates/dim-agent-capabilities/src/timeline_tree.rs index 9d9e624108..ccc9a26b1e 100644 --- a/crates/dim-agent-capabilities/src/timeline_tree.rs +++ b/crates/dim-agent-capabilities/src/timeline_tree.rs @@ -3473,7 +3473,7 @@ const IDENTITY_ENTRY: &str = r#": the lines you opened, under the key `branch:roster` and apart from your own identity under `branch:line`: the runtime lists the tool lines you opened that are still open, each with the first line of its purpose. A later block of this name replaces the earlier one; it is state about the lines, not a request."#; -/// The roster's closing sentence, coordination text for `main` +/// The roster's closing sentence, coordination text for an opener /// ([timeline branches §12.4](../../../docs/design/timeline-branches.md#124-texts-and-their-classes)), /// replaceable at [`BranchToolConfig::roster_closing`]. const ROSTER_CLOSING: &str = "They message you when they find something, need you, or end. Use the branch tool to message or read them, and the `wait` tool to wait for them; end the wait when your lines have nothing left to tell you."; From 67c31b21b91da108545ce914d83901402ca9ad7e Mon Sep 17 00:00:00 2001 From: huihui Date: Mon, 23 Nov 2026 00:49:55 +0800 Subject: [PATCH 08/35] fix(xtask): compare each arm with the text it was given The scenario runner filled its current arm with the assembly's own texts, so an evaluation on a head that already carries the candidate compared the new policy with itself. Every `--text ID` now names `--baseline FILE` beside `--candidate FILE`, and the current arm puts the baseline in place through the same factory overrides the candidate uses. A pair with a file missing, a text named twice, and a pair whose baseline and candidate hold the same bytes are refused before any run starts. Each run's record and the report name the texts its arm emitted by id, byte length and fingerprint, so a saved run and a pooled report state which two texts were compared. --- xtask/src/scenario_eval.rs | 481 +++++++++++++++++++++++++++++++++---- 1 file changed, 430 insertions(+), 51 deletions(-) diff --git a/xtask/src/scenario_eval.rs b/xtask/src/scenario_eval.rs index 1f3adba200..890cfff7a1 100644 --- a/xtask/src/scenario_eval.rs +++ b/xtask/src/scenario_eval.rs @@ -5,18 +5,22 @@ //! //! ```text //! cargo run --locked -p xtask -- scenario-eval --scenarios DIR --text ID -//! --candidate FILE [--text ID --candidate FILE]... --model PROVIDER/MODEL -//! --judge PROVIDER/MODEL --runs N --out DIR [--jobs N] -//! [--model-config FILE] +//! --baseline FILE --candidate FILE [--text ID --baseline FILE +//! --candidate FILE]... --model PROVIDER/MODEL --judge PROVIDER/MODEL +//! --runs N --out DIR [--jobs N] [--model-config FILE] //! ``` //! -//! Both arms run the shipped assembly: `current` with the product's own texts -//! and `candidate` with each candidate file in place of the text its `--text` -//! id names. Every `--text ID --candidate FILE` pair replaces one text, a -//! pair reads in either order, a text named twice is an error, and the report -//! gives each candidate text's own token cost. The runs are interleaved: for -//! each run index and scenario the `current` run is scheduled before the -//! `candidate` one, so a drift in +//! Both arms run the same assembly with each text named by a `--text` id put +//! in place of the assembly's: `current` with the baseline file and +//! `candidate` with the candidate file. A pair names both files, so an +//! evaluation compares two texts it was given and never the candidate with the +//! copy the checkout ships; a pair whose baseline and candidate hold the same +//! bytes is refused, as is one with a file missing. A pair reads in either +//! order, a text named twice is an error, and the report gives each candidate +//! text's own token cost. The report and `runs.jsonl` also record the texts +//! each arm emitted, as each text's id, length and fingerprint. The runs are +//! interleaved: for each run index and scenario the `current` run is scheduled +//! before the `candidate` one, so a drift in //! the endpoint lands on both arms alike, and the records come out in that //! order whatever order the runs complete in. `--jobs N` (default 1) runs N //! runs at once; each run keeps its own workspace copy, Dim home, local @@ -735,7 +739,7 @@ async fn evaluate(options: &Options) -> Result { } } let candidate = overrides(&options.texts)?; - let current = Overrides::default(); + let baseline = overrides(&options.baseline)?; let scenarios = read_scenarios(&options.scenarios)?; // A live evaluation is isolated: the run's server must come from a // model configuration, which also names the credential its calls use. @@ -762,7 +766,7 @@ async fn evaluate(options: &Options) -> Result { .map(|(index, &(arm, scenario, run))| { let mut measured = instrument.clone(); let overrides = match arm { - "current" => ¤t, + "current" => &baseline, _ => &candidate, }; let native = &native; @@ -1035,6 +1039,7 @@ fn pooled_record(source: &Path, run: SavedRun, scenarios: &[Scenario]) -> Result arm: arm_name(&run.arm)?, scenario: run.scenario, run: run.run, + texts: run.texts, session: run.session, stop: stop_name(&run.stop)?, turns: run.turns, @@ -1133,6 +1138,7 @@ async fn rejudge_one( arm: arm_name(&saved.arm)?, scenario: saved.scenario.clone(), run: saved.run, + texts: saved.texts.clone(), session: saved.session.clone(), stop, turns: saved.turns, @@ -1182,6 +1188,10 @@ struct SavedRun { judge_reasks: u32, #[serde(default)] judge_calls: Vec, + /// The texts the arm emitted; empty in a record written before the runner + /// recorded them. + #[serde(default)] + texts: Vec, /// `None` in a record written before the runner wrote this fact. #[serde(default)] temperature_dropped: Option, @@ -1330,6 +1340,10 @@ fn schedule(runs: usize, scenarios: usize) -> Vec<(&'static str, usize, usize)> struct Options { scenarios: PathBuf, + /// The `--text ID --baseline FILE` pairs, in the order given: the text each + /// candidate replaces, put in place of the assembly's in the `current` + /// arm. + baseline: Vec<(String, Arc)>, /// The `--text ID --candidate FILE` pairs, in the order given. texts: Vec<(String, Arc)>, model: ModelId, @@ -1410,10 +1424,12 @@ impl Options { /// absolute, as `session.create` requires of the cwd. fn parse_from(args: impl IntoIterator) -> Result { let usage = "usage: cargo run -p xtask -- scenario-eval --scenarios DIR \ - --text ID --candidate FILE [--text ID --candidate FILE]... \ + --text ID --baseline FILE --candidate FILE [--text ID \ + --baseline FILE --candidate FILE]... \ --model PROVIDER/MODEL --judge PROVIDER/MODEL --runs N \ --out DIR [--jobs N] [--model-config FILE] \ - [--defaults FILE]; a text named twice is an error, and a \ + [--defaults FILE]; every text names the baseline it replaces \ + and its candidate, a text named twice is an error, and a \ run whose view does not fit the judge's own declared \ window is unjudged, so a model configuration narrowed for \ the scenarios declares the judge under its own provider \ @@ -1428,12 +1444,16 @@ impl Options { // names another default configuration file. let mut args = args.into_iter(); let (mut scenarios, mut out) = (None, None); - let (mut text, mut candidate, mut model, mut judge) = (None, None, None, None); + let (mut model, mut judge) = (None, None); let (mut runs, mut jobs, mut model_config, mut defaults) = (None, None, None, None); let mut rejudge = None; let mut select: Vec = Vec::new(); let mut pool: Vec = Vec::new(); + let mut baseline: Vec<(String, Arc)> = Vec::new(); let mut texts: Vec<(String, Arc)> = Vec::new(); + // The pair whose files are being read: each `--text ID` opens one and + // the two roles fill it, in either order. + let mut pending = PendingText::default(); while let Some(flag) = args.next() { let value = args.next().ok_or(format!("{flag} requires a value"))?; match flag.as_str() { @@ -1451,23 +1471,43 @@ impl Options { } "--pool" => pool.push(PathBuf::from(value)), "--text" => { - if let Some(pending) = &text { - return Err(format!("--text {pending} has no --candidate").into()); + if let Some(open) = &pending.id { + return Err( + format!("--text {open} has no --baseline and no --candidate").into(), + ); } - if texts.iter().any(|(given, _)| *given == value) { + if baseline.iter().any(|(given, _)| *given == value) + || texts.iter().any(|(given, _)| *given == value) + { return Err(format!("--text {value} is named twice").into()); } - match candidate.take() { - Some(prompt) => texts.push((value, prompt)), - None => text = Some(value), - } + pending.id = Some(value); } - "--candidate" => { - let prompt = candidate_prompt(Path::new(&value))?; - match text.take() { - Some(id) => texts.push((id, prompt)), - None if candidate.is_none() => candidate = Some(prompt), - None => return Err("--candidate has no --text".into()), + "--baseline" | "--candidate" => { + let is_baseline = flag == "--baseline"; + let filled = if is_baseline { + pending.baseline.is_some() + } else { + pending.candidate.is_some() + }; + if pending.id.is_none() + && (pending.baseline.is_some() || pending.candidate.is_some()) + { + return Err(format!("{flag} has no --text").into()); + } + if filled { + return Err(format!("{flag} is given twice for one --text").into()); + } + let text = candidate_prompt(Path::new(&value))?; + if is_baseline { + pending.baseline = Some(text); + } else { + pending.candidate = Some(text); + } + if pending.baseline.is_some() && pending.candidate.is_some() { + let id = pending.id.take().expect("a filled pair names its text"); + baseline.push((id.clone(), pending.baseline.take().expect("filled"))); + texts.push((id, pending.candidate.take().expect("filled"))); } } "--model" => model = Some(target(&value)?), @@ -1481,11 +1521,35 @@ impl Options { _ => return Err(usage.into()), } } - if let Some(text) = &text { - return Err(format!("--text {text} has no --candidate").into()); + if let Some(open) = pending.id { + let missing = if pending.baseline.is_none() { + "--baseline" + } else { + "--candidate" + }; + return Err(format!("--text {open} has no {missing}").into()); + } + for (role, flag) in [ + (&pending.baseline, "--baseline"), + (&pending.candidate, "--candidate"), + ] { + if role.is_some() { + return Err(format!("{flag} has no --text").into()); + } } - if candidate.is_some() { - return Err("--candidate has no --text".into()); + for (id, candidate) in &texts { + let replaced = &baseline + .iter() + .find(|(given, _)| given == id) + .expect("every pair carries its baseline") + .1; + if replaced == candidate { + return Err(format!( + "--text {id}: the baseline and the candidate are the same text, so the \ + evaluation would compare the text with itself" + ) + .into()); + } } if texts.is_empty() && rejudge.is_none() && pool.is_empty() { return Err(usage.into()); @@ -1511,7 +1575,7 @@ impl Options { if finished && (!texts.is_empty() || runs.is_some() || defaults.is_some()) { return Err( "--rejudge and --pool read finished evaluations' saved runs: --text, \ - --candidate, --runs and --defaults belong to a new evaluation" + --baseline, --candidate, --runs and --defaults belong to a new evaluation" .into(), ); } @@ -1534,6 +1598,7 @@ impl Options { .map_err(|error| format!("--out {}: {error}", out.display()))?; Ok(Self { scenarios, + baseline, texts, model, judge, @@ -1561,6 +1626,30 @@ impl Options { pool, }) } + + /// The texts one arm puts in place of the assembly's, in the order the + /// evaluation was given them: `current` is each pair's baseline and + /// `candidate` its candidate. + fn arm_texts(&self, arm: &str) -> Vec { + let texts = if arm == "current" { + &self.baseline + } else { + &self.texts + }; + texts + .iter() + .map(|(id, text)| EmittedText::of(id, text)) + .collect() + } +} + +/// One `--text ID` pair while its files are read: each `--text ID` opens the +/// pair and `--baseline` and `--candidate` fill it, in either order. +#[derive(Default)] +struct PendingText { + id: Option, + baseline: Option>, + candidate: Option>, } /// A path from the environment: the TypeScript plugin rows run in Node, @@ -2220,6 +2309,10 @@ struct RunRecord { arm: &'static str, scenario: String, run: usize, + /// The texts the arm put in place of the assembly's, in the order the + /// evaluation was given them: each is a text the arm emitted in place of + /// the one its id names. + texts: Vec, session: Option, /// `idle`, `turns`, `seconds`, `switch_target_not_reached`, /// `switch_target_ended`, `switch_target_unknown` or `error`. @@ -2279,6 +2372,38 @@ impl RunRecord { !self.failed && self.judge_outcome == JudgeOutcome::Judged } } + +/// One text an arm emitted: the id naming the text it replaced, the text's +/// length in bytes, and a fingerprint of its bytes, so a report states which +/// text each arm ran without carrying the text itself. +#[derive(Clone, serde::Serialize, serde::Deserialize)] +#[serde(rename_all = "camelCase")] +struct EmittedText { + id: String, + bytes: usize, + fingerprint: String, +} +impl EmittedText { + fn of(id: &str, text: &str) -> Self { + Self { + id: id.to_owned(), + bytes: text.len(), + fingerprint: fingerprint(text), + } + } +} + +/// A text's fingerprint: FNV-1a 64 over its bytes, in lowercase hex. It tells +/// the texts an evaluation compares apart in its records and report; it is not +/// a security digest. +fn fingerprint(text: &str) -> String { + let mut hash: u64 = 0xcbf2_9ce4_8422_2325; + for byte in text.as_bytes() { + hash ^= u64::from(*byte); + hash = hash.wrapping_mul(0x0000_0100_0000_01b3); + } + format!("{hash:016x}") +} #[derive(Clone, serde::Serialize, serde::Deserialize)] #[serde(rename_all = "camelCase")] struct ProbeRecord { @@ -3832,7 +3957,7 @@ async fn run_once( let socket = run_socket(options, arm, scenario, run); private_directory(socket.parent().expect("a socket has a parent"))?; let socket = bindable_socket(&socket)?; - let (record, outcome) = isolate_run( + let (mut record, outcome) = isolate_run( options, arm, overrides, @@ -3847,6 +3972,7 @@ async fn run_once( instrument, ) .await?; + record.texts = options.arm_texts(arm); write_run_outputs(options, arm, scenario, run, &outcome)?; Ok(record) } @@ -4721,6 +4847,7 @@ fn child_record( arm, scenario: scenario.id.clone(), run, + texts: Vec::new(), session: outcome.session.clone(), stop, turns: outcome.turns, @@ -7502,8 +7629,9 @@ fn report(instrument: &Instrument, scenarios: &[Scenario], records: &[RunRecord] ) }); let mut text = String::from("| | |\n| --- | --- |\n"); - // A report built from saved runs names its sources instead: no saved run - // records the texts under test. + // A report built from saved runs names its sources instead: the ids an + // evaluation was given are not saved with a record, and the arm rows below + // state the texts each arm emitted. if instrument.sources.is_none() { let texts: Vec = instrument .texts @@ -7512,6 +7640,29 @@ fn report(instrument: &Instrument, scenarios: &[Scenario], records: &[RunRecord] .collect(); text += &format!("| text | {} |\n", texts.join(", ")); } + // Every run of an arm carries the same texts, so the first one that names + // them states what the arm emitted. + let emitted = |arm: &str| { + records + .iter() + .find(|record| record.arm == arm && !record.texts.is_empty()) + .map(|record| record.texts.as_slice()) + }; + for arm in ["current", "candidate"] { + let Some(texts) = emitted(arm) else { + continue; + }; + let listed: Vec = texts + .iter() + .map(|text| { + format!( + "`{}`: {} bytes, fingerprint {}", + text.id, text.bytes, text.fingerprint + ) + }) + .collect(); + text += &format!("| {arm} texts | {} |\n", listed.join("; ")); + } text += &format!( "| model | `{}/{}`, {} |\n| judge | `{}/{}`, temperature 0, {}{window} |\n| runs | {} per arm and scenario |\n", instrument.model.provider_id, @@ -7760,6 +7911,7 @@ mod tests { arm, scenario: scenario.id.clone(), run: 0, + texts: Vec::new(), session: None, stop: "idle", turns: 1, @@ -8944,12 +9096,16 @@ mod tests { std::fs::create_dir_all(&directory).unwrap(); let candidate = directory.join("candidate.md"); std::fs::write(&candidate, "candidate").unwrap(); + let baseline = directory.join("baseline.md"); + std::fs::write(&baseline, "baseline").unwrap(); let out = directory.join("out"); let args = [ "--scenarios", "scenarios", "--text", "context-compaction/summary", + "--baseline", + baseline.to_str().unwrap(), "--candidate", candidate.to_str().unwrap(), "--model", @@ -9184,16 +9340,22 @@ mod tests { std::fs::create_dir_all(&directory).unwrap(); let candidate = directory.join("candidate.md"); std::fs::write(&candidate, "candidate").unwrap(); + let baseline = directory.join("baseline.md"); + std::fs::write(&baseline, "baseline").unwrap(); let parsed = Options::parse_from( [ "--scenarios", "scenarios", "--text", "goal/objective", + "--baseline", + baseline.to_str().unwrap(), "--candidate", candidate.to_str().unwrap(), "--text", "goal/objective", + "--baseline", + baseline.to_str().unwrap(), "--candidate", candidate.to_str().unwrap(), "--model", @@ -9215,9 +9377,8 @@ mod tests { let _ = std::fs::remove_dir_all(&directory); } - /// A `--text ID --candidate FILE` pair reads in either order: the - /// candidate given first pairs with the text that follows it - /// (model-prompts §8.1). + /// A `--text ID` pair reads in either order: a file given before the text + /// pairs with the text that follows it (model-prompts §8.1). #[test] fn a_pair_reads_in_either_order() { let directory = @@ -9225,17 +9386,16 @@ mod tests { std::fs::create_dir_all(&directory).unwrap(); let candidate = directory.join("candidate.md"); std::fs::write(&candidate, "candidate").unwrap(); + let baseline = directory.join("baseline.md"); + std::fs::write(&baseline, "baseline").unwrap(); let out = directory.join("out"); let file = candidate.to_str().unwrap(); - let parse = |flags: [&str; 4]| { - Options::parse_from( + let base = baseline.to_str().unwrap(); + let parse = |flags: &[&str]| { + let mut args: Vec = ["--scenarios", "scenarios"].map(str::to_owned).to_vec(); + args.extend(flags.iter().map(|value| (*value).to_owned())); + args.extend( [ - "--scenarios", - "scenarios", - flags[0], - flags[1], - flags[2], - flags[3], "--model", "gateway/model", "--judge", @@ -9246,20 +9406,119 @@ mod tests { out.to_str().unwrap(), ] .map(str::to_owned), - ) + ); + Options::parse_from(args) }; for flags in [ - ["--text", "goal/objective", "--candidate", file], - ["--candidate", file, "--text", "goal/objective"], + [ + "--text", + "goal/objective", + "--baseline", + base, + "--candidate", + file, + ], + [ + "--text", + "goal/objective", + "--candidate", + file, + "--baseline", + base, + ], + [ + "--baseline", + base, + "--text", + "goal/objective", + "--candidate", + file, + ], + [ + "--candidate", + file, + "--text", + "goal/objective", + "--baseline", + base, + ], ] { - let options = parse(flags).unwrap_or_else(|error| panic!("{flags:?}: {error}")); + let options = parse(&flags).unwrap_or_else(|error| panic!("{flags:?}: {error}")); assert_eq!(options.texts.len(), 1, "{flags:?}"); + assert_eq!(options.baseline.len(), 1, "{flags:?}"); assert_eq!(options.texts[0].0, "goal/objective", "{flags:?}"); assert_eq!(&*options.texts[0].1, "candidate", "{flags:?}"); + assert_eq!(&*options.baseline[0].1, "baseline", "{flags:?}"); } let _ = std::fs::remove_dir_all(&directory); } + /// A text is compared with the text it replaces, never with the copy the + /// checkout ships: `--text ID` names the baseline beside the candidate, + /// and a pair without one, or one whose baseline is its candidate, is + /// refused before any run (model-prompts §8.1). + #[test] + fn a_pair_without_its_baseline_is_refused() { + let directory = + std::env::temp_dir().join(format!("dim-scenario-eval-baseline-{}", std::process::id())); + let _ = std::fs::remove_dir_all(&directory); + std::fs::create_dir_all(&directory).unwrap(); + let candidate = directory.join("candidate.md"); + std::fs::write(&candidate, "candidate").unwrap(); + let baseline = directory.join("baseline.md"); + std::fs::write(&baseline, "baseline").unwrap(); + let same = directory.join("same.md"); + std::fs::write(&same, "baseline").unwrap(); + let out = directory.join("out"); + let parse = |flags: &[&str]| { + let mut args: Vec = [ + "--scenarios", + "scenarios", + "--model", + "gateway/model", + "--judge", + "gateway/model", + "--runs", + "1", + "--out", + out.to_str().unwrap(), + ] + .map(str::to_owned) + .to_vec(); + args.extend(flags.iter().map(|value| (*value).to_owned())); + Options::parse_from(args) + }; + let error = match parse(&[ + "--text", + "goal/objective", + "--candidate", + candidate.to_str().unwrap(), + ]) { + Err(error) => error.to_string(), + Ok(_) => panic!("a candidate without the baseline it replaces is refused"), + }; + assert!( + error.contains("--text goal/objective has no --baseline"), + "the refusal names the missing text: {error}" + ); + let error = match parse(&[ + "--text", + "goal/objective", + "--baseline", + baseline.to_str().unwrap(), + "--candidate", + same.to_str().unwrap(), + ]) { + Err(error) => error.to_string(), + Ok(_) => panic!("a pair whose baseline is its candidate is refused"), + }; + assert!( + error.contains("the baseline and the candidate are the same text"), + "the refusal says the comparison is the text with itself: {error}" + ); + let _ = std::fs::remove_dir_all(&directory); + } + /// The arms are interleaved: for each run index and scenario the current /// arm is scheduled before the candidate one (model-prompts §8.1). The /// order is fixed before any run starts, so `--jobs` cannot change which @@ -11022,6 +11281,10 @@ mod tests { /// The candidate text every fixture's candidate arm carries. const CANDIDATE: &str = "CANDIDATE SUMMARY PROMPT. Summarize the transcript briefly."; + /// The baseline text every fixture's current arm carries. It opens with + /// the shipped prompt's first words, which the fixture's summarizer + /// answers, and is not the candidate. + const BASELINE: &str = "You summarize a coding session. BASELINE SUMMARY PROMPT."; /// The text the workspace file `notes.txt` holds; a run's request carries /// it only once the `read` tool has returned it. const FILE_TEXT: &str = "The notes file says the read tool carried this line back."; @@ -11256,6 +11519,7 @@ mod tests { fn options(&self, out: PathBuf) -> Options { Options { scenarios: self.scenarios.clone(), + baseline: pairs(&[("context-compaction/summary", BASELINE)]), texts: pairs(&[("context-compaction/summary", CANDIDATE)]), model: self.target(), judge: self.target(), @@ -11541,6 +11805,13 @@ mod tests { // tool's description. const BRANCH: &str = "CANDIDATE BRANCH TOOL DESCRIPTION"; let mut options = fixture.judge_options(fixture.directory.join("out")); + options.baseline = pairs(&[ + ("context-compaction/summary", BASELINE), + ( + "timeline-tree/branch-description", + "BASELINE BRANCH TOOL DESCRIPTION", + ), + ]); options.texts = pairs(&[ ("context-compaction/summary", CANDIDATE), ("timeline-tree/branch-description", BRANCH), @@ -11619,6 +11890,109 @@ mod tests { } } + /// A text's fingerprint is FNV-1a 64 over its bytes, in lowercase hex: the + /// canonical test vectors pin it, so a report's fingerprints stay + /// comparable across runs. + #[test] + fn a_texts_fingerprint_is_fnv1a_64() { + assert_eq!(fingerprint(""), "cbf29ce484222325"); + assert_eq!(fingerprint("a"), "af63dc4c8601ec8c"); + assert_eq!(fingerprint("foobar"), "85944171f73967e8"); + } + + /// Each arm emits the text its pair names, and the run's record and the + /// report state which: the current arm's requests carry the baseline, the + /// candidate arm's the candidate, and each record names both by length and + /// fingerprint. An evaluation on a head that already carries the candidate + /// therefore compares two texts it was given, not the candidate with + /// itself (model-prompts §8.1). + #[tokio::test(flavor = "multi_thread", worker_threads = 4)] + async fn each_arm_emits_and_records_the_text_its_pair_names() { + const BASELINE: &str = "BASELINE BRANCH TOOL DESCRIPTION"; + const CANDIDATE: &str = "CANDIDATE BRANCH TOOL DESCRIPTION"; + let fixture = Fixture::start( + "arm-texts", + judged, + json!({ + "message": "Say hello.", + "budget": {"turns": 2, "seconds": 60, "window": 24000}, + "probes": [{"id": "ran", "kind": "must_show", "text": "the run has a transcript"}] + }), + &[], + ) + .await; + let mut options = fixture.options(fixture.directory.join("out")); + options.baseline = pairs(&[("timeline-tree/branch-description", BASELINE)]); + options.texts = pairs(&[("timeline-tree/branch-description", CANDIDATE)]); + let report = fixture.evaluate(&options).await.unwrap(); + assert!( + report.contains("candidate is inconclusive: no comparison is a regression"), + "{report}" + ); + let records = fixture.records(&options.out); + assert_eq!(records.len(), 2, "one run per arm"); + let emitted = |arm: &str| { + records + .iter() + .find(|record| record["arm"] == arm) + .unwrap_or_else(|| panic!("a {arm} run"))["texts"] + .clone() + }; + for (arm, text) in [("current", BASELINE), ("candidate", CANDIDATE)] { + let texts = emitted(arm); + let texts = texts.as_array().unwrap_or_else(|| panic!("{arm}: {texts}")); + assert_eq!(texts.len(), 1, "{arm}: {texts:?}"); + assert_eq!(texts[0]["id"], "timeline-tree/branch-description", "{arm}"); + assert_eq!(texts[0]["bytes"], text.len(), "{arm}: {texts:?}"); + assert_eq!( + texts[0]["fingerprint"], + fingerprint(text), + "{arm}: the record names the text the arm emitted" + ); + } + assert_ne!( + emitted("current")[0]["fingerprint"], + emitted("candidate")[0]["fingerprint"], + "the arms emitted different texts" + ); + for (arm, text) in [("current", BASELINE), ("candidate", CANDIDATE)] { + assert!( + report.contains(&format!( + "| {arm} texts | `timeline-tree/branch-description`: {} bytes, \ + fingerprint {} |", + text.len(), + fingerprint(text) + )), + "{arm}: the report names the text the arm emitted: {report}" + ); + } + let described = |arm: &str| -> Vec { + fixture + .arm(arm) + .iter() + .filter_map(|request| { + let request: Value = serde_json::from_str(request).ok()?; + request["tools"].as_array()?.iter().find_map(|tool| { + (tool["function"]["name"] == "branch") + .then(|| tool["function"]["description"].as_str().map(str::to_owned)) + .flatten() + }) + }) + .collect() + }; + for (arm, text) in [("current", BASELINE), ("candidate", CANDIDATE)] { + let descriptions = described(arm); + assert!( + !descriptions.is_empty(), + "{arm}: the requests declare the branch tool" + ); + assert!( + descriptions.iter().all(|description| description == text), + "{arm}: the branch tool description is the pair's text: {descriptions:?}" + ); + } + } + /// A run whose export is longer than the judge's window is judged through /// the view, which carries each request's unchanged fields once: the judge /// refuses the raw export and answers the view (issue #635). The raw @@ -11991,6 +12365,8 @@ mod tests { .await; let candidate = fixture.directory.join("candidate.md"); std::fs::write(&candidate, CANDIDATE).unwrap(); + let baseline = fixture.directory.join("baseline.md"); + std::fs::write(&baseline, BASELINE).unwrap(); let out = fixture.directory.join("out"); let relative = relative_to_working_directory(&out); let mut options = Options::parse_from( @@ -11999,6 +12375,8 @@ mod tests { fixture.scenarios.to_str().unwrap(), "--text", "context-compaction/summary", + "--baseline", + baseline.to_str().unwrap(), "--candidate", candidate.to_str().unwrap(), "--model", @@ -14440,6 +14818,7 @@ mod tests { let options = Options { out: out.clone(), scenarios: PathBuf::new(), + baseline: Vec::new(), texts: Vec::new(), model: model(), judge: model(), From e7570297355ca76e59fa8419881d2665893573f8 Mon Sep 17 00:00:00 2001 From: huihui Date: Mon, 23 Nov 2026 01:13:36 +0800 Subject: [PATCH 09/35] fix(xtask): refuse a pool whose runs recorded different texts A pooled report stated the texts of the first record that named any, so a pool of evaluations that were given different texts reported one set for runs that compared several. A pool now refuses an arm whose runs recorded different texts and says that such evaluations are pooled only when they were given the same texts or reported separately. The comment that said a record does not save the ids it was given now says what the report reads instead. `a_pool_refuses_runs_that_recorded_different_texts` asserts that a pool states the texts its runs recorded and that runs of one arm with different texts are refused. --- xtask/src/scenario_eval.rs | 108 ++++++++++++++++++++++++++++++++++--- 1 file changed, 102 insertions(+), 6 deletions(-) diff --git a/xtask/src/scenario_eval.rs b/xtask/src/scenario_eval.rs index 890cfff7a1..d9fe0891f3 100644 --- a/xtask/src/scenario_eval.rs +++ b/xtask/src/scenario_eval.rs @@ -881,6 +881,7 @@ async fn pooled(options: &Options, observe: impl Fn(&mut AgentBuilder)) -> Resul directories.push((source, read.len())); records.extend(read); } + one_texts_per_arm(&records)?; let cancel = CancellationToken::new(); let server = served(options, observe).await?; let resolved = async { @@ -976,6 +977,30 @@ fn read_pooled_runs(source: &Path, scenarios: &[Scenario]) -> Result Result<()> { + for arm in ["current", "candidate"] { + let mut recorded: Option<&[EmittedText]> = None; + for record in records + .iter() + .filter(|record| record.arm == arm && !record.texts.is_empty()) + { + if recorded.is_some_and(|texts| texts != record.texts.as_slice()) { + return Err(format!( + "--pool: the {arm} runs recorded different texts; a report states one set per \ + arm, so pool evaluations that were given the same texts or report them \ + separately" + ) + .into()); + } + recorded.get_or_insert(record.texts.as_slice()); + } + } + Ok(()) +} + /// One pooled run as the report reads it: each probe keeps the kind its /// source recorded, checked against the scenario's, so a probe that changed /// kind since is refused rather than reinterpreted, and a record naming a @@ -2376,7 +2401,7 @@ impl RunRecord { /// One text an arm emitted: the id naming the text it replaced, the text's /// length in bytes, and a fingerprint of its bytes, so a report states which /// text each arm ran without carrying the text itself. -#[derive(Clone, serde::Serialize, serde::Deserialize)] +#[derive(Clone, PartialEq, Eq, serde::Serialize, serde::Deserialize)] #[serde(rename_all = "camelCase")] struct EmittedText { id: String, @@ -7629,9 +7654,9 @@ fn report(instrument: &Instrument, scenarios: &[Scenario], records: &[RunRecord] ) }); let mut text = String::from("| | |\n| --- | --- |\n"); - // A report built from saved runs names its sources instead: the ids an - // evaluation was given are not saved with a record, and the arm rows below - // state the texts each arm emitted. + // A report built from saved runs names its sources instead: a pool or a + // re-judge is given no --text, and the arm rows below state the texts the + // saved records carry. if instrument.sources.is_none() { let texts: Vec = instrument .texts @@ -7640,8 +7665,9 @@ fn report(instrument: &Instrument, scenarios: &[Scenario], records: &[RunRecord] .collect(); text += &format!("| text | {} |\n", texts.join(", ")); } - // Every run of an arm carries the same texts, so the first one that names - // them states what the arm emitted. + // Each evaluation's runs carry the texts it was given, and a pool refuses + // runs of one arm that recorded different ones, so the first record that + // names them states what the arm emitted. let emitted = |arm: &str| { records .iter() @@ -10993,6 +11019,76 @@ mod tests { assert!(out.join("scenario.md").exists()); } + /// A pool states the texts its runs recorded, and refuses an arm whose + /// runs recorded different ones: a report that stated one set for runs + /// that compared several would be wrong. + #[tokio::test(flavor = "multi_thread", worker_threads = 4)] + async fn a_pool_refuses_runs_that_recorded_different_texts() { + const BASELINE: &str = "BASELINE BRANCH TOOL DESCRIPTION"; + const CANDIDATE: &str = "CANDIDATE BRANCH TOOL DESCRIPTION"; + const OTHER: &str = "OTHER BASELINE BRANCH TOOL DESCRIPTION"; + let fixture = Fixture::start( + "pool-texts", + judged, + json!({ + "message": "Say hello.", + "budget": {"turns": 4, "seconds": 120, "window": 24000}, + "probes": [{"id": "ran", "kind": "must_show", "text": "the run has a transcript"}] + }), + &[], + ) + .await; + let source = |name: &str, baseline: &str| { + let directory = fixture.directory.join(name); + std::fs::create_dir_all(&directory).unwrap(); + let texts = |text: &str| { + json!([{"id": "timeline-tree/branch-description", "bytes": text.len(), + "fingerprint": fingerprint(text)}]) + }; + let runs = [ + json!({"arm": "current", "scenario": "case", "run": 0, "session": null, + "stop": "idle", "turns": 2, "window": 24000.0, "durationMs": 1.0, + "failed": false, "judgeOutcome": "judged", "error": null, + "judgeError": null, "judgeReasks": 0, "texts": texts(baseline), + "probes": [{"id": "ran", "kind": "must_show", + "verdict": "present", "quote": null}]}), + json!({"arm": "candidate", "scenario": "case", "run": 0, "session": null, + "stop": "idle", "turns": 2, "window": 24000.0, "durationMs": 1.0, + "failed": false, "judgeOutcome": "judged", "error": null, + "judgeError": null, "judgeReasks": 0, "texts": texts(CANDIDATE), + "probes": [{"id": "ran", "kind": "must_show", + "verdict": "present", "quote": null}]}), + ]; + let jsonl: String = runs.iter().map(|record| format!("{record}\n")).collect(); + std::fs::write(directory.join("runs.jsonl"), &jsonl).unwrap(); + directory + }; + let (first, second) = (source("first", BASELINE), source("second", BASELINE)); + let mut options = fixture.options(fixture.directory.join("pooled")); + options.pool = vec![first.clone(), second]; + let report = fixture.pooled(&options).await.unwrap(); + for (arm, text) in [("current", BASELINE), ("candidate", CANDIDATE)] { + assert!( + report.contains(&format!( + "| {arm} texts | `timeline-tree/branch-description`: {} bytes, \ + fingerprint {} |", + text.len(), + fingerprint(text) + )), + "{arm}: a pool states the texts its runs recorded: {report}" + ); + } + let other = source("other", OTHER); + let mut options = fixture.options(fixture.directory.join("pooled-again")); + options.pool = vec![first, other]; + let error = fixture.pooled(&options).await.unwrap_err().to_string(); + assert!( + error.contains("the current runs recorded different texts"), + "{error}" + ); + assert!(error.contains("report them separately"), "{error}"); + } + /// A report over saved runs counts the declines their records carry and /// says how many records carry none: a record written before the runner /// counted them is not read as no declines. From 789a9191773d819ee64e82ade254ab2d45c038e9 Mon Sep 17 00:00:00 2001 From: huihui Date: Mon, 23 Nov 2026 01:13:37 +0800 Subject: [PATCH 10/35] docs(prompts): record the baseline flag and a pool's text rows The evaluation tooling section now names the `--text`/`--baseline`/`--candidate` triple the runner takes, so the documented combination is one the runner accepts. A report built from saved runs states the texts its runs recorded, so the section no longer says such a report has no text row. Both statements are in the Chinese translation too. --- docs/design/model-prompts.md | 4 ++-- docs/zh/design/model-prompts.md | 4 ++-- 2 files changed, 4 insertions(+), 4 deletions(-) diff --git a/docs/design/model-prompts.md b/docs/design/model-prompts.md index 6f56cd31d4..18a1434323 100644 --- a/docs/design/model-prompts.md +++ b/docs/design/model-prompts.md @@ -252,9 +252,9 @@ SessionTitle is out of scope: its `SYSTEM` (`crates/dim-session-title/src/lib.rs **Owner:** the evaluation tooling, `xtask`; implemented under [#550](https://github.com/arcships/dim/issues/550). -- **A scenario runner** with the candidate injection and the test of §8.1: the scenarios are the cases, both arms run the shipped assembly, and the result is reported in the pull request. It interleaves the arms run by run and accepts `--jobs` and repeated `--text`/`--candidate` pairs, so a change that spans two texts of one owner is judged as the one change it is (Goal §A.5.2). +- **A scenario runner** with the candidate injection and the test of §8.1: the scenarios are the cases, both arms run the shipped assembly, and the result is reported in the pull request. It interleaves the arms run by run and accepts `--jobs` and repeated `--text`/`--baseline`/`--candidate` triples, so a change that spans two texts of one owner is judged as the one change it is (Goal §A.5.2). - **A scenario may move the default branch mid-run.** Its `switch` step names the target line, by role (`latest_tool_line`) or id, and the runner calls `session.branch_set_default` at that line's first `turn/start` before sending the next input; the move is retried a few times while the line is not registered yet, and a line that never registers ends the run with its own outcome. An input that names no line lands on the default branch, and one that names a line keeps that target. -- **A finished evaluation's saved runs are judged again or pooled.** `--rejudge DIR` judges them from the views they saved, with no model turn, keeping each run's own outcome and writing to a new `--out`; `--pool DIR` adds a finished evaluation's saved runs to a report under the same rule and format, and the flag may be repeated to pool several evaluations, writing to none of them, and an `--out` that resolves inside a source, through `..` or a link, is refused before anything is created. Such a report names its sources, has no text or candidate-token row, and in a pool its model and judge rows are the ones given, while each source's own report states the instrument its runs were judged with. Such a report also gives the declines the runner sent again and how many runs did not record it. +- **A finished evaluation's saved runs are judged again or pooled.** `--rejudge DIR` judges them from the views they saved, with no model turn, keeping each run's own outcome and writing to a new `--out`; `--pool DIR` adds a finished evaluation's saved runs to a report under the same rule and format, and the flag may be repeated to pool several evaluations, writing to none of them, and an `--out` that resolves inside a source, through `..` or a link, is refused before anything is created. Such a report names its sources instead of the instrument's text and candidate-token rows, states the texts each arm's saved runs recorded, and in a pool its model and judge rows are the ones given, while each source's own report states the instrument its runs were judged with. Such a report also gives the declines the runner sent again and how many runs did not record it. - **A run's file roots.** Each live run serves with three kinds of file-tool root: its workspace, which the model may read and write; its disposable home, which `~` resolves against and which the model may read; and the platform's fixed read-only roots, which carry the toolchain the run's commands read, such as the interpreter's own installation. A file-tool path outside them is refused with `outside_file_roots`, and the refusal leaves what is outside untouched. The roots bound the model's file-tool calls — `read`, `write`, `edit`, `glob` and `grep`; `exec` is bounded by the sandbox, and the client-initiated paths, `@` mention expansion and the App Server's `session.files.*` methods, are not calls the model makes and stay outside the roots. - **No absolute pass line and no CI run** (§8.1). diff --git a/docs/zh/design/model-prompts.md b/docs/zh/design/model-prompts.md index d1edbb431d..acd73c759c 100644 --- a/docs/zh/design/model-prompts.md +++ b/docs/zh/design/model-prompts.md @@ -251,9 +251,9 @@ SessionTitle 不在范围内:它的 `SYSTEM`(`crates/dim-session-title/src/l **所有者:** 评估工具,`xtask`;在 [#550](https://github.com/arcships/dim/issues/550) 下实现。 -- **一个场景运行器**,带 §8.1 的候选注入与检验:场景即用例,两臂都跑 shipped 装配,结果写进 PR。它逐次交错两臂,并接受 `--jobs` 与重复的 `--text`/`--candidate` 对,因此一个跨同一所有者两段文本的改动按它本来就是的一次改动来判定(Goal §A.5.2)。 +- **一个场景运行器**,带 §8.1 的候选注入与检验:场景即用例,两臂都跑 shipped 装配,结果写进 PR。它逐次交错两臂,并接受 `--jobs` 与重复的 `--text`/`--baseline`/`--candidate` 三元组,因此一个跨同一所有者两段文本的改动按它本来就是的一次改动来判定(Goal §A.5.2)。 - **场景可以在运行中途移动默认分支。** `switch` 步骤按角色(`latest_tool_line`)或 id 指定目标线;运行器在那条线第一次 `turn/start` 时、发下一条输入之前调用 `session.branch_set_default`。线还没注册好时,移动会有限次重试;始终注册不上的线让这次运行以自己的结局结束。不点名线的输入落到默认分支,点名线的输入仍以那个目标为准。 -- **已完成评估的运行可以重判,也可以合并报告。** `--rejudge DIR` 按这些运行保存的视图重新判定,不产生模型轮次,保留每次运行自身的结局,写入新的 `--out`;`--pool DIR` 把一次已完成评估的运行加入报告,该参数可以重复给出,从而把多次已完成评估的运行按同一规则与同一格式一起报告,不写入其中任何一个,而解析后落在某个来源内部的 `--out`(经由 `..` 或链接)会在创建任何东西之前被拒绝。这样的报告会列出它的来源,没有 text 行与 candidate-token 行;合并报告里的 model 与 judge 两行是收到的参数,每个来源自己的报告才写着它的运行是凭什么判的。这样的报告还会给出再次发送 decline 的次数,以及有多少运行没有记录该次数。 +- **已完成评估的运行可以重判,也可以合并报告。** `--rejudge DIR` 按这些运行保存的视图重新判定,不产生模型轮次,保留每次运行自身的结局,写入新的 `--out`;`--pool DIR` 把一次已完成评估的运行加入报告,该参数可以重复给出,从而把多次已完成评估的运行按同一规则与同一格式一起报告,不写入其中任何一个,而解析后落在某个来源内部的 `--out`(经由 `..` 或链接)会在创建任何东西之前被拒绝。这样的报告列出它的来源,取代评估工具的 text 与 candidate-token 两行,并写出每个臂保存的运行所记录的文本;合并报告里的 model 与 judge 两行是收到的参数,每个来源自己的报告才写着它的运行是凭什么判的。这样的报告还会给出再次发送 decline 的次数,以及有多少运行没有记录该次数。 - **一次运行的文件根。** 每个 isolate 运行都以三类文件工具根提供服务:工作区,模型可读可写;一次性 home,`~` 解析到它,模型可读;以及平台固定的只读根,承载运行的命令要读取的工具链,例如解释器自身的安装目录。文件工具路径落在这些根之外时以 `outside_file_roots` 拒绝,且拒绝不触碰根外的任何内容。这些根约束模型的文件工具调用——`read`、`write`、`edit`、`glob`、`grep`;`exec` 由沙箱约束,而客户端发起的路径(`@` 提及展开与 App Server 的 `session.files.*` 方法)不是模型发起的调用,不在根内。 - **不用绝对通过线,不进 CI**(§8.1)。 From 94796e4822fc433ec018170ddb01653de52acd06 Mon Sep 17 00:00:00 2001 From: huihui Date: Mon, 23 Nov 2026 01:33:12 +0800 Subject: [PATCH 11/35] docs(prompts): state the pool's one text set per arm A report built from saved runs states one set of texts for each arm, so the pool bullet now names the refusal the runner gives a pool whose runs of one arm recorded different texts, and says that such evaluations are pooled only when they were given the same texts and are reported separately otherwise. The Chinese translation carries the same sentence. The Goal page's evaluation section now names the flags the runner takes, `--text` with its `--baseline` and `--candidate`, so the two texts one evaluation judges together are described as the runner accepts them. --- docs/design/model-prompts.md | 2 +- docs/zh/design/model-prompts.md | 2 +- docs/zh/design/plugins/Goal.md | 2 +- 3 files changed, 3 insertions(+), 3 deletions(-) diff --git a/docs/design/model-prompts.md b/docs/design/model-prompts.md index 18a1434323..ff685ffdac 100644 --- a/docs/design/model-prompts.md +++ b/docs/design/model-prompts.md @@ -254,7 +254,7 @@ SessionTitle is out of scope: its `SYSTEM` (`crates/dim-session-title/src/lib.rs - **A scenario runner** with the candidate injection and the test of §8.1: the scenarios are the cases, both arms run the shipped assembly, and the result is reported in the pull request. It interleaves the arms run by run and accepts `--jobs` and repeated `--text`/`--baseline`/`--candidate` triples, so a change that spans two texts of one owner is judged as the one change it is (Goal §A.5.2). - **A scenario may move the default branch mid-run.** Its `switch` step names the target line, by role (`latest_tool_line`) or id, and the runner calls `session.branch_set_default` at that line's first `turn/start` before sending the next input; the move is retried a few times while the line is not registered yet, and a line that never registers ends the run with its own outcome. An input that names no line lands on the default branch, and one that names a line keeps that target. -- **A finished evaluation's saved runs are judged again or pooled.** `--rejudge DIR` judges them from the views they saved, with no model turn, keeping each run's own outcome and writing to a new `--out`; `--pool DIR` adds a finished evaluation's saved runs to a report under the same rule and format, and the flag may be repeated to pool several evaluations, writing to none of them, and an `--out` that resolves inside a source, through `..` or a link, is refused before anything is created. Such a report names its sources instead of the instrument's text and candidate-token rows, states the texts each arm's saved runs recorded, and in a pool its model and judge rows are the ones given, while each source's own report states the instrument its runs were judged with. Such a report also gives the declines the runner sent again and how many runs did not record it. +- **A finished evaluation's saved runs are judged again or pooled.** `--rejudge DIR` judges them from the views they saved, with no model turn, keeping each run's own outcome and writing to a new `--out`; `--pool DIR` adds a finished evaluation's saved runs to a report under the same rule and format, and the flag may be repeated to pool several evaluations, writing to none of them, and an `--out` that resolves inside a source, through `..` or a link, is refused before anything is created. Such a report names its sources instead of the instrument's text and candidate-token rows, states the texts each arm's saved runs recorded, and in a pool its model and judge rows are the ones given, while each source's own report states the instrument its runs were judged with. Such a report also gives the declines the runner sent again and how many runs did not record it. A report states one set of texts per arm, so a pool whose runs of one arm recorded different texts is refused: such evaluations are pooled only when they were given the same texts, and otherwise they are reported separately. - **A run's file roots.** Each live run serves with three kinds of file-tool root: its workspace, which the model may read and write; its disposable home, which `~` resolves against and which the model may read; and the platform's fixed read-only roots, which carry the toolchain the run's commands read, such as the interpreter's own installation. A file-tool path outside them is refused with `outside_file_roots`, and the refusal leaves what is outside untouched. The roots bound the model's file-tool calls — `read`, `write`, `edit`, `glob` and `grep`; `exec` is bounded by the sandbox, and the client-initiated paths, `@` mention expansion and the App Server's `session.files.*` methods, are not calls the model makes and stay outside the roots. - **No absolute pass line and no CI run** (§8.1). diff --git a/docs/zh/design/model-prompts.md b/docs/zh/design/model-prompts.md index acd73c759c..cf04d2ba23 100644 --- a/docs/zh/design/model-prompts.md +++ b/docs/zh/design/model-prompts.md @@ -253,7 +253,7 @@ SessionTitle 不在范围内:它的 `SYSTEM`(`crates/dim-session-title/src/l - **一个场景运行器**,带 §8.1 的候选注入与检验:场景即用例,两臂都跑 shipped 装配,结果写进 PR。它逐次交错两臂,并接受 `--jobs` 与重复的 `--text`/`--baseline`/`--candidate` 三元组,因此一个跨同一所有者两段文本的改动按它本来就是的一次改动来判定(Goal §A.5.2)。 - **场景可以在运行中途移动默认分支。** `switch` 步骤按角色(`latest_tool_line`)或 id 指定目标线;运行器在那条线第一次 `turn/start` 时、发下一条输入之前调用 `session.branch_set_default`。线还没注册好时,移动会有限次重试;始终注册不上的线让这次运行以自己的结局结束。不点名线的输入落到默认分支,点名线的输入仍以那个目标为准。 -- **已完成评估的运行可以重判,也可以合并报告。** `--rejudge DIR` 按这些运行保存的视图重新判定,不产生模型轮次,保留每次运行自身的结局,写入新的 `--out`;`--pool DIR` 把一次已完成评估的运行加入报告,该参数可以重复给出,从而把多次已完成评估的运行按同一规则与同一格式一起报告,不写入其中任何一个,而解析后落在某个来源内部的 `--out`(经由 `..` 或链接)会在创建任何东西之前被拒绝。这样的报告列出它的来源,取代评估工具的 text 与 candidate-token 两行,并写出每个臂保存的运行所记录的文本;合并报告里的 model 与 judge 两行是收到的参数,每个来源自己的报告才写着它的运行是凭什么判的。这样的报告还会给出再次发送 decline 的次数,以及有多少运行没有记录该次数。 +- **已完成评估的运行可以重判,也可以合并报告。** `--rejudge DIR` 按这些运行保存的视图重新判定,不产生模型轮次,保留每次运行自身的结局,写入新的 `--out`;`--pool DIR` 把一次已完成评估的运行加入报告,该参数可以重复给出,从而把多次已完成评估的运行按同一规则与同一格式一起报告,不写入其中任何一个,而解析后落在某个来源内部的 `--out`(经由 `..` 或链接)会在创建任何东西之前被拒绝。这样的报告列出它的来源,取代评估工具的 text 与 candidate-token 两行,并写出每个臂保存的运行所记录的文本;合并报告里的 model 与 judge 两行是收到的参数,每个来源自己的报告才写着它的运行是凭什么判的。这样的报告还会给出再次发送 decline 的次数,以及有多少运行没有记录该次数。报告每个臂只写一组文本,因此同一个臂的运行记录了不同文本时池化会被拒绝:这些评估只有在收到同样的文本时才一起池化,否则分别报告。 - **一次运行的文件根。** 每个 isolate 运行都以三类文件工具根提供服务:工作区,模型可读可写;一次性 home,`~` 解析到它,模型可读;以及平台固定的只读根,承载运行的命令要读取的工具链,例如解释器自身的安装目录。文件工具路径落在这些根之外时以 `outside_file_roots` 拒绝,且拒绝不触碰根外的任何内容。这些根约束模型的文件工具调用——`read`、`write`、`edit`、`glob`、`grep`;`exec` 由沙箱约束,而客户端发起的路径(`@` 提及展开与 App Server 的 `session.files.*` 方法)不是模型发起的调用,不在根内。 - **不用绝对通过线,不进 CI**(§8.1)。 diff --git a/docs/zh/design/plugins/Goal.md b/docs/zh/design/plugins/Goal.md index 99ad52201e..0af479ea7c 100644 --- a/docs/zh/design/plugins/Goal.md +++ b/docs/zh/design/plugins/Goal.md @@ -452,7 +452,7 @@ in its last 3 continued turns",`evaluation_failed` "the evaluator could not ch ### A.5.2 评估 -状态记录中目标文本与状态句子的句子、以及续跑块的句子,是同一次策略改动,按 [model-facing prompts §8](../model-prompts.md#8-一次改动怎样判定) 的场景集以 current 对 candidate 判定:`main` 上设置的目标会续跑;一条线不续跑它继承来的目标;已完成或已阻塞的目标停止。两句话都在出厂配置上开放,因此候选走真实装配运行,结果在交付处报告。`GoalTexts` 承载它们,字段为 `objective` 与 `continuation`,分支处写为 `{branch}` 由代码替换;`install_with` 在工厂处换成候选。两句话分别判定,各一个 `--text` id;一次评估可以同时带上这两对 `--text`/`--candidate`,因此它们按本节所说的同一次改动来判定。 +状态记录中目标文本与状态句子的句子、以及续跑块的句子,是同一次策略改动,按 [model-facing prompts §8](../model-prompts.md#8-一次改动怎样判定) 的场景集以 current 对 candidate 判定:`main` 上设置的目标会续跑;一条线不续跑它继承来的目标;已完成或已阻塞的目标停止。两句话都在出厂配置上开放,因此候选走真实装配运行,结果在交付处报告。`GoalTexts` 承载它们,字段为 `objective` 与 `continuation`,分支处写为 `{branch}` 由代码替换;`install_with` 在工厂处换成候选。两句话分别判定,各一个 `--text` id;一次评估可以同时带上这两组 `--text`/`--baseline`/`--candidate`,因此它们按本节所说的同一次改动来判定。 ### A.6 Timeline 机制 From 48d3fdc30d809731129927b92f18ebd716aa134c Mon Sep 17 00:00:00 2001 From: huihui Date: Mon, 23 Nov 2026 02:02:21 +0800 Subject: [PATCH 12/35] fix(branch): omit the guidance heading from an empty note block An empty default_note, user_default_note or former_default_note now writes the status note without the How you work here: heading, so a baseline that replaces the block with no text emits the note the pre-policy head wrote. The shipped blocks are non-empty and keep the heading. The flow test asserts the note and the rendered model request byte for byte against the pre-policy output, and a second test keeps the shipped heading. --- .../src/timeline_tree.rs | 13 ++- .../tests/branch_flow.rs | 102 ++++++++++++++++++ 2 files changed, 110 insertions(+), 5 deletions(-) diff --git a/crates/dim-agent-capabilities/src/timeline_tree.rs b/crates/dim-agent-capabilities/src/timeline_tree.rs index ccc9a26b1e..a347c77bf2 100644 --- a/crates/dim-agent-capabilities/src/timeline_tree.rs +++ b/crates/dim-agent-capabilities/src/timeline_tree.rs @@ -4865,7 +4865,8 @@ impl BranchLine { /// The status note a move writes on this line: the line's birth identity /// under the same key, restated byte for byte, then the sentences the move /// changes and the guidance block a candidate replaces (design §5, - /// §12.1). A line the user opened and a tool line get their own rule. + /// §12.1). An empty block writes no `How you work here:` heading. A line + /// the user opened and a tool line get their own rule. fn status_note( &self, parent: &str, @@ -4919,10 +4920,12 @@ impl BranchLine { .unwrap_or(FORMER_DEFAULT_NOTE), ) }; - let body = format!( - "{birth}\n\n{change}\n\nHow you work here:\n{}", - block.replace("{parent}", parent).replace("{other}", other) - ); + let guidance = block.replace("{parent}", parent).replace("{other}", other); + let body = if guidance.is_empty() { + format!("{birth}\n\n{change}") + } else { + format!("{birth}\n\n{change}\n\nHow you work here:\n{guidance}") + }; let mut attrs = vec![ ("branch", line), ("parent", parent), diff --git a/crates/dim-agent-capabilities/tests/branch_flow.rs b/crates/dim-agent-capabilities/tests/branch_flow.rs index d3b8f40ae0..efb2bf190b 100644 --- a/crates/dim-agent-capabilities/tests/branch_flow.rs +++ b/crates/dim-agent-capabilities/tests/branch_flow.rs @@ -4563,6 +4563,108 @@ async fn a_configured_note_block_reaches_the_note() { soon(agent.close()).await.unwrap(); } +/// The note `4560a5d67` wrote when a tool line became the default branch: its +/// birth identity, then the sentences the move changes, with no `How you work +/// here:` block, which that head's `status_note` had not grown yet. The +/// branch-policy evaluation gives `default_note` an empty baseline so its +/// current arm emits this text byte for byte. `{line}` and `{purpose}` stand +/// where the code substitutes them. +const PRE_POLICY_TOOL_NOTE: &str = r#" +You are line {line} of this session. Line main opened you at this point of its history to work in parallel with it. You are the same agent as main: everything above is your own history, and you continue from here on your own line. main keeps working on its line; you can read its work after this point, and it can read yours. Messages above that were addressed to main, such as its list of open lines, are main's, not yours. + +Your purpose, as main wrote it: +{purpose} + +How you work with main: +- Work on this purpose only. You cannot open lines unless this line is the default branch of the session, and this block does not make it one: a status note would. If more parallel work is needed and you cannot open a line, tell main. +- Read main with the branch tool (action read, branch "main") when what main did or decided since your cut changes your work; the parent block reports when main has moved. Message main only for what it must act on: a decision that changes its work, a blocker only the user can settle, a conflict with another line, or a change to your purpose. Use mode "steer" for what main must act on now, "append" for what main should see at its next step. Do not send main a progress report it can read, and do not page through main's whole stream: read the page that answers your question, then act. +- You share the workspace with main and its other lines. Change only the files main gave you; before changing any other file, tell main which. If edit or write fails because the file was modified after it was last read, another line may have changed the file: read it again and tell main before you continue. +- The user can talk to you directly. Answer the user, and ask with ask_user when only the user can decide. +- When your purpose is done, or cannot be done, call the branch tool with action "end" and content saying what you found, did, changed and left undone. If you already told main that in a message, your end content carries only what is new. Read main once more before you end if the parent block says main has moved, so your last word still holds. That is your last action; main receives it. + +This line is now the session's default branch, switched from line main. While this block is your latest one: answer the user here; you can open lines with create; you send no automatic idle notice to main; you cannot call end on yourself. Line main stays open and keeps the lines it opened. +"#; + +/// An empty `default_note` writes the note with no `How you work here:` block, +/// byte for byte as `4560a5d67` wrote it: the branch-policy evaluation's +/// current arm is that head's text, not this head's default block (timeline +/// branches §12.4, model-prompts §8.1). +#[tokio::test(flavor = "multi_thread", worker_threads = 2)] +async fn an_empty_note_block_writes_the_note_without_guidance() { + let purpose = "the purpose of B"; + let probe = Arc::new(Probe::default()); + let agent = MinimalHost::start(&builder_with_branch_config( + &probe, + BranchToolConfig { + default_note: Some("".into()), + ..Default::default() + }, + )) + .await + .unwrap(); + let session = soon(agent.create_session(SessionConfig::default())) + .await + .unwrap(); + let line = open_line(&session, purpose).await; + switch(&session, &line).await; + let notes = owed_notes(&session, &line, 1).await; + let note = notes.last().expect("the line holds its note"); + let expected = PRE_POLICY_TOOL_NOTE + .replace("{line}", &line) + .replace("{purpose}", purpose); + assert_eq!( + note, &expected, + "an empty block emits the note the pre-policy head wrote" + ); + soon(session.submit("next request".into(), InputMode::Queue, &line)) + .await + .unwrap(); + soon(session.idle(&line)).await.unwrap(); + let events = local_events(&session, &line).await; + let request = events + .iter() + .rev() + .find_map(|event| match &event.kind { + EventKind::ModelCall(data) => Some(&data.request), + _ => None, + }) + .expect("the line's next turn makes a request"); + assert!( + request + .messages + .iter() + .any(|message| said(message).contains(&expected)), + "the rendered request carries the note the baseline wrote" + ); + soon(agent.close()).await.unwrap(); +} + +/// The product's note blocks keep their `How you work here:` heading: the +/// empty-block rule serves a candidate that replaces the block with nothing, +/// not the shipped text. +#[tokio::test(flavor = "multi_thread", worker_threads = 2)] +async fn the_product_note_block_keeps_its_guidance_heading() { + let probe = Arc::new(Probe::default()); + let agent = MinimalHost::start(&builder_with_branch_config( + &probe, + BranchToolConfig::default(), + )) + .await + .unwrap(); + let session = soon(agent.create_session(SessionConfig::default())) + .await + .unwrap(); + let line = open_line(&session, "the shipped line").await; + switch(&session, &line).await; + let notes = owed_notes(&session, &line, 1).await; + let note = notes.last().expect("the line holds its note"); + assert!( + note.contains("\n\nHow you work here:\n- The user switched here to continue directly from this line's context and approach"), + "{note}" + ); + soon(agent.close()).await.unwrap(); +} + /// #549: a description set at the declaring owner's factory configuration /// reaches the model request byte for byte, carried through ToolRegistry and /// ToolBinding by the shipped assembly. From 6160e2660c8996c565da007e860b890ba22eb948 Mon Sep 17 00:00:00 2001 From: huihui Date: Mon, 23 Nov 2026 02:02:24 +0800 Subject: [PATCH 13/35] test(xtask): add the branch policy evaluation baselines Four files under xtask/scenario-eval/branch-policy-baseline give the branch policy family its pre-change texts: the tool description from 4560a5d67 with its last protocol sentence aligned to the new one, and empty blocks for the three status notes that had no How you work here: guidance. The description file is 2058 bytes with fingerprint 4818522f696ae9f0; the three empty files are 0 bytes with fingerprint cbf29ce484222325. --- .../branch-policy-baseline/branch-description.txt | 6 ++++++ xtask/scenario-eval/branch-policy-baseline/default-note.txt | 0 .../branch-policy-baseline/former-default-note.txt | 0 .../branch-policy-baseline/user-default-note.txt | 0 4 files changed, 6 insertions(+) create mode 100644 xtask/scenario-eval/branch-policy-baseline/branch-description.txt create mode 100644 xtask/scenario-eval/branch-policy-baseline/default-note.txt create mode 100644 xtask/scenario-eval/branch-policy-baseline/former-default-note.txt create mode 100644 xtask/scenario-eval/branch-policy-baseline/user-default-note.txt diff --git a/xtask/scenario-eval/branch-policy-baseline/branch-description.txt b/xtask/scenario-eval/branch-policy-baseline/branch-description.txt new file mode 100644 index 0000000000..afe3de7ac3 --- /dev/null +++ b/xtask/scenario-eval/branch-policy-baseline/branch-description.txt @@ -0,0 +1,6 @@ +Work with the other lines of this session. A line is you: it starts from your history at the point it is opened, then works in parallel on its own line. It is not a helper with its own memory, and it owes you no result; you and it keep each other informed by reading each other's work and messaging what the other must act on. On main you coordinate: answer a line's steer and act on what it asks for; leave a line's part to that line instead of redoing it; read a line's work instead of waiting for a report. +- create (the root and the current default branch only): open a line to work on prompt in parallel. Open one line per part that can go on at the same time as the rest — separate files, a separate question, or a second approach — instead of doing those parts one after another yourself; not for a single quick edit, nor when your next step needs its result. Write prompt as a brief to yourself: the purpose, what you already know that it needs, which files or area are its own, and when it should tell you or end. Returns the line's id. +- message: send content to a line you opened, or to the line that opened you. Send a decision, a blocker, or a conflict, not a progress report the receiver can read. Mode "append" (default) reaches the receiver at its next step without interrupting it and does not wake an idle line. Use "steer" when the receiver must act now or is idle. +- read: show a page of the activity of the line you were cut from, or of a line you opened, also after it ended. With no after, a read continues after your last read of that line: from your cut for the line you were cut from, and from its first event for a line you opened. Pass after to read from another point. Do not page through a whole line. +- end: on a line opened with create, end your own line. content is your final message to the line that opened you: what you found, did, changed and left undone. It is your last action. +A line messages and reads the line it was cut from and the lines it opened. The end action ends the calling line and every line below it. \ No newline at end of file diff --git a/xtask/scenario-eval/branch-policy-baseline/default-note.txt b/xtask/scenario-eval/branch-policy-baseline/default-note.txt new file mode 100644 index 0000000000..e69de29bb2 diff --git a/xtask/scenario-eval/branch-policy-baseline/former-default-note.txt b/xtask/scenario-eval/branch-policy-baseline/former-default-note.txt new file mode 100644 index 0000000000..e69de29bb2 diff --git a/xtask/scenario-eval/branch-policy-baseline/user-default-note.txt b/xtask/scenario-eval/branch-policy-baseline/user-default-note.txt new file mode 100644 index 0000000000..e69de29bb2 From 8b66ef16ecf2e3a01e24cc5d33170ec87bfe0bbf Mon Sep 17 00:00:00 2001 From: huihui Date: Mon, 23 Nov 2026 02:02:33 +0800 Subject: [PATCH 14/35] fix(xtask): keep a pool's text provenance separate A pool or rejudge now refuses an arm that mixes runs which name their configured texts with runs written before the runner recorded them, before any judge call. An all-unrecorded pool stays supported, and the report states not recorded for that arm. The report labels the per-arm hashes as configured texts rather than emitted texts, and reading a text file names the flag that was read, so a missing baseline is reported as a baseline. --- docs/design/model-prompts.md | 2 +- docs/zh/design/model-prompts.md | 2 +- xtask/src/scenario_eval.rs | 270 ++++++++++++++++++++++++-------- 3 files changed, 208 insertions(+), 66 deletions(-) diff --git a/docs/design/model-prompts.md b/docs/design/model-prompts.md index ff685ffdac..9b64aa2f13 100644 --- a/docs/design/model-prompts.md +++ b/docs/design/model-prompts.md @@ -254,7 +254,7 @@ SessionTitle is out of scope: its `SYSTEM` (`crates/dim-session-title/src/lib.rs - **A scenario runner** with the candidate injection and the test of §8.1: the scenarios are the cases, both arms run the shipped assembly, and the result is reported in the pull request. It interleaves the arms run by run and accepts `--jobs` and repeated `--text`/`--baseline`/`--candidate` triples, so a change that spans two texts of one owner is judged as the one change it is (Goal §A.5.2). - **A scenario may move the default branch mid-run.** Its `switch` step names the target line, by role (`latest_tool_line`) or id, and the runner calls `session.branch_set_default` at that line's first `turn/start` before sending the next input; the move is retried a few times while the line is not registered yet, and a line that never registers ends the run with its own outcome. An input that names no line lands on the default branch, and one that names a line keeps that target. -- **A finished evaluation's saved runs are judged again or pooled.** `--rejudge DIR` judges them from the views they saved, with no model turn, keeping each run's own outcome and writing to a new `--out`; `--pool DIR` adds a finished evaluation's saved runs to a report under the same rule and format, and the flag may be repeated to pool several evaluations, writing to none of them, and an `--out` that resolves inside a source, through `..` or a link, is refused before anything is created. Such a report names its sources instead of the instrument's text and candidate-token rows, states the texts each arm's saved runs recorded, and in a pool its model and judge rows are the ones given, while each source's own report states the instrument its runs were judged with. Such a report also gives the declines the runner sent again and how many runs did not record it. A report states one set of texts per arm, so a pool whose runs of one arm recorded different texts is refused: such evaluations are pooled only when they were given the same texts, and otherwise they are reported separately. +- **A finished evaluation's saved runs are judged again or pooled.** `--rejudge DIR` judges them from the views they saved, with no model turn, keeping each run's own outcome and writing to a new `--out`; `--pool DIR` adds a finished evaluation's saved runs to a report under the same rule and format, and the flag may be repeated to pool several evaluations, writing to none of them, and an `--out` that resolves inside a source, through `..` or a link, is refused before anything is created. Such a report names its sources instead of the instrument's text and candidate-token rows, states the configured texts each arm's saved runs recorded (or that an arm's runs recorded none), and in a pool its model and judge rows are the ones given, while each source's own report states the instrument its runs were judged with. Such a report also gives the declines the runner sent again and how many runs did not record it. A report states one set of configured texts per arm, so a pool whose runs of one arm recorded different texts is refused, and so is a pool that mixes runs which recorded their texts with runs written before the runner recorded them: such evaluations are reported separately, while a pool of runs that all recorded none stays supported as unrecorded. - **A run's file roots.** Each live run serves with three kinds of file-tool root: its workspace, which the model may read and write; its disposable home, which `~` resolves against and which the model may read; and the platform's fixed read-only roots, which carry the toolchain the run's commands read, such as the interpreter's own installation. A file-tool path outside them is refused with `outside_file_roots`, and the refusal leaves what is outside untouched. The roots bound the model's file-tool calls — `read`, `write`, `edit`, `glob` and `grep`; `exec` is bounded by the sandbox, and the client-initiated paths, `@` mention expansion and the App Server's `session.files.*` methods, are not calls the model makes and stay outside the roots. - **No absolute pass line and no CI run** (§8.1). diff --git a/docs/zh/design/model-prompts.md b/docs/zh/design/model-prompts.md index cf04d2ba23..37f9c994ae 100644 --- a/docs/zh/design/model-prompts.md +++ b/docs/zh/design/model-prompts.md @@ -253,7 +253,7 @@ SessionTitle 不在范围内:它的 `SYSTEM`(`crates/dim-session-title/src/l - **一个场景运行器**,带 §8.1 的候选注入与检验:场景即用例,两臂都跑 shipped 装配,结果写进 PR。它逐次交错两臂,并接受 `--jobs` 与重复的 `--text`/`--baseline`/`--candidate` 三元组,因此一个跨同一所有者两段文本的改动按它本来就是的一次改动来判定(Goal §A.5.2)。 - **场景可以在运行中途移动默认分支。** `switch` 步骤按角色(`latest_tool_line`)或 id 指定目标线;运行器在那条线第一次 `turn/start` 时、发下一条输入之前调用 `session.branch_set_default`。线还没注册好时,移动会有限次重试;始终注册不上的线让这次运行以自己的结局结束。不点名线的输入落到默认分支,点名线的输入仍以那个目标为准。 -- **已完成评估的运行可以重判,也可以合并报告。** `--rejudge DIR` 按这些运行保存的视图重新判定,不产生模型轮次,保留每次运行自身的结局,写入新的 `--out`;`--pool DIR` 把一次已完成评估的运行加入报告,该参数可以重复给出,从而把多次已完成评估的运行按同一规则与同一格式一起报告,不写入其中任何一个,而解析后落在某个来源内部的 `--out`(经由 `..` 或链接)会在创建任何东西之前被拒绝。这样的报告列出它的来源,取代评估工具的 text 与 candidate-token 两行,并写出每个臂保存的运行所记录的文本;合并报告里的 model 与 judge 两行是收到的参数,每个来源自己的报告才写着它的运行是凭什么判的。这样的报告还会给出再次发送 decline 的次数,以及有多少运行没有记录该次数。报告每个臂只写一组文本,因此同一个臂的运行记录了不同文本时池化会被拒绝:这些评估只有在收到同样的文本时才一起池化,否则分别报告。 +- **已完成评估的运行可以重判,也可以合并报告。** `--rejudge DIR` 按这些运行保存的视图重新判定,不产生模型轮次,保留每次运行自身的结局,写入新的 `--out`;`--pool DIR` 把一次已完成评估的运行加入报告,该参数可以重复给出,从而把多次已完成评估的运行按同一规则与同一格式一起报告,不写入其中任何一个,而解析后落在某个来源内部的 `--out`(经由 `..` 或链接)会在创建任何东西之前被拒绝。这样的报告列出它的来源,取代评估工具的 text 与 candidate-token 两行,并写出每个臂保存的运行所记录的配置文本(或某个臂的运行一条都没记录);合并报告里的 model 与 judge 两行是收到的参数,每个来源自己的报告才写着它的运行是凭什么判的。这样的报告还会给出再次发送 decline 的次数,以及有多少运行没有记录该次数。报告每个臂只写一组配置文本,因此同一个臂的运行记录了不同文本时池化会被拒绝,把记录了文本的运行与运行器开始记录之前写下的运行混在一起也会被拒绝:这些评估分别报告;而全部都没有记录文本的运行仍可作为未记录合并。 - **一次运行的文件根。** 每个 isolate 运行都以三类文件工具根提供服务:工作区,模型可读可写;一次性 home,`~` 解析到它,模型可读;以及平台固定的只读根,承载运行的命令要读取的工具链,例如解释器自身的安装目录。文件工具路径落在这些根之外时以 `outside_file_roots` 拒绝,且拒绝不触碰根外的任何内容。这些根约束模型的文件工具调用——`read`、`write`、`edit`、`glob`、`grep`;`exec` 由沙箱约束,而客户端发起的路径(`@` 提及展开与 App Server 的 `session.files.*` 方法)不是模型发起的调用,不在根内。 - **不用绝对通过线,不进 CI**(§8.1)。 diff --git a/xtask/src/scenario_eval.rs b/xtask/src/scenario_eval.rs index d9fe0891f3..3322a5657d 100644 --- a/xtask/src/scenario_eval.rs +++ b/xtask/src/scenario_eval.rs @@ -17,8 +17,9 @@ //! copy the checkout ships; a pair whose baseline and candidate hold the same //! bytes is refused, as is one with a file missing. A pair reads in either //! order, a text named twice is an error, and the report gives each candidate -//! text's own token cost. The report and `runs.jsonl` also record the texts -//! each arm emitted, as each text's id, length and fingerprint. The runs are +//! text's own token cost. The report and `runs.jsonl` also record the +//! configured texts each arm was given, as each text's id, length and +//! fingerprint. The runs are //! interleaved: for each run index and scenario the `current` run is scheduled //! before the `candidate` one, so a drift in //! the endpoint lands on both arms alike, and the records come out in that @@ -837,6 +838,7 @@ async fn rejudge( .map_err(|error| format!("--rejudge {}: {error}", source.display()))?; let saved = read_saved_runs(&source)?; let selected = select_saved(&saved, &options.select)?; + one_saved_texts_per_arm(&selected, "--rejudge")?; let scenarios = read_scenarios(&options.scenarios)?; let mut plan = Vec::with_capacity(selected.len()); for run in selected { @@ -881,7 +883,7 @@ async fn pooled(options: &Options, observe: impl Fn(&mut AgentBuilder)) -> Resul directories.push((source, read.len())); records.extend(read); } - one_texts_per_arm(&records)?; + one_texts_per_arm(&records, "--pool")?; let cancel = CancellationToken::new(); let server = served(options, observe).await?; let resolved = async { @@ -977,26 +979,67 @@ fn read_pooled_runs(source: &Path, scenarios: &[Scenario]) -> Result Result<()> { +/// A report states one configured set of texts for each arm, so the runs of +/// one arm must all name the same set or all name none: a report that stated +/// one set for runs whose texts only some of them recorded would be wrong. +fn one_texts_per_arm(records: &[RunRecord], flag: &str) -> Result<()> { for arm in ["current", "candidate"] { - let mut recorded: Option<&[EmittedText]> = None; - for record in records - .iter() - .filter(|record| record.arm == arm && !record.texts.is_empty()) - { - if recorded.is_some_and(|texts| texts != record.texts.as_slice()) { - return Err(format!( - "--pool: the {arm} runs recorded different texts; a report states one set per \ - arm, so pool evaluations that were given the same texts or report them \ - separately" - ) - .into()); - } - recorded.get_or_insert(record.texts.as_slice()); + one_text_set( + flag, + arm, + records + .iter() + .filter(|record| record.arm == arm) + .map(|record| record.texts.as_slice()), + )?; + } + Ok(()) +} + +/// The same rule over a rejudge source's saved runs, checked before any judge +/// call. +fn one_saved_texts_per_arm(runs: &[&SavedRun], flag: &str) -> Result<()> { + for arm in ["current", "candidate"] { + one_text_set( + flag, + arm, + runs.iter() + .filter(|run| run.arm == arm) + .map(|run| run.texts.as_slice()), + )?; + } + Ok(()) +} + +fn one_text_set<'a>( + flag: &str, + arm: &str, + runs: impl Iterator, +) -> Result<()> { + let mut recorded: Option<&'a [ConfiguredText]> = None; + let mut unrecorded = false; + for texts in runs { + if texts.is_empty() { + unrecorded = true; + continue; + } + if recorded.is_some_and(|recorded| recorded != texts) { + return Err(format!( + "{flag}: the {arm} runs recorded different texts; a report states one set per \ + arm, so pool evaluations that were given the same texts or report them \ + separately" + ) + .into()); } + recorded.get_or_insert(texts); + } + if unrecorded && recorded.is_some() { + return Err(format!( + "{flag}: the {arm} runs mix records that name their configured texts with records \ + written before the runner recorded them; a report states one set per arm, so report \ + the runs that name their texts and the older runs separately" + ) + .into()); } Ok(()) } @@ -1213,10 +1256,10 @@ struct SavedRun { judge_reasks: u32, #[serde(default)] judge_calls: Vec, - /// The texts the arm emitted; empty in a record written before the runner - /// recorded them. + /// The texts the arm was given; empty in a record written before the + /// runner recorded them. #[serde(default)] - texts: Vec, + texts: Vec, /// `None` in a record written before the runner wrote this fact. #[serde(default)] temperature_dropped: Option, @@ -1523,7 +1566,7 @@ impl Options { if filled { return Err(format!("{flag} is given twice for one --text").into()); } - let text = candidate_prompt(Path::new(&value))?; + let text = candidate_prompt(Path::new(&value), &flag)?; if is_baseline { pending.baseline = Some(text); } else { @@ -1655,7 +1698,7 @@ impl Options { /// The texts one arm puts in place of the assembly's, in the order the /// evaluation was given them: `current` is each pair's baseline and /// `candidate` its candidate. - fn arm_texts(&self, arm: &str) -> Vec { + fn arm_texts(&self, arm: &str) -> Vec { let texts = if arm == "current" { &self.baseline } else { @@ -1663,7 +1706,7 @@ impl Options { }; texts .iter() - .map(|(id, text)| EmittedText::of(id, text)) + .map(|(id, text)| ConfiguredText::of(id, text)) .collect() } } @@ -1791,11 +1834,11 @@ fn refuse_output_inside_sources( Ok(()) } -fn candidate_prompt(path: &Path) -> Result> { +fn candidate_prompt(path: &Path, flag: &str) -> Result> { let bytes = - std::fs::read(path).map_err(|error| format!("--candidate {}: {error}", path.display()))?; + std::fs::read(path).map_err(|error| format!("{flag} {}: {error}", path.display()))?; let text = String::from_utf8(bytes) - .map_err(|_| format!("--candidate {}: not UTF-8 text", path.display()))?; + .map_err(|_| format!("{flag} {}: not UTF-8 text", path.display()))?; Ok(Arc::from(text)) } @@ -2334,10 +2377,11 @@ struct RunRecord { arm: &'static str, scenario: String, run: usize, - /// The texts the arm put in place of the assembly's, in the order the - /// evaluation was given them: each is a text the arm emitted in place of - /// the one its id names. - texts: Vec, + /// The texts the arm was given, in the order the evaluation was given + /// them: each is a configured input in place of the text its id names. A + /// record states what the arm was configured with, not that every text was + /// emitted. + texts: Vec, session: Option, /// `idle`, `turns`, `seconds`, `switch_target_not_reached`, /// `switch_target_ended`, `switch_target_unknown` or `error`. @@ -2398,17 +2442,17 @@ impl RunRecord { } } -/// One text an arm emitted: the id naming the text it replaced, the text's +/// One text an arm was given: the id naming the text it replaced, the text's /// length in bytes, and a fingerprint of its bytes, so a report states which -/// text each arm ran without carrying the text itself. +/// configured text each arm ran without carrying the text itself. #[derive(Clone, PartialEq, Eq, serde::Serialize, serde::Deserialize)] #[serde(rename_all = "camelCase")] -struct EmittedText { +struct ConfiguredText { id: String, bytes: usize, fingerprint: String, } -impl EmittedText { +impl ConfiguredText { fn of(id: &str, text: &str) -> Self { Self { id: id.to_owned(), @@ -7665,17 +7709,21 @@ fn report(instrument: &Instrument, scenarios: &[Scenario], records: &[RunRecord] .collect(); text += &format!("| text | {} |\n", texts.join(", ")); } - // Each evaluation's runs carry the texts it was given, and a pool refuses - // runs of one arm that recorded different ones, so the first record that - // names them states what the arm emitted. - let emitted = |arm: &str| { + // Each evaluation's runs carry the configured texts it was given. A pool + // and a rejudge refuse runs of one arm that mix recorded and unrecorded + // texts, so the first record that names them states the arm's set. + let configured = |arm: &str| { records .iter() .find(|record| record.arm == arm && !record.texts.is_empty()) .map(|record| record.texts.as_slice()) }; for arm in ["current", "candidate"] { - let Some(texts) = emitted(arm) else { + if !records.iter().any(|record| record.arm == arm) { + continue; + } + let Some(texts) = configured(arm) else { + text += &format!("| {arm} configured texts | not recorded |\n"); continue; }; let listed: Vec = texts @@ -7687,7 +7735,7 @@ fn report(instrument: &Instrument, scenarios: &[Scenario], records: &[RunRecord] ) }) .collect(); - text += &format!("| {arm} texts | {} |\n", listed.join("; ")); + text += &format!("| {arm} configured texts | {} |\n", listed.join("; ")); } text += &format!( "| model | `{}/{}`, {} |\n| judge | `{}/{}`, temperature 0, {}{window} |\n| runs | {} per arm and scenario |\n", @@ -10845,6 +10893,12 @@ mod tests { !report.contains("| text |"), "no saved run records the texts under test: {report}" ); + for arm in ["current", "candidate"] { + assert!( + report.contains(&format!("| {arm} configured texts | not recorded |")), + "{arm}: runs that recorded no text are reported as unrecorded: {report}" + ); + } assert!( report.contains("| decline retries | 3 across all runs; not recorded for 2 runs |"), "a saved run written before the runner counted declines is not read as none: {report}" @@ -11000,6 +11054,12 @@ mod tests { !report.contains("| text |"), "no saved run records the texts under test: {report}" ); + for arm in ["current", "candidate"] { + assert!( + report.contains(&format!("| {arm} configured texts | not recorded |")), + "{arm}: runs that recorded no text are reported as unrecorded: {report}" + ); + } assert_eq!( std::fs::read_to_string(first.join("runs.jsonl")).unwrap(), first_jsonl, @@ -11019,9 +11079,9 @@ mod tests { assert!(out.join("scenario.md").exists()); } - /// A pool states the texts its runs recorded, and refuses an arm whose - /// runs recorded different ones: a report that stated one set for runs - /// that compared several would be wrong. + /// A pool states the configured texts its runs recorded, and refuses an + /// arm whose runs recorded different ones: a report that stated one set + /// for runs that compared several would be wrong. #[tokio::test(flavor = "multi_thread", worker_threads = 4)] async fn a_pool_refuses_runs_that_recorded_different_texts() { const BASELINE: &str = "BASELINE BRANCH TOOL DESCRIPTION"; @@ -11070,12 +11130,12 @@ mod tests { for (arm, text) in [("current", BASELINE), ("candidate", CANDIDATE)] { assert!( report.contains(&format!( - "| {arm} texts | `timeline-tree/branch-description`: {} bytes, \ + "| {arm} configured texts | `timeline-tree/branch-description`: {} bytes, \ fingerprint {} |", text.len(), fingerprint(text) )), - "{arm}: a pool states the texts its runs recorded: {report}" + "{arm}: a pool states the configured texts its runs recorded: {report}" ); } let other = source("other", OTHER); @@ -11089,6 +11149,88 @@ mod tests { assert!(error.contains("report them separately"), "{error}"); } + /// A pool refuses runs of one arm whose texts only some of them recorded: + /// a record written before the runner recorded texts would otherwise be + /// counted and labeled as one comparison with a recorded run. An + /// all-legacy pool stays supported as unrecorded. + #[tokio::test(flavor = "multi_thread", worker_threads = 4)] + async fn a_pool_refuses_mixed_text_provenance() { + const TEXT: &str = "BASELINE BRANCH TOOL DESCRIPTION"; + let fixture = Fixture::start( + "pool-mixed", + judged, + json!({ + "message": "Say hello.", + "budget": {"turns": 4, "seconds": 120, "window": 24000}, + "probes": [{"id": "ran", "kind": "must_show", "text": "the run has a transcript"}] + }), + &[], + ) + .await; + let run = |arm: &str, texts: Option| { + let mut record = json!({"arm": arm, "scenario": "case", "run": 0, + "session": null, "stop": "idle", "turns": 2, "window": 24000.0, + "durationMs": 1.0, "failed": false, "judgeOutcome": "judged", + "error": null, "judgeError": null, "judgeReasks": 0, + "probes": [{"id": "ran", "kind": "must_show", + "verdict": "present", "quote": null}]}); + if let Some(texts) = texts { + record["texts"] = texts; + } + record + }; + let recorded = || { + json!([{"id": "timeline-tree/branch-description", "bytes": TEXT.len(), + "fingerprint": fingerprint(TEXT)}]) + }; + let source = |name: &str, current: Value, candidate: Value| { + let directory = fixture.directory.join(name); + std::fs::create_dir_all(&directory).unwrap(); + let jsonl: String = [current, candidate] + .into_iter() + .map(|record| format!("{record}\n")) + .collect(); + std::fs::write(directory.join("runs.jsonl"), &jsonl).unwrap(); + directory + }; + let legacy = source("legacy", run("current", None), run("candidate", None)); + let named = source( + "named", + run("current", Some(recorded())), + run("candidate", Some(recorded())), + ); + let mut options = fixture.options(fixture.directory.join("mixed")); + options.pool = vec![legacy, named]; + let error = fixture.pooled(&options).await.unwrap_err().to_string(); + assert!( + error.contains("the current runs mix records that name their configured texts"), + "{error}" + ); + assert!( + error.contains("report the runs that name their texts and the older runs separately"), + "{error}" + ); + // The candidate arm is checked on its own: both sources' current runs + // recorded none, while one candidate run names its text. + let legacy_current = source( + "legacy-current", + run("current", None), + run("candidate", None), + ); + let named_candidate = source( + "named-candidate", + run("current", None), + run("candidate", Some(recorded())), + ); + let mut options = fixture.options(fixture.directory.join("mixed-candidate")); + options.pool = vec![legacy_current, named_candidate]; + let error = fixture.pooled(&options).await.unwrap_err().to_string(); + assert!( + error.contains("the candidate runs mix records that name their configured texts"), + "{error}" + ); + } + /// A report over saved runs counts the declines their records carry and /// says how many records carry none: a record written before the runner /// counted them is not read as no declines. @@ -11996,14 +12138,14 @@ mod tests { assert_eq!(fingerprint("foobar"), "85944171f73967e8"); } - /// Each arm emits the text its pair names, and the run's record and the - /// report state which: the current arm's requests carry the baseline, the - /// candidate arm's the candidate, and each record names both by length and - /// fingerprint. An evaluation on a head that already carries the candidate - /// therefore compares two texts it was given, not the candidate with - /// itself (model-prompts §8.1). + /// Each arm is given the text its pair names, and the run's record and + /// the report state which: the current arm's requests carry the baseline, + /// the candidate arm's the candidate, and each record names both by length + /// and fingerprint. An evaluation on a head that already carries the + /// candidate therefore compares two texts it was given, not the candidate + /// with itself (model-prompts §8.1). #[tokio::test(flavor = "multi_thread", worker_threads = 4)] - async fn each_arm_emits_and_records_the_text_its_pair_names() { + async fn each_arm_records_the_configured_text_its_pair_names() { const BASELINE: &str = "BASELINE BRANCH TOOL DESCRIPTION"; const CANDIDATE: &str = "CANDIDATE BRANCH TOOL DESCRIPTION"; let fixture = Fixture::start( @@ -12027,7 +12169,7 @@ mod tests { ); let records = fixture.records(&options.out); assert_eq!(records.len(), 2, "one run per arm"); - let emitted = |arm: &str| { + let configured = |arm: &str| { records .iter() .find(|record| record["arm"] == arm) @@ -12035,7 +12177,7 @@ mod tests { .clone() }; for (arm, text) in [("current", BASELINE), ("candidate", CANDIDATE)] { - let texts = emitted(arm); + let texts = configured(arm); let texts = texts.as_array().unwrap_or_else(|| panic!("{arm}: {texts}")); assert_eq!(texts.len(), 1, "{arm}: {texts:?}"); assert_eq!(texts[0]["id"], "timeline-tree/branch-description", "{arm}"); @@ -12043,23 +12185,23 @@ mod tests { assert_eq!( texts[0]["fingerprint"], fingerprint(text), - "{arm}: the record names the text the arm emitted" + "{arm}: the record names the configured text" ); } assert_ne!( - emitted("current")[0]["fingerprint"], - emitted("candidate")[0]["fingerprint"], - "the arms emitted different texts" + configured("current")[0]["fingerprint"], + configured("candidate")[0]["fingerprint"], + "the arms were given different texts" ); for (arm, text) in [("current", BASELINE), ("candidate", CANDIDATE)] { assert!( report.contains(&format!( - "| {arm} texts | `timeline-tree/branch-description`: {} bytes, \ + "| {arm} configured texts | `timeline-tree/branch-description`: {} bytes, \ fingerprint {} |", text.len(), fingerprint(text) )), - "{arm}: the report names the text the arm emitted: {report}" + "{arm}: the report names the configured text: {report}" ); } let described = |arm: &str| -> Vec { From 278305fe1efec1614dee343cff319eaae83fc9ed Mon Sep 17 00:00:00 2001 From: huihui Date: Mon, 23 Nov 2026 02:22:23 +0800 Subject: [PATCH 15/35] test(xtask): refuse a rejudge that mixes text provenance A re-judge reads its saved runs through the same rule as a pool: each arm states one configured set of texts, so an arm that mixes runs naming their texts with runs written before the runner recorded them is refused. The test asserts the refusal for both arms and that it happens before any judge call. --- xtask/src/scenario_eval.rs | 99 ++++++++++++++++++++++++++++++++++++++ 1 file changed, 99 insertions(+) diff --git a/xtask/src/scenario_eval.rs b/xtask/src/scenario_eval.rs index 3322a5657d..f3e0dd7efb 100644 --- a/xtask/src/scenario_eval.rs +++ b/xtask/src/scenario_eval.rs @@ -11231,6 +11231,105 @@ mod tests { ); } + /// A re-judge refuses saved runs of one arm whose texts only some of them + /// recorded, before any judge call: a re-judged record written before the + /// runner recorded texts would otherwise be counted and labeled as one + /// comparison with a recorded run. + #[tokio::test(flavor = "multi_thread", worker_threads = 4)] + async fn a_rejudge_refuses_mixed_text_provenance() { + const TEXT: &str = "BASELINE BRANCH TOOL DESCRIPTION"; + let fixture = Fixture::start( + "rejudge-mixed", + judged, + json!({ + "message": "Say hello.", + "budget": {"turns": 4, "seconds": 120, "window": 24000}, + "probes": [{"id": "ran", "kind": "must_show", "text": "the run has a transcript"}] + }), + &[], + ) + .await; + let recorded = || { + json!([{"id": "timeline-tree/branch-description", "bytes": TEXT.len(), + "fingerprint": fingerprint(TEXT)}]) + }; + let run = |arm: &str, run: usize, texts: Option| { + let mut record = json!({"arm": arm, "scenario": "case", "run": run, + "session": null, "stop": "idle", "turns": 2, "window": 24000.0, + "durationMs": 1.0, "failed": false, "judgeOutcome": "judged", + "error": null, "judgeError": null, "judgeReasks": 0, + "probes": [{"id": "ran", "kind": "must_show", + "verdict": "present", "quote": null}]}); + if let Some(texts) = texts { + record["texts"] = texts; + } + record + }; + let source = |name: &str, runs: &[Value]| { + let directory = fixture.directory.join(name); + for arm in ["current", "candidate"] { + let views = directory.join("outputs").join(arm).join("case"); + std::fs::create_dir_all(&views).unwrap(); + for run in 0..2 { + std::fs::write( + views.join(format!("run-{run}.judge-view.jsonl")), + "SAVED VIEW", + ) + .unwrap(); + } + } + let jsonl: String = runs.iter().map(|record| format!("{record}\n")).collect(); + std::fs::write(directory.join("runs.jsonl"), &jsonl).unwrap(); + directory + }; + let mixed_current = source( + "mixed-current", + &[ + run("current", 0, None), + run("current", 1, Some(recorded())), + run("candidate", 0, Some(recorded())), + run("candidate", 1, Some(recorded())), + ], + ); + let mut options = fixture.options(fixture.directory.join("rejudged-current")); + options.rejudge = Some(mixed_current); + let error = fixture.rejudge(&options).await.unwrap_err().to_string(); + assert!( + error.contains( + "--rejudge: the current runs mix records that name their configured texts" + ), + "{error}" + ); + assert!( + error.contains("report the runs that name their texts and the older runs separately"), + "{error}" + ); + // The candidate arm is checked on its own: its runs mix while the + // current arm recorded none. + let mixed_candidate = source( + "mixed-candidate", + &[ + run("current", 0, None), + run("current", 1, None), + run("candidate", 0, None), + run("candidate", 1, Some(recorded())), + ], + ); + let mut options = fixture.options(fixture.directory.join("rejudged-candidate")); + options.rejudge = Some(mixed_candidate); + let error = fixture.rejudge(&options).await.unwrap_err().to_string(); + assert!( + error.contains( + "--rejudge: the candidate runs mix records that name their configured texts" + ), + "{error}" + ); + assert!( + fixture.judge().is_empty(), + "a mixed set is refused before any judge call" + ); + } + /// A report over saved runs counts the declines their records carry and /// says how many records carry none: a record written before the runner /// counted them is not read as no declines. From 88cd4df522a9cb83b7565eeb071cf885fb28f55d Mon Sep 17 00:00:00 2001 From: huihui Date: Mon, 23 Nov 2026 08:33:19 +0800 Subject: [PATCH 16/35] test(branch): drive the switched-line compaction with the flow model The test opens a second tool line after the first one is switched in. With the echo model, a child's idle notice and the branch call can enter one request, and the echo model answers it without calling the branch tool, so the second tool result never arrives. The flow model drops the branch markers before it answers, which keeps the second open line's tool call. --- crates/dim-agent-capabilities/tests/branch_flow.rs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/crates/dim-agent-capabilities/tests/branch_flow.rs b/crates/dim-agent-capabilities/tests/branch_flow.rs index efb2bf190b..f4a70562e7 100644 --- a/crates/dim-agent-capabilities/tests/branch_flow.rs +++ b/crates/dim-agent-capabilities/tests/branch_flow.rs @@ -9705,7 +9705,7 @@ async fn a_switched_line_keeps_its_identity_after_a_compaction() { MemoryTimelineStore::default(), ))) .session_value(Arc::new(HistoryRenderer::default())) - .process_value(Arc::new(ModelHost(Arc::new(EchoModel)))) + .process_value(Arc::new(ModelHost(Arc::new(FlowModel)))) .session_value(Arc::new(ToolHost(Arc::new(MockTools)))) .session_value(Arc::new(PrepareContextHost(Arc::new(IdentityContext)))) .session_value(Arc::new(ContextModelHost(Some(Arc::new(Compact))))) From 82907b852aa8149b4d8079e8a7cd4175646e78b5 Mon Sep 17 00:00:00 2001 From: huihui Date: Mon, 23 Nov 2026 09:10:10 +0800 Subject: [PATCH 17/35] test(xtask): add the user-line switch scenario and its fixture flow The scenario creates a user line, lets main open a tool line, moves the default branch to the tool line and then to the user line, and sends an input to each. The fixture flow runs the committed directory and asserts that both note policies reach the lines' requests. The commit alone cannot pass: the runner has no multi-move step, no user-line role and no former-default input yet, so the committed set does not parse the moves. --- .../user-line-becomes-default/scenario.json | 32 +++ .../workspace/README.md | 15 ++ .../workspace/test_token.py | 13 ++ .../workspace/token.py | 17 ++ xtask/src/scenario_eval.rs | 189 +++++++++++++++++- 5 files changed, 265 insertions(+), 1 deletion(-) create mode 100644 xtask/scenario-eval/timeline-branches/user-line-becomes-default/scenario.json create mode 100644 xtask/scenario-eval/timeline-branches/user-line-becomes-default/workspace/README.md create mode 100644 xtask/scenario-eval/timeline-branches/user-line-becomes-default/workspace/test_token.py create mode 100644 xtask/scenario-eval/timeline-branches/user-line-becomes-default/workspace/token.py diff --git a/xtask/scenario-eval/timeline-branches/user-line-becomes-default/scenario.json b/xtask/scenario-eval/timeline-branches/user-line-becomes-default/scenario.json new file mode 100644 index 0000000000..ee3ee1a587 --- /dev/null +++ b/xtask/scenario-eval/timeline-branches/user-line-becomes-default/scenario.json @@ -0,0 +1,32 @@ +{ + "description": "The user's own line becomes the default branch while a tool line holds it; the user-line note and the former-default note reach the lines' requests", + "message": "Open one line to diagnose the early-expiry bug in token.py and write the diagnosis to notes.md. While it works, check README.md for steps that no longer match the code.", + "calls": [ + { + "method": "session.branch_create", + "params": { + "parentBranchId": "main", + "at": 0, + "prompt": "Review README.md's install and test steps against token.py and test_token.py, and report every step that is stale. Do not change any file yet." + } + } + ], + "moves": [ + { + "to": {"role": "latest_tool_line"}, + "message": "Continue the diagnosis here. Write notes.md with what you found and report it to the user." + }, + { + "to": {"role": "user_line"}, + "message": "Take the session's conversation from here. Finish the README review and report the stale steps, then wait for the next request.", + "formerMessage": "Report your diagnosis to the user now, and keep coordinating any line you opened. Do not change files outside the diagnosis." + } + ], + "budget": {"turns": 30, "seconds": 900, "window": 131072}, + "probes": [ + {"id": "user-line-carries-the-work", "kind": "must_show", "text": "after the user's line became the default branch, it answers the user's request from its own context and carries its own work forward instead of ending itself or handing it to another line"}, + {"id": "former-default-answers-and-coordinates", "kind": "must_show", "text": "after the tool line lost the default branch, it answers the input addressed to it and stays ready to coordinate any line it opened"}, + {"id": "former-default-leaves-the-new-scope", "kind": "must_not_show", "text": "after the tool line lost the default branch, it opens a new line or edits files outside its remaining scope"}, + {"id": "user-line-does-not-end-itself", "kind": "must_not_show", "text": "the user's line calls end on itself after it became the default branch"} + ] +} diff --git a/xtask/scenario-eval/timeline-branches/user-line-becomes-default/workspace/README.md b/xtask/scenario-eval/timeline-branches/user-line-becomes-default/workspace/README.md new file mode 100644 index 0000000000..0402a00d16 --- /dev/null +++ b/xtask/scenario-eval/timeline-branches/user-line-becomes-default/workspace/README.md @@ -0,0 +1,15 @@ +# auth-tools + +`token.py` issues and validates access tokens. + +## Install + + python3 -m pip install -r requirements.txt + +## Test + + python3 -m pytest tests + +## Requirements + +Python 3.6 or newer. diff --git a/xtask/scenario-eval/timeline-branches/user-line-becomes-default/workspace/test_token.py b/xtask/scenario-eval/timeline-branches/user-line-becomes-default/workspace/test_token.py new file mode 100644 index 0000000000..2132a2878c --- /dev/null +++ b/xtask/scenario-eval/timeline-branches/user-line-becomes-default/workspace/test_token.py @@ -0,0 +1,13 @@ +import unittest + +import token + + +class TokenTest(unittest.TestCase): + def test_token_lasts_the_ttl(self): + issued = token.issue(ttl=60) + self.assertAlmostEqual(issued["expires_at"] - issued["issued_at"], 60, delta=1) + + +if __name__ == "__main__": + unittest.main() diff --git a/xtask/scenario-eval/timeline-branches/user-line-becomes-default/workspace/token.py b/xtask/scenario-eval/timeline-branches/user-line-becomes-default/workspace/token.py new file mode 100644 index 0000000000..280174f932 --- /dev/null +++ b/xtask/scenario-eval/timeline-branches/user-line-becomes-default/workspace/token.py @@ -0,0 +1,17 @@ +"""Issues and validates access tokens.""" + +import time + +DEFAULT_TTL = 60 + + +def issue(ttl=DEFAULT_TTL): + """Issues a token that expires after ttl seconds.""" + issued_at = time.time() + return {"value": "token", "issued_at": issued_at, "expires_at": issued_at + ttl // 2} + + +def expired(token, now=None): + """Whether the token has expired.""" + now = time.time() if now is None else now + return now >= token["expires_at"] diff --git a/xtask/src/scenario_eval.rs b/xtask/src/scenario_eval.rs index 2737ef88d5..3cf66536f3 100644 --- a/xtask/src/scenario_eval.rs +++ b/xtask/src/scenario_eval.rs @@ -9018,8 +9018,9 @@ mod tests { "sibling-relay", "switch-continue-directly", "switch-then-open-lines", + "user-line-becomes-default", ], - "the committed branch set is the fifteen scenarios" + "the committed branch set is the sixteen scenarios" ); assert_eq!( compact @@ -17294,6 +17295,192 @@ mod tests { "the member declares no plugin tool: {offered:?}" ); } + + /// The two note policies the user-line move turns on reach the model, on + /// the committed scenario: its `session.branch_create` call opens a user + /// line, main opens a tool line, and the move goes from main to the tool + /// line and then to the user line, after which the tool line and the user + /// line each receive an input. The current arm's requests carry no + /// guidance block, and the candidate arm carries each note with its + /// `{other}` placeholder replaced by the line id (Timeline branches §12.4, + /// model-prompts §9.8). + #[tokio::test(flavor = "multi_thread", worker_threads = 4)] + async fn the_user_line_switch_carries_both_notes_into_the_requests() { + const DESCRIPTION: &str = "CANDIDATE BRANCH TOOL DESCRIPTION"; + const BASELINE_DESCRIPTION: &str = "BASELINE BRANCH TOOL DESCRIPTION"; + const DEFAULT_NOTE: &str = + "- CANDIDATE default guidance for {parent}, switched from {other}."; + const USER_NOTE: &str = "- CANDIDATE user-line guidance for {other}."; + const FORMER_NOTE: &str = "- CANDIDATE former-default guidance for {other}."; + let case = repository() + .join("xtask/scenario-eval/timeline-branches/user-line-becomes-default"); + let scenario: Value = + serde_json::from_slice(&std::fs::read(case.join("scenario.json")).unwrap()).unwrap(); + let workspace: Vec<(String, String)> = workspace_files(&case) + .into_iter() + .map(|(path, text)| { + ( + path.strip_prefix("workspace") + .expect("a file under workspace") + .to_string_lossy() + .into_owned(), + text, + ) + }) + .collect(); + let workspace: Vec<(&str, &str)> = workspace + .iter() + .map(|(path, text)| (path.as_str(), text.as_str())) + .collect(); + let fixture = Fixture::with_window( + "user-line-notes", + user_line_notes, + scenario, + &workspace, + 131_072, + ) + .await; + let mut options = fixture.options(fixture.directory.join("out")); + options.baseline = pairs(&[ + ("timeline-tree/branch-description", BASELINE_DESCRIPTION), + ("timeline-tree/default-note", ""), + ("timeline-tree/user-default-note", ""), + ("timeline-tree/former-default-note", ""), + ]); + options.texts = pairs(&[ + ("timeline-tree/branch-description", DESCRIPTION), + ("timeline-tree/default-note", DEFAULT_NOTE), + ("timeline-tree/user-default-note", USER_NOTE), + ("timeline-tree/former-default-note", FORMER_NOTE), + ]); + let report = fixture.evaluate(&options).await.unwrap(); + assert!( + report.contains("candidate is inconclusive: no comparison is a regression"), + "{report}" + ); + let records = fixture.records(&options.out); + assert_eq!(records.len(), 2, "one run per arm"); + for record in &records { + assert_eq!( + record["failed"], false, + "the scenario reaches idle on every line: {record}" + ); + } + for arm in ["current", "candidate"] { + let directory = options.out.join("outputs").join(arm).join("case"); + let export = std::fs::read_to_string(directory.join("run-0.timeline.jsonl")).unwrap(); + let created = |kind: &str| -> String { + export + .lines() + .filter_map(|line| serde_json::from_str::(line).ok()) + .find(|line| { + line["event"]["type"] == "branch" + && line["event"]["name"] == "create" + && line["event"]["data"]["source"]["kind"] == kind + }) + .and_then(|line| line["event"]["data"]["branch"].as_str().map(str::to_owned)) + .unwrap_or_else(|| panic!("{arm}: a {kind} line was created")) + }; + let tool = created("tool"); + let user = created("user"); + let requests = fixture.arm(arm); + let descriptions: Vec = requests + .iter() + .filter_map(|request| { + let request: Value = serde_json::from_str(request).ok()?; + request["tools"].as_array()?.iter().find_map(|tool| { + (tool["function"]["name"] == "branch") + .then(|| { + tool["function"]["description"] + .as_str() + .map(str::to_owned) + }) + .flatten() + }) + }) + .collect(); + let expected_description = if arm == "current" { + BASELINE_DESCRIPTION + } else { + DESCRIPTION + }; + assert!( + !descriptions.is_empty() + && descriptions + .iter() + .all(|description| description == expected_description), + "{arm}: the branch tool description is the pair's text: {descriptions:?}" + ); + if arm == "current" { + assert!( + requests + .iter() + .all(|request| !carried(request, "How you work here:")), + "the empty note baselines write no guidance block" + ); + continue; + } + let user_note = format!( + "How you work here:\n{}", + USER_NOTE.replace("{other}", &tool) + ); + assert!( + requests.iter().any(|request| carried(request, &user_note)), + "the user line's request carries its note with the tool line id: {user_note}" + ); + let former_note = format!( + "How you work here:\n{}", + FORMER_NOTE.replace("{other}", &user) + ); + assert!( + requests + .iter() + .any(|request| carried(request, &former_note)), + "the former default line's request carries its note with the user line id: {former_note}" + ); + for attribute in [ + format!( + "" + ), + format!( + "" + ), + ] { + assert!( + requests + .iter() + .any(|request| carried(request, &attribute)), + "a request carries {attribute}" + ); + } + } + } + + /// The run model of the user-line scenario: main opens the tool line on + /// its first request, every line answers with text, and the judge gives + /// each probe its verdict. A request that carries the tool result or a + /// line's birth identity is not main's first: the tool's result says + /// `Line created:`, and a line's first input says `You are line `. + fn user_line_notes(text: &str) -> Option { + if text.contains("You check statements") { + return Some(content( + r#"[{"id":"user-line-carries-the-work","verdict":"present","quote":"turn/end"}, + {"id":"former-default-answers-and-coordinates","verdict":"present","quote":"turn/end"}, + {"id":"former-default-leaves-the-new-scope","verdict":"absent","quote":"nothing"}, + {"id":"user-line-does-not-end-itself","verdict":"absent","quote":"nothing"}]"#, + )); + } + if text.contains("Open one line to diagnose the early-expiry bug") + && !text.contains("Line created:") + && !text.contains("You are line ") + { + return Some(tool_call( + "branch", + r#"{"action":"create","prompt":"diagnose the early-expiry bug in token.py and write notes.md"}"#, + )); + } + Some(content("Done.")) + } } #[cfg(test)] From 638ae49520d293b02e870dd71b8ad681165993e0 Mon Sep 17 00:00:00 2001 From: huihui Date: Mon, 23 Nov 2026 09:11:28 +0800 Subject: [PATCH 18/35] feat(xtask): move the default branch to a user line and wake the former one A scenario can name the line its session.branch_create call opened as the move's target, and can state several moves: each later one runs right after the one before it, on a line that may already have started its first turn. A move can also carry the input for the line it moved away from, because the note a move writes goes in as append input and an append input never starts a turn. --- xtask/src/scenario_eval.rs | 439 ++++++++++++++++++++++++++++++------- 1 file changed, 354 insertions(+), 85 deletions(-) diff --git a/xtask/src/scenario_eval.rs b/xtask/src/scenario_eval.rs index 3cf66536f3..f6b2d1280c 100644 --- a/xtask/src/scenario_eval.rs +++ b/xtask/src/scenario_eval.rs @@ -308,7 +308,7 @@ use rutis::Ctx; use rutis::host::{BoxFuture, CtxHost, DynPlugin, Effect, Key, TypeKey}; use serde_json::{Value, json}; use std::{ - collections::{BTreeMap, BTreeSet}, + collections::{BTreeMap, BTreeSet, VecDeque}, ffi::{OsStr, OsString}, path::{Component, Path, PathBuf}, process::Stdio, @@ -2003,6 +2003,13 @@ struct ScenarioFile { /// The mid-run move of the default branch, when the scenario runs one. #[serde(default)] switch: Option, + /// The mid-run moves of the default branch, in order, when the scenario + /// runs more than one: the first waits for its target line's first + /// `turn/start` like `switch`, and each later one moves right after the + /// one before it. `switch` stays the one-move spelling the committed + /// scenarios use. + #[serde(default)] + moves: Vec, budget: Budget, probes: Vec, } @@ -2024,6 +2031,12 @@ pub(crate) struct Switch { /// switch. #[serde(default)] pub(crate) branch_id: Option, + /// An input sent to the line this move moved away from, after the move + /// and the next input. The note a move writes goes in as `append` input, + /// and an append input never starts a turn, so an idle line that lost the + /// default branch needs this input to answer at all. + #[serde(default)] + pub(crate) former_message: Option, } /// The line a [`Switch`] moves to, by role or by id. @@ -2035,11 +2048,13 @@ pub(crate) enum SwitchTarget { } /// The role a [`SwitchTarget`] names. A tool line is a line the branch tool -/// opened; the latest one is the line most recently opened that way. +/// opened; the latest one is the line most recently opened that way. A user +/// line is the line the scenario's last `session.branch_create` call opened. #[derive(Clone, Copy, serde::Serialize, serde::Deserialize, PartialEq, Eq)] #[serde(rename_all = "snake_case")] pub(crate) enum SwitchRole { LatestToolLine, + UserLine, } /// How many further moves a switch makes while the target line is not @@ -2059,15 +2074,19 @@ struct PendingSwitch { retries_left: u32, } impl PendingSwitch { - fn new(switch: Switch) -> Self { + /// `chained` switches fire right after the move before them instead of + /// waiting for their target's first `turn/start`: a second move runs on + /// a line that may have started its first turn before the run reached it. + fn new(switch: Switch, user_line: Option<&str>, chained: bool) -> Self { let line = match &switch.to { SwitchTarget::Id(id) => Some(id.clone()), - SwitchTarget::Role(_) => None, + SwitchTarget::Role(SwitchRole::UserLine) => user_line.map(str::to_owned), + SwitchTarget::Role(SwitchRole::LatestToolLine) => None, }; Self { switch, line, - triggered: false, + triggered: chained, retries_left: UNKNOWN_BRANCH_RETRIES, } } @@ -2078,14 +2097,13 @@ impl PendingSwitch { /// afterwards has its own purpose, and the move and the input after it /// stay with the line that started. fn notice(&mut self, branch: &str, event: &Value) { - if self.triggered { - return; - } if event["type"] == "branch" && event["name"] == "create" { - if matches!( - &self.switch.to, - SwitchTarget::Role(SwitchRole::LatestToolLine) - ) && event["data"]["source"]["kind"] == "tool" + if (!self.triggered || self.line.is_none()) + && matches!( + &self.switch.to, + SwitchTarget::Role(SwitchRole::LatestToolLine) + ) + && event["data"]["source"]["kind"] == "tool" && let Some(line) = event["data"]["branch"].as_str() { self.line = Some(line.to_owned()); @@ -2232,6 +2250,9 @@ pub(crate) struct Scenario { /// The mid-run move of the default branch, when the scenario runs one. #[serde(default)] pub(crate) switch: Option, + /// The mid-run moves after `switch`, in order. + #[serde(default)] + pub(crate) moves: Vec, pub(crate) budget: Budget, probes: Vec, } @@ -2296,7 +2317,7 @@ fn into_scenario( } } } - if let Some(switch) = &raw.switch { + for switch in raw.switch.iter().chain(&raw.moves) { if switch.message.trim().is_empty() { return Err("a switch needs the input to send after the move".into()); } @@ -2312,6 +2333,28 @@ fn into_scenario( { return Err("a switch names an empty branch for its input".into()); } + if switch + .former_message + .as_deref() + .is_some_and(|message| message.trim().is_empty()) + { + return Err("a switch's former-default input is empty".into()); + } + } + if !raw + .calls + .iter() + .any(|call| call.method == "session.branch_create") + && raw + .switch + .iter() + .chain(&raw.moves) + .any(|switch| matches!(switch.to, SwitchTarget::Role(SwitchRole::UserLine))) + { + return Err( + "a switch to the user line needs a session.branch_create call before the message" + .into(), + ); } for call in &raw.calls { if call.method.trim().is_empty() { @@ -2431,6 +2474,7 @@ fn into_scenario( events: raw.events, steers: raw.steers, switch: raw.switch, + moves: raw.moves, budget: raw.budget, probes: raw.probes, }) @@ -5946,20 +5990,31 @@ async fn drive( return driven; } } + // The line the scenario's last `session.branch_create` call opened: a + // switch names it by role, and the reply is where its id is known before + // the run starts. + let mut user_line: Option = None; for (index, call) in scenario.calls.iter().enumerate() { let mut params = match &call.params { Value::Object(params) => params.clone(), _ => serde_json::Map::new(), }; params.insert("sessionId".to_owned(), json!(session)); - if let Err(error) = client.rpc(&call.method, Value::Object(params)).await { - driven.stop = "error"; - driven.error = Some(format!( - "the calls step {} ({}) failed: {error}", - index + 1, - call.method - )); - return driven; + match client.rpc(&call.method, Value::Object(params)).await { + Ok(reply) => { + if call.method == "session.branch_create" { + user_line = reply["branch"]["branchId"].as_str().map(str::to_owned); + } + } + Err(error) => { + driven.stop = "error"; + driven.error = Some(format!( + "the calls step {} ({}) failed: {error}", + index + 1, + call.method + )); + return driven; + } } } for source in &scenario.sources { @@ -5997,7 +6052,27 @@ async fn drive( .cloned() .map(|steer| (steer, false)) .collect(); - let mut switch = scenario.switch.clone().map(PendingSwitch::new); + // The moves still to make, in order, and the default branch they move + // away from. A chained move fires right after the one before it. + let mut switches: VecDeque = scenario + .switch + .iter() + .chain(&scenario.moves) + .enumerate() + .map(|(index, switch)| PendingSwitch::new(switch.clone(), user_line.as_deref(), index > 0)) + .collect(); + if switches.iter().any(|pending| { + matches!(pending.switch.to, SwitchTarget::Role(SwitchRole::UserLine)) + && pending.line.is_none() + }) { + driven.stop = "error"; + driven.error = Some( + "the switch to the user line has no line: the scenario's session.branch_create call answered no branch id" + .into(), + ); + return driven; + } + let mut default = "main".to_owned(); let mut last_event = Instant::now(); // The events still to publish, and whether each was. let mut events: Vec<(EventSpec, bool)> = scenario @@ -6059,10 +6134,12 @@ async fn drive( // The move and the input after it are bounded by the same absolute // deadline the budget check below applies: a reply that never comes // must not hold the run past its wall clock (model-prompts §8.1). - let line = switch.as_ref().and_then(|pending| pending.line.clone()); + let line = switches + .front() + .and_then(|pending| pending.line.clone()); let fired = match tokio::time::timeout( time_left(started, &scenario.budget), - fire_switch(client, &session, &mut switch), + fire_switch(client, &session, &mut switches, &mut default), ) .await { @@ -6120,7 +6197,7 @@ async fn drive( // first in this pass, so a subscription the model made in its last // turn has already started the clock and keeps the run open here // (EventHub design A.4). - let pending = switch.is_some() + let pending = !switches.is_empty() || steers.iter().any(|(_, fired)| !fired) || events.iter().any(|(event, fired)| { !fired @@ -6187,7 +6264,7 @@ async fn drive( return driven; } } - if let Some(pending) = switch.as_mut() { + if let Some(pending) = switches.front_mut() { pending.notice(&branch, &event); } match fire_triggered(client, &session, &mut steers, &event).await { @@ -6315,7 +6392,7 @@ async fn drive( } } } - if let Some(pending) = &switch { + if let Some(pending) = switches.front() { let reason = match (&pending.line, pending.triggered) { (Some(line), true) => format!( "the move to line {line} did not complete before the run stopped on {}", @@ -6326,7 +6403,7 @@ async fn drive( driven.stop ), (None, _) => format!( - "the switch never fired: no tool line was opened before the run stopped on {}", + "the switch never fired: the line its role names was never opened before the run stopped on {}", driven.stop ), }; @@ -7242,25 +7319,26 @@ fn unknown_branch(error: &dim_client::Error) -> bool { .is_some_and(|error| error.message.starts_with("unknown branch:")) } -/// Runs the scenario's switch once the target line has started its first turn: -/// the Session's default branch moves first, then the next input is submitted, -/// naming a line only when the scenario does. A switch fires once; a later -/// call leaves it unfired. +/// Runs the next move once it is due: the Session's default branch moves +/// first, then the next input is submitted, naming a line only when the +/// scenario does, and then the input meant for the line it moved away from. +/// A move fires once and leaves the queue; the move after it fires on the next +/// call. async fn fire_switch( client: &mut impl SwitchClient, session: &str, - switch: &mut Option, + switches: &mut VecDeque, + default: &mut String, ) -> std::result::Result { - let Some(pending) = switch.as_mut() else { + let Some(pending) = switches.front_mut() else { return Ok(SwitchFire::NotFired); }; if !pending.triggered { return Ok(SwitchFire::NotFired); } - let line = pending - .line - .clone() - .expect("a triggered switch names its line"); + let Some(line) = pending.line.clone() else { + return Ok(SwitchFire::NotFired); + }; if let Err(error) = client .rpc( "session.branch_set_default", @@ -7269,7 +7347,7 @@ async fn fire_switch( .await { if let Some("branch_ended" | "branch_target_protected") = dim_client::app_error(&error) { - switch.take(); + switches.pop_front(); return Ok(SwitchFire::TargetEnded { line: line.clone(), error: error.to_string(), @@ -7280,7 +7358,7 @@ async fn fire_switch( pending.retries_left -= 1; return Ok(SwitchFire::Retry); } - switch.take(); + switches.pop_front(); return Ok(SwitchFire::TargetUnknown { line: line.clone(), error: error.to_string(), @@ -7288,7 +7366,11 @@ async fn fire_switch( } return Err(format!("the switch to {line} failed: {error}")); } - let pending = switch.take().expect("the switch is pending"); + let pending = switches.pop_front().expect("the switch is pending"); + if let Some(next) = switches.front_mut() { + next.triggered = true; + } + let former = std::mem::replace(default, line); submit( client, session, @@ -7297,6 +7379,9 @@ async fn fire_switch( pending.switch.branch_id.as_deref(), ) .await?; + if let Some(message) = pending.switch.former_message.as_deref() { + submit(client, session, message, None, Some(former.as_str())).await?; + } Ok(SwitchFire::Fired) } @@ -8399,6 +8484,7 @@ mod tests { events: Vec::new(), steers: Vec::new(), switch: None, + moves: Vec::new(), budget: Budget { turns: 4, seconds: 60., @@ -8671,11 +8757,16 @@ mod tests { json!({"type": "branch", "name": "create", "data": {"branch": branch, "source": {"kind": kind}}}) }; - let mut pending = PendingSwitch::new(Switch { - to: SwitchTarget::Role(SwitchRole::LatestToolLine), - message: "next".into(), - branch_id: None, - }); + let mut pending = PendingSwitch::new( + Switch { + to: SwitchTarget::Role(SwitchRole::LatestToolLine), + message: "next".into(), + branch_id: None, + former_message: None, + }, + None, + false, + ); pending.notice("main", &turn_start); assert!(!pending.triggered, "main's turn starts no switch"); pending.notice("main", &create("2", "tool")); @@ -8685,11 +8776,16 @@ mod tests { pending.notice("2", &turn_start); assert!(pending.triggered, "the target's first turn start is"); assert_eq!(pending.line.as_deref(), Some("2")); - let mut pending = PendingSwitch::new(Switch { - to: SwitchTarget::Role(SwitchRole::LatestToolLine), - message: "next".into(), - branch_id: None, - }); + let mut pending = PendingSwitch::new( + Switch { + to: SwitchTarget::Role(SwitchRole::LatestToolLine), + message: "next".into(), + branch_id: None, + former_message: None, + }, + None, + false, + ); pending.notice("main", &create("2", "tool")); pending.notice("3", &turn_start); assert!(!pending.triggered, "another line's turn starts no switch"); @@ -8699,15 +8795,170 @@ mod tests { !pending.triggered, "a line the user opened is not a tool line" ); - let mut pending = PendingSwitch::new(Switch { - to: SwitchTarget::Id("4".into()), - message: "next".into(), - branch_id: None, - }); + let mut pending = PendingSwitch::new( + Switch { + to: SwitchTarget::Id("4".into()), + message: "next".into(), + branch_id: None, + former_message: None, + }, + None, + false, + ); pending.notice("4", &turn_start); assert!(pending.triggered); } + /// A scenario's moves can end on the line its `session.branch_create` call + /// opened, and a move can carry the input for the line it moved away from: + /// the role and that input parse, and a user-line move without the call is + /// refused before any run (design §12.3). + #[test] + fn a_move_names_the_user_line_and_the_input_for_the_former_default() { + let directory = std::env::temp_dir().join(format!( + "dim-scenario-eval-user-line-{}", + std::process::id() + )); + std::fs::create_dir_all(directory.join("workspace")).unwrap(); + let parse = |moves: Value, calls: Value| { + let file: ScenarioFile = serde_json::from_value(json!({ + "message": "first", + "calls": calls, + "moves": moves, + "budget": {"turns": 3, "seconds": 60, "window": 1000}, + "probes": [{"id": "ran", "kind": "must_show", "text": "it ran"}] + })) + .unwrap(); + into_scenario("case".into(), directory.clone(), file) + }; + let create = json!([{"method": "session.branch_create", + "params": {"parentBranchId": "main", "at": 0, + "prompt": "the user's line"}}]); + let scenario = parse( + json!([ + {"to": {"role": "latest_tool_line"}, "message": "second"}, + {"to": {"role": "user_line"}, "message": "third", + "formerMessage": "report to the user"} + ]), + create.clone(), + ) + .unwrap(); + assert_eq!(scenario.moves.len(), 2); + assert!(matches!( + scenario.moves[1].to, + SwitchTarget::Role(SwitchRole::UserLine) + )); + assert_eq!( + scenario.moves[1].former_message.as_deref(), + Some("report to the user") + ); + assert!( + scenario.switch.is_none(), + "a scenario with several moves states them under moves" + ); + let Err(error) = parse( + json!([{"to": {"role": "user_line"}, "message": "second"}]), + json!([]), + ) else { + panic!("a user-line move without the call is refused"); + }; + assert!(error.contains("session.branch_create"), "{error}"); + let Err(error) = parse( + json!([{"to": {"id": "3"}, "message": "second", + "formerMessage": " "}]), + create, + ) else { + panic!("an empty former-default input is refused"); + }; + assert!(error.contains("former-default input is empty"), "{error}"); + let _ = std::fs::remove_dir_all(directory); + } + + /// A second move fires right after the first, and a move that names a + /// former-default input sends it to the line it moved away from: the note + /// a move writes goes in as `append` input, which never starts a turn, so + /// that input is the only thing that brings the former default line's + /// answer (model-prompts §9.8). + #[tokio::test] + async fn a_second_move_fires_after_the_first_and_wakes_the_former_default() { + let create = |line: &str| { + json!({"type": "branch", "name": "create", + "data": {"branch": line, "source": {"kind": "tool"}}}) + }; + let turn_start = json!({"type": "turn", "name": "start", "data": {}}); + let mut first = PendingSwitch::new( + Switch { + to: SwitchTarget::Role(SwitchRole::LatestToolLine), + message: "to the tool line".into(), + branch_id: None, + former_message: None, + }, + None, + false, + ); + first.notice("main", &create("2")); + first.notice("2", &turn_start); + let second = PendingSwitch::new( + Switch { + to: SwitchTarget::Role(SwitchRole::UserLine), + message: "to the user line".into(), + branch_id: None, + former_message: Some("to the former default".into()), + }, + Some("3"), + true, + ); + assert!( + second.triggered, + "a chained move fires after the move before it" + ); + let mut switches: VecDeque = [first, second].into(); + let mut default = "main".to_owned(); + let mut client = SwitchRecorder::default(); + for move_number in [1, 2] { + assert!( + matches!( + fire_switch(&mut client, "session", &mut switches, &mut default).await, + Ok(SwitchFire::Fired) + ), + "move {move_number}" + ); + } + assert!(matches!( + fire_switch(&mut client, "session", &mut switches, &mut default).await, + Ok(SwitchFire::NotFired) + )); + let calls: Vec<&str> = client + .calls + .iter() + .map(|(method, _)| method.as_str()) + .collect(); + assert_eq!( + calls, + [ + "session.branch_set_default", + "session.submit", + "session.branch_set_default", + "session.submit", + "session.submit" + ], + "each move runs before its input, and the former default's input follows the move" + ); + assert_eq!(client.calls[0].1["branchId"], "2"); + assert_eq!(client.calls[2].1["branchId"], "3"); + assert_eq!(client.calls[3].1["text"], "to the user line"); + assert!( + client.calls[3].1.get("branchId").is_none(), + "the next input lands on the new default branch" + ); + assert_eq!(client.calls[4].1["text"], "to the former default"); + assert_eq!( + client.calls[4].1["branchId"], "2", + "the former-default input names the line the move moved away from" + ); + assert_eq!(default, "3", "the last move holds the default branch"); + } + /// A switch that has started its target stays with it: a tool line opened /// afterwards has its own purpose, so the retry of a move promotes the /// line that started rather than the newer line (model-prompts §9.8). @@ -8718,12 +8969,18 @@ mod tests { "data": {"branch": line, "source": {"kind": "tool"}}}) }; let turn_start = json!({"type": "turn", "name": "start", "data": {}}); - let mut switch = Some(PendingSwitch::new(Switch { - to: SwitchTarget::Role(SwitchRole::LatestToolLine), - message: "next".into(), - branch_id: None, - })); - let pending = switch.as_mut().expect("the switch is pending"); + let mut switch: VecDeque = vec![PendingSwitch::new( + Switch { + to: SwitchTarget::Role(SwitchRole::LatestToolLine), + message: "next".into(), + branch_id: None, + former_message: None, + }, + None, + false, + )] + .into(); + let pending = switch.front_mut().expect("the switch is pending"); pending.notice("main", &create("A")); pending.notice("A", &turn_start); assert!(pending.triggered); @@ -8732,10 +8989,10 @@ mod tests { ..SwitchRecorder::default() }; assert!(matches!( - fire_switch(&mut client, "session", &mut switch).await, + fire_switch(&mut client, "session", &mut switch, &mut "main".into()).await, Ok(SwitchFire::Retry) )); - let pending = switch.as_mut().expect("the retry keeps the switch"); + let pending = switch.front_mut().expect("the retry keeps the switch"); pending.notice("main", &create("B")); assert_eq!( pending.line.as_deref(), @@ -8743,7 +9000,7 @@ mod tests { "the line that started keeps the move" ); assert!(matches!( - fire_switch(&mut client, "session", &mut switch).await, + fire_switch(&mut client, "session", &mut switch, &mut "main".into()).await, Ok(SwitchFire::Fired) )); let calls: Vec<&str> = client @@ -8784,16 +9041,21 @@ mod tests { } } - /// A switch whose target has started its first turn, ready to move. - fn triggered_switch() -> Option { - let mut pending = PendingSwitch::new(Switch { - to: SwitchTarget::Id("2".into()), - message: "next".into(), - branch_id: None, - }); + /// A move whose target has started its first turn, ready to move. + fn triggered_switch() -> VecDeque { + let mut pending = PendingSwitch::new( + Switch { + to: SwitchTarget::Id("2".into()), + message: "next".into(), + branch_id: None, + former_message: None, + }, + None, + false, + ); pending.notice("2", &json!({"type": "turn", "name": "start", "data": {}})); assert!(pending.triggered); - Some(pending) + vec![pending].into() } /// The tree's `unknown_branch` as the Session protocol answers it: the @@ -8814,7 +9076,7 @@ mod tests { let mut client = SwitchRecorder::default(); let mut switch = triggered_switch(); assert!(matches!( - fire_switch(&mut client, "session", &mut switch).await, + fire_switch(&mut client, "session", &mut switch, &mut "main".into()).await, Ok(SwitchFire::Fired) )); let calls: Vec<&str> = client @@ -8834,7 +9096,7 @@ mod tests { "the next input lands on the new default branch" ); assert!(matches!( - fire_switch(&mut client, "session", &mut switch).await, + fire_switch(&mut client, "session", &mut switch, &mut "main".into()).await, Ok(SwitchFire::NotFired) )); assert_eq!(client.calls.len(), 2, "a switch fires once"); @@ -8852,7 +9114,7 @@ mod tests { ..SwitchRecorder::default() }; let mut switch = triggered_switch(); - let error = match fire_switch(&mut client, "session", &mut switch).await { + let error = match fire_switch(&mut client, "session", &mut switch, &mut "main".into()).await { Err(error) => error, Ok(outcome) => panic!("the move was refused, not {outcome:?}"), }; @@ -8876,12 +9138,15 @@ mod tests { }; let mut switch = triggered_switch(); assert!(matches!( - fire_switch(&mut client, "session", &mut switch).await, + fire_switch(&mut client, "session", &mut switch, &mut "main".into()).await, Ok(SwitchFire::Retry) )); - assert!(switch.is_some(), "the switch stays pending for the retry"); + assert!( + !switch.is_empty(), + "the switch stays pending for the retry" + ); assert!(matches!( - fire_switch(&mut client, "session", &mut switch).await, + fire_switch(&mut client, "session", &mut switch, &mut "main".into()).await, Ok(SwitchFire::Fired) )); let calls: Vec<&str> = client @@ -8899,7 +9164,7 @@ mod tests { "the retry moves before it sends the next input" ); assert_eq!(client.calls[2].1["text"], "next"); - assert!(switch.is_none()); + assert!(switch.is_empty()); } /// A line that never becomes ready is its own outcome after the retry @@ -8916,21 +9181,21 @@ mod tests { for retry in 0..UNKNOWN_BRANCH_RETRIES { assert!( matches!( - fire_switch(&mut client, "session", &mut switch).await, + fire_switch(&mut client, "session", &mut switch, &mut "main".into()).await, Ok(SwitchFire::Retry) ), "retry {retry}" ); - assert!(switch.is_some(), "retry {retry}: still pending"); + assert!(!switch.is_empty(), "retry {retry}: still pending"); } - match fire_switch(&mut client, "session", &mut switch).await { + match fire_switch(&mut client, "session", &mut switch, &mut "main".into()).await { Ok(SwitchFire::TargetUnknown { line, error }) => { assert_eq!(line, "2"); assert!(error.contains("unknown branch"), "{error}"); } outcome => panic!("the unready target is its own outcome, not {outcome:?}"), } - assert!(switch.is_none()); + assert!(switch.is_empty()); assert_eq!( client.calls.len(), UNKNOWN_BRANCH_RETRIES as usize + 1, @@ -8964,7 +9229,7 @@ mod tests { ..SwitchRecorder::default() }; let mut switch = triggered_switch(); - match fire_switch(&mut client, "session", &mut switch).await { + match fire_switch(&mut client, "session", &mut switch, &mut "main".into()).await { Ok(SwitchFire::TargetEnded { line, error }) => { assert_eq!(line, "2"); assert!(error.contains(code), "{code}: {error}"); @@ -13885,6 +14150,7 @@ mod tests { to: SwitchTarget::Id("2".into()), message: "next".into(), branch_id: None, + former_message: None, }); let driven = drive( &mut client, @@ -13933,6 +14199,7 @@ mod tests { to: SwitchTarget::Id("2".into()), message: "next".into(), branch_id: None, + former_message: None, }); let driven = drive( &mut client, @@ -13995,6 +14262,7 @@ mod tests { to: SwitchTarget::Id("2".into()), message: "next".into(), branch_id: None, + former_message: None, }); let driven = tokio::time::timeout( GUARD, @@ -14064,6 +14332,7 @@ mod tests { to: SwitchTarget::Id("2".into()), message: "next".into(), branch_id: None, + former_message: None, }); let cancel = CancellationToken::new(); let model = peer_model(); From 5d447ff61af441c991b75446ad977bc4c2436c49 Mon Sep 17 00:00:00 2001 From: huihui Date: Mon, 23 Nov 2026 09:12:13 +0800 Subject: [PATCH 19/35] test(branch): assert the user-line and former-default notes reach the model request The note a move writes on a line the user opened, and the note on a tool line that lost the default branch, are asserted in the line's ModelCall request body, once with an empty factory member and once with the product default. A third flow pins that the appended note starts no turn, which is why the user-line scenario sends the former default line an input. --- .../tests/branch_flow.rs | 256 ++++++++++++++++++ 1 file changed, 256 insertions(+) diff --git a/crates/dim-agent-capabilities/tests/branch_flow.rs b/crates/dim-agent-capabilities/tests/branch_flow.rs index f4a70562e7..2c362ae1c3 100644 --- a/crates/dim-agent-capabilities/tests/branch_flow.rs +++ b/crates/dim-agent-capabilities/tests/branch_flow.rs @@ -4665,6 +4665,262 @@ async fn the_product_note_block_keeps_its_guidance_heading() { soon(agent.close()).await.unwrap(); } +/// The note a move writes on a line the user opened is the factory member +/// `BranchToolConfig::user_default_note`: an empty member writes the note with +/// no `How you work here:` block, and the product default writes its bullets +/// into the line's next model request, with `{other}` replaced by the line the +/// move moved away from (design §12.1, §12.4). +#[tokio::test(flavor = "multi_thread", worker_threads = 2)] +async fn a_user_lines_default_note_reaches_the_model_request() { + for (configured, heading) in [(Some(""), false), (None, true)] { + let probe = Arc::new(Probe::default()); + let agent = MinimalHost::start(&builder_with_branch_config( + &probe, + BranchToolConfig { + user_default_note: configured.map(Into::into), + ..Default::default() + }, + )) + .await + .unwrap(); + let session = soon(agent.create_session(SessionConfig::default())) + .await + .unwrap(); + let cut = idle_cut(&session, "main").await; + let user = soon(session.branch( + "main".into(), + cut, + BranchOptions { + prompt: "review the docs".into(), + source: BranchSource::User { + operation_id: "client".into(), + }, + }, + )) + .await + .unwrap(); + quiet(&session, &user).await; + switch(&session, &user).await; + owed_notes(&session, &user, 1).await; + soon(session.submit("next request".into(), InputMode::Queue, &user)) + .await + .unwrap(); + soon(session.idle(&user)).await.unwrap(); + let events = local_events(&session, &user).await; + let request = events + .iter() + .rev() + .find_map(|event| match &event.kind { + EventKind::ModelCall(data) => Some(&data.request), + _ => None, + }) + .expect("the user line makes a request after the move"); + let note = request + .messages + .iter() + .map(|message| said(message)) + .find(|text| { + text.starts_with("" + )), + "{note}" + ); + assert!( + note.contains( + "The user has now made this line the session's default branch, switched from line main." + ), + "{note}" + ); + if heading { + assert!( + note.contains( + "\n\nHow you work here:\n- Carry this line's work forward yourself; open a new line only when the four conditions for opening one hold again. The user's request takes precedence over the prompt this line was opened with.\n- Line main stays open in the shared workspace and keeps coordinating any lines it already opened." + ), + "{note}" + ); + } else { + assert!( + !note.contains("How you work here:"), + "an empty member writes no guidance block: {note}" + ); + } + soon(agent.close()).await.unwrap(); + } +} + +/// The note a move writes on the former default branch is the factory member +/// `BranchToolConfig::former_default_note`, for a tool line too: an empty +/// member writes the note with no `How you work here:` block, and the product +/// default writes its bullets into the line's next model request, with +/// `{other}` replaced by the line that holds the default branch (design §12.1, +/// §12.4). +#[tokio::test(flavor = "multi_thread", worker_threads = 2)] +async fn a_former_default_tool_lines_note_reaches_the_model_request() { + for (configured, heading) in [(Some(""), false), (None, true)] { + let probe = Arc::new(Probe::default()); + let agent = MinimalHost::start(&builder_with_branch_config( + &probe, + BranchToolConfig { + former_default_note: configured.map(Into::into), + ..Default::default() + }, + )) + .await + .unwrap(); + let session = soon(agent.create_session(SessionConfig::default())) + .await + .unwrap(); + let line = open_line(&session, "the parser race").await; + switch(&session, &line).await; + owed_notes(&session, &line, 1).await; + let cut = idle_cut(&session, "main").await; + let user = soon(session.branch( + "main".into(), + cut, + BranchOptions { + prompt: "the user line".into(), + source: BranchSource::User { + operation_id: "client".into(), + }, + }, + )) + .await + .unwrap(); + quiet(&session, &user).await; + switch(&session, &user).await; + owed_notes(&session, &line, 2).await; + soon(session.submit("report what you found".into(), InputMode::Queue, &line)) + .await + .unwrap(); + soon(session.idle(&line)).await.unwrap(); + let events = local_events(&session, &line).await; + let request = events + .iter() + .rev() + .find_map(|event| match &event.kind { + EventKind::ModelCall(data) => Some(&data.request), + _ => None, + }) + .expect("the former default line answers the input"); + let note = request + .messages + .iter() + .map(|message| said(message)) + .find(|text| { + text.starts_with("" + )), + "{note}" + ); + assert!( + note.contains(&format!( + "The session's default branch moved from this line to line {user}." + )), + "{note}" + ); + if heading { + assert!( + note.contains( + "\n\nHow you work here:\n- Keep coordinating any open lines you already opened, and answer messages or user inputs addressed to this line.\n- You share the workspace with the other open lines; do not edit files outside your remaining scope unless asked, and if edit or write fails because the file was modified after it was last read, read the file again before continuing." + ), + "{note}" + ); + } else { + assert!( + !note.contains("How you work here:"), + "an empty member writes no guidance block: {note}" + ); + } + soon(agent.close()).await.unwrap(); + } +} + +/// The note a move writes goes in as `append` input, and an append input never +/// starts a turn: the former default line, idle when the move happens, holds +/// the note as its head without making a request for it, and the next input is +/// what wakes it. The user-line scenario sends that input for this reason +/// (design §5, model-prompts §9.8). +#[tokio::test(flavor = "multi_thread", worker_threads = 2)] +async fn an_appended_note_does_not_wake_the_idle_former_default() { + let probe = Arc::new(Probe::default()); + let agent = MinimalHost::start(&builder_with_branch_config( + &probe, + BranchToolConfig::default(), + )) + .await + .unwrap(); + let session = soon(agent.create_session(SessionConfig::default())) + .await + .unwrap(); + let line = open_line(&session, "the parser race").await; + switch(&session, &line).await; + owed_notes(&session, &line, 1).await; + let cut = idle_cut(&session, "main").await; + let user = soon(session.branch( + "main".into(), + cut, + BranchOptions { + prompt: "the user line".into(), + source: BranchSource::User { + operation_id: "client".into(), + }, + }, + )) + .await + .unwrap(); + quiet(&session, &user).await; + switch(&session, &user).await; + owed_notes(&session, &line, 2).await; + soon(session.idle(&line)).await.unwrap(); + let events = local_events(&session, &line).await; + let note_at = events + .iter() + .rev() + .find(|event| { + blocks_with(std::slice::from_ref(event), " note_at + && matches!(event.kind, EventKind::TurnStart(_) | EventKind::ModelCall(_)) + }), + "the appended note starts no turn and makes no request" + ); + soon(session.submit("report what you found".into(), InputMode::Queue, &line)) + .await + .unwrap(); + soon(session.idle(&line)).await.unwrap(); + let events = local_events(&session, &line).await; + let request = events + .iter() + .rev() + .find_map(|event| match &event.kind { + EventKind::ModelCall(data) if event.sequence > note_at => Some(&data.request), + _ => None, + }) + .expect("the input wakes the line into a request"); + assert!( + request.messages.iter().any(|message| said(message) + .contains("The session's default branch moved from this line")), + "the woken request carries the note: {request:?}" + ); + soon(agent.close()).await.unwrap(); +} + /// #549: a description set at the declaring owner's factory configuration /// reaches the model request byte for byte, carried through ToolRegistry and /// ToolBinding by the shipped assembly. From dbcfcbbc8a6116bf582d9df0d875d712473cd842 Mon Sep 17 00:00:00 2001 From: huihui Date: Mon, 23 Nov 2026 09:12:16 +0800 Subject: [PATCH 20/35] docs(branch): describe the user-line move and its scenario The scenario count and the switching description cover the multi-move step, the user-line role and the former-default input, in both languages. --- docs/design/model-prompts.md | 4 ++-- docs/design/timeline-branches.md | 5 +++-- docs/zh/design/model-prompts.md | 4 ++-- docs/zh/design/timeline-branches.md | 5 +++-- 4 files changed, 10 insertions(+), 8 deletions(-) diff --git a/docs/design/model-prompts.md b/docs/design/model-prompts.md index 9b64aa2f13..25a7f9e75a 100644 --- a/docs/design/model-prompts.md +++ b/docs/design/model-prompts.md @@ -220,7 +220,7 @@ SessionTitle is out of scope: its `SYSTEM` (`crates/dim-session-title/src/lib.rs - **Protocol.** The marker names and attributes, the identity blocks' factual sentences, the branch tool's actions and modes, and its refusal codes change only with the branch mechanism, in the same change as the flow tests that assert them (§4). - **The coordination text for `main` covers the items of [Timeline branches §12.2](timeline-branches.md#122-items-for-the-prompt-layer-429).** -- **Evaluation.** These texts are policy: a change is evaluated with the sixteen scenarios of [Timeline branches §12.3](timeline-branches.md#123-evaluation-scenarios), current against candidate (§8). +- **Evaluation.** These texts are policy: a change is evaluated with the seventeen scenarios of [Timeline branches §12.3](timeline-branches.md#123-evaluation-scenarios), current against candidate (§8). ### 9.5 Goal @@ -253,7 +253,7 @@ SessionTitle is out of scope: its `SYSTEM` (`crates/dim-session-title/src/lib.rs **Owner:** the evaluation tooling, `xtask`; implemented under [#550](https://github.com/arcships/dim/issues/550). - **A scenario runner** with the candidate injection and the test of §8.1: the scenarios are the cases, both arms run the shipped assembly, and the result is reported in the pull request. It interleaves the arms run by run and accepts `--jobs` and repeated `--text`/`--baseline`/`--candidate` triples, so a change that spans two texts of one owner is judged as the one change it is (Goal §A.5.2). -- **A scenario may move the default branch mid-run.** Its `switch` step names the target line, by role (`latest_tool_line`) or id, and the runner calls `session.branch_set_default` at that line's first `turn/start` before sending the next input; the move is retried a few times while the line is not registered yet, and a line that never registers ends the run with its own outcome. An input that names no line lands on the default branch, and one that names a line keeps that target. +- **A scenario may move the default branch mid-run.** Its `switch` step names the target line, by role (`latest_tool_line`, or `user_line` for the line the scenario's `session.branch_create` call opened) or id, and the runner calls `session.branch_set_default` at that line's first `turn/start` before sending the next input; a scenario with more than one move states them in `moves`, where each later move runs right after the one before it. The move is retried a few times while the line is not registered yet, and a line that never registers ends the run with its own outcome. An input that names no line lands on the default branch, and one that names a line keeps that target. A move may carry `formerMessage`, an input sent to the line it moved away from after its own input: a move's note goes in as `append` input, which never starts a turn, so an idle line needs that input to answer. - **A finished evaluation's saved runs are judged again or pooled.** `--rejudge DIR` judges them from the views they saved, with no model turn, keeping each run's own outcome and writing to a new `--out`; `--pool DIR` adds a finished evaluation's saved runs to a report under the same rule and format, and the flag may be repeated to pool several evaluations, writing to none of them, and an `--out` that resolves inside a source, through `..` or a link, is refused before anything is created. Such a report names its sources instead of the instrument's text and candidate-token rows, states the configured texts each arm's saved runs recorded (or that an arm's runs recorded none), and in a pool its model and judge rows are the ones given, while each source's own report states the instrument its runs were judged with. Such a report also gives the declines the runner sent again and how many runs did not record it. A report states one set of configured texts per arm, so a pool whose runs of one arm recorded different texts is refused, and so is a pool that mixes runs which recorded their texts with runs written before the runner recorded them: such evaluations are reported separately, while a pool of runs that all recorded none stays supported as unrecorded. - **A run's file roots.** Each live run serves with three kinds of file-tool root: its workspace, which the model may read and write; its disposable home, which `~` resolves against and which the model may read; and the platform's fixed read-only roots, which carry the toolchain the run's commands read, such as the interpreter's own installation. A file-tool path outside them is refused with `outside_file_roots`, and the refusal leaves what is outside untouched. The roots bound the model's file-tool calls — `read`, `write`, `edit`, `glob` and `grep`; `exec` is bounded by the sandbox, and the client-initiated paths, `@` mention expansion and the App Server's `session.files.*` methods, are not calls the model makes and stay outside the roots. - **No absolute pass line and no CI run** (§8.1). diff --git a/docs/design/timeline-branches.md b/docs/design/timeline-branches.md index ba698ea805..2102084880 100644 --- a/docs/design/timeline-branches.md +++ b/docs/design/timeline-branches.md @@ -511,11 +511,11 @@ The requirements that answer these items are in [Model-facing prompts](model-pro ### 12.3 Evaluation scenarios -The set lives in the repository, one directory per scenario, holding a `scenario.json` and the starting `workspace/` beside it: fifteen under [`xtask/scenario-eval/timeline-branches/`](../../xtask/scenario-eval/timeline-branches/), each declaring a window of 131,072 tokens, and `identity-after-compaction` under [`xtask/scenario-eval/timeline-branches-compact/`](../../xtask/scenario-eval/timeline-branches-compact/), declaring 29,000 so that compaction happens. `budget.window` is a check, not a setting: a run whose Session declares another window fails before its first turn, so a rerun needs a model that declares exactly the scenario's window, and a model that declares none falls back to 128,000 and fails too. These are run locally on real models, and the results are reported in the implementation PR. CI asserts only behavior. +The set lives in the repository, one directory per scenario, holding a `scenario.json` and the starting `workspace/` beside it: sixteen under [`xtask/scenario-eval/timeline-branches/`](../../xtask/scenario-eval/timeline-branches/), each declaring a window of 131,072 tokens, and `identity-after-compaction` under [`xtask/scenario-eval/timeline-branches-compact/`](../../xtask/scenario-eval/timeline-branches-compact/), declaring 29,000 so that compaction happens. `budget.window` is a check, not a setting: a run whose Session declares another window fails before its first turn, so a rerun needs a model that declares exactly the scenario's window, and a model that declares none falls back to 128,000 and fails too. These are run locally on real models, and the results are reported in the implementation PR. CI asserts only behavior. `main-moved-on` is the scenario for the parent block (§7.1.1): `main` works before the cut, opens a line, then keeps working; the line must read what `main` did after the cut before it answers or ends, and it must not page through all of `main`'s activity. It is the scenario for [§12.4](#124-texts-and-their-classes)'s parent-block policy sentence. -The opening and switching roles add seven scenarios: `long-work-and-a-flaky-test`, `refactor-and-a-pasted-report`, `same-file-tradeoff`, `background-command-not-branch`, `switch-continue-directly`, `switch-then-open-lines` and `root-opens-after-switch`. +The opening and switching roles add eight scenarios: `long-work-and-a-flaky-test`, `refactor-and-a-pasted-report`, `same-file-tradeoff`, `background-command-not-branch`, `switch-continue-directly`, `switch-then-open-lines`, `root-opens-after-switch` and `user-line-becomes-default`. `identity-after-compaction` reuses `redone-work`'s message and workspace, and `flooding` and `never-ending` share one workspace: each pair stays identical, and the no-model test that reads both committed directories fails when one copy changes alone. @@ -535,6 +535,7 @@ The opening and switching roles add seven scenarios: `long-work-and-a-flaky-test | Continuing on a line after a switch | `—` | A line that became the default branch calls `end` on itself, hands its work to another line, keeps waking its opener with idle notices, or cannot open a line while the root could | | Opening lines after a switch | `timeline-branches/switch-then-open-lines` | The new default branch does both independent additions itself instead of opening a line for one of them, or the former default branch takes the new work | | The root opens while a line holds the role | `timeline-branches/root-opens-after-switch` | The user asks the root for a line after another line became the default branch: the root must open it, the new line must start from the root's history, and it must report to the root | +| The user's line takes the role | `timeline-branches/user-line-becomes-default` | A line the user opened becomes the default branch while a tool line held it: the user's line must carry its own work forward and not end itself, and the former default tool line must answer the input addressed to it and stay within its remaining scope | | Ping-pong | `timeline-branches/ping-pong` | Steer exchanges that do not move the work forward | | Asking the user | `timeline-branches/asking-the-user` | A line asks the user directly when it should, and does not route through `main` | diff --git a/docs/zh/design/model-prompts.md b/docs/zh/design/model-prompts.md index 37f9c994ae..24faff6a0a 100644 --- a/docs/zh/design/model-prompts.md +++ b/docs/zh/design/model-prompts.md @@ -219,7 +219,7 @@ SessionTitle 不在范围内:它的 `SYSTEM`(`crates/dim-session-title/src/l - **协议。** 标记名与属性、身份块里的事实句、branch 工具的 action 与 mode、以及它的拒绝码,只随分支机制一起改,并与断言它们的流程测试同一个改动(§4)。 - **`main` 的协调文字覆盖 [Timeline 分支 §12.2](timeline-branches.md#122-交给提示词层的事项429) 的事项。** -- **评估。** 这些文字是策略:改动用 [Timeline 分支 §12.3](timeline-branches.md#123-评估场景) 的十六个场景评估,当前对照候选(§8)。 +- **评估。** 这些文字是策略:改动用 [Timeline 分支 §12.3](timeline-branches.md#123-评估场景) 的十七个场景评估,当前对照候选(§8)。 ### 9.5 Goal @@ -252,7 +252,7 @@ SessionTitle 不在范围内:它的 `SYSTEM`(`crates/dim-session-title/src/l **所有者:** 评估工具,`xtask`;在 [#550](https://github.com/arcships/dim/issues/550) 下实现。 - **一个场景运行器**,带 §8.1 的候选注入与检验:场景即用例,两臂都跑 shipped 装配,结果写进 PR。它逐次交错两臂,并接受 `--jobs` 与重复的 `--text`/`--baseline`/`--candidate` 三元组,因此一个跨同一所有者两段文本的改动按它本来就是的一次改动来判定(Goal §A.5.2)。 -- **场景可以在运行中途移动默认分支。** `switch` 步骤按角色(`latest_tool_line`)或 id 指定目标线;运行器在那条线第一次 `turn/start` 时、发下一条输入之前调用 `session.branch_set_default`。线还没注册好时,移动会有限次重试;始终注册不上的线让这次运行以自己的结局结束。不点名线的输入落到默认分支,点名线的输入仍以那个目标为准。 +- **场景可以在运行中途移动默认分支。** `switch` 步骤按角色(`latest_tool_line`,或用 `user_line` 指场景里 `session.branch_create` 调用开出的线)或 id 指定目标线;运行器在那条线第一次 `turn/start` 时、发下一条输入之前调用 `session.branch_set_default`。需要多次移动的场景把它们写在 `moves` 里,后一次移动紧接在前一次之后执行。线还没注册好时,移动会有限次重试;始终注册不上的线让这次运行以自己的结局结束。不点名线的输入落到默认分支,点名线的输入仍以那个目标为准。一次移动可以带 `formerMessage`:在它自己的输入之后,再给被移走的那条线发一条输入。移动写下的状态说明以 `append` 输入进入,而 append 输入从不开启轮次,所以空闲的线需要那条输入才能作答。 - **已完成评估的运行可以重判,也可以合并报告。** `--rejudge DIR` 按这些运行保存的视图重新判定,不产生模型轮次,保留每次运行自身的结局,写入新的 `--out`;`--pool DIR` 把一次已完成评估的运行加入报告,该参数可以重复给出,从而把多次已完成评估的运行按同一规则与同一格式一起报告,不写入其中任何一个,而解析后落在某个来源内部的 `--out`(经由 `..` 或链接)会在创建任何东西之前被拒绝。这样的报告列出它的来源,取代评估工具的 text 与 candidate-token 两行,并写出每个臂保存的运行所记录的配置文本(或某个臂的运行一条都没记录);合并报告里的 model 与 judge 两行是收到的参数,每个来源自己的报告才写着它的运行是凭什么判的。这样的报告还会给出再次发送 decline 的次数,以及有多少运行没有记录该次数。报告每个臂只写一组配置文本,因此同一个臂的运行记录了不同文本时池化会被拒绝,把记录了文本的运行与运行器开始记录之前写下的运行混在一起也会被拒绝:这些评估分别报告;而全部都没有记录文本的运行仍可作为未记录合并。 - **一次运行的文件根。** 每个 isolate 运行都以三类文件工具根提供服务:工作区,模型可读可写;一次性 home,`~` 解析到它,模型可读;以及平台固定的只读根,承载运行的命令要读取的工具链,例如解释器自身的安装目录。文件工具路径落在这些根之外时以 `outside_file_roots` 拒绝,且拒绝不触碰根外的任何内容。这些根约束模型的文件工具调用——`read`、`write`、`edit`、`glob`、`grep`;`exec` 由沙箱约束,而客户端发起的路径(`@` 提及展开与 App Server 的 `session.files.*` 方法)不是模型发起的调用,不在根内。 - **不用绝对通过线,不进 CI**(§8.1)。 diff --git a/docs/zh/design/timeline-branches.md b/docs/zh/design/timeline-branches.md index 7eeeac2931..3e77880abf 100644 --- a/docs/zh/design/timeline-branches.md +++ b/docs/zh/design/timeline-branches.md @@ -477,11 +477,11 @@ WorkspaceTools 不变。 ### 12.3 评估场景 -场景放在仓库里,一个场景一个目录,目录里是 `scenario.json` 和它旁边的起始 `workspace/`:十五个在 [`xtask/scenario-eval/timeline-branches/`](../../../xtask/scenario-eval/timeline-branches/) 下,各自声明 131,072 tokens 的窗口;`identity-after-compaction` 在 [`xtask/scenario-eval/timeline-branches-compact/`](../../../xtask/scenario-eval/timeline-branches-compact/) 下,声明 29,000,以便发生压缩。`budget.window` 是校验而不是设置:Session 声明的窗口与之不同时,这次运行在第一轮之前就失败,所以复跑需要模型声明正好这个窗口;没有声明窗口的模型回退到 128,000,同样失败。这些场景在本地用真实模型运行,结果在实现 PR 里报告。CI 只断言行为。 +场景放在仓库里,一个场景一个目录,目录里是 `scenario.json` 和它旁边的起始 `workspace/`:十六个在 [`xtask/scenario-eval/timeline-branches/`](../../../xtask/scenario-eval/timeline-branches/) 下,各自声明 131,072 tokens 的窗口;`identity-after-compaction` 在 [`xtask/scenario-eval/timeline-branches-compact/`](../../../xtask/scenario-eval/timeline-branches-compact/) 下,声明 29,000,以便发生压缩。`budget.window` 是校验而不是设置:Session 声明的窗口与之不同时,这次运行在第一轮之前就失败,所以复跑需要模型声明正好这个窗口;没有声明窗口的模型回退到 128,000,同样失败。这些场景在本地用真实模型运行,结果在实现 PR 里报告。CI 只断言行为。 `main-moved-on` 是父线块(§7.1.1)的场景:`main` 在切点之前有工作,开一条线,然后继续工作;这条线在回答或结束之前必须读取 `main` 在切点之后做的事,并且不能逐页读遍 `main` 的全部活动。它是 [§12.4](#124-文本及其类别) 父线块策略句的场景。 -开线与切换角色新增七个场景:`long-work-and-a-flaky-test`、`refactor-and-a-pasted-report`、`same-file-tradeoff`、`background-command-not-branch`、`switch-continue-directly`、`switch-then-open-lines`、`root-opens-after-switch`。 +开线与切换角色新增八个场景:`long-work-and-a-flaky-test`、`refactor-and-a-pasted-report`、`same-file-tradeoff`、`background-command-not-branch`、`switch-continue-directly`、`switch-then-open-lines`、`root-opens-after-switch`、`user-line-becomes-default`。 `identity-after-compaction` 沿用 `redone-work` 的消息和 workspace,`flooding` 与 `never-ending` 共用同一个 workspace:这两对保持完全相同,改动其中一份而不同步另一份时,读取两个提交目录的无模型测试会失败。 @@ -501,6 +501,7 @@ WorkspaceTools 不变。 | 切换后继续在线上工作 | — | 成为默认分支的线对自己调用 `end`、把工作交给另一条线、不断用 idle 通知唤醒开它的线,或者根能开线而这条线不能 | | 切换后开线 | `timeline-branches/switch-then-open-lines` | 新的默认分支自己做掉两处互不相干的新增,而不是为其中一处开一条线;或者原默认分支接过新工作 | | 线持有角色时根开线 | `timeline-branches/root-opens-after-switch` | 另一条线成为默认分支后,用户向根要一条线:根必须开这条线,新线必须从根的历史开始,并向根汇报 | +| 用户开的线接过角色 | `timeline-branches/user-line-becomes-default` | 用户开的线在工具线持有默认分支时成为默认分支:用户这条线必须自己接着做自己的工作、不结束自己,而原来的默认工具线必须回答发给它的输入,并且不超出自己剩下的范围 | | 来回空转 | `timeline-branches/ping-pong` | 不推进工作的 steer 往复 | | 问用户 | `timeline-branches/asking-the-user` | 该问用户时,线直接问用户,而不是绕道 `main` | From 9e4a85a87157202de4593edbabdb9cb3071c8854 Mon Sep 17 00:00:00 2001 From: huihui Date: Mon, 23 Nov 2026 09:14:16 +0800 Subject: [PATCH 21/35] style: apply rustfmt to the new note flows No behaviour change. --- .../tests/branch_flow.rs | 18 ++++++++----- xtask/src/scenario_eval.rs | 26 ++++++------------- 2 files changed, 19 insertions(+), 25 deletions(-) diff --git a/crates/dim-agent-capabilities/tests/branch_flow.rs b/crates/dim-agent-capabilities/tests/branch_flow.rs index 2c362ae1c3..27d1217e61 100644 --- a/crates/dim-agent-capabilities/tests/branch_flow.rs +++ b/crates/dim-agent-capabilities/tests/branch_flow.rs @@ -4720,8 +4720,7 @@ async fn a_user_lines_default_note_reaches_the_model_request() { .iter() .map(|message| said(message)) .find(|text| { - text.starts_with(" note_at - && matches!(event.kind, EventKind::TurnStart(_) | EventKind::ModelCall(_)) + && matches!( + event.kind, + EventKind::TurnStart(_) | EventKind::ModelCall(_) + ) }), "the appended note starts no turn and makes no request" ); @@ -4914,8 +4915,11 @@ async fn an_appended_note_does_not_wake_the_idle_former_default() { }) .expect("the input wakes the line into a request"); assert!( - request.messages.iter().any(|message| said(message) - .contains("The session's default branch moved from this line")), + request + .messages + .iter() + .any(|message| said(message) + .contains("The session's default branch moved from this line")), "the woken request carries the note: {request:?}" ); soon(agent.close()).await.unwrap(); diff --git a/xtask/src/scenario_eval.rs b/xtask/src/scenario_eval.rs index f6b2d1280c..146ea3cc4f 100644 --- a/xtask/src/scenario_eval.rs +++ b/xtask/src/scenario_eval.rs @@ -6134,9 +6134,7 @@ async fn drive( // The move and the input after it are bounded by the same absolute // deadline the budget check below applies: a reply that never comes // must not hold the run past its wall clock (model-prompts §8.1). - let line = switches - .front() - .and_then(|pending| pending.line.clone()); + let line = switches.front().and_then(|pending| pending.line.clone()); let fired = match tokio::time::timeout( time_left(started, &scenario.budget), fire_switch(client, &session, &mut switches, &mut default), @@ -9114,7 +9112,8 @@ mod tests { ..SwitchRecorder::default() }; let mut switch = triggered_switch(); - let error = match fire_switch(&mut client, "session", &mut switch, &mut "main".into()).await { + let error = match fire_switch(&mut client, "session", &mut switch, &mut "main".into()).await + { Err(error) => error, Ok(outcome) => panic!("the move was refused, not {outcome:?}"), }; @@ -9141,10 +9140,7 @@ mod tests { fire_switch(&mut client, "session", &mut switch, &mut "main".into()).await, Ok(SwitchFire::Retry) )); - assert!( - !switch.is_empty(), - "the switch stays pending for the retry" - ); + assert!(!switch.is_empty(), "the switch stays pending for the retry"); assert!(matches!( fire_switch(&mut client, "session", &mut switch, &mut "main".into()).await, Ok(SwitchFire::Fired) @@ -17581,8 +17577,8 @@ mod tests { "- CANDIDATE default guidance for {parent}, switched from {other}."; const USER_NOTE: &str = "- CANDIDATE user-line guidance for {other}."; const FORMER_NOTE: &str = "- CANDIDATE former-default guidance for {other}."; - let case = repository() - .join("xtask/scenario-eval/timeline-branches/user-line-becomes-default"); + let case = + repository().join("xtask/scenario-eval/timeline-branches/user-line-becomes-default"); let scenario: Value = serde_json::from_slice(&std::fs::read(case.join("scenario.json")).unwrap()).unwrap(); let workspace: Vec<(String, String)> = workspace_files(&case) @@ -17659,11 +17655,7 @@ mod tests { let request: Value = serde_json::from_str(request).ok()?; request["tools"].as_array()?.iter().find_map(|tool| { (tool["function"]["name"] == "branch") - .then(|| { - tool["function"]["description"] - .as_str() - .map(str::to_owned) - }) + .then(|| tool["function"]["description"].as_str().map(str::to_owned)) .flatten() }) }) @@ -17716,9 +17708,7 @@ mod tests { ), ] { assert!( - requests - .iter() - .any(|request| carried(request, &attribute)), + requests.iter().any(|request| carried(request, &attribute)), "a request carries {attribute}" ); } From 30f256d6abb20e2c5359f87ceaefb56616f551a4 Mon Sep 17 00:00:00 2001 From: huihui Date: Mon, 23 Nov 2026 09:39:46 +0800 Subject: [PATCH 22/35] test(branch): give the appended-note test a quiet window The former default line's idle wait can return before the appended note has been dispatched, so a wake that arrives just after it would miss the negative assertion. The test now waits through the file's quiet helper, which samples three stable sequence pairs before it reads the events. --- crates/dim-agent-capabilities/tests/branch_flow.rs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/crates/dim-agent-capabilities/tests/branch_flow.rs b/crates/dim-agent-capabilities/tests/branch_flow.rs index 27d1217e61..586a433f7d 100644 --- a/crates/dim-agent-capabilities/tests/branch_flow.rs +++ b/crates/dim-agent-capabilities/tests/branch_flow.rs @@ -4879,7 +4879,7 @@ async fn an_appended_note_does_not_wake_the_idle_former_default() { quiet(&session, &user).await; switch(&session, &user).await; owed_notes(&session, &line, 2).await; - soon(session.idle(&line)).await.unwrap(); + quiet(&session, &line).await; let events = local_events(&session, &line).await; let note_at = events .iter() From da1e596419a2382d5b5c41e6473e6726585573b5 Mon Sep 17 00:00:00 2001 From: huihui Date: Mon, 23 Nov 2026 10:32:38 +0800 Subject: [PATCH 23/35] test(xtask): script the chained move to a tool line opened before it The two scripted peers record the `branchId` of every `session.branch_set_default` a run sends, so a test can read which lines its moves reached. One script opens tool line `2` while the first move, to the explicit line `7`, waits for its target's first turn, and opens no line afterwards; the other opens `2` only after that move fired. `a_chained_switch_uses_the_tool_line_the_run_has_seen` asserts the later move to the latest tool line moves to `2`. `a_chained_switch_waits_for_the_tool_line_opened_after_it_was_activated` asserts the same move waits for the creation and then moves to it. --- xtask/src/scenario_eval.rs | 176 +++++++++++++++++++++++++++++++++++++ 1 file changed, 176 insertions(+) diff --git a/xtask/src/scenario_eval.rs b/xtask/src/scenario_eval.rs index 146ea3cc4f..5ebf38373b 100644 --- a/xtask/src/scenario_eval.rs +++ b/xtask/src/scenario_eval.rs @@ -13645,6 +13645,15 @@ mod tests { /// that stopped on its wall clock must still return, with cleanup /// bounded. SwitchMoveAndCloseStall, + /// The first move names the explicit line `7`, and the tool line `2` + /// opens while that move waits for its target's first turn. No other + /// line opens afterwards, so the later move to the latest tool line + /// can only run on `2`. + ChainedToolLineBeforeActivation, + /// The first move names the explicit line `7` and fires before any + /// tool line exists; `2` opens after that move's input, and its first + /// turn fires the later move to the latest tool line. + ChainedToolLineAfterActivation, /// The setup's context window read answers `context_usage_unavailable`, /// so the check is deferred, and the deferred read answers /// `session_reloading`: a failure that is not the deferral itself. @@ -13662,6 +13671,8 @@ mod tests { settled_at: AtomicUsize, idles: AtomicUsize, usages: AtomicUsize, + /// The `branchId` of every `session.branch_set_default`, in order. + moves: Mutex>, attached: tokio::sync::Notify, closes: AtomicUsize, } @@ -13709,6 +13720,17 @@ mod tests { fn notice(event: Value) -> Vec { notice_on("main", event) } + /// One `branch/create` notice of tool line `branch` at `sequence`. + fn created(sequence: u64, branch: &str) -> Value { + json!({"type": "branch", "name": "create", "id": format!("e{sequence}"), + "sequence": sequence, + "data": {"branch": branch, "source": {"kind": "tool"}}}) + } + /// One `turn` notice at `sequence`. + fn turn(sequence: u64, name: &str) -> Value { + json!({"type": "turn", "name": name, "id": format!("e{sequence}"), + "sequence": sequence, "data": {}}) + } /// The refusal a client gets while the call has no waiter. fn not_pending() -> Value { json!({"error": {"code": -32000, "message": "No ask_user call is waiting for this answer", @@ -13806,6 +13828,14 @@ mod tests { let Some(line) = line.unwrap() else { break }; let request: Value = serde_json::from_str(&line).unwrap(); let method = request["method"].as_str().unwrap_or_default(); + if method == "session.branch_set_default" { + recorded.moves.lock().unwrap().push( + request["params"]["branchId"] + .as_str() + .unwrap_or_default() + .to_owned(), + ); + } if method == "session.attach" { recorded.attached.notify_one(); } @@ -13927,6 +13957,8 @@ mod tests { PeerScript::SwitchMoveStalls | PeerScript::SwitchSubmitStalls | PeerScript::SwitchMoveAndCloseStall => None, + PeerScript::ChainedToolLineBeforeActivation + | PeerScript::ChainedToolLineAfterActivation => None, PeerScript::DeferredUsageFails => None, }; if let Some((request, sequence)) = closed { @@ -13994,6 +14026,37 @@ mod tests { )) .await .unwrap(); + if matches!( + script, + PeerScript::ChainedToolLineBeforeActivation + | PeerScript::ChainedToolLineAfterActivation + ) { + let before = + matches!(script, PeerScript::ChainedToolLineBeforeActivation); + let written = match (before, submits) { + // The tool line opens while the first move waits + // for its own target's first turn; the line that + // starts afterwards fires that move. + (true, 1) => vec![("2", created(2, "2")), ("7", turn(3, "start"))], + // The first move's input: its target's turn starts, + // and its end stops the run on the turn budget. + (true, 2) => vec![("7", turn(4, "start")), ("7", turn(5, "end"))], + // The first move fires before any tool line exists. + (false, 1) => vec![("7", turn(2, "start"))], + // The tool line opens after that, and its first + // turn starts before the run stops. + (false, 2) => vec![ + ("2", created(3, "2")), + ("2", turn(4, "start")), + ("2", turn(5, "end")), + ], + _ => Vec::new(), + }; + for (branch, event) in written { + write.write_all(¬ice_on(branch, event)).await.unwrap(); + } + continue; + } // The held line asks nothing: the run's only work is the // turn the peer holds open. A switch that never fires // likewise asks nothing: its turn starts and ends. @@ -14234,6 +14297,119 @@ mod tests { ); } + /// A chained move to the latest tool line uses the line the run has seen + /// opened, even when it opened while the move before it waited: a line + /// that exists when the move is activated is the one its role names, so + /// the move runs instead of waiting for a creation that never comes + /// (model-prompts §9.8). + #[cfg(unix)] + #[tokio::test(flavor = "multi_thread", worker_threads = 2)] + async fn a_chained_switch_uses_the_tool_line_the_run_has_seen() { + let directory = std::env::temp_dir().join(format!( + "dim-scenario-eval-chained-tool-line-{}", + std::process::id() + )); + let (socket, reads) = + scripted_peer(&directory, 8_000, PeerScript::ChainedToolLineBeforeActivation).await; + let mut client = driver_client(socket).await; + let mut scenario = scenario(Vec::new()); + scenario.budget.turns = 1; + scenario.budget.seconds = 10.; + scenario.moves = vec![ + Switch { + to: SwitchTarget::Id("7".into()), + message: "to the line that waited".into(), + branch_id: None, + former_message: None, + }, + Switch { + to: SwitchTarget::Role(SwitchRole::LatestToolLine), + message: "to the tool line".into(), + branch_id: None, + former_message: None, + }, + ]; + let driven = drive( + &mut client, + &RunSettings::default(), + &scenario, + &std::env::temp_dir(), + &peer_model(), + &ProducerState::default(), + None, + ) + .await; + let moves: Vec = reads.moves.lock().unwrap().clone(); + let _ = std::fs::remove_dir_all(directory); + assert_eq!( + moves, + ["7", "2"], + "the chained move moves to the tool line the run had seen opened: {:?}", + driven.error + ); + assert_ne!( + driven.stop, "switch_target_not_reached", + "the move's target existed: {:?}", + driven.error + ); + } + + /// A chained move to the latest tool line waits for a creation when the + /// run has seen none: the line that opens after the move is activated is + /// the one its role names, and its first turn fires the move + /// (model-prompts §9.8). + #[cfg(unix)] + #[tokio::test(flavor = "multi_thread", worker_threads = 2)] + async fn a_chained_switch_waits_for_the_tool_line_opened_after_it_was_activated() { + let directory = std::env::temp_dir().join(format!( + "dim-scenario-eval-chained-tool-line-later-{}", + std::process::id() + )); + let (socket, reads) = + scripted_peer(&directory, 8_000, PeerScript::ChainedToolLineAfterActivation).await; + let mut client = driver_client(socket).await; + let mut scenario = scenario(Vec::new()); + scenario.budget.turns = 1; + scenario.budget.seconds = 10.; + scenario.moves = vec![ + Switch { + to: SwitchTarget::Id("7".into()), + message: "to the line that waited".into(), + branch_id: None, + former_message: None, + }, + Switch { + to: SwitchTarget::Role(SwitchRole::LatestToolLine), + message: "to the tool line".into(), + branch_id: None, + former_message: None, + }, + ]; + let driven = drive( + &mut client, + &RunSettings::default(), + &scenario, + &std::env::temp_dir(), + &peer_model(), + &ProducerState::default(), + None, + ) + .await; + let moves: Vec = reads.moves.lock().unwrap().clone(); + let _ = std::fs::remove_dir_all(directory); + assert_eq!( + moves, + ["7", "2"], + "the chained move moves to the tool line opened after it was activated: {:?}", + driven.error + ); + assert_ne!( + driven.stop, "switch_target_not_reached", + "the move's target existed: {:?}", + driven.error + ); + } + /// A switch call that never answers is bounded by the scenario's wall /// clock: the run records the timeout and returns instead of waiting on /// the connection, so its worker is released (model-prompts §8.1). From 14a5b797cbb6f1fd2967d184b0b2efb45d79ef21 Mon Sep 17 00:00:00 2001 From: huihui Date: Mon, 23 Nov 2026 10:33:57 +0800 Subject: [PATCH 24/35] fix(xtask): resolve a chained move to the tool line the run has seen `PendingSwitch::new` left the `latest_tool_line` target unset, and the event pump hands a `branch/create` only to the move that is front when it arrives. A move activated after the creation, a later entry of `moves` that fires right after the move before it, therefore had no line and waited for a creation that would not come: the run ended with `switch_target_not_reached` although its target existed. The runner keeps the latest tool-line creation as run state and reads it when it activates the next move: a move to that role with no line of its own takes the line the run has seen, and a line opened after the activation still renames an unset target through `PendingSwitch::notice`. `user_line` and explicit ids carry their line from the scenario, so their resolution is unchanged, and so is a single `switch`, which is never activated this way. --- xtask/src/scenario_eval.rs | 168 +++++++++++++++++++++++++++++++------ 1 file changed, 144 insertions(+), 24 deletions(-) diff --git a/xtask/src/scenario_eval.rs b/xtask/src/scenario_eval.rs index 5ebf38373b..0b91bf9a50 100644 --- a/xtask/src/scenario_eval.rs +++ b/xtask/src/scenario_eval.rs @@ -2062,6 +2062,18 @@ pub(crate) enum SwitchRole { /// turn before the line is marked ready. const UNKNOWN_BRANCH_RETRIES: u32 = 3; +/// The tool line a `branch/create` notice opened: the branch tool's line, which +/// [`SwitchRole::LatestToolLine`] names. Any other notice answers `None`. +fn tool_line(event: &Value) -> Option<&str> { + if event["type"] != "branch" || event["name"] != "create" { + return None; + } + if event["data"]["source"]["kind"] != "tool" { + return None; + } + event["data"]["branch"].as_str() +} + /// A [`Switch`] as the run drives it: the target the role currently names, /// kept current while the switch is pending and that target has not started. struct PendingSwitch { @@ -2097,14 +2109,12 @@ impl PendingSwitch { /// afterwards has its own purpose, and the move and the input after it /// stay with the line that started. fn notice(&mut self, branch: &str, event: &Value) { - if event["type"] == "branch" && event["name"] == "create" { + if let Some(line) = tool_line(event) { if (!self.triggered || self.line.is_none()) && matches!( &self.switch.to, SwitchTarget::Role(SwitchRole::LatestToolLine) ) - && event["data"]["source"]["kind"] == "tool" - && let Some(line) = event["data"]["branch"].as_str() { self.line = Some(line.to_owned()); } @@ -2117,6 +2127,22 @@ impl PendingSwitch { self.triggered = true; } } + + /// Activates a chained move: it fires right after the move before it, so a + /// move to the latest tool line takes the line the run has recorded. A + /// move without one keeps waiting for a `branch/create` notice, as a + /// single move does. + fn activated(&mut self, latest_tool_line: Option<&str>) { + self.triggered = true; + if self.line.is_none() + && matches!( + &self.switch.to, + SwitchTarget::Role(SwitchRole::LatestToolLine) + ) + { + self.line = latest_tool_line.map(str::to_owned); + } + } } /// One source a scenario declares through the `eventHub` service, and /// optionally subscribes its Session's `main` branch to (EventHub design A.1, @@ -6073,6 +6099,11 @@ async fn drive( return driven; } let mut default = "main".to_owned(); + // The latest tool line the run has seen opened. The role + // `latest_tool_line` names it, and a move activated after the line opened + // uses it: a `branch/create` reaches only the move that is front when it + // arrives. + let mut latest_tool_line: Option = None; let mut last_event = Instant::now(); // The events still to publish, and whether each was. let mut events: Vec<(EventSpec, bool)> = scenario @@ -6137,7 +6168,13 @@ async fn drive( let line = switches.front().and_then(|pending| pending.line.clone()); let fired = match tokio::time::timeout( time_left(started, &scenario.budget), - fire_switch(client, &session, &mut switches, &mut default), + fire_switch( + client, + &session, + &mut switches, + &mut default, + latest_tool_line.as_deref(), + ), ) .await { @@ -6240,6 +6277,9 @@ async fn drive( { branches.insert(branch.to_owned()); } + if let Some(line) = tool_line(&event) { + latest_tool_line = Some(line.to_owned()); + } // A steer is taken inside the turn it reaches, so no // turn starts for it: either event means the input is // no longer outstanding. @@ -7321,12 +7361,13 @@ fn unknown_branch(error: &dim_client::Error) -> bool { /// first, then the next input is submitted, naming a line only when the /// scenario does, and then the input meant for the line it moved away from. /// A move fires once and leaves the queue; the move after it fires on the next -/// call. +/// call, and is activated here with the tool line the run has seen opened. async fn fire_switch( client: &mut impl SwitchClient, session: &str, switches: &mut VecDeque, default: &mut String, + latest_tool_line: Option<&str>, ) -> std::result::Result { let Some(pending) = switches.front_mut() else { return Ok(SwitchFire::NotFired); @@ -7366,7 +7407,7 @@ async fn fire_switch( } let pending = switches.pop_front().expect("the switch is pending"); if let Some(next) = switches.front_mut() { - next.triggered = true; + next.activated(latest_tool_line); } let former = std::mem::replace(default, line); submit( @@ -8916,14 +8957,14 @@ mod tests { for move_number in [1, 2] { assert!( matches!( - fire_switch(&mut client, "session", &mut switches, &mut default).await, + fire_switch(&mut client, "session", &mut switches, &mut default, None).await, Ok(SwitchFire::Fired) ), "move {move_number}" ); } assert!(matches!( - fire_switch(&mut client, "session", &mut switches, &mut default).await, + fire_switch(&mut client, "session", &mut switches, &mut default, None).await, Ok(SwitchFire::NotFired) )); let calls: Vec<&str> = client @@ -8987,7 +9028,14 @@ mod tests { ..SwitchRecorder::default() }; assert!(matches!( - fire_switch(&mut client, "session", &mut switch, &mut "main".into()).await, + fire_switch( + &mut client, + "session", + &mut switch, + &mut "main".into(), + None + ) + .await, Ok(SwitchFire::Retry) )); let pending = switch.front_mut().expect("the retry keeps the switch"); @@ -8998,7 +9046,14 @@ mod tests { "the line that started keeps the move" ); assert!(matches!( - fire_switch(&mut client, "session", &mut switch, &mut "main".into()).await, + fire_switch( + &mut client, + "session", + &mut switch, + &mut "main".into(), + None + ) + .await, Ok(SwitchFire::Fired) )); let calls: Vec<&str> = client @@ -9074,7 +9129,14 @@ mod tests { let mut client = SwitchRecorder::default(); let mut switch = triggered_switch(); assert!(matches!( - fire_switch(&mut client, "session", &mut switch, &mut "main".into()).await, + fire_switch( + &mut client, + "session", + &mut switch, + &mut "main".into(), + None + ) + .await, Ok(SwitchFire::Fired) )); let calls: Vec<&str> = client @@ -9094,7 +9156,14 @@ mod tests { "the next input lands on the new default branch" ); assert!(matches!( - fire_switch(&mut client, "session", &mut switch, &mut "main".into()).await, + fire_switch( + &mut client, + "session", + &mut switch, + &mut "main".into(), + None + ) + .await, Ok(SwitchFire::NotFired) )); assert_eq!(client.calls.len(), 2, "a switch fires once"); @@ -9112,7 +9181,14 @@ mod tests { ..SwitchRecorder::default() }; let mut switch = triggered_switch(); - let error = match fire_switch(&mut client, "session", &mut switch, &mut "main".into()).await + let error = match fire_switch( + &mut client, + "session", + &mut switch, + &mut "main".into(), + None, + ) + .await { Err(error) => error, Ok(outcome) => panic!("the move was refused, not {outcome:?}"), @@ -9137,12 +9213,26 @@ mod tests { }; let mut switch = triggered_switch(); assert!(matches!( - fire_switch(&mut client, "session", &mut switch, &mut "main".into()).await, + fire_switch( + &mut client, + "session", + &mut switch, + &mut "main".into(), + None + ) + .await, Ok(SwitchFire::Retry) )); assert!(!switch.is_empty(), "the switch stays pending for the retry"); assert!(matches!( - fire_switch(&mut client, "session", &mut switch, &mut "main".into()).await, + fire_switch( + &mut client, + "session", + &mut switch, + &mut "main".into(), + None + ) + .await, Ok(SwitchFire::Fired) )); let calls: Vec<&str> = client @@ -9177,14 +9267,29 @@ mod tests { for retry in 0..UNKNOWN_BRANCH_RETRIES { assert!( matches!( - fire_switch(&mut client, "session", &mut switch, &mut "main".into()).await, + fire_switch( + &mut client, + "session", + &mut switch, + &mut "main".into(), + None + ) + .await, Ok(SwitchFire::Retry) ), "retry {retry}" ); assert!(!switch.is_empty(), "retry {retry}: still pending"); } - match fire_switch(&mut client, "session", &mut switch, &mut "main".into()).await { + match fire_switch( + &mut client, + "session", + &mut switch, + &mut "main".into(), + None, + ) + .await + { Ok(SwitchFire::TargetUnknown { line, error }) => { assert_eq!(line, "2"); assert!(error.contains("unknown branch"), "{error}"); @@ -9225,7 +9330,15 @@ mod tests { ..SwitchRecorder::default() }; let mut switch = triggered_switch(); - match fire_switch(&mut client, "session", &mut switch, &mut "main".into()).await { + match fire_switch( + &mut client, + "session", + &mut switch, + &mut "main".into(), + None, + ) + .await + { Ok(SwitchFire::TargetEnded { line, error }) => { assert_eq!(line, "2"); assert!(error.contains(code), "{code}: {error}"); @@ -14031,8 +14144,7 @@ mod tests { PeerScript::ChainedToolLineBeforeActivation | PeerScript::ChainedToolLineAfterActivation ) { - let before = - matches!(script, PeerScript::ChainedToolLineBeforeActivation); + let before = matches!(script, PeerScript::ChainedToolLineBeforeActivation); let written = match (before, submits) { // The tool line opens while the first move waits // for its own target's first turn; the line that @@ -14309,8 +14421,12 @@ mod tests { "dim-scenario-eval-chained-tool-line-{}", std::process::id() )); - let (socket, reads) = - scripted_peer(&directory, 8_000, PeerScript::ChainedToolLineBeforeActivation).await; + let (socket, reads) = scripted_peer( + &directory, + 8_000, + PeerScript::ChainedToolLineBeforeActivation, + ) + .await; let mut client = driver_client(socket).await; let mut scenario = scenario(Vec::new()); scenario.budget.turns = 1; @@ -14365,8 +14481,12 @@ mod tests { "dim-scenario-eval-chained-tool-line-later-{}", std::process::id() )); - let (socket, reads) = - scripted_peer(&directory, 8_000, PeerScript::ChainedToolLineAfterActivation).await; + let (socket, reads) = scripted_peer( + &directory, + 8_000, + PeerScript::ChainedToolLineAfterActivation, + ) + .await; let mut client = driver_client(socket).await; let mut scenario = scenario(Vec::new()); scenario.budget.turns = 1; From 3f640359c9be6a82330a45e42559560ca8560f75 Mon Sep 17 00:00:00 2001 From: huihui Date: Mon, 23 Nov 2026 10:43:11 +0800 Subject: [PATCH 25/35] test(xtask): keep the scripted peer sockets within the unix path length The chained-move tests named their directories after the role and the timing, and the longer one put the socket path at 106 bytes: `UnixListener::bind` answered `InvalidInput` because the path did not fit `sun_path`. Both directories are shorter now, and both tests pass. --- xtask/src/scenario_eval.rs | 8 +++----- 1 file changed, 3 insertions(+), 5 deletions(-) diff --git a/xtask/src/scenario_eval.rs b/xtask/src/scenario_eval.rs index 0b91bf9a50..4bf9205b8f 100644 --- a/xtask/src/scenario_eval.rs +++ b/xtask/src/scenario_eval.rs @@ -14417,10 +14417,8 @@ mod tests { #[cfg(unix)] #[tokio::test(flavor = "multi_thread", worker_threads = 2)] async fn a_chained_switch_uses_the_tool_line_the_run_has_seen() { - let directory = std::env::temp_dir().join(format!( - "dim-scenario-eval-chained-tool-line-{}", - std::process::id() - )); + let directory = + std::env::temp_dir().join(format!("dim-scenario-eval-chained-{}", std::process::id())); let (socket, reads) = scripted_peer( &directory, 8_000, @@ -14478,7 +14476,7 @@ mod tests { #[tokio::test(flavor = "multi_thread", worker_threads = 2)] async fn a_chained_switch_waits_for_the_tool_line_opened_after_it_was_activated() { let directory = std::env::temp_dir().join(format!( - "dim-scenario-eval-chained-tool-line-later-{}", + "dim-scenario-eval-chained-later-{}", std::process::id() )); let (socket, reads) = scripted_peer( From 8905160566cf9a78d004fe340c962b36492efec5 Mon Sep 17 00:00:00 2001 From: huihui Date: Mon, 23 Nov 2026 14:16:49 +0800 Subject: [PATCH 26/35] test(xtask): hold a switch's note past its acknowledgment A move writes its status note after `session.branch_set_default` answered, so a line that is idle can start the request that answers the follow-up before the note lands. `a_follow_up_waits_for_the_note_after_the_moves_acknowledgment` holds the note until after the move's answer and asserts the follow-up is still unsent, and `a_chained_move_waits_for_the_input_before_it` asserts a chained move does not fire before the line that took the move before it has consumed its input. --- xtask/src/scenario_eval.rs | 157 +++++++++++++++++++++++++++++++++++++ 1 file changed, 157 insertions(+) diff --git a/xtask/src/scenario_eval.rs b/xtask/src/scenario_eval.rs index 4bf9205b8f..be4e0fdebc 100644 --- a/xtask/src/scenario_eval.rs +++ b/xtask/src/scenario_eval.rs @@ -8998,6 +8998,125 @@ mod tests { assert_eq!(default, "3", "the last move holds the default branch"); } + /// A move's acknowledgment does not send its follow-up: the line answers + /// the input only after it wrote the note, so an idle line cannot answer a + /// follow-up before its note lands (Timeline branches §12.4). + #[tokio::test] + async fn a_follow_up_waits_for_the_note_after_the_moves_acknowledgment() { + let turn_start = json!({"type": "turn", "name": "start", "data": {}}); + let mut pending = PendingSwitch::new( + Switch { + to: SwitchTarget::Id("2".into()), + message: "next".into(), + branch_id: None, + former_message: None, + }, + None, + false, + ); + pending.notice("2", &turn_start); + let mut switches: VecDeque = [pending].into(); + let mut default = "main".to_owned(); + let mut client = SwitchRecorder { + inputs: ["i1".to_owned()].into(), + ..SwitchRecorder::default() + }; + assert!( + matches!( + fire_switch(&mut client, "session", &mut switches, &mut default, None).await, + Ok(SwitchFire::NotFired) + ), + "the move's answer alone sends nothing" + ); + assert_eq!( + client.methods(), + ["session.branch_set_default"], + "the follow-up waits for the note the move wrote" + ); + let pending = switches.front_mut().expect("the move waits for its note"); + pending.notice("2", &move_note("2", true, "main")); + assert!( + matches!( + fire_switch(&mut client, "session", &mut switches, &mut default, None).await, + Ok(SwitchFire::Fired) + ), + "the note releases the follow-up" + ); + assert_eq!( + client.methods(), + ["session.branch_set_default", "session.submit"], + "the move runs before its input" + ); + assert_eq!(default, "2", "the move holds the new default"); + } + + /// A chained move waits for the input the move before it sent: the first + /// move's target answers with its note in effect before the next move can + /// retire it (Timeline branches §12.4). + #[tokio::test] + async fn a_chained_move_waits_for_the_input_before_it() { + let turn_start = json!({"type": "turn", "name": "start", "data": {}}); + let first = PendingSwitch::new( + Switch { + to: SwitchTarget::Id("2".into()), + message: "to the tool line".into(), + branch_id: None, + former_message: None, + }, + None, + false, + ); + let second = PendingSwitch::new( + Switch { + to: SwitchTarget::Id("3".into()), + message: "to the user line".into(), + branch_id: None, + former_message: None, + }, + None, + true, + ); + let mut switches: VecDeque = [first, second].into(); + let mut default = "main".to_owned(); + let mut client = SwitchRecorder { + inputs: ["i1".to_owned(), "i2".to_owned()].into(), + ..SwitchRecorder::default() + }; + switches + .front_mut() + .expect("the first move is pending") + .notice("2", &turn_start); + assert!( + matches!( + fire_switch(&mut client, "session", &mut switches, &mut default, None).await, + Ok(SwitchFire::Fired) + ), + "the first move fires" + ); + assert!( + matches!( + fire_switch(&mut client, "session", &mut switches, &mut default, None).await, + Ok(SwitchFire::NotFired) + ), + "the chained move waits for the input before it" + ); + assert_eq!( + client.methods(), + ["session.branch_set_default", "session.submit"], + "the second move sends nothing before the first input is consumed" + ); + let pending = switches.front_mut().expect("the second move is pending"); + pending.notice("2", &consumed("i1")); + assert!( + matches!( + fire_switch(&mut client, "session", &mut switches, &mut default, None).await, + Ok(SwitchFire::Fired) + ), + "the consumed input releases the chained move" + ); + assert_eq!(default, "3", "the chained move holds the new default"); + } + /// A switch that has started its target stays with it: a tool line opened /// afterwards has its own purpose, so the retry of a move promotes the /// line that started rather than the newer line (model-prompts §9.8). @@ -9083,6 +9202,17 @@ mod tests { struct SwitchRecorder { calls: Vec<(String, Value)>, refusals: Vec, + /// The input ids its `session.submit` answers carry, in order; a call + /// past the list answers an empty result. + inputs: VecDeque, + } + impl SwitchRecorder { + fn methods(&self) -> Vec<&str> { + self.calls + .iter() + .map(|(method, _)| method.as_str()) + .collect() + } } impl SwitchClient for SwitchRecorder { async fn rpc(&mut self, method: &str, params: Value) -> dim_client::Result { @@ -9090,10 +9220,37 @@ mod tests { if method == "session.branch_set_default" && !self.refusals.is_empty() { return Err(self.refusals.remove(0).into()); } + if method == "session.submit" + && let Some(input) = self.inputs.pop_front() + { + return Ok(json!({"event": {"id": input}})); + } Ok(json!({})) } } + /// The `branch:line` message a move writes on `line`: the role it gives + /// the line and the participant it names (design §12.1). + fn move_note(line: &str, default: bool, other: &str) -> Value { + let marker = if default { + format!("This line is now the session's default branch, switched from line {other}.") + } else { + format!("The session's default branch moved from this line to line {other}.") + }; + let text = format!( + "\n{marker}\n", + if default { "true" } else { "false" } + ); + json!({"type": "input", "name": "message", "id": format!("note-{line}"), "sequence": 1, + "data": {"blocks": [{"type": "raw", "key": "branch:line", "text": text}]}}) + } + + /// The `input/consumed` notice of `input` on a line. + fn consumed(input: &str) -> Value { + json!({"type": "input", "name": "consumed", "id": format!("consumed-{input}"), + "sequence": 2, "data": {"input_id": input}}) + } + /// A move whose target has started its first turn, ready to move. fn triggered_switch() -> VecDeque { let mut pending = PendingSwitch::new( From f5aed3b1b42406b85d2d56d540e63ccca064101d Mon Sep 17 00:00:00 2001 From: huihui Date: Mon, 23 Nov 2026 14:18:01 +0800 Subject: [PATCH 27/35] fix(xtask): wait for a move's notes before its follow-ups `session.branch_set_default` answering publishes the root move; the line's `branch:line` note is written by the line's own task afterwards. A switch therefore submitted its follow-ups while an idle line could already start the request that answered them, so the policy comparison could score an answer that did not see the text being evaluated. A move now records the lines that answer its follow-ups and sends nothing until each has written its note, within the scenario's existing budget. A chained move also waits until the line that took the previous move's input has consumed it, so the next move cannot retire that line's note before its request starts. Before the judge, the run reads the exported Timeline: the request that consumed each follow-up must carry the note the move wrote on that line. A run whose request does not is failed with `switch_note_missing` and is not judged. `a_follow_up_waits_for_the_note_after_the_moves_acknowledgment`, `a_chained_move_waits_for_the_input_before_it` and `a_request_that_consumed_a_follow_up_without_its_note_is_unseen` pin the timing and the check, and `the_user_line_switch_carries_both_notes_into_the_requests` asserts the note in the exact request that consumed each follow-up. --- xtask/src/scenario_eval.rs | 735 ++++++++++++++++++++++++++++++++++--- 1 file changed, 681 insertions(+), 54 deletions(-) diff --git a/xtask/src/scenario_eval.rs b/xtask/src/scenario_eval.rs index be4e0fdebc..d21c8c19a3 100644 --- a/xtask/src/scenario_eval.rs +++ b/xtask/src/scenario_eval.rs @@ -1382,6 +1382,7 @@ fn stop_name(stop: &str) -> Result<&'static str> { "switch_target_not_reached" => Ok("switch_target_not_reached"), "switch_target_ended" => Ok("switch_target_ended"), "switch_target_unknown" => Ok("switch_target_unknown"), + "switch_note_missing" => Ok("switch_note_missing"), "error" => Ok("error"), other => Err(format!("the saved run has an unknown stop {other}").into()), } @@ -2080,15 +2081,32 @@ struct PendingSwitch { switch: Switch, line: Option, /// The target line's first `turn/start` has been seen: the move and the - /// next input happen now, or on a retry while the line is not ready. + /// next input happen now, or on a retry while the line is not ready. A + /// chained move is due once the input before it has been consumed. triggered: bool, /// The further attempts left while the move answers `unknown_branch`. retries_left: u32, + /// `session.branch_set_default` answered: the follow-ups this move sends + /// wait for the notes it writes on the lines that answer them. + moved: bool, + /// The line the move left once it answered. + former: Option, + /// The note the move wrote on the target line, and on the line it left. + target_note: Option, + former_note: Option, + /// A line the move owes a note ended before it wrote one: the line can + /// answer no follow-up. + ended: Option<(String, String)>, + /// The input the move before this one sent, and the line that took it: a + /// chained move fires once that line consumed it. + previous: Option<(String, String)>, } impl PendingSwitch { - /// `chained` switches fire right after the move before them instead of - /// waiting for their target's first `turn/start`: a second move runs on - /// a line that may have started its first turn before the run reached it. + /// `chained` switches do not wait for their target's first `turn/start`: + /// a second move runs on a line that may have started its first turn + /// before the run reached it. Such a move fires once the input the move + /// before it sent has been consumed, so the note the previous move wrote + /// on its target cannot be retired before that target answers. fn new(switch: Switch, user_line: Option<&str>, chained: bool) -> Self { let line = match &switch.to { SwitchTarget::Id(id) => Some(id.clone()), @@ -2100,15 +2118,57 @@ impl PendingSwitch { line, triggered: chained, retries_left: UNKNOWN_BRANCH_RETRIES, - } - } - - /// Reads one notice: a tool `branch/create` renames the role's target, and - /// the target's first `turn/start` is when the move and the next input - /// happen. Once that turn has started the target is fixed: a line opened - /// afterwards has its own purpose, and the move and the input after it - /// stay with the line that started. + moved: false, + former: None, + target_note: None, + former_note: None, + ended: None, + previous: None, + } + } + + /// Reads one notice: a tool `branch/create` renames the role's target, the + /// target's first `turn/start` is when a single move and the next input + /// happen, a `branch:line` message is a note the move wrote, and a chained + /// move moves on when the input before it has been consumed. Once that + /// turn has started the target is fixed: a line opened afterwards has its + /// own purpose, and the move and the input after it stay with the line + /// that started. fn notice(&mut self, branch: &str, event: &Value) { + if event["type"] == "branch" && matches!(event["name"].as_str(), Some("end" | "ended")) { + if Some(branch) == self.line.as_deref() || self.former.as_deref() == Some(branch) { + self.ended = Some(( + branch.to_owned(), + format!("line {branch} ended before its move note was written"), + )); + } + if self + .previous + .as_ref() + .is_some_and(|(line, _)| line == branch) + { + self.previous = None; + self.triggered = true; + } + return; + } + if event["type"] == "input" + && event["name"] == "consumed" + && let Some((_, input)) = &self.previous + && event["data"]["input_id"].as_str() == Some(input.as_str()) + { + self.previous = None; + self.triggered = true; + return; + } + if let Some(note) = branch_line_note(event, branch) { + if Some(branch) == self.line.as_deref() { + self.target_note = Some(note); + } else if self.former.as_deref() == Some(branch) { + self.former_note = Some(note); + } + return; + } if let Some(line) = tool_line(event) { if (!self.triggered || self.line.is_none()) && matches!( @@ -2128,12 +2188,15 @@ impl PendingSwitch { } } - /// Activates a chained move: it fires right after the move before it, so a - /// move to the latest tool line takes the line the run has recorded. A - /// move without one keeps waiting for a `branch/create` notice, as a - /// single move does. - fn activated(&mut self, latest_tool_line: Option<&str>) { - self.triggered = true; + /// Activates a chained move: it fires once the input the move before it + /// sent is consumed, so that move's target answers with its note in + /// effect. A move to the latest tool line takes the line the run has + /// recorded; one without a line keeps waiting for a `branch/create` + /// notice, as a single move does. A Session that named no input (the + /// move's answer carried no id) leaves the move due at once. + fn activated(&mut self, latest_tool_line: Option<&str>, previous: Option<(String, String)>) { + self.triggered = previous.is_none(); + self.previous = previous; if self.line.is_none() && matches!( &self.switch.to, @@ -2143,7 +2206,112 @@ impl PendingSwitch { self.line = latest_tool_line.map(str::to_owned); } } + + /// The notes this move's follow-ups need: one for each line that answers + /// one, when that line takes the move's role and is not the root, which + /// writes no note (design §12.1). + fn notes(&self, target: &str, former: &str) -> Vec<(String, bool, String)> { + let mut notes = Vec::new(); + let message_line = self.switch.branch_id.as_deref().unwrap_or(target); + if message_line == target && target != "main" { + notes.push((target.to_owned(), true, former.to_owned())); + } else if message_line == former && former != "main" { + notes.push((former.to_owned(), false, target.to_owned())); + } + if self.switch.former_message.is_some() && former != "main" { + notes.push((former.to_owned(), false, target.to_owned())); + } + notes + } + + /// Whether the note the move wrote on `line` is in: the role it states and + /// the participant it names. + fn saw_note(&self, line: &str, default: bool, other: &str) -> bool { + let note = if Some(line) == self.line.as_deref() { + &self.target_note + } else if self.former.as_deref() == Some(line) { + &self.former_note + } else { + return false; + }; + note.as_ref().is_some_and(|note| { + note.default == default && note.text.contains(¬e_marker(default, other)) + }) + } } + +/// A move's status note as a line published it: whether the line became the +/// default, and the note's text, which names the other participant. +struct NoteSeen { + default: bool, + text: String, +} + +/// The sentence a move's note states for role `default` and participant +/// `other`: the fixed words around the line id (design §12.1). +fn note_marker(default: bool, other: &str) -> String { + if default { + format!("switched from line {other}.") + } else { + format!("moved from this line to line {other}.") + } +} + +/// The status note a `branch:line` message carries for `branch`: the role it +/// states and its text. A message without that block, or for another line, +/// answers `None` (design §5, §12.1). +fn branch_line_note(event: &Value, branch: &str) -> Option { + if event["type"] != "input" || event["name"] != "message" { + return None; + } + for block in event["data"]["blocks"].as_array()? { + if block["key"] != "branch:line" { + continue; + } + let text = block["text"].as_str()?; + let tag = text.split_once('>')?.0; + if note_attribute(tag, "branch") != Some(branch) { + continue; + } + let default = match note_attribute(tag, "default") { + Some("true") => true, + Some("false") => false, + _ => continue, + }; + return Some(NoteSeen { + default, + text: text.to_owned(), + }); + } + None +} + +/// One attribute of a `` tag. +fn note_attribute<'a>(tag: &'a str, name: &str) -> Option<&'a str> { + tag.split(' ').find_map(|attribute| { + let (key, value) = attribute.split_once("=\"")?; + (key == name).then(|| value.strip_suffix('"')).flatten() + }) +} + +/// One follow-up a move sent and the note its line must have written before +/// the request that consumes it: the line, the input the Session wrote, and +/// the note's role and other participant. +struct SwitchNote { + line: String, + input: String, + default: bool, + other: String, +} + +/// The run's switch follow-ups and the notes they must follow: a move waits +/// for each note before it submits the input its line answers, and the run is +/// not judged when a request consumed an input without its note. +#[derive(Default)] +struct SwitchNotes { + expected: Vec, +} + /// One source a scenario declares through the `eventHub` service, and /// optionally subscribes its Session's `main` branch to (EventHub design A.1, /// A.3). Without `subscribe` the source starts unsubscribed, for a scenario @@ -2520,7 +2688,8 @@ struct RunRecord { texts: Vec, session: Option, /// `idle`, `turns`, `seconds`, `switch_target_not_reached`, - /// `switch_target_ended`, `switch_target_unknown` or `error`. + /// `switch_target_ended`, `switch_target_unknown`, `switch_note_missing` + /// or `error`. stop: &'static str, turns: u32, window: Option, @@ -3599,7 +3768,7 @@ async fn product_probe( .rpc("session.attach", json!({"sessionId": probe})) .await .map_err(|error| format!("session.attach failed: {error}"))?; - submit(client, &probe, "PRODUCT-TOOLS\n", None, None) + let _ = submit(client, &probe, "PRODUCT-TOOLS\n", None, None) .await .map_err(|error| error.to_string())?; loop { @@ -3762,7 +3931,7 @@ async fn preflight_session( .rpc("session.attach", json!({"sessionId": session})) .await .map_err(|error| (Vec::new(), format!("session.attach failed: {error}")))?; - submit(client, &session, &message, None, None) + let _ = submit(client, &session, &message, None, None) .await .map_err(|error| (Vec::new(), error))?; // The tool results in arrival order: the scripted steps run one per @@ -5366,6 +5535,7 @@ fn child_record( "switch_target_not_reached" => "switch_target_not_reached", "switch_target_ended" => "switch_target_ended", "switch_target_unknown" => "switch_target_unknown", + "switch_note_missing" => "switch_note_missing", _ => "error", }; let error = match &outcome.harness { @@ -5459,6 +5629,7 @@ impl Finished { window: None, decline_retries: 0, switch_retries: 0, + switch_notes: SwitchNotes::default(), error: Some(error), }, export: None, @@ -5685,6 +5856,22 @@ async fn drive_once( }); } }; + // A scored follow-up must answer under the note its move wrote. A run + // whose request consumed the input without it is failed before the judge, + // so the policy comparison cannot score an answer that did not see the + // text being evaluated (Timeline branches §12.4). + if driven.error.is_none() + && let Some(error) = switch_notes_unseen(&export, &driven.switch_notes.expected) + { + driven.stop = "switch_note_missing"; + driven.error = Some(error.clone()); + return Ok(Finished { + driven, + export: Some(export), + view: None, + judging: Judging::not_asked(scenario, Some(error)), + }); + } let (Some(host), Some(resolver)) = ( server.service::(), server.service::(), @@ -5829,6 +6016,127 @@ fn settle_failed_turn(driven: &mut Driven, failed_turn: Option) { } } +/// Why a scored switch follow-up did not see its note, or `None` when every +/// consumed follow-up's request carries it: the request the line began after +/// it consumed the input, and the note's exact text (Timeline branches §12.4). +/// An input no request consumed is not checked: no answer of that line is +/// scored. +fn switch_notes_unseen(export: &str, notes: &[SwitchNote]) -> Option { + /// One `input/message` of the export, the line it is on, and the note it + /// carries when it is one. + struct Message { + branch: String, + note: Option, + } + let mut messages: BTreeMap = BTreeMap::new(); + let mut consumed: Vec<(String, u64, String)> = Vec::new(); + let mut starts: Vec<(String, u64, String)> = Vec::new(); + let mut calls: BTreeMap<(String, String), Value> = BTreeMap::new(); + for line in export.lines() { + let Ok(record) = serde_json::from_str::(line) else { + continue; + }; + if record["kind"] != "event" { + continue; + } + let branch = record["branch_id"].as_str().unwrap_or_default().to_owned(); + let event = &record["event"]; + let sequence = event["sequence"].as_u64().unwrap_or_default(); + let id = event["id"].as_str().unwrap_or_default().to_owned(); + match (event["type"].as_str(), event["name"].as_str()) { + (Some("input"), Some("message")) => { + messages.insert( + id, + Message { + note: branch_line_note(event, &branch), + branch, + }, + ); + } + (Some("input"), Some("consumed")) => { + if let Some(input) = event["data"]["input_id"].as_str() { + consumed.push((branch, sequence, input.to_owned())); + } + } + (Some("step"), Some("model-start")) => { + if let Some(request) = event["data"]["request_id"].as_str() { + starts.push((branch, sequence, request.to_owned())); + } + } + (Some("model"), Some("call")) => { + if let Some(request) = event["data"]["request_id"].as_str() { + calls.insert( + (branch, request.to_owned()), + event["data"]["request"].clone(), + ); + } + } + _ => {} + } + } + for note in notes { + let Some(message) = messages.get(¬e.input) else { + return Some(format!( + "the switch input {} on line {} is not in the export", + note.input, note.line + )); + }; + let Some(consumed_at) = consumed + .iter() + .filter(|(branch, _, input)| branch == &message.branch && input == ¬e.input) + .map(|(_, sequence, _)| *sequence) + .min() + else { + continue; + }; + let Some((_, _, request)) = starts + .iter() + .filter(|(branch, sequence, _)| branch == &message.branch && *sequence > consumed_at) + .min_by_key(|(_, sequence, _)| *sequence) + else { + return Some(format!( + "line {} consumed the switch input {} but started no request after it", + note.line, note.input + )); + }; + let Some(call) = calls.get(&(message.branch.clone(), request.clone())) else { + return Some(format!( + "line {} consumed the switch input {} but its request never reached the model", + note.line, note.input + )); + }; + let marker = note_marker(note.default, ¬e.other); + let texts: Vec<&str> = messages + .values() + .filter(|message| message.branch == note.line) + .filter_map(|message| message.note.as_ref()) + .filter(|seen| seen.default == note.default && seen.text.contains(&marker)) + .map(|seen| seen.text.as_str()) + .collect(); + if !texts + .iter() + .any(|text| request_carries(&call["messages"], text)) + { + return Some(format!( + "the request that consumed the switch input on line {} does not carry the note it must answer under", + note.line + )); + } + } + None +} + +/// Whether any string in `value` carries `needle`: a request is JSON, so a +/// text with quotes in it is compared through the parsed value. +fn request_carries(value: &Value, needle: &str) -> bool { + match value { + Value::String(text) => text.contains(needle), + Value::Array(items) => items.iter().any(|item| request_carries(item, needle)), + Value::Object(map) => map.values().any(|item| request_carries(item, needle)), + _ => false, + } +} + pub(crate) async fn selection( server: &RunningServer, target: &ModelId, @@ -5901,6 +6209,9 @@ struct Driven { /// How many times the runner moved again after the target line answered /// `unknown_branch`. switch_retries: u32, + /// The switch follow-ups the run sent and the notes each line's request + /// must carry; the run is not judged when one is missing. + switch_notes: SwitchNotes, error: Option, } @@ -5940,6 +6251,7 @@ async fn drive( window: None, decline_retries: 0, switch_retries: 0, + switch_notes: SwitchNotes::default(), error: Some(error), }; } @@ -5965,6 +6277,7 @@ async fn drive( window: None, decline_retries: 0, switch_retries: 0, + switch_notes: SwitchNotes::default(), error: Some(format!("session.create failed: {error}")), }; } @@ -5978,6 +6291,7 @@ async fn drive( window: None, decline_retries: 0, switch_retries: 0, + switch_notes: SwitchNotes::default(), error: None, }; if let Err(error) = client @@ -6104,6 +6418,10 @@ async fn drive( // uses it: a `branch/create` reaches only the move that is front when it // arrives. let mut latest_tool_line: Option = None; + // The follow-ups the moves sent and the notes their lines must carry: a + // move waits for its notes before it sends them, and the run is not judged + // when a request consumed one without its note. + let mut switch_notes = SwitchNotes::default(); let mut last_event = Instant::now(); // The events still to publish, and whether each was. let mut events: Vec<(EventSpec, bool)> = scenario @@ -6174,6 +6492,7 @@ async fn drive( &mut switches, &mut default, latest_tool_line.as_deref(), + Some(&mut switch_notes), ), ) .await @@ -6245,6 +6564,20 @@ async fn drive( tokio::time::Instant::now() + cleanup_budget(settings.stall_cleanup, settings.cleanup_budget_ms), ); + // A pending switch the run stopped waiting on names itself, as the + // move's own deadline does: its note or its input did not come. + if let Some(pending) = switches.front() { + driven.error = Some(match &pending.line { + Some(line) => format!( + "the switch to line {line} did not answer before the run's {}s budget ran out", + scenario.budget.seconds + ), + None => format!( + "the switch did not answer before the run's {}s budget ran out", + scenario.budget.seconds + ), + }); + } break; } if driven.turns >= scenario.budget.turns { @@ -6430,8 +6763,25 @@ async fn drive( } } } - if let Some(pending) = switches.front() { + // A move that already happened leaves the outcome the run reached: the + // move is not the thing the run stopped waiting on (the run may have been + // waiting for its note or its input). A move that never happened keeps its + // own outcome, so a scenario that could not switch is not read as a run + // that reached its budget. + if let Some(pending) = switches.front() + && !pending.moved + { let reason = match (&pending.line, pending.triggered) { + _ if pending.previous.is_some() => match &pending.line { + Some(line) => format!( + "the chained move to line {line} did not fire: the input before it was not consumed before the run stopped on {}", + driven.stop + ), + None => format!( + "the chained move did not fire: its target was not opened and the input before it was not consumed before the run stopped on {}", + driven.stop + ), + }, (Some(line), true) => format!( "the move to line {line} did not complete before the run stopped on {}", driven.stop @@ -6455,6 +6805,7 @@ async fn drive( driven.error = Some(reason); } } + driven.switch_notes = switch_notes; driven } @@ -7300,18 +7651,21 @@ fn submit_params( params } +/// Sends one input and answers the id the Session wrote it under, when the +/// reply names the event: a switch records it to check the note the line's +/// request must carry. async fn submit( client: &mut impl SwitchClient, session: &str, text: &str, mode: Option, branch: Option<&str>, -) -> std::result::Result<(), String> { - client +) -> std::result::Result, String> { + let reply = client .rpc("session.submit", submit_params(session, text, mode, branch)) .await - .map(|_| ()) - .map_err(|error| format!("session.submit failed: {error}")) + .map_err(|error| format!("session.submit failed: {error}"))?; + Ok(reply["event"]["id"].as_str().map(str::to_owned)) } /// The one RPC a switch and its next input make; the tests' fake records the @@ -7358,20 +7712,27 @@ fn unknown_branch(error: &dim_client::Error) -> bool { } /// Runs the next move once it is due: the Session's default branch moves -/// first, then the next input is submitted, naming a line only when the -/// scenario does, and then the input meant for the line it moved away from. -/// A move fires once and leaves the queue; the move after it fires on the next -/// call, and is activated here with the tool line the run has seen opened. +/// first, and then the inputs the move sends: the one on the new default, +/// naming a line only when the scenario does, and the one meant for the line +/// it moved away from. With `notes`, those inputs wait for the notes the move +/// writes on the lines that answer them, and each input is recorded with its +/// note for the run's check before the judge. A move fires once and leaves the +/// queue; the move after it fires on a later call once its input has been +/// consumed, and is activated here with the tool line the run has seen opened. async fn fire_switch( client: &mut impl SwitchClient, session: &str, switches: &mut VecDeque, default: &mut String, latest_tool_line: Option<&str>, + notes: Option<&mut SwitchNotes>, ) -> std::result::Result { let Some(pending) = switches.front_mut() else { return Ok(SwitchFire::NotFired); }; + if pending.moved { + return send_switch_follow_ups(client, session, switches, latest_tool_line, notes).await; + } if !pending.triggered { return Ok(SwitchFire::NotFired); } @@ -7405,12 +7766,52 @@ async fn fire_switch( } return Err(format!("the switch to {line} failed: {error}")); } - let pending = switches.pop_front().expect("the switch is pending"); - if let Some(next) = switches.front_mut() { - next.activated(latest_tool_line); - } + let pending = switches.front_mut().expect("the switch is pending"); let former = std::mem::replace(default, line); - submit( + pending.moved = true; + pending.former = Some(former); + send_switch_follow_ups(client, session, switches, latest_tool_line, notes).await +} + +/// Sends a moved switch's follow-ups once the notes they must follow are in, +/// and records each input with the note its line answers under. A line the +/// move owes a note that ended first fails the run's switch instead. +async fn send_switch_follow_ups( + client: &mut impl SwitchClient, + session: &str, + switches: &mut VecDeque, + latest_tool_line: Option<&str>, + mut notes: Option<&mut SwitchNotes>, +) -> std::result::Result { + let Some(pending) = switches.front() else { + return Ok(SwitchFire::NotFired); + }; + let target = pending.line.clone().expect("a moved switch names its line"); + let former = pending.former.clone().expect("a moved switch left a line"); + let wanted = pending.notes(&target, &former); + if notes.is_some() { + if let Some((line, error)) = &pending.ended + && wanted.iter().any(|(awaited, _, _)| awaited == line) + { + let line = line.clone(); + let error = error.clone(); + switches.pop_front(); + return Ok(SwitchFire::TargetEnded { line, error }); + } + if !wanted + .iter() + .all(|(line, default, other)| pending.saw_note(line, *default, other)) + { + return Ok(SwitchFire::NotFired); + } + } + let pending = switches.pop_front().expect("the switch is pending"); + let message_line = pending + .switch + .branch_id + .clone() + .unwrap_or_else(|| target.clone()); + let receipt = submit( client, session, &pending.switch.message, @@ -7418,8 +7819,39 @@ async fn fire_switch( pending.switch.branch_id.as_deref(), ) .await?; + if let Some(gate) = notes.as_mut() { + let input = receipt.clone().ok_or_else(|| { + format!("session.submit answered no input id for the switch to {target}") + })?; + for (line, default, other) in &wanted { + if *line == message_line { + gate.expected.push(SwitchNote { + line: line.clone(), + input: input.clone(), + default: *default, + other: other.clone(), + }); + } + } + } if let Some(message) = pending.switch.former_message.as_deref() { - submit(client, session, message, None, Some(former.as_str())).await?; + let receipt = submit(client, session, message, None, Some(former.as_str())).await?; + if let Some(gate) = notes.as_mut() + && former != "main" + { + let input = receipt.ok_or_else(|| { + format!("session.submit answered no input id for the switch to {target}") + })?; + gate.expected.push(SwitchNote { + line: former.clone(), + input, + default: false, + other: target.clone(), + }); + } + } + if let Some(next) = switches.front_mut() { + next.activated(latest_tool_line, receipt.map(|input| (message_line, input))); } Ok(SwitchFire::Fired) } @@ -7438,7 +7870,7 @@ async fn fire_due( .is_some_and(|after| started.elapsed().as_secs_f64() >= after); if due && !*fired { *fired = true; - submit(client, session, &steer.text, Some(InputMode::Steer), None).await?; + let _ = submit(client, session, &steer.text, Some(InputMode::Steer), None).await?; sent = true; } } @@ -7465,7 +7897,7 @@ async fn fire_triggered( .is_some_and(|trigger| data.contains(trigger.as_str())); if triggered && !*fired { *fired = true; - submit(client, session, &steer.text, Some(InputMode::Steer), None).await?; + let _ = submit(client, session, &steer.text, Some(InputMode::Steer), None).await?; sent = true; } } @@ -8957,14 +9389,30 @@ mod tests { for move_number in [1, 2] { assert!( matches!( - fire_switch(&mut client, "session", &mut switches, &mut default, None).await, + fire_switch( + &mut client, + "session", + &mut switches, + &mut default, + None, + None + ) + .await, Ok(SwitchFire::Fired) ), "move {move_number}" ); } assert!(matches!( - fire_switch(&mut client, "session", &mut switches, &mut default, None).await, + fire_switch( + &mut client, + "session", + &mut switches, + &mut default, + None, + None + ) + .await, Ok(SwitchFire::NotFired) )); let calls: Vec<&str> = client @@ -9021,9 +9469,18 @@ mod tests { inputs: ["i1".to_owned()].into(), ..SwitchRecorder::default() }; + let mut notes = SwitchNotes::default(); assert!( matches!( - fire_switch(&mut client, "session", &mut switches, &mut default, None).await, + fire_switch( + &mut client, + "session", + &mut switches, + &mut default, + None, + Some(&mut notes) + ) + .await, Ok(SwitchFire::NotFired) ), "the move's answer alone sends nothing" @@ -9037,7 +9494,15 @@ mod tests { pending.notice("2", &move_note("2", true, "main")); assert!( matches!( - fire_switch(&mut client, "session", &mut switches, &mut default, None).await, + fire_switch( + &mut client, + "session", + &mut switches, + &mut default, + None, + Some(&mut notes) + ) + .await, Ok(SwitchFire::Fired) ), "the note releases the follow-up" @@ -9048,6 +9513,11 @@ mod tests { "the move runs before its input" ); assert_eq!(default, "2", "the move holds the new default"); + assert_eq!(notes.expected.len(), 1, "one input, one note"); + assert_eq!(notes.expected[0].line, "2"); + assert_eq!(notes.expected[0].input, "i1"); + assert!(notes.expected[0].default); + assert_eq!(notes.expected[0].other, "main"); } /// A chained move waits for the input the move before it sent: the first @@ -9088,14 +9558,30 @@ mod tests { .notice("2", &turn_start); assert!( matches!( - fire_switch(&mut client, "session", &mut switches, &mut default, None).await, + fire_switch( + &mut client, + "session", + &mut switches, + &mut default, + None, + None + ) + .await, Ok(SwitchFire::Fired) ), "the first move fires" ); assert!( matches!( - fire_switch(&mut client, "session", &mut switches, &mut default, None).await, + fire_switch( + &mut client, + "session", + &mut switches, + &mut default, + None, + None + ) + .await, Ok(SwitchFire::NotFired) ), "the chained move waits for the input before it" @@ -9109,7 +9595,15 @@ mod tests { pending.notice("2", &consumed("i1")); assert!( matches!( - fire_switch(&mut client, "session", &mut switches, &mut default, None).await, + fire_switch( + &mut client, + "session", + &mut switches, + &mut default, + None, + None + ) + .await, Ok(SwitchFire::Fired) ), "the consumed input releases the chained move" @@ -9117,6 +9611,53 @@ mod tests { assert_eq!(default, "3", "the chained move holds the new default"); } + /// The judge is not asked about a request that consumed a switch's input + /// without the note the move wrote: the check reads the export's + /// consumption and the request that began after it (Timeline branches + /// §12.4). + #[test] + fn a_request_that_consumed_a_follow_up_without_its_note_is_unseen() { + let note = "\nswitched from line main.\n"; + let export = |request: &str| { + [ + json!({"kind": "event", "branch_id": "2", + "event": {"id": "n1", "sequence": 1, "type": "input", "name": "message", + "data": {"blocks": [{"type": "raw", "key": "branch:line", + "text": note}]}}}), + json!({"kind": "event", "branch_id": "2", + "event": {"id": "f1", "sequence": 2, "type": "input", "name": "message", + "data": {}}}), + json!({"kind": "event", "branch_id": "2", + "event": {"id": "c1", "sequence": 3, "type": "input", "name": "consumed", + "data": {"input_id": "f1"}}}), + json!({"kind": "event", "branch_id": "2", + "event": {"id": "s1", "sequence": 4, "type": "step", "name": "model-start", + "data": {"request_id": "r1"}}}), + json!({"kind": "event", "branch_id": "2", + "event": {"id": "m1", "sequence": 5, "type": "model", "name": "call", + "data": {"request_id": "r1", + "request": {"messages": [{"role": "user", "content": request}]}}}}), + ] + .iter() + .map(|record| serde_json::to_string(record).unwrap()) + .collect::>() + .join("\n") + }; + let notes = [SwitchNote { + line: "2".into(), + input: "f1".into(), + default: true, + other: "main".into(), + }]; + assert!( + switch_notes_unseen(&export(note), ¬es).is_none(), + "the request carries the note" + ); + let unseen = switch_notes_unseen(&export("the follow-up was answered"), ¬es) + .expect("the request without the note is unseen"); + assert!(unseen.contains("line 2"), "{unseen}"); + } + /// A switch that has started its target stays with it: a tool line opened /// afterwards has its own purpose, so the retry of a move promotes the /// line that started rather than the newer line (model-prompts §9.8). @@ -9152,6 +9693,7 @@ mod tests { "session", &mut switch, &mut "main".into(), + None, None ) .await, @@ -9170,6 +9712,7 @@ mod tests { "session", &mut switch, &mut "main".into(), + None, None ) .await, @@ -9291,6 +9834,7 @@ mod tests { "session", &mut switch, &mut "main".into(), + None, None ) .await, @@ -9318,6 +9862,7 @@ mod tests { "session", &mut switch, &mut "main".into(), + None, None ) .await, @@ -9344,6 +9889,7 @@ mod tests { &mut switch, &mut "main".into(), None, + None, ) .await { @@ -9375,6 +9921,7 @@ mod tests { "session", &mut switch, &mut "main".into(), + None, None ) .await, @@ -9387,6 +9934,7 @@ mod tests { "session", &mut switch, &mut "main".into(), + None, None ) .await, @@ -9429,6 +9977,7 @@ mod tests { "session", &mut switch, &mut "main".into(), + None, None ) .await, @@ -9444,6 +9993,7 @@ mod tests { &mut switch, &mut "main".into(), None, + None, ) .await { @@ -9493,6 +10043,7 @@ mod tests { &mut switch, &mut "main".into(), None, + None, ) .await { @@ -11009,6 +11560,7 @@ mod tests { window: None, decline_retries: 0, switch_retries: 0, + switch_notes: SwitchNotes::default(), error: None, } } @@ -14067,6 +14619,8 @@ mod tests { // The `session.submit` calls read so far: the stalling scripts // hold the one after the move. let mut submits = 0; + // The default branch the chained scripts' moves leave. + let mut default = "main".to_owned(); let mut first: Option = None; // The line is busy until the peer writes the call's result, the // way a running turn is: `session.idle` stays unanswered and the @@ -14286,9 +14840,55 @@ mod tests { json!({"error": {"code": -32000, "message": "unknown branch: 2", "data": {"appError": "session_invalid_input"}}}) } + "session.submit" => { + json!({"result": {"event": {"id": format!("input-{submits}")}}}) + } _ => json!({"result": {}}), }; write.write_all(&frame(&request, body)).await.unwrap(); + // The line a chained script moves to writes its note after the + // move's acknowledgment: the run waits for that note before it + // sends the input the line answers. + if method == "session.branch_set_default" + && matches!( + script, + PeerScript::ChainedToolLineBeforeActivation + | PeerScript::ChainedToolLineAfterActivation + ) + { + let target = request["params"]["branchId"] + .as_str() + .unwrap_or_default() + .to_owned(); + let note = json!({ + "type": "input", "name": "message", "id": format!("note-{target}"), + "sequence": 6, + "data": {"blocks": [{"type": "raw", "key": "branch:line", + "text": format!( + "\nThis line is now the session's default branch, switched from line {default}.\n" + )}]} + }); + write.write_all(¬ice_on(&target, note)).await.unwrap(); + default = target; + } + // A chained script consumes the input it answered: the move + // after it fires once its line has taken that input. + if method == "session.submit" + && matches!( + script, + PeerScript::ChainedToolLineBeforeActivation + | PeerScript::ChainedToolLineAfterActivation + ) + { + let consumed = json!({ + "type": "input", "name": "consumed", "id": format!("consumed-{submits}"), + "sequence": 7, "data": {"input_id": format!("input-{submits}")} + }); + write + .write_all(¬ice_on(&default, consumed)) + .await + .unwrap(); + } if method == "session.submit" { write .write_all(¬ice( @@ -18048,6 +18648,12 @@ mod tests { .iter() .map(|(path, text)| (path.as_str(), text.as_str())) .collect(); + // The follow-ups the scenario sends: the tool line's input, then the + // user line's input and the former default's input. + let moves = scenario["moves"].as_array().cloned().unwrap_or_default(); + let tool_input = moves[0]["message"].as_str().unwrap().to_owned(); + let user_input = moves[1]["message"].as_str().unwrap().to_owned(); + let former_input = moves[1]["formerMessage"].as_str().unwrap().to_owned(); let fixture = Fixture::with_window( "user-line-notes", user_line_notes, @@ -18132,23 +18738,44 @@ mod tests { ); continue; } - let user_note = format!( + let default_note = format!( "How you work here:\n{}", - USER_NOTE.replace("{other}", &tool) + DEFAULT_NOTE + .replace("{parent}", "main") + .replace("{other}", "main") ); - assert!( - requests.iter().any(|request| carried(request, &user_note)), - "the user line's request carries its note with the tool line id: {user_note}" + let user_note = format!( + "How you work here:\n{}", + USER_NOTE + .replace("{parent}", "main") + .replace("{other}", &tool) ); let former_note = format!( "How you work here:\n{}", - FORMER_NOTE.replace("{other}", &user) + FORMER_NOTE + .replace("{parent}", "main") + .replace("{other}", &user) ); - assert!( + // The request that consumed each follow-up is the first that + // carries it: it must carry the note the move wrote on that line, + // so the line's answer was made under the policy text. + let consuming = |input: &str| -> &String { requests .iter() - .any(|request| carried(request, &former_note)), - "the former default line's request carries its note with the user line id: {former_note}" + .find(|request| carried(request, input)) + .unwrap_or_else(|| panic!("{arm}: a request answers {input:?}")) + }; + assert!( + carried(consuming(&tool_input), &default_note), + "the request that answers the tool line's follow-up carries the move's default note: {default_note}" + ); + assert!( + carried(consuming(&user_input), &user_note), + "the request that answers the user line's follow-up carries its note with the tool line id: {user_note}" + ); + assert!( + carried(consuming(&former_input), &former_note), + "the request that answers the former default's input carries its note with the user line id: {former_note}" ); for attribute in [ format!( From 7c0c245d0c032c6dab468ba3a2599b338e2a51ca Mon Sep 17 00:00:00 2001 From: huihui Date: Mon, 23 Nov 2026 17:36:57 +0800 Subject: [PATCH 28/35] test(xtask): end a run's turns before the move's note A run can reach its turn budget after a move answered while the note that releases its scored follow-up is still outstanding; such a run currently ends `turns` with no error and is judged like a complete scenario. `a_run_that_reaches_the_turn_budget_before_the_note_is_not_scored` adds a scripted peer whose last turn ends after the move's answer and before the note, and asserts the run is failed instead of scored. --- xtask/src/scenario_eval.rs | 61 ++++++++++++++++++++++++++++++++++++++ 1 file changed, 61 insertions(+) diff --git a/xtask/src/scenario_eval.rs b/xtask/src/scenario_eval.rs index 5a25a7cf26..ffe14d2799 100644 --- a/xtask/src/scenario_eval.rs +++ b/xtask/src/scenario_eval.rs @@ -14531,6 +14531,11 @@ mod tests { /// The target line `2` starts and ends its first turn and the move /// answers, and the input after the move never does. SwitchSubmitStalls, + /// The target line `2` starts and ends its first turn while the move + /// waits for the note it owes it: the move answers, the line writes + /// its note afterwards, and the run's turn budget ends it before the + /// note releases the follow-up. + SwitchNoteAfterTheLastTurn, /// The target line `2` starts and ends its first turn, the move to it /// never answers, and the Session's close never answers either: a run /// that stopped on its wall clock must still return, with cleanup @@ -14849,6 +14854,7 @@ mod tests { PeerScript::SwitchMoveRetries => None, PeerScript::SwitchMoveStalls | PeerScript::SwitchSubmitStalls + | PeerScript::SwitchNoteAfterTheLastTurn | PeerScript::SwitchMoveAndCloseStall => None, PeerScript::ChainedToolLineBeforeActivation | PeerScript::ChainedToolLineAfterActivation => None, @@ -14923,6 +14929,7 @@ mod tests { script, PeerScript::ChainedToolLineBeforeActivation | PeerScript::ChainedToolLineAfterActivation + | PeerScript::SwitchNoteAfterTheLastTurn ) { let target = request["params"]["branchId"] @@ -15021,6 +15028,7 @@ mod tests { PeerScript::SwitchMoveRetries | PeerScript::SwitchMoveStalls | PeerScript::SwitchSubmitStalls + | PeerScript::SwitchNoteAfterTheLastTurn | PeerScript::SwitchMoveAndCloseStall ) { for (name, sequence) in [("start", 1), ("end", 2)] { @@ -15235,6 +15243,59 @@ mod tests { ); } + /// A run that stops on its turn budget while a move waits for its note is + /// not scored: the move happened, but the input that must answer under + /// the note was never sent, so the run is incomplete instead of ending on + /// `turns` with no error (Timeline branches §12.4). + #[cfg(unix)] + #[tokio::test(flavor = "multi_thread", worker_threads = 2)] + async fn a_run_that_reaches_the_turn_budget_before_the_note_is_not_scored() { + let directory = std::env::temp_dir().join(format!( + "dim-scenario-eval-note-turn-budget-{}", + std::process::id() + )); + let (socket, reads) = + scripted_peer(&directory, 8_000, PeerScript::SwitchNoteAfterTheLastTurn).await; + let mut client = driver_client(socket).await; + let mut scenario = scenario(Vec::new()); + scenario.budget.turns = 1; + scenario.budget.seconds = 10.; + scenario.switch = Some(Switch { + to: SwitchTarget::Id("2".into()), + message: "next".into(), + branch_id: None, + former_message: None, + }); + let driven = drive( + &mut client, + &RunSettings::default(), + &scenario, + &std::env::temp_dir(), + &peer_model(), + &ProducerState::default(), + None, + ) + .await; + let moves: Vec = reads.moves.lock().unwrap().clone(); + let _ = std::fs::remove_dir_all(directory); + assert_eq!(moves, ["2"], "the move happened before the run stopped"); + assert_eq!(driven.turns, 1, "the run stopped on its turn budget"); + assert_eq!(driven.stop, "switch_incomplete", "{:?}", driven.error); + let error = driven.error.as_deref().unwrap_or_default(); + assert!( + error.contains("line 2") && error.contains("follow-up") && error.contains("turns"), + "{error}" + ); + assert!( + driven.switch_notes.expected.is_empty(), + "the run sent no scored follow-up" + ); + assert!( + failed(driven.stop, driven.error.as_deref(), JudgeOutcome::Judged), + "the incomplete switch is a failed run and enters no probe rate" + ); + } + /// A chained move to the latest tool line uses the line the run has seen /// opened, even when it opened while the move before it waited: a line /// that exists when the move is activated is the one its role names, so From f05221ef5f1de05cf0f092c56df2e38c26437837 Mon Sep 17 00:00:00 2001 From: huihui Date: Mon, 23 Nov 2026 17:38:13 +0800 Subject: [PATCH 29/35] fix(xtask): fail a move whose scored follow-ups never leave A run that reached its turn budget after a move was acknowledged, while the note that releases the move's scored follow-up was still outstanding, ended `turns` with no error and was judged and counted in its arm's probe rates like a complete scenario. The final pending-switch check now marks any switch still at the front incomplete, except a wall-clock stop that already names the switch it stopped waiting on: a moved switch with unsent follow-ups is recorded as `switch_incomplete` and failed, so it enters no probe rate. `a_run_that_reaches_the_turn_budget_before_the_note_is_not_scored` pins the turn-budget path with a scripted peer. --- xtask/src/scenario_eval.rs | 88 ++++++++++++++++++++++++-------------- 1 file changed, 56 insertions(+), 32 deletions(-) diff --git a/xtask/src/scenario_eval.rs b/xtask/src/scenario_eval.rs index ffe14d2799..6d71fde15c 100644 --- a/xtask/src/scenario_eval.rs +++ b/xtask/src/scenario_eval.rs @@ -1432,6 +1432,7 @@ fn stop_name(stop: &str) -> Result<&'static str> { "switch_target_ended" => Ok("switch_target_ended"), "switch_target_unknown" => Ok("switch_target_unknown"), "switch_note_missing" => Ok("switch_note_missing"), + "switch_incomplete" => Ok("switch_incomplete"), "error" => Ok("error"), other => Err(format!("the saved run has an unknown stop {other}").into()), } @@ -2737,8 +2738,8 @@ struct RunRecord { texts: Vec, session: Option, /// `idle`, `turns`, `seconds`, `switch_target_not_reached`, - /// `switch_target_ended`, `switch_target_unknown`, `switch_note_missing` - /// or `error`. + /// `switch_target_ended`, `switch_target_unknown`, `switch_note_missing`, + /// `switch_incomplete` or `error`. stop: &'static str, turns: u32, window: Option, @@ -5597,6 +5598,7 @@ fn child_record( "switch_target_ended" => "switch_target_ended", "switch_target_unknown" => "switch_target_unknown", "switch_note_missing" => "switch_note_missing", + "switch_incomplete" => "switch_incomplete", _ => "error", }; let error = match &outcome.harness { @@ -6001,13 +6003,17 @@ async fn drive_once( } /// Whether the run is a failed run (model-prompts §8.1): it failed on its -/// own, an error, its wall-clock budget or a switch that could not happen, -/// or its judging did not happen — a judge call failed, there was no export -/// to judge, or no model host for the judge. +/// own, an error, its wall-clock budget or a switch that could not happen or +/// did not send its scored follow-ups, or its judging did not happen — a judge +/// call failed, there was no export to judge, or no model host for the judge. fn failed(stop: &str, error: Option<&str>, judge_outcome: JudgeOutcome) -> bool { matches!( stop, - "seconds" | "switch_target_not_reached" | "switch_target_ended" | "switch_target_unknown" + "seconds" + | "switch_target_not_reached" + | "switch_target_ended" + | "switch_target_unknown" + | "switch_incomplete" ) || error.is_some() || matches!( judge_outcome, @@ -6824,37 +6830,51 @@ async fn drive( } } } - // A move that already happened leaves the outcome the run reached: the - // move is not the thing the run stopped waiting on (the run may have been - // waiting for its note or its input). A move that never happened keeps its - // own outcome, so a scenario that could not switch is not read as a run - // that reached its budget. + // A switch still at the front when the loop ended never completed. A move + // that never happened keeps its own outcome, so a scenario that could not + // switch is not read as a run that reached its budget. A move that + // happened without sending its scored follow-ups is incomplete: no request + // answered under the text the evaluation compares, so the run is failed + // instead of scored as a complete scenario. A run that stopped on its wall + // clock already named the switch it stopped waiting on and keeps that + // ending. if let Some(pending) = switches.front() - && !pending.moved + && !(driven.stop == "seconds" && driven.error.is_some()) { - let reason = match (&pending.line, pending.triggered) { - _ if pending.previous.is_some() => match &pending.line { - Some(line) => format!( - "the chained move to line {line} did not fire: the input before it was not consumed before the run stopped on {}", + let reason = if pending.moved { + let line = pending + .line + .as_deref() + .expect("a moved switch names its line"); + format!( + "the move to line {line} happened but its scored follow-up was not sent before the run stopped on {}", + driven.stop + ) + } else { + match (&pending.line, pending.triggered) { + _ if pending.previous.is_some() => match &pending.line { + Some(line) => format!( + "the chained move to line {line} did not fire: the input before it was not consumed before the run stopped on {}", + driven.stop + ), + None => format!( + "the chained move did not fire: its target was not opened and the input before it was not consumed before the run stopped on {}", + driven.stop + ), + }, + (Some(line), true) => format!( + "the move to line {line} did not complete before the run stopped on {}", driven.stop ), - None => format!( - "the chained move did not fire: its target was not opened and the input before it was not consumed before the run stopped on {}", + (Some(line), false) => format!( + "the switch never fired: line {line}'s first turn did not start before the run stopped on {}", driven.stop ), - }, - (Some(line), true) => format!( - "the move to line {line} did not complete before the run stopped on {}", - driven.stop - ), - (Some(line), false) => format!( - "the switch never fired: line {line}'s first turn did not start before the run stopped on {}", - driven.stop - ), - (None, _) => format!( - "the switch never fired: the line its role names was never opened before the run stopped on {}", - driven.stop - ), + (None, _) => format!( + "the switch never fired: the line its role names was never opened before the run stopped on {}", + driven.stop + ), + } }; if driven.stop == "error" { driven.error = Some(match driven.error.take() { @@ -6862,7 +6882,11 @@ async fn drive( None => reason, }); } else { - driven.stop = "switch_target_not_reached"; + driven.stop = if pending.moved { + "switch_incomplete" + } else { + "switch_target_not_reached" + }; driven.error = Some(reason); } } From d8783cba31ce723c410d408d6a4ce31064dc3fee Mon Sep 17 00:00:00 2001 From: huihui Date: Mon, 23 Nov 2026 18:19:02 +0800 Subject: [PATCH 30/35] fix(xtask): report a switch that never moved as not reached A switch that never moved is reported as `switch_target_not_reached` again when the run stopped on its wall clock, so a scenario that could not switch is not read as a run that reached its budget; only a move that happened and left its scored follow-ups unsent is incomplete. --- xtask/src/scenario_eval.rs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/xtask/src/scenario_eval.rs b/xtask/src/scenario_eval.rs index 6d71fde15c..5f00c1d0e5 100644 --- a/xtask/src/scenario_eval.rs +++ b/xtask/src/scenario_eval.rs @@ -6839,7 +6839,7 @@ async fn drive( // clock already named the switch it stopped waiting on and keeps that // ending. if let Some(pending) = switches.front() - && !(driven.stop == "seconds" && driven.error.is_some()) + && !(pending.moved && driven.stop == "seconds" && driven.error.is_some()) { let reason = if pending.moved { let line = pending From 1148425925d3f5c0d2159d3bb180e266e8a1dfc4 Mon Sep 17 00:00:00 2001 From: huihui Date: Tue, 24 Nov 2026 11:21:09 +0800 Subject: [PATCH 31/35] refactor(branch): keep the opening policy out of the shipped texts Restore the branch tool description to its pre-policy text, keeping the corrected cascade sentence as its last line, and delete the three built-in status-note blocks so a note writes a guidance block only when the factory configures one. The design returns section 12.1's tool description and status-note rows and section 12.4's policy pointers to that same state, and the tests this change added assert the empty default and a configured block instead of the built-in bullets. The candidate texts, their baseline fixtures and the evaluation that judges them belong to a later change. --- .../src/timeline_tree.rs | 60 +++------- .../tests/branch_flow.rs | 109 +++++++----------- docs/design/timeline-branches.md | 16 +-- docs/zh/design/timeline-branches.md | 16 +-- 4 files changed, 73 insertions(+), 128 deletions(-) diff --git a/crates/dim-agent-capabilities/src/timeline_tree.rs b/crates/dim-agent-capabilities/src/timeline_tree.rs index 00484cd03c..534a51033e 100644 --- a/crates/dim-agent-capabilities/src/timeline_tree.rs +++ b/crates/dim-agent-capabilities/src/timeline_tree.rs @@ -5053,16 +5053,13 @@ impl BranchLine { format!( "This line is now the session's default branch, switched from line {other}. While this block is your latest one: answer the user here; you can open lines with create; you send no automatic idle notice to {parent}; you cannot call end on yourself. Line {other} stays open and keeps the lines it opened." ), - self.config.default_note.as_deref().unwrap_or(DEFAULT_NOTE), + self.config.default_note.as_deref().unwrap_or(""), ), _ => ( format!( "The user has now made this line the session's default branch, switched from line {other}. While this block is your latest one: answer the user here; you can open lines with create; you cannot call end on yourself; the user ends this line. Line {other} stays open and keeps the lines it opened." ), - self.config - .user_default_note - .as_deref() - .unwrap_or(USER_DEFAULT_NOTE), + self.config.user_default_note.as_deref().unwrap_or(""), ), } } else if kind == "tool" { @@ -5070,20 +5067,14 @@ impl BranchLine { format!( "The session's default branch moved from this line to line {other}. This line stays open, reports to {parent} as before and keeps coordinating the lines it opened; it can no longer open lines with create, and the rest of the rules above hold again. {CANNOT_END_TEXT} If end is refused when your purpose is done, message {parent} with what you found, did, changed and left undone and keep working." ), - self.config - .former_default_note - .as_deref() - .unwrap_or(FORMER_DEFAULT_NOTE), + self.config.former_default_note.as_deref().unwrap_or(""), ) } else { ( format!( "The session's default branch moved from this line to line {other}. This line stays open and keeps coordinating the lines it opened; it can no longer open lines with create, and the rest of the rules above hold again. {CANNOT_END_TEXT}" ), - self.config - .former_default_note - .as_deref() - .unwrap_or(FORMER_DEFAULT_NOTE), + self.config.former_default_note.as_deref().unwrap_or(""), ) }; let guidance = block.replace("{parent}", parent).replace("{other}", other); @@ -6189,29 +6180,13 @@ const CANNOT_END_TEXT: &str = "Only a line opened with create can end itself, an const LIMIT_REACHED_TEXT: &str = "This Session holds its limit of open lines. Continue on this line, or end one of its open lines first."; /// The `branch` tool's description: its policy sentences are the coordination -/// text for a line that opens lines ([timeline branches §12.4](../../../docs/design/timeline-branches.md#124-texts-and-their-classes)), -/// replaceable at [`BranchToolConfig::description`]. -const BRANCH_TOOL_DESCRIPTION: &str = "Work with the other lines of this session. A line is you: it starts from your history at the point it is opened, then works in parallel on its own line. It is not a helper with its own memory, and it owes you no result; you and it keep each other informed by reading each other's work and messaging what the other must act on. On a line that opens lines you coordinate: answer a line's steer and act on what it asks for; leave a line's part to that line instead of redoing it; read a line's work instead of waiting for a report.\n- create (the root and the current default branch only): open a line to work on prompt in parallel. Open a line only when all four of these hold: the work needs this conversation's context, or its approach is worth the user seeing and taking over; after opening it you have other work to do here right away rather than waiting for it; the part you hand over is multi-step work, not two or three quick actions; and the two lines will not write the same files at the same time. When the user asks for a line, open it. These are not line-shaped: a long command runs in the background instead of taking a line; work that needs none of this conversation's context, or needs different instructions, belongs to another member; one task pursued to completion stays here, or uses a goal; waiting for something outside the session uses an event subscription. Write prompt as a brief to yourself: the purpose in one line, what you decided in this response that the line needs, which files or area are its own (or that it is read-only), and when it should tell you or end. Returns the line's id.\n- message: send content to a line you opened, or to the line that opened you. Send a decision, a blocker, or a conflict, not a progress report the receiver can read. Mode \"append\" (default) reaches the receiver at its next step without interrupting it and does not wake an idle line. Use \"steer\" when the receiver must act now or is idle.\n- read: show a page of the activity of the line you were cut from, or of a line you opened, also after it ended. With no after, a read continues after your last read of that line: from your cut for the line you were cut from, and from its first event for a line you opened. Pass after to read from another point. Do not page through a whole line.\n- end: on a line opened with create, end your own line. content is your final message to the line that opened you: what you found, did, changed and left undone. It is your last action.\nA line messages and reads the line it was cut from and the lines it opened. The end action ends the calling line and every line below it."; - -/// The `How you work here:` bullets of the note a move writes on a tool line -/// that becomes the default branch, after the note's protocol sentences -/// ([timeline branches §12.1](../../../docs/design/timeline-branches.md#121-context-mapping)), -/// replaceable at [`BranchToolConfig::default_note`]. `{parent}` and `{other}` -/// stand for the line ids the note names. -const DEFAULT_NOTE: &str = "- The user switched here to continue directly from this line's context and approach, so the user's request takes precedence over the purpose above, which still says what this line is for.\n- Carry this line's main work forward yourself; open a new line only when the four conditions for opening one hold again, not to hand off your current task.\n- When your purpose is done, or cannot be done, message {parent} with what you found, did, changed and left undone and keep working: while this line is the default branch you cannot call end on yourself.\n- You share the workspace with {parent} and its other lines. Avoid redoing work assigned to lines opened before your cut. If edit or write fails because the file was modified after it was last read, another line may have changed that file: read it again before editing."; - -/// The `How you work here:` bullets of the note a move writes on a line the -/// user opened that becomes the default branch (design §12.1), replaceable at -/// [`BranchToolConfig::user_default_note`]. -const USER_DEFAULT_NOTE: &str = "- Carry this line's work forward yourself; open a new line only when the four conditions for opening one hold again. The user's request takes precedence over the prompt this line was opened with.\n- Line {other} stays open in the shared workspace and keeps coordinating any lines it already opened. If edit or write fails because the file was modified after it was last read, another line may have changed that file: read it again before editing."; - -/// The `How you work here:` bullets of the note a move writes on the former -/// default branch, either source (design §12.1), replaceable at -/// [`BranchToolConfig::former_default_note`]. -const FORMER_DEFAULT_NOTE: &str = "- Keep coordinating any open lines you already opened, and answer messages or user inputs addressed to this line.\n- You share the workspace with the other open lines; do not edit files outside your remaining scope unless asked, and if edit or write fails because the file was modified after it was last read, read the file again before continuing."; +/// text for `main` ([timeline branches §12.4](../../../docs/design/timeline-branches.md#124-texts-and-their-classes)), +/// replaceable at [`BranchToolConfig`]. +const BRANCH_TOOL_DESCRIPTION: &str = "Work with the other lines of this session. A line is you: it starts from your history at the point it is opened, then works in parallel on its own line. It is not a helper with its own memory, and it owes you no result; you and it keep each other informed by reading each other's work and messaging what the other must act on. On main you coordinate: answer a line's steer and act on what it asks for; leave a line's part to that line instead of redoing it; read a line's work instead of waiting for a report.\n- create (the root and the current default branch only): open a line to work on prompt in parallel. Open one line per part that can go on at the same time as the rest — separate files, a separate question, or a second approach — instead of doing those parts one after another yourself; not for a single quick edit, nor when your next step needs its result. Write prompt as a brief to yourself: the purpose, what you already know that it needs, which files or area are its own, and when it should tell you or end. Returns the line's id.\n- message: send content to a line you opened, or to the line that opened you. Send a decision, a blocker, or a conflict, not a progress report the receiver can read. Mode \"append\" (default) reaches the receiver at its next step without interrupting it and does not wake an idle line. Use \"steer\" when the receiver must act now or is idle.\n- read: show a page of the activity of the line you were cut from, or of a line you opened, also after it ended. With no after, a read continues after your last read of that line: from your cut for the line you were cut from, and from its first event for a line you opened. Pass after to read from another point. Do not page through a whole line.\n- end: on a line opened with create, end your own line. content is your final message to the line that opened you: what you found, did, changed and left undone. It is your last action.\nA line messages and reads the line it was cut from and the lines it opened. The end action ends the calling line and every line below it."; /// Factory configuration of the branch tool ([timeline branches §12.4](../../../docs/design/timeline-branches.md#124-texts-and-their-classes)). -/// The product sets none of it, so the built-in text is in force. +/// The product sets none of it: the built-in description, roster closing and +/// cap are in force, and a note member left unset writes no guidance block. #[derive(Clone, Default)] pub struct BranchToolConfig { /// The tool description in place of [`BRANCH_TOOL_DESCRIPTION`]. A @@ -6222,17 +6197,16 @@ pub struct BranchToolConfig { /// BranchLine, the part that writes the roster /// ([timeline branches §12.4](../../../docs/design/timeline-branches.md#124-texts-and-their-classes)). pub roster_closing: Option>, - /// The `How you work here:` bullets in place of [`DEFAULT_NOTE`], the - /// guidance of the note a move writes on a tool line it makes the default - /// branch ([timeline branches §12.4](../../../docs/design/timeline-branches.md#124-texts-and-their-classes)). + /// The `How you work here:` bullets of the note a move writes on a tool + /// line it makes the default branch ([timeline branches §12.4](../../../docs/design/timeline-branches.md#124-texts-and-their-classes)). + /// `{parent}` and `{other}` stand for the line ids the note names, and an + /// unset or empty value writes no block. pub default_note: Option>, - /// The `How you work here:` bullets in place of [`USER_DEFAULT_NOTE`], the - /// guidance of the note a move writes on a line the user opened that it - /// makes the default branch (design §12.4). + /// The `How you work here:` bullets of the note a move writes on a line the + /// user opened that it makes the default branch (design §12.4). pub user_default_note: Option>, - /// The `How you work here:` bullets in place of [`FORMER_DEFAULT_NOTE`], - /// the guidance of the note a move writes on the former default branch of - /// either source (design §12.4). + /// The `How you work here:` bullets of the note a move writes on the former + /// default branch of either source (design §12.4). pub former_default_note: Option>, /// The Session's cap on open tool lines in place of the built-in four /// ([timeline branches §6.1](../../../docs/design/timeline-branches.md#61-resources-and-limits)). diff --git a/crates/dim-agent-capabilities/tests/branch_flow.rs b/crates/dim-agent-capabilities/tests/branch_flow.rs index 585325c2ce..2a220dda71 100644 --- a/crates/dim-agent-capabilities/tests/branch_flow.rs +++ b/crates/dim-agent-capabilities/tests/branch_flow.rs @@ -4577,9 +4577,8 @@ async fn a_configured_roster_closing_reaches_the_roster() { /// A note's `How you work here:` block is the factory member /// `BranchToolConfig::default_note`: a configured value reaches the note byte -/// for byte in place of the built-in bullets, with the line ids its `{parent}` -/// and `{other}` placeholders name, while the note's protocol sentences stay -/// the code's (design §12.1, §12.4). +/// for byte, with the line ids its `{parent}` and `{other}` placeholders name, +/// while the note's protocol sentences stay the code's (design §12.1, §12.4). #[tokio::test(flavor = "multi_thread", worker_threads = 2)] async fn a_configured_note_block_reaches_the_note() { let block = "- Configured guidance for {parent}, switched from {other}."; @@ -4604,10 +4603,7 @@ async fn a_configured_note_block_reaches_the_note() { note.contains("How you work here:\n- Configured guidance for main, switched from main."), "{note}" ); - assert!( - !note.contains("- The user switched here to continue directly"), - "the built-in bullets are replaced: {note}" - ); + assert!(!note.contains('{'), "no placeholder is left: {note}"); assert!( note.contains("you send no automatic idle notice to main"), "the note's protocol sentences stay: {note}" @@ -4615,13 +4611,11 @@ async fn a_configured_note_block_reaches_the_note() { soon(agent.close()).await.unwrap(); } -/// The note `4560a5d67` wrote when a tool line became the default branch: its -/// birth identity, then the sentences the move changes, with no `How you work -/// here:` block, which that head's `status_note` had not grown yet. The -/// branch-policy evaluation gives `default_note` an empty baseline so its -/// current arm emits this text byte for byte. `{line}` and `{purpose}` stand -/// where the code substitutes them. -const PRE_POLICY_TOOL_NOTE: &str = r#" +/// The note a move writes on a tool line that becomes the default branch: its +/// birth identity, then the sentences the move changes, and no `How you work +/// here:` block, because `BranchToolConfig` sets no note member. `{line}` and +/// `{purpose}` stand where the code substitutes them. +const PROTOCOL_ONLY_TOOL_NOTE: &str = r#" You are line {line} of this session. Line main opened you at this point of its history to work in parallel with it. You are the same agent as main: everything above is your own history, and you continue from here on your own line. main keeps working on its line; you can read its work after this point, and it can read yours. Messages above that were addressed to main, such as its list of open lines, are main's, not yours. Your purpose, as main wrote it: @@ -4637,20 +4631,17 @@ How you work with main: This line is now the session's default branch, switched from line main. While this block is your latest one: answer the user here; you can open lines with create; you send no automatic idle notice to main; you cannot call end on yourself. Line main stays open and keeps the lines it opened. "#; -/// An empty `default_note` writes the note with no `How you work here:` block, -/// byte for byte as `4560a5d67` wrote it: the branch-policy evaluation's -/// current arm is that head's text, not this head's default block (timeline -/// branches §12.4, model-prompts §8.1). +/// The product configures no note member, so the note a move writes carries +/// the protocol sentences and no `How you work here:` block, and the line's +/// next request carries that note byte for byte (timeline branches §12.1, +/// §12.4). #[tokio::test(flavor = "multi_thread", worker_threads = 2)] -async fn an_empty_note_block_writes_the_note_without_guidance() { +async fn the_default_configuration_writes_no_guidance_block() { let purpose = "the purpose of B"; let probe = Arc::new(Probe::default()); let agent = MinimalHost::start(&builder_with_branch_config( &probe, - BranchToolConfig { - default_note: Some("".into()), - ..Default::default() - }, + BranchToolConfig::default(), )) .await .unwrap(); @@ -4661,12 +4652,16 @@ async fn an_empty_note_block_writes_the_note_without_guidance() { switch(&session, &line).await; let notes = owed_notes(&session, &line, 1).await; let note = notes.last().expect("the line holds its note"); - let expected = PRE_POLICY_TOOL_NOTE + let expected = PROTOCOL_ONLY_TOOL_NOTE .replace("{line}", &line) .replace("{purpose}", purpose); assert_eq!( note, &expected, - "an empty block emits the note the pre-policy head wrote" + "the default writes the note without a guidance block" + ); + assert!( + !note.contains("How you work here:"), + "no guidance block without a configured one: {note}" ); soon(session.submit("next request".into(), InputMode::Queue, &line)) .await @@ -4686,45 +4681,20 @@ async fn an_empty_note_block_writes_the_note_without_guidance() { .messages .iter() .any(|message| said(message).contains(&expected)), - "the rendered request carries the note the baseline wrote" - ); - soon(agent.close()).await.unwrap(); -} - -/// The product's note blocks keep their `How you work here:` heading: the -/// empty-block rule serves a candidate that replaces the block with nothing, -/// not the shipped text. -#[tokio::test(flavor = "multi_thread", worker_threads = 2)] -async fn the_product_note_block_keeps_its_guidance_heading() { - let probe = Arc::new(Probe::default()); - let agent = MinimalHost::start(&builder_with_branch_config( - &probe, - BranchToolConfig::default(), - )) - .await - .unwrap(); - let session = soon(agent.create_session(SessionConfig::default())) - .await - .unwrap(); - let line = open_line(&session, "the shipped line").await; - switch(&session, &line).await; - let notes = owed_notes(&session, &line, 1).await; - let note = notes.last().expect("the line holds its note"); - assert!( - note.contains("\n\nHow you work here:\n- The user switched here to continue directly from this line's context and approach"), - "{note}" + "the rendered request carries the note the default writes" ); soon(agent.close()).await.unwrap(); } /// The note a move writes on a line the user opened is the factory member -/// `BranchToolConfig::user_default_note`: an empty member writes the note with -/// no `How you work here:` block, and the product default writes its bullets -/// into the line's next model request, with `{other}` replaced by the line the -/// move moved away from (design §12.1, §12.4). +/// `BranchToolConfig::user_default_note`: the product sets no member, so the +/// note carries no `How you work here:` block, and a configured value reaches +/// the line's next model request with its `{parent}` and `{other}` placeholders +/// replaced (design §12.1, §12.4). #[tokio::test(flavor = "multi_thread", worker_threads = 2)] async fn a_user_lines_default_note_reaches_the_model_request() { - for (configured, heading) in [(Some(""), false), (None, true)] { + let block = "- Configured user guidance for {parent}, moved from {other}."; + for (configured, heading) in [(None, false), (Some(block), true)] { let probe = Arc::new(Probe::default()); let agent = MinimalHost::start(&builder_with_branch_config( &probe, @@ -4790,14 +4760,14 @@ async fn a_user_lines_default_note_reaches_the_model_request() { if heading { assert!( note.contains( - "\n\nHow you work here:\n- Carry this line's work forward yourself; open a new line only when the four conditions for opening one hold again. The user's request takes precedence over the prompt this line was opened with.\n- Line main stays open in the shared workspace and keeps coordinating any lines it already opened." + "\n\nHow you work here:\n- Configured user guidance for main, moved from main." ), "{note}" ); } else { assert!( !note.contains("How you work here:"), - "an empty member writes no guidance block: {note}" + "no guidance block without a configured one: {note}" ); } soon(agent.close()).await.unwrap(); @@ -4805,14 +4775,15 @@ async fn a_user_lines_default_note_reaches_the_model_request() { } /// The note a move writes on the former default branch is the factory member -/// `BranchToolConfig::former_default_note`, for a tool line too: an empty -/// member writes the note with no `How you work here:` block, and the product -/// default writes its bullets into the line's next model request, with -/// `{other}` replaced by the line that holds the default branch (design §12.1, -/// §12.4). +/// `BranchToolConfig::former_default_note`, for a tool line too: the product +/// sets no member, so the note carries no `How you work here:` block, and a +/// configured value reaches the line's next model request with its `{parent}` +/// and `{other}` placeholders replaced by the line that holds the default +/// branch (design §12.1, §12.4). #[tokio::test(flavor = "multi_thread", worker_threads = 2)] async fn a_former_default_tool_lines_note_reaches_the_model_request() { - for (configured, heading) in [(Some(""), false), (None, true)] { + let block = "- Configured former guidance for {parent}, moved to {other}."; + for (configured, heading) in [(None, false), (Some(block), true)] { let probe = Arc::new(Probe::default()); let agent = MinimalHost::start(&builder_with_branch_config( &probe, @@ -4880,15 +4851,15 @@ async fn a_former_default_tool_lines_note_reaches_the_model_request() { ); if heading { assert!( - note.contains( - "\n\nHow you work here:\n- Keep coordinating any open lines you already opened, and answer messages or user inputs addressed to this line.\n- You share the workspace with the other open lines; do not edit files outside your remaining scope unless asked, and if edit or write fails because the file was modified after it was last read, read the file again before continuing." - ), + note.contains(&format!( + "\n\nHow you work here:\n- Configured former guidance for main, moved to {user}." + )), "{note}" ); } else { assert!( !note.contains("How you work here:"), - "an empty member writes no guidance block: {note}" + "no guidance block without a configured one: {note}" ); } soon(agent.close()).await.unwrap(); diff --git a/docs/design/timeline-branches.md b/docs/design/timeline-branches.md index 1f54ca2f4e..54a1ad24dd 100644 --- a/docs/design/timeline-branches.md +++ b/docs/design/timeline-branches.md @@ -6,7 +6,7 @@ Status: Accepted ([#427](https://github.com/arcships/dim/issues/427)). This docu This design delivers two capabilities: the Session's **default branch**, the line its conversation is on and choosing another open line as that line; and **who may open a line**, which is now the root always, plus whichever line is the current default branch. Every other line is refused, so at most two lines can open at any moment, and the root keeps the ability it has today. -One decision it does not take is the guidance for *when* a model should open a line: the four conditions and their boundaries with neighbouring mechanisms are stated in §12.1 as policy, and the change that first puts a candidate for them in place judges it with the scenarios in §12.3. A Session-wide cap on open tool lines sits beside the right to open (§6.1). +One decision it does not take is the guidance for *when* a model should open a line: the four conditions and their boundaries with neighbouring mechanisms are stated in §12.4 as policy, and the change that first puts a candidate for them in place judges it with the scenarios in §12.3. A Session-wide cap on open tool lines sits beside the right to open (§6.1). The English words are **default branch** for the role and **root** for the line with no parent, whose id is always `main`. The UI keeps 主线 for the default branch and 起点 for the root. @@ -488,11 +488,11 @@ still break adjacent-text merging. No event cache or additional storage format i | Final message | `P`, no key | Steer | `` / `` / blank / `Line C ends with this message.` / `` | | Idle notice | `P`, no key, for a tool line `C` that `P` opened | Steer | `` / `Line C's turn ended () without a message to you, and C is waiting. Read it if you need its state; message it with mode "steer" to give it more work, or leave it.` / `` | | Ended notice | `P`, no key, in the roster's input, for any end of a tool line `P` opened other than its own `end` | Steer | `` / `Line C was ended from outside its own line, by the user or a host operation. It no longer receives messages; read it if you need what it did.` / `` | -| Status note, new default branch, a tool line | `C`, `branch:line` | Append | `` / the birth identity's sentences byte for byte, purpose label and purpose included, then blank / `This line is now the session's default branch, switched from line O. While this block is your latest one: answer the user here; you can open lines with create; you send no automatic idle notice to P; you cannot call end on yourself. Line O stays open and keeps the lines it opened.` / blank / `How you work here:` / `- The user switched here to continue directly from this line's context and approach, so the user's request takes precedence over the purpose above, which still says what this line is for.` / `- Carry this line's main work forward yourself; open a new line only when the four conditions for opening one hold again, not to hand off your current task.` / `- When your purpose is done, or cannot be done, message P with what you found, did, changed and left undone and keep working: while this line is the default branch you cannot call end on yourself.` / `- You share the workspace with P and its other lines. Avoid redoing work assigned to lines opened before your cut. If edit or write fails because the file was modified after it was last read, another line may have changed that file: read it again before editing.` / `` | -| Status note, new default branch, a line the user opened | `C`, `branch:line` | Append | `` / its birth identity's sentence byte for byte, then blank / `The user has now made this line the session's default branch, switched from line O. While this block is your latest one: answer the user here; you can open lines with create; you cannot call end on yourself; the user ends this line. Line O stays open and keeps the lines it opened.` / blank / `How you work here:` / `- Carry this line's work forward yourself; open a new line only when the four conditions for opening one hold again. The user's request takes precedence over the prompt this line was opened with.` / `- Line O stays open in the shared workspace and keeps coordinating any lines it already opened. If edit or write fails because the file was modified after it was last read, another line may have changed that file: read it again before editing.` / `` | -| Status note, former default branch, a tool line | `C`, `branch:line` | Append | `` / its birth identity's sentences byte for byte, then blank / `The session's default branch moved from this line to line O. This line stays open, reports to P as before and keeps coordinating the lines it opened; it can no longer open lines with create, and the rest of the rules above hold again. Only a line opened with create can end itself, and not while it or a line below it is the default branch. If end is refused when your purpose is done, message P with what you found, did, changed and left undone and keep working.` / blank / `How you work here:` / `- Keep coordinating any open lines you already opened, and answer messages or user inputs addressed to this line.` / `- You share the workspace with the other open lines; do not edit files outside your remaining scope unless asked, and if edit or write fails because the file was modified after it was last read, read the file again before continuing.` / `` | -| Status note, former default branch, a line the user opened | `C`, `branch:line` | Append | `` / its birth identity's sentences byte for byte, then blank / `The session's default branch moved from this line to line O. This line stays open and keeps coordinating the lines it opened; it can no longer open lines with create, and the rest of the rules above hold again. Only a line opened with create can end itself, and not while it or a line below it is the default branch.` / blank / `How you work here:` / `- Keep coordinating any open lines you already opened, and answer messages or user inputs addressed to this line.` / `- You share the workspace with the other open lines; do not edit files outside your remaining scope unless asked, and if edit or write fails because the file was modified after it was last read, read the file again before continuing.` / `` | -| Tool description | Every line | — | `Work with the other lines of this session. A line is you: it starts from your history at the point it is opened, then works in parallel on its own line. It is not a helper with its own memory, and it owes you no result; you and it keep each other informed by reading each other's work and messaging what the other must act on. On a line that opens lines you coordinate: answer a line's steer and act on what it asks for; leave a line's part to that line instead of redoing it; read a line's work instead of waiting for a report.` / `- create (the root and the current default branch only): open a line to work on prompt in parallel. Open a line only when all four of these hold: the work needs this conversation's context, or its approach is worth the user seeing and taking over; after opening it you have other work to do here right away rather than waiting for it; the part you hand over is multi-step work, not two or three quick actions; and the two lines will not write the same files at the same time. When the user asks for a line, open it. These are not line-shaped: a long command runs in the background instead of taking a line; work that needs none of this conversation's context, or needs different instructions, belongs to another member; one task pursued to completion stays here, or uses a goal; waiting for something outside the session uses an event subscription. Write prompt as a brief to yourself: the purpose in one line, what you decided in this response that the line needs, which files or area are its own (or that it is read-only), and when it should tell you or end. Returns the line's id.` / `- message: send content to a line you opened, or to the line that opened you. Send a decision, a blocker, or a conflict, not a progress report the receiver can read. Mode "append" (default) reaches the receiver at its next step without interrupting it and does not wake an idle line. Use "steer" when the receiver must act now or is idle.` / `- read: show a page of the activity of the line you were cut from, or of a line you opened, also after it ended. With no after, a read continues after your last read of that line: from your cut for the line you were cut from, and from its first event for a line you opened. Pass after to read from another point. Do not page through a whole line.` / `- end: on a line opened with create, end your own line. content is your final message to the line that opened you: what you found, did, changed and left undone. It is your last action.` / `A line messages and reads the line it was cut from and the lines it opened. The end action ends the calling line and every line below it.` | +| Status note, new default branch, a tool line | `C`, `branch:line` | Append | `` / the birth identity's sentences byte for byte, purpose label and purpose included, then blank / `This line is now the session's default branch, switched from line O. While this block is your latest one: answer the user here; you can open lines with create; you send no automatic idle notice to P; you cannot call end on yourself. Line O stays open and keeps the lines it opened.` / blank / `How you work here:` / `- The user switched here to continue directly from this line's context and approach, so the user's request takes precedence over the purpose above, which still says what this line is for.` / `- When your purpose is done, or cannot be done, message P with what you found, did, changed and left undone and keep working: while this line is the default branch you cannot call end on yourself.` / `- You share the workspace with P and its other lines. If edit or write fails because the file was modified after it was last read, another line may have changed that file: read it again before editing.` / `` | +| Status note, new default branch, a line the user opened | `C`, `branch:line` | Append | `` / its birth identity's sentence byte for byte, then blank / `The user has now made this line the session's default branch, switched from line O. While this block is your latest one: answer the user here; you can open lines with create; you cannot call end on yourself; the user ends this line. Line O stays open and keeps the lines it opened.` / blank / `How you work here:` / `- Carry this line's work forward yourself; the user's request takes precedence over the prompt this line was opened with.` / `` | +| Status note, former default branch, a tool line | `C`, `branch:line` | Append | `` / its birth identity's sentences byte for byte, then blank / `The session's default branch moved from this line to line O. This line stays open, reports to P as before and keeps coordinating the lines it opened; it can no longer open lines with create, and the rest of the rules above hold again. Only a line opened with create can end itself, and not while it or a line below it is the default branch. If end is refused when your purpose is done, message P with what you found, did, changed and left undone and keep working.` / `` | +| Status note, former default branch, a line the user opened | `C`, `branch:line` | Append | `` / its birth identity's sentences byte for byte, then blank / `The session's default branch moved from this line to line O. This line stays open and keeps coordinating the lines it opened; it can no longer open lines with create, and the rest of the rules above hold again. Only a line opened with create can end itself, and not while it or a line below it is the default branch.` / `` | +| Tool description | Every line | — | `Work with the other lines of this session. A line is you: it starts from your history at the point it is opened, then works in parallel on its own line. It is not a helper with its own memory, and it owes you no result; you and it keep each other informed by reading each other's work and messaging what the other must act on. On main you coordinate: answer a line's steer and act on what it asks for; leave a line's part to that line instead of redoing it; read a line's work instead of waiting for a report.` / `- create (the root and the current default branch only): open a line to work on prompt in parallel. Open one line per part that can go on at the same time as the rest — separate files, a separate question, or a second approach — instead of doing those parts one after another yourself; not for a single quick edit, nor when your next step needs its result. Write prompt as a brief to yourself: the purpose, what you already know that it needs, which files or area are its own, and when it should tell you or end. Returns the line's id.` / `- message: send content to a line you opened, or to the line that opened you. Send a decision, a blocker, or a conflict, not a progress report the receiver can read. Mode "append" (default) reaches the receiver at its next step without interrupting it and does not wake an idle line. Use "steer" when the receiver must act now or is idle.` / `- read: show a page of the activity of the line you were cut from, or of a line you opened, also after it ended. With no after, a read continues after your last read of that line: from your cut for the line you were cut from, and from its first event for a line you opened. Pass after to read from another point. Do not page through a whole line.` / `- end: on a line opened with create, end your own line. content is your final message to the line that opened you: what you found, did, changed and left undone. It is your last action.` / `A line messages and reads the line it was cut from and the lines it opened. The end action ends the calling line and every line below it.` | These texts replace the delegation wording in the code today: the `dim-branch-task` block in `first_input` ("That branch delegated this task to you") and the tool description ("works on prompt as a task you delegate"). Their classes are in [§12.4](#124-texts-and-their-classes). @@ -559,11 +559,11 @@ Every model-facing text of the branch mechanism, with its class ([model-facing p **Policy.** -- **The coordination text for an opener.** The `branch` tool description's guidance, the same text on every line and therefore for both openers: the opening paragraph on what a line is and what coordinating means for a line that may open lines, the `create` rule for when to open a line and what the brief carries, the `message` rule for choosing a mode and for sending a decision instead of a progress report, and the `read` rule for reading a line's work instead of waiting for a report. The `create` rule's four conditions, its exception for a line the user asks for, and its boundaries by need are policy, and §12.1 holds their text. [`BranchToolConfig.description`](../../crates/dim-agent-capabilities/src/timeline_tree.rs) replaces the description and nothing else. It covers [§12.2](#122-items-for-the-prompt-layer-429)'s first item, how an opener briefs a line and assigns its files or area, in the `create` rule, and how it answers steers and does not redo a line's work, in the opening paragraph's coordination sentence. The roster's closing sentence, "They message you when they find something, need you, or end. Use the branch tool to message or read them, and the `wait` tool to wait for them; end the wait when your lines have nothing left to tell you.", is coordination text for an opener too, and its "end the wait when your lines have nothing left to tell you" covers ending the opener's own wait; [`BranchToolConfig.roster_closing`](../../crates/dim-agent-capabilities/src/timeline_tree.rs) replaces it and nothing else. +- **The coordination text for an opener.** The `branch` tool description's guidance, the same text on every line and therefore for both openers: the opening paragraph on what a line is and what coordinating means for a line that may open lines, the `create` rule for when to open a line and what the brief carries, the `message` rule for choosing a mode and for sending a decision instead of a progress report, and the `read` rule for reading a line's work instead of waiting for a report. [`BranchToolConfig.description`](../../crates/dim-agent-capabilities/src/timeline_tree.rs) replaces the description and nothing else. It covers [§12.2](#122-items-for-the-prompt-layer-429)'s first item, how an opener briefs a line and assigns its files or area, in the `create` rule, and how it answers steers and does not redo a line's work, in the opening paragraph's coordination sentence. The roster's closing sentence, "They message you when they find something, need you, or end. Use the branch tool to message or read them, and the `wait` tool to wait for them; end the wait when your lines have nothing left to tell you.", is coordination text for an opener too, and its "end the wait when your lines have nothing left to tell you" covers ending the opener's own wait; [`BranchToolConfig.roster_closing`](../../crates/dim-agent-capabilities/src/timeline_tree.rs) replaces it and nothing else. - **The line's working rules.** The five bullets of "How you work with P:", on the purpose, the reads and messages — including "Do not send P a progress report it can read" and "do not page through P's whole stream" — the workspace, the user and the end, including "Read P once more before you end if the parent block says P has moved", apart from the clauses that name a mechanism: the opening rule, the action and mode names, and "the file was modified after it was last read", the failure `edit` and `write` report, are protocol, as above. It has no factory member yet, and gets one in the change that first evaluates a candidate for it. - **The parent block's guidance.** "Read it when what P did changes what you do, and before your final message; do not page through all of P's work." It has no factory member yet, and gets one in the change that first evaluates a candidate for it. The rest of the block is protocol, above. - **The notices' guidance.** "Read it if you need its state; message it with mode \"steer\" to give it more work, or leave it." and "read it if you need what it did." It has no factory member yet, and gets one in the change that first evaluates a candidate for it. -- **The status notes' guidance.** Each note's `How you work here:` block is its guidance, and §12.1 holds its exact text: the four bullets after the change sentences on the new default branch of a tool line, the two bullets on the new default branch of a line the user opened, and the two bullets at the end of the note to the former default branch. [`BranchToolConfig.default_note`](../../crates/dim-agent-capabilities/src/timeline_tree.rs), [`BranchToolConfig.user_default_note`](../../crates/dim-agent-capabilities/src/timeline_tree.rs) and [`BranchToolConfig.former_default_note`](../../crates/dim-agent-capabilities/src/timeline_tree.rs) replace those blocks and nothing else, and BranchLine writes each with the note's protocol sentences. A candidate keeps the block's protocol sentences byte-identical: the sentence on what to do when the purpose is done on a tool line, and, in every block, the clause that names the `edit` or `write` failure. Everything else in the notes is protocol too: the restated identity, whether the line may open a line, that it sends no idle notice, whether it may `end` and why, the line it was switched from or the line the role moved to, that a former default branch stays open and keeps its lines, and that only a line opened with `create` can end itself and not while it or a line below it is the default branch. The opening rule is protocol rather than policy because it is the tree's own answer to whether `create` would succeed, and a note that hedged it would tell a line less than the tool call tells it. +- **The status notes' guidance.** Six sentences are policy, each behind its factory member: on the new default branch, "The user switched here to continue directly from this line's context and approach, so the user's request takes precedence over the purpose above, which still says what this line is for.", "Carry this line's main work forward yourself; open a new line only when the four conditions for opening one hold again, not to hand off your current task." and "Avoid redoing work assigned to lines opened before your cut."; on a new default branch the user opened, "Carry this line's work forward yourself; open a new line only when the four conditions for opening one hold again."; on the former default branch, "Keep coordinating any open lines you already opened, and answer messages or user inputs addressed to this line." and "You share the workspace with line N; do not edit files outside your remaining scope unless asked." [`BranchToolConfig.default_note`](../../crates/dim-agent-capabilities/src/timeline_tree.rs), [`BranchToolConfig.user_default_note`](../../crates/dim-agent-capabilities/src/timeline_tree.rs) and [`BranchToolConfig.former_default_note`](../../crates/dim-agent-capabilities/src/timeline_tree.rs) replace them and nothing else. The product sets none of the three, so a shipped note carries no `How you work here:` block: the block is written only when a member is configured. Everything else in the notes is protocol: the restated identity, whether the line may open a line, that it sends no idle notice, whether it may `end` and why, the line it was switched from or the line the role moved to, that a former default branch stays open and keeps its lines, and that only a line opened with `create` can end itself and not while it or a line below it is the default branch. The opening rule is protocol rather than policy because it is the tree's own answer to whether `create` would succeed, and a note that hedged it would tell a line less than the tool call tells it. A candidate for a policy text is put in place at that text's factory member ([model-facing prompts §8.1](model-prompts.md#81-the-rule)) and keeps the protocol sentences of the text it replaces byte-identical. diff --git a/docs/zh/design/timeline-branches.md b/docs/zh/design/timeline-branches.md index 5e5f001057..78c4ea8d98 100644 --- a/docs/zh/design/timeline-branches.md +++ b/docs/zh/design/timeline-branches.md @@ -4,7 +4,7 @@ 本次交付两件事:Session 的**默认分支**(英文 default branch,界面上仍叫“主线”),也就是它的对话所在的那条线,以及由用户把另一条未结束的线选为这条线;以及**谁能开线**,现在是根永远可以,加上当前默认分支。其余每条线都被拒绝,所以任何时刻最多两条线能开线,而根保留它今天的权利。 -它不做的一个决定是什么时候该开线的说明:四个条件以及它们与相邻机制的边界写在 §12.1,作为策略,由第一次把它们放进去的改动用 §12.3 的场景判定。开着的工具线的 Session 级上限与开线权放在一起(§6.1)。 +它不做的一个决定是什么时候该开线的说明:四个条件以及它们与相邻机制的边界写在 §12.4,作为策略,由第一次把它们放进去的改动用 §12.3 的场景判定。开着的工具线的 Session 级上限与开线权放在一起(§6.1)。 ## 1. 分支用来做什么 @@ -454,11 +454,11 @@ WorkspaceTools 不变。 | 最终消息 | `P`,无 key | Steer | `` / `` / 空行 / `Line C ends with this message.` / `` | | 空闲通知 | `P`,无 key,针对 `P` 开出的工具线 `C` | Steer | `` / `Line C's turn ended () without a message to you, and C is waiting. Read it if you need its state; message it with mode "steer" to give it more work, or leave it.` / `` | | 结束通知 | `P`,无 key,与名册在同一条输入里;`P` 开出的工具线除自己的 `end` 之外的任何结束 | Steer | `` / `Line C was ended from outside its own line, by the user or a host operation. It no longer receives messages; read it if you need what it did.` / `` | -| 状态说明,新的默认分支,工具线 | `C`,`branch:line` | Append | `` / 逐字重述出生身份的句子,包括目的标签和目的本身,然后空行 / `This line is now the session's default branch, switched from line O. While this block is your latest one: answer the user here; you can open lines with create; you send no automatic idle notice to P; you cannot call end on yourself. Line O stays open and keeps the lines it opened.` / 空行 / `How you work here:` / `- The user switched here to continue directly from this line's context and approach, so the user's request takes precedence over the purpose above, which still says what this line is for.` / `- Carry this line's main work forward yourself; open a new line only when the four conditions for opening one hold again, not to hand off your current task.` / `- When your purpose is done, or cannot be done, message P with what you found, did, changed and left undone and keep working: while this line is the default branch you cannot call end on yourself.` / `- You share the workspace with P and its other lines. Avoid redoing work assigned to lines opened before your cut. If edit or write fails because the file was modified after it was last read, another line may have changed that file: read it again before editing.` / `` | -| 状态说明,新的默认分支,用户开的线 | `C`,`branch:line` | Append | `` / 逐字重述出生身份的句子,然后空行 / `The user has now made this line the session's default branch, switched from line O. While this block is your latest one: answer the user here; you can open lines with create; you cannot call end on yourself; the user ends this line. Line O stays open and keeps the lines it opened.` / 空行 / `How you work here:` / `- Carry this line's work forward yourself; open a new line only when the four conditions for opening one hold again. The user's request takes precedence over the prompt this line was opened with.` / `- Line O stays open in the shared workspace and keeps coordinating any lines it already opened. If edit or write fails because the file was modified after it was last read, another line may have changed that file: read it again before editing.` / `` | -| 状态说明,原来的默认分支,工具线 | `C`,`branch:line` | Append | `` / 逐字重述出生身份的句子,然后空行 / `The session's default branch moved from this line to line O. This line stays open, reports to P as before and keeps coordinating the lines it opened; it can no longer open lines with create, and the rest of the rules above hold again. Only a line opened with create can end itself, and not while it or a line below it is the default branch. If end is refused when your purpose is done, message P with what you found, did, changed and left undone and keep working.` / 空行 / `How you work here:` / `- Keep coordinating any open lines you already opened, and answer messages or user inputs addressed to this line.` / `- You share the workspace with the other open lines; do not edit files outside your remaining scope unless asked, and if edit or write fails because the file was modified after it was last read, read the file again before continuing.` / `` | -| 状态说明,原来的默认分支,用户开的线 | `C`,`branch:line` | Append | `` / 逐字重述出生身份的句子,然后空行 / `The session's default branch moved from this line to line O. This line stays open and keeps coordinating the lines it opened; it can no longer open lines with create, and the rest of the rules above hold again. Only a line opened with create can end itself, and not while it or a line below it is the default branch.` / 空行 / `How you work here:` / `- Keep coordinating any open lines you already opened, and answer messages or user inputs addressed to this line.` / `- You share the workspace with the other open lines; do not edit files outside your remaining scope unless asked, and if edit or write fails because the file was modified after it was last read, read the file again before continuing.` / `` | -| 工具描述 | 每条线 | — | `Work with the other lines of this session. A line is you: it starts from your history at the point it is opened, then works in parallel on its own line. It is not a helper with its own memory, and it owes you no result; you and it keep each other informed by reading each other's work and messaging what the other must act on. On a line that opens lines you coordinate: answer a line's steer and act on what it asks for; leave a line's part to that line instead of redoing it; read a line's work instead of waiting for a report.` / `- create (the root and the current default branch only): open a line to work on prompt in parallel. Open a line only when all four of these hold: the work needs this conversation's context, or its approach is worth the user seeing and taking over; after opening it you have other work to do here right away rather than waiting for it; the part you hand over is multi-step work, not two or three quick actions; and the two lines will not write the same files at the same time. When the user asks for a line, open it. These are not line-shaped: a long command runs in the background instead of taking a line; work that needs none of this conversation's context, or needs different instructions, belongs to another member; one task pursued to completion stays here, or uses a goal; waiting for something outside the session uses an event subscription. Write prompt as a brief to yourself: the purpose in one line, what you decided in this response that the line needs, which files or area are its own (or that it is read-only), and when it should tell you or end. Returns the line's id.` / `- message: send content to a line you opened, or to the line that opened you. Send a decision, a blocker, or a conflict, not a progress report the receiver can read. Mode "append" (default) reaches the receiver at its next step without interrupting it and does not wake an idle line. Use "steer" when the receiver must act now or is idle.` / `- read: show a page of the activity of the line you were cut from, or of a line you opened, also after it ended. With no after, a read continues after your last read of that line: from your cut for the line you were cut from, and from its first event for a line you opened. Pass after to read from another point. Do not page through a whole line.` / `- end: on a line opened with create, end your own line. content is your final message to the line that opened you: what you found, did, changed and left undone. It is your last action.` / `A line messages and reads the line it was cut from and the lines it opened. The end action ends the calling line and every line below it.` | +| 状态说明,新的默认分支,工具线 | `C`,`branch:line` | Append | `` / 逐字重述出生身份的句子,包括目的标签和目的本身,然后空行 / `This line is now the session's default branch, switched from line O. While this block is your latest one: answer the user here; you can open lines with create; you send no automatic idle notice to P; you cannot call end on yourself. Line O stays open and keeps the lines it opened.` / 空行 / `How you work here:` / `- The user switched here to continue directly from this line's context and approach, so the user's request takes precedence over the purpose above, which still says what this line is for.` / `- When your purpose is done, or cannot be done, message P with what you found, did, changed and left undone and keep working: while this line is the default branch you cannot call end on yourself.` / `- You share the workspace with P and its other lines. If edit or write fails because the file was modified after it was last read, another line may have changed that file: read it again before editing.` / `` | +| 状态说明,新的默认分支,用户开的线 | `C`,`branch:line` | Append | `` / 逐字重述出生身份的句子,然后空行 / `The user has now made this line the session's default branch, switched from line O. While this block is your latest one: answer the user here; you can open lines with create; you cannot call end on yourself; the user ends this line. Line O stays open and keeps the lines it opened.` / 空行 / `How you work here:` / `- Carry this line's work forward yourself; the user's request takes precedence over the prompt this line was opened with.` / `` | +| 状态说明,原来的默认分支,工具线 | `C`,`branch:line` | Append | `` / 逐字重述出生身份的句子,然后空行 / `The session's default branch moved from this line to line O. This line stays open, reports to P as before and keeps coordinating the lines it opened; it can no longer open lines with create, and the rest of the rules above hold again. Only a line opened with create can end itself, and not while it or a line below it is the default branch. If end is refused when your purpose is done, message P with what you found, did, changed and left undone and keep working.` / `` | +| 状态说明,原来的默认分支,用户开的线 | `C`,`branch:line` | Append | `` / 逐字重述出生身份的句子,然后空行 / `The session's default branch moved from this line to line O. This line stays open and keeps coordinating the lines it opened; it can no longer open lines with create, and the rest of the rules above hold again. Only a line opened with create can end itself, and not while it or a line below it is the default branch.` / `` | +| 工具描述 | 每条线 | — | `Work with the other lines of this session. A line is you: it starts from your history at the point it is opened, then works in parallel on its own line. It is not a helper with its own memory, and it owes you no result; you and it keep each other informed by reading each other's work and messaging what the other must act on. On main you coordinate: answer a line's steer and act on what it asks for; leave a line's part to that line instead of redoing it; read a line's work instead of waiting for a report.` / `- create (the root and the current default branch only): open a line to work on prompt in parallel. Open one line per part that can go on at the same time as the rest — separate files, a separate question, or a second approach — instead of doing those parts one after another yourself; not for a single quick edit, nor when your next step needs its result. Write prompt as a brief to yourself: the purpose, what you already know that it needs, which files or area are its own, and when it should tell you or end. Returns the line's id.` / `- message: send content to a line you opened, or to the line that opened you. Send a decision, a blocker, or a conflict, not a progress report the receiver can read. Mode "append" (default) reaches the receiver at its next step without interrupting it and does not wake an idle line. Use "steer" when the receiver must act now or is idle.` / `- read: show a page of the activity of the line you were cut from, or of a line you opened, also after it ended. With no after, a read continues after your last read of that line: from your cut for the line you were cut from, and from its first event for a line you opened. Pass after to read from another point. Do not page through a whole line.` / `- end: on a line opened with create, end your own line. content is your final message to the line that opened you: what you found, did, changed and left undone. It is your last action.` / `A line messages and reads the line it was cut from and the lines it opened. The end action ends the calling line and every line below it.` | 这些文本取代代码里现有的委派措辞:`first_input` 里的 `dim-branch-task` 块("That branch delegated this task to you")和工具描述("works on prompt as a task you delegate")。那条状态说明的类别见 [§12.4](#124-文本及其类别)。 @@ -525,12 +525,12 @@ WorkspaceTools 不变。 **策略。** -- **开线方的协调文字。** `branch` 工具描述的指引,每条线上都是同一份,所以两个开线方都适用:说明一条线是什么、以及对于一条能开线的线而言协调意味着什么的开头段、`create` 关于何时开线与 brief 带什么的规则、`message` 关于选模式和发决定而不是进度报告的规则,以及 `read` 关于读线上的工作而不是等报告的规则。`create` 规则里的四个条件、用户要求开线时的例外,以及按需要划的边界是策略,它们的文本在 §12.1。[`BranchToolConfig.description`](../../../crates/dim-agent-capabilities/src/timeline_tree.rs) 只替换这段描述,不替换别的。它覆盖 [§12.2](#122-交给提示词层的事项429) 的第一项:开线方怎样给一条线写说明、分配它的文件或区域,在 `create` 规则里;以及它怎样回应 steer、不重做线上的工作,在开头段的协调句里。名册的收尾句 "They message you when they find something, need you, or end. Use the branch tool to message or read them, and the `wait` tool to wait for them; end the wait when your lines have nothing left to tell you." 也是开线方的协调文字,其中 "end the wait when your lines have nothing left to tell you" 覆盖结束开线方自己的等待;[`BranchToolConfig.roster_closing`](../../../crates/dim-agent-capabilities/src/timeline_tree.rs) 只替换这句,不替换别的。 +- **开线方的协调文字。** `branch` 工具描述的指引,每条线上都是同一份,所以两个开线方都适用:说明一条线是什么、以及对于一条能开线的线而言协调意味着什么的开头段、`create` 关于何时开线与 brief 带什么的规则、`message` 关于选模式和发决定而不是进度报告的规则,以及 `read` 关于读线上的工作而不是等报告的规则。[`BranchToolConfig.description`](../../../crates/dim-agent-capabilities/src/timeline_tree.rs) 只替换这段描述,不替换别的。它覆盖 [§12.2](#122-交给提示词层的事项429) 的第一项:开线方怎样给一条线写说明、分配它的文件或区域,在 `create` 规则里;以及它怎样回应 steer、不重做线上的工作,在开头段的协调句里。名册的收尾句 "They message you when they find something, need you, or end. Use the branch tool to message or read them, and the `wait` tool to wait for them; end the wait when your lines have nothing left to tell you." 也是开线方的协调文字,其中 "end the wait when your lines have nothing left to tell you" 覆盖结束开线方自己的等待;[`BranchToolConfig.roster_closing`](../../../crates/dim-agent-capabilities/src/timeline_tree.rs) 只替换这句,不替换别的。 - **线的工作规则。** "How you work with P:" 的五条要点——目的、读取与消息(含 "Do not send P a progress report it can read" 和 "do not page through P's whole stream")、工作区、用户和结束(含 "Read P once more before you end if the parent block says P has moved")——除了点明机制的从句:开线那条规则、动作名与模式名,以及 "the file was modified after it was last read"(`edit` 与 `write` 报告的那次失败)是协议,见上。它还没有工厂配置成员,在第一次为它评估候选的改动里获得成员。 - **父线块的指引。** "Read it when what P did changes what you do, and before your final message; do not page through all of P's work."。它还没有工厂配置成员,在第一次为它评估候选的改动里获得成员。块的其余部分是协议,见上。 - **通知的指引。** "Read it if you need its state; message it with mode \"steer\" to give it more work, or leave it." 与 "read it if you need what it did."。它还没有工厂配置成员,在第一次为它评估候选的改动里获得成员。 -- **状态说明的指引。** 每条说明的 `How you work here:` 块就是它的指引,确切文本在 §12.1:工具线的新默认分支是更改句之后的四条要点,用户开的那条线是两条要点,原默认分支是说明末尾的两条要点。[`BranchToolConfig.default_note`](../../../crates/dim-agent-capabilities/src/timeline_tree.rs)、[`BranchToolConfig.user_default_note`](../../../crates/dim-agent-capabilities/src/timeline_tree.rs) 与 [`BranchToolConfig.former_default_note`](../../../crates/dim-agent-capabilities/src/timeline_tree.rs) 只替换这些块,不替换别的,由 BranchLine 连同说明里的协议句一起写出。候选要逐字节保留块里的协议句:工具线上目的完成时该做什么的那一句,以及每个块里点明 `edit` 或 `write` 失败的那一句。说明里其余的都是协议:重述的身份、这条线能不能开线、不发空闲通知、能不能 `end` 及原因、它从哪条线切过来或角色移到了哪条线、原默认分支照旧开着并保留自己的线,以及只有用 `create` 开出的线才能结束自己、当它自己或它下面的一条线是默认分支时不能结束。开线那条规则属于协议而不是策略,因为它是树对 `create` 会不会成功的直接答案,一条含糊的说明反而会让线知道得比工具调用更少。 +- **状态说明的指引。** 有六句是策略,各自在工厂配置成员后面:给新默认分支的“用户移到这里,是为了直接从这条线的上下文和做法继续,所以用户的请求优先于上面那个目的,那个目的仍然说明这条线是做什么的。”“自己把这条线的主要工作接着做下去;只有在开线的四个条件再次全部成立时才开新线,而不是把当前任务交出去。”和“避免重做切点之前开出的线已经分到的工作。”;给用户新开的默认分支的“自己把这条线的工作接着做下去;只有在开线的四个条件再次全部成立时才开新线。”;给原默认分支的“继续协调你已经开过的线,并回答发给这条线的消息或用户输入。”和“你与线 N 共用工作区;除非被要求,不要改你剩余范围之外的文件。”。[`BranchToolConfig.default_note`](../../../crates/dim-agent-capabilities/src/timeline_tree.rs)、[`BranchToolConfig.user_default_note`](../../../crates/dim-agent-capabilities/src/timeline_tree.rs) 与 [`BranchToolConfig.former_default_note`](../../../crates/dim-agent-capabilities/src/timeline_tree.rs) 替换它们,别的都不动。产品一个都不设置,所以发出的说明不带 `How you work here:` 块:只有配置了成员才写这个块。说明里其余的都是协议:重述的身份、这条线能不能开线、不发空闲通知、能不能 `end` 及原因、它从哪条线切过来或角色移到了哪条线、原默认分支照旧开着并保留自己的线,以及只有用 `create` 开出的线才能结束自己、当它自己或它下面的一条线是默认分支时不能结束。开线那条规则属于协议而不是策略,因为它是树对 `create` 会不会成功的直接答案,一条含糊的说明反而会让线知道得比工具调用更少。 策略文本的候选放在该文本的工厂配置成员上([面向模型的提示词 §8.1](model-prompts.md#81-规则)),并让它替换的文本里的协议句逐字节不变。 From 858dae9661e4925fb8874671030bd058270dfd74 Mon Sep 17 00:00:00 2001 From: huihui Date: Tue, 24 Nov 2026 11:21:16 +0800 Subject: [PATCH 32/35] chore(branch): drop the branch-policy baseline fixtures The shipped texts are the current arm again, so the four files that held a candidate's baseline are gone; a later change that puts a candidate in place brings its own. --- .../branch-policy-baseline/branch-description.txt | 6 ------ xtask/scenario-eval/branch-policy-baseline/default-note.txt | 0 .../branch-policy-baseline/former-default-note.txt | 0 .../branch-policy-baseline/user-default-note.txt | 0 4 files changed, 6 deletions(-) delete mode 100644 xtask/scenario-eval/branch-policy-baseline/branch-description.txt delete mode 100644 xtask/scenario-eval/branch-policy-baseline/default-note.txt delete mode 100644 xtask/scenario-eval/branch-policy-baseline/former-default-note.txt delete mode 100644 xtask/scenario-eval/branch-policy-baseline/user-default-note.txt diff --git a/xtask/scenario-eval/branch-policy-baseline/branch-description.txt b/xtask/scenario-eval/branch-policy-baseline/branch-description.txt deleted file mode 100644 index afe3de7ac3..0000000000 --- a/xtask/scenario-eval/branch-policy-baseline/branch-description.txt +++ /dev/null @@ -1,6 +0,0 @@ -Work with the other lines of this session. A line is you: it starts from your history at the point it is opened, then works in parallel on its own line. It is not a helper with its own memory, and it owes you no result; you and it keep each other informed by reading each other's work and messaging what the other must act on. On main you coordinate: answer a line's steer and act on what it asks for; leave a line's part to that line instead of redoing it; read a line's work instead of waiting for a report. -- create (the root and the current default branch only): open a line to work on prompt in parallel. Open one line per part that can go on at the same time as the rest — separate files, a separate question, or a second approach — instead of doing those parts one after another yourself; not for a single quick edit, nor when your next step needs its result. Write prompt as a brief to yourself: the purpose, what you already know that it needs, which files or area are its own, and when it should tell you or end. Returns the line's id. -- message: send content to a line you opened, or to the line that opened you. Send a decision, a blocker, or a conflict, not a progress report the receiver can read. Mode "append" (default) reaches the receiver at its next step without interrupting it and does not wake an idle line. Use "steer" when the receiver must act now or is idle. -- read: show a page of the activity of the line you were cut from, or of a line you opened, also after it ended. With no after, a read continues after your last read of that line: from your cut for the line you were cut from, and from its first event for a line you opened. Pass after to read from another point. Do not page through a whole line. -- end: on a line opened with create, end your own line. content is your final message to the line that opened you: what you found, did, changed and left undone. It is your last action. -A line messages and reads the line it was cut from and the lines it opened. The end action ends the calling line and every line below it. \ No newline at end of file diff --git a/xtask/scenario-eval/branch-policy-baseline/default-note.txt b/xtask/scenario-eval/branch-policy-baseline/default-note.txt deleted file mode 100644 index e69de29bb2..0000000000 diff --git a/xtask/scenario-eval/branch-policy-baseline/former-default-note.txt b/xtask/scenario-eval/branch-policy-baseline/former-default-note.txt deleted file mode 100644 index e69de29bb2..0000000000 diff --git a/xtask/scenario-eval/branch-policy-baseline/user-default-note.txt b/xtask/scenario-eval/branch-policy-baseline/user-default-note.txt deleted file mode 100644 index e69de29bb2..0000000000 From cca66591e54c8d709ccb7c2357b159246a801867 Mon Sep 17 00:00:00 2001 From: huihui Date: Tue, 24 Nov 2026 11:44:13 +0800 Subject: [PATCH 33/35] docs(branch): say that a shipped status note carries no guidance block The product sets none of the branch tool's note members, so the note a move writes ends after the sentences the move changes; the design's first-version blocks are supplied at the three members. --- docs/design/timeline-branches.md | 2 ++ docs/zh/design/timeline-branches.md | 2 ++ 2 files changed, 4 insertions(+) diff --git a/docs/design/timeline-branches.md b/docs/design/timeline-branches.md index 54a1ad24dd..470f4d3e8d 100644 --- a/docs/design/timeline-branches.md +++ b/docs/design/timeline-branches.md @@ -496,6 +496,8 @@ still break adjacent-text merging. No event cache or additional storage format i These texts replace the delegation wording in the code today: the `dim-branch-task` block in `first_input` ("That branch delegated this task to you") and the tool description ("works on prompt as a task you delegate"). Their classes are in [§12.4](#124-texts-and-their-classes). +The product sets none of `BranchToolConfig`'s note members, so a shipped status note ends after the sentences the move changes: the `How you work here:` blocks in the table above are the design's first versions, and the three members supply them (§12.4). + **Why a status note restates the identity.** A note is a later block of the `branch:line` key, so it replaces the birth identity of the line that receives it, and a compaction replays the note alone: a line that could not name its parent, its source and its purpose from its own current block would lose them for the rest of its life. A note therefore repeats the birth block's sentences byte for byte and changes only the sentences the move changes. No note says whether some other line is the default branch, because a later move writes nothing to this line; what a note states are the rules for this line, and the rule it states about `end` is the tree's own, applied when `end` is called (§10). **Which lines get a note.** The rule is per participant: each participant of a move that is not the root receives one note, and the root receives none. A move has two participants, the line the user moved to and the line the user moved from, so it writes two notes when neither is the root, one when one of them is, and none only when both are, which no move has. `main → B` writes one note, to B with `default="true"`; `B → main` writes one note, to B with `default="false"`; `B → C` writes two. The root never receives one in either direction, because neither of its rules changes: it opens lines and it never ends, whichever line holds the default branch. Every other line receives nothing, so no other line's cached prefix moves (§7.3). That is also why no fork-retire rule is needed: a fork copies the root's `branch:line` block, and the only such block the root can hold is its roster. diff --git a/docs/zh/design/timeline-branches.md b/docs/zh/design/timeline-branches.md index 78c4ea8d98..fce8de3084 100644 --- a/docs/zh/design/timeline-branches.md +++ b/docs/zh/design/timeline-branches.md @@ -462,6 +462,8 @@ WorkspaceTools 不变。 这些文本取代代码里现有的委派措辞:`first_input` 里的 `dim-branch-task` 块("That branch delegated this task to you")和工具描述("works on prompt as a task you delegate")。那条状态说明的类别见 [§12.4](#124-文本及其类别)。 +产品不设置 `BranchToolConfig` 的任何 note 成员,所以发出的状态说明在移动所改变的那几句之后就结束:上表里的 `How you work here:` 块是设计里的第一版,由三个 note 成员提供(§12.4)。 + **状态说明为什么重述身份。** 说明是 `branch:line` key 的后续块,所以它取代收到它的那条线的出生身份,而压缩也只重放这条说明:一条无法从自己当前块里说出父分支、来源和目的的线,会在余生里一直缺这几项。所以说明逐字重复出生块的句子,只改移动所改变的那几句。说明里不写别的线现在是不是默认分支,因为再移一次并不会给这条线写任何东西;说明写的是这条线自己的规则,而它写的那条 `end` 规则是树自己的规则,在 `end` 被调用时适用(§10)。 **哪些线会收到说明。** 规则按参与者算:一次移动的每个参与者,只要不是根,就收到恰好一条说明;根一条也不收。一次移动有两个参与者,用户移去的那条线和移开的那条线,所以两者都不是根时写两条,其中之一是根时写一条,只有两者都是根时才是零条,而没有这样的移动。`main → B` 写一条,给 B,`default="true"`;`B → main` 写一条,给 B,`default="false"`;`B → C` 写两条。根在两个方向上都不收,因为它的规则一条都没变:它开线、它永不结束,不论默认分支是哪条线。其他每条线都收不到任何东西,所以其他任何线的缓存前缀都不会移动(§7.3)。这也是为什么不需要 fork 清理规则:fork 复制根上的 `branch:line` 块,而根能持有的这种块只有它的名册。各段文本的类别见 [§12.4](#124-文本及其类别)。 From 0a0bc83bbc45c54a30fe9d6a2079753efbd4ca2c Mon Sep 17 00:00:00 2001 From: huihui Date: Tue, 24 Nov 2026 11:46:30 +0800 Subject: [PATCH 34/35] test(branch): pin the product's empty note configuration The default the product hands the branch tool names no note member, which is what makes a shipped status note stop after the sentences the move changes. --- .../dim-agent-capabilities/tests/branch_flow.rs | 16 ++++++++++------ 1 file changed, 10 insertions(+), 6 deletions(-) diff --git a/crates/dim-agent-capabilities/tests/branch_flow.rs b/crates/dim-agent-capabilities/tests/branch_flow.rs index 2a220dda71..fc0c612236 100644 --- a/crates/dim-agent-capabilities/tests/branch_flow.rs +++ b/crates/dim-agent-capabilities/tests/branch_flow.rs @@ -4638,13 +4638,17 @@ This line is now the session's default branch, switched from line main. While th #[tokio::test(flavor = "multi_thread", worker_threads = 2)] async fn the_default_configuration_writes_no_guidance_block() { let purpose = "the purpose of B"; + let config = BranchToolConfig::default(); + assert!( + config.default_note.is_none() + && config.user_default_note.is_none() + && config.former_default_note.is_none(), + "the product configures no note member" + ); let probe = Arc::new(Probe::default()); - let agent = MinimalHost::start(&builder_with_branch_config( - &probe, - BranchToolConfig::default(), - )) - .await - .unwrap(); + let agent = MinimalHost::start(&builder_with_branch_config(&probe, config)) + .await + .unwrap(); let session = soon(agent.create_session(SessionConfig::default())) .await .unwrap(); From 867a6f508434234febdee6de537d40b50cfdf87e Mon Sep 17 00:00:00 2001 From: huihui Date: Tue, 24 Nov 2026 12:46:42 +0800 Subject: [PATCH 35/35] fix(branch): keep the former-line note to the end guard The note a move writes on a tool line it moves away from told the model to message its opener and keep working when end is refused. Whether a line reports and keeps working is a model choice, so the note states only the tree's own end guard, and design section 12.4 records the removed sentence as a policy sentence of the former default note member, which ships unset. The former default branch test now asserts that the shipped note ends with the guard, and the design rows and protocol list follow the shipped text. --- crates/dim-agent-capabilities/src/timeline_tree.rs | 2 +- crates/dim-agent-capabilities/tests/branch_flow.rs | 4 ++++ docs/design/timeline-branches.md | 6 +++--- docs/zh/design/timeline-branches.md | 6 +++--- 4 files changed, 11 insertions(+), 7 deletions(-) diff --git a/crates/dim-agent-capabilities/src/timeline_tree.rs b/crates/dim-agent-capabilities/src/timeline_tree.rs index 534a51033e..b72a3263ac 100644 --- a/crates/dim-agent-capabilities/src/timeline_tree.rs +++ b/crates/dim-agent-capabilities/src/timeline_tree.rs @@ -5065,7 +5065,7 @@ impl BranchLine { } else if kind == "tool" { ( format!( - "The session's default branch moved from this line to line {other}. This line stays open, reports to {parent} as before and keeps coordinating the lines it opened; it can no longer open lines with create, and the rest of the rules above hold again. {CANNOT_END_TEXT} If end is refused when your purpose is done, message {parent} with what you found, did, changed and left undone and keep working." + "The session's default branch moved from this line to line {other}. This line stays open, reports to {parent} as before and keeps coordinating the lines it opened; it can no longer open lines with create, and the rest of the rules above hold again. {CANNOT_END_TEXT}" ), self.config.former_default_note.as_deref().unwrap_or(""), ) diff --git a/crates/dim-agent-capabilities/tests/branch_flow.rs b/crates/dim-agent-capabilities/tests/branch_flow.rs index fc0c612236..7d03619c9a 100644 --- a/crates/dim-agent-capabilities/tests/branch_flow.rs +++ b/crates/dim-agent-capabilities/tests/branch_flow.rs @@ -4865,6 +4865,10 @@ async fn a_former_default_tool_lines_note_reaches_the_model_request() { !note.contains("How you work here:"), "no guidance block without a configured one: {note}" ); + assert!( + note.ends_with("Only a line opened with create can end itself, and not while it or a line below it is the default branch.\n"), + "the shipped note ends with the end guard, not with an instruction: {note}" + ); } soon(agent.close()).await.unwrap(); } diff --git a/docs/design/timeline-branches.md b/docs/design/timeline-branches.md index 470f4d3e8d..78e118641e 100644 --- a/docs/design/timeline-branches.md +++ b/docs/design/timeline-branches.md @@ -490,7 +490,7 @@ still break adjacent-text merging. No event cache or additional storage format i | Ended notice | `P`, no key, in the roster's input, for any end of a tool line `P` opened other than its own `end` | Steer | `` / `Line C was ended from outside its own line, by the user or a host operation. It no longer receives messages; read it if you need what it did.` / `` | | Status note, new default branch, a tool line | `C`, `branch:line` | Append | `` / the birth identity's sentences byte for byte, purpose label and purpose included, then blank / `This line is now the session's default branch, switched from line O. While this block is your latest one: answer the user here; you can open lines with create; you send no automatic idle notice to P; you cannot call end on yourself. Line O stays open and keeps the lines it opened.` / blank / `How you work here:` / `- The user switched here to continue directly from this line's context and approach, so the user's request takes precedence over the purpose above, which still says what this line is for.` / `- When your purpose is done, or cannot be done, message P with what you found, did, changed and left undone and keep working: while this line is the default branch you cannot call end on yourself.` / `- You share the workspace with P and its other lines. If edit or write fails because the file was modified after it was last read, another line may have changed that file: read it again before editing.` / `` | | Status note, new default branch, a line the user opened | `C`, `branch:line` | Append | `` / its birth identity's sentence byte for byte, then blank / `The user has now made this line the session's default branch, switched from line O. While this block is your latest one: answer the user here; you can open lines with create; you cannot call end on yourself; the user ends this line. Line O stays open and keeps the lines it opened.` / blank / `How you work here:` / `- Carry this line's work forward yourself; the user's request takes precedence over the prompt this line was opened with.` / `` | -| Status note, former default branch, a tool line | `C`, `branch:line` | Append | `` / its birth identity's sentences byte for byte, then blank / `The session's default branch moved from this line to line O. This line stays open, reports to P as before and keeps coordinating the lines it opened; it can no longer open lines with create, and the rest of the rules above hold again. Only a line opened with create can end itself, and not while it or a line below it is the default branch. If end is refused when your purpose is done, message P with what you found, did, changed and left undone and keep working.` / `` | +| Status note, former default branch, a tool line | `C`, `branch:line` | Append | `` / its birth identity's sentences byte for byte, then blank / `The session's default branch moved from this line to line O. This line stays open, reports to P as before and keeps coordinating the lines it opened; it can no longer open lines with create, and the rest of the rules above hold again. Only a line opened with create can end itself, and not while it or a line below it is the default branch.` / `` | | Status note, former default branch, a line the user opened | `C`, `branch:line` | Append | `` / its birth identity's sentences byte for byte, then blank / `The session's default branch moved from this line to line O. This line stays open and keeps coordinating the lines it opened; it can no longer open lines with create, and the rest of the rules above hold again. Only a line opened with create can end itself, and not while it or a line below it is the default branch.` / `` | | Tool description | Every line | — | `Work with the other lines of this session. A line is you: it starts from your history at the point it is opened, then works in parallel on its own line. It is not a helper with its own memory, and it owes you no result; you and it keep each other informed by reading each other's work and messaging what the other must act on. On main you coordinate: answer a line's steer and act on what it asks for; leave a line's part to that line instead of redoing it; read a line's work instead of waiting for a report.` / `- create (the root and the current default branch only): open a line to work on prompt in parallel. Open one line per part that can go on at the same time as the rest — separate files, a separate question, or a second approach — instead of doing those parts one after another yourself; not for a single quick edit, nor when your next step needs its result. Write prompt as a brief to yourself: the purpose, what you already know that it needs, which files or area are its own, and when it should tell you or end. Returns the line's id.` / `- message: send content to a line you opened, or to the line that opened you. Send a decision, a blocker, or a conflict, not a progress report the receiver can read. Mode "append" (default) reaches the receiver at its next step without interrupting it and does not wake an idle line. Use "steer" when the receiver must act now or is idle.` / `- read: show a page of the activity of the line you were cut from, or of a line you opened, also after it ended. With no after, a read continues after your last read of that line: from your cut for the line you were cut from, and from its first event for a line you opened. Pass after to read from another point. Do not page through a whole line.` / `- end: on a line opened with create, end your own line. content is your final message to the line that opened you: what you found, did, changed and left undone. It is your last action.` / `A line messages and reads the line it was cut from and the lines it opened. The end action ends the calling line and every line below it.` | @@ -556,7 +556,7 @@ Every model-facing text of the branch mechanism, with its class ([model-facing p - **The notices' factual sentences.** "Line C's turn ended () without a message to you, and C is waiting." and "Line C was ended from outside its own line, by the user or a host operation. It no longer receives messages". - **The branch tool's actions and modes.** The actions `create`, `message`, `read` and `end` and what each one does; `mode` `append` or `steer` and what it does to the receiver; the fields each action takes, with `action` required and nothing else accepted; the `read` target rule and its cursor rule ("With no after, a read continues after your last read of that line"); and the sentences that state a guarantee: "Returns the line's id", "Pass after to read from another point", "It is your last action" and "A line messages and reads the line it was cut from and the lines it opened. The end action ends the calling line and every line below it." - **The results and refusals.** `Line created: C`, `Sent to C.`, the page `{items, nextCursor, done}`, `Line C is ending; your final message was sent to P.` and `Line C ends with this message.`; the codes `branch_not_opener`, `branch_limit_reached`, `branch_not_kin`, `branch_not_tool_line`, `branch_ended` and `branch_cannot_end`, with the text each one returns, and `branch_already_default`, `branch_target_protected` and `branch_not_selectable`, which the switch method answers at `session.branch_set_default`; `after A is past line T's head H; a read starts at or below H`, the error result a read returns for an `after` past the target's head, with no code; and `Invalid branch arguments: …`. -- **The status notes' factual sentences.** A note to the new default branch states its id, its parent, its source and its purpose (from the birth block it repeats), the line it was switched from, and the rules that hold while the block is the line's latest one: it answers the user here, it may open lines with `create`, it sends no automatic idle notice to the line that opened it, and it cannot `end` itself. A note to the former default branch states the move that took the role from this line, naming the line it moved to, that this line stays open and keeps coordinating the lines it opened, that it can no longer open lines, that only a line opened with `create` can end itself and not while it or a line below it is the default branch, that a tool line is told to message the line that opened it and keep working when `end` is refused with its purpose done, and that the rest of its birth identity's rules hold again. Neither says whether any other line is the default branch now (§6.2), the root gets no note, and the rule a note states about whether `end` applies is the tree's own, applied whenever `end` is called (§10). +- **The status notes' factual sentences.** A note to the new default branch states its id, its parent, its source and its purpose (from the birth block it repeats), the line it was switched from, and the rules that hold while the block is the line's latest one: it answers the user here, it may open lines with `create`, it sends no automatic idle notice to the line that opened it, and it cannot `end` itself. A note to the former default branch states the move that took the role from this line, naming the line it moved to, that this line stays open and keeps coordinating the lines it opened, that it can no longer open lines, that only a line opened with `create` can end itself and not while it or a line below it is the default branch, and that the rest of its birth identity's rules hold again. Neither says whether any other line is the default branch now (§6.2), the root gets no note, and the rule a note states about whether `end` applies is the tree's own, applied whenever `end` is called (§10). - **The guide entries.** An entry states what its marker is, whose words or which facts it carries, and that it is state or information and never a request. The `` entry states that a later block of that name replaces it, that a block carrying `default` is the note a move writes, and that it belongs to TimelineTree, which writes every identity block, so it is in force in every execution profile. The `` entry belongs to TimelineTree with it and registers at `session` scope, as Goal's does ([Goal §A.5.1](plugins/Goal.md#a51-protocol-and-policy)), because a line's System has to equal its parent's (§7.3): it is in force on `main` too, which never receives the block. The entries of ``, `` and `` belong to BranchLine, which writes the roster and both notices; the `` entry registers with them, and BranchLine is loaded exactly where BranchTool, which writes a message, is. The roster and message entries stay on every line. **Policy.** @@ -565,7 +565,7 @@ Every model-facing text of the branch mechanism, with its class ([model-facing p - **The line's working rules.** The five bullets of "How you work with P:", on the purpose, the reads and messages — including "Do not send P a progress report it can read" and "do not page through P's whole stream" — the workspace, the user and the end, including "Read P once more before you end if the parent block says P has moved", apart from the clauses that name a mechanism: the opening rule, the action and mode names, and "the file was modified after it was last read", the failure `edit` and `write` report, are protocol, as above. It has no factory member yet, and gets one in the change that first evaluates a candidate for it. - **The parent block's guidance.** "Read it when what P did changes what you do, and before your final message; do not page through all of P's work." It has no factory member yet, and gets one in the change that first evaluates a candidate for it. The rest of the block is protocol, above. - **The notices' guidance.** "Read it if you need its state; message it with mode \"steer\" to give it more work, or leave it." and "read it if you need what it did." It has no factory member yet, and gets one in the change that first evaluates a candidate for it. -- **The status notes' guidance.** Six sentences are policy, each behind its factory member: on the new default branch, "The user switched here to continue directly from this line's context and approach, so the user's request takes precedence over the purpose above, which still says what this line is for.", "Carry this line's main work forward yourself; open a new line only when the four conditions for opening one hold again, not to hand off your current task." and "Avoid redoing work assigned to lines opened before your cut."; on a new default branch the user opened, "Carry this line's work forward yourself; open a new line only when the four conditions for opening one hold again."; on the former default branch, "Keep coordinating any open lines you already opened, and answer messages or user inputs addressed to this line." and "You share the workspace with line N; do not edit files outside your remaining scope unless asked." [`BranchToolConfig.default_note`](../../crates/dim-agent-capabilities/src/timeline_tree.rs), [`BranchToolConfig.user_default_note`](../../crates/dim-agent-capabilities/src/timeline_tree.rs) and [`BranchToolConfig.former_default_note`](../../crates/dim-agent-capabilities/src/timeline_tree.rs) replace them and nothing else. The product sets none of the three, so a shipped note carries no `How you work here:` block: the block is written only when a member is configured. Everything else in the notes is protocol: the restated identity, whether the line may open a line, that it sends no idle notice, whether it may `end` and why, the line it was switched from or the line the role moved to, that a former default branch stays open and keeps its lines, and that only a line opened with `create` can end itself and not while it or a line below it is the default branch. The opening rule is protocol rather than policy because it is the tree's own answer to whether `create` would succeed, and a note that hedged it would tell a line less than the tool call tells it. +- **The status notes' guidance.** Seven sentences are policy, each behind its factory member: on the new default branch, "The user switched here to continue directly from this line's context and approach, so the user's request takes precedence over the purpose above, which still says what this line is for.", "Carry this line's main work forward yourself; open a new line only when the four conditions for opening one hold again, not to hand off your current task." and "Avoid redoing work assigned to lines opened before your cut."; on a new default branch the user opened, "Carry this line's work forward yourself; open a new line only when the four conditions for opening one hold again."; on the former default branch, "Keep coordinating any open lines you already opened, and answer messages or user inputs addressed to this line.", "You share the workspace with line N; do not edit files outside your remaining scope unless asked." and, on a tool line, "If end is refused when your purpose is done, message P with what you found, did, changed and left undone and keep working." [`BranchToolConfig.default_note`](../../crates/dim-agent-capabilities/src/timeline_tree.rs), [`BranchToolConfig.user_default_note`](../../crates/dim-agent-capabilities/src/timeline_tree.rs) and [`BranchToolConfig.former_default_note`](../../crates/dim-agent-capabilities/src/timeline_tree.rs) replace them and nothing else. The product sets none of the three, so a shipped note carries no `How you work here:` block: the block is written only when a member is configured. Everything else in the notes is protocol: the restated identity, whether the line may open a line, that it sends no idle notice, whether it may `end` and why, the line it was switched from or the line the role moved to, that a former default branch stays open and keeps its lines, and that only a line opened with `create` can end itself and not while it or a line below it is the default branch. The opening rule is protocol rather than policy because it is the tree's own answer to whether `create` would succeed, and a note that hedged it would tell a line less than the tool call tells it. A candidate for a policy text is put in place at that text's factory member ([model-facing prompts §8.1](model-prompts.md#81-the-rule)) and keeps the protocol sentences of the text it replaces byte-identical. diff --git a/docs/zh/design/timeline-branches.md b/docs/zh/design/timeline-branches.md index fce8de3084..30d5e3c618 100644 --- a/docs/zh/design/timeline-branches.md +++ b/docs/zh/design/timeline-branches.md @@ -456,7 +456,7 @@ WorkspaceTools 不变。 | 结束通知 | `P`,无 key,与名册在同一条输入里;`P` 开出的工具线除自己的 `end` 之外的任何结束 | Steer | `` / `Line C was ended from outside its own line, by the user or a host operation. It no longer receives messages; read it if you need what it did.` / `` | | 状态说明,新的默认分支,工具线 | `C`,`branch:line` | Append | `` / 逐字重述出生身份的句子,包括目的标签和目的本身,然后空行 / `This line is now the session's default branch, switched from line O. While this block is your latest one: answer the user here; you can open lines with create; you send no automatic idle notice to P; you cannot call end on yourself. Line O stays open and keeps the lines it opened.` / 空行 / `How you work here:` / `- The user switched here to continue directly from this line's context and approach, so the user's request takes precedence over the purpose above, which still says what this line is for.` / `- When your purpose is done, or cannot be done, message P with what you found, did, changed and left undone and keep working: while this line is the default branch you cannot call end on yourself.` / `- You share the workspace with P and its other lines. If edit or write fails because the file was modified after it was last read, another line may have changed that file: read it again before editing.` / `` | | 状态说明,新的默认分支,用户开的线 | `C`,`branch:line` | Append | `` / 逐字重述出生身份的句子,然后空行 / `The user has now made this line the session's default branch, switched from line O. While this block is your latest one: answer the user here; you can open lines with create; you cannot call end on yourself; the user ends this line. Line O stays open and keeps the lines it opened.` / 空行 / `How you work here:` / `- Carry this line's work forward yourself; the user's request takes precedence over the prompt this line was opened with.` / `` | -| 状态说明,原来的默认分支,工具线 | `C`,`branch:line` | Append | `` / 逐字重述出生身份的句子,然后空行 / `The session's default branch moved from this line to line O. This line stays open, reports to P as before and keeps coordinating the lines it opened; it can no longer open lines with create, and the rest of the rules above hold again. Only a line opened with create can end itself, and not while it or a line below it is the default branch. If end is refused when your purpose is done, message P with what you found, did, changed and left undone and keep working.` / `` | +| 状态说明,原来的默认分支,工具线 | `C`,`branch:line` | Append | `` / 逐字重述出生身份的句子,然后空行 / `The session's default branch moved from this line to line O. This line stays open, reports to P as before and keeps coordinating the lines it opened; it can no longer open lines with create, and the rest of the rules above hold again. Only a line opened with create can end itself, and not while it or a line below it is the default branch.` / `` | | 状态说明,原来的默认分支,用户开的线 | `C`,`branch:line` | Append | `` / 逐字重述出生身份的句子,然后空行 / `The session's default branch moved from this line to line O. This line stays open and keeps coordinating the lines it opened; it can no longer open lines with create, and the rest of the rules above hold again. Only a line opened with create can end itself, and not while it or a line below it is the default branch.` / `` | | 工具描述 | 每条线 | — | `Work with the other lines of this session. A line is you: it starts from your history at the point it is opened, then works in parallel on its own line. It is not a helper with its own memory, and it owes you no result; you and it keep each other informed by reading each other's work and messaging what the other must act on. On main you coordinate: answer a line's steer and act on what it asks for; leave a line's part to that line instead of redoing it; read a line's work instead of waiting for a report.` / `- create (the root and the current default branch only): open a line to work on prompt in parallel. Open one line per part that can go on at the same time as the rest — separate files, a separate question, or a second approach — instead of doing those parts one after another yourself; not for a single quick edit, nor when your next step needs its result. Write prompt as a brief to yourself: the purpose, what you already know that it needs, which files or area are its own, and when it should tell you or end. Returns the line's id.` / `- message: send content to a line you opened, or to the line that opened you. Send a decision, a blocker, or a conflict, not a progress report the receiver can read. Mode "append" (default) reaches the receiver at its next step without interrupting it and does not wake an idle line. Use "steer" when the receiver must act now or is idle.` / `- read: show a page of the activity of the line you were cut from, or of a line you opened, also after it ended. With no after, a read continues after your last read of that line: from your cut for the line you were cut from, and from its first event for a line you opened. Pass after to read from another point. Do not page through a whole line.` / `- end: on a line opened with create, end your own line. content is your final message to the line that opened you: what you found, did, changed and left undone. It is your last action.` / `A line messages and reads the line it was cut from and the lines it opened. The end action ends the calling line and every line below it.` | @@ -522,7 +522,7 @@ WorkspaceTools 不变。 - **通知的事实句。** "Line C's turn ended () without a message to you, and C is waiting." 与 "Line C was ended from outside its own line, by the user or a host operation. It no longer receives messages"。 - **branch 工具的动作与模式。** 动作 `create`、`message`、`read`、`end` 及各自做什么;`mode` 为 `append` 或 `steer` 及它对接收方的作用;每个动作接收的字段,`action` 必填且不接受别的字段;`read` 的目标规则及其游标规则("With no after, a read continues after your last read of that line");以及陈述保证的句子:"Returns the line's id"、"Pass after to read from another point"、"It is your last action"、"A line messages and reads the line it was cut from and the lines it opened. The end action ends the calling line and every line below it."。 - **结果与拒绝。** `Line created: C`、`Sent to C.`、页 `{items, nextCursor, done}`、`Line C is ending; your final message was sent to P.` 与 `Line C ends with this message.`;拒绝码 `branch_not_opener`、`branch_limit_reached`、`branch_not_kin`、`branch_not_tool_line`、`branch_ended`、`branch_cannot_end` 及各自的文本,以及切换方法在 `session.branch_set_default` 处返回的 `branch_already_default`、`branch_target_protected` 和 `branch_not_selectable`;`after A is past line T's head H; a read starts at or below H`,即读取在 `after` 超过目标头部时返回的错误结果,不带代码;以及 `Invalid branch arguments: …`。 -- **状态说明的事实句。** 给新默认分支的说明写出它的 id、父分支、来源和目的(逐字重述出生块)、它从哪条线切过来,以及这块是它最新块时成立的规则:它在这里回答用户、可以用 `create` 开线、不向开它的那条线发自动空闲通知、不能对自己 `end`。给原默认分支的说明写出这次把角色从这条线移走的移动、并点明移到了哪条线;这条线照旧开着并继续协调它开过的线;它不能再开线;只有用 `create` 开出的线才能结束自己,而且当它自己或它下面的一条线是默认分支时不能结束;工具线还被告知在目的完成而 `end` 被拒时给开它的那条线发消息并继续工作;以及它出生身份里其余规则重新成立。两条说明都不说别的线现在是不是默认分支(§6.2),根不写说明,而说明里关于 `end` 是否适用的规则是树自己的规则,在每次调用 `end` 时适用(§10)。 +- **状态说明的事实句。** 给新默认分支的说明写出它的 id、父分支、来源和目的(逐字重述出生块)、它从哪条线切过来,以及这块是它最新块时成立的规则:它在这里回答用户、可以用 `create` 开线、不向开它的那条线发自动空闲通知、不能对自己 `end`。给原默认分支的说明写出这次把角色从这条线移走的移动、并点明移到了哪条线;这条线照旧开着并继续协调它开过的线;它不能再开线;只有用 `create` 开出的线才能结束自己,而且当它自己或它下面的一条线是默认分支时不能结束;以及它出生身份里其余规则重新成立。两条说明都不说别的线现在是不是默认分支(§6.2),根不写说明,而说明里关于 `end` 是否适用的规则是树自己的规则,在每次调用 `end` 时适用(§10)。 - **指南条目。** 每个条目标明它的标记是什么、承载谁的话或哪些事实,以及它是状态或信息、绝不是请求。`` 的条目说明后出现的同名块会取代它,并说明带 `default` 的块是移动默认分支时写的说明,它归 TimelineTree——每段身份块都由它写——所以在任何执行配置下都在位。`` 的条目与它一起归 TimelineTree,按 `session` 作用域注册,和 Goal 的一样([Goal §A.5.1](plugins/Goal.md#a51-协议与策略)),因为一条线的 System 必须等于它父线的 System(§7.3):它在根上同样在位,尽管根从不收到这个块。``、`` 和 `` 的条目归 BranchLine,名册和两条通知都由它写;`` 的条目与它们一起注册,因为 BranchLine 恰好在写消息的 BranchTool 所在之处加载。名册条目和消息条目在每条线上都在。 **策略。** @@ -532,7 +532,7 @@ WorkspaceTools 不变。 - **父线块的指引。** "Read it when what P did changes what you do, and before your final message; do not page through all of P's work."。它还没有工厂配置成员,在第一次为它评估候选的改动里获得成员。块的其余部分是协议,见上。 - **通知的指引。** "Read it if you need its state; message it with mode \"steer\" to give it more work, or leave it." 与 "read it if you need what it did."。它还没有工厂配置成员,在第一次为它评估候选的改动里获得成员。 -- **状态说明的指引。** 有六句是策略,各自在工厂配置成员后面:给新默认分支的“用户移到这里,是为了直接从这条线的上下文和做法继续,所以用户的请求优先于上面那个目的,那个目的仍然说明这条线是做什么的。”“自己把这条线的主要工作接着做下去;只有在开线的四个条件再次全部成立时才开新线,而不是把当前任务交出去。”和“避免重做切点之前开出的线已经分到的工作。”;给用户新开的默认分支的“自己把这条线的工作接着做下去;只有在开线的四个条件再次全部成立时才开新线。”;给原默认分支的“继续协调你已经开过的线,并回答发给这条线的消息或用户输入。”和“你与线 N 共用工作区;除非被要求,不要改你剩余范围之外的文件。”。[`BranchToolConfig.default_note`](../../../crates/dim-agent-capabilities/src/timeline_tree.rs)、[`BranchToolConfig.user_default_note`](../../../crates/dim-agent-capabilities/src/timeline_tree.rs) 与 [`BranchToolConfig.former_default_note`](../../../crates/dim-agent-capabilities/src/timeline_tree.rs) 替换它们,别的都不动。产品一个都不设置,所以发出的说明不带 `How you work here:` 块:只有配置了成员才写这个块。说明里其余的都是协议:重述的身份、这条线能不能开线、不发空闲通知、能不能 `end` 及原因、它从哪条线切过来或角色移到了哪条线、原默认分支照旧开着并保留自己的线,以及只有用 `create` 开出的线才能结束自己、当它自己或它下面的一条线是默认分支时不能结束。开线那条规则属于协议而不是策略,因为它是树对 `create` 会不会成功的直接答案,一条含糊的说明反而会让线知道得比工具调用更少。 +- **状态说明的指引。** 有七句是策略,各自在工厂配置成员后面:给新默认分支的“用户移到这里,是为了直接从这条线的上下文和做法继续,所以用户的请求优先于上面那个目的,那个目的仍然说明这条线是做什么的。”“自己把这条线的主要工作接着做下去;只有在开线的四个条件再次全部成立时才开新线,而不是把当前任务交出去。”和“避免重做切点之前开出的线已经分到的工作。”;给用户新开的默认分支的“自己把这条线的工作接着做下去;只有在开线的四个条件再次全部成立时才开新线。”;给原默认分支的“继续协调你已经开过的线,并回答发给这条线的消息或用户输入。”“你与线 N 共用工作区;除非被要求,不要改你剩余范围之外的文件。”,以及工具线上的“目的完成而 `end` 被拒时,把发现、做过的、改过的和没做完的告诉 P,并继续工作。”。[`BranchToolConfig.default_note`](../../../crates/dim-agent-capabilities/src/timeline_tree.rs)、[`BranchToolConfig.user_default_note`](../../../crates/dim-agent-capabilities/src/timeline_tree.rs) 与 [`BranchToolConfig.former_default_note`](../../../crates/dim-agent-capabilities/src/timeline_tree.rs) 替换它们,别的都不动。产品一个都不设置,所以发出的说明不带 `How you work here:` 块:只有配置了成员才写这个块。说明里其余的都是协议:重述的身份、这条线能不能开线、不发空闲通知、能不能 `end` 及原因、它从哪条线切过来或角色移到了哪条线、原默认分支照旧开着并保留自己的线,以及只有用 `create` 开出的线才能结束自己、当它自己或它下面的一条线是默认分支时不能结束。开线那条规则属于协议而不是策略,因为它是树对 `create` 会不会成功的直接答案,一条含糊的说明反而会让线知道得比工具调用更少。 策略文本的候选放在该文本的工厂配置成员上([面向模型的提示词 §8.1](model-prompts.md#81-规则)),并让它替换的文本里的协议句逐字节不变。